text
string
size
int64
token_count
int64
#include "RenderAPI.h" namespace ArcanaTools { RenderAPI::API RenderAPI::s_API = RenderAPI::API::OPENGL; }
109
41
//here take a cat #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <string> #include <utility> #include <cmath> #include <cassert> #include <algorithm> #include <vector> #include <random> #include <chrono> #include <queue> #include <set> #define ll long long #define lb long double #define pii pair<int, int> #define pb push_back #define mp make_pair #define ins insert #define cont continue #define pow2(n) (1 << (n)) #define LC(n) (((n) << 1) + 1) #define RC(n) (((n) << 1) + 2) #define add(a, b) (((a)%mod + (b)%mod)%mod) #define mul(a, b) (((a)%mod * (b)%mod)%mod) #define init(arr, val) memset(arr, val, sizeof(arr)) #define bckt(arr, val, sz) memset(arr, val, sizeof(arr[0]) * (sz)) #define uid(a, b) uniform_int_distribution<int>(a, b)(rng) #define tern(a, b, c) ((a) ? (b) : (c)) #define feq(a, b) (fabs(a - b) < eps) #define moo printf #define oom scanf #define mool puts("") #define orz assert #define fll fflush(stdout) const lb eps = 1e-9; const ll mod = 1e9 + 7, ll_max = (ll)1e18; const int MX = 2e5 +10, int_max = 0x3f3f3f3f; using namespace std; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); struct node{ int u, w; node(){}; node(int a, int b){ u=a, w=b; } bool operator < (const node& b) const{ return w < b.w; //HMMMM } }; int dep[MX], dist[MX][5], vis[MX], par[MX], deg[MX]; int n; priority_queue<node> pq; vector<int> adj[MX]; vector<pair<pii, int>> ans; void dfs(int u, int p, int d, int op){ par[u] = p; dep[u] = d; dist[u][op] = max(d, dist[u][op]); for(int v : adj[u]){ if(v != p) dfs(v, u, d + 1, op); } } void mark(int x){ if(!x || vis[x]) return ; vis[x] = 1; mark(par[x]); } int far(int x, int op){ dfs(x, 0, 0, op); for(int i = 1; i<=n; i++){ if(dep[i] > dep[x]) x = i; } return x; } int main(){ cin.tie(0) -> sync_with_stdio(0); cin >> n; for(int i = 0; i<n-1; i++){ int a, b; cin >> a >> b; adj[a].pb(b); adj[b].pb(a); } int d1 = far(1, 0), d2 = far(d1, 1); far(d2, 2); mark(d1); mark(d2); for(int i = 1; i<=n; i++){ deg[i] = adj[i].size(); if(deg[i] == 1) pq.push(node(i, max(dist[i][1], dist[i][2]))); } ll res = 0ll; while(!pq.empty()){ node cur = pq.top(); pq.pop(); int u = cur.u, w = cur.w, v = tern(dist[u][1] > dist[u][2], d1, d2), p = par[u]; if(vis[u]) cont; ans.pb(mp(mp(u, v), u)); res += w; deg[p]--; if(deg[p] == 1){ pq.push(node(p, max(dist[p][1], dist[p][2]))); } } for(; d1 != d2; d1 = par[d1]){ ans.pb(mp(mp(d1, d2), d1)); res += (ll)dep[d1]; } moo("%lld\n", res); for(const auto& e : ans){ moo("%d %d %d\n", e.first.first, e.first.second, e.second); } return 0; }
2,740
1,332
//Author= Aryan Rathee //Subtract Complex Number Using Operator Overloading #include <iostream> using namespace std; class Complex { private: float real; float imag; public: Complex(): real(0), imag(0){ } void input() { cout << "Enter real and imaginary parts respectively: "; cin >> real; cin >> imag; } // Operator overloading Complex operator - (Complex c2) { Complex temp; temp.real = real - c2.real; temp.imag = imag - c2.imag; return temp; }
604
172
/* * Copyright © 2012, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed * under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ /** * @file RPModel.cpp * @brief Contains the implementation of class RocketPower. * @author Brian Cera, based on code from Kyunam Kim * @version 1.0.0 * $Id$ */ // This module //#include "RPModel.h" // This library #include "core/tgBasicActuator.h" #include "core/tgRod.h" #include "tgcreator/tgBuildSpec.h" #include "tgcreator/tgBasicActuatorInfo.h" #include "tgcreator/tgRodInfo.h" #include "tgcreator/tgStructure.h" #include "tgcreator/tgStructureInfo.h" // The Bullet Physics library #include "LinearMath/btVector3.h" // The C++ Standard Library #include <stdexcept> #include <iostream> #include <fstream> namespace { // see tgBasicActuator and tgRod for a descripton of these rod parameters // (specifically, those related to the motor moving the strings.) // NOTE that any parameter that depends on units of length will scale // with the current gravity scaling. E.g., with gravity as 98.1, // the length units below are in decimeters. // Note: This current model of the SUPERball rod is 1.5m long by 3 cm radius, // which is 0.00424 m^3. // For SUPERball v1.5, mass = 3.5kg per strut, which comes out to // 0.825 kg / (decimeter^3). // similarly, frictional parameters are for the tgRod objects. //const double sf = 20;//scaling factor with respect to meter scale. E.g., centimeter scale is achieved by setting sf = 100 //const double length_scale = 0.25; //1 makes 4 m long rods // In meter scale, the robot is too small, while in centimeter scale, the robot rotates freely (free energy!) // Also, don't forget to change gravity scale in AppThruster.cpp and T6Thruster.cpp! const struct Config { double density; double radius; double stiffness; double damping; double rod_length; double rod_space; double friction; double rollFriction; double restitution; double pretension; bool hist; double maxTens; double targetVelocity; } c = { 2700/pow(sf,3),//0.688, // density (kg / length^3) 0.0254*sf,//0.31, // radius (length) 600,//1192.5*10,//613.0, // stiffness (kg / sec^2) was 1500 500, // damping (kg / sec) 4*sf*length_scale, // rod_length (length) .02*sf, // rod_space (length) 0.99, // friction (unitless) 0.1, // rollFriction (unitless) 0.0, // restitution (?) 150*sf, //610, // pretension -> set to 4 * 613, the previous value of the rest length controller 0, // History logging (boolean) 300*sf, // maxTens .02, //sf, // targetVelocity // Use the below values for earlier versions of simulation. // 1.006, // 0.31, // 300000.0, // 3000.0, // 15.0, // 7.5, }; } // namespace RPModel::RPModel() : tgModel() { } RPModel::~RPModel() { } void RPModel::setup(tgWorld& world) { allAbstractMarkers=tgCast::filter<tgModel, abstractMarker> (getDescendants()); } void RPModel::step(double dt) { // Precondition if (dt <= 0.0) { throw std::invalid_argument("dt is not positive"); } else { // Notify observers (controllers) of the step so that they can take action notifyStep(dt); tgModel::step(dt); // Step any children } for(int k=1;k<36;k++){ std::cout << allActuators[k]->getTension() << " "; } std::cout << std::endl; } void RPModel::onVisit(tgModelVisitor& r) { tgModel::onVisit(r); } const std::vector<tgBasicActuator*>& RPModel::getAllActuators() const { return allActuators; } const std::vector<tgRod*>& RPModel::getAllRods() const { return allRods; } const std::vector<tgBaseRigid*>& RPModel::getAllBaseRigids() const { return allBaseRigids; } const std::vector<abstractMarker*>& RPModel::getAllAbstractMarkers() const { return allAbstractMarkers; } void RPModel::teardown() { notifyTeardown(); tgModel::teardown(); }
4,634
1,702
// Copyright (c) MisCar 1574 #include "miscar/Fix.h" #include <cmath> double miscar::Fix(double value, double range) { return (std::abs(value) < range) ? 0 : (value - range) / (1 - range); }
196
82
/* * Copyright (C) 2010-2019 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * 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. */ #include "stdafx.h" #include "VideoInputPin.h" #include "ILAVDynamicAllocator.h" CVideoInputPin::CVideoInputPin(TCHAR* pObjectName, CLAVVideo* pFilter, HRESULT* phr, LPWSTR pName) : CDeCSSTransformInputPin(pObjectName, pFilter, phr, pName) , m_pLAVVideo(pFilter) { } STDMETHODIMP CVideoInputPin::NonDelegatingQueryInterface(REFIID riid, void** ppv) { CheckPointer(ppv, E_POINTER); return QI(IPinSegmentEx) __super::NonDelegatingQueryInterface(riid, ppv); } STDMETHODIMP CVideoInputPin::NotifyAllocator(IMemAllocator * pAllocator, BOOL bReadOnly) { HRESULT hr = __super::NotifyAllocator(pAllocator, bReadOnly); m_bDynamicAllocator = FALSE; if (SUCCEEDED(hr) && pAllocator) { ILAVDynamicAllocator *pDynamicAllocator = nullptr; if (SUCCEEDED(pAllocator->QueryInterface(&pDynamicAllocator))) { m_bDynamicAllocator = pDynamicAllocator->IsDynamicAllocator(); } SafeRelease(&pDynamicAllocator); } return hr; } STDMETHODIMP CVideoInputPin::EndOfSegment() { CAutoLock lck(&m_pLAVVideo->m_csReceive); HRESULT hr = CheckStreaming(); if (S_OK == hr) { hr = m_pLAVVideo->EndOfSegment(); } return hr; } // IKsPropertySet STDMETHODIMP CVideoInputPin::Set(REFGUID PropSet, ULONG Id, LPVOID pInstanceData, ULONG InstanceLength, LPVOID pPropertyData, ULONG DataLength) { if(PropSet != AM_KSPROPSETID_TSRateChange) { return __super::Set(PropSet, Id, pInstanceData, InstanceLength, pPropertyData, DataLength); } switch(Id) { case AM_RATE_SimpleRateChange: { AM_SimpleRateChange* p = (AM_SimpleRateChange*)pPropertyData; if (!m_CorrectTS) { return E_PROP_ID_UNSUPPORTED; } CAutoLock cAutoLock(&m_csRateLock); m_ratechange = *p; } break; case AM_RATE_UseRateVersion: { WORD* p = (WORD*)pPropertyData; if (*p > 0x0101) { return E_PROP_ID_UNSUPPORTED; } } break; case AM_RATE_CorrectTS: { LONG* p = (LONG*)pPropertyData; m_CorrectTS = *p; } break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; } STDMETHODIMP CVideoInputPin::Get(REFGUID PropSet, ULONG Id, LPVOID pInstanceData, ULONG InstanceLength, LPVOID pPropertyData, ULONG DataLength, ULONG* pBytesReturned) { if(PropSet != AM_KSPROPSETID_TSRateChange) { return __super::Get(PropSet, Id, pInstanceData, InstanceLength, pPropertyData, DataLength, pBytesReturned); } switch(Id) { case AM_RATE_SimpleRateChange: { AM_SimpleRateChange* p = (AM_SimpleRateChange*)pPropertyData; CAutoLock cAutoLock(&m_csRateLock); *p = m_ratechange; *pBytesReturned = sizeof(AM_SimpleRateChange); } break; case AM_RATE_MaxFullDataRate: { AM_MaxFullDataRate* p = (AM_MaxFullDataRate*)pPropertyData; *p = 2 * 10000; *pBytesReturned = sizeof(AM_MaxFullDataRate); } break; case AM_RATE_QueryFullFrameRate: { AM_QueryRate* p = (AM_QueryRate*)pPropertyData; p->lMaxForwardFullFrame = 2 * 10000; p->lMaxReverseFullFrame = 0; *pBytesReturned = sizeof(AM_QueryRate); } break; case AM_RATE_QueryLastRateSegPTS: { //REFERENCE_TIME* p = (REFERENCE_TIME*)pPropertyData; return E_PROP_ID_UNSUPPORTED; } break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; } STDMETHODIMP CVideoInputPin::QuerySupported(REFGUID PropSet, ULONG Id, ULONG* pTypeSupport) { if(PropSet != AM_KSPROPSETID_TSRateChange) { return __super::QuerySupported(PropSet, Id, pTypeSupport); } switch (Id) { case AM_RATE_SimpleRateChange: *pTypeSupport = KSPROPERTY_SUPPORT_GET | KSPROPERTY_SUPPORT_SET; break; case AM_RATE_MaxFullDataRate: *pTypeSupport = KSPROPERTY_SUPPORT_GET; break; case AM_RATE_UseRateVersion: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; case AM_RATE_QueryFullFrameRate: *pTypeSupport = KSPROPERTY_SUPPORT_GET; break; case AM_RATE_QueryLastRateSegPTS: *pTypeSupport = KSPROPERTY_SUPPORT_GET; break; case AM_RATE_CorrectTS: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; }
5,038
1,930
#include "StepParser.hpp" #include "SnapshotParser.hpp" #include "ResultCollectorParser.hpp" #include "application/factories/parsers/StepParserProvider.hpp" #include "application/jobs/AnalysisStep.hpp" #include "application/jobs/StructuralAnalysis.hpp" #include "application/locators/ClockworkFactoryLocator.hpp" #include "application/locators/SolverFactoryLocator.hpp" #include "application/output/ResultBucketConcrete.hpp" #include "application/parsing/core/SymbolTable.hpp" #include "application/parsing/core/ParseContext.hpp" #include "application/parsing/parsers/EmptyBlockParser.hpp" #include "application/parsing/error_messages.hpp" #include "domain/algorithms/Solver.hpp" #include "services/language/syntax/evaluation/ParameterList.hpp" #include "services/messaging/ErrorMessage.hpp" #include "foundation/NotSupportedException.hpp" #include "foundation/definitions/AxisInputLanguage.hpp" namespace aaj = axis::application::jobs; namespace aal = axis::application::locators; namespace aao = axis::application::output; namespace aapps = axis::application::parsing::parsers; namespace aafp = axis::application::factories::parsers; namespace aapc = axis::application::parsing::core; namespace adal = axis::domain::algorithms; namespace asli = axis::services::language::iterators; namespace aslse = axis::services::language::syntax::evaluation; namespace aslp = axis::services::language::parsing; namespace asmm = axis::services::messaging; namespace afdf = axis::foundation::definitions; // Enforce instantiation of this specialized template template class aapps::StepParserTemplate<aal::SolverFactoryLocator, aal::ClockworkFactoryLocator>; template <class SolverFactoryLoc, class ClockworkFactoryLoc> aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::StepParserTemplate( aafp::StepParserProvider& parentProvider, const axis::String& stepName, SolverFactoryLoc& solverLocator, const axis::String& solverType, real startTime, real endTime, const aslse::ParameterList& solverParams, aal::CollectorFactoryLocator& collectorLocator, aal::WorkbookFactoryLocator& formatLocator) : provider_(parentProvider), stepName_(stepName), solverLocator_(solverLocator), collectorLocator_(collectorLocator), formatLocator_(formatLocator) { Init(solverType, startTime, endTime, solverParams); } template <class SolverFactoryLoc, class ClockworkFactoryLoc> aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::StepParserTemplate( aafp::StepParserProvider& parentProvider, const axis::String& stepName, SolverFactoryLoc& solverLocator, ClockworkFactoryLoc& clockworkLocator, const axis::String& solverType, real startTime, real endTime, const aslse::ParameterList& solverParams, const axis::String& clockworkType, const aslse::ParameterList& clockworkParams, aal::CollectorFactoryLocator& collectorLocator, aal::WorkbookFactoryLocator& formatLocator) : provider_(parentProvider), stepName_(stepName), solverLocator_(solverLocator), collectorLocator_(collectorLocator), formatLocator_(formatLocator) { Init(solverType, startTime, endTime, solverParams); isClockworkDeclared_ = true; clockworkTypeName_ = clockworkType; clockworkParams_ = &clockworkParams.Clone(); clockworkLocator_ = &clockworkLocator; } template <class SolverFactoryLoc, class ClockworkFactoryLoc> void aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::Init( const axis::String& solverType, real startTime, real endTime, const aslse::ParameterList& solverParams ) { solverTypeName_ = solverType; stepStartTime_ = startTime; stepEndTime_ = endTime; solverParams_ = &solverParams.Clone(); isNewReadRound_ = false; dirtyStepBlock_ = false; isClockworkDeclared_ = false; clockworkParams_ = NULL; clockworkLocator_ = NULL; stepResultBucket_ = NULL; nullParser_ = new axis::application::parsing::parsers::EmptyBlockParser(provider_); } template <class SolverFactoryLoc, class ClockworkFactoryLoc> aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::~StepParserTemplate( void ) { delete nullParser_; solverParams_->Destroy(); if (clockworkParams_ != NULL) clockworkParams_->Destroy(); clockworkParams_ = NULL; solverParams_ = NULL; } template <class SolverFactoryLoc, class ClockworkFactoryLoc> aapps::BlockParser& aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::GetNestedContext( const axis::String& contextName, const aslse::ParameterList& paramList ) { // if couldn't build a step block, we cannot provide nested // contexts because it probably depends on the step begin // defined if (dirtyStepBlock_) { // throwing this exception shows that we don't know how to // proceed with these blocks throw axis::foundation::NotSupportedException(); } // check if the requested context is the special context // 'SNAPSHOT' if (contextName == afdf::AxisInputLanguage::SnapshotsBlockName && paramList.IsEmpty()) { // yes, it is; let's override the default behavior and trick // the main parser giving him our own snapshot block parser SnapshotParser& p = *new SnapshotParser(isNewReadRound_); p.SetAnalysis(GetAnalysis()); return p; } else if (contextName == afdf::AxisInputLanguage::ResultCollectionSyntax.BlockName) { // no, this is the special context 'OUTPUT' if (!ValidateCollectorBlockInformation(paramList)) { // invalid, insufficient or unknown parameters throw axis::foundation::NotSupportedException(); } BlockParser& p = CreateResultCollectorParser(paramList); p.SetAnalysis(GetAnalysis()); return p; } // any other non-special block registered if (provider_.ContainsProvider(contextName, paramList)) { aafp::BlockProvider& provider = provider_.GetProvider(contextName, paramList); aapps::BlockParser& nestedContext = provider.BuildParser(contextName, paramList); nestedContext.SetAnalysis(GetAnalysis()); return nestedContext; } // no provider found throw axis::foundation::NotSupportedException(); } template <class SolverFactoryLoc, class ClockworkFactoryLoc> aslp::ParseResult aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::Parse( const asli::InputIterator& begin, const asli::InputIterator& end ) { return nullParser_->Parse(begin, end); } template <class SolverFactoryLoc, class ClockworkFactoryLoc> void aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::DoStartContext( void ) { aapc::SymbolTable& st = GetParseContext().Symbols(); nullParser_->StartContext(GetParseContext()); // first, check if we are able to build the specified solver bool canBuildSolver; if (isClockworkDeclared_) { canBuildSolver = solverLocator_.CanBuild(solverTypeName_, *solverParams_, stepStartTime_, stepEndTime_, clockworkTypeName_, *clockworkParams_); } else { canBuildSolver = solverLocator_.CanBuild(solverTypeName_, *solverParams_, stepStartTime_, stepEndTime_); } if (!canBuildSolver) { // huh? GetParseContext().RegisterEvent(asmm::ErrorMessage(AXIS_ERROR_ID_UNKNOWN_SOLVER_TYPE, AXIS_ERROR_MSG_UNKNOWN_SOLVER_TYPE)); dirtyStepBlock_ = true; return; } // then, check if this is a new read round axis::String symbolName = st.GenerateDecoratedName(aapc::SymbolTable::kAnalysisStep); if (st.IsSymbolDefined(symbolName, aapc::SymbolTable::kAnalysisStep)) { // yes, it is a new read round; we don't need to create a new solver and step objects isNewReadRound_ = true; } st.DefineOrRefreshSymbol(symbolName, aapc::SymbolTable::kAnalysisStep); // set analysis step to work on aaj::StructuralAnalysis& analysis = GetAnalysis(); if (!isNewReadRound_) { // we need to create the new step // build clockwork if we have to adal::Solver *solver = NULL; if (isClockworkDeclared_) { adal::Clockwork *clockwork = NULL; if (clockworkLocator_->CanBuild(clockworkTypeName_, *clockworkParams_, stepStartTime_, stepEndTime_)) { clockwork = &clockworkLocator_->BuildClockwork(clockworkTypeName_, *clockworkParams_, stepStartTime_, stepEndTime_); } else { // there is something wrong with supplied parameters GetParseContext().RegisterEvent( asmm::ErrorMessage(AXIS_ERROR_ID_UNKNOWN_TIME_CONTROL_ALGORITHM, AXIS_ERROR_MSG_UNKNOWN_TIME_CONTROL_ALGORITHM)); dirtyStepBlock_ = true; return; } solver = &solverLocator_.BuildSolver(solverTypeName_, *solverParams_, stepStartTime_, stepEndTime_, *clockwork); } else { solver = &solverLocator_.BuildSolver(solverTypeName_, *solverParams_, stepStartTime_, stepEndTime_); } stepResultBucket_ = new aao::ResultBucketConcrete(); aaj::AnalysisStep& step = aaj::AnalysisStep::Create(stepStartTime_, stepEndTime_, *solver, *stepResultBucket_); step.SetName(stepName_); analysis.AddStep(step); } else { // since we are on a new parse round, retrieve result bucket that we created earlier int stepIndex = GetParseContext().GetStepOnFocusIndex() + 1; aaj::AnalysisStep *step = &GetAnalysis().GetStep(stepIndex); stepResultBucket_ = static_cast<aao::ResultBucketConcrete *>(&step->GetResults()); GetParseContext().SetStepOnFocus(step); GetParseContext().SetStepOnFocusIndex(stepIndex); } if (analysis.GetStepCount() == 1) { // we are parsing the first step GetParseContext().SetStepOnFocus(&analysis.GetStep(0)); GetParseContext().SetStepOnFocusIndex(0); } else { int nextStepIndex = GetParseContext().GetStepOnFocusIndex() + 1; GetParseContext().SetStepOnFocus(&analysis.GetStep(nextStepIndex)); GetParseContext().SetStepOnFocusIndex(nextStepIndex); } } template <class SolverFactoryLoc, class ClockworkFactoryLoc> bool aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc> ::ValidateCollectorBlockInformation( const aslse::ParameterList& contextParams ) { int paramsFound = 2; if (!contextParams.IsDeclared( afdf::AxisInputLanguage::ResultCollectionSyntax.FileNameParameterName)) return false; if (!contextParams.IsDeclared( afdf::AxisInputLanguage::ResultCollectionSyntax.FileFormatParameterName)) return false; // check optional parameters if (contextParams.IsDeclared(afdf::AxisInputLanguage::ResultCollectionSyntax.AppendParameterName)) { String val = contextParams.GetParameterValue( afdf::AxisInputLanguage::ResultCollectionSyntax.AppendParameterName).ToString(); val.to_lower_case().trim(); if (val != _T("yes") && val != _T("no") && val != _T("true") && val != _T("false")) { return false; } paramsFound++; } if (contextParams.IsDeclared( afdf::AxisInputLanguage::ResultCollectionSyntax.FormatArgumentsParameterName)) { aslse::ParameterValue& val = contextParams.GetParameterValue( afdf::AxisInputLanguage::ResultCollectionSyntax.FormatArgumentsParameterName); if (!val.IsArray()) return false; // check if it is an array of parameters try { aslse::ParameterList& test = aslse::ParameterList::FromParameterArray(static_cast<aslse::ArrayValue&>(val)); test.Destroy(); } catch (...) { // uh oh, it is not valid return false; } paramsFound++; } return (contextParams.Count() == paramsFound); } template <class SolverFactoryLoc, class ClockworkFactoryLoc> aapps::BlockParser& aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc> ::CreateResultCollectorParser( const aslse::ParameterList& contextParams ) const { String fileName = contextParams.GetParameterValue( afdf::AxisInputLanguage::ResultCollectionSyntax.FileNameParameterName).ToString(); String formatName = contextParams.GetParameterValue( afdf::AxisInputLanguage::ResultCollectionSyntax.FileFormatParameterName).ToString(); const aslse::ParameterList *formatArgs = NULL; bool append = false; if (contextParams.IsDeclared(afdf::AxisInputLanguage::ResultCollectionSyntax.AppendParameterName)) { String val = contextParams.GetParameterValue( afdf::AxisInputLanguage::ResultCollectionSyntax.AppendParameterName).ToString(); val.to_lower_case().trim(); append = (val != _T("yes") && val != _T("true")); } if (contextParams.IsDeclared( afdf::AxisInputLanguage::ResultCollectionSyntax.FormatArgumentsParameterName)) { aslse::ParameterValue& val = contextParams.GetParameterValue( afdf::AxisInputLanguage::ResultCollectionSyntax.FormatArgumentsParameterName); formatArgs = &aslse::ParameterList::FromParameterArray(static_cast<aslse::ArrayValue&>(val)); } else { formatArgs = &aslse::ParameterList::Empty.Clone(); } aapps::BlockParser *parser = new aapps::ResultCollectorParser(formatLocator_, collectorLocator_, *stepResultBucket_, fileName, formatName, *formatArgs, append); formatArgs->Destroy(); return *parser; }
14,504
4,044
/****************************************************************************** ** (C) Chris Oldwood ** ** MODULE: CLUBDETAILSDLG.CPP ** COMPONENT: The Application. ** DESCRIPTION: CClubDetailsDlg class definition. ** ******************************************************************************* */ #include "Common.hpp" #include "ClubDetailsDlg.hpp" #include "ClubDetails.hpp" /****************************************************************************** ** Method: Constructor. ** ** Description: . ** ** Parameters: None. ** ** Returns: Nothing. ** ******************************************************************************* */ CClubDetailsDlg::CClubDetailsDlg(CRow& oDetails) : CDialog(IDD_CLUB_DETAILS) , m_oDetails(oDetails) { DEFINE_CTRL_TABLE CTRL(IDC_CLUB_NAME, &m_ebName) CTRL(IDC_SEASON, &m_ebSeason) CTRL(IDC_LEAGUE_NAME, &m_ebLeague) END_CTRL_TABLE } /****************************************************************************** ** Method: OnInitDialog() ** ** Description: Initialise the dialog. ** ** Parameters: None. ** ** Returns: Nothing. ** ******************************************************************************* */ void CClubDetailsDlg::OnInitDialog() { // Initialise the controls. m_ebName.Text(m_oDetails[CClubDetails::NAME]); m_ebName.TextLimit(CClubDetails::NAME_LEN); m_ebSeason.Text(m_oDetails[CClubDetails::SEASON]); m_ebSeason.TextLimit(CClubDetails::SEASON_LEN); m_ebLeague.Text(m_oDetails[CClubDetails::LEAGUE]); m_ebLeague.TextLimit(CClubDetails::LEAGUE_LEN); } /****************************************************************************** ** Method: OnOk() ** ** Description: Validate the data and close the dialog. ** ** Parameters: None. ** ** Returns: true or false. ** ******************************************************************************* */ bool CClubDetailsDlg::OnOk() { // Fetch data from the controls. m_oDetails[CClubDetails::NAME] = m_ebName.Text(); m_oDetails[CClubDetails::SEASON] = m_ebSeason.Text(); m_oDetails[CClubDetails::LEAGUE] = m_ebLeague.Text(); return true; }
2,088
694
/********************************************************************** * Copyright (c) 2008-2016, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <gtest/gtest.h> #include "EnergyPlusFixture.hpp" #include "../ErrorFile.hpp" #include "../ForwardTranslator.hpp" #include "../ReverseTranslator.hpp" // Objects of interest #include "../../model/GeneratorMicroTurbine.hpp" #include "../../model/GeneratorMicroTurbine_Impl.hpp" #include "../../model/GeneratorMicroTurbineHeatRecovery.hpp" #include "../../model/GeneratorMicroTurbineHeatRecovery_Impl.hpp" // Needed resources #include "../../model/PlantLoop.hpp" #include "../../model/PlantLoop_Impl.hpp" #include "../../model/Node.hpp" #include "../../model/Node_Impl.hpp" #include "../../model/Curve.hpp" #include "../../model/Curve_Impl.hpp" #include "../../model/CurveBiquadratic.hpp" #include "../../model/CurveBiquadratic_Impl.hpp" #include "../../model/CurveCubic.hpp" #include "../../model/CurveCubic_Impl.hpp" #include "../../model/CurveQuadratic.hpp" #include "../../model/CurveQuadratic_Impl.hpp" #include "../../model/StraightComponent.hpp" #include "../../model/StraightComponent_Impl.hpp" #include "../../model/Schedule.hpp" #include "../../model/Schedule_Impl.hpp" // For testing PlantEquipOperation #include "../../model/WaterHeaterMixed.hpp" #include "../../model/WaterHeaterMixed_Impl.hpp" #include "../../model/PlantEquipmentOperationHeatingLoad.hpp" #include "../../model/PlantEquipmentOperationHeatingLoad_Impl.hpp" #include "../../model/ElectricLoadCenterDistribution.hpp" #include "../../model/ElectricLoadCenterDistribution_Impl.hpp" // IDF FieldEnums #include <utilities/idd/Generator_MicroTurbine_FieldEnums.hxx> // #include <utilities/idd/OS_Generator_MicroTurbine_HeatRecovery_FieldEnums.hxx> #include <utilities/idd/PlantEquipmentList_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> #include <utilities/idd/IddFactory.hxx> // Misc #include "../../model/Version.hpp" #include "../../model/Version_Impl.hpp" #include "../../utilities/core/Optional.hpp" #include "../../utilities/core/Checksum.hpp" #include "../../utilities/core/UUID.hpp" #include "../../utilities/sql/SqlFile.hpp" #include "../../utilities/idf/IdfFile.hpp" #include "../../utilities/idf/IdfObject.hpp" #include "../../utilities/idf/IdfExtensibleGroup.hpp" #include <boost/algorithm/string/predicate.hpp> #include <QThread> #include <resources.hxx> #include <sstream> #include <vector> // Debug #include "../../utilities/core/Logger.hpp" using namespace openstudio::energyplus; using namespace openstudio::model; using namespace openstudio; /** * Tests whether the ForwarTranslator will handle the name of the GeneratorMicroTurbine correctly in the PlantEquipmentOperationHeatingLoad **/ TEST_F(EnergyPlusFixture,ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop) { // TODO: Temporarily output the Log in the console with the Trace (-3) level // for debug // openstudio::Logger::instance().standardOutLogger().enable(); // openstudio::Logger::instance().standardOutLogger().setLogLevel(Trace); // Create a model, a mchp, a mchpHR, a plantLoop and an electricalLoadCenter Model model; GeneratorMicroTurbine mchp = GeneratorMicroTurbine(model); GeneratorMicroTurbineHeatRecovery mchpHR = GeneratorMicroTurbineHeatRecovery(model, mchp); ASSERT_EQ(mchpHR, mchp.generatorMicroTurbineHeatRecovery().get()); PlantLoop plantLoop(model); // Add a supply branch for the mchpHR ASSERT_TRUE(plantLoop.addSupplyBranchForComponent(mchpHR)); // Create a WaterHeater:Mixed WaterHeaterMixed waterHeater(model); // Add it on the same branch as the chpHR, right after it Node mchpHROutletNode = mchpHR.outletModelObject()->cast<Node>(); ASSERT_TRUE(waterHeater.addToNode(mchpHROutletNode)); // Create a plantEquipmentOperationHeatingLoad PlantEquipmentOperationHeatingLoad operation(model); operation.setName(plantLoop.name().get() + " PlantEquipmentOperationHeatingLoad"); ASSERT_TRUE(plantLoop.setPlantEquipmentOperationHeatingLoad(operation)); ASSERT_TRUE(operation.addEquipment(mchpHR)); ASSERT_TRUE(operation.addEquipment(waterHeater)); // Create an ELCD ElectricLoadCenterDistribution elcd = ElectricLoadCenterDistribution(model); elcd.setName("Capstone C65 ELCD"); elcd.setElectricalBussType("AlternatingCurrent"); elcd.addGenerator(mchp); // Forward Translates ForwardTranslator forwardTranslator; Workspace workspace = forwardTranslator.translateModel(model); EXPECT_EQ(0u, forwardTranslator.errors().size()); ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::WaterHeater_Mixed).size()); ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::ElectricLoadCenter_Distribution).size()); // The MicroTurbine should have been forward translated since there is an ELCD WorkspaceObjectVector microTurbineObjects(workspace.getObjectsByType(IddObjectType::Generator_MicroTurbine)); EXPECT_EQ(1u, microTurbineObjects.size()); // Check that the HR nodes have been set WorkspaceObject idf_mchp(microTurbineObjects[0]); EXPECT_EQ(mchpHR.inletModelObject()->name().get(), idf_mchp.getString(Generator_MicroTurbineFields::HeatRecoveryWaterInletNodeName).get()); EXPECT_EQ(mchpHR.outletModelObject()->name().get(), idf_mchp.getString(Generator_MicroTurbineFields::HeatRecoveryWaterOutletNodeName).get()); OptionalWorkspaceObject idf_operation(workspace.getObjectByTypeAndName(IddObjectType::PlantEquipmentOperation_HeatingLoad,*(operation.name()))); ASSERT_TRUE(idf_operation); // Get the extensible ASSERT_EQ(1u, idf_operation->numExtensibleGroups()); // IdfExtensibleGroup eg = idf_operation.getExtensibleGroup(0); // idf_operation.targets[0] ASSERT_EQ(1u, idf_operation->targets().size()); WorkspaceObject plantEquipmentList(idf_operation->targets()[0]); ASSERT_EQ(2u, plantEquipmentList.extensibleGroups().size()); IdfExtensibleGroup eg(plantEquipmentList.extensibleGroups()[0]); ASSERT_EQ("Generator:MicroTurbine", eg.getString(PlantEquipmentListExtensibleFields::EquipmentObjectType).get()); // This fails EXPECT_EQ(mchp.name().get(), eg.getString(PlantEquipmentListExtensibleFields::EquipmentName).get()); IdfExtensibleGroup eg2(plantEquipmentList.extensibleGroups()[1]); ASSERT_EQ("WaterHeater:Mixed", eg2.getString(PlantEquipmentListExtensibleFields::EquipmentObjectType).get()); EXPECT_EQ(waterHeater.name().get(), eg2.getString(PlantEquipmentListExtensibleFields::EquipmentName).get()); model.save(toPath("./ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop.osm"), true); workspace.save(toPath("./ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop.idf"), true); }
7,501
2,541
#include <inttypes.h> #include "WProgram.h" #include "helpers.h" #include "MDRecorder.h" MDRecorderClass::MDRecorderClass() { recording = false; playing = false; recordLength = 0; playPtr = NULL; looping = true; md_playback_phase = MD_PLAYBACK_NONE; muted = false; } void MDRecorderClass::setup() { MidiClock.addOn16Callback(this, (midi_clock_callback_ptr_t)&MDRecorderClass::on16Callback); } void MDRecorderClass::startRecord(uint8_t length, uint8_t boundary) { if (playing) { stopPlayback(); } USE_LOCK(); SET_LOCK(); eventList.freeAll(); // start16th = MidiClock.div16th_counter; rec16th_counter = 0; if (boundary != 0) { recordingBoundary = boundary; recordingTriggered = true; recording = false; } else { recording = true; } recordLength = length; MidiUart.addOnNoteOnCallback(this, (midi_callback_ptr_t)&MDRecorderClass::onNoteOnCallback); MidiUart.addOnControlChangeCallback(this, (midi_callback_ptr_t)&MDRecorderClass::onCCCallback); CLEAR_LOCK(); } void MDRecorderClass::stopRecord() { USE_LOCK(); SET_LOCK(); recording = false; MidiUart.removeOnNoteOnCallback(this); MidiUart.removeOnControlChangeCallback(this); CLEAR_LOCK(); eventList.reverse(); } void MDRecorderClass::startMDPlayback(uint8_t boundary) { md_playback_phase = MD_PLAYBACK_HITS; startPlayback(boundary); } void MDRecorderClass::startPlayback(uint8_t boundary) { if (recording) { stopRecord(); } USE_LOCK(); SET_LOCK(); play16th_counter = 0; if (boundary != 0) { playbackBoundary = boundary; playbackTriggered = true; playing = false; } else { playing = true; } playPtr = eventList.head; CLEAR_LOCK(); } void MDRecorderClass::stopPlayback() { USE_LOCK(); SET_LOCK(); playing = false; CLEAR_LOCK(); } void MDRecorderClass::onNoteOnCallback(uint8_t *msg) { USE_LOCK(); SET_LOCK(); uint8_t pos = rec16th_counter; CLEAR_LOCK(); ListElt<md_recorder_event_t> *elt = eventList.pool.alloc(); if (elt != NULL) { elt->obj.channel = msg[0] & 0xF; elt->obj.pitch = msg[1]; elt->obj.value = msg[2]; elt->obj.step = pos; eventList.push(elt); // GUI.setLine(GUI.LINE2); // GUI.put_value(1, pos); } } void MDRecorderClass::onCCCallback(uint8_t *msg) { USE_LOCK(); SET_LOCK(); uint8_t pos = rec16th_counter; CLEAR_LOCK(); ListElt<md_recorder_event_t> *elt = eventList.pool.alloc(); if (elt != NULL) { elt->obj.channel = (msg[0] & 0xF) | 0x80; elt->obj.pitch = msg[1]; elt->obj.value = msg[2]; elt->obj.step = pos; eventList.push(elt); } } void MDRecorderClass::on16Callback() { USE_LOCK(); SET_LOCK(); if (recording) { if (++rec16th_counter >= recordLength) { stopRecord(); } } if (recordingTriggered) { if ((MidiClock.div16th_counter % recordingBoundary) == 0) { recordingTriggered = false; recording = true; } } if (playbackTriggered) { if ((MidiClock.div16th_counter % playbackBoundary) == 0) { playbackTriggered = false; playing = true; } } if (playing) { while ((playPtr != NULL) && (playPtr->obj.step <= play16th_counter)) { if (!muted) { if (playPtr->obj.channel & 0x80) { if (md_playback_phase == MD_PLAYBACK_NONE) { MidiUart.sendCC(playPtr->obj.channel & 0xF, playPtr->obj.pitch, playPtr->obj.value); } else if (md_playback_phase == MD_PLAYBACK_CCS) { MidiUart.sendCC(playPtr->obj.channel & 0xF, playPtr->obj.pitch, playPtr->obj.value - 5); delayMicroseconds(100); MidiUart.sendCC(playPtr->obj.channel & 0xF, playPtr->obj.pitch, playPtr->obj.value); } } else { if (md_playback_phase != MD_PLAYBACK_CCS) { MidiUart.sendNoteOn(playPtr->obj.channel, playPtr->obj.pitch, playPtr->obj.value); } } } playPtr = playPtr->next; } if (++play16th_counter >= recordLength) { if (md_playback_phase == MD_PLAYBACK_HITS) { md_playback_phase = MD_PLAYBACK_CCS; play16th_counter = 0; playing = true; playPtr = eventList.head; return; } else if (md_playback_phase == MD_PLAYBACK_CCS) { md_playback_phase = MD_PLAYBACK_NONE; } if (looping) { play16th_counter = 0; playing = true; playPtr = eventList.head; } else { stopPlayback(); } } } CLEAR_LOCK(); } MDRecorderClass MDRecorder;
4,393
1,793
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/opsworks/model/AppAttributesKeys.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace OpsWorks { namespace Model { namespace AppAttributesKeysMapper { static const int DocumentRoot_HASH = HashingUtils::HashString("DocumentRoot"); static const int RailsEnv_HASH = HashingUtils::HashString("RailsEnv"); static const int AutoBundleOnDeploy_HASH = HashingUtils::HashString("AutoBundleOnDeploy"); static const int AwsFlowRubySettings_HASH = HashingUtils::HashString("AwsFlowRubySettings"); AppAttributesKeys GetAppAttributesKeysForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == DocumentRoot_HASH) { return AppAttributesKeys::DocumentRoot; } else if (hashCode == RailsEnv_HASH) { return AppAttributesKeys::RailsEnv; } else if (hashCode == AutoBundleOnDeploy_HASH) { return AppAttributesKeys::AutoBundleOnDeploy; } else if (hashCode == AwsFlowRubySettings_HASH) { return AppAttributesKeys::AwsFlowRubySettings; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<AppAttributesKeys>(hashCode); } return AppAttributesKeys::NOT_SET; } Aws::String GetNameForAppAttributesKeys(AppAttributesKeys enumValue) { switch(enumValue) { case AppAttributesKeys::DocumentRoot: return "DocumentRoot"; case AppAttributesKeys::RailsEnv: return "RailsEnv"; case AppAttributesKeys::AutoBundleOnDeploy: return "AutoBundleOnDeploy"; case AppAttributesKeys::AwsFlowRubySettings: return "AwsFlowRubySettings"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace AppAttributesKeysMapper } // namespace Model } // namespace OpsWorks } // namespace Aws
2,709
721
#include "DestroyGraphicEntityMessage.h" #include "message/GraphicMessageHandler.h" DestroyGraphicEntityMessage::DestroyGraphicEntityMessage(GraphicEntity * entity_p, bool delete_p) : GraphicMessage("") , _entity(entity_p) , _delete(delete_p) {} void DestroyGraphicEntityMessage::visit(GraphicMessageHandler &handler_p) { handler_p.visitDestroyGraphicEntity(*this); }
375
129
/**********************************************************************/ /* */ /* This file is part of the RFSM package */ /* */ /* Copyright (c) 2018-present, Jocelyn SEROT. All rights reserved. */ /* */ /* This source code is licensed under the license found in the */ /* LICENSE file in the root directory of this source tree. */ /* */ /**********************************************************************/ #include "option.h" AppOption::AppOption(QString _category, QString _name, Opt_kind _kind, QString _desc) { category = _category; name = _name; kind = _kind; desc = _desc; switch ( kind ) { case UnitOpt: checkbox = new QCheckBox(); val = NULL; break; case StringOpt: checkbox = NULL; val = new QLineEdit(); //val->setFixedSize(100,20); case IntOpt: checkbox = NULL; val = new QLineEdit(); //val->setFixedSize(100,20); break; } }
1,253
320
#include<bits/stdc++.h> using namespace std; typedef long long int ll; ll c[1010][1010], mod = 1e9 + 7; void comb(){ c[0][0] = 1; for(ll i = 1; i < 1010; ++i){ c[i][0] = 1; for(ll j = 1; j < 1010; ++j) c[i][j] = (c[i-1][j-1] + c[i-1][j])%mod; } } void solve(){ comb(); string s; cin >> s; ll k; cin >> k; if(!k){ cout << 1 << endl; return; } ll f[1010] = {0}, cnt = 0, ans = 0, n = s.size(); if(k == 1){ cout << n-1 << endl; return; } for(ll i = 2; i <= n; ++i) f[i] = f[__builtin_popcount(i)] + 1; for(ll i = 0; i < n; i++) if(s[i] == '1'){ for(ll j = (i==0); j < n-i; ++j) ans = (ans + c[n-i-1][j]*(f[cnt + j] == k-1))%mod; cnt++; } ans = (ans + (f[cnt] == k-1))%mod; cout << ans << endl; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); // int t;cin>>t;for(int i = 0 ;i<t;i++) solve(); return 0; }
952
484
#include <iostream> using namespace std; int main() { int vetor[10]; int pares = 0; //Para cada posição eu irei pedir um valor para o usuário for (int i = 0; i < 10; i++) { cout << "Digite um valor para posição " << i << endl; cin >> vetor[i]; }; //Para cada posição irei analisar se essa é par e apenas exibir caso seja. for (int i = 0; i < 10; i++) { if (vetor[i] % 2 == 0) { cout << "Elemento " << i << " é par" << endl; cout << "Valor: " << vetor[i] << endl; //Somando caso seja par. pares++; }; }; cout << "Total de elementos pares: " << pares; return 0; }
736
281
#include "AST.h" extern ErrorHandler error_log; extern TypeManager type_manager; AST::AST() { PROFILE(); } AST::~AST() { PROFILE(); } //FIXME fix all of this absolute trash // at the moment we are making copies of the vectors and moving some and none of it is good // FIXME use allocator [[nodiscard]] Project* AST::new_project_node(const SourcePos pos, std::vector<File*>& files) { PROFILE(); return new Project{{pos}, files}; } [[nodiscard]] File* AST::new_file_node( const SourcePos pos, const std::string name, std::vector<Import*>& imports, std::vector<Decl*>& decls, std::vector<Function*>& functions, const bool is_main ) { PROFILE(); return new File{{pos}, name, std::move(imports), std::move(decls), std::move(functions), is_main}; } [[nodiscard]] Import* AST::new_import_node(const SourcePos pos, std::string& id, std::string& filename) { PROFILE(); return new Import{{pos}, id, filename}; } [[nodiscard]] Function* AST::new_function_node(const SourcePos pos, std::string& id, std::vector<Arg>& fn_args, type_handle type, Block* body, const bool is_main) { PROFILE(); return new Function{{pos}, id, fn_args, type, body, is_main }; } [[nodiscard]] Block* AST::new_block_node(const SourcePos pos, std::vector<Statement*>& statements) { PROFILE(); return new Block{{pos}, statements}; } [[nodiscard]] WhileStmnt* AST::new_while_node(const SourcePos pos, Expr* expr, Block* block) { PROFILE(); return new WhileStmnt{{pos}, expr, block}; } [[nodiscard]] ForStmnt* AST::new_for_node(const SourcePos pos, Decl* decl, Expr* expr1, Expr* expr2, Block* block) { PROFILE(); return new ForStmnt{{pos}, decl, expr1, expr2, block}; } [[nodiscard]] IfStmnt* AST::new_if_node(const SourcePos pos, Expr* expr, Block* block, Block* else_stmnt) { PROFILE(); return new IfStmnt{{pos}, expr, block, else_stmnt}; } [[nodiscard]] RetStmnt* AST::new_ret_node(const SourcePos pos, Expr* expr) { PROFILE(); return new RetStmnt{{pos}, expr}; } [[nodiscard]] Statement* AST::new_statement_node_while(const SourcePos pos, WhileStmnt* while_stmnt) { PROFILE(); auto *ptr = new Statement{ {pos}, WHILE}; ptr->while_stmnt = while_stmnt; return ptr; } [[nodiscard]] Statement* AST::new_statement_node_for(const SourcePos pos, ForStmnt* for_stmnt) { PROFILE(); auto *ptr = new Statement{ {pos}, FOR}; ptr->for_stmnt = for_stmnt; return ptr; } [[nodiscard]] Statement* AST::new_statement_node_if(const SourcePos pos, IfStmnt* if_stmnt) { PROFILE(); auto *ptr = new Statement{ {pos}, IF}; ptr->if_stmnt = if_stmnt; return ptr; } [[nodiscard]] Statement* AST::new_statement_node_ret(const SourcePos pos, RetStmnt* ret_stmnt) { PROFILE(); auto *ptr = new Statement{ {pos}, RET}; ptr->ret_stmnt = ret_stmnt; return ptr; } Statement* AST::new_statement_node_decl(const SourcePos pos, Decl* decl) { PROFILE(); auto *ptr = new Statement{ {pos}, DECLARATION}; ptr->decl = decl; return ptr; } [[nodiscard]] Statement* AST::new_statement_node_expr(const SourcePos pos, Expr* expr) { PROFILE(); auto *ptr = new Statement { {pos}, EXPRESSION}; ptr->expr = expr; return ptr; } [[nodiscard]] Expr* AST::new_expr_node_int_literal(const SourcePos pos, const i64 int_literal, type_handle type) { PROFILE(); auto *ptr = new Expr{{pos}, EXPR_INT_LIT, type}; ptr->int_literal.val = int_literal; return ptr; } [[nodiscard]] Expr* AST::new_expr_node_float_literal(const SourcePos pos, const f64 float_literal, type_handle type) { PROFILE(); auto *ptr = new Expr{{pos}, EXPR_FLOAT_LIT, type}; ptr->float_literal.val = float_literal; return ptr; } [[nodiscard]] Expr* AST::new_expr_node_string_literal(const SourcePos pos, std::string& string_literal, type_handle type) { PROFILE(); auto *ptr = new Expr{{pos}, EXPR_STRING_LIT, type}; ptr->string_literal.val = new std::string(string_literal); return ptr; } [[nodiscard]] Expr* AST::new_expr_node_variable(const SourcePos pos, std::string& id, type_handle type) { PROFILE(); auto *ptr = new Expr{{pos}, EXPR_ID, type}; // FIXME allocator ptr->id.val = new std::string(id); return ptr; } [[nodiscard]] Expr* AST::new_expr_node_fn_call(const SourcePos pos, std::string& id, u32 argc, Expr** argv, type_handle type) { PROFILE(); auto *ptr = new Expr{{pos}, EXPR_FN_CALL, type}; // FIXME allocator ptr->fn_call.val = new std::string(id); ptr->fn_call.argc = argc; ptr->fn_call.args = argv; return ptr; } [[nodiscard]] Expr* AST::new_expr_node_bin_expr(const SourcePos pos, const TokenKind op, Expr* left, Expr* right, type_handle type) { PROFILE(); auto *ptr = new Expr{ {pos}, EXPR_BIN, type}; ptr->binary_expr.op = op; ptr->binary_expr.left = left; ptr->binary_expr.right = right; return ptr; } [[nodiscard]] Expr* AST::new_expr_node_unary_expr(const SourcePos pos, const TokenKind op, Expr* expr, type_handle type) { PROFILE(); auto* ptr = new Expr{ {pos}, EXPR_UNARY, type}; ptr->unary_expr.op = op; ptr->unary_expr.expr = expr; return ptr; } [[nodiscard]] Decl* AST::new_decl_node(const SourcePos pos, std::string& id, const type_handle type, Expr* val) { PROFILE(); // FIXME allocator auto* ptr = new Decl{ {pos}, new std::string(id), type, val }; return ptr; }
5,476
2,024
//10. Given an n lines, m columns matrix, write an algorithm which will // first display the matrix with each line sorted in ascending order, //then display the matrix with each column sorted in ascending order. #include <iostream> using namespace std; int main(){ int m, n; int matrice[50][50], copie_matrice[50][50]; cout << "\nIntroduceti m,n positive integers, 1 > m,n <= 50 (size of the matrix):"; cout << "\nm = "; cin >> m; cout << "\nn = "; cin >> n; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++){ cout << "\nelement [" << j << "][" << i << "] = "; cin >> matrice[j][i]; copie_matrice[j][i] = matrice[j][i]; } cout << "\nInitial matrix:"; cout << "\n"; for (int i = 1; i <= n; i++){ for (int j = 1; j <= m; j++){ cout << " " << matrice[j][i] << " "; } cout << "\n"; } for (int i = 1; i <= n; i++){ bool sortat = false; while (not sortat){ sortat = true; for (int j = 1; j <= m - 1; j++){ if (matrice[j + 1][i] < matrice[j][i]){ int temp = matrice[j][i]; matrice[j][i] = matrice[j + 1][i]; matrice[j + 1][i] = temp; sortat = false; } } } } cout << "\nLines sorted in ascending order: "; cout << "\n"; for (int i = 1; i <= n; i++){ for (int j = 1; j <= m; j++){ cout << " " << matrice[j][i] << " "; } cout << "\n"; } //matrice = copie_matrice; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) matrice[j][i] = copie_matrice[j][i]; for (int i = 1; i <= n; i++){ bool sortat = false; while (not sortat){ sortat = true; for (int j = 1; j <= m - 1; j++){ if (matrice[i][j + 1] < matrice[i][j]){ int temp = matrice[j][i]; matrice[i][j] = matrice[i][j + 1]; matrice[i][j + 1] = temp; sortat = false; } } } } cout << "\nColumns sorted in ascending order: "; cout << "\n"; for (int i = 1; i <= n; i++){ for (int j = 1; j <= m; j++){ cout << " " << matrice[j][i] << " "; } cout << "\n"; } char ch; cin >> ch; return 0; }
2,588
960
#include "pch.h" #include "Box.h" #include <algorithm> Box::Box(const std::wstring& name) : m_name{ name } { CharacterMap charMap; for (wchar_t ch : name) { if (charMap.end() == charMap.find(ch)) { charMap[ch] = 1u; } else { ++charMap[ch]; } } auto two_count_comparator{ [](const CharacterMap::value_type& v) { return v.second == 2u; } }; CharacterMap::iterator two_char_iter{ find_if(charMap.begin(), charMap.end(), two_count_comparator) }; m_has_exactly_two = (charMap.end() != two_char_iter); auto three_count_comparator{ [](const CharacterMap::value_type& v) { return v.second == 3u; } }; CharacterMap::iterator three_char_iter{ find_if(charMap.begin(), charMap.end(), three_count_comparator) }; m_has_exactly_three = (charMap.end() != three_char_iter); } bool Box::has_exactly_two_of_a_character() const { return m_has_exactly_two; } bool Box::has_exactly_three_of_a_character() const { return m_has_exactly_three; } unsigned int Box::edit_distance(const Box& other) const { std::wstring otherName{ other.get_name() }; unsigned int diffCount{ 0u }; for (unsigned int i = 0; i < m_name.length(); ++i) { if (m_name[i] != otherName[i]) { ++diffCount; } } return diffCount; } std::wstring Box::get_name() const { return m_name; }
1,323
503
/* */ #include "crate_ptr.hpp" #include "hir.hpp" ::HIR::CratePtr::CratePtr(): m_ptr(nullptr) { } ::HIR::CratePtr::CratePtr(HIR::Crate c): m_ptr( new ::HIR::Crate(mv$(c)) ) { } ::HIR::CratePtr::~CratePtr() { if( m_ptr ) { delete m_ptr, m_ptr = nullptr; } }
284
140
#include "token.hpp" TOKEN::TOKEN(DOMAIN_TAG tag, POSITION starting, POSITION following) : tag(tag), frag(FRAGMENT(starting, following)) {} DOMAIN_TAG TOKEN::get_tag() const { return tag; } FRAGMENT TOKEN::get_frag() const { return frag; } std::ostream& operator<<(std::ostream &strm, const TOKEN &tok) { return strm << tok.frag; }
348
141
// 函数指针 #include <iostream> using namespace std; int foo(); double goo(); int hoo(int x); int main() { // 给函数指针赋值 int (*funcPtr1)() = foo; // 可以 //int (*funcPtr2)() = goo; // 错误!返回值不匹配! double (*funcPtr4)() = goo; // 可以 //funcPtr1 = hoo; // 错误,因为参数不匹配,funcPtr1只能指向不含参数的函数,而hoo含有int型的参数 int (*funcPtr3)(int) = hoo; // 可以,所以应该这么写 return 0; } int foo() { return 1; } double goo() { return 3.14; } int hoo(int x) { return x * x; }
475
271
#include <catch2/catch.hpp> #include "support/test_compiler.hpp" namespace tiro::test { TEST_CASE("Using the same record structure multiple times should only generate one record template", "[bytecode_gen]") { std::string_view source = R"( export func a() { return (foo: "1", bar: 2, baz: #x); } export func b() { return (foo: 3, bar: 2, baz: 1); } export func c() { return (bar: "x", foo: "y", baz: "z"); } export func d() { return (baz: "x", bar: "y", foo: "z"); } )"; auto module = test_support::compile(source); REQUIRE(module->record_count() == 1); } } // namespace tiro::test
721
240
// Final project for CS 294-73 at Berkeley // Amirreza Hashemi and Júlio Caineta // 2017 #include "RectMDArray.H" #include "FFT1DW.H" #include "FieldData.H" #include "RK4.H" #include "WriteRectMDArray.H" #include "RHSNavierStokes.H" void computeVorticity(RectMDArray< double >& vorticity, const DBox box, FieldData& velocities, double dx) { for (Point pt = box.getLowCorner(); box.notDone(pt); box.increment(pt)) { Point lowShift; Point highShift; double dudy; double dvdx; lowShift[0] = pt[0]; lowShift[1] = pt[1] - 1; highShift[0] = pt[0]; highShift[1] = pt[1] + 1; dudy = (velocities.m_data(highShift, 0) - velocities.m_data(lowShift, 0)) / (2 * dx); lowShift[0] = pt[0] - 1; lowShift[1] = pt[1]; highShift[0] = pt[0] + 1; highShift[1] = pt[1]; dvdx = (velocities.m_data(highShift, 1) - velocities.m_data(lowShift, 1)) / (2 * dx); vorticity[pt] = dudy - dvdx; } }; double maxVelocity(RectMDArray< double, DIM > velocities) { // only working for 2D double umax = 0.; double vmax = 0.; DBox box = velocities.getDBox(); for (Point pt = box.getLowCorner(); box.notDone(pt); box.increment(pt)) { double velocity[2]; velocity[0] = velocities(pt, 0); velocity[1] = velocities(pt, 1); umax = max(velocity[0], umax); vmax = max(velocity[1], vmax); } return max(umax, vmax); }; int main(int argc, char* argv[]) { int M; // int M = 8; cout << "input log_2(number of grid points) [e.g., 8]" << endl; cin >> M; int N = Power(2, M); std::shared_ptr< FFT1D > fft1dPtr(new FFT1DW(M)); FieldData velocities(fft1dPtr, 1); Point low = {{{0, 0}}}; Point high = {{{N - 1, N - 1}}}; DBox box(low, high); double dx = 1.0 / ((double) N); double timeEnd = 0.8; char filename[10]; int nstop = 400; double sigma = 0.04; double x_0 = 0.4; double y_0 = 0.5; for (Point pt = box.getLowCorner(); box.notDone(pt); box.increment(pt)) { velocities.m_data(pt, 0) = exp(-(pow((pt[0] * dx - x_0), 2) + pow((pt[1] * dx - y_0), 2)) / (2 * pow(sigma, 2.))) / pow(sigma, 2.); velocities.m_data(pt, 1) = exp(-(pow((pt[0] * dx - x_0), 2) + pow((pt[1] * dx - y_0), 2)) / (2 * pow(sigma, 2.))) / pow(sigma, 2.); } RK4 <FieldData, RHSNavierStokes, DeltaVelocity> integrator; double dt = 0.0001; double time = 0.0; RectMDArray< double > vorticity(box); computeVorticity(vorticity, box, velocities, dx); sprintf(filename, "Vorticity.%.4f.%.4f", timeEnd, time); MDWrite(string(filename), vorticity); int nstep = 0; while (nstep < nstop) { velocities.setBoundaries(); integrator.advance(time, dt, velocities); sprintf(filename, "velocity.%d", nstep); MDWrite(string(filename), velocities.m_data); velocities.setBoundaries(); time += dt; nstep++; computeVorticity(vorticity, box, velocities, dx); sprintf(filename, "Vorticity.%d", nstep); MDWrite(string(filename), vorticity); cout << "iter = " << nstep << endl; } };
3,190
1,322
/* * The MIT License (MIT) * * Copyright (c) 2018 Sylko Olzscher * */ #include <smf/https/srv/session.h> #include <smf/https/srv/connections.h> #include <cyng/vm/controller.h> #include <cyng/vm/generator.h> #include <boost/uuid/uuid_io.hpp> namespace node { namespace https { plain_session::plain_session(cyng::logging::log_ptr logger , connections& cm , boost::uuids::uuid tag , boost::asio::ip::tcp::socket socket , boost::beast::flat_buffer buffer , std::string const& doc_root , auth_dirs const& ad) : session<plain_session>(logger, cm, tag, socket.get_executor().context(), std::move(buffer), doc_root, ad) , socket_(std::move(socket)) , strand_(socket_.get_executor()) {} plain_session::~plain_session() {} // Called by the base class boost::asio::ip::tcp::socket& plain_session::stream() { return socket_; } // Called by the base class boost::asio::ip::tcp::socket plain_session::release_stream() { return std::move(socket_); } // Start the asynchronous operation void plain_session::run(cyng::object obj) { // // substitute cb_ // this->connection_manager_.vm().async_run(cyng::generate_invoke("http.session.launch", tag(), false, stream().lowest_layer().remote_endpoint())); // Run the timer. The timer is operated // continuously, this simplifies the code. //on_timer({}); on_timer(obj, boost::system::error_code{}); do_read(obj); } void plain_session::do_eof(cyng::object obj) { // Send a TCP shutdown boost::system::error_code ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec); // // substitute cb_ // //this->connection_manager_.vm().async_run(cyng::generate_invoke("http.session.eof", tag(), false)); //cb_(cyng::generate_invoke("https.eof.session.plain", obj)); // At this point the connection is closed gracefully } void plain_session::do_timeout(cyng::object obj) { // Closing the socket cancels all outstanding operations. They // will complete with boost::asio::error::operation_aborted boost::system::error_code ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); socket_.close(ec); } ssl_session::ssl_session(cyng::logging::log_ptr logger , connections& cm , boost::uuids::uuid tag , boost::asio::ip::tcp::socket socket , boost::asio::ssl::context& ctx , boost::beast::flat_buffer buffer , std::string const& doc_root , auth_dirs const& ad) : session<ssl_session>(logger, cm, tag, socket.get_executor().context(), std::move(buffer), doc_root, ad) , stream_(std::move(socket), ctx) , strand_(stream_.get_executor()) {} ssl_session::~ssl_session() { //std::cerr << "ssl_session::~ssl_session()" << std::endl; } // Called by the base class boost::beast::ssl_stream<boost::asio::ip::tcp::socket>& ssl_session::stream() { return stream_; } // Called by the base class boost::beast::ssl_stream<boost::asio::ip::tcp::socket> ssl_session::release_stream() { return std::move(stream_); } // Start the asynchronous operation void ssl_session::run(cyng::object obj) { // // ToDo: substitute cb_ // this->connection_manager_.vm().async_run(cyng::generate_invoke("http.session.launch", tag(), true, stream().lowest_layer().remote_endpoint())); // Run the timer. The timer is operated // continuously, this simplifies the code. //on_timer({}); on_timer(obj, boost::system::error_code{}); // Set the timer timer_.expires_after(std::chrono::seconds(15)); // Perform the SSL handshake // Note, this is the buffered version of the handshake. stream_.async_handshake( boost::asio::ssl::stream_base::server, buffer_.data(), boost::asio::bind_executor( strand_, std::bind( &ssl_session::on_handshake, this, obj, // hold reference std::placeholders::_1, std::placeholders::_2))); } void ssl_session::on_handshake(cyng::object obj , boost::system::error_code ec , std::size_t bytes_used) { // Happens when the handshake times out if (ec == boost::asio::error::operation_aborted) { CYNG_LOG_ERROR(logger_, "handshake timeout "); return; } if (ec) { CYNG_LOG_FATAL(logger_, "handshake: " << ec.message()); return; } // Consume the portion of the buffer used by the handshake buffer_.consume(bytes_used); do_read(obj); } void ssl_session::do_eof(cyng::object obj) { eof_ = true; // Set the timer timer_.expires_after(std::chrono::seconds(15)); // Perform the SSL shutdown stream_.async_shutdown( boost::asio::bind_executor( strand_, std::bind( &ssl_session::on_shutdown, this, obj, std::placeholders::_1))); // // ToDo: substitute cb_ // CYNG_LOG_WARNING(logger_, tag() << " - SSL shutdown"); //cb_(cyng::generate_invoke("https.eof.session.ssl", obj)); } void ssl_session::on_shutdown(cyng::object obj, boost::system::error_code ec) { // Happens when the shutdown times out if (ec == boost::asio::error::operation_aborted) { CYNG_LOG_WARNING(logger_, tag() << " - SSL shutdown timeout"); connection_manager_.stop_session(tag()); return; } if (ec) { //return fail(ec, "shutdown"); CYNG_LOG_WARNING(logger_, tag() << " - SSL shutdown failed"); connection_manager_.stop_session(tag()); return; } // // ToDo: substitute cb_ // //cb_(cyng::generate_invoke("https.on.shutdown.session.ssl", obj)); connection_manager_.stop_session(tag()); // At this point the connection is closed gracefully } void ssl_session::do_timeout(cyng::object obj) { // If this is true it means we timed out performing the shutdown if (eof_) { return; } // Start the timer again timer_.expires_at((std::chrono::steady_clock::time_point::max)()); //on_timer({}); on_timer(obj, boost::system::error_code()); do_eof(obj); } } } namespace cyng { namespace traits { #if defined(CYNG_LEGACY_MODE_ON) const char type_tag<node::https::plain_session>::name[] = "plain-session"; const char type_tag<node::https::ssl_session>::name[] = "ssl-session"; #endif } // traits } namespace std { size_t hash<node::https::plain_session>::operator()(node::https::plain_session const& s) const noexcept { return s.hash(); } bool equal_to<node::https::plain_session>::operator()(node::https::plain_session const& s1, node::https::plain_session const& s2) const noexcept { return s1.hash() == s2.hash(); } bool less<node::https::plain_session>::operator()(node::https::plain_session const& s1, node::https::plain_session const& s2) const noexcept { return s1.hash() < s2.hash(); } size_t hash<node::https::ssl_session>::operator()(node::https::ssl_session const& s) const noexcept { return s.hash(); } bool equal_to<node::https::ssl_session>::operator()(node::https::ssl_session const& s1, node::https::ssl_session const& s2) const noexcept { return s1.hash() == s2.hash(); } bool less<node::https::ssl_session>::operator()(node::https::ssl_session const& s1, node::https::ssl_session const& s2) const noexcept { return s1.hash() < s2.hash(); } }
7,266
2,956
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <moaicore/MOAIGfxDevice.h> #include <moaicore/MOAILogMessages.h> #include <moaicore/MOAIFrameBufferTexture.h> //================================================================// // local //================================================================// //----------------------------------------------------------------// /** @name init @text Initializes frame buffer. @in MOAIFrameBufferTexture self @in number width @in number height @out nil */ int MOAIFrameBufferTexture::_init ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIFrameBufferTexture, "UNN" ) u32 width = state.GetValue < u32 >( 2, 0 ); u32 height = state.GetValue < u32 >( 3, 0 ); // TODO: fix me #ifdef MOAI_OS_ANDROID GLenum colorFormat = state.GetValue < GLenum >( 4, GL_RGB565 ); #else GLenum colorFormat = state.GetValue < GLenum >( 4, GL_RGBA8 ); #endif GLenum depthFormat = state.GetValue < GLenum >( 5, 0 ); GLenum stencilFormat = state.GetValue < GLenum >( 6, 0 ); self->Init ( width, height, colorFormat, depthFormat, stencilFormat ); return 0; } //================================================================// // MOAIFrameBufferTexture //================================================================// //----------------------------------------------------------------// void MOAIFrameBufferTexture::Init ( u32 width, u32 height, GLenum colorFormat, GLenum depthFormat, GLenum stencilFormat ) { this->Clear (); if ( MOAIGfxDevice::Get ().IsFramebufferSupported ()) { this->mWidth = width; this->mHeight = height; this->mColorFormat = colorFormat; this->mDepthFormat = depthFormat; this->mStencilFormat = stencilFormat; this->Load (); } else { MOAILog ( 0, MOAILogMessages::MOAITexture_NoFramebuffer ); } } //----------------------------------------------------------------// bool MOAIFrameBufferTexture::IsRenewable () { return true; } //----------------------------------------------------------------// bool MOAIFrameBufferTexture::IsValid () { return ( this->mGLFrameBufferID != 0 ); } //----------------------------------------------------------------// MOAIFrameBufferTexture::MOAIFrameBufferTexture () : mGLColorBufferID ( 0 ), mGLDepthBufferID ( 0 ), mGLStencilBufferID ( 0 ), mColorFormat ( 0 ), mDepthFormat ( 0 ), mStencilFormat ( 0 ) { RTTI_BEGIN RTTI_EXTEND ( MOAIFrameBuffer ) RTTI_EXTEND ( MOAITextureBase ) RTTI_END } //----------------------------------------------------------------// MOAIFrameBufferTexture::~MOAIFrameBufferTexture () { this->Clear (); } //----------------------------------------------------------------// void MOAIFrameBufferTexture::OnCreate () { if ( !( this->mWidth && this->mHeight && ( this->mColorFormat || this->mDepthFormat || this->mStencilFormat ))) { return; } this->mBufferWidth = this->mWidth; this->mBufferHeight = this->mHeight; // bail and retry (no error) if GL cannot generate buffer ID glGenFramebuffers ( 1, &this->mGLFrameBufferID ); if ( !this->mGLFrameBufferID ) return; if ( this->mColorFormat ) { glGenRenderbuffers( 1, &this->mGLColorBufferID ); glBindRenderbuffer ( GL_RENDERBUFFER, this->mGLColorBufferID ); glRenderbufferStorage ( GL_RENDERBUFFER, this->mColorFormat, this->mWidth, this->mHeight ); } if ( this->mDepthFormat ) { glGenRenderbuffers ( 1, &this->mGLDepthBufferID ); glBindRenderbuffer ( GL_RENDERBUFFER, this->mGLDepthBufferID ); glRenderbufferStorage ( GL_RENDERBUFFER, this->mDepthFormat, this->mWidth, this->mHeight ); } if ( this->mStencilFormat ) { glGenRenderbuffers ( 1, &this->mGLStencilBufferID ); glBindRenderbuffer ( GL_RENDERBUFFER, this->mGLStencilBufferID ); glRenderbufferStorage ( GL_RENDERBUFFER, this->mStencilFormat, this->mWidth, this->mHeight ); } glBindFramebuffer ( GL_FRAMEBUFFER, this->mGLFrameBufferID ); if ( this->mGLColorBufferID ) { glFramebufferRenderbuffer ( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, this->mGLColorBufferID ); } if ( this->mGLDepthBufferID ) { glFramebufferRenderbuffer ( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, this->mGLDepthBufferID ); } if ( this->mGLStencilBufferID ) { glFramebufferRenderbuffer ( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, this->mGLStencilBufferID ); } // TODO: handle error; clear GLenum status = glCheckFramebufferStatus ( GL_FRAMEBUFFER ); if ( status == GL_FRAMEBUFFER_COMPLETE ) { glGenTextures ( 1, &this->mGLTexID ); glBindTexture ( GL_TEXTURE_2D, this->mGLTexID ); glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGBA, this->mWidth, this->mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0 ); glFramebufferTexture2D ( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->mGLTexID, 0 ); // refresh tex params on next bind this->mIsDirty = true; } else { this->Clear (); } } //----------------------------------------------------------------// void MOAIFrameBufferTexture::OnDestroy () { if ( this->mGLFrameBufferID ) { MOAIGfxDevice::Get ().PushDeleter ( MOAIGfxDeleter::DELETE_FRAMEBUFFER, this->mGLFrameBufferID ); this->mGLFrameBufferID = 0; } if ( this->mGLColorBufferID ) { MOAIGfxDevice::Get ().PushDeleter ( MOAIGfxDeleter::DELETE_RENDERBUFFER, this->mGLColorBufferID ); this->mGLColorBufferID = 0; } if ( this->mGLDepthBufferID ) { MOAIGfxDevice::Get ().PushDeleter ( MOAIGfxDeleter::DELETE_RENDERBUFFER, this->mGLDepthBufferID ); this->mGLDepthBufferID = 0; } if ( this->mGLStencilBufferID ) { MOAIGfxDevice::Get ().PushDeleter ( MOAIGfxDeleter::DELETE_RENDERBUFFER, this->mGLStencilBufferID ); this->mGLStencilBufferID = 0; } this->MOAITextureBase::OnDestroy (); } //----------------------------------------------------------------// void MOAIFrameBufferTexture::OnInvalidate () { this->mGLFrameBufferID = 0; this->mGLColorBufferID = 0; this->mGLDepthBufferID = 0; this->mGLStencilBufferID = 0; this->MOAITextureBase::OnInvalidate (); } //----------------------------------------------------------------// void MOAIFrameBufferTexture::OnLoad () { } //----------------------------------------------------------------// void MOAIFrameBufferTexture::RegisterLuaClass ( MOAILuaState& state ) { MOAIFrameBuffer::RegisterLuaClass ( state ); MOAITextureBase::RegisterLuaClass ( state ); } //----------------------------------------------------------------// void MOAIFrameBufferTexture::RegisterLuaFuncs ( MOAILuaState& state ) { MOAIFrameBuffer::RegisterLuaFuncs ( state ); MOAITextureBase::RegisterLuaFuncs ( state ); luaL_Reg regTable [] = { { "init", _init }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); } //----------------------------------------------------------------// void MOAIFrameBufferTexture::Render () { if ( this->Affirm ()) { MOAIFrameBuffer::Render (); } } //----------------------------------------------------------------// void MOAIFrameBufferTexture::SerializeIn ( MOAILuaState& state, MOAIDeserializer& serializer ) { MOAITextureBase::SerializeIn ( state, serializer ); } //----------------------------------------------------------------// void MOAIFrameBufferTexture::SerializeOut ( MOAILuaState& state, MOAISerializer& serializer ) { MOAITextureBase::SerializeOut ( state, serializer ); }
7,391
2,609
#include <iostream> using namespace std; int main(){ int age; cout<<"enter your age"<<endl; cin>>age; /* if (age>=150){ cout<<"invalid age"; } else if (age >=18){ cout<<"you can vote"; } else { cout<<"sorry,you can not vote"; } */ switch (age){ case 12: cout<<"you are 10 year old"; break; case 18: cout<<"you are 18 year old"; break; default : cout<<"you are dis match"; break; } }
498
256
#include <netinet/tcp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <pthread.h> #define BUF_SIZE 100 #define NAME_SIZE 20 void* send_msg(void *arg); void* recv_msg(void *arg); void error_handling(char* msg); char name[NAME_SIZE] = "[DEFAULT]"; char msg[BUF_SIZE]; int main(int argc, char* argv[]){ int sock; struct sockaddr_in serv_addr; pthread_t send_thread, recv_thread; void* thread_return; // cout<< argc<<endl; if(argc != 4){ printf("Usage: %s <IP> <port> <name> \n", argv[0]); exit(0); } sprintf(name,"[%s]", argv[3]); //格式化字符串name sock =socket(PF_INET, SOCK_STREAM, 0); memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = inet_addr(argv[1]);//将字符串形式的IP地址->网络字节顺序的整型值 serv_addr.sin_port = htons(atoi(argv[2])); if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1){ error_handling("connect error"); } pthread_create(&send_thread, NULL, send_msg, (void*)&sock); pthread_create(&recv_thread, NULL, recv_msg, (void*)&sock); pthread_join(send_thread, &thread_return); pthread_join(send_thread, &thread_return); close(sock); return 0; } void* send_msg(void *arg){ int sock = *((int*)arg); char name_msg[NAME_SIZE+BUF_SIZE]; while(1){ fgets(msg, BUF_SIZE, stdin); if(!strcmp(msg, "q\n")||!strcmp(msg,"Q\n")){ close(sock); exit(0); } sprintf(name_msg, "%s %s", name, msg); write(sock, name_msg,sizeof(name_msg)); } return NULL; } void* recv_msg(void *arg){ int sock = *((int*)arg); char name_msg[NAME_SIZE+BUF_SIZE]; int str_len; while(1){ str_len = read(sock, name_msg, sizeof(NAME_SIZE)); if(str_len == -1){ return (void*)-1; } name_msg[str_len] = 0; fputs(name_msg, stdout); } return NULL; } void error_handling(char* msg){ fputs(msg, stderr); fputc('\n', stderr); exit(1); }
2,132
884
// Copyright (c) 2012 Christopher Lux <christopherlux@gmail.com> // Distributed under the Modified BSD License, see license.txt. #include "volume_generator_checkerboard.h" #include <scm/core/math/math.h> #include <exception> #include <new> namespace scm { namespace gl_classic { bool volume_generator_checkerboard::generate_float_volume(unsigned dim_x, unsigned dim_y, unsigned dim_z, unsigned components, boost::scoped_array<float>& buffer) { if (dim_x < 1 || dim_y < 1 || dim_z < 1 || components < 1) { return (false); } try { buffer.reset(new float[dim_x * dim_y * dim_z * components]); } catch (std::bad_alloc&) { return (false); } float val; unsigned offset_dst; for (unsigned z = 0; z < dim_z; z++) { for (unsigned y = 0; y < dim_y; y++) { for (unsigned x = 0; x < dim_x; x++) { val = float(scm::math::sign(-int((x+y+z) % 2))); offset_dst = x * components + y * dim_x * components + z * dim_x * dim_y * components; for (unsigned c = 0; c < components; c++) { buffer[offset_dst + c] = val; } } } } return (true); } } // namespace gl_classic } // namespace scm
1,561
463
#include "Distance.h" #include <DebugUtils.h> #if USE_IR #include "IR_Distance.h" #endif //Init int avr_front , avr_right , avr_left, avr_TOTAL = 0; //int angle, delta_angle; NewPing sonar_front (PING_PIN_FRONT, PING_PIN_FRONT, MAX_DISTANCE); NewPing sonar_right (PING_PIN_RIGHT, PING_PIN_RIGHT, MAX_DISTANCE); NewPing sonar_left (PING_PIN_LEFT, PING_PIN_LEFT, MAX_DISTANCE); distance* distance::GetInstance() { static distance* _distance = NULL; if(!_distance) { _distance = new distance(); } return _distance; } distance::distance(): isFollowLeft(false), isWallOnLeft(false), isWallOnRight(false), isWallInFront(false), isSlowSpeed(false), m_isMinFront(false) { Last_active_sensor = millis(); Last_distance_check = millis(); } const int& distance::getAvrTotal() { return avr_TOTAL; } void distance::init() { d_front = get_distance(sonar_front, MIN_DISTANCE, MAX_DISTANCE); DEBUG_PRINTLN("Setup d_front!"); d_right = get_distance(sonar_right, MIN_DISTANCE, MAX_DISTANCE); DEBUG_PRINTLN("Setup d_right!"); d_left = get_distance(sonar_left, MIN_DISTANCE, MAX_DISTANCE); DEBUG_PRINTLN("Setup d_left!"); for (uint8_t i = 0; i < DISTANCE_STACK_MAX; i++) { arr_front_stack[i] = d_front + 10 ; arr_right_stack[i] = d_right + 10; arr_left_stack[i] = d_left + 10; } #if USE_IR IR_DISTANCE->init(); #endif isFollowLeft = (d_right > d_left); } uint8_t distance::getAvrDistance(uint8_t stack[], uint8_t max_count) { int sum = 0; for(uint8_t i = 0; i < max_count; i++) { sum += stack[i]; } return sum/max_count; } void distance::updateDistanceStack() { arr_front_stack[g_DistanceStackIndex] = d_front; arr_right_stack[g_DistanceStackIndex] = d_right; arr_left_stack[g_DistanceStackIndex] = d_left; g_DistanceStackIndex++; if (g_DistanceStackIndex >= DISTANCE_STACK_MAX) g_DistanceStackIndex = 0; avr_front = getAvrDistance(arr_front_stack,DISTANCE_STACK_MAX); avr_right = getAvrDistance(arr_right_stack,DISTANCE_STACK_MAX); avr_left = getAvrDistance(arr_left_stack,DISTANCE_STACK_MAX); avr_TOTAL = avr_front + avr_right + avr_left ; // Debug Log + DEBUG_PRINT(">>>>>>>> g_DistanceStackIndex "); DEBUG_PRINTLN(g_DistanceStackIndex); DEBUG_PRINTLN("updateDistanceStack ______________ BEGIN"); DEBUG_PRINT("avr_front "); DEBUG_PRINT(avr_front); DEBUG_PRINT(" avr_right "); DEBUG_PRINT(avr_right); DEBUG_PRINT(" avr_left "); DEBUG_PRINT(avr_left); DEBUG_PRINT(" [[avr_TOTAL]] "); DEBUG_PRINTLN(avr_TOTAL); DEBUG_PRINT("d_front "); DEBUG_PRINT(d_front); DEBUG_PRINT(" d_right "); DEBUG_PRINT(d_right); DEBUG_PRINT(" d_left "); DEBUG_PRINT(d_left); DEBUG_PRINT(" <<d_TOTAL>> "); DEBUG_PRINTLN(d_front + d_right + d_left); DEBUG_PRINTLN(" ______________ END "); // Debug Log - } int distance::ping_mean_cm(NewPing& sonar, int N, int max_cm_distance) { int sum_dist = 0; int temp_dist = 0; int i = 0; unsigned long t; while(i<=N) { t = micros(); temp_dist = sonar.ping_cm(max_cm_distance); if(temp_dist > 0 && temp_dist <= max_cm_distance) { sum_dist += temp_dist; i++; } else { if(N==1) { return 0; //error result every ping } N--; } //add delay between ping (hardware limitation) if(i<=N && (micros() - t) < PING_MEAN_DELAY) { delay((PING_MEAN_DELAY + t - micros())/1000); } } return (sum_dist/N); } int distance::get_distance(NewPing sonar , int min , int max , int last_distance) { int d = ping_mean_cm(sonar, GET_DISTANCE_COUNTS, MAX_DISTANCE); if (last_distance > 0 && (d < min || d > max)) { d = last_distance; } else { if (d < min) d = min; if (d > max) d = max; } return d; } void distance::updateDistance() { #if USE_IR IR_DISTANCE->updateIR_distance(); #endif if(Last_distance_check < (millis()-CHECK_DISTANCE_DELAY)) { updateDistanceStack(); d_front = get_distance(sonar_front, MIN_DISTANCE, MAX_DISTANCE, MAX_DISTANCE );// phphat the 4th param should be previous value , not MAX_DISTANCE !!! d_right = get_distance(sonar_right, MIN_DISTANCE, MAX_DISTANCE, MAX_DISTANCE); d_left = get_distance(sonar_left, MIN_DISTANCE, MAX_DISTANCE, MAX_DISTANCE); Last_distance_check = millis(); } }
4,390
1,958
#include "NeuralInterface.h" int main() { //Define how much dimension we want and how large it is0 int dimensionSize[] = {2,50,70}; int size = 3; //Create a manager. This is the core component. NeuralInterface::InterfaceManager interfaceManager; //Add a Interface named "Test1" with the parameter we defined. interfaceManager.add("Test1",dimensionSize,size); //set every element in our interface to 0.2; interfaceManager.find("Test1").clear(0.2); //pick a random one and print it out std::cout << interfaceManager.find("Test1")[0][0].interface->data[0] << std::endl; return 0; }
596
199
#include "nau/material/materialGroup.h" #include "nau.h" #include "nau/geometry/vertexData.h" #include "nau/render/opengl/glMaterialGroup.h" #include "nau/math/vec3.h" #include "nau/clogger.h" using namespace nau::material; using namespace nau::render; using namespace nau::render::opengl; using namespace nau::math; std::shared_ptr<MaterialGroup> MaterialGroup::Create(IRenderable *parent, std::string materialName) { #ifdef NAU_OPENGL return std::shared_ptr<MaterialGroup>(new GLMaterialGroup(parent, materialName)); #endif } MaterialGroup::MaterialGroup() : m_Parent (0), m_MaterialName ("default") { //ctor } MaterialGroup::MaterialGroup(IRenderable *parent, std::string materialName) : m_Parent(parent), m_MaterialName(materialName) { //ctor } MaterialGroup::~MaterialGroup() { } void MaterialGroup::setParent(std::shared_ptr<nau::render::IRenderable> &parent) { this->m_Parent = parent.get(); } void MaterialGroup::setMaterialName (std::string name) { this->m_MaterialName = name; m_IndexData->setName(getName()); } std::string & MaterialGroup::getName() { m_Name = m_Parent->getName() + ":" + m_MaterialName; return m_Name; } const std::string& MaterialGroup::getMaterialName () { return m_MaterialName; } std::shared_ptr<nau::geometry::IndexData>& MaterialGroup::getIndexData (void) { if (!m_IndexData) { m_IndexData = IndexData::Create(getName()); } return (m_IndexData); } size_t MaterialGroup::getIndexOffset(void) { return 0; } size_t MaterialGroup::getIndexSize(void) { if (!m_IndexData) { return 0; } return m_IndexData->getIndexSize(); } void MaterialGroup::setIndexList (std::shared_ptr<std::vector<unsigned int>> &indices) { if (!m_IndexData) { m_IndexData.reset(); m_IndexData = IndexData::Create(getName()); } m_IndexData->setIndexData (indices); } unsigned int MaterialGroup::getNumberOfPrimitives(void) { return RENDERER->getNumberOfPrimitives(this); } IRenderable& MaterialGroup::getParent () { return *(this->m_Parent); } void MaterialGroup::updateIndexDataName() { m_IndexData->setName(getName()); }
2,110
775
#ifndef Books_ElementsOfProgrammingInterviews_ch8_hpp #define Books_ElementsOfProgrammingInterviews_ch8_hpp #include "reference/ch8.hpp" #include <cstdlib> #include <memory> #include <string> #include <vector> namespace study { extern std::shared_ptr<reference::ListNode<int>> MergeTwoSortedLists(std::shared_ptr<reference::ListNode<int>> l1, std::shared_ptr<reference::ListNode<int>> l2); extern std::shared_ptr<reference::ListNode<int>> ReverseLinkedList(const std::shared_ptr<reference::ListNode<int>> &list); extern std::shared_ptr<reference::ListNode<int>> HasCycle(const std::shared_ptr<reference::ListNode<int>> &list); extern std::shared_ptr<reference::ListNode<int>> OverlappingNoCycleLists(const std::shared_ptr<reference::ListNode<int>> &l1, const std::shared_ptr<reference::ListNode<int>> &l2); extern void DeleteFromList(const std::shared_ptr<reference::ListNode<int>> &list); extern std::shared_ptr<reference::ListNode<int>> RemoveKthLast(std::shared_ptr<reference::ListNode<int>> &list, int k); extern void RemoveDuplicates(const std::shared_ptr<reference::ListNode<int>> &list); extern void CyclicallyRightShiftList(std::shared_ptr<reference::ListNode<int>> &list, int k); extern void EvenOddMerge(std::shared_ptr<reference::ListNode<int>> &list); extern bool IsPalindrome(std::shared_ptr<reference::ListNode<int>> &list); extern void PivotList(std::shared_ptr<reference::ListNode<int>> &list, int k); extern std::shared_ptr<reference::ListNode<int>> AddNumbers(const std::shared_ptr<reference::ListNode<int>> &l1, const std::shared_ptr<reference::ListNode<int>> &l2); } #endif // Books_ElementsOfProgrammingInterviews_ch8_hpp
1,866
579
#include "sim/init.hh" namespace { const uint8_t data_m5_internal_param_X86ACPIRSDP[] = { 120,156,197,88,109,115,220,72,17,238,209,190,121,109,175,189, 142,223,242,226,196,162,136,47,11,199,217,192,85,224,224,66, 138,92,46,64,170,14,39,37,135,74,98,168,82,201,171,177, 45,103,87,218,90,141,237,236,149,205,7,28,94,254,6,31, 169,226,27,63,16,250,233,145,20,197,113,114,87,5,89,214, 222,217,209,168,103,166,123,158,167,123,122,166,75,217,103,158, 191,191,116,137,210,127,40,162,144,255,21,189,32,234,41,218, 118,72,105,135,194,121,58,168,81,114,133,84,88,163,87,68, 219,21,210,21,58,227,74,149,126,95,161,248,83,43,181,80, 72,53,46,146,106,241,11,30,123,130,94,84,165,201,161,209, 36,233,26,109,215,233,105,60,79,85,221,160,131,73,74,26, 164,248,19,243,204,207,70,109,202,122,76,208,118,147,165,86, 89,106,82,164,230,69,42,123,219,196,91,233,17,54,41,156, 164,87,172,249,20,133,83,162,197,52,133,211,82,105,81,216, 146,202,12,133,51,82,153,205,135,111,211,246,92,94,191,84, 170,207,151,234,11,165,250,98,169,190,84,170,47,75,125,150, 244,28,69,151,41,186,66,209,85,218,85,20,182,49,29,175, 196,243,237,107,164,171,20,173,208,246,10,105,254,191,70,103, 138,151,101,174,212,227,186,244,184,84,244,184,33,61,86,105, 123,149,52,255,223,176,61,38,104,171,179,200,176,69,255,230, 79,135,97,35,51,205,197,145,30,166,81,18,251,81,188,155, 68,14,222,55,80,0,228,46,138,10,127,235,252,189,15,180, 135,36,80,179,238,140,246,41,143,160,136,251,132,14,102,8, 43,116,229,84,225,33,170,208,9,87,170,180,43,47,162,106, 38,113,202,248,205,209,9,143,94,163,19,105,217,122,26,95, 167,170,169,11,64,115,2,144,125,205,157,241,154,225,33,86, 187,198,211,110,138,222,6,122,175,139,118,230,18,23,254,32, 24,6,125,255,217,103,63,185,119,255,241,67,111,235,203,199, 29,168,111,154,176,161,63,72,134,166,23,237,152,9,72,250, 113,208,215,190,111,38,249,97,200,221,76,100,216,110,83,229, 199,131,36,138,13,140,236,165,102,24,13,76,171,232,237,247, 147,240,176,167,205,20,183,60,148,150,7,195,97,50,236,96, 85,60,20,6,197,224,197,158,129,142,125,76,209,129,114,82, 164,191,227,98,99,63,233,107,46,226,189,209,225,198,158,238, 223,254,100,119,180,177,115,24,245,194,13,214,218,255,237,131, 173,135,254,147,227,196,255,74,31,233,222,198,96,100,88,116, 163,127,123,131,53,210,195,56,224,166,243,22,174,179,16,108, 79,143,163,61,63,83,115,95,247,6,122,8,171,211,25,76, 173,166,213,188,186,161,42,106,78,205,168,168,158,131,137,181, 105,229,96,254,51,3,211,201,92,151,241,84,25,184,14,157, 74,5,136,117,0,38,48,172,0,58,182,147,129,217,83,116, 230,208,31,42,16,56,229,178,202,158,230,22,64,46,88,79, 179,67,53,232,148,209,174,1,203,175,87,100,168,9,25,202, 161,19,46,25,230,42,157,178,59,179,40,55,113,121,208,164, 100,134,20,63,68,77,208,89,197,76,222,103,39,117,166,65, 181,160,129,165,47,172,9,163,33,22,221,3,115,59,147,121, 107,146,174,15,2,179,239,181,114,132,120,153,4,233,205,36, 182,96,238,70,113,152,131,107,233,177,27,245,152,30,30,214, 80,70,19,177,94,18,20,98,64,184,219,75,82,45,20,147, 177,189,89,8,66,122,119,32,195,96,86,232,35,157,67,157, 118,65,39,166,153,29,17,26,96,180,113,80,196,131,115,47, 96,138,171,66,136,54,83,162,206,132,232,48,33,108,109,197, 105,169,89,181,25,97,45,187,181,204,205,171,57,59,254,69, 22,17,69,7,142,248,230,137,68,5,150,102,220,196,55,79, 196,243,241,246,7,164,140,147,181,179,243,51,188,104,189,196, 125,132,51,76,30,150,189,3,87,22,52,65,130,26,49,43, 45,226,204,36,75,17,193,189,134,30,24,202,193,20,85,26, 44,243,224,19,32,195,9,101,172,57,171,48,43,88,35,118, 101,142,19,220,188,196,243,254,73,232,150,197,10,33,129,217, 143,210,228,216,122,56,234,18,238,182,216,105,30,143,30,237, 28,232,174,73,87,185,225,121,114,232,118,131,56,78,140,27, 132,161,27,24,142,0,59,135,70,167,174,73,220,181,180,3, 32,189,171,57,143,138,241,70,3,237,73,197,146,39,140,186, 134,99,203,188,60,136,99,166,218,48,13,246,147,48,229,118, 116,221,211,198,107,163,7,150,57,17,5,132,37,62,68,49, 45,203,193,119,239,229,26,216,72,83,207,137,147,234,222,174, 4,175,110,47,72,83,31,26,72,187,208,13,86,31,5,189, 67,45,163,167,60,30,43,132,170,213,97,44,49,233,50,140, 201,109,23,131,226,36,14,71,172,95,212,253,20,83,95,22, 34,182,56,38,181,212,18,127,155,106,81,53,152,142,13,181, 236,116,171,25,249,138,189,102,9,134,147,160,174,50,224,153, 140,103,28,73,58,142,4,2,177,9,228,245,190,143,26,58, 123,55,81,172,161,248,8,197,173,220,236,15,109,123,235,188, 237,247,49,159,35,6,119,43,153,105,133,111,249,111,248,214, 76,201,183,206,224,35,39,178,171,70,149,146,127,84,96,126, 50,149,123,148,248,31,131,206,254,7,97,241,36,222,108,203, 126,128,73,55,189,43,80,227,59,92,220,90,75,111,185,150, 117,238,126,144,186,113,242,154,234,46,94,218,160,6,162,123, 43,88,249,18,149,247,74,84,246,92,72,128,199,222,119,81, 84,223,181,244,223,27,255,210,239,217,165,255,53,230,155,206, 184,54,35,28,155,82,93,16,5,120,52,114,16,182,184,50, 90,6,8,229,213,95,230,141,239,105,188,194,123,153,32,128, 237,172,101,183,51,217,19,109,202,152,71,181,168,150,87,234, 192,97,183,66,75,217,46,149,98,27,25,12,147,151,35,55, 217,117,13,229,42,221,89,75,215,215,210,207,57,176,184,119, 95,175,120,22,68,134,122,128,32,96,131,2,214,197,68,49, 63,99,168,7,47,187,90,54,18,121,242,125,27,3,108,50, 227,103,27,20,131,35,104,56,57,26,18,5,57,163,65,240, 27,11,20,147,5,20,48,229,49,38,155,20,28,42,106,153, 189,190,132,2,190,21,160,0,154,253,149,36,129,85,244,23, 194,26,243,74,102,46,46,158,147,123,207,60,196,145,197,156, 168,11,119,37,39,243,10,39,11,25,236,54,131,150,108,54, 217,46,197,105,201,223,74,241,164,216,69,42,89,106,83,246, 158,106,225,61,2,208,183,218,41,170,111,58,16,22,159,61, 13,98,226,42,54,103,188,249,102,108,146,60,166,34,209,221, 124,104,116,38,236,52,62,52,122,254,26,27,196,227,235,106, 193,177,12,17,242,252,20,197,103,133,3,171,188,237,3,42, 183,122,62,128,150,54,15,223,70,159,103,208,160,42,58,207, 54,204,13,254,229,49,30,110,221,243,239,63,250,234,209,230, 150,143,225,242,58,134,149,140,23,31,108,142,95,128,61,63, 230,138,230,83,156,34,45,145,245,149,36,192,40,29,112,224, 204,81,124,2,229,148,226,149,156,64,237,65,211,179,41,133, 48,55,255,74,252,64,220,121,35,110,151,22,176,96,129,5, 24,197,203,177,120,32,48,190,211,11,250,59,97,112,247,5, 166,194,124,221,220,227,156,92,247,118,89,119,248,138,122,135, 250,242,248,121,110,195,209,88,18,215,59,36,199,75,171,187, 56,71,152,116,37,80,60,217,215,110,95,247,119,248,200,186, 31,13,220,221,94,176,39,184,84,50,219,30,229,182,25,1, 182,228,207,18,78,82,228,9,155,137,219,77,98,142,138,135, 93,147,12,221,80,243,73,64,135,238,39,174,132,84,55,74, 221,96,135,223,6,93,99,121,255,166,235,74,198,21,12,247, 82,73,174,94,28,163,58,54,96,125,62,164,71,156,102,246, 169,200,45,236,30,34,145,7,41,150,36,144,214,141,120,243, 225,19,161,25,217,32,118,15,197,109,20,27,84,222,151,63, 52,150,63,231,145,15,48,5,150,171,174,174,57,77,199,204, 89,207,205,197,30,163,95,250,182,179,254,253,219,56,171,174, 210,118,45,119,217,58,36,117,3,39,76,148,77,108,1,219, 147,121,227,148,148,211,210,216,202,27,103,164,156,149,198,118, 222,56,39,229,37,105,156,167,236,2,107,65,26,23,105,123, 137,194,186,180,44,35,54,52,254,203,216,32,206,53,54,183, 50,255,203,144,224,253,226,255,162,186,119,151,178,188,225,93, 225,64,149,237,106,217,190,145,202,243,102,89,246,77,107,134, 156,202,47,95,196,71,191,59,212,129,209,22,163,155,99,50, 84,130,138,157,248,248,181,143,23,73,83,45,183,233,87,133, 77,103,146,49,141,22,4,186,252,230,13,215,125,114,243,105, 36,69,69,14,219,182,119,107,178,8,190,147,165,177,84,44, 70,189,88,12,220,16,198,250,216,127,107,65,108,162,10,193, 96,48,208,113,232,253,16,125,126,68,229,132,83,100,198,194, 8,196,179,63,82,145,195,76,115,134,185,192,121,204,219,158, 136,208,88,50,84,224,108,23,206,55,46,96,133,193,127,206, 25,220,1,227,94,7,109,239,11,20,18,166,139,8,237,61, 40,16,89,185,144,158,137,238,251,81,136,35,207,251,5,56, 155,178,23,14,242,152,103,77,231,100,135,250,40,146,75,96, 12,247,13,34,24,16,155,81,222,96,174,94,44,159,134,70, 134,123,207,107,12,133,85,192,195,59,228,94,190,127,152,151, 229,97,240,32,196,16,143,14,117,79,27,253,54,143,13,208, 207,14,182,161,230,157,62,25,241,57,170,33,141,220,199,247, 199,183,57,222,207,8,145,226,154,142,55,71,85,231,237,113, 81,201,159,211,172,55,149,228,29,231,46,229,75,109,245,162, 205,165,252,24,49,74,61,180,24,208,41,75,4,68,27,191, 124,207,47,119,131,150,93,114,105,153,167,10,32,162,28,48, 55,131,190,189,126,146,247,217,81,52,181,46,47,23,164,200, 164,188,143,81,124,82,240,246,103,232,125,157,139,254,237,245, 220,240,245,243,134,63,145,219,210,254,109,243,209,57,193,76, 100,107,148,126,169,211,238,147,96,135,15,180,71,26,57,154, 89,123,223,152,229,14,230,218,133,146,91,81,223,94,248,73, 234,81,126,31,14,3,174,47,158,107,77,245,48,10,122,209, 215,250,253,214,60,131,53,88,159,252,181,193,109,240,249,41, 177,92,197,147,228,67,230,99,250,166,163,139,32,55,212,123, 81,202,35,203,176,197,16,89,52,6,119,222,225,170,229,190, 99,35,179,61,121,216,139,136,187,114,239,240,27,46,218,184, 229,155,104,170,6,126,103,249,215,225,72,237,84,212,164,154, 81,53,254,109,243,239,156,51,221,110,86,155,77,150,155,154, 86,229,191,85,118,129,73,103,117,190,169,254,3,9,41,59, 195, }; EmbeddedPython embedded_m5_internal_param_X86ACPIRSDP( "m5/internal/param_X86ACPIRSDP.py", "/home/hongyu/gem5-fy/build/X86_MESI_Two_Level/python/m5/internal/param_X86ACPIRSDP.py", "m5.internal.param_X86ACPIRSDP", data_m5_internal_param_X86ACPIRSDP, 2465, 7288); } // anonymous namespace
10,012
9,336
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/shield/model/ProtectionGroupArbitraryPatternLimits.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Shield { namespace Model { ProtectionGroupArbitraryPatternLimits::ProtectionGroupArbitraryPatternLimits() : m_maxMembers(0), m_maxMembersHasBeenSet(false) { } ProtectionGroupArbitraryPatternLimits::ProtectionGroupArbitraryPatternLimits(JsonView jsonValue) : m_maxMembers(0), m_maxMembersHasBeenSet(false) { *this = jsonValue; } ProtectionGroupArbitraryPatternLimits& ProtectionGroupArbitraryPatternLimits::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("MaxMembers")) { m_maxMembers = jsonValue.GetInt64("MaxMembers"); m_maxMembersHasBeenSet = true; } return *this; } JsonValue ProtectionGroupArbitraryPatternLimits::Jsonize() const { JsonValue payload; if(m_maxMembersHasBeenSet) { payload.WithInt64("MaxMembers", m_maxMembers); } return payload; } } // namespace Model } // namespace Shield } // namespace Aws
1,228
451
// UVa 116 #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int MAXR = 10+10; const int MAXC = 100+10; const int INF = 1 << 30; int F[MAXR][MAXC]; int dp[MAXR][MAXC]; int nxt[MAXR][MAXC]; int R, C; void print_table() { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) printf("%d(%d) ", dp[i][j], nxt[i][j]); printf("\n"); } printf("\n"); } void solve() { for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) dp[r][c] = INF; for (int r = 0; r < R; r++) dp[r][C-1] = F[r][C-1]; for (int c = C-2; c >= 0; c--) { for (int r = 0; r < R; r++) { int up = (r-1+R)%R; int down = (r+1)%R; if (dp[r][c] > dp[up][c+1] + F[r][c] || (dp[r][c] == dp[up][c+1] + F[r][c] && nxt[r][c] > up)) { dp[r][c] = dp[up][c+1] + F[r][c]; nxt[r][c] = up; } if (dp[r][c] > dp[r][c+1] + F[r][c] || (dp[r][c] == dp[r][c+1] + F[r][c] && nxt[r][c] > r)) { dp[r][c] = dp[r][c+1] + F[r][c]; nxt[r][c] = r; } if (dp[r][c] > dp[down][c+1] + F[r][c] || (dp[r][c] == dp[down][c+1] + F[r][c] && nxt[r][c] > down)) { dp[r][c] = dp[down][c+1] + F[r][c]; nxt[r][c] = down; } } } // print_table(); int row, ans = INF; for (int r = 0; r < R; r++) if (dp[r][0] < ans) { ans = dp[r][0]; row = r; } printf("%d", row+1); for (int i = 0; i < C-1; i++) { printf(" %d", nxt[row][i]+1); row = nxt[row][i]; } printf("\n%d\n", ans); } int main() { while (scanf("%d%d", &R, &C) == 2) { memset(dp, 0, sizeof(dp)); for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) scanf("%d", &F[i][j]); // printf("INF = %d\n", INF); solve(); } }
2,010
944
#include "pch.h" #include "ItemBankWindow.h" #include "ItemBankPage.h" #include "../[Lib]__EngineUI/Sources/BasicButton.h" #include "GLGaeaClient.h" #include "../[Lib]__EngineUI/Sources/BasicTextBox.h" #include "InnerInterface.h" #include "ModalCallerID.h" #include "../[Lib]__Engine/Sources/DxTools/DxFontMan.h" #include "ModalWindow.h" #include "UITextControl.h" #include "GameTextControl.h" #include "BasicTextButton.h" #ifdef _DEBUG #define new DEBUG_NEW #endif CItemBankWindow::CItemBankWindow () : m_pPage ( NULL ) { } CItemBankWindow::~CItemBankWindow () { } void CItemBankWindow::CreateSubControl () { // CreateTextButton ( "ITEMBANK_REFRESH_BUTTON", ITEMBANK_REFRESH_BUTTON, const_cast<char*>(ID2GAMEWORD("ITEMBANK_REFRESH_BUTTON")) ); CItemBankPage* pItemBankPage = new CItemBankPage; pItemBankPage->CreateSub ( this, "ITEMBANK_PAGE", UI_FLAG_DEFAULT, ITEMBANK_PAGE ); pItemBankPage->CreateSubControl (); RegisterControl ( pItemBankPage ); m_pPage = pItemBankPage; } CBasicTextButton* CItemBankWindow::CreateTextButton ( char* szButton, UIGUID ControlID, char* szText ) { const int nBUTTONSIZE = CBasicTextButton::SIZE14; CBasicTextButton* pTextButton = new CBasicTextButton; pTextButton->CreateSub ( this, "BASIC_TEXT_BUTTON14", UI_FLAG_XSIZE, ControlID ); pTextButton->CreateBaseButton ( szButton, nBUTTONSIZE, CBasicButton::CLICK_FLIP, szText ); RegisterControl ( pTextButton ); return pTextButton; } void CItemBankWindow::InitItemBank () { m_pPage->UnLoadItemPage (); GLCharacter* pCharacter = GLGaeaClient::GetInstance().GetCharacter(); m_pPage->LoadItemPage ( pCharacter->m_cInvenCharged ); } void CItemBankWindow::ClearItemBank() { m_pPage->UnLoadItemPage (); } void CItemBankWindow::TranslateUIMessage ( UIGUID ControlID, DWORD dwMsg ) { CUIWindowEx::TranslateUIMessage ( ControlID, dwMsg ); if ( ET_CONTROL_TITLE == ControlID || ET_CONTROL_TITLE_F == ControlID ) { if ( (dwMsg & UIMSG_LB_DUP) && CHECK_MOUSE_IN ( dwMsg ) ) { CInnerInterface::GetInstance().SetDefaultPosInterface( ITEMBANK_WINDOW ); return; } } else if ( ITEMBANK_PAGE == ControlID ) { if ( CHECK_MOUSE_IN ( dwMsg ) ) { int nPosX, nPosY; m_pPage->GetItemIndex ( &nPosX, &nPosY ); //CDebugSet::ToView ( 1, 3, "[itembank] Page:%d %d / %d", nPosX, nPosY ); if ( nPosX < 0 || nPosY < 0 ) return ; SINVENITEM sInvenItem = m_pPage->GetItem ( nPosX, nPosY ); if ( sInvenItem.sItemCustom.sNativeID != NATIVEID_NULL () ) { CInnerInterface::GetInstance().SHOW_ITEM_INFO ( sInvenItem.sItemCustom, FALSE, FALSE, FALSE, sInvenItem.wPosX, sInvenItem.wPosY ); } if ( dwMsg & UIMSG_LB_UP ) { GLGaeaClient::GetInstance().GetCharacter()->ReqChargedItemTo ( static_cast<WORD>(nPosX), static_cast<WORD>(nPosY) ); return ; } } } }
2,807
1,193
#include "Player.h" Player::Player(std::string username, sf::Uint64 id, sf::IpAddress address, unsigned short port) : username(username), id(id), address(address), port(port) { //ctor } Player::~Player() { //dtor }
225
84
#pragma once #include <algorithm.hpp> namespace ktl { namespace str::details { template <class Traits, class CharT, class SizeType> constexpr SizeType find_ch(const CharT* str, CharT ch, SizeType length, SizeType start_pos, SizeType npos) { if (start_pos >= length) { return npos; } const CharT* found_ptr{Traits::find(str + start_pos, length - start_pos, ch)}; return found_ptr ? static_cast<SizeType>(found_ptr - str) : npos; } template <class Traits, class CharT, class SizeType> constexpr SizeType rfind_ch(const CharT* str, CharT ch, SizeType length, SizeType start_pos, SizeType npos) { if (start_pos >= length) { return npos; } for (SizeType idx = length; idx > 0; --idx) { const SizeType pos{idx - 1}; if (Traits::eq(str[pos], ch)) { return pos; } } return npos; } template <class Traits, class CharT, class SizeType> constexpr SizeType find_substr(const CharT* str, SizeType str_start_pos, SizeType str_length, const CharT* substr, SizeType substr_length, SizeType npos) { if (substr_length > str_length) { return npos; } const CharT* str_end{str + str_length}; const auto found_ptr{find_subrange( str + str_start_pos, str_end, substr, substr + substr_length, [](CharT lhs, CharT rhs) { return Traits::eq(lhs, rhs); })}; return found_ptr != str_end ? static_cast<SizeType>(found_ptr - str) : npos; } } // namespace str::details } // namespace ktl
1,805
536
#ifndef STRING_TOOLS_HPP #define STRING_TOOLS_HPP #include <string> namespace APAL { /** * @brief Replaces all occurences of an itemToReplace in the given strToChange * @param strToChange string to replaces stuff in. * @param itemToReplace String value, which should be replaces * @param substitute Text to replace itemToReplace with */ std::string replaceInString(std::string strToChange, const std::string itemToReplace, const std::string substitute); /** * @brief Gets the filename from a path with or without extension * When no seperator is found, the whole filePath is returned. * @param filePath filepath, to retreive filename from * @param withExtension return the fileextension with the filename. * @param seperator Seperator for the given fielpath. Defaults to /. * @return */ std::string getFileName(std::string filePath, bool withExtension = true, char seperator = '/'); } #endif //! STRING_TOOLS_HPP
983
277
#pragma once #include <cassert> #include <iostream> #include <iterator> #include <limits> #include <set> #include <tuple> #include <utility> template <typename T> struct SetManagedByInterval { using IntervalType = std::set<std::pair<T, T>>; IntervalType interval{ {std::numeric_limits<T>::lowest(), std::numeric_limits<T>::lowest()}, {std::numeric_limits<T>::max(), std::numeric_limits<T>::max()}, }; bool contains(T x) const { return contains(x, x); } bool contains(T left, T right) const { typename IntervalType::const_iterator it = interval.lower_bound({left, left}); if (left < it->first) it = std::prev(it); return it->first <= left && right <= it->second; } std::pair<typename IntervalType::const_iterator, bool> erase(T x) { typename IntervalType::const_iterator it = interval.lower_bound({x, x}); if (it->first == x) { T right = it->second; it = interval.erase(it); if (x + 1 <= right) it = interval.emplace(x + 1, right).first; return {it, true}; } it = std::prev(it); T left, right; std::tie(left, right) = *it; if (right < x) return {std::next(it), false}; interval.erase(it); it = std::next(interval.emplace(left, x - 1).first); if (x + 1 <= right) it = interval.emplace(x + 1, right).first; return {it, true}; } std::pair<typename IntervalType::const_iterator, T> erase(T left, T right) { assert(left <= right); typename IntervalType::const_iterator it = interval.lower_bound({left, left}); T res = 0; for (; it->second <= right; it = interval.erase(it)) res += it->second - it->first + 1; if (it->first <= right) { res += right - it->first + 1; T r = it->second; interval.erase(it); it = interval.emplace(right + 1, r).first; } if (left < std::prev(it)->second) { it = std::prev(it); res += it->second - left + 1; T l = it->first; interval.erase(it); it = std::next(interval.emplace(l, left - 1).first); } return {it, res}; } std::pair<typename IntervalType::const_iterator, bool> insert(T x) { typename IntervalType::const_iterator it = interval.lower_bound({x, x}); if (it->first == x) return {it, false}; if (x <= std::prev(it)->second) return {std::prev(it), false}; T left = x, right = x; if (x + 1 == it->first) { right = it->second; it = interval.erase(it); } if (std::prev(it)->second == x - 1) { it = std::prev(it); left = it->first; interval.erase(it); } return {interval.emplace(left, right).first, true}; } std::pair<typename IntervalType::const_iterator, T> insert(T left, T right) { assert(left <= right); typename IntervalType::const_iterator it = interval.lower_bound({left, left}); if (left <= std::prev(it)->second) { it = std::prev(it); left = it->first; } T res = 0; if (left == it->first && right <= it->second) return {it, res}; for (; it->second <= right; it = interval.erase(it)) res -= it->second - it->first + 1; if (it->first <= right) { res -= it->second - it->first + 1; right = it->second; it = interval.erase(it); } res += right - left + 1; if (right + 1 == it->first) { right = it->second; it = interval.erase(it); } if (std::prev(it)->second == left - 1) { it = std::prev(it); left = it->first; interval.erase(it); } return {interval.emplace(left, right).first, res}; } T mex(T x = 0) const { auto it = interval.lower_bound({x, x}); if (x <= std::prev(it)->second) it = std::prev(it); return x < it->first ? x : it->second + 1; } friend std::ostream &operator<<(std::ostream &os, const SetManagedByInterval &st) { if (st.interval.size() == 2) return os; auto it = next(st.interval.begin()); while (true) { os << '[' << it->first << ", " << it->second << ']'; it = next(it); if (next(it) == st.interval.end()) { break; } else { os << ' '; } } return os; } };
4,217
1,489
/* ISC License Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "dualHingedRigidBodyStateEffector.h" DualHingedRigidBodyStateEffector::DualHingedRigidBodyStateEffector() { // - zero the mass props and mass prop rates contributions this->effProps.mEff = 0.0; this->effProps.mEffDot = 0.0; this->effProps.rEff_CB_B.setZero(); this->effProps.IEffPntB_B.setZero(); this->effProps.rEffPrime_CB_B.setZero(); this->effProps.IEffPrimePntB_B.setZero(); this->matrixFDHRB.resize(2, 3); this->matrixGDHRB.resize(2, 3); // - Initialize the variables to working values this->mass1 = 0.0; this->d1 = 1.0; this->k1 = 1.0; this->c1 = 0.0; this->mass2 = 0.0; this->d2 = 1.0; this->k2 = 1.0; this->c2 = 0.0; this->theta1Init = 0.0; this->theta1DotInit = 0.0; this->theta2Init = 0.0; this->theta2DotInit = 0.0; this->IPntS1_S1.setIdentity(); this->IPntS2_S2.setIdentity(); this->rH1B_B.setZero(); this->dcmH1B.setIdentity(); this->thetaH2S1 = 0.0; this->nameOfTheta1State = "hingedRigidBodyTheta1"; this->nameOfTheta1DotState = "hingedRigidBodyTheta1Dot"; this->nameOfTheta2State = "hingedRigidBodyTheta2"; this->nameOfTheta2DotState = "hingedRigidBodyTheta2Dot"; return; } DualHingedRigidBodyStateEffector::~DualHingedRigidBodyStateEffector() { return; } void DualHingedRigidBodyStateEffector::linkInStates(DynParamManager& statesIn) { // - Get access to the hubs sigma, omegaBN_B and velocity needed for dynamic coupling this->hubVelocity = statesIn.getStateObject("hubVelocity"); this->hubSigma = statesIn.getStateObject("hubSigma"); this->hubOmega = statesIn.getStateObject("hubOmega"); this->g_N = statesIn.getPropertyReference("g_N"); return; } void DualHingedRigidBodyStateEffector::registerStates(DynParamManager& states) { // - Register the states associated with hinged rigid bodies - theta and thetaDot this->theta1State = states.registerState(1, 1, this->nameOfTheta1State); this->theta1DotState = states.registerState(1, 1, this->nameOfTheta1DotState); this->theta2State = states.registerState(1, 1, this->nameOfTheta2State); this->theta2DotState = states.registerState(1, 1, this->nameOfTheta2DotState); // - Add this code to allow for non-zero initial conditions, as well hingedRigidBody Eigen::MatrixXd theta1InitMatrix(1,1); theta1InitMatrix(0,0) = this->theta1Init; this->theta1State->setState(theta1InitMatrix); Eigen::MatrixXd theta1DotInitMatrix(1,1); theta1DotInitMatrix(0,0) = this->theta1DotInit; this->theta1DotState->setState(theta1DotInitMatrix); Eigen::MatrixXd theta2InitMatrix(1,1); theta2InitMatrix(0,0) = this->theta2Init; this->theta2State->setState(theta2InitMatrix); Eigen::MatrixXd theta2DotInitMatrix(1,1); theta2DotInitMatrix(0,0) = this->theta2DotInit; this->theta2DotState->setState(theta2DotInitMatrix); return; } void DualHingedRigidBodyStateEffector::updateEffectorMassProps(double integTime) { // - Give the mass of the hinged rigid body to the effProps mass this->effProps.mEff = this->mass1 + this->mass2; // - find hinged rigid bodies' position with respect to point B // - First need to grab current states this->theta1 = this->theta1State->getState()(0, 0); this->theta1Dot = this->theta1DotState->getState()(0, 0); this->theta2 = this->theta2State->getState()(0, 0); this->theta2Dot = this->theta2DotState->getState()(0, 0); // - Next find the sHat unit vectors Eigen::Matrix3d dcmS1H1; dcmS1H1 = eigenM2(this->theta1); this->dcmS1B = dcmS1H1*this->dcmH1B; Eigen::Matrix3d dcmH2S1; dcmH2S1 = eigenM2(this->thetaH2S1); Eigen::Matrix3d dcmH2B; dcmH2B = dcmH2S1*this->dcmS1B; Eigen::Matrix3d dcmS2H2; dcmS2H2 = eigenM2(this->theta2); this->dcmS2B = dcmS2H2 * dcmH2B; this->sHat11_B = this->dcmS1B.row(0); this->sHat12_B = this->dcmS1B.row(1); this->sHat13_B = this->dcmS1B.row(2); this->sHat21_B = this->dcmS2B.row(0); this->sHat22_B = this->dcmS2B.row(1); this->sHat23_B = this->dcmS2B.row(2); this->rS1B_B = this->rH1B_B - this->d1*this->sHat11_B; this->rS2B_B = this->rH1B_B - this->l1*this->sHat11_B - this->d2*this->sHat21_B; this->effProps.rEff_CB_B = 1.0/this->effProps.mEff*(this->mass1*this->rS1B_B + this->mass2*this->rS2B_B); // - Find the inertia of the hinged rigid body about point B // - Define rTildeSB_B this->rTildeS1B_B = eigenTilde(this->rS1B_B); this->rTildeS2B_B = eigenTilde(this->rS2B_B); this->effProps.IEffPntB_B = this->dcmS1B.transpose()*this->IPntS1_S1*this->dcmS1B + this->mass1*this->rTildeS1B_B*this->rTildeS1B_B.transpose() + this->dcmS2B.transpose()*this->IPntS2_S2*this->dcmS2B + this->mass2*this->rTildeS2B_B*this->rTildeS2B_B.transpose(); // First, find the rPrimeSB_B this->rPrimeS1B_B = this->d1*this->theta1Dot*this->sHat13_B; this->rPrimeS2B_B = this->l1*this->theta1Dot*this->sHat13_B + this->d2*(this->theta1Dot + this->theta2Dot)*this->sHat23_B; this->effProps.rEffPrime_CB_B = 1.0/this->effProps.mEff*(this->mass1*this->rPrimeS1B_B + this->mass2*this->rPrimeS2B_B); // - Next find the body time derivative of the inertia about point B // - Define tilde matrix of rPrimeSB_B this->rPrimeTildeS1B_B = eigenTilde(this->rPrimeS1B_B); this->rPrimeTildeS2B_B = eigenTilde(this->rPrimeS2B_B); // - Find body time derivative of IPntS_B this->IS1PrimePntS1_B = this->theta1Dot*(this->IPntS1_S1(2,2) - this->IPntS1_S1(0,0))*(this->sHat11_B*this->sHat13_B.transpose() + this->sHat13_B*this->sHat11_B.transpose()); this->IS2PrimePntS2_B = (this->theta1Dot+this->theta2Dot)*(this->IPntS2_S2(2,2) - this->IPntS2_S2(0,0))*(this->sHat21_B*this->sHat23_B.transpose() + this->sHat23_B*this->sHat21_B.transpose()); // - Find body time derivative of IPntB_B this->effProps.IEffPrimePntB_B = this->IS1PrimePntS1_B - this->mass1*(this->rPrimeTildeS1B_B*this->rTildeS1B_B + this->rTildeS1B_B*this->rPrimeTildeS1B_B) + this->IS2PrimePntS2_B - this->mass2*(this->rPrimeTildeS2B_B*this->rTildeS2B_B + this->rTildeS2B_B*this->rPrimeTildeS2B_B); return; } void DualHingedRigidBodyStateEffector::updateContributions(double integTime, BackSubMatrices & backSubContr, Eigen::Vector3d sigma_BN, Eigen::Vector3d omega_BN_B, Eigen::Vector3d g_N) { Eigen::MRPd sigmaBNLocal; Eigen::Matrix3d dcmBN; /* direction cosine matrix from N to B */ Eigen::Matrix3d dcmNB; /* direction cosine matrix from B to N */ Eigen::Vector3d gravityTorquePntH1_B; /* torque of gravity on HRB about Pnt H */ Eigen::Vector3d gravityTorquePntH2_B; /* torque of gravity on HRB about Pnt H */ Eigen::Vector3d gLocal_N; /* gravitational acceleration in N frame */ Eigen::Vector3d g_B; /* gravitational acceleration in B frame */ gLocal_N = *this->g_N; // - Find dcmBN sigmaBNLocal = (Eigen::Vector3d )this->hubSigma->getState(); dcmNB = sigmaBNLocal.toRotationMatrix(); dcmBN = dcmNB.transpose(); // - Map gravity to body frame g_B = dcmBN*gLocal_N; // - Define gravity terms Eigen::Vector3d gravTorquePan1PntH1 = -this->d1*this->sHat11_B.cross(this->mass1*g_B); Eigen::Vector3d gravForcePan2 = this->mass2*g_B; Eigen::Vector3d gravTorquePan2PntH2 = -this->d2*this->sHat21_B.cross(this->mass2*g_B); // - Define omegaBN_S this->omegaBNLoc_B = this->hubOmega->getState(); this->omegaBN_S1 = this->dcmS1B*this->omegaBNLoc_B; this->omegaBN_S2 = this->dcmS2B*this->omegaBNLoc_B; // - Define omegaTildeBNLoc_B this->omegaTildeBNLoc_B = eigenTilde(this->omegaBNLoc_B); // - Define matrices needed for back substitution //gravityTorquePntH1_B = -this->d1*this->sHat11_B.cross(this->mass1*g_B); //Need to review these equations and implement them - SJKC //gravityTorquePntH2_B = -this->d2*this->sHat21_B.cross(this->mass2*g_B); //Need to review these equations and implement them - SJKC this->matrixADHRB(0,0) = this->IPntS1_S1(1,1) + this->mass1*this->d1*this->d1 + this->mass2*this->l1*this->l1 + this->mass2*this->l1*this->d2*this->sHat13_B.transpose()*(this->sHat23_B); this->matrixADHRB(0,1) = this->mass2*this->l1*this->d2*this->sHat13_B.transpose()*(this->sHat23_B); this->matrixADHRB(1,0) = IPntS2_S2(1,1) + this->mass2*this->d2*this->d2 + this->mass2*this->l1*this->d2*this->sHat23_B.transpose()*this->sHat13_B; this->matrixADHRB(1,1) = this->IPntS2_S2(1,1) + this->mass2*this->d2*this->d2; this->matrixEDHRB = this->matrixADHRB.inverse(); this->matrixFDHRB.row(0) = -(this->mass2*this->l1 + this->mass1*this->d1)*this->sHat13_B.transpose(); this->matrixFDHRB.row(1) = -this->mass2*this->d2*this->sHat23_B.transpose(); this->matrixGDHRB.row(0) = -(this->IPntS1_S1(1,1)*this->sHat12_B.transpose() - this->mass1*this->d1*this->sHat13_B.transpose()*this->rTildeS1B_B - this->mass2*this->l1*this->sHat13_B.transpose()*this->rTildeS2B_B); this->matrixGDHRB.row(1) = -(this->IPntS2_S2(1,1)*this->sHat22_B.transpose() - this->mass2*this->d2*this->sHat23_B.transpose()*this->rTildeS2B_B); this->vectorVDHRB(0) = -(this->IPntS1_S1(0,0) - this->IPntS1_S1(2,2))*this->omegaBN_S1(2)*this->omegaBN_S1(0) - this->k1*this->theta1 - this->c1*this->theta1Dot + this->k2*this->theta2 + this->c2*this->theta2Dot + this->sHat12_B.dot(gravTorquePan1PntH1) + this->l1*this->sHat13_B.dot(gravForcePan2) - this->mass1*this->d1*this->sHat13_B.transpose()*(2*this->omegaTildeBNLoc_B*this->rPrimeS1B_B + this->omegaTildeBNLoc_B*this->omegaTildeBNLoc_B*this->rS1B_B) - this->mass2*this->l1*this->sHat13_B.transpose()*(2*this->omegaTildeBNLoc_B*this->rPrimeS2B_B + this->omegaTildeBNLoc_B*this->omegaTildeBNLoc_B*this->rS2B_B + this->l1*this->theta1Dot*this->theta1Dot*this->sHat11_B + this->d2*(this->theta1Dot + this->theta2Dot)*(this->theta1Dot + this->theta2Dot)*this->sHat21_B); //still missing torque and force terms - SJKC this->vectorVDHRB(1) = -(this->IPntS2_S2(0,0) - this->IPntS2_S2(2,2))*this->omegaBN_S2(2)*this->omegaBN_S2(0) - this->k2*this->theta2 - this->c2*this->theta2Dot + this->sHat22_B.dot(gravTorquePan2PntH2) - this->mass2*this->d2*this->sHat23_B.transpose()*(2*this->omegaTildeBNLoc_B*this->rPrimeS2B_B + this->omegaTildeBNLoc_B*this->omegaTildeBNLoc_B*this->rS2B_B + this->l1*this->theta1Dot*this->theta1Dot*this->sHat11_B); // still missing torque term. - SJKC // - Start defining them good old contributions - start with translation // - For documentation on contributions see Allard, Diaz, Schaub flex/slosh paper backSubContr.matrixA = (this->mass1*this->d1*this->sHat13_B + this->mass2*this->l1*this->sHat13_B + this->mass2*this->d2*this->sHat23_B)*matrixEDHRB.row(0)*this->matrixFDHRB + this->mass2*this->d2*this->sHat23_B*this->matrixEDHRB.row(1)*this->matrixFDHRB; backSubContr.matrixB = (this->mass1*this->d1*this->sHat13_B + this->mass2*this->l1*this->sHat13_B + this->mass2*this->d2*this->sHat23_B)*this->matrixEDHRB.row(0)*(matrixGDHRB) + this->mass2*this->d2*this->sHat23_B*this->matrixEDHRB.row(1)*(matrixGDHRB); backSubContr.vecTrans = -(this->mass1*this->d1*this->theta1Dot*this->theta1Dot*this->sHat11_B + this->mass2*(this->l1*this->theta1Dot*this->theta1Dot*this->sHat11_B + this->d2*(this->theta1Dot+this->theta2Dot)*(this->theta1Dot+this->theta2Dot)*this->sHat21_B) + (this->mass1*this->d1*this->sHat13_B + this->mass2*this->l1*this->sHat13_B + this->mass2*this->d2*this->sHat23_B)*this->matrixEDHRB.row(0)*this->vectorVDHRB + this->mass2*this->d2*this->sHat23_B*this->matrixEDHRB.row(1)*this->vectorVDHRB); // - Define rotational matrice contributions (Eq 96 in paper) backSubContr.matrixC = (this->IPntS1_S1(1,1)*this->sHat12_B + this->mass1*this->d1*this->rTildeS1B_B*this->sHat13_B + this->IPntS2_S2(1,1)*this->sHat22_B + this->mass2*this->l1*this->rTildeS2B_B*this->sHat13_B + this->mass2*this->d2*this->rTildeS2B_B*this->sHat23_B)*this->matrixEDHRB.row(0)*this->matrixFDHRB + (this->IPntS2_S2(1,1)*this->sHat22_B + this->mass2*this->d2*this->rTildeS2B_B*this->sHat23_B)*this->matrixEDHRB.row(1)*this->matrixFDHRB; backSubContr.matrixD = (this->IPntS1_S1(1,1)*this->sHat12_B + this->mass1*this->d1*this->rTildeS1B_B*this->sHat13_B + this->IPntS2_S2(1,1)*this->sHat22_B + this->mass2*this->l1*this->rTildeS2B_B*this->sHat13_B + this->mass2*this->d2*this->rTildeS2B_B*this->sHat23_B)*this->matrixEDHRB.row(0)*this->matrixGDHRB +(this->IPntS2_S2(1,1)*this->sHat22_B + this->mass2*this->d2*this->rTildeS2B_B*this->sHat23_B)*this->matrixEDHRB.row(1)*this->matrixGDHRB; backSubContr.vecRot = -(this->theta1Dot*this->IPntS1_S1(1,1)*this->omegaTildeBNLoc_B*this->sHat12_B + this->mass1*this->omegaTildeBNLoc_B*this->rTildeS1B_B*this->rPrimeS1B_B + this->mass1*this->d1*this->theta1Dot*this->theta1Dot*this->rTildeS1B_B*this->sHat11_B + (this->theta1Dot+this->theta2Dot)*this->IPntS2_S2(1,1)*this->omegaTildeBNLoc_B*this->sHat22_B + this->mass2*this->omegaTildeBNLoc_B*this->rTildeS2B_B*this->rPrimeS2B_B + this->mass2*this->rTildeS2B_B*(this->l1*this->theta1Dot*this->theta1Dot*this->sHat11_B + this->d2*(this->theta1Dot+this->theta2Dot)*(this->theta1Dot+this->theta2Dot)*this->sHat21_B) + (this->IPntS1_S1(1,1)*this->sHat12_B + this->mass1*this->d1*this->rTildeS1B_B*this->sHat13_B + this->IPntS2_S2(1,1)*this->sHat22_B + this->mass2*this->l1*this->rTildeS2B_B*this->sHat13_B + this->mass2*this->d2*this->rTildeS2B_B*this->sHat23_B)*this->matrixEDHRB.row(0)*this->vectorVDHRB + (this->IPntS2_S2(1,1)*this->sHat22_B + this->mass2*this->d2*this->rTildeS2B_B*this->sHat23_B)*this->matrixEDHRB.row(1)*this->vectorVDHRB); return; } void DualHingedRigidBodyStateEffector::computeDerivatives(double integTime, Eigen::Vector3d rDDot_BN_N, Eigen::Vector3d omegaDot_BN_B, Eigen::Vector3d sigma_BN) { // - Define necessarry variables Eigen::MRPd sigmaBNLocal; Eigen::Matrix3d dcmBN; /* direction cosine matrix from N to B */ Eigen::Matrix3d dcmNB; /* direction cosine matrix from B to N */ Eigen::MatrixXd theta1DDot(1,1); /* thetaDDot variable to send to state manager */ Eigen::MatrixXd theta2DDot(1,1); /* thetaDDot variable to send to state manager */ Eigen::Vector3d rDDotBNLoc_N; /* second time derivative of rBN in N frame */ Eigen::Vector3d rDDotBNLoc_B; /* second time derivative of rBN in B frame */ Eigen::Vector3d omegaDotBNLoc_B; /* time derivative of omegaBN in B frame */ // Grab necessarry values from manager (these have been previously computed in hubEffector) rDDotBNLoc_N = this->hubVelocity->getStateDeriv(); sigmaBNLocal = (Eigen::Vector3d )this->hubSigma->getState(); omegaDotBNLoc_B = this->hubOmega->getStateDeriv(); dcmNB = sigmaBNLocal.toRotationMatrix(); dcmBN = dcmNB.transpose(); rDDotBNLoc_B = dcmBN*rDDotBNLoc_N; // - Compute Derivatives // - First is trivial this->theta1State->setDerivative(theta1DotState->getState()); // - Second, a little more involved - see Allard, Diaz, Schaub flex/slosh paper theta1DDot(0,0) = this->matrixEDHRB.row(0).dot(this->matrixFDHRB*rDDotBNLoc_B) + this->matrixEDHRB.row(0)*this->matrixGDHRB*omegaDotBNLoc_B + this->matrixEDHRB.row(0)*this->vectorVDHRB; this->theta1DotState->setDerivative(theta1DDot); this->theta2State->setDerivative(theta2DotState->getState()); theta2DDot(0,0) = this->matrixEDHRB.row(1)*(this->matrixFDHRB*rDDotBNLoc_B) + this->matrixEDHRB.row(1).dot(this->matrixGDHRB*omegaDotBNLoc_B) + this->matrixEDHRB.row(1)*this->vectorVDHRB; this->theta2DotState->setDerivative(theta2DDot); return; } /*! This method is for calculating the contributions of the DHRB state effector to the energy and momentum of the s/c */ void DualHingedRigidBodyStateEffector::updateEnergyMomContributions(double integTime, Eigen::Vector3d & rotAngMomPntCContr_B, double & rotEnergyContr, Eigen::Vector3d omega_BN_B) { // - Get the current omega state Eigen::Vector3d omegaLocal_BN_B; omegaLocal_BN_B = hubOmega->getState(); // - Find rotational angular momentum contribution from hub Eigen::Vector3d omega_S1B_B; Eigen::Vector3d omega_S2B_B; Eigen::Vector3d omega_S1N_B; Eigen::Vector3d omega_S2N_B; Eigen::Matrix3d IPntS1_B; Eigen::Matrix3d IPntS2_B; Eigen::Vector3d rDot_S1B_B; Eigen::Vector3d rDot_S2B_B; omega_S1B_B = this->theta1Dot*this->sHat12_B; omega_S2B_B = (this->theta1Dot + this->theta2Dot)*this->sHat22_B; omega_S1N_B = omega_S1B_B + omegaLocal_BN_B; omega_S2N_B = omega_S2B_B + omegaLocal_BN_B; IPntS1_B = this->dcmS1B.transpose()*this->IPntS1_S1*this->dcmS1B; IPntS2_B = this->dcmS2B.transpose()*this->IPntS2_S2*this->dcmS2B; rDot_S1B_B = this->rPrimeS1B_B + omegaLocal_BN_B.cross(this->rS1B_B); rDot_S2B_B = this->rPrimeS2B_B + omegaLocal_BN_B.cross(this->rS2B_B); rotAngMomPntCContr_B = IPntS1_B*omega_S1N_B + this->mass1*this->rS1B_B.cross(rDot_S1B_B) + IPntS2_B*omega_S2N_B + this->mass2*this->rS2B_B.cross(rDot_S2B_B); // - Find rotational energy contribution from the hub double rotEnergyContrS1; double rotEnergyContrS2; rotEnergyContrS1 = 0.5*omega_S1N_B.dot(IPntS1_B*omega_S1N_B) + 0.5*this->mass1*rDot_S1B_B.dot(rDot_S1B_B) + 0.5*this->k1*this->theta1*this->theta1; rotEnergyContrS2 = 0.5*omega_S2N_B.dot(IPntS2_B*omega_S2N_B) + 0.5*this->mass2*rDot_S2B_B.dot(rDot_S2B_B) + 0.5*this->k2*this->theta2*this->theta2; rotEnergyContr = rotEnergyContrS1 + rotEnergyContrS2; return; }
18,897
8,301
/* * ================================================= * Copyright © 2021 * Aleksandr Dremov * * This code has been written by Aleksandr Dremov * Check license agreement of this project to evade * possible illegal use. * ================================================= */ #include "Lexer/LexerGenerator.h" #include "Lexer/StructureUnits.h" #include <string> #include <regex> #include <vector> namespace SxTree::Lexer::Generator { using std::string; using std::vector; using LexerStruct::Expression; using LexerStruct::Value; static const string contents = #include "templates/lexerStructTemplate.h.template" static const string contentsHeader = #include "templates/lexerStructTemplateHeader.h.template" static string valTypeString(Value::ValueType type) { switch (type) { case Value::VAL_EXPRESSION: return "Value::VAL_EXPRESSION"; case Value::VAL_REGEXP: return "Value::VAL_REGEXP"; case Value::VAL_SKIP: return "Value::VAL_SKIP"; } } static string exprTypeString(Expression::ExprType type) { switch (type) { case Expression::EXP_ONE: return "Expression::EXP_ONE"; case Expression::EXP_ANY: return "Expression::EXP_ANY"; case Expression::EXP_OPTIONAL: return "Expression::EXP_OPTIONAL"; } } static string generateExpression(const Expression &exp) { string output = "{{"; for (const auto &val: exp.possible) { output += "{ R\"(" + val.regexString + ")\", " + valTypeString(val.type) + "," + generateExpression(val.expr) + "},"; } output += "}, " + exprTypeString(exp.type) + "}"; return output; } static string generateLexemesToStringBody(const SxTree::LexerStruct::LexerStruct &structure) { string output; for (auto &lex: structure.getLexemesMap()) output += "\t\tcase SxTree::Lexer::LexemeType::lex_" + lex.first + ": return \"" + lex.first + "\";\n"; return output; } static string generateLexerStruct(const SxTree::LexerStruct::LexerStruct &structure) { string output = "{\n"; for (const auto &rule: structure.getRules()) output += "\t{" + std::to_string(rule.id + 1) + ", " + generateExpression(rule.expression) + "},\n"; output += "}"; return output; } static string generateIdsEnum(const SxTree::LexerStruct::LexerStruct &structure) { string output = "{\n"; const auto &ruleIdsNo = structure.getLexemesMap(); vector<const string *> orderedIds(ruleIdsNo.size() + 1, nullptr); string none = "NONE"; orderedIds[0] = &none; for (const auto &id: ruleIdsNo) orderedIds[id.second + 1] = &id.first; for (unsigned i = 0; i < orderedIds.size(); i++) output += "\tlex_" + *(orderedIds[i]) + " = " + std::to_string(i) + ",\n"; output += "}"; return output; } string getCompleteLexerStruct(const SxTree::LexerStruct::LexerStruct &structure, const string& headerName) { string newContent = contents; newContent = replaceFirstOccurrence(newContent, "HEADERNAME", headerName); newContent = replaceFirstOccurrence(newContent, "INSERT", generateLexerStruct(structure)); newContent = replaceFirstOccurrence(newContent, "SWITCHBODY", generateLexemesToStringBody(structure)); newContent = replaceFirstOccurrence(newContent, "LEXNUM", std::to_string(structure.getLexemesMap().size())); return newContent; } string getHeader(const SxTree::LexerStruct::LexerStruct &structure) { string newContent = contentsHeader; newContent = replaceFirstOccurrence(newContent, "ENUM", generateIdsEnum(structure)); return newContent; } std::string replaceFirstOccurrence( std::string &s, const std::string &toReplace, const std::string &replaceWith) { std::size_t pos = s.find(toReplace); if (pos == std::string::npos) return s; return s.replace(pos, toReplace.length(), replaceWith); } }
4,262
1,252
// Solution 01 using namespace std; class BinaryTree { public: int value; BinaryTree *left; BinaryTree *right; BinaryTree(int value) { this->value = value; left = NULL; right = NULL; } }; int nodeDepths(BinaryTree *node, int depth = 0); // Average case: when the tree is balanced // O(nlog(n)) time | O(h) space - where n is the number of nodes in // the Binary Tree and h is the height of the Binary Tree int allKindsOfNodeDepths(BinaryTree *root) { int sumOfAllDepths = 0; vector<BinaryTree *> stack = {root}; while (stack.size() > 0) { BinaryTree *node = stack.back(); stack.pop_back(); if (node == NULL) continue; sumOfAllDepths += nodeDepths(node); stack.push_back(node->left); stack.push_back(node->right); } return sumOfAllDepths; } int nodeDepths(BinaryTree *node, int depth) { if (node == NULL) return 0; return depth + nodeDepths(node->left, depth + 1) + nodeDepths(node->right, depth + 1); }
1,122
383
/* * @Author: py.wang * @Date: 2019-05-04 09:08:42 * @Last Modified by: py.wang * @Last Modified time: 2019-06-06 18:26:02 */ #include "src/base/Exception.h" #include "src/base/CurrentThread.h" #include <iostream> #include <cxxabi.h> #include <execinfo.h> #include <stdlib.h> #include <stdio.h> namespace slack { Exception::Exception(string msg) : message_(std::move(msg)), stack_(CurrentThread::stackTrace(false)) { } } // namespace slack
462
201
/* * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali/public-api/signals/signal-slot-connections.h> // EXTERNAL INCLUDES #include <cstddef> // INTERNAL INCLUDES #include <dali/public-api/signals/callback.h> namespace Dali { SlotConnection::SlotConnection( SlotObserver* slotObserver, CallbackBase* callback ) : mSlotObserver( slotObserver ), mCallback( callback ) { } SlotConnection::~SlotConnection() { } CallbackBase* SlotConnection::GetCallback() { return mCallback; } SlotObserver* SlotConnection::GetSlotObserver() { return mSlotObserver; } SignalConnection::SignalConnection( CallbackBase* callback ) : mSignalObserver( NULL ), mCallback( callback ) { } SignalConnection::SignalConnection( SignalObserver* signalObserver, CallbackBase* callback ) : mSignalObserver( signalObserver ), mCallback( callback ) { } SignalConnection::~SignalConnection() { // signal connections have ownership of the callback. delete mCallback; } void SignalConnection::Disconnect( SlotObserver* slotObserver ) { if( mSignalObserver ) { // tell the slot the signal wants to disconnect mSignalObserver->SignalDisconnected( slotObserver, mCallback ); mSignalObserver = NULL; } // we own the callback, SignalObserver is expected to delete the SlotConnection on Disconnected so its pointer to our mCallback is no longer used delete mCallback; mCallback = NULL; } CallbackBase* SignalConnection::GetCallback() { return mCallback; } } // namespace Dali
2,078
642
#include <bits/stdc++.h> #define x first #define y second #define pb push_back #define all(v) v.begin(),v.end() #pragma gcc optimize("O3") #pragma gcc optimize("Ofast") #pragma gcc optimize("unroll-loops") using namespace std; const int INF = 1e9; const int TMX = 1 << 18; const long long llINF = 2e18; const long long mod = 1e18; const long long hashmod = 100003; typedef long long ll; typedef long double ld; typedef pair <int,int> pi; typedef pair <ll,ll> pl; typedef vector <int> vec; typedef vector <pi> vecpi; typedef long long ll; int n,m,p[1000005],hole[1000005]; int ans,a[1005][1005]; vec q[1005]; vecpi op[1005]; int f(int x,int y) {return (x-1)*m+y;} int Find(int x) {return (x^p[x] ? p[x] = Find(p[x]) : x);} int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> m; for(int i = 1;i <= n;i++) { for(int j = 1;j <= m;j++) { cin >> a[i][j]; p[f(i,j)] = f(i,j); if(a[i][j] > 0) q[a[i][j]].pb(f(i,j)); } } for(int i = 1;i <= n;i++) { for(int j = 1;j <= m;j++) { if(i < n) op[max(abs(a[i][j]),abs(a[i+1][j]))].pb({f(i,j),f(i+1,j)}); if(j < m) op[max(abs(a[i][j]),abs(a[i][j+1]))].pb({f(i,j),f(i,j+1)}); } } for(int i = 1;i <= 1000;i++) { for(pi j : op[i]) { if(Find(j.x) == Find(j.y)) continue; hole[p[j.x]] |= hole[p[j.y]]; p[p[j.y]] = p[j.x]; } for(int j : q[i]) { if(!hole[Find(j)]) ans++, hole[p[j]] = 1; } } cout << ans; }
1,406
767
#ifndef COMPILE_TIME_SHA1_H #define COMPILE_TIME_SHA1_H #include "crypto_hash.hpp" #define MASK 0xffffffff #define SHA1_HASH_SIZE 5 template<typename H=const char *> class SHA1 : public CryptoHash<SHA1_HASH_SIZE> { private: constexpr static uint32_t scheduled(CircularQueue<uint32_t,16> queue) { return leftrotate(queue[13]^queue[8]^queue[2]^queue[0],1); } constexpr static uint32_t k[4] = { 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 }; struct hash_parameters { const Array<uint32_t,SHA1_HASH_SIZE> arr; const uint32_t f_array[4][5]; template <typename ... Args> constexpr hash_parameters(Args ... args): arr{args...}, f_array{ {arr[2],arr[3],arr[1],arr[3],MASK}, {arr[2],arr[1],MASK,arr[3],MASK}, {arr[2],arr[1],arr[3],arr[1],arr[2]}, {arr[2],arr[1],MASK,arr[3],MASK} } {} constexpr hash_parameters() : hash_parameters((uint32_t) 0x67452301, (uint32_t) 0xefcdab89, (uint32_t) 0x98badcfe, (uint32_t) 0x10325476, (uint32_t) 0xC3D2E1F0) {} constexpr uint32_t operator [](int index) { return arr[index]; } }; using Hash_T = SHA1<H>; using PaddedValue_T = PaddedValue<H>; using Section_T = Section<H>; constexpr Array<uint32_t,SHA1_HASH_SIZE> create_hash(PaddedValue_T value, hash_parameters h, int block_index=0) { return block_index*64 == value.total_size ? h.arr : create_hash( value, hash_block(Section_T(value,block_index*16,scheduled),h,h,block_index*16), block_index+1); } // (a ^ b) & c ^ (d & e) constexpr uint32_t f(int i, struct hash_parameters h) const { return (h.f_array[i][0] ^ h.f_array[i][1]) & h.f_array[i][2] ^ (h.f_array[i][3] & h.f_array[i][4]); } constexpr uint32_t get_updated_h0(Section_T section, int i, struct hash_parameters h) const { return leftrotate(h[0],5) + f(i/20,h) + h[4] + k[i/20] + section[i % 16]; } constexpr hash_parameters hash_section(Section_T section, hash_parameters h, int start, int i=0) const { return i == 16 ? h : hash_section( section, { get_updated_h0(section,start+i,h), h[0], leftrotate(h[1],30), h[2], h[3] }, start, i+1); } constexpr hash_parameters hash_block(Section_T section, hash_parameters h , hash_parameters prev_h, int start_index, int i=0) const { return i == 80 ? (hash_parameters) { prev_h[0]+h[0], prev_h[1]+h[1], prev_h[2]+h[2], prev_h[3]+h[3], prev_h[4]+h[4] } : hash_block( Section_T(section,start_index+i+16,scheduled), hash_section(section,h,i), prev_h, start_index, i+16); } public: constexpr SHA1(H input) : CryptoHash<SHA1_HASH_SIZE>(create_hash(PaddedValue_T(input,true),{})) {} }; typedef SHA1<> SHA1String; template<typename T> constexpr uint32_t SHA1<T>::k[4]; #endif
3,177
1,278
#include <stdio.h> extern int bar(); int main() { printf("%d\n", bar()); }
80
33
#include <iostream> #include "Car.h" #include "Engine.h" #include "Driver.h" using namespace std; Car::Car(string name, float chassisMass, Engine* engine, float* min_mass): name(name), chassisMass(chassisMass), engine(engine), min_mass(min_mass) {} float Car::getRacingMass() { if (!driver) { cout << name << " does not have a driver!" << endl; return -1; } float racing_mass = chassisMass + engine->mass + driver->mass; return racing_mass > *min_mass ? racing_mass : *min_mass; } float Car::benchmark(float distance) { return engine->benchmark(distance, getRacingMass()); } void Car::setDriver(Driver* d) { driver = d; }
685
235
/*****************************************************************************\ ljzjs.cpp : Implementation for the LJZjs class Copyright (c) 1996 - 2007, HP Co. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of HP nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PATENT INFRINGEMENT; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \*****************************************************************************/ #if defined (APDK_LJZJS_MONO) || defined (APDK_LJZJS_COLOR) || defined (APDK_LJM1005) #include "header.h" #include "io_defs.h" #include "printerproxy.h" #include "resources.h" #include "ljzjs.h" #ifdef HAVE_LIBDL #include <dlfcn.h> #endif extern "C" { int (*HPLJJBGCompress) (int iWidth, int iHeight, unsigned char **pBuff, HPLJZjcBuff *pOutBuff, HPLJZjsJbgEncSt *pJbgEncSt); int (*HPLJSoInit) (int iFlag); } APDK_BEGIN_NAMESPACE #ifdef HAVE_LIBDL extern void *LoadPlugin (const char *szPluginName); #endif const unsigned char LJZjs::szByte1[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, }; const unsigned char LJZjs::szByte2[256] = { 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170, }; LJZjs::LJZjs (SystemServices* pSS, int numfonts, BOOL proto) : Printer(pSS, numfonts, proto) { CMYMap = NULL; #ifdef APDK_AUTODUPLEX m_bRotateBackPage = FALSE; // Lasers don't require back side image to be rotated #endif m_pszInputRasterData = NULL; m_dwCurrentRaster = 0; m_bStartPageSent = FALSE; HPLJJBGCompress = NULL; m_hHPLibHandle = NULL; m_iPrinterType = UNSUPPORTED; #ifdef HAVE_LIBDL m_hHPLibHandle = LoadPlugin ("lj.so"); if (m_hHPLibHandle) { dlerror (); *(void **) (&HPLJJBGCompress) = dlsym (m_hHPLibHandle, "hp_encode_bits_to_jbig"); *(void **) (&HPLJSoInit) = dlsym (m_hHPLibHandle, "hp_init_lib"); if (!HPLJSoInit || (HPLJSoInit && !HPLJSoInit (1))) { constructor_error = PLUGIN_LIBRARY_MISSING; } } #endif if (HPLJJBGCompress == NULL) { constructor_error = PLUGIN_LIBRARY_MISSING; } //Issue: LJZJSMono class printers not printing in RHEL //Cause: Since start page is common for LJZJSMono and LJZJSColor class, the items of //LJZJSColor-2 format was used for LJZJSMono due to below variable not initialised //Fix: Added initialisation so that correct LJZJSMono items are used. //Variable is updated in LJZJSColor. m_bLJZjsColor2Printer = FALSE; } LJZjs::~LJZjs () { #ifdef HAVE_LIBDL if (m_hHPLibHandle) { dlclose (m_hHPLibHandle); } #endif if (m_pszInputRasterData) { delete [] m_pszInputRasterData; } } HeaderLJZjs::HeaderLJZjs (Printer* p,PrintContext* pc) : Header(p,pc) { } DRIVER_ERROR HeaderLJZjs::Send () { DRIVER_ERROR err = NO_ERROR; char szStr[256]; WORD wItems[3] = {ZJI_DMCOLLATE, ZJI_PAGECOUNT, ZJI_DMDUPLEX}; int i = 4; QUALITY_MODE eQuality; MEDIATYPE cmt; BOOL cdt; COLORMODE ccm; thePrintContext->GetPrintModeSettings (eQuality, cmt, ccm, cdt); if (((LJZjs *) thePrinter)->m_iPrinterType == eLJM1005) { strcpy (szStr, "\x1B\x25-12345X@PJL JOB\x0D\x0A"); strcpy (szStr+strlen (szStr), "@PJL SET JAMRECOVERY=OFF\x0D\x0A"); strcpy (szStr+strlen (szStr), "@PJL SET DENSITY=3\x0D\x0A"); strcpy (szStr+strlen (szStr), "@PJL SET RET=MEDIUM\x0D\x0A"); strcpy (szStr+strlen (szStr), "@PJL SET ECONOMODE="); if (eQuality == QUALITY_DRAFT) { strcpy (szStr+strlen (szStr), "ON\x0D\x0A"); } else { strcpy (szStr+strlen (szStr), "OFF\x0D\x0A"); } err = thePrinter->Send ((const BYTE *) szStr, strlen (szStr)); ERRCHECK; strcpy (szStr, "\x1B\x25-12345X,XQX"); err = thePrinter->Send ((const BYTE *) szStr, strlen (szStr)); memset (szStr, 0x0, 92); szStr[3] = 0x01; szStr[7] = 0x07; i = 8; i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x80000000, 0x04, 0x54); i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x10000005, 0x04, 0x01); i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x10000001, 0x04, 0x00); i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x10000002, 0x04, 0x00); i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x10000000, 0x04, 0x00); i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x10000003, 0x04, 0x01); i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x80000001, 0x04, 0xDEADBEEF); err = thePrinter->Send ((const BYTE *) szStr, i); return err; } strcpy (szStr, "\x1B\x25-12345X@PJL ENTER LANGUAGE=ZJS\x0A"); err = thePrinter->Send ((const BYTE *) szStr, strlen (szStr)); ERRCHECK; memset (szStr, 0, 256); strcpy (szStr, "JZJZ"); i = 0; szStr[i+7] = 52; szStr[i+11] = ZJT_START_DOC; szStr[i+15] = 3; szStr[i+17] = 36; szStr[i+18] = 'Z'; szStr[i+19] = 'Z'; i += 20; for (int j = 0; j < 3; j++) { szStr[i+3] = 12; szStr[i+5] = (char) wItems[j]; szStr[i+6] = ZJIT_UINT32; szStr[i+11] = j / 2; i += 12; } err = thePrinter->Send ((const BYTE *) szStr, i); return err; } int LJZjs::MapPaperSize () { switch (thePrintContext->GetPaperSize ()) { case LETTER: return 1; case LEGAL: return 5; case A4: return 9; case B4: return 12; case B5: return 357; case OUFUKU: return 43; case HAGAKI: return 43; #ifdef APDK_EXTENDED_MEDIASIZE case A3: return 8; case A5: return 11; // case LEDGER: return 4; case EXECUTIVE: return 7; // case CUSTOM_SIZE: return 96; case ENVELOPE_NO_10: return 20; case ENVELOPE_DL: return 27; case FLSA: return 258; #endif default: return 1; } } DRIVER_ERROR LJZjs::StartPage (DWORD dwWidth, DWORD dwHeight) { DRIVER_ERROR err = NO_ERROR; QUALITY_MODE cqm; MEDIATYPE cmt; BOOL cdt; DWORD dwNumItems = (m_bIamColor) ? 15 : 14; BYTE szStr[16 + 15 * 12]; int iPlanes = 1; int i; int iMediaType = 1; // Plain paper if (m_bStartPageSent) { return NO_ERROR; } m_bStartPageSent = TRUE; err = thePrintContext->GetPrintModeSettings (cqm, cmt, m_cmColorMode, cdt); if (cmt == MEDIA_TRANSPARENCY) { iMediaType = 2; } else if (cmt == MEDIA_PHOTO) { iMediaType = 3; } if (m_iPrinterType == eLJM1005) { int iOutputResolution = GetOutputResolutionY (); if (cqm == QUALITY_BEST) iOutputResolution = (int) thePrintContext->EffectiveResolutionY (); memset (szStr, 0x0, sizeof (szStr)); szStr[3] = 0x03; szStr[7] = 0x0F; err = Send ((const BYTE *) szStr, 8); i = 0; i += SendIntItem (szStr+i, 0x80000000, 0x04, 0xB4); i += SendIntItem (szStr+i, 0x20000005, 0x04, 0x01); i += SendIntItem (szStr+i, 0x20000006, 0x04, 0x07); i += SendIntItem (szStr+i, 0x20000000, 0x04, 0x01); i += SendIntItem (szStr+i, 0x20000007, 0x04, 0x01); i += SendIntItem (szStr+i, 0x20000008, 0x04, (int) thePrintContext->EffectiveResolutionX ()); i += SendIntItem (szStr+i, 0x20000009, 0x04, iOutputResolution); i += SendIntItem (szStr+i, 0x2000000D, 0x04, (int) dwWidth); i += SendIntItem (szStr+i, 0x2000000E, 0x04, (int) m_dwLastRaster); i += SendIntItem (szStr+i, 0x2000000A, 0x04, m_iBPP); i += SendIntItem (szStr+i, 0x2000000F, 0x04, (int) dwWidth/m_iBPP); i += SendIntItem (szStr+i, 0x20000010, 0x04, (int) m_dwLastRaster); i += SendIntItem (szStr+i, 0x20000011, 0x04, 0x01); i += SendIntItem (szStr+i, 0x20000001, 0x04, MapPaperSize ()); i += SendIntItem (szStr+i, 0x80000001, 0x04, 0xDEADBEEF); err = Send ((const BYTE *) szStr, i); return err; } if(m_bLJZjsColor2Printer) { dwNumItems = 13; } if (m_cmColorMode == COLOR && m_bIamColor) { iPlanes = 4; } i = 0; i += SendChunkHeader (szStr, 16 + dwNumItems * 12, ZJT_START_PAGE, dwNumItems); if (m_bIamColor) { i += SendItem (szStr+i, ZJIT_UINT32, ZJI_PLANE, iPlanes); } i += SendItem (szStr+i, ZJIT_UINT32, ZJI_DMPAPER, MapPaperSize ()); i += SendItem (szStr+i, ZJIT_UINT32, ZJI_DMCOPIES, thePrintContext->GetCopyCount ()); i += SendItem (szStr+i, ZJIT_UINT32, ZJI_DMDEFAULTSOURCE, thePrintContext->GetMediaSource ()); i += SendItem (szStr+i, ZJIT_UINT32, ZJI_DMMEDIATYPE, iMediaType); i += SendItem (szStr+i, ZJIT_UINT32, ZJI_NBIE, iPlanes); i += SendItem (szStr+i, ZJIT_UINT32, ZJI_RESOLUTION_X, thePrintContext->EffectiveResolutionX ()); i += SendItem (szStr+i, ZJIT_UINT32, ZJI_RESOLUTION_Y, thePrintContext->EffectiveResolutionY ()); i += SendItem (szStr+i, ZJIT_UINT32, ZJI_RASTER_X, dwWidth); i += SendItem (szStr+i, ZJIT_UINT32, ZJI_RASTER_Y, m_dwLastRaster); i += SendItem (szStr+i, ZJIT_UINT32, ZJI_VIDEO_BPP, m_iBPP); i += SendItem (szStr+i, ZJIT_UINT32, ZJI_VIDEO_X, dwWidth/m_iBPP); i += SendItem (szStr+i, ZJIT_UINT32, ZJI_VIDEO_Y, m_dwLastRaster); if(!m_bLJZjsColor2Printer) { i += SendItem (szStr+i, ZJIT_UINT32, ZJI_RET, RET_ON); i += SendItem (szStr+i, ZJIT_UINT32, ZJI_TONER_SAVE, (cqm == QUALITY_DRAFT) ? 1 : 0); } err = Send ((const BYTE *) szStr, i); return err; } int LJZjs::SendChunkHeader (BYTE *szStr, DWORD dwSize, DWORD dwChunkType, DWORD dwNumItems) { for (int j = 3, i = 0; j >= 0; j--) { szStr[i] = (BYTE) ((dwSize >> (8 * (j))) & 0xFF); szStr[4+i] = (BYTE) ((dwChunkType >> (8 * (j))) & 0xFF); szStr[8+i] = (BYTE) ((dwNumItems >> (8 * (j))) & 0xFF); i++; } szStr[12] = (BYTE) (((dwNumItems * 12) & 0xFF00) >> 8); szStr[13] = (BYTE) (((dwNumItems * 12) & 0x00FF)); szStr[14] = 'Z'; szStr[15] = 'Z'; return 16; } int LJZjs::SendItem (BYTE *szStr, BYTE cType, WORD wItem, DWORD dwValue, DWORD dwExtra) { int i, j; dwExtra += 12; for (j = 3, i = 0; j >= 0; j--) { szStr[i++] = (BYTE) ((dwExtra >> (8 * (j))) & 0xFF); } szStr[i++] = (BYTE) ((wItem & 0xFF00) >> 8); szStr[i++] = (BYTE) ((wItem & 0x00FF)); szStr[i++] = (BYTE) cType; szStr[i++] = 0; for (j = 3; j >= 0; j--) { szStr[i++] = (BYTE) ((dwValue >> (8 * (j))) & 0xFF); } return i; } int LJZjs::SendIntItem (BYTE *szStr, int iItem, int iItemType, int iItemValue) { int i = 0; int j; for (j = 3; j >= 0; j--) { szStr[i++] = (BYTE) ((iItem >> (8 * (j))) & 0xFF); } for (j = 3; j >= 0; j--) { szStr[i++] = (BYTE) ((iItemType >> (8 * (j))) & 0xFF); } for (j = 3; j >= 0; j--) { szStr[i++] = (BYTE) ((iItemValue >> (8 * (j))) & 0xFF); } return i; } DRIVER_ERROR LJZjs::SkipRasters (int iBlankRasters) { DRIVER_ERROR err = NO_ERROR; BOOL bLastPlane; int iPlanes = (m_cmColorMode == COLOR) ? 4 : 1; for (int i = 1; i <= iPlanes; i++) { bLastPlane = (i == iPlanes) ? TRUE : FALSE; for (int j = 0; j < iBlankRasters; j++) { err = this->Encapsulate (NULL, bLastPlane); } } return err; } DRIVER_ERROR HeaderLJZjs::FormFeed () { DRIVER_ERROR err = NO_ERROR; err = thePrinter->Flush (0); return err; } DRIVER_ERROR HeaderLJZjs::SendCAPy (unsigned int iAbsY) { return NO_ERROR; } DRIVER_ERROR LJZjs::Flush (int FlushSize) { DRIVER_ERROR err = NO_ERROR; if (m_dwCurrentRaster == 0) { return NO_ERROR; } err = SkipRasters ((m_dwLastRaster - m_dwCurrentRaster)); return err; } DRIVER_ERROR LJZjs::JbigCompress () { DRIVER_ERROR err = NO_ERROR; HPLJZjcBuff myBuffer; int iPlanes = (m_cmColorMode == COLOR) ? 4 : 1; int iIncr = (m_bIamColor) ? 100 : m_dwLastRaster; HPLJZjsJbgEncSt se; BYTE *bitmaps[4] = { m_pszInputRasterData, m_pszInputRasterData + (m_dwWidth * m_iBPP * m_dwLastRaster), m_pszInputRasterData + (m_dwWidth * m_iBPP * m_dwLastRaster * 2), m_pszInputRasterData + (m_dwWidth * m_iBPP * m_dwLastRaster * 3) }; myBuffer.pszCompressedData = new BYTE[m_dwWidth * m_dwLastRaster * m_iBPP]; myBuffer.dwTotalSize = 0; BYTE *p; int iHeight; for (DWORD y = 0; y < m_dwLastRaster; y += iIncr) { for (int i = 0; i < iPlanes; i++) { memset (myBuffer.pszCompressedData, 0, m_dwWidth * m_dwLastRaster * m_iBPP); myBuffer.dwTotalSize = 0; p = bitmaps[i] + (y * m_dwWidth * m_iBPP); iHeight = iIncr; if (y + iIncr > m_dwLastRaster) { iHeight = m_dwLastRaster - y; } HPLJJBGCompress (m_dwWidth * 8 * m_iBPP, iHeight, &p, &myBuffer, &se); if (i == 0) { StartPage (se.xd, se.yd); } err = this->SendPlaneData (i + 1, &se, &myBuffer, (y + iIncr) >= m_dwLastRaster); } } delete [] myBuffer.pszCompressedData; m_dwCurrentRaster = 0; m_pszCurPtr = m_pszInputRasterData; memset (m_pszCurPtr, 0, (m_dwWidth * m_dwLastRaster * iPlanes * m_iBPP)); err = EndPage (); return err; } /*JBig Compress for LJZjsColor-2 Printers Separate function written for LJZjsColor-2 Printers, since for them, compression is done for whole plane data at a time whereas for other deiveces, compression is done for 100 lines of each plane*/ DRIVER_ERROR LJZjs::JbigCompress_LJZjsColor2 () { DRIVER_ERROR err = NO_ERROR; HPLJZjcBuff myBuffer; int iPlanes = (m_cmColorMode == COLOR) ? 4 : 1; int arrPlanesOrder[] = {3,2,1,4}; int nByteCount = 0; int iHeight = 0; HPLJZjsJbgEncSt se; BYTE *pbUnCompressedData = NULL; BYTE *bitmaps[4] = { m_pszInputRasterData, m_pszInputRasterData + (m_dwWidth * m_iBPP * m_dwLastRaster), m_pszInputRasterData + (m_dwWidth * m_iBPP * m_dwLastRaster * 2), m_pszInputRasterData + (m_dwWidth * m_iBPP * m_dwLastRaster * 3) }; myBuffer.pszCompressedData = new BYTE[m_dwWidth * m_dwLastRaster * m_iBPP]; if(NULL == myBuffer.pszCompressedData) { return ALLOCMEM_ERROR; } myBuffer.dwTotalSize = 0; for (int nPlaneCount = 0; nPlaneCount < iPlanes; nPlaneCount++) { memset (myBuffer.pszCompressedData, 0, m_dwWidth * m_dwLastRaster * m_iBPP); myBuffer.dwTotalSize = 0; if(4 == iPlanes)/*If there are 4 planes follow LJZjsColor-2 order of 3 2 1 4*/ { pbUnCompressedData = bitmaps[arrPlanesOrder[nPlaneCount]-1] ; } else /* Should not happen */ { return SYSTEM_ERROR; } iHeight = m_dwLastRaster; /*Send all scan lines at one go*/ HPLJJBGCompress (m_dwWidth * 8 * m_iBPP, iHeight, &pbUnCompressedData, &myBuffer, &se); if(0 == nPlaneCount) { StartPage (se.xd, se.yd); } err = this->SendPlaneData (arrPlanesOrder[nPlaneCount], &se, &myBuffer, FALSE); } delete [] myBuffer.pszCompressedData; m_dwCurrentRaster = 0; m_pszCurPtr = m_pszInputRasterData; memset (m_pszCurPtr, 0, (m_dwWidth * m_dwLastRaster * iPlanes * m_iBPP)); err = EndPage (); return err; } DRIVER_ERROR HeaderLJZjs::EndJob () { DRIVER_ERROR err = NO_ERROR; char szStr[64]; if (((LJZjs *) thePrinter)->m_iPrinterType == eLJM1005) { memset (szStr, 0, 8); szStr[3] = 2; strcpy ((char *) szStr+8, "\x1B\x25-12345X@PJL EOJ\x0D\x0A\x1B\x25-12345X"); err = thePrinter->Send ((const BYTE *) szStr, 8 + strlen ((char *) (szStr+8))); return err; } memset (szStr, 0, 64); szStr[3] = 16; szStr[7] = ZJT_END_DOC; szStr[14] = 'Z'; szStr[15] = 'Z'; err = thePrinter->Send ((const BYTE *) szStr, 16); return err; } Header *LJZjs::SelectHeader (PrintContext* pc) { DRIVER_ERROR err = NO_ERROR; DWORD dwSize; int iPlanes = 1; QUALITY_MODE cqm; MEDIATYPE cmt; BOOL cdt; err = pc->GetPrintModeSettings (cqm, cmt, m_cmColorMode, cdt); if (m_cmColorMode == COLOR && m_bIamColor) { iPlanes = 4; m_iP[0] = 3; } m_dwWidth = pc->OutputPixelsPerRow () / 8; if (m_dwWidth % 8) { m_dwWidth = (m_dwWidth / 8 + 1) * 8; } m_dwLastRaster = (int) (pc->PrintableHeight () * pc->EffectiveResolutionY () + 0.5); dwSize = m_dwWidth * m_dwLastRaster * iPlanes * m_iBPP; m_pszInputRasterData = new BYTE[dwSize]; if (m_pszInputRasterData == NULL) { return NULL; } m_pszCurPtr = m_pszInputRasterData; memset (m_pszCurPtr, 0, dwSize); thePrintContext = pc; return new HeaderLJZjs (this,pc); } DRIVER_ERROR LJZjs::VerifyPenInfo() { ePen = BOTH_PENS; return NO_ERROR; } DRIVER_ERROR LJZjs::ParsePenInfo (PEN_TYPE& ePen, BOOL QueryPrinter) { ePen = BOTH_PENS; return NO_ERROR; } APDK_END_NAMESPACE #endif // defined APDK_LJZJS_MONO || defined APDK_LJZJS_COLOR || defined APDK_LJM1005
21,929
10,568
#include "imgui_utils/imgui_runner/runner_glfw.h" #include "example_gui.h" int main() { ImGui::ImGuiRunner::RunnerGlfw runner; runner.ShowGui = ExampleGui; runner.Run(); }
178
71
#include "afx.h" using namespace std; class Solution { public: bool validUtf8(vector<int> &data) { /* state: 0: end of byte sequence; >0: in byte sequence, state = bytes remaining */ int state = 0; int result = true; for (auto &i : data) { if (state == 0) { if ((i & 0xF8) == 0xF0) { state = 3; } else if ((i & 0xF0) == 0xE0) { state = 2; } else if ((i & 0xE0) == 0xC0) { state = 1; } else if ((i & 0x80) == 0) { state = 0; } else { result = false; break; } } else if ((i & 0xC0) == 0x80) { state--; } else { result = false; break; } } if (state > 0) { result = false; } return result; } }; int main() { Solution s; vector<int> data = {197, 130, 1}; s.validUtf8(data); return 0; }
1,352
407
#include <iostream> #include "PhoneCall.h" int main() { PhoneCall p; p.setLength(50); p.getPrice(); p.setNumber(9002121004); std::cout << p.getPrice() << "\n"; std::cout << p.getNumber() << "\n"; return 0; }
216
102
/** @addtogroup fir * @{ */ /** * KFR (http://kfrlib.com) * Copyright (C) 2016 D Levin * See LICENSE.txt for details */ #pragma once #include "../cident.h" namespace kfr { inline namespace CMT_ARCH_NAME { namespace internal { template <typename T, bool stateless> struct state_holder { state_holder() = delete; state_holder(const state_holder&) = default; state_holder(state_holder&&) = default; constexpr state_holder(const T& state) CMT_NOEXCEPT : s(state) {} T s; }; template <typename T> struct state_holder<T, true> { state_holder() = delete; state_holder(const state_holder&) = default; state_holder(state_holder&&) = default; constexpr state_holder(const T& state) CMT_NOEXCEPT : s(state) {} const T& s; }; } // namespace internal } // namespace CMT_ARCH_NAME } // namespace kfr
886
309
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "CRandomAccessFile.h" #include "CFile.h" #include "IoUtils.h" #include "NioUtils.h" #include "Math.h" #include "Character.h" #include "StringBuilder.h" #include "OsConstants.h" #include "IoBridge.h" #include "CLibcore.h" #include "CFileDescriptor.h" #include "CModifiedUtf8.h" #include "AutoLock.h" #include "Memory.h" #include "CCloseGuard.h" using Elastos::Droid::System::OsConstants; using Elastos::Droid::System::IStructStat; using Elastos::Core::CCloseGuard; using Elastos::Core::Character; using Elastos::Core::StringBuilder; using Elastos::IO::Channels::IChannel; using Elastos::IO::Charset::IModifiedUtf8; using Elastos::IO::Charset::CModifiedUtf8; using Libcore::IO::IoBridge; using Libcore::IO::ILibcore; using Libcore::IO::CLibcore; using Libcore::IO::IOs; using Libcore::IO::IoUtils; using Libcore::IO::Memory; namespace Elastos { namespace IO { CAR_OBJECT_IMPL(CRandomAccessFile) CAR_INTERFACE_IMPL_4(CRandomAccessFile, Object, IRandomAccessFile, IDataInput, IDataOutput, ICloseable) CRandomAccessFile::CRandomAccessFile() : mSyncMetadata(FALSE) , mMode(0) { mScratch = ArrayOf<Byte>::Alloc(8); } CRandomAccessFile::~CRandomAccessFile() { mScratch = NULL; if (mGuard != NULL) { mGuard->WarnIfOpen(); mGuard->Close(); } // can not call virtual method Close() on destructor. // AutoLock lock(this); Boolean isflag(FALSE); if (mChannel != NULL && (IChannel::Probe(mChannel)->IsOpen(&isflag) , isflag)) { ICloseable::Probe(mChannel)->Close(); mChannel = NULL; } IoBridge::CloseAndSignalBlockedThreads(mFd); } ECode CRandomAccessFile::constructor( /* [in] */ IFile* file, /* [in] */ const String& mode) { CCloseGuard::New((ICloseGuard**)&mGuard); Int32 flags; if (mode.Equals("r")) { flags = OsConstants::_O_RDONLY; } else if (mode.Equals("rw") || mode.Equals("rws") || mode.Equals("rwd")) { flags = OsConstants::_O_RDWR | OsConstants::_O_CREAT; if (mode.Equals("rws")) { // Sync file and metadata with every write mSyncMetadata = true; } else if (mode.Equals("rwd")) { // Sync file, but not necessarily metadata flags |= OsConstants::_O_SYNC; } } else { // throw new IllegalArgumentException("Invalid mode: " + mode); return E_ILLEGAL_ARGUMENT_EXCEPTION; } mMode = flags; String path; file->GetPath(&path); AutoPtr<IFileDescriptor> fd; FAIL_RETURN(IoBridge::Open(path, flags, (IFileDescriptor**)&fd)); Int32 ifd; fd->GetDescriptor(&ifd); CFileDescriptor::New((IFileDescriptor**)&mFd); mFd->SetDescriptor(ifd); // if we are in "rws" mode, attempt to sync file+metadata if (mSyncMetadata) { mFd->Sync(); } return mGuard->Open(String("CRandomAccessFile::Close")); } ECode CRandomAccessFile::constructor( /* [in] */ const String& fileName, /* [in] */ const String& mode) { AutoPtr<CFile> obj; FAIL_RETURN(CFile::NewByFriend(fileName, (CFile**)&obj)); AutoPtr<IFile> file = (IFile*)obj; return constructor(file, mode); } ECode CRandomAccessFile::Close() { mGuard->Close(); AutoLock lock(this); Boolean isflag(FALSE); if (mChannel != NULL && (IChannel::Probe(mChannel)->IsOpen(&isflag) , isflag)) { ICloseable::Probe(mChannel)->Close(); mChannel = NULL; } return IoBridge::CloseAndSignalBlockedThreads(mFd); } ECode CRandomAccessFile::GetChannel( /* [out] */ IFileChannel **channel) { VALIDATE_NOT_NULL(channel) AutoLock lock(this); if (mChannel == NULL) { mChannel = NioUtils::NewFileChannel(this, mFd, mMode); } *channel = mChannel; REFCOUNT_ADD(*channel) return NOERROR; } ECode CRandomAccessFile::GetFD( /* [out] */ IFileDescriptor ** fd) { VALIDATE_NOT_NULL(fd); *fd = mFd; REFCOUNT_ADD(*fd); return NOERROR; } ECode CRandomAccessFile::GetFilePointer( /* [out] */ Int64* offset) { VALIDATE_NOT_NULL(offset); *offset = -1; AutoPtr<ILibcore> libcore; CLibcore::AcquireSingleton((ILibcore**)&libcore); AutoPtr<IOs> os; libcore->GetOs((IOs**)&os); ECode ec = os->Lseek(mFd, 0ll, OsConstants::_SEEK_CUR, offset); if (FAILED(ec)) return E_IO_EXCEPTION; return NOERROR; } ECode CRandomAccessFile::GetLength( /* [out] */ Int64* len) { VALIDATE_NOT_NULL(len); *len = 0; AutoPtr<ILibcore> libcore; CLibcore::AcquireSingleton((ILibcore**)&libcore); AutoPtr<IOs> os; libcore->GetOs((IOs**)&os); AutoPtr<IStructStat> stat; ECode ec = os->Fstat(mFd, (IStructStat**)&stat); if (FAILED(ec)) return E_IO_EXCEPTION; return stat->GetSize(len); } ECode CRandomAccessFile::Read( /* [out] */ Int32* value) { VALIDATE_NOT_NULL(value); *value = -1; Int32 byteCount; FAIL_RETURN(Read(mScratch, 0, 1, &byteCount)) *value = byteCount != -1 ? (*mScratch)[0] & 0xff : -1; return NOERROR; } ECode CRandomAccessFile::Read( /* [out] */ ArrayOf<Byte>* buffer, /* [out] */ Int32* number) { VALIDATE_NOT_NULL(number); *number = -1; VALIDATE_NOT_NULL(buffer); return Read(buffer, 0, buffer->GetLength(), number); } ECode CRandomAccessFile::Read( /* [out] */ ArrayOf<Byte>* buffer, /* [in] */ Int32 offset, /* [in] */ Int32 length, /* [out] */ Int32* number) { VALIDATE_NOT_NULL(number); return IoBridge::Read(mFd, buffer, offset, length, number); } ECode CRandomAccessFile::ReadBoolean( /* [out] */ Boolean* value) { VALIDATE_NOT_NULL(value); Int32 temp; FAIL_RETURN(Read(&temp)); if (temp < 0) { // throw new EOFException(); return E_EOF_EXCEPTION; } *value = temp != 0; return NOERROR; } ECode CRandomAccessFile::ReadByte( /* [out] */ Byte* value) { VALIDATE_NOT_NULL(value); Int32 temp; FAIL_RETURN(Read(&temp)); if (temp < 0) { // throw new EOFException(); return E_EOF_EXCEPTION; } *value = (Byte)temp; return NOERROR; } ECode CRandomAccessFile::ReadChar( /* [out] */ Char32* value) { VALIDATE_NOT_NULL(value); Byte firstChar; FAIL_RETURN(ReadByte(&firstChar)); if ((firstChar & 0x80) == 0) { // ASCII *value = (Char32)firstChar; return NOERROR; } Char32 mask, toIgnoreMask; Int32 numToRead = 1; Char32 utf32 = firstChar; for (mask = 0x40, toIgnoreMask = 0xFFFFFF80; (firstChar & mask); numToRead++, toIgnoreMask |= mask, mask >>= 1) { // 0x3F == 00111111 Byte ch; FAIL_RETURN(ReadByte(&ch)); utf32 = (utf32 << 6) + (ch & 0x3F); } toIgnoreMask |= mask; utf32 &= ~(toIgnoreMask << (6 * (numToRead - 1))); *value = utf32; return NOERROR; } ECode CRandomAccessFile::ReadDouble( /* [out] */ Double* value) { VALIDATE_NOT_NULL(value); *value = 0; Int64 i64Value; FAIL_RETURN(ReadInt64(&i64Value)); *value = Elastos::Core::Math::Int64BitsToDouble(i64Value); return NOERROR; } ECode CRandomAccessFile::ReadFloat( /* [out] */ Float* value) { VALIDATE_NOT_NULL(value); *value = 0; Int32 i32Value; FAIL_RETURN(ReadInt32(&i32Value)); *value = Elastos::Core::Math::Int32BitsToFloat(i32Value); return NOERROR; } ECode CRandomAccessFile::ReadFully( /* [out] */ ArrayOf<Byte>* buffer) { return ReadFully(buffer, 0, buffer->GetLength()); } ECode CRandomAccessFile::ReadFully( /* [out] */ ArrayOf<byte>* buffer, /* [in] */ Int32 offset, /* [in] */ Int32 length) { if (buffer == NULL) { // throw new NullPointerException("buffer == null"); return E_NULL_POINTER_EXCEPTION; } // avoid int overflow // BEGIN android-changed // Exception priorities (in case of multiple errors) differ from // RI, but are spec-compliant. // used (offset | length) < 0 instead of separate (offset < 0) and // (length < 0) check to safe one operation if ((offset | length) < 0 || offset > buffer->GetLength() - length) { // throw new IndexOutOfBoundsException(); return E_ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION; } // END android-changed Int32 number; while (length > 0) { FAIL_RETURN(Read(buffer, offset, length, &number)); if (number < 0) { // throw new EOFException(); return E_EOF_EXCEPTION; } offset += number; length -= number; } return NOERROR; } ECode CRandomAccessFile::ReadInt32( /* [out] */ Int32* value) { VALIDATE_NOT_NULL(value); FAIL_RETURN(ReadFully(mScratch, 0, sizeof(Int32))); *value = Memory::PeekInt32(mScratch, 0, ByteOrder_BIG_ENDIAN); return NOERROR; } ECode CRandomAccessFile::ReadLine( /* [out] */ String* str) { VALIDATE_NOT_NULL(str); AutoPtr<StringBuilder> line = new StringBuilder(80); Boolean foundTerminator = FALSE; Int64 unreadPosition = 0; while (TRUE) { Int32 nextByte; FAIL_RETURN(Read(&nextByte)); switch (nextByte) { case -1: if (line->GetLength() != 0) { *str = line->ToString(); } else { *str = NULL; } return NOERROR; case (Byte)'\r': if (foundTerminator) { Seek(unreadPosition); *str = line->ToString(); return NOERROR; } foundTerminator = TRUE; /* Have to be able to peek ahead one byte */ GetFilePointer(&unreadPosition); break; case (Byte)'\n': *str = line->ToString(); return NOERROR; default: if (foundTerminator) { Seek(unreadPosition); *str = line->ToString(); return NOERROR; } line->AppendChar((Char32)nextByte); } } return NOERROR; } ECode CRandomAccessFile::ReadInt64( /* [out] */ Int64* value) { VALIDATE_NOT_NULL(value); FAIL_RETURN(ReadFully(mScratch, 0, sizeof(Int64))); *value = Memory::PeekInt64(mScratch, 0, ByteOrder_BIG_ENDIAN); return NOERROR; } ECode CRandomAccessFile::ReadInt16( /* [out] */ Int16* value) { VALIDATE_NOT_NULL(value); FAIL_RETURN(ReadFully(mScratch, 0, sizeof(Int16))); *value = Memory::PeekInt16(mScratch, 0, ByteOrder_BIG_ENDIAN); return NOERROR; } ECode CRandomAccessFile::ReadUnsignedByte( /* [out] */ Int32* value) { VALIDATE_NOT_NULL(value); FAIL_RETURN(Read(value)); return *value < 0 ? E_EOF_EXCEPTION : NOERROR; } ECode CRandomAccessFile::ReadUnsignedInt16( /* [out] */ Int32* value) { VALIDATE_NOT_NULL(value); Int16 temp; FAIL_RETURN(ReadInt16(&temp)); *value = ((Int32)temp) & 0xFFFF; return NOERROR; } ECode CRandomAccessFile::ReadUTF( /* [out] */ String* str) { VALIDATE_NOT_NULL(str) Int32 utfSize = 0; FAIL_RETURN(ReadUnsignedInt16(&utfSize)); if (utfSize == 0) { *str = ""; return NOERROR; } AutoPtr< ArrayOf<Byte> > buf = ArrayOf<Byte>::Alloc(utfSize); Int32 readsize = 0; Read(buf, 0, buf->GetLength(), &readsize); if (readsize != buf->GetLength()) { // throw new EOFException(); return E_EOF_EXCEPTION; } AutoPtr<IModifiedUtf8> mutf8help; CModifiedUtf8::AcquireSingleton((IModifiedUtf8**)&mutf8help); AutoPtr< ArrayOf<Char32> > charbuf = ArrayOf<Char32>::Alloc(utfSize); return mutf8help->Decode(buf, charbuf, 0, utfSize, str); } ECode CRandomAccessFile::Seek( /* [in] */ Int64 offset) { if (offset < 0) { // seek position is negative // throw new IOException("offset < 0"); return E_IO_EXCEPTION; } AutoPtr<CLibcore> ioObj; CLibcore::AcquireSingletonByFriend((CLibcore**)&ioObj); AutoPtr<ILibcore> libcore = (ILibcore*)ioObj.Get(); AutoPtr<IOs> os; libcore->GetOs((IOs**)&os); Int64 res; ECode ec = os->Lseek(mFd, offset, OsConstants::_SEEK_SET, &res); if (FAILED(ec)) return E_IO_EXCEPTION; return NOERROR; } ECode CRandomAccessFile::SetLength( /* [in] */ Int64 newLength) { if (newLength < 0) { // throw new IllegalArgumentException(); return E_ILLEGAL_ARGUMENT_EXCEPTION; } AutoPtr<CLibcore> ioObj; CLibcore::AcquireSingletonByFriend((CLibcore**)&ioObj); AutoPtr<ILibcore> libcore = (ILibcore*)ioObj.Get(); AutoPtr<IOs> os; libcore->GetOs((IOs**)&os); ECode ec = os->Ftruncate(mFd, newLength); if (FAILED(ec)) return E_IO_EXCEPTION; Int64 filePointer; FAIL_RETURN(GetFilePointer(&filePointer)); if (filePointer > newLength) { FAIL_RETURN(Seek(newLength)); } // if we are in "rws" mode, attempt to sync file+metadata if (mSyncMetadata) { mFd->Sync(); } return NOERROR; } ECode CRandomAccessFile::SkipBytes( /* [in] */ Int32 count, /* [out] */ Int32* number) { VALIDATE_NOT_NULL(number); *number = 0; if (count > 0) { Int64 currentPos, eof; GetFilePointer(&currentPos); GetLength(&eof); Int32 newCount = (Int32)((currentPos + count > eof) ? eof - currentPos : count); FAIL_RETURN(Seek(currentPos + newCount)); *number = newCount; return NOERROR; } *number = 0; return NOERROR; } ECode CRandomAccessFile::Write( /* [in] */ ArrayOf<Byte>* buffer) { return Write(buffer, 0, buffer->GetLength()); } ECode CRandomAccessFile::Write( /* [in] */ ArrayOf<Byte>* buffer, /* [in] */ Int32 offset, /* [in] */ Int32 count) { FAIL_RETURN(IoBridge::Write(mFd, buffer, offset, count)); // if we are in "rws" mode, attempt to sync file+metadata if (mSyncMetadata) { mFd->Sync(); } return NOERROR; } ECode CRandomAccessFile::Write( /* [in] */ Int32 oneByte) { (*mScratch)[0] = (Byte)(oneByte & 0xFF); return Write(mScratch, 0, 1); } ECode CRandomAccessFile::WriteBoolean( /* [in] */ Boolean value) { return Write(value? 1 : 0); } ECode CRandomAccessFile::WriteByte( /* [in] */ Int32 value) { return Write(value & 0xff); } ECode CRandomAccessFile::WriteChar( /* [in] */ Int32 value) { AutoPtr< ArrayOf<Byte> > buffer = ArrayOf<Byte>::Alloc(4); Int32 len; Character::ToChars((Char32)value, *buffer, 0, &len); return Write(buffer, 0, len); } ECode CRandomAccessFile::WriteBytes( /* [in] */ const String& str) { if (str.IsNullOrEmpty()) return NOERROR; AutoPtr<ArrayOf<Byte> > bytes = ArrayOf<Byte>::Alloc(str.GetLength()); for (Int32 index = 0; index < str.GetLength(); index++) { bytes->Set(index, (Byte)(str.GetChar(index) & 0xFF)); } return Write(bytes); } ECode CRandomAccessFile::WriteChars( /* [in] */ const String& str) { if (str.IsNullOrEmpty()) return NOERROR; // write(str.getBytes("UTF-16BE")); AutoPtr<ArrayOf<Byte> > chs = str.GetBytes(); return Write(chs); } ECode CRandomAccessFile::WriteDouble( /* [in] */ Double value) { return WriteInt64(Elastos::Core::Math::DoubleToInt64Bits(value)); } ECode CRandomAccessFile::WriteFloat( /* [in] */ Float value) { return WriteInt32(Elastos::Core::Math::FloatToInt32Bits(value)); } ECode CRandomAccessFile::WriteInt32( /* [in] */ Int32 value) { Memory::PokeInt32(mScratch, 0, value, ByteOrder_BIG_ENDIAN); return Write(mScratch, 0, sizeof(Int32)); } ECode CRandomAccessFile::WriteInt64( /* [in] */ Int64 value) { Memory::PokeInt64(mScratch, 0, value, ByteOrder_BIG_ENDIAN); return Write(mScratch, 0, sizeof(Int64)); } ECode CRandomAccessFile::WriteInt16( /* [in] */ Int32 value) { Memory::PokeInt16(mScratch, 0, value, ByteOrder_BIG_ENDIAN); return Write(mScratch, 0, sizeof(Int32)); } ECode CRandomAccessFile::WriteUTF( /* [in] */ const String& str) { AutoPtr<IModifiedUtf8> utf8help; CModifiedUtf8::AcquireSingleton((IModifiedUtf8**)&utf8help); AutoPtr<ArrayOf<Byte> > bytes; utf8help->Encode(str, (ArrayOf<Byte>**)&bytes); return Write(bytes); } } // namespace IO } // namespace Elastos
17,080
6,323
// Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/fit/thread_checker.h> #include <thread> #include <zxtest/zxtest.h> namespace { TEST(ThreadCheckerTest, SameThread) { fit::thread_checker checker; EXPECT_TRUE(checker.is_thread_valid()); } TEST(ThreadCheckerTest, DifferentThreads) { fit::thread_checker checker1; EXPECT_TRUE(checker1.is_thread_valid()); checker1.lock(); checker1.unlock(); std::thread thread([&checker1]() { fit::thread_checker checker2; EXPECT_TRUE(checker2.is_thread_valid()); EXPECT_FALSE(checker1.is_thread_valid()); checker2.lock(); checker2.unlock(); }); thread.join(); // Note: Without synchronization, we can't look at |checker2| from the main // thread. } } // namespace
876
325
/* ============================================================ * QupZilla - Qt web browser * Copyright (C) 2016-2017 David Rosca <nowrep@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ============================================================ */ #include "webscrollbar.h" #include "webview.h" #include "webpage.h" #include <QPaintEvent> WebScrollBar::WebScrollBar(Qt::Orientation orientation, WebView *view) : QScrollBar(orientation) , m_view(view) { setFocusProxy(m_view); resize(sizeHint()); connect(this, &QScrollBar::valueChanged, this, &WebScrollBar::performScroll); connect(view, &WebView::focusChanged, this, [this]() { update(); }); } int WebScrollBar::thickness() const { return orientation() == Qt::Vertical ? width() : height(); } void WebScrollBar::updateValues(const QSize &viewport) { setMinimum(0); setParent(m_view->overlayWidget()); int newValue; m_blockScrolling = true; if (orientation() == Qt::Vertical) { setFixedHeight(m_view->height() - (m_view->height() - viewport.height()) * devicePixelRatioF()); move(m_view->width() - width(), 0); setPageStep(viewport.height()); setMaximum(qMax(0, m_view->page()->contentsSize().toSize().height() - viewport.height())); newValue = m_view->page()->scrollPosition().toPoint().y(); } else { setFixedWidth(m_view->width() - (m_view->width() - viewport.width()) * devicePixelRatioF()); move(0, m_view->height() - height()); setPageStep(viewport.width()); setMaximum(qMax(0, m_view->page()->contentsSize().toSize().width() - viewport.width())); newValue = m_view->page()->scrollPosition().toPoint().x(); } if (!isSliderDown()) { setValue(newValue); } m_blockScrolling = false; } void WebScrollBar::performScroll() { if (m_blockScrolling) { return; } QPointF pos = m_view->page()->scrollPosition(); if (orientation() == Qt::Vertical) { pos.setY(value()); } else { pos.setX(value()); } m_view->page()->setScrollPosition(pos); } void WebScrollBar::paintEvent(QPaintEvent *ev) { QPainter painter(this); painter.fillRect(ev->rect(), palette().background()); QScrollBar::paintEvent(ev); }
2,880
908
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: sw=2 ts=8 et : */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "Layers.h" #include <algorithm> // for max, min #include "apz/src/AsyncPanZoomController.h" #include "CompositableHost.h" // for CompositableHost #include "ImageContainer.h" // for ImageContainer, etc #include "ImageLayers.h" // for ImageLayer #include "LayerSorter.h" // for SortLayersBy3DZOrder #include "LayersLogging.h" // for AppendToString #include "ReadbackLayer.h" // for ReadbackLayer #include "UnitTransforms.h" // for ViewAs #include "gfxEnv.h" #include "gfxPlatform.h" // for gfxPlatform #include "gfxPrefs.h" #include "gfxUtils.h" // for gfxUtils, etc #include "gfx2DGlue.h" #include "mozilla/DebugOnly.h" // for DebugOnly #include "mozilla/Telemetry.h" // for Accumulate #include "mozilla/dom/Animation.h" // for ComputedTimingFunction #include "mozilla/gfx/2D.h" // for DrawTarget #include "mozilla/gfx/BaseSize.h" // for BaseSize #include "mozilla/gfx/Matrix.h" // for Matrix4x4 #include "mozilla/layers/AsyncCanvasRenderer.h" #include "mozilla/layers/CompositableClient.h" // for CompositableClient #include "mozilla/layers/Compositor.h" // for Compositor #include "mozilla/layers/CompositorTypes.h" #include "mozilla/layers/LayerManagerComposite.h" // for LayerComposite #include "mozilla/layers/LayerMetricsWrapper.h" // for LayerMetricsWrapper #include "mozilla/layers/LayersMessages.h" // for TransformFunction, etc #include "mozilla/layers/LayersTypes.h" // for TextureDumpMode #include "mozilla/layers/PersistentBufferProvider.h" #include "mozilla/layers/ShadowLayers.h" // for ShadowableLayer #include "nsAString.h" #include "nsCSSValue.h" // for nsCSSValue::Array, etc #include "nsPrintfCString.h" // for nsPrintfCString #include "nsStyleStruct.h" // for nsTimingFunction, etc #include "protobuf/LayerScopePacket.pb.h" #include "mozilla/Compression.h" uint8_t gLayerManagerLayerBuilder; namespace mozilla { namespace layers { FILE* FILEOrDefault(FILE* aFile) { return aFile ? aFile : stderr; } typedef FrameMetrics::ViewID ViewID; using namespace mozilla::gfx; using namespace mozilla::Compression; //-------------------------------------------------- // LayerManager /* static */ mozilla::LogModule* LayerManager::GetLog() { static LazyLogModule sLog("Layers"); return sLog; } FrameMetrics::ViewID LayerManager::GetRootScrollableLayerId() { if (!mRoot) { return FrameMetrics::NULL_SCROLL_ID; } nsTArray<LayerMetricsWrapper> queue = { LayerMetricsWrapper(mRoot) }; while (queue.Length()) { LayerMetricsWrapper layer = queue[0]; queue.RemoveElementAt(0); const FrameMetrics& frameMetrics = layer.Metrics(); if (frameMetrics.IsScrollable()) { return frameMetrics.GetScrollId(); } LayerMetricsWrapper child = layer.GetFirstChild(); while (child) { queue.AppendElement(child); child = child.GetNextSibling(); } } return FrameMetrics::NULL_SCROLL_ID; } void LayerManager::GetRootScrollableLayers(nsTArray<Layer*>& aArray) { if (!mRoot) { return; } FrameMetrics::ViewID rootScrollableId = GetRootScrollableLayerId(); if (rootScrollableId == FrameMetrics::NULL_SCROLL_ID) { aArray.AppendElement(mRoot); return; } nsTArray<Layer*> queue = { mRoot }; while (queue.Length()) { Layer* layer = queue[0]; queue.RemoveElementAt(0); if (LayerMetricsWrapper::TopmostScrollableMetrics(layer).GetScrollId() == rootScrollableId) { aArray.AppendElement(layer); continue; } for (Layer* child = layer->GetFirstChild(); child; child = child->GetNextSibling()) { queue.AppendElement(child); } } } void LayerManager::GetScrollableLayers(nsTArray<Layer*>& aArray) { if (!mRoot) { return; } nsTArray<Layer*> queue = { mRoot }; while (!queue.IsEmpty()) { Layer* layer = queue.LastElement(); queue.RemoveElementAt(queue.Length() - 1); if (layer->HasScrollableFrameMetrics()) { aArray.AppendElement(layer); continue; } for (Layer* child = layer->GetFirstChild(); child; child = child->GetNextSibling()) { queue.AppendElement(child); } } } already_AddRefed<DrawTarget> LayerManager::CreateOptimalDrawTarget(const gfx::IntSize &aSize, SurfaceFormat aFormat) { return gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(aSize, aFormat); } already_AddRefed<DrawTarget> LayerManager::CreateOptimalMaskDrawTarget(const gfx::IntSize &aSize) { return CreateOptimalDrawTarget(aSize, SurfaceFormat::A8); } already_AddRefed<DrawTarget> LayerManager::CreateDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) { return gfxPlatform::GetPlatform()-> CreateOffscreenCanvasDrawTarget(aSize, aFormat); } already_AddRefed<PersistentBufferProvider> LayerManager::CreatePersistentBufferProvider(const mozilla::gfx::IntSize &aSize, mozilla::gfx::SurfaceFormat aFormat) { RefPtr<PersistentBufferProviderBasic> bufferProvider = new PersistentBufferProviderBasic(aSize, aFormat, gfxPlatform::GetPlatform()->GetPreferredCanvasBackend()); if (!bufferProvider->IsValid()) { bufferProvider = new PersistentBufferProviderBasic(aSize, aFormat, gfxPlatform::GetPlatform()->GetFallbackCanvasBackend()); } if (!bufferProvider->IsValid()) { return nullptr; } return bufferProvider.forget(); } #ifdef DEBUG void LayerManager::Mutated(Layer* aLayer) { } #endif // DEBUG already_AddRefed<ImageContainer> LayerManager::CreateImageContainer(ImageContainer::Mode flag) { RefPtr<ImageContainer> container = new ImageContainer(flag); return container.forget(); } bool LayerManager::AreComponentAlphaLayersEnabled() { return gfxPrefs::ComponentAlphaEnabled(); } /*static*/ void LayerManager::LayerUserDataDestroy(void* data) { delete static_cast<LayerUserData*>(data); } nsAutoPtr<LayerUserData> LayerManager::RemoveUserData(void* aKey) { nsAutoPtr<LayerUserData> d(static_cast<LayerUserData*>(mUserData.Remove(static_cast<gfx::UserDataKey*>(aKey)))); return d; } //-------------------------------------------------- // Layer Layer::Layer(LayerManager* aManager, void* aImplData) : mManager(aManager), mParent(nullptr), mNextSibling(nullptr), mPrevSibling(nullptr), mImplData(aImplData), mMaskLayer(nullptr), mPostXScale(1.0f), mPostYScale(1.0f), mOpacity(1.0), mMixBlendMode(CompositionOp::OP_OVER), mForceIsolatedGroup(false), mContentFlags(0), mUseTileSourceRect(false), mIsFixedPosition(false), mTransformIsPerspective(false), mFixedPositionData(nullptr), mStickyPositionData(nullptr), mScrollbarTargetId(FrameMetrics::NULL_SCROLL_ID), mScrollbarDirection(ScrollDirection::NONE), mScrollbarThumbRatio(0.0f), mIsScrollbarContainer(false), mDebugColorIndex(0), mAnimationGeneration(0) { MOZ_COUNT_CTOR(Layer); } Layer::~Layer() { MOZ_COUNT_DTOR(Layer); } Animation* Layer::AddAnimation() { MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) AddAnimation", this)); MOZ_ASSERT(!mPendingAnimations, "should have called ClearAnimations first"); Animation* anim = mAnimations.AppendElement(); Mutated(); return anim; } void Layer::ClearAnimations() { mPendingAnimations = nullptr; if (mAnimations.IsEmpty() && mAnimationData.IsEmpty()) { return; } MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) ClearAnimations", this)); mAnimations.Clear(); mAnimationData.Clear(); Mutated(); } Animation* Layer::AddAnimationForNextTransaction() { MOZ_ASSERT(mPendingAnimations, "should have called ClearAnimationsForNextTransaction first"); Animation* anim = mPendingAnimations->AppendElement(); return anim; } void Layer::ClearAnimationsForNextTransaction() { // Ensure we have a non-null mPendingAnimations to mark a future clear. if (!mPendingAnimations) { mPendingAnimations = new AnimationArray; } mPendingAnimations->Clear(); } static inline void SetCSSAngle(const CSSAngle& aAngle, nsCSSValue& aValue) { aValue.SetFloatValue(aAngle.value(), nsCSSUnit(aAngle.unit())); } static nsCSSValueSharedList* CreateCSSValueList(const InfallibleTArray<TransformFunction>& aFunctions) { nsAutoPtr<nsCSSValueList> result; nsCSSValueList** resultTail = getter_Transfers(result); for (uint32_t i = 0; i < aFunctions.Length(); i++) { RefPtr<nsCSSValue::Array> arr; switch (aFunctions[i].type()) { case TransformFunction::TRotationX: { const CSSAngle& angle = aFunctions[i].get_RotationX().angle(); arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_rotatex, resultTail); SetCSSAngle(angle, arr->Item(1)); break; } case TransformFunction::TRotationY: { const CSSAngle& angle = aFunctions[i].get_RotationY().angle(); arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_rotatey, resultTail); SetCSSAngle(angle, arr->Item(1)); break; } case TransformFunction::TRotationZ: { const CSSAngle& angle = aFunctions[i].get_RotationZ().angle(); arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_rotatez, resultTail); SetCSSAngle(angle, arr->Item(1)); break; } case TransformFunction::TRotation: { const CSSAngle& angle = aFunctions[i].get_Rotation().angle(); arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_rotate, resultTail); SetCSSAngle(angle, arr->Item(1)); break; } case TransformFunction::TRotation3D: { float x = aFunctions[i].get_Rotation3D().x(); float y = aFunctions[i].get_Rotation3D().y(); float z = aFunctions[i].get_Rotation3D().z(); const CSSAngle& angle = aFunctions[i].get_Rotation3D().angle(); arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_rotate3d, resultTail); arr->Item(1).SetFloatValue(x, eCSSUnit_Number); arr->Item(2).SetFloatValue(y, eCSSUnit_Number); arr->Item(3).SetFloatValue(z, eCSSUnit_Number); SetCSSAngle(angle, arr->Item(4)); break; } case TransformFunction::TScale: { arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_scale3d, resultTail); arr->Item(1).SetFloatValue(aFunctions[i].get_Scale().x(), eCSSUnit_Number); arr->Item(2).SetFloatValue(aFunctions[i].get_Scale().y(), eCSSUnit_Number); arr->Item(3).SetFloatValue(aFunctions[i].get_Scale().z(), eCSSUnit_Number); break; } case TransformFunction::TTranslation: { arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_translate3d, resultTail); arr->Item(1).SetFloatValue(aFunctions[i].get_Translation().x(), eCSSUnit_Pixel); arr->Item(2).SetFloatValue(aFunctions[i].get_Translation().y(), eCSSUnit_Pixel); arr->Item(3).SetFloatValue(aFunctions[i].get_Translation().z(), eCSSUnit_Pixel); break; } case TransformFunction::TSkewX: { const CSSAngle& x = aFunctions[i].get_SkewX().x(); arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_skewx, resultTail); SetCSSAngle(x, arr->Item(1)); break; } case TransformFunction::TSkewY: { const CSSAngle& y = aFunctions[i].get_SkewY().y(); arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_skewy, resultTail); SetCSSAngle(y, arr->Item(1)); break; } case TransformFunction::TSkew: { const CSSAngle& x = aFunctions[i].get_Skew().x(); const CSSAngle& y = aFunctions[i].get_Skew().y(); arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_skew, resultTail); SetCSSAngle(x, arr->Item(1)); SetCSSAngle(y, arr->Item(2)); break; } case TransformFunction::TTransformMatrix: { arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_matrix3d, resultTail); const gfx::Matrix4x4& matrix = aFunctions[i].get_TransformMatrix().value(); arr->Item(1).SetFloatValue(matrix._11, eCSSUnit_Number); arr->Item(2).SetFloatValue(matrix._12, eCSSUnit_Number); arr->Item(3).SetFloatValue(matrix._13, eCSSUnit_Number); arr->Item(4).SetFloatValue(matrix._14, eCSSUnit_Number); arr->Item(5).SetFloatValue(matrix._21, eCSSUnit_Number); arr->Item(6).SetFloatValue(matrix._22, eCSSUnit_Number); arr->Item(7).SetFloatValue(matrix._23, eCSSUnit_Number); arr->Item(8).SetFloatValue(matrix._24, eCSSUnit_Number); arr->Item(9).SetFloatValue(matrix._31, eCSSUnit_Number); arr->Item(10).SetFloatValue(matrix._32, eCSSUnit_Number); arr->Item(11).SetFloatValue(matrix._33, eCSSUnit_Number); arr->Item(12).SetFloatValue(matrix._34, eCSSUnit_Number); arr->Item(13).SetFloatValue(matrix._41, eCSSUnit_Number); arr->Item(14).SetFloatValue(matrix._42, eCSSUnit_Number); arr->Item(15).SetFloatValue(matrix._43, eCSSUnit_Number); arr->Item(16).SetFloatValue(matrix._44, eCSSUnit_Number); break; } case TransformFunction::TPerspective: { float perspective = aFunctions[i].get_Perspective().value(); arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_perspective, resultTail); arr->Item(1).SetFloatValue(perspective, eCSSUnit_Pixel); break; } default: NS_ASSERTION(false, "All functions should be implemented?"); } } if (aFunctions.Length() == 0) { result = new nsCSSValueList(); result->mValue.SetNoneValue(); } return new nsCSSValueSharedList(result.forget()); } void Layer::SetAnimations(const AnimationArray& aAnimations) { MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) SetAnimations", this)); mAnimations = aAnimations; mAnimationData.Clear(); for (uint32_t i = 0; i < mAnimations.Length(); i++) { AnimData* data = mAnimationData.AppendElement(); InfallibleTArray<nsAutoPtr<ComputedTimingFunction> >& functions = data->mFunctions; const InfallibleTArray<AnimationSegment>& segments = mAnimations.ElementAt(i).segments(); for (uint32_t j = 0; j < segments.Length(); j++) { TimingFunction tf = segments.ElementAt(j).sampleFn(); ComputedTimingFunction* ctf = new ComputedTimingFunction(); switch (tf.type()) { case TimingFunction::TCubicBezierFunction: { CubicBezierFunction cbf = tf.get_CubicBezierFunction(); ctf->Init(nsTimingFunction(cbf.x1(), cbf.y1(), cbf.x2(), cbf.y2())); break; } default: { NS_ASSERTION(tf.type() == TimingFunction::TStepFunction, "Function must be bezier or step"); StepFunction sf = tf.get_StepFunction(); nsTimingFunction::Type type = sf.type() == 1 ? nsTimingFunction::Type::StepStart : nsTimingFunction::Type::StepEnd; ctf->Init(nsTimingFunction(type, sf.steps(), nsTimingFunction::Keyword::Explicit)); break; } } functions.AppendElement(ctf); } // Precompute the StyleAnimationValues that we need if this is a transform // animation. InfallibleTArray<StyleAnimationValue>& startValues = data->mStartValues; InfallibleTArray<StyleAnimationValue>& endValues = data->mEndValues; for (uint32_t j = 0; j < mAnimations[i].segments().Length(); j++) { const AnimationSegment& segment = mAnimations[i].segments()[j]; StyleAnimationValue* startValue = startValues.AppendElement(); StyleAnimationValue* endValue = endValues.AppendElement(); if (segment.endState().type() == Animatable::TArrayOfTransformFunction) { const InfallibleTArray<TransformFunction>& startFunctions = segment.startState().get_ArrayOfTransformFunction(); startValue->SetTransformValue(CreateCSSValueList(startFunctions)); const InfallibleTArray<TransformFunction>& endFunctions = segment.endState().get_ArrayOfTransformFunction(); endValue->SetTransformValue(CreateCSSValueList(endFunctions)); } else { NS_ASSERTION(segment.endState().type() == Animatable::Tfloat, "Unknown Animatable type"); startValue->SetFloatValue(segment.startState().get_float()); endValue->SetFloatValue(segment.endState().get_float()); } } } Mutated(); } void Layer::StartPendingAnimations(const TimeStamp& aReadyTime) { bool updated = false; for (size_t animIdx = 0, animEnd = mAnimations.Length(); animIdx < animEnd; animIdx++) { Animation& anim = mAnimations[animIdx]; if (anim.startTime().IsNull()) { anim.startTime() = aReadyTime - anim.initialCurrentTime(); updated = true; } } if (updated) { Mutated(); } for (Layer* child = GetFirstChild(); child; child = child->GetNextSibling()) { child->StartPendingAnimations(aReadyTime); } } void Layer::SetAsyncPanZoomController(uint32_t aIndex, AsyncPanZoomController *controller) { MOZ_ASSERT(aIndex < GetFrameMetricsCount()); mApzcs[aIndex] = controller; } AsyncPanZoomController* Layer::GetAsyncPanZoomController(uint32_t aIndex) const { MOZ_ASSERT(aIndex < GetFrameMetricsCount()); #ifdef DEBUG if (mApzcs[aIndex]) { MOZ_ASSERT(GetFrameMetrics(aIndex).IsScrollable()); } #endif return mApzcs[aIndex]; } void Layer::FrameMetricsChanged() { mApzcs.SetLength(GetFrameMetricsCount()); } void Layer::ApplyPendingUpdatesToSubtree() { ApplyPendingUpdatesForThisTransaction(); for (Layer* child = GetFirstChild(); child; child = child->GetNextSibling()) { child->ApplyPendingUpdatesToSubtree(); } } bool Layer::IsOpaqueForVisibility() { return GetLocalOpacity() == 1.0f && GetEffectiveMixBlendMode() == CompositionOp::OP_OVER; } bool Layer::CanUseOpaqueSurface() { // If the visible content in the layer is opaque, there is no need // for an alpha channel. if (GetContentFlags() & CONTENT_OPAQUE) return true; // Also, if this layer is the bottommost layer in a container which // doesn't need an alpha channel, we can use an opaque surface for this // layer too. Any transparent areas must be covered by something else // in the container. ContainerLayer* parent = GetParent(); return parent && parent->GetFirstChild() == this && parent->CanUseOpaqueSurface(); } // NB: eventually these methods will be defined unconditionally, and // can be moved into Layers.h const Maybe<ParentLayerIntRect>& Layer::GetEffectiveClipRect() { if (LayerComposite* shadow = AsLayerComposite()) { return shadow->GetShadowClipRect(); } return GetClipRect(); } const LayerIntRegion& Layer::GetEffectiveVisibleRegion() { if (LayerComposite* shadow = AsLayerComposite()) { return shadow->GetShadowVisibleRegion(); } return GetVisibleRegion(); } Matrix4x4 Layer::SnapTransformTranslation(const Matrix4x4& aTransform, Matrix* aResidualTransform) { if (aResidualTransform) { *aResidualTransform = Matrix(); } if (!mManager->IsSnappingEffectiveTransforms()) { return aTransform; } Matrix matrix2D; Matrix4x4 result; if (aTransform.Is2D(&matrix2D) && !matrix2D.HasNonTranslation() && matrix2D.HasNonIntegerTranslation()) { IntPoint snappedTranslation = RoundedToInt(matrix2D.GetTranslation()); Matrix snappedMatrix = Matrix::Translation(snappedTranslation.x, snappedTranslation.y); result = Matrix4x4::From2D(snappedMatrix); if (aResidualTransform) { // set aResidualTransform so that aResidual * snappedMatrix == matrix2D. // (I.e., appying snappedMatrix after aResidualTransform gives the // ideal transform.) *aResidualTransform = Matrix::Translation(matrix2D._31 - snappedTranslation.x, matrix2D._32 - snappedTranslation.y); } return result; } if(aTransform.IsSingular() || aTransform.HasPerspectiveComponent() || aTransform.HasNonTranslation() || !aTransform.HasNonIntegerTranslation()) { // For a singular transform, there is no reversed matrix, so we // don't snap it. // For a perspective transform, the content is transformed in // non-linear, so we don't snap it too. return aTransform; } // Snap for 3D Transforms Point3D transformedOrigin = aTransform * Point3D(); // Compute the transformed snap by rounding the values of // transformed origin. IntPoint transformedSnapXY = RoundedToInt(Point(transformedOrigin.x, transformedOrigin.y)); Matrix4x4 inverse = aTransform; inverse.Invert(); // see Matrix4x4::ProjectPoint() Float transformedSnapZ = inverse._33 == 0 ? 0 : (-(transformedSnapXY.x * inverse._13 + transformedSnapXY.y * inverse._23 + inverse._43) / inverse._33); Point3D transformedSnap = Point3D(transformedSnapXY.x, transformedSnapXY.y, transformedSnapZ); if (transformedOrigin == transformedSnap) { return aTransform; } // Compute the snap from the transformed snap. Point3D snap = inverse * transformedSnap; if (snap.z > 0.001 || snap.z < -0.001) { // Allow some level of accumulated computation error. MOZ_ASSERT(inverse._33 == 0.0); return aTransform; } // The difference between the origin and snap is the residual transform. if (aResidualTransform) { // The residual transform is to translate the snap to the origin // of the content buffer. *aResidualTransform = Matrix::Translation(-snap.x, -snap.y); } // Translate transformed origin to transformed snap since the // residual transform would trnslate the snap to the origin. Point3D transformedShift = transformedSnap - transformedOrigin; result = aTransform; result.PostTranslate(transformedShift.x, transformedShift.y, transformedShift.z); // For non-2d transform, residual translation could be more than // 0.5 pixels for every axis. return result; } Matrix4x4 Layer::SnapTransform(const Matrix4x4& aTransform, const gfxRect& aSnapRect, Matrix* aResidualTransform) { if (aResidualTransform) { *aResidualTransform = Matrix(); } Matrix matrix2D; Matrix4x4 result; if (mManager->IsSnappingEffectiveTransforms() && aTransform.Is2D(&matrix2D) && gfxSize(1.0, 1.0) <= aSnapRect.Size() && matrix2D.PreservesAxisAlignedRectangles()) { IntPoint transformedTopLeft = RoundedToInt(matrix2D * ToPoint(aSnapRect.TopLeft())); IntPoint transformedTopRight = RoundedToInt(matrix2D * ToPoint(aSnapRect.TopRight())); IntPoint transformedBottomRight = RoundedToInt(matrix2D * ToPoint(aSnapRect.BottomRight())); Matrix snappedMatrix = gfxUtils::TransformRectToRect(aSnapRect, transformedTopLeft, transformedTopRight, transformedBottomRight); result = Matrix4x4::From2D(snappedMatrix); if (aResidualTransform && !snappedMatrix.IsSingular()) { // set aResidualTransform so that aResidual * snappedMatrix == matrix2D. // (i.e., appying snappedMatrix after aResidualTransform gives the // ideal transform. Matrix snappedMatrixInverse = snappedMatrix; snappedMatrixInverse.Invert(); *aResidualTransform = matrix2D * snappedMatrixInverse; } } else { result = aTransform; } return result; } static bool AncestorLayerMayChangeTransform(Layer* aLayer) { for (Layer* l = aLayer; l; l = l->GetParent()) { if (l->GetContentFlags() & Layer::CONTENT_MAY_CHANGE_TRANSFORM) { return true; } } return false; } bool Layer::MayResample() { Matrix transform2d; return !GetEffectiveTransform().Is2D(&transform2d) || ThebesMatrix(transform2d).HasNonIntegerTranslation() || AncestorLayerMayChangeTransform(this); } RenderTargetIntRect Layer::CalculateScissorRect(const RenderTargetIntRect& aCurrentScissorRect) { ContainerLayer* container = GetParent(); ContainerLayer* containerChild = nullptr; NS_ASSERTION(GetParent(), "This can't be called on the root!"); // Find the layer creating the 3D context. while (container->Extend3DContext() && !container->UseIntermediateSurface()) { containerChild = container; container = container->GetParent(); MOZ_ASSERT(container); } // Find the nearest layer with a clip, or this layer. // ContainerState::SetupScrollingMetadata() may install a clip on // the layer. Layer *clipLayer = containerChild && containerChild->GetEffectiveClipRect() ? containerChild : this; // Establish initial clip rect: it's either the one passed in, or // if the parent has an intermediate surface, it's the extents of that surface. RenderTargetIntRect currentClip; if (container->UseIntermediateSurface()) { currentClip.SizeTo(container->GetIntermediateSurfaceRect().Size()); } else { currentClip = aCurrentScissorRect; } if (!clipLayer->GetEffectiveClipRect()) { return currentClip; } if (GetVisibleRegion().IsEmpty()) { // When our visible region is empty, our parent may not have created the // intermediate surface that we would require for correct clipping; however, // this does not matter since we are invisible. return RenderTargetIntRect(currentClip.TopLeft(), RenderTargetIntSize(0, 0)); } const RenderTargetIntRect clipRect = ViewAs<RenderTargetPixel>(*clipLayer->GetEffectiveClipRect(), PixelCastJustification::RenderTargetIsParentLayerForRoot); if (clipRect.IsEmpty()) { // We might have a non-translation transform in the container so we can't // use the code path below. return RenderTargetIntRect(currentClip.TopLeft(), RenderTargetIntSize(0, 0)); } RenderTargetIntRect scissor = clipRect; if (!container->UseIntermediateSurface()) { gfx::Matrix matrix; DebugOnly<bool> is2D = container->GetEffectiveTransform().Is2D(&matrix); // See DefaultComputeEffectiveTransforms below NS_ASSERTION(is2D && matrix.PreservesAxisAlignedRectangles(), "Non preserves axis aligned transform with clipped child should have forced intermediate surface"); gfx::Rect r(scissor.x, scissor.y, scissor.width, scissor.height); gfxRect trScissor = gfx::ThebesRect(matrix.TransformBounds(r)); trScissor.Round(); IntRect tmp; if (!gfxUtils::GfxRectToIntRect(trScissor, &tmp)) { return RenderTargetIntRect(currentClip.TopLeft(), RenderTargetIntSize(0, 0)); } scissor = ViewAs<RenderTargetPixel>(tmp); // Find the nearest ancestor with an intermediate surface do { container = container->GetParent(); } while (container && !container->UseIntermediateSurface()); } if (container) { scissor.MoveBy(-container->GetIntermediateSurfaceRect().TopLeft()); } return currentClip.Intersect(scissor); } const FrameMetrics& Layer::GetFrameMetrics(uint32_t aIndex) const { MOZ_ASSERT(aIndex < GetFrameMetricsCount()); return mFrameMetrics[aIndex]; } bool Layer::HasScrollableFrameMetrics() const { for (uint32_t i = 0; i < GetFrameMetricsCount(); i++) { if (GetFrameMetrics(i).IsScrollable()) { return true; } } return false; } bool Layer::IsScrollInfoLayer() const { // A scrollable container layer with no children return AsContainerLayer() && HasScrollableFrameMetrics() && !GetFirstChild(); } const Matrix4x4 Layer::GetTransform() const { Matrix4x4 transform = mTransform; transform.PostScale(GetPostXScale(), GetPostYScale(), 1.0f); if (const ContainerLayer* c = AsContainerLayer()) { transform.PreScale(c->GetPreXScale(), c->GetPreYScale(), 1.0f); } return transform; } const CSSTransformMatrix Layer::GetTransformTyped() const { return ViewAs<CSSTransformMatrix>(GetTransform()); } const Matrix4x4 Layer::GetLocalTransform() { Matrix4x4 transform; if (LayerComposite* shadow = AsLayerComposite()) transform = shadow->GetShadowTransform(); else transform = mTransform; transform.PostScale(GetPostXScale(), GetPostYScale(), 1.0f); if (ContainerLayer* c = AsContainerLayer()) { transform.PreScale(c->GetPreXScale(), c->GetPreYScale(), 1.0f); } return transform; } const LayerToParentLayerMatrix4x4 Layer::GetLocalTransformTyped() { return ViewAs<LayerToParentLayerMatrix4x4>(GetLocalTransform()); } bool Layer::HasTransformAnimation() const { for (uint32_t i = 0; i < mAnimations.Length(); i++) { if (mAnimations[i].property() == eCSSProperty_transform) { return true; } } return false; } void Layer::ApplyPendingUpdatesForThisTransaction() { if (mPendingTransform && *mPendingTransform != mTransform) { MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) PendingUpdatesForThisTransaction", this)); mTransform = *mPendingTransform; Mutated(); } mPendingTransform = nullptr; if (mPendingAnimations) { MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) PendingUpdatesForThisTransaction", this)); mPendingAnimations->SwapElements(mAnimations); mPendingAnimations = nullptr; Mutated(); } } float Layer::GetLocalOpacity() { float opacity = mOpacity; if (LayerComposite* shadow = AsLayerComposite()) opacity = shadow->GetShadowOpacity(); return std::min(std::max(opacity, 0.0f), 1.0f); } float Layer::GetEffectiveOpacity() { float opacity = GetLocalOpacity(); for (ContainerLayer* c = GetParent(); c && !c->UseIntermediateSurface(); c = c->GetParent()) { opacity *= c->GetLocalOpacity(); } return opacity; } CompositionOp Layer::GetEffectiveMixBlendMode() { if(mMixBlendMode != CompositionOp::OP_OVER) return mMixBlendMode; for (ContainerLayer* c = GetParent(); c && !c->UseIntermediateSurface(); c = c->GetParent()) { if(c->mMixBlendMode != CompositionOp::OP_OVER) return c->mMixBlendMode; } return mMixBlendMode; } void Layer::ComputeEffectiveTransformForMaskLayers(const gfx::Matrix4x4& aTransformToSurface) { if (GetMaskLayer()) { ComputeEffectiveTransformForMaskLayer(GetMaskLayer(), aTransformToSurface); } for (size_t i = 0; i < GetAncestorMaskLayerCount(); i++) { Layer* maskLayer = GetAncestorMaskLayerAt(i); ComputeEffectiveTransformForMaskLayer(maskLayer, aTransformToSurface); } } /* static */ void Layer::ComputeEffectiveTransformForMaskLayer(Layer* aMaskLayer, const gfx::Matrix4x4& aTransformToSurface) { aMaskLayer->mEffectiveTransform = aTransformToSurface; #ifdef DEBUG bool maskIs2D = aMaskLayer->GetTransform().CanDraw2D(); NS_ASSERTION(maskIs2D, "How did we end up with a 3D transform here?!"); #endif // The mask layer can have an async transform applied to it in some // situations, so be sure to use its GetLocalTransform() rather than // its GetTransform(). aMaskLayer->mEffectiveTransform = aMaskLayer->GetLocalTransform() * aMaskLayer->mEffectiveTransform; } RenderTargetRect Layer::TransformRectToRenderTarget(const LayerIntRect& aRect) { LayerRect rect(aRect); RenderTargetRect quad = RenderTargetRect::FromUnknownRect( GetEffectiveTransform().TransformBounds(rect.ToUnknownRect())); return quad; } bool Layer::GetVisibleRegionRelativeToRootLayer(nsIntRegion& aResult, nsIntPoint* aLayerOffset) { MOZ_ASSERT(aLayerOffset, "invalid offset pointer"); if (!GetParent()) { return false; } IntPoint offset; aResult = GetEffectiveVisibleRegion().ToUnknownRegion(); for (Layer* layer = this; layer; layer = layer->GetParent()) { gfx::Matrix matrix; if (!layer->GetLocalTransform().Is2D(&matrix) || !matrix.IsTranslation()) { return false; } // The offset of |layer| to its parent. IntPoint currentLayerOffset = RoundedToInt(matrix.GetTranslation()); // Translate the accumulated visible region of |this| by the offset of // |layer|. aResult.MoveBy(currentLayerOffset.x, currentLayerOffset.y); // If the parent layer clips its lower layers, clip the visible region // we're accumulating. if (layer->GetEffectiveClipRect()) { aResult.AndWith(layer->GetEffectiveClipRect()->ToUnknownRect()); } // Now we need to walk across the list of siblings for this parent layer, // checking to see if any of these layer trees obscure |this|. If so, // remove these areas from the visible region as well. This will pick up // chrome overlays like a tab modal prompt. Layer* sibling; for (sibling = layer->GetNextSibling(); sibling; sibling = sibling->GetNextSibling()) { gfx::Matrix siblingMatrix; if (!sibling->GetLocalTransform().Is2D(&siblingMatrix) || !siblingMatrix.IsTranslation()) { return false; } // Retreive the translation from sibling to |layer|. The accumulated // visible region is currently oriented with |layer|. IntPoint siblingOffset = RoundedToInt(siblingMatrix.GetTranslation()); nsIntRegion siblingVisibleRegion(sibling->GetEffectiveVisibleRegion().ToUnknownRegion()); // Translate the siblings region to |layer|'s origin. siblingVisibleRegion.MoveBy(-siblingOffset.x, -siblingOffset.y); // Apply the sibling's clip. // Layer clip rects are not affected by the layer's transform. Maybe<ParentLayerIntRect> clipRect = sibling->GetEffectiveClipRect(); if (clipRect) { siblingVisibleRegion.AndWith(clipRect->ToUnknownRect()); } // Subtract the sibling visible region from the visible region of |this|. aResult.SubOut(siblingVisibleRegion); } // Keep track of the total offset for aLayerOffset. We use this in plugin // positioning code. offset += currentLayerOffset; } *aLayerOffset = nsIntPoint(offset.x, offset.y); return true; } Maybe<ParentLayerIntRect> Layer::GetCombinedClipRect() const { Maybe<ParentLayerIntRect> clip = GetClipRect(); for (size_t i = 0; i < mFrameMetrics.Length(); i++) { if (!mFrameMetrics[i].HasClipRect()) { continue; } const ParentLayerIntRect& other = mFrameMetrics[i].ClipRect(); if (clip) { clip = Some(clip.value().Intersect(other)); } else { clip = Some(other); } } return clip; } ContainerLayer::ContainerLayer(LayerManager* aManager, void* aImplData) : Layer(aManager, aImplData), mFirstChild(nullptr), mLastChild(nullptr), mPreXScale(1.0f), mPreYScale(1.0f), mInheritedXScale(1.0f), mInheritedYScale(1.0f), mPresShellResolution(1.0f), mScaleToResolution(false), mUseIntermediateSurface(false), mSupportsComponentAlphaChildren(false), mMayHaveReadbackChild(false), mChildrenChanged(false), mEventRegionsOverride(EventRegionsOverride::NoOverride), mVRDeviceID(0) { MOZ_COUNT_CTOR(ContainerLayer); mContentFlags = 0; // Clear NO_TEXT, NO_TEXT_OVER_TRANSPARENT } ContainerLayer::~ContainerLayer() { MOZ_COUNT_DTOR(ContainerLayer); } bool ContainerLayer::InsertAfter(Layer* aChild, Layer* aAfter) { if(aChild->Manager() != Manager()) { NS_ERROR("Child has wrong manager"); return false; } if(aChild->GetParent()) { NS_ERROR("aChild already in the tree"); return false; } if (aChild->GetNextSibling() || aChild->GetPrevSibling()) { NS_ERROR("aChild already has siblings?"); return false; } if (aAfter && (aAfter->Manager() != Manager() || aAfter->GetParent() != this)) { NS_ERROR("aAfter is not our child"); return false; } aChild->SetParent(this); if (aAfter == mLastChild) { mLastChild = aChild; } if (!aAfter) { aChild->SetNextSibling(mFirstChild); if (mFirstChild) { mFirstChild->SetPrevSibling(aChild); } mFirstChild = aChild; NS_ADDREF(aChild); DidInsertChild(aChild); return true; } Layer* next = aAfter->GetNextSibling(); aChild->SetNextSibling(next); aChild->SetPrevSibling(aAfter); if (next) { next->SetPrevSibling(aChild); } aAfter->SetNextSibling(aChild); NS_ADDREF(aChild); DidInsertChild(aChild); return true; } bool ContainerLayer::RemoveChild(Layer *aChild) { if (aChild->Manager() != Manager()) { NS_ERROR("Child has wrong manager"); return false; } if (aChild->GetParent() != this) { NS_ERROR("aChild not our child"); return false; } Layer* prev = aChild->GetPrevSibling(); Layer* next = aChild->GetNextSibling(); if (prev) { prev->SetNextSibling(next); } else { this->mFirstChild = next; } if (next) { next->SetPrevSibling(prev); } else { this->mLastChild = prev; } aChild->SetNextSibling(nullptr); aChild->SetPrevSibling(nullptr); aChild->SetParent(nullptr); this->DidRemoveChild(aChild); NS_RELEASE(aChild); return true; } bool ContainerLayer::RepositionChild(Layer* aChild, Layer* aAfter) { if (aChild->Manager() != Manager()) { NS_ERROR("Child has wrong manager"); return false; } if (aChild->GetParent() != this) { NS_ERROR("aChild not our child"); return false; } if (aAfter && (aAfter->Manager() != Manager() || aAfter->GetParent() != this)) { NS_ERROR("aAfter is not our child"); return false; } if (aChild == aAfter) { NS_ERROR("aChild cannot be the same as aAfter"); return false; } Layer* prev = aChild->GetPrevSibling(); Layer* next = aChild->GetNextSibling(); if (prev == aAfter) { // aChild is already in the correct position, nothing to do. return true; } if (prev) { prev->SetNextSibling(next); } else { mFirstChild = next; } if (next) { next->SetPrevSibling(prev); } else { mLastChild = prev; } if (!aAfter) { aChild->SetPrevSibling(nullptr); aChild->SetNextSibling(mFirstChild); if (mFirstChild) { mFirstChild->SetPrevSibling(aChild); } mFirstChild = aChild; return true; } Layer* afterNext = aAfter->GetNextSibling(); if (afterNext) { afterNext->SetPrevSibling(aChild); } else { mLastChild = aChild; } aAfter->SetNextSibling(aChild); aChild->SetPrevSibling(aAfter); aChild->SetNextSibling(afterNext); return true; } void ContainerLayer::FillSpecificAttributes(SpecificLayerAttributes& aAttrs) { aAttrs = ContainerLayerAttributes(mPreXScale, mPreYScale, mInheritedXScale, mInheritedYScale, mPresShellResolution, mScaleToResolution, mEventRegionsOverride, mVRDeviceID); } bool ContainerLayer::Creates3DContextWithExtendingChildren() { if (Extend3DContext()) { return false; } for (Layer* child = GetFirstChild(); child; child = child->GetNextSibling()) { if (child->Extend3DContext()) { return true; } } return false; } bool ContainerLayer::HasMultipleChildren() { uint32_t count = 0; for (Layer* child = GetFirstChild(); child; child = child->GetNextSibling()) { const Maybe<ParentLayerIntRect>& clipRect = child->GetEffectiveClipRect(); if (clipRect && clipRect->IsEmpty()) continue; if (child->GetVisibleRegion().IsEmpty()) continue; ++count; if (count > 1) return true; } return false; } /** * Collect all leaf descendants of the current 3D context. */ void ContainerLayer::Collect3DContextLeaves(nsTArray<Layer*>& aToSort) { for (Layer* l = GetFirstChild(); l; l = l->GetNextSibling()) { ContainerLayer* container = l->AsContainerLayer(); if (container && container->Extend3DContext() && !container->UseIntermediateSurface()) { container->Collect3DContextLeaves(aToSort); } else { aToSort.AppendElement(l); } } } void ContainerLayer::SortChildrenBy3DZOrder(nsTArray<Layer*>& aArray) { nsAutoTArray<Layer*, 10> toSort; for (Layer* l = GetFirstChild(); l; l = l->GetNextSibling()) { ContainerLayer* container = l->AsContainerLayer(); if (container && container->Extend3DContext() && !container->UseIntermediateSurface()) { container->Collect3DContextLeaves(toSort); } else { if (toSort.Length() > 0) { SortLayersBy3DZOrder(toSort); aArray.AppendElements(Move(toSort)); // XXX The move analysis gets confused here, because toSort gets moved // here, and then gets used again outside of the loop. To clarify that // we realize that the array is going to be empty to the move checker, // we clear it again here. (This method renews toSort for the move // analysis) toSort.ClearAndRetainStorage(); } aArray.AppendElement(l); } } if (toSort.Length() > 0) { SortLayersBy3DZOrder(toSort); aArray.AppendElements(Move(toSort)); } } void ContainerLayer::DefaultComputeEffectiveTransforms(const Matrix4x4& aTransformToSurface) { Matrix residual; Matrix4x4 idealTransform = GetLocalTransform() * aTransformToSurface; // Keep 3D transforms for leaves to keep z-order sorting correct. if (!Extend3DContext() && !Is3DContextLeaf()) { idealTransform.ProjectTo2D(); } bool useIntermediateSurface; if (HasMaskLayers() || GetForceIsolatedGroup()) { useIntermediateSurface = true; #ifdef MOZ_DUMP_PAINTING } else if (gfxEnv::DumpPaintIntermediate() && !Extend3DContext()) { useIntermediateSurface = true; #endif } else { float opacity = GetEffectiveOpacity(); CompositionOp blendMode = GetEffectiveMixBlendMode(); if (((opacity != 1.0f || blendMode != CompositionOp::OP_OVER) && (HasMultipleChildren() || Creates3DContextWithExtendingChildren())) || (!idealTransform.Is2D() && Creates3DContextWithExtendingChildren())) { useIntermediateSurface = true; } else { useIntermediateSurface = false; gfx::Matrix contTransform; bool checkClipRect = false; bool checkMaskLayers = false; if (!idealTransform.Is2D(&contTransform)) { // In 3D case, always check if we should use IntermediateSurface. checkClipRect = true; checkMaskLayers = true; } else { #ifdef MOZ_GFX_OPTIMIZE_MOBILE if (!contTransform.PreservesAxisAlignedRectangles()) { #else if (gfx::ThebesMatrix(contTransform).HasNonIntegerTranslation()) { #endif checkClipRect = true; } /* In 2D case, only translation and/or positive scaling can be done w/o using IntermediateSurface. * Otherwise, when rotation or flip happen, we should check whether to use IntermediateSurface. */ if (contTransform.HasNonAxisAlignedTransform() || contTransform.HasNegativeScaling()) { checkMaskLayers = true; } } if (checkClipRect || checkMaskLayers) { for (Layer* child = GetFirstChild(); child; child = child->GetNextSibling()) { const Maybe<ParentLayerIntRect>& clipRect = child->GetEffectiveClipRect(); /* We can't (easily) forward our transform to children with a non-empty clip * rect since it would need to be adjusted for the transform. See * the calculations performed by CalculateScissorRect above. * Nor for a child with a mask layer. */ if (checkClipRect && (clipRect && !clipRect->IsEmpty() && !child->GetVisibleRegion().IsEmpty())) { useIntermediateSurface = true; break; } if (checkMaskLayers && child->HasMaskLayers()) { useIntermediateSurface = true; break; } } } } } if (useIntermediateSurface) { mEffectiveTransform = SnapTransformTranslation(idealTransform, &residual); } else { mEffectiveTransform = idealTransform; } // For layers extending 3d context, its ideal transform should be // applied on children. if (!Extend3DContext()) { // Without this projection, non-container children would get a 3D // transform while 2D is expected. idealTransform.ProjectTo2D(); } mUseIntermediateSurface = useIntermediateSurface && !GetEffectiveVisibleRegion().IsEmpty(); if (useIntermediateSurface) { ComputeEffectiveTransformsForChildren(Matrix4x4::From2D(residual)); } else { ComputeEffectiveTransformsForChildren(idealTransform); } if (idealTransform.CanDraw2D()) { ComputeEffectiveTransformForMaskLayers(aTransformToSurface); } else { ComputeEffectiveTransformForMaskLayers(Matrix4x4()); } } void ContainerLayer::DefaultComputeSupportsComponentAlphaChildren(bool* aNeedsSurfaceCopy) { if (!(GetContentFlags() & Layer::CONTENT_COMPONENT_ALPHA_DESCENDANT) || !Manager()->AreComponentAlphaLayersEnabled()) { mSupportsComponentAlphaChildren = false; if (aNeedsSurfaceCopy) { *aNeedsSurfaceCopy = false; } return; } mSupportsComponentAlphaChildren = false; bool needsSurfaceCopy = false; CompositionOp blendMode = GetEffectiveMixBlendMode(); if (UseIntermediateSurface()) { if (GetEffectiveVisibleRegion().GetNumRects() == 1 && (GetContentFlags() & Layer::CONTENT_OPAQUE)) { mSupportsComponentAlphaChildren = true; } else { gfx::Matrix transform; if (HasOpaqueAncestorLayer(this) && GetEffectiveTransform().Is2D(&transform) && !gfx::ThebesMatrix(transform).HasNonIntegerTranslation() && blendMode == gfx::CompositionOp::OP_OVER) { mSupportsComponentAlphaChildren = true; needsSurfaceCopy = true; } } } else if (blendMode == gfx::CompositionOp::OP_OVER) { mSupportsComponentAlphaChildren = (GetContentFlags() & Layer::CONTENT_OPAQUE) || (GetParent() && GetParent()->SupportsComponentAlphaChildren()); } if (aNeedsSurfaceCopy) { *aNeedsSurfaceCopy = mSupportsComponentAlphaChildren && needsSurfaceCopy; } } void ContainerLayer::ComputeEffectiveTransformsForChildren(const Matrix4x4& aTransformToSurface) { for (Layer* l = mFirstChild; l; l = l->GetNextSibling()) { l->ComputeEffectiveTransforms(aTransformToSurface); } } /* static */ bool ContainerLayer::HasOpaqueAncestorLayer(Layer* aLayer) { for (Layer* l = aLayer->GetParent(); l; l = l->GetParent()) { if (l->GetContentFlags() & Layer::CONTENT_OPAQUE) return true; } return false; } void ContainerLayer::DidRemoveChild(Layer* aLayer) { PaintedLayer* tl = aLayer->AsPaintedLayer(); if (tl && tl->UsedForReadback()) { for (Layer* l = mFirstChild; l; l = l->GetNextSibling()) { if (l->GetType() == TYPE_READBACK) { static_cast<ReadbackLayer*>(l)->NotifyPaintedLayerRemoved(tl); } } } if (aLayer->GetType() == TYPE_READBACK) { static_cast<ReadbackLayer*>(aLayer)->NotifyRemoved(); } } void ContainerLayer::DidInsertChild(Layer* aLayer) { if (aLayer->GetType() == TYPE_READBACK) { mMayHaveReadbackChild = true; } } void RefLayer::FillSpecificAttributes(SpecificLayerAttributes& aAttrs) { aAttrs = RefLayerAttributes(GetReferentId(), mEventRegionsOverride); } /** * StartFrameTimeRecording, together with StopFrameTimeRecording * enable recording of frame intervals. * * To allow concurrent consumers, a cyclic array is used which serves all * consumers, practically stateless with regard to consumers. * * To save resources, the buffer is allocated on first call to StartFrameTimeRecording * and recording is paused if no consumer which called StartFrameTimeRecording is able * to get valid results (because the cyclic buffer was overwritten since that call). * * To determine availability of the data upon StopFrameTimeRecording: * - mRecording.mNextIndex increases on each PostPresent, and never resets. * - Cyclic buffer position is realized as mNextIndex % bufferSize. * - StartFrameTimeRecording returns mNextIndex. When StopFrameTimeRecording is called, * the required start index is passed as an arg, and we're able to calculate the required * length. If this length is bigger than bufferSize, it means data was overwritten. * otherwise, we can return the entire sequence. * - To determine if we need to pause, mLatestStartIndex is updated to mNextIndex * on each call to StartFrameTimeRecording. If this index gets overwritten, * it means that all earlier start indices obtained via StartFrameTimeRecording * were also overwritten, hence, no point in recording, so pause. * - mCurrentRunStartIndex indicates the oldest index of the recording after which * the recording was not paused. If StopFrameTimeRecording is invoked with a start index * older than this, it means that some frames were not recorded, so data is invalid. */ uint32_t LayerManager::StartFrameTimeRecording(int32_t aBufferSize) { if (mRecording.mIsPaused) { mRecording.mIsPaused = false; if (!mRecording.mIntervals.Length()) { // Initialize recording buffers mRecording.mIntervals.SetLength(aBufferSize); } // After being paused, recent values got invalid. Update them to now. mRecording.mLastFrameTime = TimeStamp::Now(); // Any recording which started before this is invalid, since we were paused. mRecording.mCurrentRunStartIndex = mRecording.mNextIndex; } // If we'll overwrite this index, there are no more consumers with aStartIndex // for which we're able to provide the full recording, so no point in keep recording. mRecording.mLatestStartIndex = mRecording.mNextIndex; return mRecording.mNextIndex; } void LayerManager::RecordFrame() { if (!mRecording.mIsPaused) { TimeStamp now = TimeStamp::Now(); uint32_t i = mRecording.mNextIndex % mRecording.mIntervals.Length(); mRecording.mIntervals[i] = static_cast<float>((now - mRecording.mLastFrameTime) .ToMilliseconds()); mRecording.mNextIndex++; mRecording.mLastFrameTime = now; if (mRecording.mNextIndex > (mRecording.mLatestStartIndex + mRecording.mIntervals.Length())) { // We've just overwritten the most recent recording start -> pause. mRecording.mIsPaused = true; } } } void LayerManager::PostPresent() { if (!mTabSwitchStart.IsNull()) { Telemetry::Accumulate(Telemetry::FX_TAB_SWITCH_TOTAL_MS, uint32_t((TimeStamp::Now() - mTabSwitchStart).ToMilliseconds())); mTabSwitchStart = TimeStamp(); } } void LayerManager::StopFrameTimeRecording(uint32_t aStartIndex, nsTArray<float>& aFrameIntervals) { uint32_t bufferSize = mRecording.mIntervals.Length(); uint32_t length = mRecording.mNextIndex - aStartIndex; if (mRecording.mIsPaused || length > bufferSize || aStartIndex < mRecording.mCurrentRunStartIndex) { // aStartIndex is too old. Also if aStartIndex was issued before mRecordingNextIndex overflowed (uint32_t) // and stopped after the overflow (would happen once every 828 days of constant 60fps). length = 0; } if (!length) { aFrameIntervals.Clear(); return; // empty recording, return empty arrays. } // Set length in advance to avoid possibly repeated reallocations aFrameIntervals.SetLength(length); uint32_t cyclicPos = aStartIndex % bufferSize; for (uint32_t i = 0; i < length; i++, cyclicPos++) { if (cyclicPos == bufferSize) { cyclicPos = 0; } aFrameIntervals[i] = mRecording.mIntervals[cyclicPos]; } } void LayerManager::BeginTabSwitch() { mTabSwitchStart = TimeStamp::Now(); } static void PrintInfo(std::stringstream& aStream, LayerComposite* aLayerComposite); #ifdef MOZ_DUMP_PAINTING template <typename T> void WriteSnapshotToDumpFile_internal(T* aObj, DataSourceSurface* aSurf) { nsCString string(aObj->Name()); string.Append('-'); string.AppendInt((uint64_t)aObj); if (gfxUtils::sDumpPaintFile != stderr) { fprintf_stderr(gfxUtils::sDumpPaintFile, "array[\"%s\"]=\"", string.BeginReading()); } gfxUtils::DumpAsDataURI(aSurf, gfxUtils::sDumpPaintFile); if (gfxUtils::sDumpPaintFile != stderr) { fprintf_stderr(gfxUtils::sDumpPaintFile, "\";"); } } void WriteSnapshotToDumpFile(Layer* aLayer, DataSourceSurface* aSurf) { WriteSnapshotToDumpFile_internal(aLayer, aSurf); } void WriteSnapshotToDumpFile(LayerManager* aManager, DataSourceSurface* aSurf) { WriteSnapshotToDumpFile_internal(aManager, aSurf); } void WriteSnapshotToDumpFile(Compositor* aCompositor, DrawTarget* aTarget) { RefPtr<SourceSurface> surf = aTarget->Snapshot(); RefPtr<DataSourceSurface> dSurf = surf->GetDataSurface(); WriteSnapshotToDumpFile_internal(aCompositor, dSurf); } #endif void Layer::Dump(std::stringstream& aStream, const char* aPrefix, bool aDumpHtml) { #ifdef MOZ_DUMP_PAINTING bool dumpCompositorTexture = gfxEnv::DumpCompositorTextures() && AsLayerComposite() && AsLayerComposite()->GetCompositableHost(); bool dumpClientTexture = gfxEnv::DumpPaint() && AsShadowableLayer() && AsShadowableLayer()->GetCompositableClient(); nsCString layerId(Name()); layerId.Append('-'); layerId.AppendInt((uint64_t)this); #endif if (aDumpHtml) { aStream << nsPrintfCString("<li><a id=\"%p\" ", this).get(); #ifdef MOZ_DUMP_PAINTING if (dumpCompositorTexture || dumpClientTexture) { aStream << nsPrintfCString("href=\"javascript:ViewImage('%s')\"", layerId.BeginReading()).get(); } #endif aStream << ">"; } DumpSelf(aStream, aPrefix); #ifdef MOZ_DUMP_PAINTING if (dumpCompositorTexture) { AsLayerComposite()->GetCompositableHost()->Dump(aStream, aPrefix, aDumpHtml); } else if (dumpClientTexture) { if (aDumpHtml) { aStream << nsPrintfCString("<script>array[\"%s\"]=\"", layerId.BeginReading()).get(); } AsShadowableLayer()->GetCompositableClient()->Dump(aStream, aPrefix, aDumpHtml, TextureDumpMode::DoNotCompress); if (aDumpHtml) { aStream << "\";</script>"; } } #endif if (aDumpHtml) { aStream << "</a>"; #ifdef MOZ_DUMP_PAINTING if (dumpClientTexture) { aStream << nsPrintfCString("<br><img id=\"%s\">\n", layerId.BeginReading()).get(); } #endif } if (Layer* mask = GetMaskLayer()) { aStream << nsPrintfCString("%s Mask layer:\n", aPrefix).get(); nsAutoCString pfx(aPrefix); pfx += " "; mask->Dump(aStream, pfx.get(), aDumpHtml); } for (size_t i = 0; i < GetAncestorMaskLayerCount(); i++) { aStream << nsPrintfCString("%s Ancestor mask layer %d:\n", aPrefix, uint32_t(i)).get(); nsAutoCString pfx(aPrefix); pfx += " "; GetAncestorMaskLayerAt(i)->Dump(aStream, pfx.get(), aDumpHtml); } #ifdef MOZ_DUMP_PAINTING for (size_t i = 0; i < mExtraDumpInfo.Length(); i++) { const nsCString& str = mExtraDumpInfo[i]; aStream << aPrefix << " Info:\n" << str.get(); } #endif if (Layer* kid = GetFirstChild()) { nsAutoCString pfx(aPrefix); pfx += " "; if (aDumpHtml) { aStream << "<ul>"; } kid->Dump(aStream, pfx.get(), aDumpHtml); if (aDumpHtml) { aStream << "</ul>"; } } if (aDumpHtml) { aStream << "</li>"; } if (Layer* next = GetNextSibling()) next->Dump(aStream, aPrefix, aDumpHtml); } void Layer::DumpSelf(std::stringstream& aStream, const char* aPrefix) { PrintInfo(aStream, aPrefix); aStream << "\n"; } void Layer::Dump(layerscope::LayersPacket* aPacket, const void* aParent) { DumpPacket(aPacket, aParent); if (Layer* kid = GetFirstChild()) { kid->Dump(aPacket, this); } if (Layer* next = GetNextSibling()) { next->Dump(aPacket, aParent); } } void Layer::SetDisplayListLog(const char* log) { if (gfxUtils::DumpDisplayList()) { mDisplayListLog = log; } } void Layer::GetDisplayListLog(nsCString& log) { log.SetLength(0); if (gfxUtils::DumpDisplayList()) { // This function returns a plain text string which consists of two things // 1. DisplayList log. // 2. Memory address of this layer. // We know the target layer of each display item by information in #1. // Here is an example of a Text display item line log in #1 // Text p=0xa9850c00 f=0x0xaa405b00(..... // f keeps the address of the target client layer of a display item. // For LayerScope, display-item-to-client-layer mapping is not enough since // LayerScope, which lives in the chrome process, knows only composite layers. // As so, we need display-item-to-client-layer-to-layer-composite // mapping. That's the reason we insert #2 into the log log.AppendPrintf("0x%p\n%s",(void*) this, mDisplayListLog.get()); } } void Layer::Log(const char* aPrefix) { if (!IsLogEnabled()) return; LogSelf(aPrefix); if (Layer* kid = GetFirstChild()) { nsAutoCString pfx(aPrefix); pfx += " "; kid->Log(pfx.get()); } if (Layer* next = GetNextSibling()) next->Log(aPrefix); } void Layer::LogSelf(const char* aPrefix) { if (!IsLogEnabled()) return; std::stringstream ss; PrintInfo(ss, aPrefix); MOZ_LAYERS_LOG(("%s", ss.str().c_str())); if (mMaskLayer) { nsAutoCString pfx(aPrefix); pfx += " \\ MaskLayer "; mMaskLayer->LogSelf(pfx.get()); } } void Layer::PrintInfo(std::stringstream& aStream, const char* aPrefix) { aStream << aPrefix; aStream << nsPrintfCString("%s%s (0x%p)", mManager->Name(), Name(), this).get(); layers::PrintInfo(aStream, AsLayerComposite()); if (mClipRect) { AppendToString(aStream, *mClipRect, " [clip=", "]"); } if (1.0 != mPostXScale || 1.0 != mPostYScale) { aStream << nsPrintfCString(" [postScale=%g, %g]", mPostXScale, mPostYScale).get(); } if (!mTransform.IsIdentity()) { AppendToString(aStream, mTransform, " [transform=", "]"); } if (!GetEffectiveTransform().IsIdentity()) { AppendToString(aStream, GetEffectiveTransform(), " [effective-transform=", "]"); } if (mTransformIsPerspective) { aStream << " [perspective]"; } if (!mLayerBounds.IsEmpty()) { AppendToString(aStream, mLayerBounds, " [bounds=", "]"); } if (!mVisibleRegion.IsEmpty()) { AppendToString(aStream, mVisibleRegion.ToUnknownRegion(), " [visible=", "]"); } else { aStream << " [not visible]"; } if (!mEventRegions.IsEmpty()) { AppendToString(aStream, mEventRegions, " ", ""); } if (1.0 != mOpacity) { aStream << nsPrintfCString(" [opacity=%g]", mOpacity).get(); } if (GetContentFlags() & CONTENT_OPAQUE) { aStream << " [opaqueContent]"; } if (GetContentFlags() & CONTENT_COMPONENT_ALPHA) { aStream << " [componentAlpha]"; } if (GetContentFlags() & CONTENT_BACKFACE_HIDDEN) { aStream << " [backfaceHidden]"; } if (GetScrollbarDirection() == VERTICAL) { aStream << nsPrintfCString(" [vscrollbar=%lld]", GetScrollbarTargetContainerId()).get(); } if (GetScrollbarDirection() == HORIZONTAL) { aStream << nsPrintfCString(" [hscrollbar=%lld]", GetScrollbarTargetContainerId()).get(); } if (GetIsFixedPosition()) { LayerPoint anchor = GetFixedPositionAnchor(); aStream << nsPrintfCString(" [isFixedPosition scrollId=%lld sides=0x%x anchor=%s%s]", GetFixedPositionScrollContainerId(), GetFixedPositionSides(), ToString(anchor).c_str(), IsClipFixed() ? "" : " scrollingClip").get(); } if (GetIsStickyPosition()) { aStream << nsPrintfCString(" [isStickyPosition scrollId=%d outer=%f,%f %fx%f " "inner=%f,%f %fx%f]", mStickyPositionData->mScrollId, mStickyPositionData->mOuter.x, mStickyPositionData->mOuter.y, mStickyPositionData->mOuter.width, mStickyPositionData->mOuter.height, mStickyPositionData->mInner.x, mStickyPositionData->mInner.y, mStickyPositionData->mInner.width, mStickyPositionData->mInner.height).get(); } if (mMaskLayer) { aStream << nsPrintfCString(" [mMaskLayer=%p]", mMaskLayer.get()).get(); } for (uint32_t i = 0; i < mFrameMetrics.Length(); i++) { if (!mFrameMetrics[i].IsDefault()) { aStream << nsPrintfCString(" [metrics%d=", i).get(); AppendToString(aStream, mFrameMetrics[i], "", "]"); } } } // The static helper function sets the transform matrix into the packet static void DumpTransform(layerscope::LayersPacket::Layer::Matrix* aLayerMatrix, const Matrix4x4& aMatrix) { aLayerMatrix->set_is2d(aMatrix.Is2D()); if (aMatrix.Is2D()) { Matrix m = aMatrix.As2D(); aLayerMatrix->set_isid(m.IsIdentity()); if (!m.IsIdentity()) { aLayerMatrix->add_m(m._11), aLayerMatrix->add_m(m._12); aLayerMatrix->add_m(m._21), aLayerMatrix->add_m(m._22); aLayerMatrix->add_m(m._31), aLayerMatrix->add_m(m._32); } } else { aLayerMatrix->add_m(aMatrix._11), aLayerMatrix->add_m(aMatrix._12); aLayerMatrix->add_m(aMatrix._13), aLayerMatrix->add_m(aMatrix._14); aLayerMatrix->add_m(aMatrix._21), aLayerMatrix->add_m(aMatrix._22); aLayerMatrix->add_m(aMatrix._23), aLayerMatrix->add_m(aMatrix._24); aLayerMatrix->add_m(aMatrix._31), aLayerMatrix->add_m(aMatrix._32); aLayerMatrix->add_m(aMatrix._33), aLayerMatrix->add_m(aMatrix._34); aLayerMatrix->add_m(aMatrix._41), aLayerMatrix->add_m(aMatrix._42); aLayerMatrix->add_m(aMatrix._43), aLayerMatrix->add_m(aMatrix._44); } } // The static helper function sets the IntRect into the packet template <typename T, typename Sub, typename Point, typename SizeT, typename MarginT> static void DumpRect(layerscope::LayersPacket::Layer::Rect* aLayerRect, const BaseRect<T, Sub, Point, SizeT, MarginT>& aRect) { aLayerRect->set_x(aRect.x); aLayerRect->set_y(aRect.y); aLayerRect->set_w(aRect.width); aLayerRect->set_h(aRect.height); } // The static helper function sets the nsIntRegion into the packet static void DumpRegion(layerscope::LayersPacket::Layer::Region* aLayerRegion, const nsIntRegion& aRegion) { nsIntRegionRectIterator it(aRegion); while (const IntRect* sr = it.Next()) { DumpRect(aLayerRegion->add_r(), *sr); } } void Layer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) { // Add a new layer (UnknownLayer) using namespace layerscope; LayersPacket::Layer* layer = aPacket->add_layer(); // Basic information layer->set_type(LayersPacket::Layer::UnknownLayer); layer->set_ptr(reinterpret_cast<uint64_t>(this)); layer->set_parentptr(reinterpret_cast<uint64_t>(aParent)); // Shadow if (LayerComposite* lc = AsLayerComposite()) { LayersPacket::Layer::Shadow* s = layer->mutable_shadow(); if (const Maybe<ParentLayerIntRect>& clipRect = lc->GetShadowClipRect()) { DumpRect(s->mutable_clip(), *clipRect); } if (!lc->GetShadowTransform().IsIdentity()) { DumpTransform(s->mutable_transform(), lc->GetShadowTransform()); } if (!lc->GetShadowVisibleRegion().IsEmpty()) { DumpRegion(s->mutable_vregion(), lc->GetShadowVisibleRegion().ToUnknownRegion()); } } // Clip if (mClipRect) { DumpRect(layer->mutable_clip(), *mClipRect); } // Transform if (!mTransform.IsIdentity()) { DumpTransform(layer->mutable_transform(), mTransform); } // Visible region if (!mVisibleRegion.ToUnknownRegion().IsEmpty()) { DumpRegion(layer->mutable_vregion(), mVisibleRegion.ToUnknownRegion()); } // EventRegions if (!mEventRegions.IsEmpty()) { const EventRegions &e = mEventRegions; if (!e.mHitRegion.IsEmpty()) { DumpRegion(layer->mutable_hitregion(), e.mHitRegion); } if (!e.mDispatchToContentHitRegion.IsEmpty()) { DumpRegion(layer->mutable_dispatchregion(), e.mDispatchToContentHitRegion); } if (!e.mNoActionRegion.IsEmpty()) { DumpRegion(layer->mutable_noactionregion(), e.mNoActionRegion); } if (!e.mHorizontalPanRegion.IsEmpty()) { DumpRegion(layer->mutable_hpanregion(), e.mHorizontalPanRegion); } if (!e.mVerticalPanRegion.IsEmpty()) { DumpRegion(layer->mutable_vpanregion(), e.mVerticalPanRegion); } } // Opacity layer->set_opacity(mOpacity); // Content opaque layer->set_copaque(static_cast<bool>(GetContentFlags() & CONTENT_OPAQUE)); // Component alpha layer->set_calpha(static_cast<bool>(GetContentFlags() & CONTENT_COMPONENT_ALPHA)); // Vertical or horizontal bar if (GetScrollbarDirection() != NONE) { layer->set_direct(GetScrollbarDirection() == VERTICAL ? LayersPacket::Layer::VERTICAL : LayersPacket::Layer::HORIZONTAL); layer->set_barid(GetScrollbarTargetContainerId()); } // Mask layer if (mMaskLayer) { layer->set_mask(reinterpret_cast<uint64_t>(mMaskLayer.get())); } // DisplayList log. if (mDisplayListLog.Length() > 0) { layer->set_displaylistloglength(mDisplayListLog.Length()); auto compressedData = MakeUnique<char[]>(LZ4::maxCompressedSize(mDisplayListLog.Length())); int compressedSize = LZ4::compress((char*)mDisplayListLog.get(), mDisplayListLog.Length(), compressedData.get()); layer->set_displaylistlog(compressedData.get(), compressedSize); } } bool Layer::IsBackfaceHidden() { if (GetContentFlags() & CONTENT_BACKFACE_HIDDEN) { Layer* container = AsContainerLayer() ? this : GetParent(); if (container) { // The effective transform can include non-preserve-3d parent // transforms, since we don't always require an intermediate. if (container->Extend3DContext() || container->Is3DContextLeaf()) { return container->GetEffectiveTransform().IsBackfaceVisible(); } return container->GetBaseTransform().IsBackfaceVisible(); } } return false; } nsAutoPtr<LayerUserData> Layer::RemoveUserData(void* aKey) { nsAutoPtr<LayerUserData> d(static_cast<LayerUserData*>(mUserData.Remove(static_cast<gfx::UserDataKey*>(aKey)))); return d; } void PaintedLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix) { Layer::PrintInfo(aStream, aPrefix); if (!mValidRegion.IsEmpty()) { AppendToString(aStream, mValidRegion, " [valid=", "]"); } } void PaintedLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) { Layer::DumpPacket(aPacket, aParent); // get this layer data using namespace layerscope; LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1); layer->set_type(LayersPacket::Layer::PaintedLayer); if (!mValidRegion.IsEmpty()) { DumpRegion(layer->mutable_valid(), mValidRegion); } } void ContainerLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix) { Layer::PrintInfo(aStream, aPrefix); if (UseIntermediateSurface()) { aStream << " [usesTmpSurf]"; } if (1.0 != mPreXScale || 1.0 != mPreYScale) { aStream << nsPrintfCString(" [preScale=%g, %g]", mPreXScale, mPreYScale).get(); } if (mScaleToResolution) { aStream << nsPrintfCString(" [presShellResolution=%g]", mPresShellResolution).get(); } if (mEventRegionsOverride & EventRegionsOverride::ForceDispatchToContent) { aStream << " [force-dtc]"; } if (mEventRegionsOverride & EventRegionsOverride::ForceEmptyHitRegion) { aStream << " [force-ehr]"; } if (mVRDeviceID) { aStream << nsPrintfCString(" [hmd=%lu]", mVRDeviceID).get(); } } void ContainerLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) { Layer::DumpPacket(aPacket, aParent); // Get this layer data using namespace layerscope; LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1); layer->set_type(LayersPacket::Layer::ContainerLayer); } void ColorLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix) { Layer::PrintInfo(aStream, aPrefix); AppendToString(aStream, mColor, " [color=", "]"); AppendToString(aStream, mBounds, " [bounds=", "]"); } void ColorLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) { Layer::DumpPacket(aPacket, aParent); // Get this layer data using namespace layerscope; LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1); layer->set_type(LayersPacket::Layer::ColorLayer); layer->set_color(mColor.ToABGR()); } CanvasLayer::CanvasLayer(LayerManager* aManager, void* aImplData) : Layer(aManager, aImplData) , mPreTransCallback(nullptr) , mPreTransCallbackData(nullptr) , mPostTransCallback(nullptr) , mPostTransCallbackData(nullptr) , mFilter(gfx::Filter::GOOD) , mDirty(false) {} CanvasLayer::~CanvasLayer() {} void CanvasLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix) { Layer::PrintInfo(aStream, aPrefix); if (mFilter != Filter::GOOD) { AppendToString(aStream, mFilter, " [filter=", "]"); } } // This help function is used to assign the correct enum value // to the packet static void DumpFilter(layerscope::LayersPacket::Layer* aLayer, const Filter& aFilter) { using namespace layerscope; switch (aFilter) { case Filter::GOOD: aLayer->set_filter(LayersPacket::Layer::FILTER_GOOD); break; case Filter::LINEAR: aLayer->set_filter(LayersPacket::Layer::FILTER_LINEAR); break; case Filter::POINT: aLayer->set_filter(LayersPacket::Layer::FILTER_POINT); break; default: // ignore it break; } } void CanvasLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) { Layer::DumpPacket(aPacket, aParent); // Get this layer data using namespace layerscope; LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1); layer->set_type(LayersPacket::Layer::CanvasLayer); DumpFilter(layer, mFilter); } void ImageLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix) { Layer::PrintInfo(aStream, aPrefix); if (mFilter != Filter::GOOD) { AppendToString(aStream, mFilter, " [filter=", "]"); } } void ImageLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) { Layer::DumpPacket(aPacket, aParent); // Get this layer data using namespace layerscope; LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1); layer->set_type(LayersPacket::Layer::ImageLayer); DumpFilter(layer, mFilter); } void RefLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix) { ContainerLayer::PrintInfo(aStream, aPrefix); if (0 != mId) { AppendToString(aStream, mId, " [id=", "]"); } } void RefLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) { Layer::DumpPacket(aPacket, aParent); // Get this layer data using namespace layerscope; LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1); layer->set_type(LayersPacket::Layer::RefLayer); layer->set_refid(mId); } void ReadbackLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix) { Layer::PrintInfo(aStream, aPrefix); AppendToString(aStream, mSize, " [size=", "]"); if (mBackgroundLayer) { AppendToString(aStream, mBackgroundLayer, " [backgroundLayer=", "]"); AppendToString(aStream, mBackgroundLayerOffset, " [backgroundOffset=", "]"); } else if (mBackgroundColor.a == 1.f) { AppendToString(aStream, mBackgroundColor, " [backgroundColor=", "]"); } else { aStream << " [nobackground]"; } } void ReadbackLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent) { Layer::DumpPacket(aPacket, aParent); // Get this layer data using namespace layerscope; LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1); layer->set_type(LayersPacket::Layer::ReadbackLayer); LayersPacket::Layer::Size* size = layer->mutable_size(); size->set_w(mSize.width); size->set_h(mSize.height); } //-------------------------------------------------- // LayerManager void LayerManager::Dump(std::stringstream& aStream, const char* aPrefix, bool aDumpHtml) { #ifdef MOZ_DUMP_PAINTING if (aDumpHtml) { aStream << "<ul><li>"; } #endif DumpSelf(aStream, aPrefix); nsAutoCString pfx(aPrefix); pfx += " "; if (!GetRoot()) { aStream << nsPrintfCString("%s(null)", pfx.get()).get(); if (aDumpHtml) { aStream << "</li></ul>"; } return; } if (aDumpHtml) { aStream << "<ul>"; } GetRoot()->Dump(aStream, pfx.get(), aDumpHtml); if (aDumpHtml) { aStream << "</ul></li></ul>"; } aStream << "\n"; } void LayerManager::DumpSelf(std::stringstream& aStream, const char* aPrefix) { PrintInfo(aStream, aPrefix); aStream << "\n"; } void LayerManager::Dump() { std::stringstream ss; Dump(ss); print_stderr(ss); } void LayerManager::Dump(layerscope::LayersPacket* aPacket) { DumpPacket(aPacket); if (GetRoot()) { GetRoot()->Dump(aPacket, this); } } void LayerManager::Log(const char* aPrefix) { if (!IsLogEnabled()) return; LogSelf(aPrefix); nsAutoCString pfx(aPrefix); pfx += " "; if (!GetRoot()) { MOZ_LAYERS_LOG(("%s(null)", pfx.get())); return; } GetRoot()->Log(pfx.get()); } void LayerManager::LogSelf(const char* aPrefix) { nsAutoCString str; std::stringstream ss; PrintInfo(ss, aPrefix); MOZ_LAYERS_LOG(("%s", ss.str().c_str())); } void LayerManager::PrintInfo(std::stringstream& aStream, const char* aPrefix) { aStream << aPrefix << nsPrintfCString("%sLayerManager (0x%p)", Name(), this).get(); } void LayerManager::DumpPacket(layerscope::LayersPacket* aPacket) { using namespace layerscope; // Add a new layer data (LayerManager) LayersPacket::Layer* layer = aPacket->add_layer(); layer->set_type(LayersPacket::Layer::LayerManager); layer->set_ptr(reinterpret_cast<uint64_t>(this)); // Layer Tree Root layer->set_parentptr(0); } /*static*/ bool LayerManager::IsLogEnabled() { return MOZ_LOG_TEST(GetLog(), LogLevel::Debug); } void PrintInfo(std::stringstream& aStream, LayerComposite* aLayerComposite) { if (!aLayerComposite) { return; } if (const Maybe<ParentLayerIntRect>& clipRect = aLayerComposite->GetShadowClipRect()) { AppendToString(aStream, *clipRect, " [shadow-clip=", "]"); } if (!aLayerComposite->GetShadowTransform().IsIdentity()) { AppendToString(aStream, aLayerComposite->GetShadowTransform(), " [shadow-transform=", "]"); } if (!aLayerComposite->GetShadowVisibleRegion().IsEmpty()) { AppendToString(aStream, aLayerComposite->GetShadowVisibleRegion().ToUnknownRegion(), " [shadow-visible=", "]"); } } void SetAntialiasingFlags(Layer* aLayer, DrawTarget* aTarget) { bool permitSubpixelAA = !(aLayer->GetContentFlags() & Layer::CONTENT_DISABLE_SUBPIXEL_AA); if (aTarget->IsCurrentGroupOpaque()) { aTarget->SetPermitSubpixelAA(permitSubpixelAA); return; } const IntRect& bounds = aLayer->GetVisibleRegion().ToUnknownRegion().GetBounds(); gfx::Rect transformedBounds = aTarget->GetTransform().TransformBounds(gfx::Rect(Float(bounds.x), Float(bounds.y), Float(bounds.width), Float(bounds.height))); transformedBounds.RoundOut(); IntRect intTransformedBounds; transformedBounds.ToIntRect(&intTransformedBounds); permitSubpixelAA &= !(aLayer->GetContentFlags() & Layer::CONTENT_COMPONENT_ALPHA) || aTarget->GetOpaqueRect().Contains(intTransformedBounds); aTarget->SetPermitSubpixelAA(permitSubpixelAA); } IntRect ToOutsideIntRect(const gfxRect &aRect) { gfxRect r = aRect; r.RoundOut(); return IntRect(r.X(), r.Y(), r.Width(), r.Height()); } } // namespace layers } // namespace mozilla
77,150
25,388
#include <system.hh> #include <process.hh> #include <server.hh> #include <agent.hh> #include <wall.hh> namespace makemore { using namespace makemore; using namespace std; extern "C" void mainmore(Process *); void mainmore( Process *process ) { Session *session = process->session; Server *server = process->system->server; Urb *urb = server->urb; if (process->args.size() != 1) { strvec outvec; outvec.resize(1); outvec[0] = "nope1"; process->write(outvec); return; } if (!session->who) { strvec outvec; outvec.resize(1); outvec[0] = "nope2"; process->write(outvec); return; } Urbite &ufrom = *session->who; Parson *from = ufrom.parson(); if (!from) { strvec outvec; outvec.resize(1); outvec[0] = "nope3"; process->write(outvec); return; } std::string fromnom = from->nom; from->acted = time(NULL); string txt = process->args[0]; txt += "\n"; if (txt.length() > 16384) { strvec outvec; outvec.resize(1); outvec[0] = "nope4"; process->write(outvec); return; } ufrom.make_home_dir(); string wallfn = urb->dir + "/home/" + ufrom.nom + "/wall.txt"; FILE *fp = fopen(wallfn.c_str(), "a"); if (!fp) { strvec outvec; outvec.resize(1); outvec[0] = "nope7"; process->write(outvec); return; } size_t ret = fwrite(txt.data(), 1, txt.length(), fp); if (ret != txt.length()) { strvec outvec; outvec.resize(1); outvec[0] = "nope8"; process->write(outvec); return; } fclose(fp); Wall wall; wall.load(wallfn); if (wall.posts.size() > 8) { wall.truncate(8); wall.save(wallfn); } strvec outvec; outvec.resize(1); outvec[0] = "ok"; process->write(outvec); } }
1,755
714
#include <ros/ros.h> #include <ros/callback_queue.h> #include "geometry_msgs/TransformStamped.h" #include "geometry_msgs/Pose.h" #include <visualization_msgs/MarkerArray.h> #include "tf/transform_listener.h" #include <tf2/LinearMath/Quaternion.h> #include <hip_msgs/walls.h> #include <hip_msgs/wall.h> #include <hip_msgs/Pose.h> #include <hip_msgs/hypothesis.h> #include <hip_msgs/hypotheses.h> #include <ed_gui_server/objsPosVel.h> #include <functions.h> #include <rosnode.h> #include <functionsDiscretizedMap.h> using namespace std; /// [main] int main(int argc, char** argv) { ros::init(argc, argv, "HIP"); rosNode rosNode; vectorFieldMap map; visualization_msgs::MarkerArray staticMarkers; visualization_msgs::MarkerArray dynamicMarkers; rosNode.initialize(); map.initializeMap(); map.readMap(staticMarkers,dynamicMarkers); rosNode.setStaticMap(staticMarkers); /// [loop start] int i=0; double likelihood; double v_x = 1.0; double v_y = 0.3; // matrix A,H,P,Q,R,I; // Kalman filter matrices // initializeKalman(A,H,P,Q,R,I,1/rate); // double tPrev = ros::Time::now().toSec(); // double dt; double rate = 15.0; ros::Rate r(rate); // loop at 15 hz double u,v,dist1,dist2,totP; ros::spinOnce(); while(ros::ok()) { i++; rosNode.publishTube(map.globalTube,map.globalTubesH); // Get yaw robot tf2::Quaternion q ( rosNode.robotPose.pose.pose.orientation.x, rosNode.robotPose.pose.pose.orientation.y, rosNode.robotPose.pose.pose.orientation.z, rosNode.robotPose.pose.pose.orientation.w ); tf2::Matrix3x3 matrix ( q ); double rollRobot, pitchRobot, yawRobot; matrix.getRPY ( rollRobot, pitchRobot, yawRobot ); bool poseValid = rosNode.robotPose.pose.pose.position.x == rosNode.robotPose.pose.pose.position.x; poseValid = (poseValid && rosNode.robotPose.pose.pose.position.y == rosNode.robotPose.pose.pose.position.y); poseValid = (poseValid && yawRobot == yawRobot); if(poseValid) { for(unsigned int iHumans = 0; iHumans < rosNode.humanFilters.size(); iHumans++) { hip_msgs::PoseVel humanPosVel = rosNode.humanFilters[iHumans].predictPos(rosNode.humanFilters[iHumans].getLatestUpdateTime() ); // std::cout << "\n\n\n main, iHumans = " << iHumans << "/" << rosNode.humanFilters.size() << " humanPosVel.x = " << humanPosVel.x << " humanPosVel.y = " << humanPosVel.y << std::endl; ros::Duration dtProcessing = map.updateHypotheses(//humanPosVel.x, humanPosVel.y, humanPosVel.vx, humanPosVel.vy, rosNode.humanFilters, iHumans, rosNode.robotPose.pose.pose.position.x, rosNode.robotPose.pose.pose.position.y, yawRobot, rosNode.semanticMapFrame, rosNode.semanticMapFrame, MARKER_LIFETIME); std::string ns = "Hypotheses_Human" + std::to_string(iHumans); rosNode.publishHypotheses(map.hypotheses, ns, rosNode.humanFilters[iHumans]); map.readMap(staticMarkers,dynamicMarkers); if( iHumans == 0) { rosNode.publishProcessingTime(dtProcessing); } for(unsigned int iMarker = 0; iMarker < dynamicMarkers.markers.size(); iMarker++) { visualization_msgs::Marker marker = dynamicMarkers.markers[iMarker]; // TODO check object ID if string is empty // marker.ns = marker.ns + "object" + std::to_string(iHumans); dynamicMarkers.markers[iMarker] = marker; } // if (i%3==0) // { // rosNode.removeDynamicMap(); // } rosNode.setDynamicMap(dynamicMarkers); rosNode.publishMap(); } // } rosNode.visualizeHumans(); rosNode.visualizeMeasuredHumans(); rosNode.visualizeRobot(); // std::cout << "updateHypotheses, visualizations finished" << std::endl; // WH: why wait?! ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(1000.0)); // Call ROS stream and wait 1000 sec if no new measurement // ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(1.0)); // Call ROS stream and wait 1 sec if no new measurement // double dt = ros::Time::now().toSec() - tPrev; //TODO use measurement time! // updateKalman(A,H,P,Q,R,I,rosNode.humanPosVel,rosNode.measurement,dt); // TODO -> for all humans // cout<<"dt = "<<dt<<endl; // tPrev = ros::Time::now().toSec(); rosNode.publishHumanPV(); } else { ros::spinOnce(); } r.sleep(); } return 0; /// [loop end] }
5,104
1,696
#ifndef STAN_MATH_REV_MAT_FUN_STAN_PRINT_HPP #define STAN_MATH_REV_MAT_FUN_STAN_PRINT_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <ostream> namespace stan { namespace math { inline void stan_print(std::ostream* o, const var& x) { *o << x.val(); } } // namespace math } // namespace stan #endif
352
152
#include "common/platform/string.h" #include <string.h> namespace lightstep { int StrCaseCmp(const char* s1, const char* s2) noexcept { return ::_stricmp(s1, s2); } } // namespace lightstep
195
74
#ifndef UtGunnsBasicNode_EXISTS #define UtGunnsBasicNode_EXISTS //////////////////////////////////////////////////////////////////////////////////////////////////// /// @defgroup UT_GUNNS_BASIC_NODE Gunns Basic Node Unit Test /// @ingroup UT_GUNNS /// /// @copyright Copyright 2019 United States Government as represented by the Administrator of the /// National Aeronautics and Space Administration. All Rights Reserved. /// /// @details Unit Tests for the Gunns Basic Node class /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestFixture.h> //////////////////////////////////////////////////////////////////////////////////////////////////// // Must list of all required C Code Model includes. //////////////////////////////////////////////////////////////////////////////////////////////////// #include "core/GunnsBasicNode.hh" #include "aspects/fluid/fluid/PolyFluid.hh" class UtGunnsBasicNode; class GunnsBasicNodeUnitTest : public GunnsBasicNode { public: friend class UtGunnsBasicNode; }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details /// Class containing model tests. //////////////////////////////////////////////////////////////////////////////////////////////////// class UtGunnsBasicNode : public CppUnit::TestFixture { private: /// @brief Copy constructor unavailable since declared private and not implemented. UtGunnsBasicNode(const UtGunnsBasicNode& that); /// @brief Assignment operator unavailable since declared private and not implemented. UtGunnsBasicNode& operator =(const UtGunnsBasicNode& that); //////////////////////////////////////////////////////////////////////////////////////////// /// Test Suite Name. //////////////////////////////////////////////////////////////////////////////////////////// CPPUNIT_TEST_SUITE(UtGunnsBasicNode); //////////////////////////////////////////////////////////////////////////////////////////// /// List all unit test methods here. //////////////////////////////////////////////////////////////////////////////////////////// CPPUNIT_TEST(testDefaultConstruction); CPPUNIT_TEST(testInitialize); CPPUNIT_TEST(testValidate); CPPUNIT_TEST(testAccessMethods); CPPUNIT_TEST(testResetFlows); CPPUNIT_TEST(testIntegrateFlows); CPPUNIT_TEST(testPlaceholderMethods); CPPUNIT_TEST(testRestart); CPPUNIT_TEST_SUITE_END(); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////////////////// /// Define any data structures required in setUp. //////////////////////////////////////////////////////////////////////////////////////////// GunnsBasicNodeUnitTest tNode; GunnsNodeList tNodeList; public: UtGunnsBasicNode(); virtual ~UtGunnsBasicNode(); void tearDown(); void setUp(); void testDefaultConstruction(); void testInitialize(); void testValidate(); void testAccessMethods(); void testResetFlows(); void testIntegrateFlows(); void testPlaceholderMethods(); void testRestart(); }; ///@} #endif
3,579
796
// Copyright (c) 2020 Shivam Rathore. All rights reserved. // Use of this source code is governed by MIT License that // can be found in the LICENSE file. // This file contains Solution to Challenge #027, run using // g++ 001-050/027/c++/code.cpp -o bin/out // ./bin/out < 001-050/027/c++/in.txt > 001-050/027/c++/out.txt #include <bits/stdc++.h> using namespace std; #define ll long long void solve() { string brk; cin >> brk; int n = brk.size(), top = 0; string stk(n + 1, 0); for (int i = 0; i < n; i++) { if (stk[top] == brk[i]) top--; else if (brk[i] == '(') stk[++top] = ')'; else if (brk[i] == '[') stk[++top] = ']'; else if (brk[i] == '{') stk[++top] = '}'; else { top = -1; break; } } if (top == 0) cout << "true\n"; else cout << "false\n"; return; } int main() { int t; cin >> t; while (t--) { solve(); } }
1,016
417
#include "gtime.h" #include "gutility.h" #include "gdatetime.h" #include "gbytes.h" #include "gstring.h" #ifdef G_SYSTEM_WINDOWS # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif #include <windows.h> #include <time.h> #else // !G_SYSTEM_WINDOWS #endif // G_SYSTEM_WINDOWS #define G_TIME_OFFSET_HOUR 0 #define G_TIME_OFFSET_MINUTE 1 #define G_TIME_OFFSET_SECOND 2 #define G_TIME_OFFSET_MILLISECOND 4 #define G_TIME_SIZE_HOUR 1 #define G_TIME_SIZE_MINUTE 1 #define G_TIME_SIZE_SECOND 1 #define G_TIME_SIZE_MILLISECOND 2 namespace gsystem { // gsystem GTime GTime::Now() { GTime t; #ifdef G_SYSTEM_WINDOWS SYSTEMTIME st = { 0 }; GetLocalTime(&st); t.SetHour(st.wHour); t.SetMinute(st.wMinute); t.SetSecond(st.wSecond); t.SetMillisecond(st.wMilliseconds); #else // !G_SYSTEM_WINDOWS #endif // G_SYSTEM_WINDOWS return t; } GTime GTime::Parse(const GString &time) { // TODO return GTime(); } GTime::GTime() { GMemSet(m_tTime, 0, G_TIME_SIZE); } GTime::GTime(gtime timestamp) { GMemSet(m_tTime, 0, G_TIME_SIZE); SetTime(timestamp); } GTime::GTime(guint hour, guint minute, guint second, guint millisecond) { SetTime(hour, minute, second, millisecond); } GTime::GTime(const GTime &time) { SetTime(time); } GTime::GTime(GTime &&time) { SetTime(GForward<GTime>(time)); } GTime::GTime(const gbyte *val) { GMemCopy(m_tTime, val, G_TIME_SIZE); } guint GTime::Hour() const { GIntegerForSize<G_TIME_SIZE_HOUR>::Unsigned val = 0; GBytes::BytesToArithmetic(m_tTime + G_TIME_OFFSET_HOUR, &val); return val; } guint GTime::Minute() const { GIntegerForSize<G_TIME_SIZE_MINUTE>::Unsigned val = 0; GBytes::BytesToArithmetic(m_tTime + G_TIME_OFFSET_MINUTE, &val); return val; } guint GTime::Second() const { GIntegerForSize<G_TIME_SIZE_SECOND>::Unsigned val = 0; GBytes::BytesToArithmetic(m_tTime + G_TIME_OFFSET_SECOND, &val); return val; } guint GTime::Millisecond() const { GIntegerForSize<G_TIME_SIZE_MILLISECOND>::Unsigned val = 0; GBytes::BytesToArithmetic(m_tTime + G_TIME_OFFSET_MILLISECOND, &val); return val; } gbool GTime::SetTime(gtime timestamp) { struct tm t = { 0 }; if (0 != localtime_s(&t, &timestamp)) { return false; } SetHour(t.tm_hour); SetMinute(t.tm_min); SetSecond(t.tm_sec); SetMillisecond(0); return true; } gvoid GTime::SetTime(const GTime &time) { GMemCopy(m_tTime, time.m_tTime, G_TIME_SIZE); } gvoid GTime::SetTime(GTime &&time) { GMemCopy(m_tTime, time.m_tTime, G_TIME_SIZE); } gvoid GTime::SetTime(guint hour, guint minute, guint second, guint millisecond) { SetHour(hour); SetMinute(minute); SetSecond(second); SetMillisecond(millisecond); } gvoid GTime::SetHour(guint h) { using Type = GIntegerForSize<G_TIME_SIZE_HOUR>::Unsigned; Type val = h; GBytes::ArithmeticToBytes<Type>(&val, m_tTime + G_TIME_OFFSET_HOUR); } gvoid GTime::SetMinute(guint mm) { using Type = GIntegerForSize<G_TIME_SIZE_MINUTE>::Unsigned; Type val = mm; GBytes::ArithmeticToBytes<Type>(&val, m_tTime + G_TIME_OFFSET_MINUTE); } gvoid GTime::SetSecond(guint s) { using Type = GIntegerForSize<G_TIME_SIZE_SECOND>::Unsigned; Type val = s; GBytes::ArithmeticToBytes<Type>(&val, m_tTime + G_TIME_OFFSET_SECOND); } gvoid GTime::SetMillisecond(guint ms) { using Type = GIntegerForSize<G_TIME_SIZE_MILLISECOND>::Unsigned; Type val = ms; GBytes::ArithmeticToBytes<Type>(&val, m_tTime + G_TIME_OFFSET_MILLISECOND); } gint GTime::HoursTo(const GTime &time) const { gint that_hour = time.Hour(); gint this_hour = Hour(); return that_hour - this_hour; } gint GTime::MinutesTo(const GTime &time) const { gint minutes_to = HoursTo(time) * 60; minutes_to -= Minute(); minutes_to += time.Minute(); return minutes_to; } gint GTime::SecondsTo(const GTime &time) const { gint seconds_to = MinutesTo(time) * 60; seconds_to -= Second(); seconds_to += time.Second(); return seconds_to; } gint GTime::MillisecondsTo(const GTime &time) const { gint milliseconds_to = SecondsTo(time) * 1000; milliseconds_to -= Millisecond(); milliseconds_to += time.Millisecond(); return milliseconds_to; } GTime &GTime::AddHours(gint h) { if (h == 0) { return *this; } gint new_hour = Hour() + h; guint hours_in_a_day = 24; while (new_hour / hours_in_a_day) { if (new_hour > 0) { new_hour = new_hour - hours_in_a_day; } else { new_hour = new_hour + hours_in_a_day; } } SetHour(new_hour); return *this; } GTime &GTime::AddMinutes(gint mm) { if (mm == 0) { return *this; } gint new_minute = Minute() + mm; gint add_hours = 0; guint minutes_in_an_hour = 60; while (new_minute / minutes_in_an_hour) { if (new_minute > 0) { new_minute = new_minute - minutes_in_an_hour; ++add_hours; } else { new_minute = new_minute + minutes_in_an_hour; --add_hours; } } AddHours(add_hours).SetMinute(new_minute); return *this; } GTime &GTime::AddSeconds(gint s) { if (s == 0) { return *this; } gint new_second = Second() + s; gint add_minutes = 0; guint seconds_in_a_minute = 60; while (new_second / seconds_in_a_minute) { if (new_second > 0) { new_second = new_second - seconds_in_a_minute; ++add_minutes; } else { new_second = new_second + seconds_in_a_minute; --add_minutes; } } AddMinutes(add_minutes).SetSecond(new_second); return *this; } GTime &GTime::AddMilliseconds(gint ms) { if (ms == 0) { return *this; } gint new_millisecond = Millisecond() + ms; gint add_seconds = 0; guint milliseconds_in_a_second = 1000; while (new_millisecond / milliseconds_in_a_second) { if (new_millisecond > 0) { new_millisecond = new_millisecond - milliseconds_in_a_second; ++add_seconds; } else { new_millisecond = new_millisecond + milliseconds_in_a_second; --add_seconds; } } AddSeconds(add_seconds).SetMillisecond(new_millisecond); return *this; } /* GString GTime::ToString() const { // 20:40 00:000 GString str; str.Reserve(12); str.Append(GString::Number(Hour())); str.Append(":"); str.Append(GString::Number(Minute())); str.Append(" "); str.Append(GString::Number(Second())); str.Append(":"); str.Append(GString::Number(Millisecond())); return str; } */ } // namespace gsystem #undef G_TIME_SIZE_MILLISECOND #undef G_TIME_SIZE_SECOND #undef G_TIME_SIZE_MINUTE #undef G_TIME_SIZE_HOUR #undef G_TIME_OFFSET_MILLISECOND #undef G_TIME_OFFSET_SECOND #undef G_TIME_OFFSET_MINUTE #undef G_TIME_OFFSET_HOUR
6,436
2,948
/************************************************************************* > File Name: PA.cpp > Author: Gavin Lee > Mail: sz110010@gmail.com > Created Time: 西元2016年01月30日 (週六) 00時45分08秒 ************************************************************************/ #include <bits/stdc++.h> using namespace std; int sv[10000]; int main() { int n; cin >> n; int cnt = 0; while(n) { if(n & 1) sv[cnt] = 1; n >>= 1; cnt++; } for(int i = cnt-1; i >= 0; --i) if(sv[i]) cout << i+1 << ' '; return 0; }
588
238
// This source file is part of the Argon project. // // Licensed under the Apache License v2.0 #include <memory/memory.h> #include <vm/runtime.h> #include "bool.h" #include "bounds.h" #include "error.h" #include "integer.h" #include "iterator.h" #include "hash_magic.h" #include "bytes.h" #define BUFFER_GET(bs) (bs->view.buffer) #define BUFFER_LEN(bs) (bs->view.len) #define BUFFER_MAXLEN(left, right) (BUFFER_LEN(left) > BUFFER_LEN(right) ? BUFFER_LEN(right) : BUFFER_LEN(self)) using namespace argon::memory; using namespace argon::object; bool bytes_get_buffer(Bytes *self, ArBuffer *buffer, ArBufferFlags flags) { return BufferSimpleFill(self, buffer, flags, BUFFER_GET(self), BUFFER_LEN(self), !self->frozen); } const BufferSlots bytes_buffer = { (BufferGetFn) bytes_get_buffer, nullptr }; ArSize bytes_len(Bytes *self) { return BUFFER_LEN(self); } ArObject *bytes_get_item(Bytes *self, ArSSize index) { if (index < 0) index = BUFFER_LEN(self) + index; if (index < BUFFER_LEN(self)) return IntegerNew(BUFFER_GET(self)[index]); return ErrorFormat(type_overflow_error_, "bytes index out of range (len: %d, idx: %d)", BUFFER_LEN(self), index); } bool bytes_set_item(Bytes *self, ArObject *obj, ArSSize index) { Bytes *other; ArSize value; if (self->frozen) { ErrorFormat(type_type_error_, "unable to set item to frozen bytes object"); return false; } if (AR_TYPEOF(obj, type_bytes_)) { other = (Bytes *) obj; if (BUFFER_LEN(other) > 1) { ErrorFormat(type_value_error_, "expected bytes of length 1 not %d", BUFFER_LEN(other)); return false; } value = BUFFER_GET(other)[0]; } else if (AR_TYPEOF(obj, type_integer_)) value = ((Integer *) obj)->integer; else { ErrorFormat(type_type_error_, "expected integer or bytes, found '%s'", AR_TYPE_NAME(obj)); return false; } if (value < 0 || value > 255) { ErrorFormat(type_value_error_, "byte must be in range(0, 255)"); return false; } if (index < 0) index = BUFFER_LEN(self) + index; if (index < BUFFER_LEN(self)) { BUFFER_GET(self)[index] = value; return true; } ErrorFormat(type_overflow_error_, "bytes index out of range (len: %d, idx: %d)", BUFFER_LEN(self), index); return false; } ArObject *bytes_get_slice(Bytes *self, Bounds *bounds) { Bytes *ret; ArSSize slice_len; ArSSize start; ArSSize stop; ArSSize step; slice_len = BoundsIndex(bounds, BUFFER_LEN(self), &start, &stop, &step); if (step >= 0) { ret = BytesNew(self, start, slice_len); } else { if ((ret = BytesNew(slice_len, true, false, self->frozen)) == nullptr) return nullptr; for (ArSize i = 0; stop < start; start += step) BUFFER_GET(ret)[i++] = BUFFER_GET(self)[start]; } return ret; } const SequenceSlots bytes_sequence = { (SizeTUnaryOp) bytes_len, (BinaryOpArSize) bytes_get_item, (BoolTernOpArSize) bytes_set_item, (BinaryOp) bytes_get_slice, nullptr }; ARGON_FUNCTION5(bytes_, new, "Creates bytes object." "" "The src parameter is optional, in case of call without src parameter an empty zero-length" "bytes object will be constructed." "" "- Parameter [src]: integer or bytes-like object." "- Returns: construct a new bytes object.", 0, true) { IntegerUnderlying size = 0; if (!VariadicCheckPositional("bytes::new", count, 0, 1)) return nullptr; if (count == 1) { if (!AR_TYPEOF(*argv, type_integer_)) return BytesNew(*argv); size = ((Integer *) *argv)->integer; } return BytesNew(size, true, true, false); } ARGON_METHOD5(bytes_, count, "Returns the number of times a specified value occurs in bytes." "" "- Parameter sub: subsequence to search." "- Returns: number of times a specified value appears in bytes.", 1, false) { ArBuffer buffer{}; Bytes *bytes; ArSSize n; bytes = (Bytes *) self; if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ)) return nullptr; n = support::Count(BUFFER_GET(bytes), BUFFER_LEN(bytes), buffer.buffer, buffer.len, -1); BufferRelease(&buffer); return IntegerNew(n); } ARGON_METHOD5(bytes_, clone, "Returns the number of times a specified value occurs in bytes." "" "- Parameter sub: subsequence to search." "- Returns: number of times a specified value appears in the string.", 0, false) { return BytesNew(self); } ARGON_METHOD5(bytes_, endswith, "Returns true if bytes ends with the specified value." "" "- Parameter suffix: the value to check if the bytes ends with." "- Returns: true if bytes ends with the specified value, false otherwise." "" "# SEE" "- startswith: Returns true if bytes starts with the specified value.", 1, false) { ArBuffer buffer{}; Bytes *bytes; int res; bytes = (Bytes *) self; if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ)) return nullptr; res = BUFFER_LEN(bytes) > buffer.len ? buffer.len : BUFFER_LEN(bytes); res = MemoryCompare(BUFFER_GET(bytes) + (BUFFER_LEN(bytes) - res), buffer.buffer, res); BufferRelease(&buffer); return BoolToArBool(res == 0); } ARGON_METHOD5(bytes_, find, "Searches bytes for a specified value and returns the position of where it was found." "" "- Parameter sub: the value to search for." "- Returns: index of the first position, -1 otherwise." "" "# SEE" "- rfind: Same as find, but returns the index of the last position.", 1, false) { ArBuffer buffer{}; Bytes *bytes; ArSSize pos; bytes = (Bytes *) self; if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ)) return nullptr; pos = support::Find(BUFFER_GET(bytes), BUFFER_LEN(bytes), buffer.buffer, buffer.len, false); return IntegerNew(pos); } ARGON_METHOD5(bytes_, freeze, "Freeze bytes object." "" "If bytes is already frozen, the same object will be returned, otherwise a new frozen bytes(view) will be returned." "- Returns: frozen bytes object.", 0, false) { auto *bytes = (Bytes *) self; return BytesFreeze(bytes); } ARGON_METHOD5(bytes_, hex, "Convert bytes to str of hexadecimal numbers." "" "- Returns: new str object.", 0, false) { StringBuilder builder{}; Bytes *bytes; bytes = (Bytes *) self; if (StringBuilderWriteHex(&builder, BUFFER_GET(bytes), BUFFER_LEN(bytes)) < 0) { StringBuilderClean(&builder); return nullptr; } return StringBuilderFinish(&builder); } ARGON_METHOD5(bytes_, isalnum, "Check if all characters in the bytes are alphanumeric (either alphabets or numbers)." "" "- Returns: true if all characters are alphanumeric, false otherwise." "" "# SEE" "- isalpha: Check if all characters in the bytes are alphabets." "- isascii: Check if all characters in the bytes are ascii." "- isdigit: Check if all characters in the bytes are digits.", 0, false) { auto *bytes = (Bytes *) self; int chr; for (ArSize i = 0; i < BUFFER_LEN(bytes); i++) { chr = BUFFER_GET(bytes)[i]; if ((chr < 'A' || chr > 'Z') && (chr < 'a' || chr > 'z') && (chr < '0' || chr > '9')) return BoolToArBool(false); } return BoolToArBool(true); } ARGON_METHOD5(bytes_, isalpha, "Check if all characters in the bytes are alphabets." "" "- Returns: true if all characters are alphabets, false otherwise." "" "# SEE" "- isalnum: Check if all characters in the bytes are alphanumeric (either alphabets or numbers)." "- isascii: Check if all characters in the bytes are ascii." "- isdigit: Check if all characters in the bytes are digits.", 0, false) { auto *bytes = (Bytes *) self; int chr; for (ArSize i = 0; i < BUFFER_LEN(bytes); i++) { chr = BUFFER_GET(bytes)[i]; if ((chr < 'A' || chr > 'Z') && (chr < 'a' || chr > 'z')) return BoolToArBool(false); } return BoolToArBool(true); } ARGON_METHOD5(bytes_, isascii, "Check if all characters in the bytes are ascii." "" "- Returns: true if all characters are ascii, false otherwise." "" "# SEE" "- isalnum: Check if all characters in the bytes are alphanumeric (either alphabets or numbers)." "- isalpha: Check if all characters in the bytes are alphabets." "- isdigit: Check if all characters in the bytes are digits.", 0, false) { auto *bytes = (Bytes *) self; int chr; for (ArSize i = 0; i < BUFFER_LEN(bytes); i++) { chr = BUFFER_GET(bytes)[i]; if (chr > 0x7F) return BoolToArBool(false); } return BoolToArBool(true); } ARGON_METHOD5(bytes_, isdigit, "Check if all characters in the bytes are digits." "" "- Returns: true if all characters are digits, false otherwise." "" "# SEE" "- isalnum: Check if all characters in the bytes are alphanumeric (either alphabets or numbers)." "- isalpha: Check if all characters in the bytes are alphabets." "- isascii: Check if all characters in the bytes are ascii.", 0, false) { auto *bytes = (Bytes *) self; int chr; for (ArSize i = 0; i < BUFFER_LEN(bytes); i++) { chr = BUFFER_GET(bytes)[i]; if (chr < '0' || chr > '9') return BoolToArBool(false); } return BoolToArBool(true); } ARGON_METHOD5(bytes_, isfrozen, "Check if this bytes object is frozen." "" "- Returns: true if it is frozen, false otherwise.", 0, false) { return BoolToArBool(((Bytes *) self)->frozen); } ARGON_METHOD5(bytes_, join, "Joins the elements of an iterable to the end of the bytes." "" "- Parameter iterable: any iterable object where all the returned values are bytes-like object." "- Returns: new bytes where all items in an iterable are joined into one bytes.", 1, false) { ArBuffer buffer{}; ArObject *item = nullptr; ArObject *iter; Bytes *bytes; Bytes *ret; ArSize idx = 0; ArSize len; bytes = (Bytes *) self; if ((iter = IteratorGet(argv[0])) == nullptr) return nullptr; if ((ret = BytesNew()) == nullptr) goto error; while ((item = IteratorNext(iter)) != nullptr) { if (!BufferGet(item, &buffer, ArBufferFlags::READ)) goto error; len = buffer.len; if (idx > 0) len += bytes->view.len; if (!BufferViewEnlarge(&ret->view, len)) { BufferRelease(&buffer); goto error; } if (idx > 0) { MemoryCopy(BUFFER_GET(ret) + BUFFER_LEN(ret), BUFFER_GET(bytes), BUFFER_LEN(bytes)); ret->view.len += BUFFER_LEN(bytes); } MemoryCopy(BUFFER_GET(ret) + BUFFER_LEN(ret), buffer.buffer, buffer.len); ret->view.len += buffer.len; BufferRelease(&buffer); Release(item); idx++; } Release(iter); return ret; error: Release(item); Release(iter); Release(ret); return nullptr; } ARGON_METHOD5(bytes_, rfind, "Searches bytes for a specified value and returns the position of where it was found." "" "- Parameter sub: the value to search for." "- Returns: index of the first position, -1 otherwise." "" "# SEE" "- find: Same as find, but returns the index of the last position.", 1, false) { ArBuffer buffer{}; Bytes *bytes; ArSSize pos; bytes = (Bytes *) self; if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ)) return nullptr; pos = support::Find(BUFFER_GET(bytes), BUFFER_LEN(bytes), buffer.buffer, buffer.len, true); return IntegerNew(pos); } ARGON_METHOD5(bytes_, rmpostfix, "Returns new bytes without postfix(if present), otherwise return this object." "" "- Parameter postfix: postfix to looking for." "- Returns: new bytes without indicated postfix." "" "# SEE" "- rmprefix: Returns new bytes without prefix(if present), otherwise return this object.", 1, false) { ArBuffer buffer{}; auto *bytes = (Bytes *) self; int len; int compare; if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ)) return nullptr; len = BUFFER_LEN(bytes) > buffer.len ? buffer.len : BUFFER_LEN(bytes); compare = MemoryCompare(BUFFER_GET(bytes) + (BUFFER_LEN(bytes) - len), buffer.buffer, len); BufferRelease(&buffer); if (compare == 0) return BytesNew(bytes, 0, BUFFER_LEN(bytes) - len); return IncRef(bytes); } ARGON_METHOD5(bytes_, rmprefix, "Returns new bytes without prefix(if present), otherwise return this object." "" "- Parameter prefix: prefix to looking for." "- Returns: new bytes without indicated prefix." "" "# SEE" "- rmpostfix: Returns new bytes without postfix(if present), otherwise return this object.", 1, false) { ArBuffer buffer{}; auto *bytes = (Bytes *) self; int len; int compare; if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ)) return nullptr; len = BUFFER_LEN(bytes) > buffer.len ? buffer.len : BUFFER_LEN(bytes); compare = MemoryCompare(BUFFER_GET(bytes), buffer.buffer, len); BufferRelease(&buffer); if (compare == 0) return BytesNew(bytes, len, BUFFER_LEN(bytes) - len); return IncRef(bytes); } ARGON_METHOD5(bytes_, split, "Splits bytes at the specified separator, and returns a list." "" "- Parameters:" " - separator: specifies the separator to use when splitting bytes." " - maxsplit: specifies how many splits to do." "- Returns: new list of bytes.", 2, false) { ArBuffer buffer{}; Bytes *bytes; ArObject *ret; bytes = (Bytes *) self; if (!AR_TYPEOF(argv[1], type_integer_)) return ErrorFormat(type_type_error_, "bytes::split() expected integer not '%s'", AR_TYPE_NAME(argv[1])); if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ)) return nullptr; ret = BytesSplit(bytes, buffer.buffer, buffer.len, ((Integer *) argv[1])->integer); BufferRelease(&buffer); return ret; } ARGON_METHOD5(bytes_, startswith, "Returns true if bytes starts with the specified value." "" "- Parameter prefix: the value to check if the bytes starts with." "- Returns: true if bytes starts with the specified value, false otherwise." "" "# SEE" "- endswith: Returns true if bytes ends with the specified value.", 1, false) { ArBuffer buffer{}; Bytes *bytes; int res; bytes = (Bytes *) self; if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ)) return nullptr; res = BUFFER_LEN(bytes) > buffer.len ? buffer.len : BUFFER_LEN(bytes); res = MemoryCompare(BUFFER_GET(bytes), buffer.buffer, res); BufferRelease(&buffer); return BoolToArBool(res == 0); } ARGON_METHOD5(bytes_, str, "Convert bytes to str object." "" "- Returns: new str object.", 0, false) { auto *bytes = (Bytes *) self; return StringNew((const char *) BUFFER_GET(bytes), BUFFER_LEN(bytes)); } const NativeFunc bytes_methods[] = { bytes_count_, bytes_endswith_, bytes_find_, bytes_freeze_, bytes_hex_, bytes_isalnum_, bytes_isalpha_, bytes_isascii_, bytes_isdigit_, bytes_isfrozen_, bytes_join_, bytes_new_, bytes_rfind_, bytes_rmpostfix_, bytes_rmprefix_, bytes_split_, bytes_startswith_, bytes_str_, ARGON_METHOD_SENTINEL }; const ObjectSlots bytes_obj = { bytes_methods, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, -1 }; ArObject *bytes_add(Bytes *self, ArObject *other) { ArBuffer buffer = {}; Bytes *ret; if (!IsBufferable(other)) return nullptr; if (!BufferGet(other, &buffer, ArBufferFlags::READ)) return nullptr; if ((ret = BytesNew(BUFFER_LEN(self) + buffer.len, true, false, self->frozen)) == nullptr) { BufferRelease(&buffer); return nullptr; } MemoryCopy(BUFFER_GET(ret), BUFFER_GET(self), BUFFER_LEN(self)); MemoryCopy(BUFFER_GET(ret) + BUFFER_LEN(self), buffer.buffer, buffer.len); BufferRelease(&buffer); return ret; } ArObject *bytes_mul(ArObject *left, ArObject *right) { auto *bytes = (Bytes *) left; auto *num = (Integer *) right; Bytes *ret = nullptr; ArSize len; if (!AR_TYPEOF(bytes, type_bytes_)) { bytes = (Bytes *) right; num = (Integer *) left; } if (AR_TYPEOF(num, type_integer_)) { len = BUFFER_LEN(bytes) * num->integer; if ((ret = BytesNew(len, true, false, bytes->frozen)) != nullptr) { for (ArSize i = 0; i < num->integer; i++) MemoryCopy(BUFFER_GET(ret) + BUFFER_LEN(bytes) * i, BUFFER_GET(bytes), BUFFER_LEN(bytes)); } } return ret; } Bytes *ShiftBytes(Bytes *bytes, ArSSize pos) { auto ret = BytesNew(BUFFER_LEN(bytes), true, false, bytes->frozen); if (ret != nullptr) { for (ArSize i = 0; i < BUFFER_LEN(bytes); i++) ret->view.buffer[((BUFFER_LEN(bytes) + pos) + i) % BUFFER_LEN(bytes)] = BUFFER_GET(bytes)[i]; } return ret; } ArObject *bytes_shl(ArObject *left, ArObject *right) { if (AR_TYPEOF(left, type_bytes_) && AR_TYPEOF(right, type_integer_)) return ShiftBytes((Bytes *) left, -((Integer *) right)->integer); return nullptr; } ArObject *bytes_shr(ArObject *left, ArObject *right) { if (AR_TYPEOF(left, type_bytes_) && AR_TYPEOF(right, type_integer_)) return ShiftBytes((Bytes *) left, ((Integer *) right)->integer); return nullptr; } ArObject *bytes_iadd(Bytes *self, ArObject *other) { ArBuffer buffer = {}; Bytes *ret = self; if (!IsBufferable(other)) return nullptr; if (!BufferGet(other, &buffer, ArBufferFlags::READ)) return nullptr; if (self->frozen) { if ((ret = BytesNew(BUFFER_LEN(self) + buffer.len, true, false, true)) == nullptr) { BufferRelease(&buffer); return nullptr; } MemoryCopy(BUFFER_GET(ret), BUFFER_GET(self), BUFFER_LEN(self)); MemoryCopy(BUFFER_GET(ret) + BUFFER_LEN(self), buffer.buffer, buffer.len); BufferRelease(&buffer); return ret; } if (!BufferViewEnlarge(&self->view, buffer.len)) { BufferRelease(&buffer); return nullptr; } MemoryCopy(BUFFER_GET(ret) + BUFFER_LEN(ret), buffer.buffer, buffer.len); ret->view.len += buffer.len; BufferRelease(&buffer); return IncRef(self); } OpSlots bytes_ops{ (BinaryOp) bytes_add, nullptr, bytes_mul, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, bytes_shl, bytes_shr, nullptr, (BinaryOp) bytes_iadd, nullptr, nullptr, nullptr, nullptr, nullptr }; ArObject *bytes_str(Bytes *self) { StringBuilder sb = {}; // Calculate length of string if (!StringBuilderResizeAscii(&sb, BUFFER_GET(self), BUFFER_LEN(self), 3)) // +3 b"" return nullptr; // Build string StringBuilderWrite(&sb, (const unsigned char *) "b\"", 2);; StringBuilderWriteAscii(&sb, BUFFER_GET(self), BUFFER_LEN(self)); StringBuilderWrite(&sb, (const unsigned char *) "\"", 1); return StringBuilderFinish(&sb); } ArObject *bytes_iter_get(Bytes *self) { return IteratorNew(self, false); } ArObject *bytes_iter_rget(Bytes *self) { return IteratorNew(self, true); } ArObject *bytes_compare(Bytes *self, ArObject *other, CompareMode mode) { auto *o = (Bytes *) other; int left = 0; int right = 0; int res; if (!AR_SAME_TYPE(self, other)) return nullptr; if (self != other) { res = MemoryCompare(BUFFER_GET(self), BUFFER_GET(o), BUFFER_MAXLEN(self, o)); if (res < 0) left = -1; else if (res > 0) right = -1; else if (BUFFER_LEN(self) < BUFFER_LEN(o)) left = -1; else if (BUFFER_LEN(self) > BUFFER_LEN(o)) right = -1; } ARGON_RICH_COMPARE_CASES(left, right, mode); } ArSize bytes_hash(Bytes *self) { if (!self->frozen) { ErrorFormat(type_unhashable_error_, "unable to hash unfrozen bytes object"); return 0; } if (self->hash == 0) self->hash = HashBytes(BUFFER_GET(self), BUFFER_LEN(self)); return self->hash; } bool bytes_is_true(Bytes *self) { return BUFFER_LEN(self) > 0; } void bytes_cleanup(Bytes *self) { BufferViewDetach(&self->view); } const TypeInfo BytesType = { TYPEINFO_STATIC_INIT, "bytes", nullptr, sizeof(Bytes), TypeInfoFlags::BASE, nullptr, (VoidUnaryOp) bytes_cleanup, nullptr, (CompareOp) bytes_compare, (BoolUnaryOp) bytes_is_true, (SizeTUnaryOp) bytes_hash, (UnaryOp) bytes_str, (UnaryOp) bytes_iter_get, (UnaryOp) bytes_iter_rget, &bytes_buffer, nullptr, nullptr, nullptr, &bytes_obj, &bytes_sequence, &bytes_ops, nullptr, nullptr }; const TypeInfo *argon::object::type_bytes_ = &BytesType; ArObject *argon::object::BytesSplit(Bytes *bytes, unsigned char *pattern, ArSize plen, ArSSize maxsplit) { Bytes *tmp; List *ret; ArSize idx = 0; ArSSize end; ArSSize counter = 0; if ((ret = ListNew()) == nullptr) return nullptr; if (maxsplit != 0) { while ((end = support::Find(BUFFER_GET(bytes) + idx, BUFFER_LEN(bytes) - idx, pattern, plen)) >= 0) { if ((tmp = BytesNew(bytes, idx, end - idx)) == nullptr) goto error; idx += end + plen; if (!ListAppend(ret, tmp)) goto error; Release(tmp); if (maxsplit > -1 && ++counter >= maxsplit) break; } } if (BUFFER_LEN(bytes) - idx > 0) { if ((tmp = BytesNew(bytes, idx, BUFFER_LEN(bytes) - idx)) == nullptr) goto error; if (!ListAppend(ret, tmp)) goto error; Release(tmp); } return ret; error: Release(tmp); Release(ret); return nullptr; } Bytes *argon::object::BytesNew(ArObject *object) { ArBuffer buffer = {}; Bytes *bs; if (!IsBufferable(object)) return nullptr; if (!BufferGet(object, &buffer, ArBufferFlags::READ)) return nullptr; if ((bs = BytesNew(buffer.len, true, false, false)) != nullptr) MemoryCopy(BUFFER_GET(bs), buffer.buffer, buffer.len); BufferRelease(&buffer); return bs; } Bytes *argon::object::BytesNew(Bytes *stream, ArSize start, ArSize len) { auto bs = ArObjectNew<Bytes>(RCType::INLINE, type_bytes_); if (bs != nullptr) { BufferViewInit(&bs->view, &stream->view, start, len); bs->hash = 0; bs->frozen = stream->frozen; } return bs; } Bytes *argon::object::BytesNew(ArSize cap, bool same_len, bool fill_zero, bool frozen) { auto bs = ArObjectNew<Bytes>(RCType::INLINE, type_bytes_); if (bs != nullptr) { if (!BufferViewInit(&bs->view, cap)) { Release(bs); return nullptr; } if (same_len) bs->view.len = cap; if (fill_zero) MemoryZero(BUFFER_GET(bs), cap); bs->hash = 0; bs->frozen = frozen; } return bs; } Bytes *argon::object::BytesNew(unsigned char *buffer, ArSize len, bool frozen) { auto *bytes = BytesNew(len, true, false, frozen); if (bytes != nullptr) MemoryCopy(BUFFER_GET(bytes), buffer, len); return bytes; } Bytes *argon::object::BytesNewHoldBuffer(unsigned char *buffer, ArSize len, ArSize cap, bool frozen) { auto bs = ArObjectNew<Bytes>(RCType::INLINE, type_bytes_); if (bs != nullptr) { if (!BufferViewHoldBuffer(&bs->view, buffer, len, cap)) { Release(bs); return nullptr; } bs->hash = 0; bs->frozen = frozen; } return bs; } Bytes *argon::object::BytesFreeze(Bytes *stream) { Bytes *ret; if (stream->frozen) return IncRef(stream); if ((ret = BytesNew(stream, 0, BUFFER_LEN(stream))) == nullptr) return nullptr; ret->frozen = true; Hash(ret); return ret; } #undef BUFFER_GET #undef BUFFER_LEN #undef BUFFER_MAXLEN
26,120
8,426
// MIT LICENSE // // Copyright (c) 2020 FOSSA Systems // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #include "FOSSASAT2_Statistics.h" FOSSASAT2::Messages::Statistics::Statistics(Frame &frame) { uint8_t flagByte = frame.GetByteAt(0); this->temperaturesIncluded = flagByte & 0x01; this->currentsIncluded = (flagByte >> 1) & 0x01; this->voltagesIncluded = (flagByte >> 2) & 0x01; this->lightSensorsIncluded = (flagByte >> 3) & 0x01; this->imuIncluded = (flagByte >> 4) & 0x01; if (this->temperaturesIncluded) { for (int i = 0; i < 15; i++) { int startIndex = 1 + (i*2); uint8_t lsb = frame.GetByteAt(startIndex); uint8_t msb = frame.GetByteAt(startIndex + 1); int16_t temperature = lsb | (msb << 8); float temperaturesRealValue = temperature * 0.01f; this->temperatures.push_back(temperaturesRealValue); } } if (this->currentsIncluded) { for (int i = 0; i < 18; i++) { int startIndex = 31 + (i*2); uint8_t lsb = frame.GetByteAt(startIndex); uint8_t msb = frame.GetByteAt(startIndex + 1); int16_t current = lsb | (msb << 8); float currentsValue = current * 10; this->currents.push_back(currentsValue); } } if (this->voltagesIncluded) { for (int i = 0; i < 18; i++) { int startIndex = 67 + i; float voltage = frame.GetByteAt(startIndex) * 20; this->voltages.push_back(voltage); } } if (this->lightSensorsIncluded) { for (int i = 0; i < 6; i++) { int startIndex = 85 + (i * 4); uint8_t lsb = frame.GetByteAt(startIndex); uint8_t a = frame.GetByteAt(startIndex + 1); uint8_t b = frame.GetByteAt(startIndex + 2); uint8_t msb = frame.GetByteAt(startIndex + 3); uint32_t bytesVal = lsb; bytesVal |= a << 8; bytesVal |= b << 16; bytesVal |= msb << 24; float lightSensorValue = 0.0f; memcpy(&lightSensorValue, &bytesVal, 4); this->currents.push_back(lightSensorValue); } } if (this->imuIncluded) { for (int i = 0; i < 16; i++) { int startIndex = 109 + (i * 4); uint8_t lsb = frame.GetByteAt(startIndex); uint8_t a = frame.GetByteAt(startIndex + 1); uint8_t b = frame.GetByteAt(startIndex + 2); uint8_t msb = frame.GetByteAt(startIndex + 3); uint32_t bytesVal = lsb; bytesVal |= a << 8; bytesVal |= b << 16; bytesVal |= msb << 24; float imuValue = 0.0f; memcpy(&imuValue, &bytesVal, 4); this->imus.push_back(imuValue); } } } std::string FOSSASAT2::Messages::Statistics::ToString() { std::stringstream ss; ss << "Satellite Version: FOSSASAT2" << std::endl; ss << "Message Name: Statistics" << std::endl; ss << "Temperatures included: " << this->temperaturesIncluded << std::endl; ss << "Currents included: " << this->currentsIncluded << std::endl; ss << "Voltages included: " << this->voltagesIncluded << std::endl; ss << "Light sensors included: " << this->lightSensorsIncluded << std::endl; ss << "IMU included: " << this->imuIncluded << std::endl; ss << "Temperatures: " << std::endl; for (float temp : this->temperatures) { ss << " " << temp << " deg. C" << std::endl; } ss << "Currents: " << std::endl; for (float current : this->currents) { ss << " " << current << " uA" << std::endl; } ss << "Voltages: " << std::endl; for (float voltage : this->voltages) { ss << " " << voltage << " mV" << std::endl; } ss << "Light sensors: " << std::endl; for (float lightSensor : this->lightSensors) { ss << " " << lightSensor << std::endl; } ss << "IMU: " << std::endl; for (float imu : this->imus) { ss << " " << imu << std::endl; } std::string out; ss >> out; return out; } std::string FOSSASAT2::Messages::Statistics::ToJSON() { std::stringstream ss; ss << "{" << std::endl; ss << "\"Satellite Version\": \"FOSSASAT2\"," << std::endl; ss << "\"Message Name\": \"Statistics\"," << std::endl; ss << "\"Temperatures included\": " << this->temperaturesIncluded << std::endl; ss << "\"Currents included\": " << this->currentsIncluded << std::endl; ss << "\"Voltages included\": " << this->voltagesIncluded << std::endl; ss << "\"Light sensors included\": " << this->lightSensorsIncluded << std::endl; ss << "\"IMU included\": " << this->imuIncluded << std::endl; ss << "\"Temperatures\": " << std::endl; ss << "{" << std::endl; for (float temp : this->temperatures) { ss << temp << "," << std::endl; } ss << "\"Currents\": " << std::endl; ss << "{" << std::endl; for (float current : this->currents) { ss << " \"" << current << "\"," << std::endl; } ss << "}" << std::endl; ss << "\"Voltages\": " << std::endl; ss << "{" << std::endl; for (float voltage : this->voltages) { ss << " \"" << voltage << "\"," << std::endl; } ss << "}" << std::endl; ss << "\"Light sensors\": " << std::endl; ss << "{" << std::endl; for (float lightSensor : this->lightSensors) { ss << " \"" << lightSensor << "\"," << std::endl; } ss << "}" << std::endl; ss << "\"IMU\": " << std::endl; ss << "{" << std::endl; for (float imu : this->imus) { ss << " \"" << imu << "\"," << std::endl; } ss << "}" << std::endl; ss << "}" << std::endl; std::string out; ss >> out; return out; } bool FOSSASAT2::Messages::Statistics::IsTemperaturesIncluded() const { return temperaturesIncluded; } bool FOSSASAT2::Messages::Statistics::IsCurrentsIncluded() const { return currentsIncluded; } bool FOSSASAT2::Messages::Statistics::IsVoltagesIncluded() const { return voltagesIncluded; } bool FOSSASAT2::Messages::Statistics::IsLightSensorsIncluded() const { return lightSensorsIncluded; } bool FOSSASAT2::Messages::Statistics::IsImuIncluded() const { return imuIncluded; } const std::vector<float> &FOSSASAT2::Messages::Statistics::GetTemperatures() const { return temperatures; } const std::vector<float> &FOSSASAT2::Messages::Statistics::GetCurrents() const { return currents; } const std::vector<float> &FOSSASAT2::Messages::Statistics::GetVoltages() const { return voltages; } const std::vector<float> &FOSSASAT2::Messages::Statistics::GetLightSensors() const { return lightSensors; } const std::vector<float> &FOSSASAT2::Messages::Statistics::GetImus() const { return imus; }
7,976
2,802
#include "command.h" #include <iostream> int main(int argc, char* argv[]) { // This variables can be set via the command line. std::string oString = "Default Value"; int32_t oInteger = -1; uint32_t oUnsigned = 0; double oDouble = 0.0; float oFloat = 0.f; bool oBool = false; bool oPrintHelp = false; // First configure all possible command line options. CommandLine args("A demonstration of the simple command line parser."); args.addArgument({"-s", "--string"}, &oString, "A string value"); args.addArgument({"-i", "--integer"}, &oInteger, "A integer value"); args.addArgument({"-u", "--unsigned"}, &oUnsigned, "A unsigned value"); args.addArgument({"-d", "--double"}, &oDouble, "A float value"); args.addArgument({"-f", "--float"}, &oFloat, "A double value"); args.addArgument({"-b", "--bool"}, &oBool, "A bool value"); args.addArgument({"-h", "--help"}, &oPrintHelp, "Print this help. This help message is actually so long " "that it requires a line break!"); // Then do the actual parsing. try { args.parse(argc, argv); } catch (std::runtime_error const& e) { std::cout << e.what() << std::endl; return -1; } // When oPrintHelp was set to true, we print a help message and exit. if (oPrintHelp) { args.printHelp(); return 0; } // Print the resulting values. std::cout << "mString: " << oString << std::endl; std::cout << "mInteger: " << oInteger << std::endl; std::cout << "mUnsigned: " << oUnsigned << std::endl; std::cout.precision(std::numeric_limits<double>::max_digits10); std::cout << "mDouble: " << oDouble << std::endl; std::cout.precision(std::numeric_limits<float>::max_digits10); std::cout << "mFloat: " << oFloat << std::endl; std::cout << "mBool: " << oBool << std::endl; return 0; }
2,001
665
// Question Link ---> https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/ class Solution { public: vector<int> kWeakestRows(vector<vector<int>>& mat, int k) { vector<int> res; multimap<int, int> soldierRow; // {soldier, row} int M = mat.size(); int N = mat[0].size(); for (int i = 0; i < M; i++) { int j = 1; for (; j < N; j++) { if (mat[i][j] != 0) { mat[i][j] += mat[i][j - 1]; } else break; } soldierRow.insert({mat[i][j - 1], i}); } auto it = soldierRow.begin(); for (int i = 0; i < k && it != soldierRow.end(); i++, it++) { res.push_back(it->second); } return res; } };
808
281
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <chrono> #include <iostream> #include <vector> #define CL_USE_DEPRECATED_OPENCL_1_2_APIS #include "ApiHandle.h" #include "CL/opencl.h" #include "Task.h" int main(int argc, char *argv[]) { // -- Environment / Usage Check ------------------------------------------- char *xcl_mode = getenv("XCL_EMULATION_MODE"); if (argc != 2) { printf("\nUsage: %s " "./xclbin/pass.<emulation_mode>.<dsa>.xclbin ", argv[0]); return EXIT_FAILURE; } char *binaryName = argv[1]; // -- Common Parameters --------------------------------------------------- unsigned int numBuffers = 3; bool oooQueue = false; unsigned int bufferSize = 1024; // -- Setup --------------------------------------------------------------- ApiHandle api(binaryName, oooQueue); std::cout << std::endl; std::cout << std::endl; std::vector<Task> tasks(numBuffers, Task(bufferSize)); auto fpga_begin = std::chrono::high_resolution_clock::now(); // -- Execution ----------------------------------------------------------- for (unsigned int i = 0; i < numBuffers; i++) { tasks[i].run(api); } clFinish(api.getQueue()); // -- Testing ------------------------------------------------------------- auto fpga_end = std::chrono::high_resolution_clock::now(); bool outputOk = true; for (unsigned int i = 0; i < numBuffers; i++) { outputOk = tasks[i].outputOk() && outputOk; } if (!outputOk) { std::cout << "FAIL: Output Corrupted" << std::endl; return 1; } // -- Performance Statistics ---------------------------------------------- if (xcl_mode == NULL) { std::chrono::duration<double> fpga_duration = fpga_end - fpga_begin; double total = (double)bufferSize * numBuffers * 512 / (1024.0 * 1024.0); std::cout << std::endl; std::cout << " Total data: " << total << " MBits" << std::endl; std::cout << " FPGA Time: " << fpga_duration.count() << " s" << std::endl; std::cout << " FPGA Throughput: " << total / fpga_duration.count() << " MBits/s" << std::endl; std::cout << "FPGA PCIe Throughput: " << (2 * total) / fpga_duration.count() << " MBits/s" << std::endl; } std::cout << "\nPASS: Simulation" << std::endl; return 0; }
3,167
1,020
#ifndef SPROUT_DARKROOM_RENDERERS_WHITTED_STYLE_HPP #define SPROUT_DARKROOM_RENDERERS_WHITTED_STYLE_HPP #include <cstddef> #include <limits> #include <type_traits> #include <sprout/config.hpp> #include <sprout/tuple/functions.hpp> #include <sprout/darkroom/access/access.hpp> #include <sprout/darkroom/colors/rgb.hpp> #include <sprout/darkroom/coords/vector.hpp> #include <sprout/darkroom/rays/ray.hpp> #include <sprout/darkroom/materials/material.hpp> #include <sprout/darkroom/intersects/intersection.hpp> #include <sprout/darkroom/objects/intersect.hpp> namespace sprout { namespace darkroom { namespace renderers { // // whitted_mirror // class whitted_mirror { private: template< typename Color, typename Camera, typename Objects, typename Lights, typename Ray, typename Intersection, typename Tracer, typename Direction > SPROUT_CONSTEXPR Color color_1( Camera const& camera, Objects const& objs, Lights const& lights, Ray const& ray, Intersection const& inter, Tracer const& tracer, std::size_t depth_max, Direction const& reflect_dir ) const { return tracer.template operator()<Color>( camera, objs, lights, sprout::tuples::remake<Ray>( ray, sprout::darkroom::coords::add( sprout::darkroom::intersects::point_of_intersection(inter), sprout::darkroom::coords::scale( reflect_dir, std::numeric_limits<typename sprout::darkroom::access::unit<Direction>::type>::epsilon() * 256 ) // !!! // sprout::darkroom::coords::scale( // sprout::darkroom::intersects::normal(inter), // std::numeric_limits<typename sprout::darkroom::access::unit<Direction>::type>::epsilon() * 256 // ) ), reflect_dir ), depth_max - 1 ); } public: template< typename Color, typename Camera, typename Objects, typename Lights, typename Ray, typename Intersection, typename Tracer > SPROUT_CONSTEXPR Color operator()( Camera const& camera, Objects const& objs, Lights const& lights, Ray const& ray, Intersection const& inter, Tracer const& tracer, std::size_t depth_max ) const { typedef typename std::decay< decltype(sprout::darkroom::materials::reflection(sprout::darkroom::intersects::material(inter))) >::type reflection_type; return depth_max > 0 && sprout::darkroom::intersects::does_intersect(inter) && sprout::darkroom::materials::reflection(sprout::darkroom::intersects::material(inter)) > std::numeric_limits<reflection_type>::epsilon() ? color_1<Color>( camera, objs, lights, ray, inter, tracer, depth_max, sprout::darkroom::coords::reflect( sprout::darkroom::rays::direction(ray), sprout::darkroom::intersects::normal(inter) ) ) : sprout::tuples::make<Color>(0, 0, 0) ; } }; // // whitted_style // class whitted_style { private: template< typename Color, typename Ray, typename Intersection > SPROUT_CONSTEXPR Color color_3( Ray const& ray, Intersection const& inter, Color const& diffuse_color, Color const& mirror_color ) const { return sprout::darkroom::intersects::does_intersect(inter) ? sprout::darkroom::colors::add( sprout::darkroom::colors::mul( diffuse_color, 1 - sprout::darkroom::materials::reflection(sprout::darkroom::intersects::material(inter)) ), sprout::darkroom::colors::mul( sprout::darkroom::colors::filter( sprout::darkroom::materials::color(sprout::darkroom::intersects::material(inter)), mirror_color ), sprout::darkroom::materials::reflection(sprout::darkroom::intersects::material(inter)) ) ) : sprout::darkroom::coords::normal_to_color<Color>(sprout::darkroom::rays::direction(ray)) ; } template< typename Color, typename Camera, typename Objects, typename Lights, typename Ray, typename Intersection > SPROUT_CONSTEXPR Color color_2( Camera const& camera, Objects const& objs, Lights const& lights, Ray const& ray, std::size_t depth_max, Intersection const& inter, Color const& diffuse_color ) const { return color_3<Color>( ray, inter, diffuse_color, sprout::darkroom::renderers::whitted_mirror().template operator()<Color>( camera, objs, lights, ray, inter, *this, depth_max ) ); } template< typename Color, typename Camera, typename Objects, typename Lights, typename Ray, typename Intersection > SPROUT_CONSTEXPR Color color_1( Camera const& camera, Objects const& objs, Lights const& lights, Ray const& ray, std::size_t depth_max, Intersection const& inter ) const { return color_2<Color>( camera, objs, lights, ray, depth_max, inter, lights.template operator()(inter, objs) ); } public: template< typename Color, typename Camera, typename Objects, typename Lights, typename Ray > SPROUT_CONSTEXPR Color operator()( Camera const& camera, Objects const& objs, Lights const& lights, Ray const& ray, std::size_t depth_max ) const { return color_1<Color>( camera, objs, lights, ray, depth_max, sprout::darkroom::objects::intersect_list(objs, ray) ); } }; } // namespace renderers } // namespace darkroom } // namespace sprout #endif // #ifndef SPROUT_DARKROOM_RENDERERS_WHITTED_STYLE_HPP
6,210
2,978
// // Created by makstar on 01.12.2020. // #include "BlackAndWhiteNode.h" void BlackAndWhiteNode::process() { this->outputPtr = applyTransform(this->inputs[0]->getOutputPtr()); } std::shared_ptr<Image> BlackAndWhiteNode::applyTransform(const std::shared_ptr<Image>& img) { int width = img->getWidth(); int height = img->getHeight(); auto new_img = std::make_shared<Image>(height, width, 3, new Pixel[height * width]); int grey; // max, min; Pixel current; for(int i = 0; i < height; i++){ for(int j = 0; j < width; j++){ current = img->getPixel(i, j); grey = (current.red + current.green + current.blue) / 3; new_img->setPixel(i, j, grey, grey, grey); } } return new_img; } NodeType BlackAndWhiteNode::getNodeType() { return NodeType::BlackAndWhiteNode; }
856
298
/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */ #include <string> #include <vector> #include "OptArgs.h" #include "Mask.h" #include "NumericalComparison.h" #include "Utils.h" #include "IonH5File.h" #include "IonH5Arma.h" using namespace std; using namespace arma; /** * Options about the two beadfind/separator results we're comparing. * query is the test results and gold is the current stable version by * convention. */ class SepCmpOpt { public: SepCmpOpt() { min_corr = 1.0; verbosity = 0; threshold_percent = .02; } string gold_dir, query_dir; double min_corr; double threshold_percent; string mode; int verbosity; }; /** * Notes from a comparison, */ class ComparisonMsg { public: ComparisonMsg(const string &_name, double _min_corr, double _max_diff) : name(_name), min_corr(_min_corr), max_diff(_max_diff) { equivalent = true; } void Append(const string &s) { msg += s; } void ToStr(ostream &o, int verbosity) { string status = "*FAILED*"; if (equivalent) { status = "PASSED"; } // 0 is no output if (verbosity >= 1 || !equivalent) { o << name << ":\t" << status; o << endl; if (verbosity > 1) { if (cmp_names.size() > 0) { o << " " << cmp_values[0].GetCount() << " entries." << endl; } for (size_t i = 0; i < cmp_names.size(); i++) { o << " " << cmp_names[i] << "\t" << cmp_values[i].GetNumDiff() << "\t" << cmp_values[i].GetCorrelation() << endl; } } } } string name; string msg; bool equivalent; double min_corr; double max_diff; vector<string> cmp_names; vector<NumericalComparison<double> > cmp_values; }; /* utility function for messages to console. */ int global_verbosity = 0; void StatusMsg(const string &s) { if (global_verbosity > 0) { cout << s << endl; } } /* Is the query value significantly better than the gold. */ bool SigBetter(double query, double gold, double threshold_percent) { if (gold * (1 + threshold_percent) <= query) { return true; } return false; } /* Compare the masks from the two directories. */ void CompareMask(SepCmpOpt &sep, const string &mask_suffix, ComparisonMsg &msg ) { string gold_file = sep.gold_dir + "/" + mask_suffix; string query_file = sep.query_dir + "/" + mask_suffix; Mask q_mask, g_mask; StatusMsg("Loading: " + gold_file); g_mask.LoadMaskAndAbortOnFailure(gold_file.c_str()); StatusMsg("Loading: " + query_file); q_mask.LoadMaskAndAbortOnFailure(query_file.c_str()); msg.name = "Beadfind Mask"; msg.msg = "Results: "; msg.equivalent = true; if (g_mask.W() != q_mask.W() || g_mask.H() != g_mask.H()) { msg.equivalent = false; msg.Append("Masks are different sizes."); return; } msg.cmp_names.push_back("values"); msg.cmp_names.push_back("library"); msg.cmp_names.push_back("ignore"); msg.cmp_names.push_back("empty"); msg.cmp_values.resize(msg.cmp_names.size()); size_t num_entries = g_mask.H() * g_mask.W(); StatusMsg("Checking mask entries."); for (size_t i = 0; i < num_entries; i++) { short g = g_mask[i]; short q = q_mask[i]; msg.cmp_values[0].AddPair(g, q); msg.cmp_values[1].AddPair(g & MaskLib ? 1 : 0, q & MaskLib ? 1 : 0 ); msg.cmp_values[2].AddPair(g & MaskIgnore ? 1 : 0, q & MaskIgnore ? 1 : 0); msg.cmp_values[3].AddPair(g & MaskEmpty ? 1 : 0, q & MaskEmpty ? 1 : 0); } for (size_t cmp_idx = 0; cmp_idx < msg.cmp_values.size(); cmp_idx++) { if (!msg.cmp_values[cmp_idx].CorrelationOk(msg.min_corr)) { msg.equivalent = false; msg.msg += " " + msg.cmp_names[cmp_idx] + " min: " + ToStr(msg.min_corr) + " got: " + ToStr(msg.cmp_values[cmp_idx].GetCorrelation()); } } } /* Compare the summary hdf5 values from the two directories. */ void CompareSummary(SepCmpOpt &opts, const string &summary_suffix, ComparisonMsg &msg) { string gold_file = opts.gold_dir + "/" + summary_suffix; string query_file = opts.query_dir + "/" + summary_suffix; Mat<float> gold_matrix, query_matrix; StatusMsg("Reading gold file: " + gold_file); H5Arma::ReadMatrix(gold_file + ":/separator/summary", gold_matrix); StatusMsg("Reading query file: " + query_file); H5Arma::ReadMatrix(query_file + ":/separator/summary", query_matrix); msg.name = "Summary Table"; msg.msg = "Results:"; msg.equivalent = true; if (gold_matrix.n_rows != query_matrix.n_rows) { msg.equivalent = false; msg.Append("Summary table are different sizes."); return; } msg.cmp_names.push_back("key"); // 0 msg.cmp_names.push_back("t0"); // 1 msg.cmp_names.push_back("snr"); // 2 msg.cmp_names.push_back("mad"); // 3 msg.cmp_names.push_back("sd"); // 4 msg.cmp_names.push_back("bf_metric"); // 5 msg.cmp_names.push_back("taub_a"); // 6 msg.cmp_names.push_back("taub_c"); // 7 msg.cmp_names.push_back("taub_g"); // 8 msg.cmp_names.push_back("taub_t"); // 9 msg.cmp_names.push_back("peak_sig"); // 10 msg.cmp_names.push_back("flag"); msg.cmp_names.push_back("good_live"); msg.cmp_names.push_back("is_ref"); msg.cmp_names.push_back("buffer_metric"); msg.cmp_names.push_back("trace_sd"); msg.cmp_values.resize(msg.cmp_names.size()); size_t num_entries = gold_matrix.n_rows; StatusMsg("Checking summary entries."); for (size_t row_ix = 0; row_ix < num_entries; row_ix++) { for (size_t col_ix = 0; col_ix < msg.cmp_values.size(); col_ix++) { msg.cmp_values[col_ix].AddPair(gold_matrix.at(row_ix,col_ix), query_matrix.at(row_ix,col_ix)); } } for (size_t cmp_idx = 0; cmp_idx < msg.cmp_values.size(); cmp_idx++) { if (!msg.cmp_values[cmp_idx].CorrelationOk(msg.min_corr)) { msg.equivalent = false; msg.msg += " " + msg.cmp_names[cmp_idx] + " min: " + ToStr(msg.min_corr) + " got: " + ToStr(msg.cmp_values[cmp_idx].GetCorrelation()); } } } /* some crumbs of documentation. */ void help_msg(ostream &o) { o << "SeparatorCmp - Program to compare separator results from different" << endl << " versions of separator." << "options:" << endl << " -h,--help this message." << endl << " -g,--gold-dir trusted results to compare against [required]" << endl << " -q,--query-dir new results to check [required]" << endl << " -c,--min-corr minimum correlation to be considered equivalent [1.0]" << endl << " -m,--mode if 'research' output additional info ['exact']" << endl << " --signficance level for significantly better or worse in research mode [.02]" << endl << " --verbosity level of messages to print (higher is more verbose)" << endl ; exit(1); } /* Output some reseach statistics */ void OutputResearch(SepCmpOpt &opts, ComparisonMsg &mask_msg, ComparisonMsg &summary_msg) { const SampleStats<double> &gold_lib = mask_msg.cmp_values[1].GetXStats(); const SampleStats<double> &query_lib = mask_msg.cmp_values[1].GetYStats(); const SampleStats<double> &gold_ignore = mask_msg.cmp_values[2].GetXStats(); const SampleStats<double> &query_ignore = mask_msg.cmp_values[2].GetYStats(); const SampleStats<double> &gold_snr = summary_msg.cmp_values[2].GetXStats(); const SampleStats<double> &query_snr = summary_msg.cmp_values[2].GetYStats(); const SampleStats<double> &gold_mad = summary_msg.cmp_values[3].GetXStats(); const SampleStats<double> &query_mad = summary_msg.cmp_values[3].GetYStats(); const SampleStats<double> &gold_peak_sig = summary_msg.cmp_values[10].GetXStats(); const SampleStats<double> &query_peak_sig = summary_msg.cmp_values[10].GetYStats(); fprintf(stdout, "\nSeparator Results:\n"); fprintf(stdout, "Name Gold_Value Query_Value Change \n"); fprintf(stdout, "---- ---------- ----------- --------\n"); fprintf(stdout, "Lib %10.2f %10.2f %6.2f%%\n", gold_lib.GetMean(), query_lib.GetMean(), query_lib.GetMean()/ gold_lib.GetMean() * 100.0f); fprintf(stdout, "Ignore %10.2f %10.2f %6.2f%%\n", gold_ignore.GetMean(), query_ignore.GetMean(), query_ignore.GetMean()/ gold_ignore.GetMean() * 100.0f); fprintf(stdout, "SNR %10.2f %10.2f %6.2f%%\n", gold_snr.GetMean(), query_snr.GetMean(), query_snr.GetMean()/ gold_snr.GetMean() * 100.0f); fprintf(stdout, "MAD %10.2f %10.2f %6.2f%%\n", gold_mad.GetMean(), query_mad.GetMean(), query_mad.GetMean()/ gold_mad.GetMean() * 100.0f); fprintf(stdout, "Signal %10.2f %10.2f %6.2f%%\n", gold_peak_sig.GetMean(), query_peak_sig.GetMean(), query_peak_sig.GetMean()/ gold_peak_sig.GetMean() * 100.0f); if ((SigBetter(query_lib.GetMean(), query_lib.GetMean(), opts.threshold_percent) && !SigBetter(gold_lib.GetMean(), query_lib.GetMean(), opts.threshold_percent)) || (SigBetter(query_snr.GetMean(), query_snr.GetMean(), opts.threshold_percent) && !SigBetter(gold_snr.GetMean(), gold_snr.GetMean(), opts.threshold_percent)) || (SigBetter(query_peak_sig.GetMean(), query_peak_sig.GetMean(), opts.threshold_percent) && !SigBetter(gold_peak_sig.GetMean(), gold_peak_sig.GetMean(), opts.threshold_percent)) || (!SigBetter(query_mad.GetMean(), query_mad.GetMean(), opts.threshold_percent) && SigBetter(gold_mad.GetMean(), gold_mad.GetMean(), opts.threshold_percent))) { StatusMsg("Overall: **Better**"); } else if ((!SigBetter(query_lib.GetMean(), query_lib.GetMean(), opts.threshold_percent) && SigBetter(gold_lib.GetMean(), query_lib.GetMean(), opts.threshold_percent)) || (!SigBetter(query_snr.GetMean(), query_snr.GetMean(), opts.threshold_percent) && SigBetter(gold_snr.GetMean(), gold_snr.GetMean(), opts.threshold_percent)) || (!SigBetter(query_peak_sig.GetMean(), query_peak_sig.GetMean(), opts.threshold_percent) && SigBetter(gold_peak_sig.GetMean(), gold_peak_sig.GetMean(), opts.threshold_percent)) || (SigBetter(query_mad.GetMean(), query_mad.GetMean(), opts.threshold_percent) && !SigBetter(gold_mad.GetMean(), gold_mad.GetMean(), opts.threshold_percent))) { StatusMsg("Overall: **Worse**"); } else { StatusMsg("Overall: **About Same**"); } StatusMsg(""); } /* Everybody's favorite function. */ int main (int argc, const char *argv[]) { const string mask_suffix = "separator.mask.bin"; const string h5_suffix = "separator.h5"; OptArgs o; bool all_ok = true; bool exit_help = false; SepCmpOpt opts; /* Get our command line options. */ o.ParseCmdLine(argc, argv); o.GetOption(opts.gold_dir, "", 'g',"gold-dir"); o.GetOption(opts.query_dir, "", 'q',"query-dir"); o.GetOption(opts.min_corr, "1", 'c', "min-corr"); o.GetOption(opts.verbosity, "1", '-', "verbosity"); o.GetOption(opts.mode, "exact", 'm', "mode"); o.GetOption(exit_help, "false", 'h', "help"); global_verbosity = opts.verbosity; /* If something wrong or help, then help exit. */ if (exit_help || opts.gold_dir.empty() || opts.query_dir.empty()) { help_msg(cout); } /* Check the masks. */ ComparisonMsg mask_msg("mask_check", opts.min_corr, 0); mask_msg.min_corr = opts.min_corr; CompareMask(opts, mask_suffix, mask_msg); mask_msg.ToStr(cout,opts.verbosity); all_ok &= mask_msg.equivalent; /* Compare the summary tables. */ ComparisonMsg summary_msg("summary_check", opts.min_corr, 0); mask_msg.min_corr = opts.min_corr; CompareSummary(opts, h5_suffix, summary_msg); summary_msg.ToStr(cout,opts.verbosity); all_ok &= summary_msg.equivalent; if (opts.mode == "research") { OutputResearch(opts, mask_msg, summary_msg); } /* If all was ok then return 0. */ if (all_ok) { StatusMsg("Equivalent"); } else { StatusMsg("Not Equivalent"); } StatusMsg("Done."); return !all_ok; }
11,962
4,530
#include "ServerListResponse.h" #ifdef _MSC_VER #include <ciso646> #endif void ServerListResponse::serializeto( GrowingBuffer &buf ) const { assert(not m_serv_list.empty()); buf.uPut((uint8_t)4); buf.uPut((uint8_t)m_serv_list.size()); buf.uPut((uint8_t)1); //preferred server number for(const GameServerInfo &srv : m_serv_list) { buf.Put(srv.id); uint32_t addr= srv.addr; buf.Put((uint32_t)ACE_SWAP_LONG(addr)); //must be network byte order buf.Put((uint32_t)srv.port); buf.Put(uint8_t(0)); buf.Put(uint8_t(0)); buf.Put(srv.current_players); buf.Put(srv.max_players); buf.Put((uint8_t)srv.online); } } void ServerListResponse::serializefrom( GrowingBuffer &buf ) { uint8_t op,unused; buf.uGet(op); uint8_t server_list_size; buf.uGet(server_list_size); buf.uGet(m_preferred_server_idx); //preferred server number for(int i = 0; i < server_list_size; i++) { GameServerInfo srv; buf.Get(srv.id); buf.Get(srv.addr); //must be network byte order buf.Get(srv.port); buf.Get(unused); buf.Get(unused); buf.Get(srv.current_players); buf.Get(srv.max_players); buf.Get(srv.online); m_serv_list.push_back(srv); } }
1,317
519
/* Levenshtein distance # Examples $ ./levenshtein ABCDEFG ACEG Levenshtein Distance: 3 $ ./levenshtein ABCDEFG AZCPEGM Levenshtein Distance: 4 */ #include<iostream> #include<vector> #include<algorithm> using namespace std; size_t levenshtein(const string& x, const string& y) { auto m{ x.size() }; auto n{ y.size() }; vector<size_t> dp(n + 1, 0); for (size_t i = 1; i < n; i++) { dp[i] = i; } size_t s, e; char p, q; for (size_t i = 1; i <= m; i++) { s = i - 1; e = i; p = x[i - 1]; for (size_t j = 1; j <= n; j++) { q = y[j - 1]; e = min({ e + 1, dp[j] + 1, s + (p == q ? size_t{0} : size_t{1}) }); s = dp[j]; dp[j] = e; } } return dp[n]; } int main(int argc, char* argv[]) { if (argc < 3) { cout << "Please provide two strings!" << endl; return 1; } string x = argv[1]; string y = argv[2]; auto res = levenshtein(x, y); cout << "Levenshtein Distance: " << res << endl; }
1,118
477
////////////////////////////////////////////////////////////////////////////// // use of tmp: // // Tmp(0) : nax seg // Tmp(1) : nst seg // // use of debug bits: bits 0-2 are reserved // 0 : all events // 1 : passed events // 2 : rejected events // // 3 : events with N(track seeds) = 0 /////////////////////////////////////////////////////////////////////////////// #include "TF1.h" #include "TCanvas.h" #include "TPad.h" #include "TEnv.h" #include "TSystem.h" #include "Stntuple/loop/TStnAna.hh" #include "Stntuple/obj/TStnHeaderBlock.hh" #include "Stntuple/alg/TStntuple.hh" // #include "Stntuple/geom/TDisk.hh" #include "Stntuple/val/stntuple_val_functions.hh" //------------------------------------------------------------------------------ // Mu2e offline includes //----------------------------------------------------------------------------- #include "Stntuple/ana/TTrackSeedAnaModule.hh" ClassImp(stntuple::TTrackSeedAnaModule) namespace stntuple { //----------------------------------------------------------------------------- TTrackSeedAnaModule::TTrackSeedAnaModule(const char* name, const char* title): TStnModule(name,title) { fPtMin = 1.; // fTrackNumber.Set(100); //----------------------------------------------------------------------------- // MC truth: define which MC particle to consider as signal //----------------------------------------------------------------------------- fPdgCode = 11; fGeneratorCode = 2; // conversionGun, 28:StoppedParticleReactionGun } //----------------------------------------------------------------------------- TTrackSeedAnaModule::~TTrackSeedAnaModule() { } //----------------------------------------------------------------------------- void TTrackSeedAnaModule::BookTrackSeedHistograms (TrackSeedHist_t* Hist, const char* Folder){ HBook1F(Hist->fNHits ,"nhits" ,Form("%s: # of straw hits" ,Folder), 150, 0, 150,Folder); HBook1F(Hist->fClusterTime ,"clusterTime",Form("%s: cluster time; t_{cluster}[ns]",Folder), 800, 400, 1700,Folder); HBook1F(Hist->fClusterEnergy ,"clusterE" ,Form("%s: cluster energy; E [MeV] ",Folder), 400, 0, 200,Folder); HBook1F(Hist->fRadius ,"radius" ,Form("%s: curvature radius; r [mm]" ,Folder), 500, 0, 500,Folder); HBook1F(Hist->fMom ,"p" ,Form("%s: momentum; p [MeV/c]" ,Folder), 300, 50, 200,Folder); HBook1F(Hist->fPt ,"pT" ,Form("%s: pT; pT [MeV/c]" ,Folder), 600, 0, 150,Folder); HBook1F(Hist->fTanDip ,"tanDip" ,Form("%s: tanDip; tanDip" ,Folder), 300, 0, 3,Folder); HBook1F(Hist->fChi2 ,"chi2" ,Form("%s: #chi^{2}-XY; #chi^{2}/ndof" ,Folder), 100, 0, 10,Folder); HBook1F(Hist->fFitCons ,"FitCons" ,Form("%s: Fit consistency; Fit-cons" ,Folder), 100, 0, 1, Folder); HBook1F(Hist->fD0 ,"d0" ,Form("%s: D0; d0 [mm]" ,Folder), 1600, -400, 400,Folder); } //----------------------------------------------------------------------------- void TTrackSeedAnaModule::BookGenpHistograms(GenpHist_t* Hist, const char* Folder) { // char name [200]; // char title[200]; HBook1F(Hist->fP ,"p" ,Form("%s: Momentum" ,Folder),1000, 0, 200,Folder); HBook1F(Hist->fPdgCode[0],"pdg_code_0",Form("%s: PDG Code[0]" ,Folder),200, -100, 100,Folder); HBook1F(Hist->fPdgCode[1],"pdg_code_1",Form("%s: PDG Code[1]" ,Folder),500, -2500, 2500,Folder); HBook1F(Hist->fGenID ,"gen_id" ,Form("%s: Generator ID" ,Folder), 100, 0, 100,Folder); HBook1F(Hist->fZ0 ,"z0" ,Form("%s: Z0" ,Folder), 500, 5400, 6400,Folder); HBook1F(Hist->fT0 ,"t0" ,Form("%s: T0" ,Folder), 200, 0, 2000,Folder); HBook1F(Hist->fR0 ,"r" ,Form("%s: R0" ,Folder), 100, 0, 100,Folder); HBook1F(Hist->fCosTh ,"cos_th" ,Form("%s: Cos(Theta)" ,Folder), 200, -1., 1.,Folder); } //----------------------------------------------------------------------------- void TTrackSeedAnaModule::BookEventHistograms(EventHist_t* Hist, const char* Folder) { // char name [200]; // char title[200]; HBook1F(Hist->fEleCosTh ,"ce_costh" ,Form("%s: Conversion Electron Cos(Theta)" ,Folder),100,-1,1,Folder); HBook1F(Hist->fEleMom ,"ce_mom" ,Form("%s: Conversion Electron Momentum" ,Folder),1000, 0,200,Folder); HBook1F(Hist->fRv ,"rv" ,Form("%s: R(Vertex)" ,Folder), 100, 0, 1000,Folder); HBook1F(Hist->fZv ,"zv" ,Form("%s: Z(Vertex)" ,Folder), 300, 0,15000,Folder); HBook1F(Hist->fNTrackSeeds,"nts" ,Form("%s: Number of Reco Track Seeds" ,Folder),100,0,100,Folder); HBook1F(Hist->fNGenp ,"ngenp" ,Form("%s: N(Gen Particles)" ,Folder),500,0,500,Folder); } //----------------------------------------------------------------------------- void TTrackSeedAnaModule::BookSimpHistograms(SimpHist_t* Hist, const char* Folder) { // char name [200]; // char title[200]; HBook1F(Hist->fPdgCode ,"pdg" ,Form("%s: PDG code" ,Folder),200,-100,100,Folder); HBook1F(Hist->fNStrawHits,"nsth" ,Form("%s: n straw hits" ,Folder),200, 0,200,Folder); HBook1F(Hist->fMomTargetEnd ,"ptarg" ,Form("%s: CE mom after Stopping Target" ,Folder),400, 90,110,Folder); HBook1F(Hist->fMomTrackerFront ,"pfront",Form("%s: CE mom at the Tracker Front" ,Folder),400, 90,110,Folder); } //_____________________________________________________________________________ void TTrackSeedAnaModule::BookHistograms() { // char name [200]; // char title[200]; TFolder* fol; TFolder* hist_folder; char folder_name[200]; DeleteHistograms(); hist_folder = (TFolder*) GetFolder()->FindObject("Hist"); //-------------------------------------------------------------------------------- // book trackSeed histograms //-------------------------------------------------------------------------------- int book_trackSeed_histset[kNTrackSeedHistSets]; for (int i=0; i<kNTrackSeedHistSets; ++i) book_trackSeed_histset[i] = 0; book_trackSeed_histset[0] = 1; // events with at least one trackSeed book_trackSeed_histset[1] = 1; // events with at least one trackSeed with p > 80 MeV/c book_trackSeed_histset[2] = 1; // events with at least one trackSeed with p > 90 MeV/c book_trackSeed_histset[3] = 1; // events with at least one trackSeed with p > 100 MeV/c book_trackSeed_histset[4] = 1; // events with at least one trackSeed with 10 < nhits < 15 book_trackSeed_histset[5] = 1; // events with at least one trackSeed with nhits >= 15 book_trackSeed_histset[6] = 1; // events with at least one trackSeed with nhits >= 15 and chi2(ZPhi)<4 for (int i=0; i<kNTrackSeedHistSets; i++) { if (book_trackSeed_histset[i] != 0) { sprintf(folder_name,"trkseed_%i",i); fol = (TFolder*) hist_folder->FindObject(folder_name); if (! fol) fol = hist_folder->AddFolder(folder_name,folder_name); fHist.fTrackSeed[i] = new TrackSeedHist_t; BookTrackSeedHistograms(fHist.fTrackSeed[i],Form("Hist/%s",folder_name)); } } //----------------------------------------------------------------------------- // book event histograms //----------------------------------------------------------------------------- int book_event_histset[kNEventHistSets]; for (int i=0; i<kNEventHistSets; i++) book_event_histset[i] = 0; book_event_histset[ 0] = 1; // all events for (int i=0; i<kNEventHistSets; i++) { if (book_event_histset[i] != 0) { sprintf(folder_name,"evt_%i",i); fol = (TFolder*) hist_folder->FindObject(folder_name); if (! fol) fol = hist_folder->AddFolder(folder_name,folder_name); fHist.fEvent[i] = new EventHist_t; BookEventHistograms(fHist.fEvent[i],Form("Hist/%s",folder_name)); } } //----------------------------------------------------------------------------- // book simp histograms //----------------------------------------------------------------------------- int book_simp_histset[kNSimpHistSets]; for (int i=0; i<kNSimpHistSets; i++) book_simp_histset[i] = 0; book_simp_histset[ 0] = 1; // all events for (int i=0; i<kNSimpHistSets; i++) { if (book_simp_histset[i] != 0) { sprintf(folder_name,"sim_%i",i); fol = (TFolder*) hist_folder->FindObject(folder_name); if (! fol) fol = hist_folder->AddFolder(folder_name,folder_name); fHist.fSimp[i] = new SimpHist_t; BookSimpHistograms(fHist.fSimp[i],Form("Hist/%s",folder_name)); } } //----------------------------------------------------------------------------- // book Genp histograms //----------------------------------------------------------------------------- int book_genp_histset[kNGenpHistSets]; for (int i=0; i<kNGenpHistSets; i++) book_genp_histset[i] = 0; book_genp_histset[0] = 1; // all particles // book_genp_histset[1] = 1; // all crystals, e > 0 // book_genp_histset[2] = 1; // all crystals, e > 0.1 // book_genp_histset[3] = 1; // all crystals, e > 1.0 for (int i=0; i<kNGenpHistSets; i++) { if (book_genp_histset[i] != 0) { sprintf(folder_name,"gen_%i",i); fol = (TFolder*) hist_folder->FindObject(folder_name); if (! fol) fol = hist_folder->AddFolder(folder_name,folder_name); fHist.fGenp[i] = new GenpHist_t; BookGenpHistograms(fHist.fGenp[i],Form("Hist/%s",folder_name)); } } } //----------------------------------------------------------------------------- // need MC truth branch //----------------------------------------------------------------------------- void TTrackSeedAnaModule::FillEventHistograms(EventHist_t* Hist) { double cos_th(-2), xv(-1.e6), yv(-1.e6), rv(-1.e6), zv(-1.e6), p(-1.); // double e, m, r; TLorentzVector mom; if (fParticle) { fParticle->Momentum(mom); p = mom.P(); cos_th = mom.Pz()/p; xv = fParticle->Vx()+3904.; yv = fParticle->Vy(); rv = sqrt(xv*xv+yv*yv); zv = fParticle->Vz(); } Hist->fEleMom->Fill(p); Hist->fEleCosTh->Fill(cos_th); Hist->fRv->Fill(rv); Hist->fZv->Fill(zv); Hist->fNGenp->Fill(fNGenp); Hist->fNTrackSeeds->Fill(fNTrackSeeds); } //-------------------------------------------------------------------------------- // function to fill TrasckSeedHit block //-------------------------------------------------------------------------------- void TTrackSeedAnaModule::FillTrackSeedHistograms(TrackSeedHist_t* Hist, TStnTrackSeed* TrkSeed) { int nhits = TrkSeed->NHits (); double clusterT = TrkSeed->ClusterTime(); double clusterE = TrkSeed->ClusterEnergy(); double mm2MeV = 3/10.; double pT = TrkSeed->Pt(); double radius = pT/mm2MeV; double tanDip = TrkSeed->TanDip(); double p = pT/std::cos( std::atan(tanDip)); Hist->fNHits ->Fill(nhits); Hist->fClusterTime->Fill(clusterT); Hist->fClusterEnergy->Fill(clusterE); Hist->fRadius ->Fill(radius); Hist->fMom ->Fill(p); Hist->fPt ->Fill(pT); Hist->fTanDip ->Fill(tanDip); Hist->fChi2 ->Fill(TrkSeed->Chi2()); Hist->fFitCons ->Fill(TrkSeed->FitCons()); Hist->fD0 ->Fill(TrkSeed->D0()); } //----------------------------------------------------------------------------- void TTrackSeedAnaModule::FillGenpHistograms(GenpHist_t* Hist, TGenParticle* Genp) { int gen_id; float p, cos_th, z0, t0, r0, x0, y0; TLorentzVector mom, v; Genp->Momentum(mom); // Genp->ProductionVertex(v); p = mom.P(); cos_th = mom.CosTheta(); x0 = Genp->Vx()+3904.; y0 = Genp->Vy(); z0 = Genp->Vz(); t0 = Genp->T(); r0 = sqrt(x0*x0+y0*y0); gen_id = Genp->GetStatusCode(); Hist->fPdgCode[0]->Fill(Genp->GetPdgCode()); Hist->fPdgCode[1]->Fill(Genp->GetPdgCode()); Hist->fGenID->Fill(gen_id); Hist->fZ0->Fill(z0); Hist->fT0->Fill(t0); Hist->fR0->Fill(r0); Hist->fP->Fill(p); Hist->fCosTh->Fill(cos_th); } //----------------------------------------------------------------------------- void TTrackSeedAnaModule::FillSimpHistograms(SimpHist_t* Hist, TSimParticle* Simp) { Hist->fPdgCode->Fill(Simp->fPdgCode); Hist->fMomTargetEnd->Fill(Simp->fMomTargetEnd); Hist->fMomTrackerFront->Fill(Simp->fMomTrackerFront); Hist->fNStrawHits->Fill(Simp->fNStrawHits); } //----------------------------------------------------------------------------- // register data blocks and book histograms //----------------------------------------------------------------------------- int TTrackSeedAnaModule::BeginJob() { //----------------------------------------------------------------------------- // register data blocks //----------------------------------------------------------------------------- RegisterDataBlock("TrackSeedBlock","TStnTrackSeedBlock",&fTrackSeedBlock ); RegisterDataBlock("GenpBlock" ,"TGenpBlock" ,&fGenpBlock ); RegisterDataBlock("SimpBlock" ,"TSimpBlock" ,&fSimpBlock ); //----------------------------------------------------------------------------- // book histograms //----------------------------------------------------------------------------- BookHistograms(); return 0; } //_____________________________________________________________________________ int TTrackSeedAnaModule::BeginRun() { int rn = GetHeaderBlock()->RunNumber(); TStntuple::Init(rn); return 0; } //_____________________________________________________________________________ void TTrackSeedAnaModule::FillHistograms() { // double cos_th (-2.), cl_e(-1.); // int disk_id(-1), alg_mask, nsh, nactive; // float pfront, ce_pitch, reco_pitch, fcons, t0, sigt, sigp, p; //----------------------------------------------------------------------------- // event histograms //----------------------------------------------------------------------------- FillEventHistograms(fHist.fEvent[0]); //----------------------------------------------------------------------------- // Simp histograms //----------------------------------------------------------------------------- if (fSimp) { FillSimpHistograms(fHist.fSimp[0],fSimp); } //-------------------------------------------------------------------------------- // track seed histograms //-------------------------------------------------------------------------------- TStnTrackSeed* trkSeed; for (int i=0; i<fNTrackSeeds; ++i) { trkSeed = fTrackSeedBlock->TrackSeed(i); FillTrackSeedHistograms(fHist.fTrackSeed[0], trkSeed); int nhits = trkSeed->NHits(); double p = trkSeed->P(); double chi2 = trkSeed->Chi2(); if (p > 80.) FillTrackSeedHistograms(fHist.fTrackSeed[1], trkSeed); if (p > 90.) FillTrackSeedHistograms(fHist.fTrackSeed[2], trkSeed); if (p > 100.) FillTrackSeedHistograms(fHist.fTrackSeed[3], trkSeed); if ( (nhits>10) && (nhits < 15)) FillTrackSeedHistograms(fHist.fTrackSeed[4], trkSeed); if ( nhits>=15 ) FillTrackSeedHistograms(fHist.fTrackSeed[5], trkSeed); if ( (chi2 < 4) && (nhits >= 15)) FillTrackSeedHistograms(fHist.fTrackSeed[6], trkSeed); } //----------------------------------------------------------------------------- // fill GENP histograms // GEN_0: all particles //----------------------------------------------------------------------------- TGenParticle* genp; for (int i=0; i<fNGenp; i++) { genp = fGenpBlock->Particle(i); FillGenpHistograms(fHist.fGenp[0],genp); } } //----------------------------------------------------------------------------- // 2014-04-30: it looks that reading the straw hits takes a lot of time - // turn off by default by commenting it out //----------------------------------------------------------------------------- int TTrackSeedAnaModule::Event(int ientry) { double p; // TEmuLogLH::PidData_t dat; // TStnTrack* track; // int id_word; TLorentzVector mom; // TDiskCalorimeter::GeomData_t disk_geom; fTrackSeedBlock->GetEntry(ientry); fGenpBlock->GetEntry(ientry); fSimpBlock->GetEntry(ientry); //----------------------------------------------------------------------------- // assume electron in the first particle, otherwise the logic will need to // be changed //----------------------------------------------------------------------------- fNGenp = fGenpBlock->NParticles(); fNTrackSeeds = fTrackSeedBlock->NTrackSeeds(); TGenParticle* genp; int pdg_code, generator_code; fParticle = NULL; for (int i=fNGenp-1; i>=0; i--) { genp = fGenpBlock->Particle(i); pdg_code = genp->GetPdgCode(); generator_code = genp->GetStatusCode(); if ((abs(pdg_code) == fPdgCode) && (generator_code == fGeneratorCode)) { fParticle = genp; break; } } // may want to revisit the definition of fSimp fSimp = fSimpBlock->Particle(0); if (fParticle) { fParticle->Momentum(mom); p = mom.P(); } else p = 0.; fEleE = sqrt(p*p+0.511*0.511); FillHistograms(); Debug(); return 0; } //----------------------------------------------------------------------------- void TTrackSeedAnaModule::Debug() { if (GetDebugBit(3)) { if (fNTrackSeeds == 0) GetHeaderBlock()->Print(Form("%s:bit:003 N(track seeds) = 0",GetName())); } } //_____________________________________________________________________________ int TTrackSeedAnaModule::EndJob() { printf("----- end job: ---- %s\n",GetName()); return 0; } //_____________________________________________________________________________ void TTrackSeedAnaModule::Test001() { } }
17,987
6,549
/** Copyright 2020 Alibaba Group Holding Limited. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef SRC_COMMON_BACKTRACE_BACKTRACE_HPP_ #define SRC_COMMON_BACKTRACE_BACKTRACE_HPP_ #ifdef WITH_LIBUNWIND #include <cxxabi.h> #include <libunwind.h> #include <iomanip> #include <limits> #include <memory> #include <ostream> namespace vineyard { struct backtrace_info { public: static void backtrace(std::ostream& _out, bool const compact = false) noexcept { thread_local char symbol[1024]; unw_cursor_t cursor; unw_context_t context; unw_getcontext(&context); unw_init_local(&cursor, &context); _out << std::hex << std::uppercase; while (0 < unw_step(&cursor)) { unw_word_t ip = 0; unw_get_reg(&cursor, UNW_REG_IP, &ip); if (ip == 0) { break; } unw_word_t sp = 0; unw_get_reg(&cursor, UNW_REG_SP, &sp); print_reg(_out, ip); _out << ": (SP:"; print_reg(_out, sp); _out << ") "; unw_word_t offset = 0; if (unw_get_proc_name(&cursor, symbol, sizeof(symbol), &offset) == 0) { _out << "(" << get_demangled_name(symbol) << " + 0x" << offset << ")\n"; if (!compact) { _out << "\n"; } } else { _out << "-- error: unable to obtain symbol name for this frame\n\n"; } } _out << std::flush; } static char const* get_demangled_name(char const* const symbol) noexcept { thread_local std::unique_ptr<char, decltype(std::free)&> demangled_name{ nullptr, std::free}; if (!symbol) { return "<null>"; } int status = -4; demangled_name.reset(abi::__cxa_demangle(symbol, demangled_name.release(), nullptr, &status)); return ((status == 0) ? demangled_name.get() : symbol); } private: static void print_reg(std::ostream& _out, unw_word_t reg) noexcept { constexpr std::size_t address_width = std::numeric_limits<std::uintptr_t>::digits / 4; _out << "0x" << std::setfill('0') << std::setw(address_width) << reg; } }; } // namespace vineyard #endif #endif // SRC_COMMON_BACKTRACE_BACKTRACE_HPP_
2,671
938
#include<sstream> #include<cassert> #include "operations.h" void runAllTests(); int main() { runAllTests(); return 0; } void testSingleMult() { Operator times{ type::mult, new Constant{3}, new Constant{5} }; // 3*5 ElementTree tree{ &times }; std::ostringstream os; tree.parse(os); std::ostringstream correct; correct << "3*5\n"; assert(os.str() == correct.str()); } void testSingleDiv() { Operator divide{ type::div, new Constant{ 3 }, new Constant{ 5 } }; // 3/5 ElementTree tree{ &divide }; std::ostringstream os; tree.parse(os); std::ostringstream correct; correct << "3/5\n"; assert(os.str() == correct.str()); } void testSingleAdd() { Operator plus{ type::add, new Constant{ 3 }, new Constant{ 5 } }; // 3+5 ElementTree tree{ &plus }; std::ostringstream os; tree.parse(os); std::ostringstream correct; correct << "3+5\n"; assert(os.str() == correct.str()); } void testSingleSub() { Operator minus{ type::sub, new Constant{ 3 }, new Constant{ 5 } }; // 3-5 ElementTree tree{ &minus }; std::ostringstream os; tree.parse(os); std::ostringstream correct; correct << "3-5\n"; assert(os.str() == correct.str()); } void runAllTests() { testSingleMult(); testSingleDiv(); testSingleAdd(); testSingleSub(); }
1,330
484
/*! \brief This file have the implementation for SQLiteWrapper class. \file sqlitewrapper.cc \author Alvaro Denis <denisacostaq@gmail.com> \date 6/19/2019 \copyright \attention <h1><center><strong>COPYRIGHT &copy; 2019 </strong> [<strong>denisacostaq</strong>][denisacostaq-URL]. All rights reserved.</center></h1> \attention This file is part of [<strong>DAQs</strong>][DAQs-URL]. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS PRODUCT IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS PRODUCT, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [denisacostaq-URL]: https://about.me/denisacostaq "Alvaro Denis Acosta" [DAQs-URL]: https://github.com/denisacostaq/DAQs "DAQs" */ #include "src/database-server/data-source/sqlitewrapper.h" #include <cerrno> #include <cstring> #include <exception> #include <iostream> #include <memory> #include <string> #include <vector> #include <sqlite3.h> #include "src/database-server/data-model/variable.h" #include "src/database-server/data-model/varvalue.h" SQLiteWrapper::SQLiteWrapper(const std::string &db_path) : IDataSource() { int err = sqlite3_open(db_path.c_str(), &db_); if (err != SQLITE_OK) { std::cerr << sqlite3_errmsg(db_) << "\n"; std::cerr << std::strerror(sqlite3_system_errno(db_)) << "\n"; throw std::string{"Can't open database " + db_path}; } else { std::clog << "Opened database successfully\n"; } } SQLiteWrapper::~SQLiteWrapper() { sqlite3_close(db_); } IDataSource::Err SQLiteWrapper::create_scheme() noexcept { std::vector<std::string> stataments; stataments.reserve(2); std::string sql = "CREATE TABLE VARIABLE(" "ID INTEGER PRIMARY KEY AUTOINCREMENT," "COLOR CHAR(50)," "NAME CHAR(50) NOT NULL UNIQUE);"; stataments.push_back(sql); sql = "CREATE TABLE VARIABLE_VALUE(" "ID INTEGER PRIMARY KEY AUTOINCREMENT," "VAL DOUBLE NOT NULL," "TIMESTAMP INTEGER NOT NULL," "VARIABLE_ID INT NOT NULL," "FOREIGN KEY (VARIABLE_ID) REFERENCES VARIABLE(ID));"; // FIXME(denisacostaq@gmail.com): // add constrints stataments.push_back(sql); for (const auto &s : stataments) { char *err = nullptr; int rc = sqlite3_exec(db_, s.c_str(), nullptr, nullptr, &err); if (rc != SQLITE_OK) { std::cerr << "SQL error: " << err << "\n"; sqlite3_free(err); return Err::Failed; } else { std::clog << "Table created successfully\n"; } } return Err::Ok; } IDataSource::Err SQLiteWrapper::add_variable(const Variable &var) noexcept { std::string sql = sqlite3_mprintf("INSERT INTO VARIABLE(NAME, COLOR) VALUES('%q', '%q')", var.name().c_str(), var.color().c_str()); char *err = nullptr; int res = sqlite3_exec(db_, sql.c_str(), nullptr, nullptr, &err); if (res != SQLITE_OK) { std::cerr << "Can not insert " << var.name() << ". " << err << "\n"; sqlite3_free(err); return Err::Failed; } std::clog << "Insertion ok\n"; return Err::Ok; } IDataSource::Err SQLiteWrapper::add_variable_value( const VarValue &var) noexcept { auto now{std::chrono::system_clock::now()}; auto timestamp{std::chrono::duration_cast<std::chrono::milliseconds>( now.time_since_epoch())}; char *err_msg = nullptr; std::string sql = sqlite3_mprintf( "INSERT INTO VARIABLE_VALUE(VAL, TIMESTAMP, VARIABLE_ID) VALUES(%f, %ld, " "(SELECT ID FROM VARIABLE WHERE NAME = '%q'))", var.val(), timestamp.count(), var.name().c_str()); if (sqlite3_exec(db_, sql.c_str(), nullptr, this, &err_msg) != SQLITE_OK) { std::cerr << "error " << err_msg << "\n"; sqlite3_free(err_msg); return Err::Failed; } return Err::Ok; } IDataSource::Err SQLiteWrapper::fetch_variables( const std::function<void(const Variable &var, size_t index)> &send_vale) noexcept { char *err_msg = nullptr; std::string query = "SELECT COLOR, NAME FROM VARIABLE"; using callbac_t = decltype(send_vale); using unqualified_callbac_t = std::remove_const_t<std::remove_reference_t<callbac_t>>; if (sqlite3_exec( db_, query.c_str(), +[](void *callback, int argc, char **argv, char **azColName) { Variable var{}; for (decltype(argc) i = 0; i < argc; i++) { if (strcmp("NAME", azColName[i]) == 0) { std::string name{""}; if (argv[i] != nullptr && std::strcmp(argv[i], "")) { name = argv[i]; } var.set_name(name); } else if (strcmp("COLOR", azColName[i]) == 0) { if (strcmp("COLOR", azColName[i]) == 0) { std::string color{""}; if (argv[i] != nullptr && std::strcmp(argv[i], "")) { color = argv[i]; } var.set_color(color); } } else { return -1; } } static_cast<callbac_t> ( *static_cast<unqualified_callbac_t *>(callback))(var, 0); return 0; }, const_cast<unqualified_callbac_t *>(&send_vale), &err_msg) != SQLITE_OK) { std::cerr << "error " << err_msg << "\n"; sqlite3_free(err_msg); return Err::Failed; } return Err::Ok; } namespace { struct CountCallback { size_t index; std::function<void(const VarValue &val, size_t)> *send_vale; }; }; // namespace IDataSource::Err SQLiteWrapper::fetch_variable_values( const std::string &var_name, const std::function<void(const VarValue &val, size_t index)> &send_vale) noexcept { char *err_msg = nullptr; std::string query = sqlite3_mprintf( "SELECT VAL, TIMESTAMP FROM VARIABLE_VALUE WHERE VARIABLE_ID = (SELECT " "ID FROM VARIABLE WHERE NAME = '%q')", var_name.c_str()); CountCallback cc{ 0, const_cast<std::function<void(const VarValue &, size_t)> *>(&send_vale)}; if (sqlite3_exec(db_, query.c_str(), +[](void *cc, int argc, char **argv, char **azColName) { VarValue val{}; for (int i = 0; i < argc; i++) { if (strcmp("VAL", azColName[i]) == 0) { try { size_t processed = 0; val.set_val(std::stod(argv[i], &processed)); } catch (std::invalid_argument e) { std::cerr << e.what(); return -1; } catch (std::out_of_range e) { std::cerr << e.what(); return -1; } } else if (strcmp("TIMESTAMP", azColName[i]) == 0) { try { size_t processed = 0; val.set_timestamp(std::stoull(argv[i], &processed)); } catch (std::invalid_argument e) { std::cerr << e.what(); return -1; } catch (std::out_of_range e) { std::cerr << e.what(); return -1; } } } auto count_callback{static_cast<CountCallback *>(cc)}; auto cb{count_callback->send_vale}; (*cb)(val, count_callback->index); ++count_callback->index; return 0; }, &cc, &err_msg) != SQLITE_OK) { std::cerr << "error " << err_msg << "\n"; sqlite3_free(err_msg); return Err::Failed; } return Err::Ok; } IDataSource::Err SQLiteWrapper::count_variable_values( const std::string &var_name, const std::function<void(size_t count)> &send_count) noexcept { char *err_msg = nullptr; std::string count_query = sqlite3_mprintf( "SELECT COUNT(*) FROM VARIABLE_VALUE WHERE VARIABLE_ID = (SELECT " "ID FROM VARIABLE WHERE NAME = '%q')", var_name.c_str()); if (sqlite3_exec( db_, count_query.c_str(), +[](void *callback, int argc, char **argv, char **azColName) { for (int i = 0; i < argc; ++i) { if (strcmp("COUNT(*)", azColName[i]) == 0) { size_t count{}; try { size_t processed = 0; count = std::stoull(argv[i], &processed); } catch (std::invalid_argument e) { std::cerr << e.what(); return -1; } catch (std::out_of_range e) { std::cerr << e.what(); return -1; } (*static_cast<std::function<void(size_t count)> *>(callback))( count); return 0; } } return 0; }, const_cast<std::function<void(size_t count)> *>(&send_count), &err_msg) != SQLITE_OK) { std::cerr << "error " << err_msg << "\n"; sqlite3_free(err_msg); return Err::Failed; } return Err::Ok; } IDataSource::Err SQLiteWrapper::fetch_variable_values( const std::string &var_name, const std::chrono::system_clock::time_point &start_date, const std::chrono::system_clock::time_point &end_date, const std::function<void(const VarValue &val, size_t index)> &send_vale) noexcept { char *err_msg = nullptr; const std::int64_t sd{ std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::time_point_cast<std::chrono::milliseconds>(start_date) .time_since_epoch()) .count()}; const std::int64_t ed{ std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::time_point_cast<std::chrono::milliseconds>(end_date) .time_since_epoch()) .count()}; std::string query = sqlite3_mprintf( "SELECT VAL, TIMESTAMP FROM VARIABLE_VALUE WHERE VARIABLE_ID = (SELECT " "ID FROM VARIABLE WHERE NAME = '%q') AND TIMESTAMP >= %ld AND TIMESTAMP " "<= %ld;", var_name.c_str(), sd, ed); CountCallback cc{ 0, const_cast<std::function<void(const VarValue &, size_t)> *>(&send_vale)}; if (sqlite3_exec(db_, query.c_str(), +[](void *cc, int argc, char **argv, char **azColName) { VarValue val{}; for (int i = 0; i < argc; i++) { if (strcmp("VAL", azColName[i]) == 0) { try { size_t processed = 0; val.set_val(std::stod(argv[i], &processed)); } catch (std::invalid_argument e) { std::cerr << e.what(); return -1; } catch (std::out_of_range e) { std::cerr << e.what(); return -1; } } else if (strcmp("TIMESTAMP", azColName[i]) == 0) { try { size_t processed = 0; val.set_timestamp(std::stoull(argv[i], &processed)); } catch (std::invalid_argument e) { std::cerr << e.what(); return -1; } catch (std::out_of_range e) { std::cerr << e.what(); return -1; } } } auto count_callback{static_cast<CountCallback *>(cc)}; auto cb{count_callback->send_vale}; (*cb)(val, count_callback->index); ++count_callback->index; return 0; }, &cc, &err_msg) != SQLITE_OK) { std::cerr << "error " << err_msg << "\n"; sqlite3_free(err_msg); return Err::Failed; } return Err::Ok; } IDataSource::Err SQLiteWrapper::count_variable_values( const std::string &var_name, const std::chrono::system_clock::time_point &start_date, const std::chrono::system_clock::time_point &end_date, const std::function<void(size_t count)> &send_count) noexcept { char *err_msg = nullptr; const std::int64_t sd{std::chrono::duration_cast<std::chrono::milliseconds>( start_date.time_since_epoch()) .count()}; const std::int64_t ed{std::chrono::duration_cast<std::chrono::milliseconds>( end_date.time_since_epoch()) .count()}; std::string count_query = sqlite3_mprintf( "SELECT COUNT(*) FROM VARIABLE_VALUE WHERE VARIABLE_ID = (SELECT ID FROM " "VARIABLE WHERE NAME = '%q') AND TIMESTAMP >= %ld AND TIMESTAMP <= %ld;", var_name.c_str(), sd, ed); if (sqlite3_exec( db_, count_query.c_str(), +[](void *callback, int argc, char **argv, char **azColName) { for (int i = 0; i < argc; ++i) { if (strcmp("COUNT(*)", azColName[i]) == 0) { size_t count{}; try { size_t processed = 0; count = std::stoull(argv[i], &processed); } catch (std::invalid_argument e) { std::cerr << e.what(); return -1; } catch (std::out_of_range e) { std::cerr << e.what(); return -1; } (*static_cast<std::function<void(size_t count)> *>(callback))( count); return 0; } } return 0; }, const_cast<std::function<void(size_t)> *>(&send_count), &err_msg) != SQLITE_OK) { std::cerr << "error " << err_msg << "\n"; sqlite3_free(err_msg); return Err::Failed; } return Err::Ok; }
15,546
4,984
// VTK_Operation.cpp : implmentation of VTK operations to visualize a 3D model // // Author: Jungho Park (jhpark16@gmail.com) // Date: May 2015 // Description: // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "resource.h" VTK_Operation::VTK_Operation(HWND hwnd, HWND hwndParent) { CreateVTKObjects(hwnd, hwndParent); } void VTK_Operation::clear(void) { // vtkSmartPointers are deleted by assigning nullptr // (or any other object) to the pointer #ifdef OpenVR actor.~vtkNew(); renderWindow.~vtkNew(); renderer.~vtkNew(); interactor.~vtkNew(); cam.~vtkNew(); // destroy text actor and mapper // Additional variables //reader = nullptr; //mapper = nullptr; //colors = nullptr; #else renderWindow.~vtkNew(); renderer.~vtkNew(); interactor.~vtkNew(); // destroy text actor and mapper textMapper.~vtkNew(); textActor2D.~vtkNew(); scalarBar.~vtkNew(); // Additional variables //reader = nullptr; //mapper = nullptr; //colors = nullptr; actor.~vtkNew(); //backFace = nullptr; #endif } VTK_Operation::~VTK_Operation() { clear(); } int VTK_Operation::CreateVTKObjects(HWND hwnd, HWND hwndParent) { // We create the basic parts of a pipeline and connect them #ifdef OpenVR /* vtkNew<vtkActor> actor; vtkNew<vtkOpenVRRenderer> renderer; vtkNew<vtkOpenVRRenderWindow> renderWindow; vtkNew<vtkOpenVRRenderWindowInteractor> interactor; vtkNew<vtkOpenVRCamera> cam;*/ /* renderer = vtkSmartPointer<vtkOpenVRRenderer>::New(); renderWindow = vtkSmartPointer<vtkOpenVRRenderWindow>::New(); interactor = vtkSmartPointer<vtkOpenVRRenderWindowInteractor>::New(); cam = vtkSmartPointer<vtkOpenVRCamera>::New();*/ #else /* actor = vtkSmartPointer<vtkActor>::New(); renderer = vtkSmartPointer<vtkOpenGLRenderer>::New(); renderWindow = vtkSmartPointer<vtkWin32OpenGLRenderWindow>::New(); interactor = vtkSmartPointer<vtkWin32RenderWindowInteractor>::New(); */ renderWindow->Register(NULL); #endif #ifdef OpenVR renderWindow->AddRenderer(renderer.Get()); renderer->AddActor(actor.Get()); interactor->SetRenderWindow(renderWindow.Get()); renderer->SetActiveCamera(cam.Get()); vtkNew<vtkConeSource> cone; vtkNew<vtkPolyDataMapper> mapper; mapper->SetInputConnection(cone->GetOutputPort()); actor->SetMapper(mapper.Get()); //Reset camera to show the model at the centre renderer->ResetCamera(); #else renderWindow->AddRenderer(renderer); interactor->SetInstallMessageProc(0); // setup the parent window renderWindow->SetWindowId(hwnd); renderWindow->SetParentId(hwndParent); interactor->SetRenderWindow(renderWindow); interactor->Initialize(); vtkNew<vtkInteractorStyleTrackballCamera> style; interactor->SetInteractorStyle(style); // Setup Text Actor //textMapper = vtkSmartPointer<vtkTextMapper>::New(); textMapper->SetInput("MODFLOW Model"); //textActor2D = vtkSmartPointer<vtkActor2D>::New(); textActor2D->SetDisplayPosition(450, 550); textMapper->GetTextProperty()->SetFontSize(30); textMapper->GetTextProperty()->SetColor(1.0, 1.0, 1.0); textActor2D->SetMapper(textMapper); // Add Axis //axes = vtkSmartPointer<vtkAxesActor>::New(); axes->SetNormalizedLabelPosition(1.2, 1.2, 1.2); axes->GetXAxisCaptionActor2D()->SetHeight(0.025); axes->GetYAxisCaptionActor2D()->SetHeight(0.025); axes->GetZAxisCaptionActor2D()->SetHeight(0.025); #ifndef OpenVR //widget = vtkSmartPointer<vtkOrientationMarkerWidget>::New(); widget->SetOutlineColor(0.9300, 0.5700, 0.1300); widget->SetOrientationMarker(axes); widget->SetInteractor(interactor); widget->SetEnabled(1); #endif // Prevent the interaction to fix the location of the coordinate axes triad // at the left bottom //widget->InteractiveOff(); // Trigger WM_SIZE widget->SetViewport(-0.8, -0.8, 0.25, 0.25); //Add the Actors renderer->AddActor(textActor2D); //renderer->SetBackground(colors->GetColor3d("Wheat").GetData()); renderer->SetBackground(.1, .2, .4); //Reset camera to show the model at the centre renderer->ResetCamera(); #endif //renderer->SetBackground(0.0, 0.0, 0.25); return(1); } int VTK_Operation::DestroyVTKObjects() { ATLTRACE("DestroyVTKObjects\n"); return(1); } int VTK_Operation::StepObjects(int count) { return(1); } void VTK_Operation::WidgetInteractiveOff(void) { #ifndef OpenVR widget->InteractiveOff(); // Trigger WM_SIZE #endif } void VTK_Operation::Render() { if (renderWindow) { renderWindow->Render(); //interactor->Render(); } } void VTK_Operation::OnSize(CSize size) { if (renderWindow) { //int *val1; //val1 = renderWindow->GetSize(); renderWindow->SetSize(size.cx, size.cy); if (textMapper && renderer->GetVTKWindow()) { int width = textMapper->GetWidth(renderer); this->size = size; textActor2D->SetDisplayPosition((size.cx - width) / 2, size.cy - 50); //interactor->UpdateSize(size.cx, size.cy); //interactor->SetSize(size.cx, size.cy); } } } void VTK_Operation::OnTimer(HWND hWnd, UINT uMsg) { #ifndef OpenVR interactor->OnTimer(hWnd, uMsg); #endif } void VTK_Operation::OnLButtonDblClk(HWND hWnd, UINT uMsg, CPoint point) { #ifndef OpenVR interactor->OnLButtonDown(hWnd, uMsg, point.x, point.y, 1); #endif } void VTK_Operation::OnLButtonDown(HWND hWnd, UINT uMsg, CPoint point) { #ifndef OpenVR interactor->OnLButtonDown(hWnd, uMsg, point.x, point.y, 0); #endif } void VTK_Operation::OnMButtonDown(HWND hWnd, UINT uMsg, CPoint point) { #ifndef OpenVR interactor->OnMButtonDown(hWnd, uMsg, point.x, point.y, 0); #endif } void VTK_Operation::OnRButtonDown(HWND hWnd, UINT uMsg, CPoint point) { #ifndef OpenVR interactor->OnRButtonDown(hWnd, uMsg, point.x, point.y, 0); #endif } void VTK_Operation::OnLButtonUp(HWND hWnd, UINT uMsg, CPoint point) { #ifndef OpenVR interactor->OnLButtonUp(hWnd, uMsg, point.x, point.y); #endif } void VTK_Operation::OnMButtonUp(HWND hWnd, UINT uMsg, CPoint point) { #ifndef OpenVR interactor->OnMButtonUp(hWnd, uMsg, point.x, point.y); #endif } void VTK_Operation::OnRButtonUp(HWND hWnd, UINT uMsg, CPoint point) { #ifndef OpenVR interactor->OnRButtonUp(hWnd, uMsg, point.x, point.y); #endif } void VTK_Operation::OnMouseMove(HWND hWnd, UINT uMsg, CPoint point) { #ifndef OpenVR interactor->OnMouseMove(hWnd, uMsg, point.x, point.y); #endif } void VTK_Operation::OnChar(HWND hWnd, UINT nChar, UINT nRepCnt, UINT nFlags) { #ifndef OpenVR interactor->OnChar(hWnd, nChar, nRepCnt, nFlags); #endif } void VTK_Operation::FileNew() { renderer->RemoveActor(actor); renderer->RemoveActor(scalarBar); } void VTK_Operation::FileOpen(PHT3D_Model& mPHT3DM, CString fileName) { // Model Data //read all the data from the file /* vtkSmartPointer<vtkXMLUnstructuredGridReader> reader = vtkSmartPointer<vtkXMLUnstructuredGridReader>::New(); reader->SetFileName(_T("D:\\Study\\MODFLOW\\RegionalGroundwaterModelingwithMODFLOWandFlopy\\vtuFiles\\Model1_HD_Heads.vtu")); reader->Update(); vtkSmartPointer<vtkUnstructuredGrid> output = reader->GetOutput(); output->GetCellData()->SetScalars(output->GetCellData()->GetArray(0)); */ //vtkUnstructuredGrid construction vtkNew<vtkUnstructuredGrid> unstGrid; vtkNew<vtkFloatArray> fArr; vtkNew<vtkDoubleArray> dArr; vtkNew<vtkIntArray> iArr; vtkNew<vtkCellArray> cellArr; vtkNew<vtkIdTypeArray> cellIdType; vtkNew<vtkPoints> points; MODFLOWClass& mf = mPHT3DM.MODFLOW; double minVal=0, maxVal = 0; if (1) { OpenModel(mPHT3DM, fileName); int nCol = mf.DIS_NCOL + 1; int nRow = mf.DIS_NROW + 1; int nLay = mf.DIS_NLAY + 1; float *xLoc = new float[nCol]{}; float *yLoc = new float[nRow]{}; float *zLoc = new float[nRow*nCol]{}; xLoc[0] = 0; yLoc[0] = 0; for (int i = 0; i < nCol-1; i++) { xLoc[i + 1] = xLoc[i] + mf.DIS_DELR[i]; } for (int i = 0; i < nRow-1; i++) { yLoc[i + 1] = yLoc[i] + mf.DIS_DELC[i]; } // Reverse Y for correct model display for (int i = 0; i < (nRow-1)/2; i++) { int iTmp = yLoc[i]; yLoc[i] = yLoc[nRow - 1 - i]; yLoc[nRow - 1 - i] = iTmp; } int nPoints = (mf.DIS_NLAY + 1)*(mf.DIS_NROW + 1)*(mf.DIS_NCOL + 1); unique_ptr<float[]> locations(new float[3 * nPoints]); //float *locations = new float[3 * nPoints]{}; unique_ptr<int[]> connectivity(new int[9 * ((nLay - 1)*(nRow - 1)*(nCol - 1))]); unique_ptr<double[]> dVal(new double[((nLay - 1)*(nRow - 1)*(nCol - 1))]); //int *connectivity = new int[9*((nLay - 1)*(nRow - 1)*(nCol - 1))]{}; //int *connectivity = new int[(nLay-1)*(nRow-1)*(nCol-1)] {}; // The heights are not aligned at each nodal points. So, it is necessary to estimate the height // at each node using interpolation of heights CPPMatrix2<double> *elevation = &(mf.DIS_TOP); for (int k = 0; k < nLay; k++) { // Takes care of four corners if (k == 0) { // The elevation of the top layer is from the DIS_TOP elevation = &(mf.DIS_TOP); } else { // The bottom elevation is used for most layers elevation = &(mf.DIS_BOTMS[k - 1]); } zLoc[0 * nCol + 0] = (*elevation)[0][0]; zLoc[0 * nCol + (nCol-1)] = (*elevation)[0][nCol-2]; zLoc[(nRow - 1) * nCol + 0] = (*elevation)[nRow-2][0]; zLoc[(nRow - 1) * nCol + (nCol-1)] = (*elevation)[nRow-2][nCol-2]; // Interpolate edges along X direction for (int i = 1; i < nCol-1; i++) { zLoc[0*nCol + i] = ((*elevation)[0][i-1] + (*elevation)[0][i])/2.0; zLoc[(nRow-1)*nCol + i] = ((*elevation)[nRow-2][i-1] + (*elevation)[nRow - 2][i])/2.0; } // Interpolate edges along Y direction for (int j = 1; j < nRow - 1; j++) { zLoc[(j * nCol) + 0] = ((*elevation)[j-1][0] + (*elevation)[j][0]) / 2.0; zLoc[(j * nCol) + nCol-1] = ((*elevation)[j-1][nCol-2] + (*elevation)[j][nCol-2]) / 2.0; } // Interpolate the remaining part of the 3D model for (int j = 1; j < nRow-1; j++) { for (int i = 1; i < nCol-1; i++) { zLoc[(j * nCol) + i] = ((*elevation)[j - 1][i - 1] + (*elevation)[j][i - 1] + (*elevation)[j - 1][i] + (*elevation)[j][i]) / 4.0; } } // Set the X, Y, Z of all nodal points for (int j = 0; j < nRow; j++) { for (int i = 0; i < nCol; i++) { locations[3 * (k*(nRow*nCol) + j*(nCol)+i) + 0] = xLoc[i]; //X value locations[3 * (k*(nRow*nCol) + j*(nCol)+i) + 1] = yLoc[j]; //Y value locations[3 * (k*(nRow*nCol) + j*(nCol)+i) + 2] = zLoc[j*nCol+i]; //Z value } } } int numCells = 0; minVal = DBL_MAX; maxVal = -DBL_MAX; for (int k = 0; k < nLay-1; k++) { for (int j = 0; j < nRow-1; j++) { for (int i = 0; i < nCol-1; i++) { if (mf.BAS_IBOUND[k][j][i]) { connectivity[9 * numCells + 0] = 8; connectivity[9 * numCells + 1] = (k + 1)*(nRow*nCol) + (j + 1)*nCol + (i); connectivity[9 * numCells + 2] = (k + 1)*(nRow*nCol) + (j + 1)*nCol + (i + 1); connectivity[9 * numCells + 3] = (k+1)*(nRow*nCol) + (j)*nCol + (i+1); connectivity[9 * numCells + 4] = (k + 1)*(nRow*nCol) + (j)*nCol + (i); connectivity[9 * numCells + 5] = (k)*(nRow*nCol) + (j + 1)*nCol + (i); connectivity[9 * numCells + 6] = (k)*(nRow*nCol) + (j + 1)*nCol + (i + 1); connectivity[9 * numCells + 7] = (k)*(nRow*nCol) + (j)*nCol + (i + 1); connectivity[9 * numCells + 8] = (k)*(nRow*nCol) + (j)*nCol + (i); double tVal = mf.BAS_STRT[k][j][i]; dVal[numCells] = tVal; if (tVal < minVal) minVal = tVal; if (tVal > maxVal) maxVal = tVal; numCells++; } } } } cellIdType->SetArray(connectivity.get(), numCells*9, 1); connectivity.release(); fArr->SetNumberOfComponents(3); //3D data points fArr->SetArray(locations.get(), 3 * nPoints, 0); locations.release(); // Must release the pointer to prevent crash points->SetData(fArr); // The array should be allocated on the heap points->SetDataTypeToFloat(); // Setup cell array using the raw data cellArr->SetCells(numCells, cellIdType); dArr->SetNumberOfComponents(1); dArr->SetArray(dVal.get(), numCells, 1); dVal.release(); // Must release the pointer to prevent crash for (int i = 1; i < numCells; i++) { } //dArr->SetTuple1(0, 0.1); dArr->SetTuple1(1, 0.5); // Assemble the unstructured grid unstGrid->SetPoints(points); unstGrid->SetCells(12, cellArr); // 12 is the cell type unstGrid->GetCellData()->SetScalars(dArr); } else { int nPoints = 12; int numCells = 2; //cellIdType->SetNumberOfValues(18); int *iCon = new int[numCells*9]{ 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 9, 10, 11 }; cellIdType->SetArray(iCon, numCells * 9, 1); /* cellIdType->SetValue(0, 8); cellIdType->SetValue(1, 0); cellIdType->SetValue(2, 1); cellIdType->SetValue(3, 2); cellIdType->SetValue(4, 3); cellIdType->SetValue(5, 4); cellIdType->SetValue(6, 5); cellIdType->SetValue(7, 6); cellIdType->SetValue(8, 7); cellIdType->SetValue(9, 8); cellIdType->SetValue(10, 4); cellIdType->SetValue(11, 5); cellIdType->SetValue(12, 6); cellIdType->SetValue(13, 7); cellIdType->SetValue(14, 8); cellIdType->SetValue(15, 9); cellIdType->SetValue(16, 10); cellIdType->SetValue(17, 11); */ cellArr->SetCells(numCells, cellIdType); // Set points double *(val[12]); float *fPos = new float[nPoints * 3]{ 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 2, 0, 0, 2, 0, 1, 2, 1, 1, 2, 1, 0 }; fArr->SetNumberOfComponents(3); //3D data points //fArr->SetNumberOfTuples(12); // 12 set of 3D data points (not necessary) fArr->SetArray(fPos, nPoints*3, 0); points->SetData(fArr); // The array should be allocated on the heap points->SetDataTypeToFloat(); /* for (int i = 0; i<12; i++) val[i] = points->GetPoint(i); points->SetNumberOfPoints(12); points->SetPoint(0, 0, 0, 0.); points->SetPoint(1, 0, 0, 1.); points->SetPoint(2, 0, 1, 1.); points->SetPoint(3, 0, 1, 0.); points->SetPoint(4, 1, 0, 0.); points->SetPoint(5, 1, 0, 1.); points->SetPoint(6, 1, 1, 1.); points->SetPoint(7, 1, 1, 0.); points->SetPoint(8, 2, 0, 0.); points->SetPoint(9, 2, 0, 1.); points->SetPoint(10, 2, 1, 1.); points->SetPoint(11, 2, 1, 0.); points->SetDataTypeToFloat(); // Point set should be float type for (int i = 0; i<12; i++) val[i] = points->GetPoint(i); */ cellArr->SetCells(numCells, cellIdType); dArr->SetNumberOfComponents(1); //dArr->SetNumberOfTuples(2); minVal = 0, maxVal = 1; dArr->SetArray(new double[numCells] {0.1,0.5}, numCells, 1); //dArr->SetTuple1(0, 0.1); dArr->SetTuple1(1, 0.5); unstGrid->SetPoints(points); unstGrid->SetCells(12, cellArr); // 12 is the cell type unstGrid->GetCellData()->SetScalars(dArr); } // Setup Model Actor vtkNew<vtkDataSetMapper> mapper; //mapper->SetInputConnection(reader->GetOutputPort()); mapper->SetInputData(unstGrid); //mapper->ScalarVisibilityOff(); mapper->ScalarVisibilityOn(); // Scale bar actor for the Colormap //scalarBar = vtkSmartPointer<vtkScalarBarActor>::New(); scalarBar->SetLookupTable(mapper->GetLookupTable()); scalarBar->SetUnconstrainedFontSize(true); scalarBar->SetTitle("Head (ft)"); scalarBar->SetVerticalTitleSeparation(5); scalarBar->GetTitleTextProperty()->SetFontSize(20); scalarBar->GetTitleTextProperty()->ItalicOff(); scalarBar->SetLabelFormat("%.1f"); scalarBar->GetLabelTextProperty()->ItalicOff(); scalarBar->GetLabelTextProperty()->SetFontSize(15); scalarBar->SetPosition(0.87, 0.2); scalarBar->SetHeight(0.5); scalarBar->SetWidth(0.11); scalarBar->SetNumberOfLabels(4); // Jet color scheme vtkNew<vtkLookupTable> jet; jet->SetNumberOfColors(257); jet->Build(); for (int i = 0; i <= 64; i++) { jet->SetTableValue(i, 0, i / 64.0, 1, 1); } for (int i = 65; i <= 128; i++) { jet->SetTableValue(i, 0, 1, 1.0 - (i - 64.0) / 64.0, 1); } for (int i = 129; i <= 192; i++) { jet->SetTableValue(i, (i - 128.0) / 64.0, 1, 0, 1); } for (int i = 193; i <= 256; i++) { jet->SetTableValue(i, 1, 1 - (i - 192.0) / 64.0, 0, 1); } //jet->SetTableRange(3407.6445, 4673.021); mapper->SetLookupTable(jet); scalarBar->SetLookupTable(jet); mapper->SetColorModeToMapScalars(); //mapper->SetScalarRange(3407.6445, 4673.021); // min max range cannot be switched mapper->SetScalarRange(minVal, maxVal); // min max range cannot be switched mapper->SetUseLookupTableScalarRange(false); // Set scalar mode mapper->SetScalarModeToUseCellData(); //mapper->SetScalarModeToUsePointData(); actor->SetMapper(mapper); // True for grid lines if (true) { actor->GetProperty()->SetLineWidth(0.001); // This should not be zero => OpenGL error (invalid value) actor->GetProperty()->EdgeVisibilityOn(); } else actor->GetProperty()->EdgeVisibilityOff(); // Backface setup vtkNew<vtkNamedColors> colors; vtkNew<vtkProperty> backFace; backFace->SetColor(colors->GetColor3d("tomato").GetData()); actor->SetBackfaceProperty(backFace); renderer->AddActor(actor); renderer->AddActor(scalarBar); //Reset camera to show the model at the centre renderer->ResetCamera(); #ifdef OpenVR renderWindow->Render(); interactor->Start(); #endif }
17,529
7,278
#include "hayai-test.hpp" #ifndef __HAYAI_FIXTURE #define __HAYAI_FIXTURE namespace Hayai { typedef Test Fixture; } #endif
128
57
#include <iostream> using namespace std; void printArray(int* array, int n, const char* message); //a function that inits an array void initArray(int* array, int n, int value) { for (int i = 0; i < n; i++) { array[i] = value; } } //IT'S WRONG //DON'T USE IT int resizeArray(int* array, int n) { int newSize; cout << endl << "New size is:"; cin >> newSize; //delete[] array; //array = new int[newSize]; cout << endl << "Values:"; for (int i = 0; i < newSize; i++) { cout << endl << "value " << i + 1 << ": "; cin >> array[i]; } return newSize; } int main() { std::cout << endl << "Hello World !"; int array1[5]; int n1 = 5; int array2[10]; int n2 = 10; int n3 = 5; int* array3 = new int[n3]; //init the arrays initArray(array1, n1, 1); initArray(array2, n2, 20); initArray(array3, n3, 50); cout << endl << "Array 1:"; for (int i = 0; i < n1; i++) cout << array1[i] << " "; //they have the same type //array3 = array1; printArray(array2, n2, "Array 2:"); printArray(array3, n3, "Array 3:"); //resize them n1 = resizeArray(array2, n2); printArray(array1, n1, "Array 1:"); printArray(array2, n2, "Array 2:"); } //function for printing an array void printArray(int* array, int n, const char* message) { //message[0] = 'A'; cout << endl << message; for (int i = 0; i < n; i++) cout << array[i] << " "; }
1,361
591
#include "Map.h" Map::Map() { _size = 0; } Map::~Map() { for (int i = 0; i < _size; i++) { delete[] _map_matrix[i]; } delete[] _map_matrix; } void Map::resize(int size) { _size = size; _map_matrix = new char*[size]; for (int i = 0; i < size; i++) { _map_matrix[i] = new char[size]; for (int j = 0; j < size; j++) { _map_matrix[i][j] = ' '; if (j == 0 || j == size - 1) _map_matrix[i][j] = '='; if (i == 0 || i == size - 1) _map_matrix[i][j] = '='; } } } int Map::showSize() { return _size; } void Map::show() { for (int i = 0; i < _size; i++) { for (int j = 0; j < _size; j++) { std::cout << _map_matrix[i][j]; } std::cout << std::endl; } } void Map::setValueAtCoords(Position position, char value) { _map_matrix[position.x][position.y] = value; } char Map::showValueAtCoords(Position position) { if (position.x > _size - 2 || position.y > _size - 2 || position.x < 1 || position.y < 1) return 'n'; // functia returneaza 'n' pt tot ce e in afara mapei return _map_matrix[position.x][position.y]; }
1,070
520
#pragma once #include <chrono> /** * @brief Timer (実行時間計測) */ class Timer { std::chrono::system_clock::time_point m_start; public: Timer() = default; inline void start() { m_start = std::chrono::system_clock::now(); } inline uint64_t elapsedMilli() const { using namespace std::chrono; const auto end = system_clock::now(); return duration_cast<milliseconds>(end - m_start).count(); } };
450
154
#include <iostream> #include <string> using namespace std; int main() { ios_base::sync_with_stdio(false); int t; cin >> t; for (int i = 0; i < t; i++) { string a, b, c; cin >> a >> b >> c; int n = a.size(); bool pass = true; for (int j = 0; j < n; j++) { if (c[j] != a[j] && c[j] != b[j]) { pass = false; break; } } if (pass) { cout << "YES" << endl; } else { cout << "NO" << endl; } } return 0; }
446
232
#ifndef CaloMC_CaloWFExtractor_hh #define CaloMC_CaloWFExtractor_hh // // Utility to simulate waveform hit extraction in FPGA // #include <vector> namespace mu2e { class CaloWFExtractor { public: CaloWFExtractor(unsigned bufferDigi, int minPeakADC,unsigned nBinsPeak) : bufferDigi_(bufferDigi),minPeakADC_(minPeakADC),nBinsPeak_(nBinsPeak) {}; void extract(const std::vector<int>& wf, std::vector<unsigned>& starts, std::vector<unsigned>& stops) const; private: unsigned bufferDigi_; int minPeakADC_; unsigned nBinsPeak_; }; } #endif
737
228
#include "include/sunspec/common.hpp" using namespace sunspec; Common::Common(/* args */) { } Common::~Common() { }
118
45
#include "Widget.h" #include "ui_Widget.h" #include "Escena.h" Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); mEscena = new Escena(this); ui->graphicsView->setScene(mEscena); mEscena->iniciaEscena(); } Widget::~Widget() { delete ui; }
310
130
/** * Parrot Drones Awesome Video Viewer Library * Media interface * * Copyright (c) 2016 Aurelien Barre * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _PDRAW_MEDIA_HPP_ #define _PDRAW_MEDIA_HPP_ #include "pdraw_decoder.hpp" #include <pdraw/pdraw_defs.h> #include <inttypes.h> #include <pthread.h> #include <string> namespace Pdraw { enum elementary_stream_type { ELEMENTARY_STREAM_TYPE_UNKNOWN = 0, ELEMENTARY_STREAM_TYPE_VIDEO_AVC, }; class Session; class Media { public: virtual ~Media( void) {} virtual void lock( void) = 0; virtual void unlock( void) = 0; virtual enum pdraw_media_type getType( void) = 0; virtual unsigned int getId( void) = 0; virtual int enableDecoder( void) = 0; virtual int disableDecoder( void) = 0; virtual Session *getSession( void) = 0; virtual Decoder *getDecoder( void) = 0; protected: pthread_mutex_t mMutex; unsigned int mId; Session *mSession; }; } /* namespace Pdraw */ #endif /* !_PDRAW_MEDIA_HPP_ */
2,456
918
/** * @file simulator_handler.hpp * @brief Defines SimulatorHandlerImpl. * * @copyright Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ #ifndef ADUC_SIMULATOR_HANDLER_HPP #define ADUC_SIMULATOR_HANDLER_HPP #include "aduc/content_handler.hpp" #include "aduc/logging.h" EXTERN_C_BEGIN /** * @brief Instantiates an Update Content Handler simulator. * @return A pointer to an instantiated Update Content Handler object. */ ContentHandler* CreateUpdateContentHandlerExtension(ADUC_LOG_SEVERITY logLevel); EXTERN_C_END /** * @class SimulatorHandlerImpl * @brief The simulator handler implementation. */ class SimulatorHandlerImpl : public ContentHandler { public: static ContentHandler* CreateContentHandler(); // Delete copy ctor, copy assignment, move ctor and move assignment operators. SimulatorHandlerImpl(const SimulatorHandlerImpl&) = delete; SimulatorHandlerImpl& operator=(const SimulatorHandlerImpl&) = delete; SimulatorHandlerImpl(SimulatorHandlerImpl&&) = delete; SimulatorHandlerImpl& operator=(SimulatorHandlerImpl&&) = delete; ~SimulatorHandlerImpl() override; ADUC_Result Download(const tagADUC_WorkflowData* workflowData) override; ADUC_Result Install(const tagADUC_WorkflowData* workflowData) override; ADUC_Result Apply(const tagADUC_WorkflowData* workflowData) override; ADUC_Result Cancel(const tagADUC_WorkflowData* workflowData) override; ADUC_Result IsInstalled(const tagADUC_WorkflowData* workflowData) override; private: // Private constructor, must call CreateContentHandler factory method. SimulatorHandlerImpl() { } }; /** * @brief Get the simulator data file path. * * @return char* A buffer contains file path. Caller must call free() once done. */ char* GetSimulatorDataFilePath(); #endif // ADUC_SIMULATOR_HANDLER_HPP
1,862
564
#ifndef LOCKER_FS_HPP_INCLUDED #define LOCKER_FS_HPP_INCLUDED #include <string> #include <tuple> namespace locker { auto get_locker_home() noexcept -> std::pair<bool, std::string>; } #endif //LOCKER_FS_HPP_INCLUDED
220
101
#include "dlgtimedate.h" #include "ui_dlgtimedate.h" dlgTimeDate::dlgTimeDate(QWidget *parent) : QDialog(parent), ui(new Ui::dlgTimeDate) { pParent = parent; ui->setupUi(this); } dlgTimeDate::~dlgTimeDate() { delete ui; }
245
109
#include "subsystems/Arm.h" #include <frc/smartdashboard/SmartDashboard.h> Arm::Arm(){ m_arm.RestoreFactoryDefaults(); SetName("Arm"); } void Arm::Rotate(double speed){ m_arm.Set(speed); } void Arm::Stop(){ m_arm.Set(0); }
243
102
#include "tile.hpp" Tile::Tile(int x, int y, int w, int h): sprite(), x(x), y(y), marked(false), color(Textures::EmptyBlock) { this->sprite.setTexture(*texturemanager.get(Textures::EmptyBlock)); this->sprite.scale(w / this->sprite.getGlobalBounds().width, h / this->sprite.getGlobalBounds().height); this->setPosition(this->x * w, this->y * h); } void Tile::setColor(Textures::ID id) { this->sprite.setTexture(*texturemanager.get(id)); this->color = id; } sf::FloatRect Tile::getBounds() { return sf::FloatRect(sf::Vector2f(this->getPosition()), sf::Vector2f(44, 44)); } bool Tile::getMarked() { return this->marked; } Textures::ID Tile::getColor() { return this->color; } void Tile::mark(bool marked) { if(this->marked != marked) { this->marked = marked; if(DEBUG) { if(marked) { this->sprite.setColor(sf::Color::Yellow); } else { this->sprite.setColor(sf::Color::White); } } } } bool Tile::isEmpty() { return this->color == Textures::EmptyBlock || this->color == Textures::EmptyBlockDbg; } void Tile::draw(sf::RenderTarget& rt, sf::RenderStates rs) const { rs.transform *= this->getTransform(); rs.texture = NULL; rt.draw(this->sprite, rs); }
1,414
503
// // Created by kirlos on 2020-07-19. // #include "MainMenu.h" MainMenu::MainMenu(float width, float height, sf::Font &font) : MenuScroller(width, height, font, MAX_NUMBER_OF_ITEMS){ menu[0].setFont(font); menu[0].setFillColor(sf::Color::Blue); menu[0].setString("Play"); menu[0].setPosition(sf::Vector2f(X_OFFSET, height / (MAX_NUMBER_OF_ITEMS + 1) * 1)); menu[0].setCharacterSize(FONT_SIZE); menu[1].setFont(font); menu[1].setFillColor(sf::Color::Red); menu[1].setString("Hall Of Fame"); menu[1].setPosition(sf::Vector2f(X_OFFSET, height / (MAX_NUMBER_OF_ITEMS + 1) * 2)); menu[1].setCharacterSize(FONT_SIZE); menu[2].setFont(font); menu[2].setFillColor(sf::Color::Red); menu[2].setString("Options"); menu[2].setPosition(sf::Vector2f(X_OFFSET, height / (MAX_NUMBER_OF_ITEMS + 1) * 3)); menu[2].setCharacterSize(FONT_SIZE); menu[3].setFont(font); menu[3].setFillColor(sf::Color::Red); menu[3].setString("About Us"); menu[3].setPosition(sf::Vector2f(X_OFFSET, height / (MAX_NUMBER_OF_ITEMS + 1) * 4)); menu[3].setCharacterSize(FONT_SIZE); menu[4].setFont(font); menu[4].setFillColor(sf::Color::Red); menu[4].setString("Exit"); menu[4].setPosition(sf::Vector2f(X_OFFSET, height / (MAX_NUMBER_OF_ITEMS + 1) * 5)); menu[4].setCharacterSize(FONT_SIZE); } MainMenu::~MainMenu() { }
1,386
564
#include <QCheckBox> #include <QTableWidget> #include <QGraphicsWidget> #include <QGraphicsLayout> #include <QGraphicsScene> #include <QVBoxLayout> #include <QGraphicsSceneMouseEvent> #include "spaghetti/element.h" #include "CRPTR.h" #include "CRPTRNode.h" namespace CRPTR { class CRPTR; class CRPTRNode; enum class PBType { ePush, eToggle }; #define HBUTTON 15 #define HBUTTON_SPACE 5 #define HBUTTON_GLOBAL 25 class PushButtonWidget : public QGraphicsItem { public: // explicit PushButtonWidget(QGraphicsItem *const a_parent = nullptr); // ~PushButtonWidget() override; QRectF boundingRect() const override { return m_boundingRect; } void mousePressEvent(QGraphicsSceneMouseEvent *a_event) override { (void)a_event; if (m_type == PBType::eToggle){ //m_state = true; m_CRPTR->toggle(index); } else { //m_state = true; m_CRPTR->set(index,true); } } void mouseReleaseEvent(QGraphicsSceneMouseEvent *a_event) override { (void)a_event; if (m_type == PBType::eToggle){ //nop } else { //m_state = false; m_CRPTR->set(index,false); if (m_CRPTRNode != nullptr){ m_CRPTRNode->onPBReleased(index); } } } void paint(QPainter *a_painter, QStyleOptionGraphicsItem const *a_option, QWidget *a_widget) override { (void)a_option; (void)a_widget; updRec(); QBrush const BRUSH{ (state() ? QColor{ 203, 217, 81 } : QColor{ 244, 53, 64 }) }; QPen const PEN{ Qt::black }; a_painter->setPen(PEN); a_painter->setBrush(BRUSH); //a_painter->drawRect(m_boundingRect); a_painter->drawRect(boundingRect()); } void setCRPTR(CRPTR *const rptr) { m_CRPTR = rptr; } void setCRPTRNode(CRPTRNode *const node) { m_CRPTRNode = node; } void setIndex( size_t n) { index = n; } void setType( PBType nType) { m_type = nType; } void setState(bool nstate) { if (m_CRPTR != nullptr) m_CRPTR->pbStates()[index] = nstate; } bool state() { return (m_CRPTR != nullptr) ? m_CRPTR->pbStates()[index] : false; } void updRec(){ m_boundingRect.setX((m_type == PBType::ePush)?0:40); m_boundingRect.setY(index*(HBUTTON+HBUTTON_SPACE)); m_boundingRect.setHeight(HBUTTON); m_boundingRect.setWidth(40); } private: size_t index = 0; //bool m_state{}; PBType m_type{ PBType::ePush }; QRectF m_boundingRect{ 0, 0, 40, index*(HBUTTON+HBUTTON_SPACE) }; //QRectF m_boundingRect{ 0, 0, 0, 0 }; CRPTR *m_CRPTR{}; CRPTRNode *m_CRPTRNode{}; }; class PushButtonsWidget : public QGraphicsItem { public: QRectF boundingRect() const override { return m_boundingRect;/*return m_boundingRect;*/ } /*void mousePressEvent(QGraphicsSceneMouseEvent *a_event) override { //(void)a_event; //m_state = true; //m_pushButton->set(index,m_state); } void mouseReleaseEvent(QGraphicsSceneMouseEvent *a_event) override { //(void)a_event; //m_state = false; //m_pushButton->set(index,m_state); }*/ void paint(QPainter *a_painter, QStyleOptionGraphicsItem const *a_option, QWidget *a_widget) override { (void)a_option; (void)a_widget; updRec(); //QBrush const BRUSH{ (m_state ? QColor{ 203, 217, 81 } : QColor{ 244, 53, 64 }) }; //QPen const PEN{ Qt::black }; //a_painter->setPen(PEN); //a_painter->setBrush(BRUSH); //a_painter->drawRect(m_boundingRect); //a_painter->drawRect(boundingRect()); } void setCRPTR(CRPTR *const a_pushButton) { m_crptr = a_pushButton; } private: void updRec(){ if (m_crptr != nullptr){ m_boundingRect.setHeight(m_crptr->outputs().size()*(HBUTTON+HBUTTON_SPACE)+HBUTTON_GLOBAL); } } //size_t index = 0; //bool m_state{}; QRectF m_boundingRect{ 0, 0, 80, 0 }; CRPTR *m_crptr{}; }; void CRPTRNode::onPBReleased(size_t index){ // update toggle button if (index<m_tbuttons.size()){ m_tbuttons[index]->setState(false); //m_rbuttons[index]->setState(false); } } void CRPTRNode::addPButtons(){ bool delta = false; while (m_pbuttons.size()<outputs().size()){ auto const button = new PushButtonWidget;//{ static_cast<PushButtonsWidget *>(m_centralWidget) }; button->setType(PBType::ePush); button->setCRPTR(static_cast<CRPTR *>(m_element)); button->setIndex(m_pbuttons.size()); button->setParentItem(static_cast<PushButtonsWidget *>(m_centralWidget)); button->setCRPTRNode(this); m_pbuttons.push_back(button); delta=true; } while (m_pbuttons.size()>outputs().size()){ delete m_pbuttons.back(); m_pbuttons.pop_back(); delta=true; } while (m_tbuttons.size()<outputs().size()){ auto const button = new PushButtonWidget;//{ static_cast<PushButtonsWidget *>(m_centralWidget) }; button->setType(PBType::eToggle); button->setCRPTR(static_cast<CRPTR *>(m_element)); button->setIndex(m_tbuttons.size()); button->setParentItem(static_cast<PushButtonsWidget *>(m_centralWidget)); button->setCRPTRNode(this); m_tbuttons.push_back(button); delta=true; } while (m_tbuttons.size()>outputs().size()){ delete m_tbuttons.back(); m_tbuttons.pop_back(); delta=true; } /*if (delta){ expand(); iconify(); expand(); QGraphicsSceneMouseEvent me{};// = new QGraphicsSceneMouseEvent(); mouseDoubleClickEvent(&me); }*/ } CRPTRNode::CRPTRNode() { auto const widget = new PushButtonsWidget;//{ this }; //widget->layout()->setAlignment(Qt::AlignTop); //QVBoxLayout layout = QVBoxLayout(); //QVBoxLayout *playout = new chips/CRPTRQVBoxLayout; //layout.setAlignment(Qt.AlignTop) //playout->setAlignment(Qt::AlignTop); //widget->setLayout((QGraphicsLayout *)playout); setCentralWidget(widget); //QGraphicsLayout layout = new QGraphicsLayout; m_widget = widget; } void CRPTRNode::paint(QPainter *a_painter, QStyleOptionGraphicsItem const *a_option, QWidget *a_widget) { (void)a_option; (void)a_widget; paintBorder(a_painter); } void CRPTRNode::elementSet() { auto const pushButtonsWidget = static_cast<PushButtonsWidget *>(m_centralWidget); pushButtonsWidget->setCRPTR(static_cast<CRPTR *>(m_element)); addPButtons(); //removeInput(); /*(m_mode == Mode::eIconified) ?*/ //expand();// : iconify(); //calculateBoundingRect(); //pvShowProperties(); //scene()->update(); //expand(); //updateOutputs(); //refreshCentralWidget(); //update(); } void CRPTRNode::refreshCentralWidget() { if (!m_element) return; calculateBoundingRect(); } void CRPTRNode::showProperties() { spaghetti::Node::showProperties(); //showIOProperties(spaghetti::IOSocketsType::eOutputs); } //void removeInput() override; //void removeOutput() override; void CRPTRNode::addOutput(){ Node::addOutput(); while (element()->outputs().size() > element()->inputs().size()){ Node::addInput(); } addPButtons(); } void CRPTRNode::addInput(){ Node::addInput(); while (element()->inputs().size() > element()->outputs().size()){ Node::addOutput(); } addPButtons(); } void CRPTRNode::removeInput(){ Node::removeInput(); while (element()->inputs().size() < element()->outputs().size()){ Node::removeOutput(); } addPButtons(); } void CRPTRNode::removeOutput(){ Node::removeOutput(); while (element()->outputs().size() < element()->inputs().size()){ Node::removeInput(); } addPButtons(); } /*void CRPTRNode::addSocket(spaghetti::IOSocketsType ioType, uint8_t const a_id, QString const &a_name, spaghetti::ValueType const a_valueType, SocketType const a_type) { //!TODO! dynamic? //if (IOSocketsType::eInputs == ioType){ Node::addSocket(spaghetti::IOSocketsType::eInputs,a_id, a_name+"(i)", a_valueType, spaghetti::SocketItemType::eInput); Node::addSocket(spaghetti::IOSocketsType::eOutputs,a_id, a_name+"(o)", a_valueType, spaghetti::SocketItemType::eOutput); //} else { //} }*/ } // namespace spaghetti::nodes::values
8,042
3,097
#ifdef PEGASUS_OS_LINUX #ifndef __UNIX_CONFIGURATIONCOMPONENT_PRIVATE_H #define __UNIX_CONFIGURATIONCOMPONENT_PRIVATE_H #endif #endif
140
67
#include <stdio.h> #include <stdlib.h> #include <windows.h> #include <dsound.h> #include "synther.h" #include "synthtable.h" #include "notetable_touhou.h" #pragma comment(lib, "dsound.lib") #pragma comment(lib, "dxguid.lib") #define MAX_AUDIO_BUF 4 #define BUFFERNOTIFYSIZE 192000 int sample_rate = 44100; //PCM sample rate int channels = 1; //PCM channel number int bits_per_sample = 16; //bits per sample DEFINE_SYNTH_TABLE(g_table_piano_wavefile) { 702, 1144, 1552, 2278, 3140, 4168, 5417, 6664, 7749, 8628, 9120, 9054, 8626, 8164, 7679, 7182, 7033, 7281, 7602, 8026, 8697, 9426, 10183, 11185, 12372, 13553, 14837, 16304, 17754, 19133, 20592, 22117, 23607, 24991, 26063, 26751, 27164, 27158, 26613, 25876, 25220, 24619, 24120, 23865, 23834, 23947, 24152, 24419, 24771, 25315, 26046, 26749, 27281, 27766, 28202, 28346, 28213, 28007, 27723, 27318, 26833, 26330, 25727, 24937, 24025, 23039, 22049, 21395, 21136, 21073, 21398, 22316, 23527, 24733, 25945, 27103, 27975, 28446, 28520, 28120, 27325, 26269, 24930, 23460, 22162, 20973, 19775, 18657, 17551, 16189, 14553, 13003, 11813, 10908, 10392, 10451, 10823, 11231, 11724, 12218, 12596, 12842, 12840, 12536, 12045, 11296, 10052, 8346, 6571, 4912, 3244, 1841, 1133, 867, 805, 1169, 1867, 2644, 3514, 4407, 5263, 6099, 6787, 7361, 7925, 8328, 8484, 8479, 8390, 8299, 8140, 7918, 7702, 7372, 7068, 7169, 7523, 7915, 8589, 9480, 10128, 10560, 11083, 11531, 11734, 11841, 11798, 11488, 11006, 10293, 9290, 8343, 7690, 7192, 6884, 6994, 7353, 7564, 7743, 8131, 8472, 8730, 9402, 10482, 11523, 12621, 13916, 14897, 15202, 15048, 14591, 13671, 12355, 11013, 9874, 8857, 7999, 7566, 7618, 7872, 8113, 8354, 8580, 8571, 8218, 7722, 7197, 6532, 5807, 5160, 4491, 3737, 2975, 2236, 1521, 854, 241, -377, -1049, -1765, -2614, -3599, -4353, -4660, -4666, -4222, -3183, -2023, -1041, 10, 1038, 1675, 2100, 2614, 3044, 3237, 3488, 4016, 4598, 4976, 5189, 5293, 5086, 4502, 3798, 3126, 2475, 1973, 1793, 2029, 2582, 3217, 3893, 4455, 4514, 4175, 3775, 3147, 2306, 1775, 1672, 1706, 1828, 2155, 2618, 2878, 2718, 2442, 2283, 1991, 1557, 1356, 1401, 1500, 1682, 2044, 2529, 2886, 2760, 2149, 1203, -221, -1982, -3547, -4899, -6201, -7217, -7861, -8226, -8231, -7871, -7258, -6371, -5120, -3627, -2159, -790, 585, 1903, 2862, 3244, 3229, 2981, 2259, 997, -490, -1995, -3460, -4763, -5691, -5930, -5479, -4680, -3622, -2252, -898, -28, 406, 744, 797, 357, -272, -1083, -2291, -3685, -5171, -6786, -8246, -9372, -10165, -10583, -10565, -10110, -9441, -8731, -7867, -6922, -6025, -5147, -4353, -3680, -3042, -2513, -2073, -1603, -1110, -670, -326, -129, -134, -352, -592, -708, -726, -598, -285, 44, 331, 580, 647, 498, 298, 77, -293, -744, -1082, -1436, -1987, -2485, -2803, -3175, -3468, -3370, -3080, -2813, -2385, -1811, -1377, -1052, -652, -220, 190, 638, 1064, 1359, 1547, 1631, 1487, 1128, 698, 211, -395, -1075, -1765, -2416, -3006, -3465, -3731, -3708, -3301, -2645, -1911, -1087, -207, 520, 972, 1252, 1498, 1652, 1619, 1415, 1028, 505, -72, -705, -1259, -1751, -2563, -3680, -4753, -5956, -7382, -8610, -9456, -10092, -10511, -10713, -10918, -11244, -11619, -12116, -12893, -13780, -14632, -15625, -16766, -17856, -18980, -20129, -20980, -21460, -21757, -21790, -21475, -21003, -20500, -20005, -19561, -19118, -18659, -18292, -18076, -18094, -18387, -19051, -20259, -21881, -23563, -25235, -27000, -28706, -30036, -30865, -31250, -31222, -30719, -29757, -28621, -27577, -26610, -25730, -25053, -24737, -24881, -25301, -25884, -26754, -27715, -28595, -29495, -30383, -31208, -32008, -32578, -32768, -32671, -32206, -31144, -29554, -27808, -26133, -24512, -23089, -22073, -21465, -21331, -21763, -22588, -23783, -25328, -26753, -27715, -28352, -28734, -28747, -28556, -28402, -28121, -27602, -27105, -26584, -25930, -25269, -24620, -23940, -23181, -22250, -21103, -19705, -18149, -16533, -14786, -13167, -11900, -10800, -9754, -8817, -7866, -6646, -5107, -3542, -1616 }; DEFINE_SYNTH_TABLE(g_table_triangleTable) { 0, 255, 511, 767, 1023, 1279, 1535, 1791, 2047, 2303, 2559, 2815, 3071, 3327, 3583, 3839, 4095, 4351, 4607, 4863, 5119, 5375, 5631, 5887, 6143, 6399, 6655, 6911, 7167, 7423, 7679, 7935, 8191, 8447, 8703, 8959, 9215, 9471, 9727, 9983, 10239, 10495, 10751, 11007, 11263, 11519, 11775, 12031, 12287, 12543, 12799, 13055, 13311, 13567, 13823, 14079, 14335, 14591, 14847, 15103, 15359, 15615, 15871, 16127, 16383, 16639, 16895, 17151, 17407, 17663, 17919, 18175, 18431, 18687, 18943, 19199, 19455, 19711, 19967, 20223, 20479, 20735, 20991, 21247, 21503, 21759, 22015, 22271, 22527, 22783, 23039, 23295, 23551, 23807, 24063, 24319, 24575, 24831, 25087, 25343, 25599, 25855, 26111, 26367, 26623, 26879, 27135, 27391, 27647, 27903, 28159, 28415, 28671, 28927, 29183, 29439, 29695, 29951, 30207, 30463, 30719, 30975, 31231, 31487, 31743, 31999, 32255, 32511, 32767, 32512, 32256, 32000, 31744, 31488, 31232, 30976, 30720, 30464, 30208, 29952, 29696, 29440, 29184, 28928, 28672, 28416, 28160, 27904, 27648, 27392, 27136, 26880, 26624, 26368, 26112, 25856, 25600, 25344, 25088, 24832, 24576, 24320, 24064, 23808, 23552, 23296, 23040, 22784, 22528, 22272, 22016, 21760, 21504, 21248, 20992, 20736, 20480, 20224, 19968, 19712, 19456, 19200, 18944, 18688, 18432, 18176, 17920, 17664, 17408, 17152, 16896, 16640, 16384, 16128, 15872, 15616, 15360, 15104, 14848, 14592, 14336, 14080, 13824, 13568, 13312, 13056, 12800, 12544, 12288, 12032, 11776, 11520, 11264, 11008, 10752, 10496, 10240, 9984, 9728, 9472, 9216, 8960, 8704, 8448, 8192, 7936, 7680, 7424, 7168, 6912, 6656, 6400, 6144, 5888, 5632, 5376, 5120, 4864, 4608, 4352, 4096, 3840, 3584, 3328, 3072, 2816, 2560, 2304, 2048, 1792, 1536, 1280, 1024, 768, 512, 256, 0, -256, -512, -768, -1024, -1280, -1536, -1792, -2048, -2304, -2560, -2816, -3072, -3328, -3584, -3840, -4096, -4352, -4608, -4864, -5120, -5376, -5632, -5888, -6144, -6400, -6656, -6912, -7168, -7424, -7680, -7936, -8192, -8448, -8704, -8960, -9216, -9472, -9728, -9984, -10240, -10496, -10752, -11008, -11264, -11520, -11776, -12032, -12288, -12544, -12800, -13056, -13312, -13568, -13824, -14080, -14336, -14592, -14848, -15104, -15360, -15616, -15872, -16128, -16384, -16640, -16896, -17152, -17408, -17664, -17920, -18176, -18432, -18688, -18944, -19200, -19456, -19712, -19968, -20224, -20480, -20736, -20992, -21248, -21504, -21760, -22016, -22272, -22528, -22784, -23040, -23296, -23552, -23808, -24064, -24320, -24576, -24832, -25088, -25344, -25600, -25856, -26112, -26368, -26624, -26880, -27136, -27392, -27648, -27904, -28160, -28416, -28672, -28928, -29184, -29440, -29696, -29952, -30208, -30464, -30720, -30976, -31232, -31488, -31744, -32000, -32256, -32512, -32768, -32512, -32256, -32000, -31744, -31488, -31232, -30976, -30720, -30464, -30208, -29952, -29696, -29440, -29184, -28928, -28672, -28416, -28160, -27904, -27648, -27392, -27136, -26880, -26624, -26368, -26112, -25856, -25600, -25344, -25088, -24832, -24576, -24320, -24064, -23808, -23552, -23296, -23040, -22784, -22528, -22272, -22016, -21760, -21504, -21248, -20992, -20736, -20480, -20224, -19968, -19712, -19456, -19200, -18944, -18688, -18432, -18176, -17920, -17664, -17408, -17152, -16896, -16640, -16384, -16128, -15872, -15616, -15360, -15104, -14848, -14592, -14336, -14080, -13824, -13568, -13312, -13056, -12800, -12544, -12288, -12032, -11776, -11520, -11264, -11008, -10752, -10496, -10240, -9984, -9728, -9472, -9216, -8960, -8704, -8448, -8192, -7936, -7680, -7424, -7168, -6912, -6656, -6400, -6144, -5888, -5632, -5376, -5120, -4864, -4608, -4352, -4096, -3840, -3584, -3328, -3072, -2816, -2560, -2304, -2048, -1792, -1536, -1280, -1024, -768, -512, -256 }; DEFINE_SYNTH_TABLE(g_table_piano) { 0, 362, 725, 1089, 1456, 1826, 2199, 2577, 2960, 3349, 3744, 4146, 4554, 4971, 5394, 5826, 6266, 6714, 7170, 7634, 8105, 8584, 9070, 9563, 10062, 10567, 11078, 11592, 12111, 12632, 13156, 13682, 14208, 14734, 15258, 15781, 16301, 16818, 17330, 17836, 18337, 18830, 19316, 19793, 20261, 20719, 21167, 21604, 22029, 22442, 22844, 23232, 23608, 23971, 24320, 24656, 24979, 25288, 25584, 25867, 26137, 26394, 26638, 26870, 27090, 27299, 27496, 27682, 27858, 28024, 28181, 28329, 28468, 28599, 28723, 28840, 28951, 29056, 29155, 29250, 29341, 29428, 29511, 29592, 29670, 29746, 29821, 29894, 29967, 30039, 30111, 30183, 30255, 30328, 30401, 30476, 30552, 30628, 30706, 30786, 30866, 30948, 31031, 31116, 31201, 31287, 31375, 31462, 31550, 31638, 31725, 31812, 31898, 31983, 32066, 32147, 32225, 32300, 32371, 32439, 32501, 32559, 32611, 32656, 32694, 32725, 32748, 32762, 32767, 32762, 32746, 32720, 32682, 32632, 32569, 32493, 32404, 32300, 32183, 32050, 31903, 31740, 31561, 31367, 31157, 30930, 30688, 30430, 30155, 29865, 29559, 29238, 28902, 28550, 28185, 27805, 27412, 27006, 26588, 26158, 25716, 25265, 24804, 24334, 23856, 23371, 22880, 22383, 21881, 21376, 20867, 20357, 19845, 19333, 18822, 18311, 17803, 17297, 16795, 16297, 15804, 15316, 14834, 14359, 13891, 13430, 12978, 12533, 12097, 11670, 11252, 10844, 10445, 10055, 9675, 9305, 8945, 8595, 8254, 7923, 7601, 7289, 6987, 6693, 6409, 6133, 5867, 5609, 5359, 5118, 4884, 4659, 4441, 4231, 4028, 3832, 3643, 3460, 3285, 3116, 2953, 2796, 2645, 2500, 2361, 2227, 2098, 1975, 1857, 1744, 1635, 1532, 1433, 1338, 1247, 1161, 1079, 1000, 925, 854, 786, 721, 659, 600, 543, 489, 437, 388, 340, 294, 249, 205, 163, 122, 81, 40, 0, -40, -81, -122, -163, -205, -249, -294, -340, -388, -437, -489, -543, -600, -659, -721, -786, -854, -925, -1000, -1079, -1161, -1247, -1338, -1433, -1532, -1635, -1744, -1857, -1975, -2098, -2227, -2361, -2500, -2645, -2796, -2953, -3116, -3285, -3460, -3643, -3832, -4028, -4231, -4441, -4659, -4884, -5118, -5359, -5609, -5867, -6133, -6409, -6693, -6987, -7289, -7601, -7923, -8254, -8595, -8945, -9305, -9675, -10055, -10445, -10844, -11252, -11670, -12097, -12533, -12978, -13430, -13891, -14359, -14834, -15316, -15804, -16297, -16795, -17297, -17803, -18311, -18822, -19333, -19845, -20357, -20867, -21376, -21881, -22383, -22880, -23371, -23856, -24334, -24804, -25265, -25716, -26158, -26588, -27006, -27412, -27805, -28185, -28550, -28902, -29238, -29559, -29865, -30155, -30430, -30688, -30930, -31157, -31367, -31561, -31740, -31903, -32050, -32183, -32300, -32404, -32493, -32569, -32632, -32682, -32720, -32746, -32762, -32767, -32762, -32748, -32725, -32694, -32656, -32611, -32559, -32501, -32439, -32371, -32300, -32225, -32147, -32066, -31983, -31898, -31812, -31725, -31638, -31550, -31462, -31375, -31287, -31201, -31116, -31031, -30948, -30866, -30786, -30706, -30628, -30552, -30476, -30401, -30328, -30255, -30183, -30111, -30039, -29967, -29894, -29821, -29746, -29670, -29592, -29511, -29428, -29341, -29250, -29155, -29056, -28951, -28840, -28723, -28599, -28468, -28329, -28181, -28024, -27858, -27682, -27496, -27299, -27090, -26870, -26638, -26394, -26137, -25867, -25584, -25288, -24979, -24656, -24320, -23971, -23608, -23232, -22844, -22442, -22029, -21604, -21167, -20719, -20261, -19793, -19316, -18830, -18337, -17836, -17330, -16818, -16301, -15781, -15258, -14734, -14208, -13682, -13156, -12632, -12111, -11592, -11078, -10567, -10062, -9563, -9070, -8584, -8105, -7634, -7170, -6714, -6266, -5826, -5394, -4971, -4554, -4146, -3744, -3349, -2960, -2577, -2199, -1826, -1456, -1089, -725, -362 }; DEFINE_SYNTH_TABLE(g_table_pulse25) { 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768 }; DEFINE_SYNTH_TABLE(g_table_pulse50) { 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768 }; DEFINE_SYNTH_TABLE(g_table_pulse75) { 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768 }; DEFINE_SYNTH_TABLE(g_table_random) { -5913, 17729, -17705, 20413, -19262, -31887, -26275, -27241, 30880, -31890, -25503, -30713, -30460, 21731, -1528, 17805, 24186, 27812, -25357, -4430, 14358, -25296, -18586, 17159, 32497, -29887, 4602, -13276, 8181, -18118, -19439, -6162, 11659, 32604, 24277, -13825, -13514, -2253, 24095, 9639, 19539, -30564, 9794, -13993, 10069, -20861, 6026, -19338, -14532, 18842, 8478, -23767, -27308, 10676, 29177, 28826, -30602, 4384, -23767, 16711, -19739, 15694, 12965, 22033, -28694, -20912, 16883, -30704, 26254, -16132, -8895, -21555, -20002, -19258, 1567, -19568, -20785, -17533, -6050, -10506, 20615, -30834, 14852, -5670, 2908, 2539, -9939, 23124, -9332, 19379, 15000, -25510, -28275, -8101, 9281, 626, -27573, -1651, 3506, -29187, 17296, 2842, 2613, 877, -18036, 9908, 24776, 13438, -1959, 18916, -27236, -30119, -11006, 2002, -28735, 14586, -25544, -2192, 23712, 19296, -9787, 16006, -21160, 30918, 28724, -24100, -4435, 15803, -27122, -26875, 23078, -30336, -30230, 22695, -10399, 16046, 15403, 7912, 11847, 11273, 5912, 31293, -2420, 242, -19384, 32295, -6271, -12772, 25516, -12462, -30292, 14005, 28742, -14581, 27184, 18082, 759, -26228, 23250, -8041, -7809, 13585, 31425, -15828, 252, 16535, 31751, 28918, 6744, -12713, -25582, 21554, -3854, -23828, -29701, -8673, 11977, 11766, -16147, 27816, 3629, -7581, 124, 25460, -22734, 31403, -15508, 9219, 17833, 27939, 28722, -8306, -26600, 9651, 18775, -5013, 32295, 5611, 28763, -16998, -8208, -32597, -390, 23149, 28859, -17644, 15608, 14057, 11585, 16573, 21940, -1195, -7356, -23246, 29944, -9856, -14320, -21126, 2057, 3172, -12251, 6147, -16981, -27164, 2872, 11514, 23682, 22370, -1728, 32275, -3492, 4223, 1210, -22418, 27626, 5309, -24641, 17624, -4954, -4652, 10816, 19974, -21045, 1195, -32464, 3057, -24559, 24799, -13328, -2199, 5950, 14263, 25184, -31150, -30769, -19255, -4054, -11018, -16058, 12852, -21632, -15765, 9808, -3315, -26321, 28768, 3479, -31272, 27846, 17042, -22725, -30363, 19028, 2902, 19948, 21509, -16686, -14201, 1835, 22882, 7710, 5630, -11205, -1647, -15062, 31357, -26865, 23460, 17613, -17964, -5052, 28627, 6257, 28950, -20010, 27125, 7695, -11291, 25652, -18131, -29043, 13125, 30995, 11215, 14977, -29599, 11818, 23970, -20362, -1261, -28468, 5038, -31700, -3854, -16885, 2468, -28748, 26276, -11889, -21910, 20052, 10460, 29537, 8202, -18393, -32390, 27880, 16423, -10270, 16055, 16211, -7720, 9510, -3340, -25514, 29323, 1757, 7442, 16720, 30273, -20308, -30837, -1243, -5447, -7463, -1016, 447, 13332, -13912, 22432, 17718, -31448, -13992, -5033, -17451, -152, -19355, -31587, 8849, 9270, -15457, -23617, 26455, -12845, -6527, 4630, 5712, 32539, 28906, -6794, 10327, 15646, 25143, -29730, -5849, -2026, 28912, 2014, -1503, 22061, -1773, 19645, -20780, -3242, 22754, 3150, -10846, 5757, 4112, 27255, -4224, 8050, 32119, -26681, -11027, -24766, 8644, -3853, 5833, -18659, -16093, -11106, 27253, 9550, -24124, 22700, 19512, -24499, -11581, 554, 8345, -24408, -23808, -17287, -9402, -9392, 10367, -26172, 8530, 11302, -5201, -29700, 3091, -17911, -16826, 31801, 4753, 31801, -16050, -10344, 5615, 9479, -5982, 23812, 13092, 7639, -24843, -15585, 22675, 25016, 8796, 19391, -21155, -11446, 13075, -6063, -29714, -9464, 30181, -6771, 11318, -31299, -10604, -20509, -24801, 23356, 17081, -2635, -27936, -26192, 6645, 19431, -5333, -13084, 26343, -18766, 26558, -10574, -26747, 11671, 28051, -10503, -8336, -14401, -2686, -22072, -5187, 19819, 5521, 32143, -13420, -18499, -32728, -27406, -30662, -26449, 7002, 30095, 24048, -1594, -24496, 26149, -19162, -10999, 23004, -17933, 17504, -6634, 28127, 3649, 2436, -16175, -5693, 6847, -6141, 27518, -4459, 29568, 20039, 21071, 5396, -22070 }; BOOL main(int argc, char * argv[]) { printf("FM Synther By Angelic47\n"); printf("Using DirectSound for output\n"); printf("Sound name: 恋娘 ~湖上ノ旋律~\n\n"); printf("Allocating synther...\n"); int i, j; unsigned short trackernum_all = g_touhou_notes.tracker_num; unsigned short tracks = 1; synther_t *synther; synther = (synther_t *)malloc(trackernum_all * sizeof(synther_t)); synthnote_p *notes_array = (synthnote_p *)malloc(trackernum_all * sizeof(synthnote_p)); synthnotetime_p *notes_time_array = (synthnotetime_p *)malloc(trackernum_all * sizeof(synthnotetime_p)); synthnotenum_t *notes_num_array = (synthnotenum_t *)malloc(trackernum_all * sizeof(synthnotenum_t)); synthnoteppm_t *notebpm_array = (synthnoteppm_t*)malloc(trackernum_all * sizeof(synthnoteppm_t)); // 设置音符, 设置音色波形和adsr包络参数 printf("Initalizing canon notes...\n"); for (i = 0; i < g_touhou_notes.tracker_num; i++) { notes_array[i] = g_touhou_notes.notetables_array[i]; notes_time_array[i] = g_touhou_notes.notetimes_array[i]; notes_num_array[i] = g_touhou_notes.notenum_array[i]; notebpm_array[i] = g_touhou_notes.notebpm; synth_initalize(&synther[i], g_table_piano); synth_adsr_set( &synther[i], 25, 65535, 200, 51000, 36000, 15000, 200 ); } printf("Creating DirectSound Object...\n"); // 创建DirectSound声音输出对象 IDirectSound8 *m_pDS = NULL; IDirectSoundBuffer8 *m_pDSBuffer8 = NULL; //used to manage sound buffers. IDirectSoundBuffer *m_pDSBuffer = NULL; IDirectSoundNotify8 *m_pDSNotify = NULL; DSBPOSITIONNOTIFY m_pDSPosNotify[MAX_AUDIO_BUF]; HANDLE m_event[MAX_AUDIO_BUF]; SetConsoleTitle(TEXT("FM Synther By Angelic47"));//Console Title //Init DirectSound if (FAILED(DirectSoundCreate8(NULL, &m_pDS, NULL))) return FALSE; if (FAILED(m_pDS->SetCooperativeLevel(FindWindow(NULL, TEXT("FM Synther By Angelic47")), DSSCL_NORMAL))) return FALSE; SetConsoleTitle(TEXT("FM Synther By Angelic47 - DirectSound - 恋娘 ~湖上ノ旋律~"));//Console Title DSBUFFERDESC dsbd; memset(&dsbd, 0, sizeof(dsbd)); dsbd.dwSize = sizeof(dsbd); dsbd.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_GETCURRENTPOSITION2; dsbd.dwBufferBytes = MAX_AUDIO_BUF * BUFFERNOTIFYSIZE; //WAVE Header dsbd.lpwfxFormat = (WAVEFORMATEX*)malloc(sizeof(WAVEFORMATEX)); dsbd.lpwfxFormat->wFormatTag = WAVE_FORMAT_PCM; /* format type */ (dsbd.lpwfxFormat)->nChannels = channels; /* number of channels (i.e. mono, stereo...) */ (dsbd.lpwfxFormat)->nSamplesPerSec = sample_rate; /* sample rate */ (dsbd.lpwfxFormat)->nAvgBytesPerSec = sample_rate * (bits_per_sample / 8)*channels; /* for buffer estimation */ (dsbd.lpwfxFormat)->nBlockAlign = (bits_per_sample / 8)*channels; /* block size of data */ (dsbd.lpwfxFormat)->wBitsPerSample = bits_per_sample; /* number of bits per sample of mono data */ (dsbd.lpwfxFormat)->cbSize = 0; //Creates a sound buffer object to manage audio samples. if (FAILED(m_pDS->CreateSoundBuffer(&dsbd, &m_pDSBuffer, NULL))) { return FALSE; } if (FAILED(m_pDSBuffer->QueryInterface(IID_IDirectSoundBuffer8, (LPVOID*)&m_pDSBuffer8))) { return FALSE; } //Get IDirectSoundNotify8 if (FAILED(m_pDSBuffer8->QueryInterface(IID_IDirectSoundNotify, (LPVOID*)&m_pDSNotify))) { return FALSE; } for (i = 0; i < MAX_AUDIO_BUF; i++) { m_pDSPosNotify[i].dwOffset = i * BUFFERNOTIFYSIZE; m_event[i] = ::CreateEvent(NULL, false, false, NULL); m_pDSPosNotify[i].hEventNotify = m_event[i]; } m_pDSNotify->SetNotificationPositions(MAX_AUDIO_BUF, m_pDSPosNotify); m_pDSNotify->Release(); //Start Playing BOOL isPlaying = TRUE; LPVOID buf = NULL; DWORD buf_len = 0; DWORD res = WAIT_OBJECT_0; DWORD offset = BUFFERNOTIFYSIZE; m_pDSBuffer8->SetCurrentPosition(0); m_pDSBuffer8->Play(0, 0, DSBPLAY_LOOPING); unsigned long *process, *pointer; process = (unsigned long*)malloc(trackernum_all * sizeof(unsigned long)); pointer = (unsigned long*)malloc(trackernum_all * sizeof(unsigned long)); for (i = 0; i < trackernum_all; i++) { process[i] = 0; pointer[i] = 0; synth_key_on(&synther[i], notes_array[i][0]); } printf("Start rendering and play!\n\n"); while (isPlaying) { if ((res >= WAIT_OBJECT_0) && (res <= WAIT_OBJECT_0 + 3)) {; m_pDSBuffer8->Lock(offset, BUFFERNOTIFYSIZE, &buf, &buf_len, NULL, NULL, 0); printf("Rending %7d of buffer\n", offset); // 缓冲区渲染 for (i = 0; i < buf_len / 2; i++) { signed long temp = 0; int j; for (j = 0; j < trackernum_all; j++) { if (process[j] > notes_time_array[j][pointer[j]] * notebpm_array[j]) { synth_key_off(&synther[j]); process[j] = 0; pointer[j]++; if (pointer[j] >= notes_num_array[j]) pointer[j] = 0; synth_key_on(&synther[j], notes_array[j][pointer[j]]); } signed long result = synth_get_next_data_adsr(&synther[j]); temp += result; process[j]++; } ((synthdata_t *)buf)[i] = temp / 5; } m_pDSBuffer8->Unlock(buf, buf_len, NULL, 0); offset += buf_len; offset %= (BUFFERNOTIFYSIZE * MAX_AUDIO_BUF); } res = WaitForMultipleObjects(MAX_AUDIO_BUF, m_event, FALSE, INFINITE); } free(process); free(pointer); free(synther); return 0; }
31,841
26,907
/** *Codeforces Round #353 DIV2 B *18/05/16 07:44:53 *xuchen * */ #include <stdio.h> #include <iostream> #include <cmath> #include <cstring> #include <map> #include <set> #include <stdlib.h> #include <algorithm> #include <queue> using namespace std; const int N = 100005; set<int> valset; map<int, int> L, R; int main(int argc, char* args[]) { int n, val; scanf("%d", &n); for(int i=0; i<n; ++i) { scanf("%d", &val); if(i==0) valset.insert(val); else { auto iter = valset.lower_bound(val); if(iter == valset.end()) R[*(--iter)] = val; else { if(!L[*iter]) L[*iter] = val; else R[*(--iter)] = val; } if(i==1) printf("%d", *iter); else printf(" %d", *iter); valset.insert(val); } } return 0; }
951
355