text
stringlengths
8
6.88M
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.ApplicationModel.Payments.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e #define WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e template <> struct __declspec(uuid("e2fcc7c1-3bfc-5a0b-b2b0-72e769d1cb7e")) __declspec(novtable) IIterable<hstring> : impl_IIterable<hstring> {}; #endif #ifndef WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e #define WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e template <> struct __declspec(uuid("2f13c006-a03a-5f69-b090-75a43e33423e")) __declspec(novtable) IVectorView<hstring> : impl_IVectorView<hstring> {}; #endif #ifndef WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90 #define WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90 template <> struct __declspec(uuid("98b9acc1-4b56-532e-ac73-03d5291cca90")) __declspec(novtable) IVector<hstring> : impl_IVector<hstring> {}; #endif #ifndef WINRT_GENERIC_1011b9ba_6a05_5b16_82cf_0175085105e0 #define WINRT_GENERIC_1011b9ba_6a05_5b16_82cf_0175085105e0 template <> struct __declspec(uuid("1011b9ba-6a05-5b16-82cf-0175085105e0")) __declspec(novtable) IVectorView<Windows::ApplicationModel::Payments::PaymentMethodData> : impl_IVectorView<Windows::ApplicationModel::Payments::PaymentMethodData> {}; #endif #ifndef WINRT_GENERIC_8c9ed87e_4add_58a8_ad9a_9dfa48ca250a #define WINRT_GENERIC_8c9ed87e_4add_58a8_ad9a_9dfa48ca250a template <> struct __declspec(uuid("8c9ed87e-4add-58a8-ad9a-9dfa48ca250a")) __declspec(novtable) IIterable<Windows::ApplicationModel::Payments::PaymentMethodData> : impl_IIterable<Windows::ApplicationModel::Payments::PaymentMethodData> {}; #endif #ifndef WINRT_GENERIC_6baf1241_1fa6_5c22_83ef_415e93cdf7b1 #define WINRT_GENERIC_6baf1241_1fa6_5c22_83ef_415e93cdf7b1 template <> struct __declspec(uuid("6baf1241-1fa6-5c22-83ef-415e93cdf7b1")) __declspec(novtable) IVectorView<Windows::ApplicationModel::Payments::PaymentItem> : impl_IVectorView<Windows::ApplicationModel::Payments::PaymentItem> {}; #endif #ifndef WINRT_GENERIC_8c8128eb_8c33_56dd_9648_39e8040312d4 #define WINRT_GENERIC_8c8128eb_8c33_56dd_9648_39e8040312d4 template <> struct __declspec(uuid("8c8128eb-8c33-56dd-9648-39e8040312d4")) __declspec(novtable) IVectorView<Windows::ApplicationModel::Payments::PaymentShippingOption> : impl_IVectorView<Windows::ApplicationModel::Payments::PaymentShippingOption> {}; #endif #ifndef WINRT_GENERIC_da7e871c_6e0c_5e32_be40_10715a9f75eb #define WINRT_GENERIC_da7e871c_6e0c_5e32_be40_10715a9f75eb template <> struct __declspec(uuid("da7e871c-6e0c-5e32-be40-10715a9f75eb")) __declspec(novtable) IVectorView<Windows::ApplicationModel::Payments::PaymentDetailsModifier> : impl_IVectorView<Windows::ApplicationModel::Payments::PaymentDetailsModifier> {}; #endif #ifndef WINRT_GENERIC_b61b704c_e5fa_5524_8b95_7d03f5d36ae9 #define WINRT_GENERIC_b61b704c_e5fa_5524_8b95_7d03f5d36ae9 template <> struct __declspec(uuid("b61b704c-e5fa-5524-8b95-7d03f5d36ae9")) __declspec(novtable) IIterable<Windows::ApplicationModel::Payments::PaymentItem> : impl_IIterable<Windows::ApplicationModel::Payments::PaymentItem> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_cf290deb_5549_57c3_8abd_53b76c643cca #define WINRT_GENERIC_cf290deb_5549_57c3_8abd_53b76c643cca template <> struct __declspec(uuid("cf290deb-5549-57c3-8abd-53b76c643cca")) __declspec(novtable) IAsyncOperation<Windows::ApplicationModel::Payments::PaymentRequestSubmitResult> : impl_IAsyncOperation<Windows::ApplicationModel::Payments::PaymentRequestSubmitResult> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236 #define WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236 template <> struct __declspec(uuid("8c304ebb-6615-50a4-8829-879ecd443236")) __declspec(novtable) IIterator<hstring> : impl_IIterator<hstring> {}; #endif #ifndef WINRT_GENERIC_cbe5ce35_2d88_5385_8328_8480ca15fe7d #define WINRT_GENERIC_cbe5ce35_2d88_5385_8328_8480ca15fe7d template <> struct __declspec(uuid("cbe5ce35-2d88-5385-8328-8480ca15fe7d")) __declspec(novtable) IVector<Windows::ApplicationModel::Payments::PaymentMethodData> : impl_IVector<Windows::ApplicationModel::Payments::PaymentMethodData> {}; #endif #ifndef WINRT_GENERIC_9666522e_e5ac_5374_a5d9_5cf57c4bf689 #define WINRT_GENERIC_9666522e_e5ac_5374_a5d9_5cf57c4bf689 template <> struct __declspec(uuid("9666522e-e5ac-5374-a5d9-5cf57c4bf689")) __declspec(novtable) IIterator<Windows::ApplicationModel::Payments::PaymentMethodData> : impl_IIterator<Windows::ApplicationModel::Payments::PaymentMethodData> {}; #endif #ifndef WINRT_GENERIC_61f86a3b_b48e_59f2_87d1_b5ac0d14413d #define WINRT_GENERIC_61f86a3b_b48e_59f2_87d1_b5ac0d14413d template <> struct __declspec(uuid("61f86a3b-b48e-59f2-87d1-b5ac0d14413d")) __declspec(novtable) IVector<Windows::ApplicationModel::Payments::PaymentItem> : impl_IVector<Windows::ApplicationModel::Payments::PaymentItem> {}; #endif #ifndef WINRT_GENERIC_93c12cc3_6a0b_5f02_ac74_056007472731 #define WINRT_GENERIC_93c12cc3_6a0b_5f02_ac74_056007472731 template <> struct __declspec(uuid("93c12cc3-6a0b-5f02-ac74-056007472731")) __declspec(novtable) IIterator<Windows::ApplicationModel::Payments::PaymentItem> : impl_IIterator<Windows::ApplicationModel::Payments::PaymentItem> {}; #endif #ifndef WINRT_GENERIC_1dd11e67_accf_5c32_b0a5_0fa8aef67837 #define WINRT_GENERIC_1dd11e67_accf_5c32_b0a5_0fa8aef67837 template <> struct __declspec(uuid("1dd11e67-accf-5c32-b0a5-0fa8aef67837")) __declspec(novtable) IVector<Windows::ApplicationModel::Payments::PaymentShippingOption> : impl_IVector<Windows::ApplicationModel::Payments::PaymentShippingOption> {}; #endif #ifndef WINRT_GENERIC_49edc9f4_2ce6_534c_b529_5ceec705def5 #define WINRT_GENERIC_49edc9f4_2ce6_534c_b529_5ceec705def5 template <> struct __declspec(uuid("49edc9f4-2ce6-534c-b529-5ceec705def5")) __declspec(novtable) IIterator<Windows::ApplicationModel::Payments::PaymentShippingOption> : impl_IIterator<Windows::ApplicationModel::Payments::PaymentShippingOption> {}; #endif #ifndef WINRT_GENERIC_de881c69_6642_54de_a8f7_d1a88b2404cf #define WINRT_GENERIC_de881c69_6642_54de_a8f7_d1a88b2404cf template <> struct __declspec(uuid("de881c69-6642-54de-a8f7-d1a88b2404cf")) __declspec(novtable) IIterable<Windows::ApplicationModel::Payments::PaymentShippingOption> : impl_IIterable<Windows::ApplicationModel::Payments::PaymentShippingOption> {}; #endif #ifndef WINRT_GENERIC_13664f78_2e27_524f_9d9a_01bdcf2fc4a5 #define WINRT_GENERIC_13664f78_2e27_524f_9d9a_01bdcf2fc4a5 template <> struct __declspec(uuid("13664f78-2e27-524f-9d9a-01bdcf2fc4a5")) __declspec(novtable) IVector<Windows::ApplicationModel::Payments::PaymentDetailsModifier> : impl_IVector<Windows::ApplicationModel::Payments::PaymentDetailsModifier> {}; #endif #ifndef WINRT_GENERIC_fafb6774_b665_5b8b_b1ef_95038c3aabe1 #define WINRT_GENERIC_fafb6774_b665_5b8b_b1ef_95038c3aabe1 template <> struct __declspec(uuid("fafb6774-b665-5b8b-b1ef-95038c3aabe1")) __declspec(novtable) IIterator<Windows::ApplicationModel::Payments::PaymentDetailsModifier> : impl_IIterator<Windows::ApplicationModel::Payments::PaymentDetailsModifier> {}; #endif #ifndef WINRT_GENERIC_585d2b3d_cb34_58c4_81f4_1ea157996def #define WINRT_GENERIC_585d2b3d_cb34_58c4_81f4_1ea157996def template <> struct __declspec(uuid("585d2b3d-cb34-58c4-81f4-1ea157996def")) __declspec(novtable) IIterable<Windows::ApplicationModel::Payments::PaymentDetailsModifier> : impl_IIterable<Windows::ApplicationModel::Payments::PaymentDetailsModifier> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_cbcd07a6_ae2a_5a70_bc0b_9120560825d1 #define WINRT_GENERIC_cbcd07a6_ae2a_5a70_bc0b_9120560825d1 template <> struct __declspec(uuid("cbcd07a6-ae2a-5a70-bc0b-9120560825d1")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::ApplicationModel::Payments::PaymentRequestSubmitResult> : impl_AsyncOperationCompletedHandler<Windows::ApplicationModel::Payments::PaymentRequestSubmitResult> {}; #endif #ifndef WINRT_GENERIC_2f92b529_119b_575a_a419_3904b4e41af2 #define WINRT_GENERIC_2f92b529_119b_575a_a419_3904b4e41af2 template <> struct __declspec(uuid("2f92b529-119b-575a-a419-3904b4e41af2")) __declspec(novtable) IAsyncOperation<Windows::Foundation::Collections::IVectorView<hstring>> : impl_IAsyncOperation<Windows::Foundation::Collections::IVectorView<hstring>> {}; #endif #ifndef WINRT_GENERIC_7c7899be_5f2e_5bf3_ade5_ad98b772c7cd #define WINRT_GENERIC_7c7899be_5f2e_5bf3_ade5_ad98b772c7cd template <> struct __declspec(uuid("7c7899be-5f2e-5bf3-ade5-ad98b772c7cd")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<hstring>> : impl_AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<hstring>> {}; #endif } namespace Windows::ApplicationModel::Payments { struct PaymentRequestChangedHandler : Windows::Foundation::IUnknown { PaymentRequestChangedHandler(std::nullptr_t = nullptr) noexcept {} template <typename L> PaymentRequestChangedHandler(L lambda); template <typename F> PaymentRequestChangedHandler (F * function); template <typename O, typename M> PaymentRequestChangedHandler(O * object, M method); void operator()(const Windows::ApplicationModel::Payments::PaymentRequest & paymentRequest, const Windows::ApplicationModel::Payments::PaymentRequestChangedArgs & args) const; }; struct IPaymentAddress : Windows::Foundation::IInspectable, impl::consume<IPaymentAddress> { IPaymentAddress(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentCurrencyAmount : Windows::Foundation::IInspectable, impl::consume<IPaymentCurrencyAmount> { IPaymentCurrencyAmount(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentCurrencyAmountFactory : Windows::Foundation::IInspectable, impl::consume<IPaymentCurrencyAmountFactory> { IPaymentCurrencyAmountFactory(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentDetails : Windows::Foundation::IInspectable, impl::consume<IPaymentDetails> { IPaymentDetails(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentDetailsFactory : Windows::Foundation::IInspectable, impl::consume<IPaymentDetailsFactory> { IPaymentDetailsFactory(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentDetailsModifier : Windows::Foundation::IInspectable, impl::consume<IPaymentDetailsModifier> { IPaymentDetailsModifier(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentDetailsModifierFactory : Windows::Foundation::IInspectable, impl::consume<IPaymentDetailsModifierFactory> { IPaymentDetailsModifierFactory(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentItem : Windows::Foundation::IInspectable, impl::consume<IPaymentItem> { IPaymentItem(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentItemFactory : Windows::Foundation::IInspectable, impl::consume<IPaymentItemFactory> { IPaymentItemFactory(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentMediator : Windows::Foundation::IInspectable, impl::consume<IPaymentMediator> { IPaymentMediator(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentMerchantInfo : Windows::Foundation::IInspectable, impl::consume<IPaymentMerchantInfo> { IPaymentMerchantInfo(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentMerchantInfoFactory : Windows::Foundation::IInspectable, impl::consume<IPaymentMerchantInfoFactory> { IPaymentMerchantInfoFactory(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentMethodData : Windows::Foundation::IInspectable, impl::consume<IPaymentMethodData> { IPaymentMethodData(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentMethodDataFactory : Windows::Foundation::IInspectable, impl::consume<IPaymentMethodDataFactory> { IPaymentMethodDataFactory(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentOptions : Windows::Foundation::IInspectable, impl::consume<IPaymentOptions> { IPaymentOptions(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentRequest : Windows::Foundation::IInspectable, impl::consume<IPaymentRequest> { IPaymentRequest(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentRequestChangedArgs : Windows::Foundation::IInspectable, impl::consume<IPaymentRequestChangedArgs> { IPaymentRequestChangedArgs(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentRequestChangedResult : Windows::Foundation::IInspectable, impl::consume<IPaymentRequestChangedResult> { IPaymentRequestChangedResult(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentRequestChangedResultFactory : Windows::Foundation::IInspectable, impl::consume<IPaymentRequestChangedResultFactory> { IPaymentRequestChangedResultFactory(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentRequestFactory : Windows::Foundation::IInspectable, impl::consume<IPaymentRequestFactory> { IPaymentRequestFactory(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentRequestSubmitResult : Windows::Foundation::IInspectable, impl::consume<IPaymentRequestSubmitResult> { IPaymentRequestSubmitResult(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentResponse : Windows::Foundation::IInspectable, impl::consume<IPaymentResponse> { IPaymentResponse(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentShippingOption : Windows::Foundation::IInspectable, impl::consume<IPaymentShippingOption> { IPaymentShippingOption(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentShippingOptionFactory : Windows::Foundation::IInspectable, impl::consume<IPaymentShippingOptionFactory> { IPaymentShippingOptionFactory(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentToken : Windows::Foundation::IInspectable, impl::consume<IPaymentToken> { IPaymentToken(std::nullptr_t = nullptr) noexcept {} }; struct IPaymentTokenFactory : Windows::Foundation::IInspectable, impl::consume<IPaymentTokenFactory> { IPaymentTokenFactory(std::nullptr_t = nullptr) noexcept {} }; } }
#include "sortwidget.h" #include "ui_sortwidget.h" #define GREY QColor(220,220,220) SortWidget::SortWidget(std::vector<double> gwPoint,std::vector<double> totPoint,std::vector<QString> names,QWidget *parent) : QWidget(parent) , ui(new Ui::SortWidget) { ui->setupUi(this); //creating visualizing scene and setting it to visualizing background visualizingScene = new QGraphicsScene(this); ui->visualizingBackground->setScene(visualizingScene); visualizingScene->setBackgroundBrush(QBrush(GREY)); double sceneHeight = ui->visualizingBackground->size().height(); double sceneWidth = ui->visualizingBackground->size().width(); sorting = new Sorting; ui->choosePoints->hide(); ui->choosePointsLabel->hide(); sorting->initialize(sceneHeight,sceneWidth,visualizingScene,gwPoint,totPoint,names); } SortWidget::~SortWidget() { delete ui; } void SortWidget::on_slider_valueChanged(int value) { ui->label->setText("Number Of Elements = "+ QString::number(value)); sorting->setRectangles(value); sorting->resetRectangles(); } void SortWidget::on_pushButton_clicked() { if(ui->chooseData->currentIndex()==1) sorting->selectionSort(); else { if(ui->comboBox->currentIndex()==0) sorting->selectionSort(); else if(ui->comboBox->currentIndex()==1) sorting->switchToQuickSort(); else if(ui->comboBox->currentIndex()==2) sorting->switchToMergeSort(); } } void SortWidget::on_resetButton_clicked() { if(ui->chooseData->currentIndex()==0) sorting->resetRectangles(); else if(ui->chooseData->currentIndex()==1) sorting->resetRectanglesFantasy(ui->choosePoints->currentIndex()); } void SortWidget::on_delaySlider_valueChanged(int value) { ui->delayLabel->setText("Delay = "+ QString::number(value)+"ms"); sorting->setDelay(value); } void SortWidget::on_stopButton_clicked() { sorting->setStopButton(); } void SortWidget::on_quitButton_clicked() { hide(); } void SortWidget::on_chooseData_currentIndexChanged(int index) { if(index==0) { ui->label->show(); ui->label_2->show(); ui->comboBox->show(); ui->slider->show(); ui->choosePoints->hide(); ui->choosePointsLabel->hide(); ui->delaySlider->setGeometry(1120,250,171,31); ui->delayLabel->setGeometry(1180,220,81,21); sorting->setFantasySelected(false); sorting->resetRectangles(); } else if(index==1) { ui->label->hide(); ui->label_2->hide(); ui->comboBox->hide(); ui->slider->hide(); ui->choosePoints->show(); ui->choosePointsLabel->show(); ui->delayLabel->setGeometry(1150,170,141,21); ui->delaySlider->setGeometry(1120,210,171,31); sorting->setFantasySelected(true); sorting->switchToFantasy(); } } void SortWidget::on_choosePoints_currentIndexChanged(int index) { sorting->resetRectanglesFantasy(index); }
/*************************************************************************** estrategia.cpp - description ------------------- begin : abr 13 2003 copyright : (C) 2003 by Oscar GermánDuarte Velasco email : ogduarte@ing.unal.edu.co ***************************************************************************/ /*************************************************************************** * * * Este programa ha sido diseñado por Oscar G. Duarte V. por encargo del * * Departamento de Ciencias de la Computación e Inteligencia * * Artificial de la Universidad de Granada. * * * ***************************************************************************/ #include "estrategia.h" Estrategia::Estrategia() { Nombre=wxT("Sin Nombre"); } Estrategia::~Estrategia() { Grafo.eliminarNodosAbajoTodos(); } /** * La estrategia de calculo sigue los siguientes pasos * * a) Crea una copia temporal de VarCalculada en Cada Nodo del Grafo * * b) Asigna TipoDeValor=0 (Indefinido) a VarCalculada en Cada Nodo del Grafo * * c) Busca si alguna VariableLinguistica del Caso tiene el mismo Nombre que * VarCalculada en Cada Nodo del Grafo. En caso afirmativo, la copia en el Nodo * * d) Calcula el resultado del Grafo * * e) Restaura VarCalculada de la copia temporal en Cada Nodo del Grafo */ NumeroDifuso* Estrategia::calcular(Caso *caso) { return Grafo.calcularCaso(caso); } /** * Calcula el resultado de aplicar la estrategia al Caso caso, en el nodo * cuya variable Calculada tiene por nombre nom. Si no existe tal Nodo * retorna un trapecio T(0,0,0,0) */ NumeroDifuso* Estrategia::calcularNodo(Caso *caso,wxString nom) { NumeroDifuso *Num; NodoCalculo *Nod; Nod=Grafo.buscarNodo(nom); if(Nod!=NULL) { Num=Nod->calcularCaso(caso); }else { Num=new NumeroDifuso; Num->trapecio(0,0,0,0); } return Num; } /** * Asigna a caso un conjunto de variables liguisticas iguales a aquellas variables * de la estrategia que deban conocerse para efectuar el cálculo, es decir, aquellas * que no tienen nodos hijos, o aquellas que no se calculan con los hijos. */ void Estrategia::llenarCasoIndefinido(Caso *caso,int Flag) { // caso->Variables.Clear(); Grafo.llenarCasoIndefinido(caso); if(Flag) { // copiar generalidades wxArrayString nombresEst=Generalidades.listaNombres(); int i,tam; tam=Generalidades.tamano(); for(i=0;i<tam;i++) { wxArrayString nombresCaso=caso->Generalidades.listaNombres(); wxString cad; cad=nombresEst.Item(i); if(nombresCaso.Index(cad)==wxNOT_FOUND) { caso->Generalidades.adicionarPropiedad(cad); } } } } /** * Adiciona las propiedades de Estrategia a Caso (sólo las que no están previamente definidas). */ void Estrategia::copiarPropiedades(Caso *caso) { int i,tam,j,tam2; tam=Generalidades.tamano(); for(i=0;i<tam;i++) { tam2=caso->Generalidades.tamano(); int flag=0; for(j=0;j<tam2;j++) { if(Generalidades.nombre(i)==caso->Generalidades.nombre(j)) { flag=1; j=tam2; } } if(flag==0) { caso->Generalidades.adicionarPropiedad(Generalidades.nombre(i)); } } } void Estrategia::write(Mi_ofpstream &str) { str << Nombre; str << Descripcion; Grafo.write(str); Generalidades.write(str); } void Estrategia::read(Mi_ifpstream &str) { str >> Nombre; str >> Descripcion; ListaNodos ListaTmp,ListaArbol; ListaTmp.Add(&Grafo); Grafo.read(str,&ListaTmp); ////////////////////////////////// // Estas líneas permiten verificar qué nodos están repetidos y deben eliminarse Grafo.llenarArreglo(&ListaArbol,-1); int i,j,tam,tam2; tam=ListaTmp.GetCount(); tam2=ListaArbol.GetCount(); for(i=0;i<tam;i++) { int flag=0; for(j=0;j<tam2;j++) { if(&ListaTmp.Item(0)==&ListaArbol.Item(j)) { flag=1; j=tam2; } } if(flag==0) // No se encontró!!! { int k,tam3; tam3=ListaTmp.Item(0).NodosDeCalculo.GetCount(); for(k=0;k<tam3;k++) { int ind=ListaTmp.Item(0).NodosDeCalculo.Item(0).NodosPadre.Index(ListaTmp.Item(0)); ListaTmp.Item(0).NodosDeCalculo.Item(0).NodosPadre.Detach(ind); ListaTmp.Item(0).NodosDeCalculo.Detach(0); } tam3=ListaTmp.Item(0).NodosPadre.GetCount(); for(k=0;k<tam3;k++) { ListaTmp.Item(0).NodosPadre.Detach(0); } ListaTmp.RemoveAt(0); }else // si se encontró { { ListaTmp.Detach(0); } } for(j=0;j<tam2;j++) { ListaArbol.Detach(0); } /////////// ////// Aqui se verifica si hay dos nodos de igual nombre int flagCiclo; do { flagCiclo=0; Grafo.llenarArreglo(&ListaArbol,-1); tam=ListaArbol.GetCount(); for(i=0;i<tam;i++) { for(j=i+1;j<tam;j++) { // si los nombres son iguales if(ListaArbol.Item(i).VarCalculada.Nombre==ListaArbol.Item(j).VarCalculada.Nombre) { // el problema está si los apuntadores son diferentes if(&ListaArbol.Item(i)!=&ListaArbol.Item(j)) { // qué hacer? // quitamos los hijos del repetido... ////////////////////////////// // OJO: la siguiente lpinea fue comentada para que el programa no hiciera crash al abrir una red compleja (DSM / SMTG) // REVISAR // ListaArbol.Item(j).eliminarNodosAbajoTodos(); ////////////////////////////////// // cambiamos los apuntadores en los padres del repetido int k,tam3; tam3=ListaArbol.Item(j).NodosPadre.GetCount(); for(k=0;k<tam3;k++) { // este es un padre NodoCalculo *nodpad=&ListaArbol.Item(j).NodosPadre.Item(k); int m,tam4; // buscamos cuál hijo es el nodo repetido y lo cambiamos tam4=nodpad->NodosDeCalculo.GetCount(); for(m=0;m<tam4;m++) { // este es el nodo a remplazar if(&nodpad->NodosDeCalculo.Item(m)==&ListaArbol.Item(j)) { nodpad->NodosDeCalculo.Detach(m); nodpad->NodosDeCalculo.Insert(&ListaArbol.Item(i),m); } } // adicionamos apuntadores a padre del original ListaArbol.Item(i).NodosPadre.Add(nodpad); } // eliminamos el nodo repetido.. ListaArbol.Detach(j); // deberá hacerse delete !!! j=tam; flagCiclo=1; // salimos del ciclo... } } } } tam=ListaArbol.GetCount(); for(i=0;i<tam;i++) { ListaArbol.Detach(0); } }while(flagCiclo==1); //////////////////// Fin de la verificación Generalidades.read(str); } /** * Implementación de la segunda estrategia de cálculo de impacto en vertederos (Monserrat Zambrano) */ void Estrategia::crearVertedero2() { // Generalidades Generalidades.adicionarPropiedad(wxT("Ubicación")); // Declaración y construcción de los nodos del árbol NodoCalculo *IMVASP,*IMVAST,*IMVAT,*IMVSL,*IMVSP; NodoCalculo *IRAASP,*IRAAST,*IRAAT,*IRASL,*IRASP; NodoCalculo *CPAASP,*CPAAST,*CPAAT,*CPASL,*CPASP; NodoCalculo *PBCASP,*PBCAST,*PBCAT,*PBCSL,*PBCSP; NodoCalculo *VAASP, *VAAST, *VAAT, *VASL,*VASP; NodoCalculo *A1,*A2,*A3,*A4,*A5; NodoCalculo *B1,*B2; NodoCalculo *C1,*C2,*C3,*C4,*C5,*C6; NodoCalculo *UsoAgricola,*UsoRecreacional,*UsoResidencial; NodoCalculo *DAG,*DRC,*DRS; NodoCalculo *D1,*D2,*D3,*D4,*D5,*D6; NodoCalculo *a,*b,*c,*d,*e,*f,*g,*h,*i,*j,*k,*l,*m,*n,*o,*p,*q,*r,*s,*t,*u,*v,*w,*xx,*y; NodoCalculo *mo; NodoCalculo *res; NodoCalculo *IASP,*IAST,*IAT,*ISL,*ISP; NodoCalculo *RASP,*RAST,*RAT,*RSL,*RSP; NodoCalculo *DASP,*DAST,*DAT,*DSL,*DSP; NodoCalculo *EASP,*EAST,*EAT,*ESL,*ESP; IMVASP=new NodoCalculo(); IMVAST=new NodoCalculo(); IMVAT=new NodoCalculo(); IMVSL=new NodoCalculo(); IMVSP=new NodoCalculo(); IRAASP=new NodoCalculo(); IRAAST=new NodoCalculo(); IRAAT=new NodoCalculo(); IRASL=new NodoCalculo(); IRASP=new NodoCalculo(); CPAASP=new NodoCalculo(); CPAAST=new NodoCalculo(); CPAAT=new NodoCalculo(); CPASL=new NodoCalculo(); CPASP=new NodoCalculo(); PBCASP=new NodoCalculo(); PBCAST=new NodoCalculo(); PBCAT=new NodoCalculo(); PBCSL=new NodoCalculo(); PBCSP=new NodoCalculo(); VAASP=new NodoCalculo(); VAAST=new NodoCalculo(); VAAT=new NodoCalculo(); VASL=new NodoCalculo(); VASP=new NodoCalculo(); A1=new NodoCalculo();A2=new NodoCalculo();A3=new NodoCalculo();A4=new NodoCalculo();A5=new NodoCalculo(); B1=new NodoCalculo();B2=new NodoCalculo(); C1=new NodoCalculo();C2=new NodoCalculo();C3=new NodoCalculo();C4=new NodoCalculo();C5=new NodoCalculo();C6=new NodoCalculo(); UsoAgricola=new NodoCalculo();UsoRecreacional=new NodoCalculo();UsoResidencial=new NodoCalculo(); DAG=new NodoCalculo();DRC=new NodoCalculo();DRS=new NodoCalculo(); D1=new NodoCalculo();D2=new NodoCalculo();D3=new NodoCalculo();D4=new NodoCalculo();D5=new NodoCalculo();D6=new NodoCalculo(); a=new NodoCalculo();b=new NodoCalculo();c=new NodoCalculo();d=new NodoCalculo();e=new NodoCalculo(); f=new NodoCalculo();g=new NodoCalculo();h=new NodoCalculo();i=new NodoCalculo();j=new NodoCalculo(); k=new NodoCalculo();l=new NodoCalculo();m=new NodoCalculo();n=new NodoCalculo();o=new NodoCalculo(); p=new NodoCalculo();q=new NodoCalculo();r=new NodoCalculo();s=new NodoCalculo();t=new NodoCalculo(); u=new NodoCalculo();v=new NodoCalculo();w=new NodoCalculo();xx=new NodoCalculo();y=new NodoCalculo(); mo=new NodoCalculo();res=new NodoCalculo(); IASP=new NodoCalculo(); IAST=new NodoCalculo(); IAT=new NodoCalculo(); ISL=new NodoCalculo(); ISP=new NodoCalculo(); RASP=new NodoCalculo(); RAST=new NodoCalculo(); RAT=new NodoCalculo(); RSL=new NodoCalculo(); RSP=new NodoCalculo(); DASP=new NodoCalculo(); DAST=new NodoCalculo(); DAT=new NodoCalculo(); DSL=new NodoCalculo(); DSP=new NodoCalculo(); EASP=new NodoCalculo(); EAST=new NodoCalculo(); EAT=new NodoCalculo(); ESL=new NodoCalculo(); ESP=new NodoCalculo(); // Definición de Variables Grafo.VarCalculada.Nombre=wxT("IMV"); Etiqueta *Et; VariableLinguistica *Var; Var=&(Grafo.VarCalculada); Var->autodefinirRecto(5); IMVASP->VarCalculada.Nombre=wxT("IMVASP"); Var=&(IMVASP->VarCalculada); Var->autodefinirRecto(5); IMVAST->VarCalculada.Nombre=wxT("IMVAST"); Var=&(IMVAST->VarCalculada); Var->autodefinirRecto(5); IMVAT->VarCalculada.Nombre=wxT("IMVAT"); Var=&(IMVAT->VarCalculada); Var->autodefinirRecto(5); IMVSL->VarCalculada.Nombre=wxT("IMVSL"); Var=&(IMVSL->VarCalculada); Var->autodefinirRecto(5); IMVSP->VarCalculada.Nombre=wxT("IMVSP"); Var=&(IMVSP->VarCalculada); Var->autodefinirRecto(5); IRAASP->VarCalculada.Nombre=wxT("IRAASP"); Var=&(IRAASP->VarCalculada); Var->autodefinirRecto(5); IRAAST->VarCalculada.Nombre=wxT("IRAAST"); Var=&(IRAAST->VarCalculada); Var->autodefinirRecto(5); IRAAT->VarCalculada.Nombre=wxT("IRAAT"); Var=&(IRAAT->VarCalculada); Var->autodefinirRecto(5); IRASL->VarCalculada.Nombre=wxT("IRASL"); Var=&(IRASL->VarCalculada); Var->autodefinirRecto(5); IRASP->VarCalculada.Nombre=wxT("IRASP"); Var=&(IRASP->VarCalculada); Var->autodefinirRecto(5); CPAASP->VarCalculada.Nombre=wxT("CPAASP"); Var=&(CPAASP->VarCalculada); Var->autodefinirRecto(5); CPAAST->VarCalculada.Nombre=wxT("CPAAST"); Var=&(CPAAST->VarCalculada); Var->autodefinirRecto(5); CPAAT->VarCalculada.Nombre=wxT("CPAAT"); Var=&(CPAAT->VarCalculada); Var->autodefinirRecto(5); CPASL->VarCalculada.Nombre=wxT("CPASL"); Var=&(CPASL->VarCalculada); Var->autodefinirRecto(5); CPASP->VarCalculada.Nombre=wxT("CPASP"); Var=&(CPASP->VarCalculada); Var->autodefinirRecto(5); PBCASP->VarCalculada.Nombre=wxT("PBCASP"); Var=&(PBCASP->VarCalculada); Var->autodefinirRecto(5); PBCAST->VarCalculada.Nombre=wxT("PBCAST"); Var=&(PBCAST->VarCalculada); Var->autodefinirRecto(5); PBCAT->VarCalculada.Nombre=wxT("PBCAT"); Var=&(PBCAT->VarCalculada); Var->autodefinirRecto(5); PBCSL->VarCalculada.Nombre=wxT("PBCSL"); Var=&(PBCSL->VarCalculada); Var->autodefinirRecto(5); PBCSP->VarCalculada.Nombre=wxT("PBCSP"); Var=&(PBCSP->VarCalculada); Var->autodefinirRecto(5); VAASP->VarCalculada.Nombre=wxT("VAASP"); Var=&(VAASP->VarCalculada); Var->autodefinirRecto(5); VAAST->VarCalculada.Nombre=wxT("VAAST"); Var=&(VAAST->VarCalculada); Var->autodefinirRecto(5); VAAT->VarCalculada.Nombre=wxT("VAAT"); Var=&(VAAT->VarCalculada); Var->autodefinirRecto(5); VASL->VarCalculada.Nombre=wxT("VASL"); Var=&(VASL->VarCalculada); Var->autodefinirRecto(5); VASP->VarCalculada.Nombre=wxT("VASP"); Var=&(VASP->VarCalculada); Var->autodefinirRecto(5); A1->VarCalculada.Nombre=wxT("A1"); Var=&(A1->VarCalculada); Var->autodefinirRecto(5); A2->VarCalculada.Nombre=wxT("A2"); Var=&(A2->VarCalculada); Var->autodefinirRecto(5); A3->VarCalculada.Nombre=wxT("A3"); Var=&(A3->VarCalculada); Var->autodefinirRecto(5); A4->VarCalculada.Nombre=wxT("A4"); Var=&(A4->VarCalculada); Var->autodefinirRecto(5); A5->VarCalculada.Nombre=wxT("A5"); Var=&(A5->VarCalculada); Var->autodefinirRecto(5); B1->VarCalculada.Nombre=wxT("B1"); Var=&(B1->VarCalculada); Var->autodefinirRecto(5); B2->VarCalculada.Nombre=wxT("B2"); Var=&(B2->VarCalculada); Var->autodefinirRecto(5); C1->VarCalculada.Nombre=wxT("C1"); Var=&(C1->VarCalculada); Var->autodefinirRecto(5); C2->VarCalculada.Nombre=wxT("C2"); Var=&(C2->VarCalculada); Var->autodefinirRecto(5); C3->VarCalculada.Nombre=wxT("C3"); Var=&(C3->VarCalculada); Var->autodefinirRecto(5); C4->VarCalculada.Nombre=wxT("C4"); Var=&(C4->VarCalculada); Var->autodefinirRecto(5); C5->VarCalculada.Nombre=wxT("C5"); Var=&(C5->VarCalculada); Var->autodefinirRecto(5); C6->VarCalculada.Nombre=wxT("C6"); Var=&(C6->VarCalculada); Var->autodefinirRecto(5); UsoAgricola->VarCalculada.Nombre=wxT("Uso Agricola"); Var=&(UsoAgricola->VarCalculada); Var->autodefinirRecto(2); UsoRecreacional->VarCalculada.Nombre=wxT("Uso Recreacional"); Var=&(UsoRecreacional->VarCalculada); Var->autodefinirRecto(2); UsoResidencial->VarCalculada.Nombre=wxT("Uso Residencial"); Var=&(UsoResidencial->VarCalculada); Var->autodefinirRecto(2); DAG->VarCalculada.Nombre=wxT("DAG"); Var=&(DAG->VarCalculada); Var->autodefinirRecto(5); DRC->VarCalculada.Nombre=wxT("DRS"); Var=&(DRC->VarCalculada); Var->autodefinirRecto(5); DRS->VarCalculada.Nombre=wxT("DRC"); Var=&(DRS->VarCalculada); Var->autodefinirRecto(5); D1->VarCalculada.Nombre=wxT("D1"); Var=&(D1->VarCalculada); Var->autodefinirRecto(5); D2->VarCalculada.Nombre=wxT("D2"); Var=&(D2->VarCalculada); Var->autodefinirRecto(5); D3->VarCalculada.Nombre=wxT("D3"); Var=&(D3->VarCalculada); Var->autodefinirRecto(5); D4->VarCalculada.Nombre=wxT("D4"); Var=&(D4->VarCalculada); Var->autodefinirRecto(5); D5->VarCalculada.Nombre=wxT("D5"); Var=&(D5->VarCalculada); Var->autodefinirRecto(5); D6->VarCalculada.Nombre=wxT("D6"); Var=&(D6->VarCalculada); Var->autodefinirRecto(5); a->VarCalculada.Nombre=wxT("Compactación"); Var=&(a->VarCalculada); Var->autodefinirRecto(5); b->VarCalculada.Nombre=wxT("Residuos y m.o."); Var=&(b->VarCalculada); Var->autodefinirRecto(5); c->VarCalculada.Nombre=wxT("Edad"); Var=&(c->VarCalculada); Var->autodefinirRecto(5); d->VarCalculada.Nombre=wxT("Cobertura"); Var=&(d->VarCalculada); Var->autodefinirRecto(5); e->VarCalculada.Nombre=wxT("Gases"); Var=&(e->VarCalculada); Var->autodefinirRecto(5); f->VarCalculada.Nombre=wxT("Caminos"); Var=&(f->VarCalculada); Var->autodefinirRecto(5); g->VarCalculada.Nombre=wxT("Pluviometría"); Var=&(g->VarCalculada); Var->autodefinirRecto(5); h->VarCalculada.Nombre=wxT("Lixiviados"); Var=&(h->VarCalculada); Var->autodefinirRecto(5); i->VarCalculada.Nombre=wxT("Cobertura Final"); Var=&(i->VarCalculada); Var->autodefinirRecto(5); j->VarCalculada.Nombre=wxT("Operatividad"); Var=&(j->VarCalculada); Var->autodefinirRecto(5); k->VarCalculada.Nombre=wxT("Pendiente a cauces"); Var=&(k->VarCalculada); Var->autodefinirRecto(5); l->VarCalculada.Nombre=wxT("Permeabilidad"); Var=&(l->VarCalculada); Var->autodefinirRecto(5); m->VarCalculada.Nombre=wxT("Drenaje"); Var=&(m->VarCalculada); Var->autodefinirRecto(5); n->VarCalculada.Nombre=wxT("Aguas superficiales"); Var=&(n->VarCalculada); Var->autodefinirRecto(5); o->VarCalculada.Nombre=wxT("Impermeabilización"); Var=&(o->VarCalculada); Var->autodefinirRecto(5); p->VarCalculada.Nombre=wxT("Área inundable"); Var=&(p->VarCalculada); Var->autodefinirRecto(5); q->VarCalculada.Nombre=wxT("Escorrentía superficial"); Var=&(q->VarCalculada); Var->autodefinirRecto(5); r->VarCalculada.Nombre=wxT("Profundidad aguas subterráneas"); Var=&(r->VarCalculada); Var->autodefinirRecto(5); s->VarCalculada.Nombre=wxT("Fallas cercanas"); Var=&(s->VarCalculada); Var->autodefinirRecto(5); t->VarCalculada.Nombre=wxT("Edad y m.o."); Var=&(t->VarCalculada); Var->autodefinirRecto(5); u->VarCalculada.Nombre=wxT("Taludes"); Var=&(u->VarCalculada); Var->autodefinirRecto(5); v->VarCalculada.Nombre=wxT("Distancia a Infraestructuras"); Var=&(v->VarCalculada); Var->autodefinirRecto(5); w->VarCalculada.Nombre=wxT("Control Ambiental"); Var=&(w->VarCalculada); Var->autodefinirRecto(5); xx->VarCalculada.Nombre=wxT("Distancia a poblados"); Var=&(xx->VarCalculada); Var->autodefinirRecto(5); y->VarCalculada.Nombre=wxT("Equipamiento Personal"); Var=&(y->VarCalculada); Var->autodefinirRecto(5); mo->VarCalculada.Nombre=wxT("Materia Orgánica"); Var=&(mo->VarCalculada); Var->autodefinirRecto(5); res->VarCalculada.Nombre=wxT("Residuos"); Var=&(res->VarCalculada); Var->autodefinirRecto(5); IASP->VarCalculada.Nombre=wxT("Intensidad ASP"); Var=&(IASP->VarCalculada); Var->autodefinirRecto(5); IAST->VarCalculada.Nombre=wxT("Intensidad AST"); Var=&(IAST->VarCalculada); Var->autodefinirRecto(5); IAT->VarCalculada.Nombre=wxT("Intensidad AT"); Var=&(IAT->VarCalculada); Var->autodefinirRecto(5); ISL->VarCalculada.Nombre=wxT("Intensidad SL"); Var=&(ISL->VarCalculada); Var->autodefinirRecto(5); ISP->VarCalculada.Nombre=wxT("Intensidad SP"); Var=&(ISP->VarCalculada); Var->autodefinirRecto(5); RASP->VarCalculada.Nombre=wxT("Reversibilidad ASP"); Var=&(RASP->VarCalculada); Var->autodefinirRecto(5); RAST->VarCalculada.Nombre=wxT("Reversibilidad AST"); Var=&(RAST->VarCalculada); Var->autodefinirRecto(5); RAT->VarCalculada.Nombre=wxT("Reversibilidad AT"); Var=&(RAT->VarCalculada); Var->autodefinirRecto(5); RSL->VarCalculada.Nombre=wxT("Reversibilidad SL"); Var=&(RSL->VarCalculada); Var->autodefinirRecto(5); RSP->VarCalculada.Nombre=wxT("Reversibilidad SP"); Var=&(RSP->VarCalculada); Var->autodefinirRecto(5); DASP->VarCalculada.Nombre=wxT("Duración ASP"); Var=&(DASP->VarCalculada); Var->autodefinirRecto(5); DAST->VarCalculada.Nombre=wxT("Duración AST"); Var=&(DAST->VarCalculada); Var->autodefinirRecto(5); DAT->VarCalculada.Nombre=wxT("Duración AT"); Var=&(DAT->VarCalculada); Var->autodefinirRecto(5); DSL->VarCalculada.Nombre=wxT("Duración SL"); Var=&(DSL->VarCalculada); Var->autodefinirRecto(5); DSP->VarCalculada.Nombre=wxT("Duración SP"); Var=&(DSP->VarCalculada); Var->autodefinirRecto(5); EASP->VarCalculada.Nombre=wxT("Extensión ASP"); Var=&(EASP->VarCalculada); Var->autodefinirRecto(5); EAST->VarCalculada.Nombre=wxT("Extensión AST"); Var=&(EAST->VarCalculada); Var->autodefinirRecto(5); EAT->VarCalculada.Nombre=wxT("Extensión AT"); Var=&(EAT->VarCalculada); Var->autodefinirRecto(5); ESL->VarCalculada.Nombre=wxT("Extensión SL"); Var=&(ESL->VarCalculada); Var->autodefinirRecto(5); ESP->VarCalculada.Nombre=wxT("Extensión SP"); Var=&(ESP->VarCalculada); Var->autodefinirRecto(5); // INCOMPLETO // asignación de los nodos y funciones Funcion *F; float x[20]; Grafo.adicionarNodo(IMVASP); Grafo.adicionarNodo(IMVAST); Grafo.adicionarNodo(IMVAT); Grafo.adicionarNodo(IMVSL); Grafo.adicionarNodo(IMVSP); x[0]=1.0;x[1]=1.0;x[2]=1.0;x[3]=1.0;x[4]=1.0; F=new CombinacionLineal(x,5,0.0); Grafo.asignarFuncion(F); IMVASP->adicionarNodo(IRAASP); IMVASP->adicionarNodo(CPAASP); x[0]=1.0;x[1]=1.0; F=new SumaProd(x,2,0.0); IMVASP->asignarFuncion(F); IMVAST->adicionarNodo(IRAAST); IMVAST->adicionarNodo(CPAAST); x[0]=1.0;x[1]=1.0; F=new SumaProd(x,2,0.0); IMVAST->asignarFuncion(F); IMVAT->adicionarNodo(IRAAT); IMVAT->adicionarNodo(CPAAT); x[0]=1.0;x[1]=1.0; F=new SumaProd(x,2,0.0); IMVAT->asignarFuncion(F); IMVSL->adicionarNodo(IRASL); IMVSL->adicionarNodo(CPASL); x[0]=1.0;x[1]=1.0; F=new SumaProd(x,2,0.0); IMVSL->asignarFuncion(F); IMVSP->adicionarNodo(IRASP); IMVSP->adicionarNodo(CPASP); x[0]=1.0;x[1]=1.0; F=new SumaProd(x,2,0.0); IMVSP->asignarFuncion(F); IRAASP->adicionarNodo(PBCASP); IRAASP->adicionarNodo(VAASP); x[0]=1.0;x[1]=1.0; F=new SumaProd(x,2,0.0); IRAASP->asignarFuncion(F); IRAAST->adicionarNodo(PBCAST); IRAAST->adicionarNodo(VAAST); x[0]=1.0;x[1]=1.0; F=new SumaProd(x,2,0.0); IRAAST->asignarFuncion(F); IRAAT->adicionarNodo(PBCAT); IRAAT->adicionarNodo(VAAT); x[0]=1.0;x[1]=1.0; F=new SumaProd(x,2,0.0); IRAAT->asignarFuncion(F); IRASL->adicionarNodo(PBCSL); IRASL->adicionarNodo(VASL); x[0]=1.0;x[1]=1.0; F=new SumaProd(x,2,0.0); IRASL->asignarFuncion(F); IRASP->adicionarNodo(PBCSP); IRASP->adicionarNodo(VASP); x[0]=1.0;x[1]=1.0; F=new SumaProd(x,2,0.0); IRASP->asignarFuncion(F); VAASP->adicionarNodo(A1); VAASP->adicionarNodo(A2); VAASP->adicionarNodo(A3); VAASP->adicionarNodo(A4); VAASP->adicionarNodo(A5); x[0]=1.0;x[1]=1.0;x[2]=2.0;x[3]=1.0;x[4]=1.0; F=new CombinacionLineal(x,5,0.0); VAASP->asignarFuncion(F); VAAST->adicionarNodo(B1); VAAST->adicionarNodo(B2); x[0]=1.0;x[1]=2.0; F=new CombinacionLineal(x,2,0.0); VAAST->asignarFuncion(F); VAAT->adicionarNodo(C1); VAAT->adicionarNodo(C2); VAAT->adicionarNodo(C3); VAAT->adicionarNodo(C4); VAAT->adicionarNodo(C5); VAAT->adicionarNodo(C6); x[0]=2.0;x[1]=1.0;x[2]=1.0;x[3]=1.0;x[4]=1.0;x[5]=1.0; F=new CombinacionLineal(x,6,0.0); VAAT->asignarFuncion(F); VASL->adicionarNodo(UsoAgricola); VASL->adicionarNodo(DAG); VASL->adicionarNodo(UsoRecreacional); VASL->adicionarNodo(DRC); VASL->adicionarNodo(UsoResidencial); VASL->adicionarNodo(DRS); x[0]=1.0;x[1]=1.0;x[2]=1.0;x[3]=1.0;x[4]=1.0;x[5]=1.0; F=new SumaProd(x,6,0.0); VASL->asignarFuncion(F); DAG->adicionarNodo(D1); DAG->adicionarNodo(D2); DAG->adicionarNodo(D3); DAG->adicionarNodo(D4); x[0]=1.0;x[1]=1.0;x[2]=1.0;x[3]=1.0; F=new CombinacionLineal(x,4,0.0); DAG->asignarFuncion(F); DRC->adicionarNodo(D1); DRC->adicionarNodo(D2); DRC->adicionarNodo(D4); x[0]=1.0;x[1]=1.0;x[2]=1.0; F=new CombinacionLineal(x,5,0.0); DRC->asignarFuncion(F); DRS->adicionarNodo(D1); DRS->adicionarNodo(D2); DRS->adicionarNodo(D4); DRS->adicionarNodo(D5); DRS->adicionarNodo(D6); x[0]=1.0;x[1]=1.0;x[2]=1.0;x[3]=1.0;x[4]=1.0; F=new CombinacionLineal(x,5,0.0); DRS->asignarFuncion(F); PBCAT->adicionarNodo(a); PBCAT->adicionarNodo(b); PBCAT->adicionarNodo(c); PBCAT->adicionarNodo(d); PBCAT->adicionarNodo(e); PBCAT->adicionarNodo(f); PBCAT->adicionarNodo(g); PBCAT->adicionarNodo(h); PBCAT->adicionarNodo(i); PBCAT->adicionarNodo(j); x[0]=2.0/10.0;x[1]=2.0/10.0;x[2]=1.0/10.0;x[3]=2.0/10.0;x[4]=2.0/10.0; x[5]=1.0/10.0;x[6]=2.0/10.0;x[7]=1.0/10.0;x[8]=2.0/10.0;x[9]=1.0/10.0; F=new CombinacionLineal(x,10,0.0); PBCAT->asignarFuncion(F); PBCASP->adicionarNodo(a); PBCASP->adicionarNodo(b); PBCASP->adicionarNodo(c); PBCASP->adicionarNodo(d); PBCASP->adicionarNodo(k); PBCASP->adicionarNodo(l); PBCASP->adicionarNodo(m); PBCASP->adicionarNodo(n); PBCASP->adicionarNodo(g); PBCASP->adicionarNodo(o); PBCASP->adicionarNodo(h); PBCASP->adicionarNodo(i); PBCASP->adicionarNodo(p); PBCASP->adicionarNodo(q); PBCASP->adicionarNodo(j); x[0]=2.0/15.0;x[1]=2.0/15.0;x[2]=1.0/15.0;x[3]=2.0/15.0;x[4]=1.0/15.0; x[5]=1.0/15.0;x[6]=1.0/15.0;x[7]=2.0/15.0;x[8]=2.0/15.0;x[9]=2.0/15.0; x[10]=2.0/15.0;x[11]=2.0/15.0;x[12]=2.0/15.0;x[13]=2.0/15.0;x[14]=1.0/15.0; F=new CombinacionLineal(x,15,0.0); PBCASP->asignarFuncion(F); PBCAST->adicionarNodo(a); PBCAST->adicionarNodo(b); PBCAST->adicionarNodo(c); PBCAST->adicionarNodo(d); PBCAST->adicionarNodo(r); PBCAST->adicionarNodo(s); PBCAST->adicionarNodo(m); PBCAST->adicionarNodo(g); PBCAST->adicionarNodo(o); PBCAST->adicionarNodo(h); PBCAST->adicionarNodo(i); PBCAST->adicionarNodo(p); PBCAST->adicionarNodo(q); PBCAST->adicionarNodo(j); x[0]=2.0/14.0;x[1]=2.0/14.0;x[2]=1.0/14.0;x[3]=2.0/14.0;x[4]=2.0/14.0; x[5]=1.0/14.0;x[6]=1.0/14.0;x[7]=2.0/14.0;x[8]=2.0/14.0;x[9]=2.0/14.0; x[10]=2.0/14.0;x[11]=2.0/14.0;x[12]=2.0/14.0;x[13]=1.0/14.0; F=new CombinacionLineal(x,14,0.0); PBCAST->asignarFuncion(F); PBCSL->adicionarNodo(a); PBCSL->adicionarNodo(t); PBCSL->adicionarNodo(d); PBCSL->adicionarNodo(e); PBCSL->adicionarNodo(u); PBCSL->adicionarNodo(o); PBCSL->adicionarNodo(p); PBCSL->adicionarNodo(h); PBCSL->adicionarNodo(i); PBCSL->adicionarNodo(q); PBCSL->adicionarNodo(j); x[0]=2.0/11.0;x[1]=2.0/11.0;x[2]=2.0/11.0;x[3]=1.0/11.0;x[4]=2.0/11.0; x[5]=1.0/11.0;x[6]=2.0/11.0;x[7]=1.0/11.0;x[8]=2.0/11.0;x[9]=2.0/11.0; x[10]=1.0/11.0; F=new CombinacionLineal(x,11,0.0); PBCSL->asignarFuncion(F); PBCSP->adicionarNodo(a); PBCSP->adicionarNodo(b); PBCSP->adicionarNodo(c); PBCSP->adicionarNodo(d); PBCSP->adicionarNodo(v); PBCSP->adicionarNodo(e); PBCSP->adicionarNodo(w); PBCSP->adicionarNodo(h); PBCSP->adicionarNodo(i); PBCSP->adicionarNodo(xx); PBCSP->adicionarNodo(y); PBCSP->adicionarNodo(j); x[0]=2.0/12.0;x[1]=2.0/12.0;x[2]=1.0/12.0;x[3]=1.0/12.0;x[4]=2.0/12.0; x[5]=1.0/12.0;x[6]=1.0/12.0;x[7]=1.0/12.0;x[8]=2.0/12.0;x[9]=2.0/12.0; x[10]=2.0/12.0;x[11]=1.0/12.0; F=new CombinacionLineal(x,12,0.0); PBCSP->asignarFuncion(F); t->adicionarNodo(c); t->adicionarNodo(mo); x[0]=1.0;x[1]=1.0; F=new CombinacionLineal(x,2,0.0); t->asignarFuncion(F); b->adicionarNodo(res); b->adicionarNodo(mo); x[0]=1.0;x[1]=1.0; F=new CombinacionLineal(x,2,0.0); b->asignarFuncion(F); CPAASP->adicionarNodo(IASP); CPAASP->adicionarNodo(RASP); CPAASP->adicionarNodo(DASP); CPAASP->adicionarNodo(EASP); x[0]=1.0/3.0;x[1]=1.0;x[2]=1.0;x[3]=1.0; F=new CombinacionLineal(x,4,0.0); CPAASP->asignarFuncion(F); CPAAST->adicionarNodo(IAST); CPAAST->adicionarNodo(RAST); CPAAST->adicionarNodo(DAST); CPAAST->adicionarNodo(EAST); x[0]=1.0/3.0;x[1]=1.0;x[2]=1.0;x[3]=1.0; F=new CombinacionLineal(x,4,0.0); CPAAST->asignarFuncion(F); CPAAT->adicionarNodo(IAT); CPAAT->adicionarNodo(RAT); CPAAT->adicionarNodo(DAT); CPAAT->adicionarNodo(EAT); x[0]=1.0/3.0;x[1]=1.0;x[2]=1.0;x[3]=1.0; F=new CombinacionLineal(x,4,0.0); CPAAT->asignarFuncion(F); CPASL->adicionarNodo(ISL); CPASL->adicionarNodo(RSL); CPASL->adicionarNodo(DSL); CPASL->adicionarNodo(ESL); x[0]=1.0/3.0;x[1]=1.0;x[2]=1.0;x[3]=1.0; F=new CombinacionLineal(x,4,0.0); CPASL->asignarFuncion(F); CPASP->adicionarNodo(ISP); CPASP->adicionarNodo(RSP); CPASP->adicionarNodo(DSP); CPASP->adicionarNodo(ESP); x[0]=1.0/3.0;x[1]=1.0;x[2]=1.0;x[3]=1.0; F=new CombinacionLineal(x,4,0.0); CPASP->asignarFuncion(F); } ////////////////////////////////////////// void Estrategia::crearRed1() { /** * Implementación de la primera estrategia de cálculo para la Casa de la Calidad */ // Generalidades Generalidades.adicionarPropiedad(wxT("Ubicación")); // Generalidades.modificarValor("xxx","Ubicación"); // Declaración y construcción de los nodos del árbol NodoCalculo *bi0,*mi,*ti0,*RankingPosicion; NodoCalculo *gi,*vi,*wi,*RankingOrden; //Estas faltan *xi,*yj, Faltan las var de salida NodoCalculo *bi1; // Competencia bik NodoCalculo *bi2; // Competencia bik NodoCalculo *ti1; // tik NodoCalculo *ti2; // tik bi0=new NodoCalculo(); mi=new NodoCalculo(); ti0=new NodoCalculo(); RankingPosicion=new NodoCalculo(); gi=new NodoCalculo(); vi=new NodoCalculo(); wi=new NodoCalculo(); RankingOrden=new NodoCalculo(); bi1=new NodoCalculo(); // SON 2 Competidores bi2=new NodoCalculo(); // SON 2 Competidores ti1=new NodoCalculo(); // SON 2 Competidores ti2=new NodoCalculo(); // SON 2 Competidores // Definición de Variables Grafo.VarCalculada.Nombre=wxT("zi"); // corresponde al nodo superior en la Red1 Etiqueta *Et; VariableLinguistica *Var; Var=&(Grafo.VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Nulo");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Indiferente");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Recomendado");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Importante");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Importante");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); // V: semántica provisional. bi0->VarCalculada.Nombre=wxT("bi0"); Var=&(bi0->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Muy Lejano");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); // Et->ND->trapecio(.1,.2,.3,.4) Et=new Etiqueta; Et->Label=wxT("Lejano");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Cercano");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Cercano");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); mi->VarCalculada.Nombre=wxT("mi"); Var=&(mi->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Meta");Et->ND->trapecio(.4,.5,.5,.6);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Meta Ideal");Et->ND->trapecio(.6,.7,.7,.8);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Meta Fisiologica");Et->ND->trapecio(.8,1,1,1);Var->Etiquetas.Add(Et); bi1->VarCalculada.Nombre=wxT("bi-1"); Var=&(bi1->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Muy Lejano");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); // Et->ND->trapecio(.1,.2,.3,.4) Et=new Etiqueta; Et->Label=wxT("Lejano");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Cercano");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Cercano");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); bi2->VarCalculada.Nombre=wxT("bi-2"); Var=&(bi2->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Muy Lejano");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); // Et->ND->trapecio(.1,.2,.3,.4) Et=new Etiqueta; Et->Label=wxT("Lejano");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Cercano");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Cercano");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); ti0->VarCalculada.Nombre=wxT("ti0"); Var=&(ti0->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Muy Cercano");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Cercano");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Lejano");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Lejano");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); // vector de ti ti1->VarCalculada.Nombre=wxT("ti-1"); Var=&(ti1->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Muy Cercano");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Cercano");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Lejano");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Lejano");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); ti2->VarCalculada.Nombre=wxT("ti-2"); Var=&(ti2->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Muy Cercano");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Cercano");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Lejano");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Lejano");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); RankingPosicion->VarCalculada.Nombre=wxT("RankingPosicion"); Var=&(RankingPosicion->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Ultimo");Et->ND->trapecio(0,0,0,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Primero");Et->ND->trapecio(.7,1,1,1);Var->Etiquetas.Add(Et); gi->VarCalculada.Nombre=wxT("gi"); Var=&(gi->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Nulo");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Indiferente");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Recomendado");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Importante");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Importante");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); vi->VarCalculada.Nombre=wxT("vi"); Var=&(vi->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Poco Importante");Et->ND->trapecio(0,0,0,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Importante");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Importante");Et->ND->trapecio(.7,1,1,1);Var->Etiquetas.Add(Et); wi->VarCalculada.Nombre=wxT("wi"); Var=&(wi->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Nulo");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Indiferente");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Recomendado");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Importante");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Importante");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); RankingOrden->VarCalculada.Nombre=wxT("RankingOrden"); Var=&(RankingOrden->VarCalculada); Var->autodefinirRecto(4); Et=&Var->Etiquetas.Item(0); Et->Label=wxT("Nula"); Et=&Var->Etiquetas.Item(1); Et->Label=wxT("Baja"); Et=&Var->Etiquetas.Item(2); Et->Label=wxT("Alta"); Et=&Var->Etiquetas.Item(3); Et->Label=wxT("Inminente"); ////////////////////////////////////////////////////////////////////////////// // asignación de los nodos y funciones Funcion *F; float x[20]; Grafo.adicionarNodo(RankingPosicion); Grafo.adicionarNodo(RankingOrden); x[0]=0.5;x[1]=0.5; F=new CombinacionLineal(x,2,0.0); Grafo.asignarFuncion(F); RankingPosicion->adicionarNodo(ti0); RankingPosicion->adicionarNodo(ti1); RankingPosicion->adicionarNodo(ti2); x[0]=0.5;x[0]=0.3;x[0]=0.2; F=new CombinacionLineal(x,2+1,0.0); RankingPosicion->asignarFuncion(F); ti0->adicionarNodo(bi0); ti0->adicionarNodo(mi); x[0]= .5;x[1]=.5; F=new CombinacionLineal(x,2,0.0); ti0->asignarFuncion(F); ti1->adicionarNodo(mi); ti1->adicionarNodo(bi1); x[0]=0.5;x[1]=0.5; F=new CombinacionLineal(x,2,0.0); ti1->asignarFuncion(F); ti2->adicionarNodo(mi); ti2->adicionarNodo(bi2); x[0]=0.5;x[1]=0.5; F=new CombinacionLineal(x,2,0.0); ti2->asignarFuncion(F); RankingOrden->adicionarNodo(wi); x[0]= 1; F=new CombinacionLineal(x,1,0.0); RankingOrden->asignarFuncion(F); wi->adicionarNodo(gi); wi->adicionarNodo(vi); wi->adicionarNodo(ti0); x[0]= .5;x[1]=.3;x[2]=.2; F=new CombinacionLineal(x,3,0.0); wi->asignarFuncion(F); } void Estrategia::crearRed2() { /** * Implementación de la primera estrategia de cálculo para la Casa de la Calidad */ // Generalidades Generalidades.adicionarPropiedad(wxT("Ubicación")); // Generalidades.modificarValor("xxx","Ubicación"); // Declaración y construcción de los nodos del árbol NodoCalculo *bj0,*mj,*tj0,*RankingPosicionj; NodoCalculo *sjj,*wj,*RankingOrdenj; //Estas faltan *xi,*yj, Faltan las var de salida NodoCalculo *bj1; // Competencia bjk NodoCalculo *bj2; NodoCalculo *tj1; NodoCalculo *tj2; NodoCalculo **cij; NodoCalculo **wi; NodoCalculo *zi; bj0=new NodoCalculo(); mj=new NodoCalculo(); tj0=new NodoCalculo(); RankingPosicionj=new NodoCalculo();sjj=new NodoCalculo(); wj=new NodoCalculo();RankingOrdenj=new NodoCalculo(); bj1=new NodoCalculo(); // SON 2 Competidores bj2=new NodoCalculo(); tj1=new NodoCalculo(); // SON 2 Competidores tj2=new NodoCalculo(); cij=new NodoCalculo*[32]; // SON 23 Caracteristicas de Calidad wi=new NodoCalculo*[32]; // SON 23 Caracteristicas de Calidad zi=new NodoCalculo(); // Es el valor resultante de la Red1 // Definición de Variables Grafo.VarCalculada.Nombre=wxT("zj"); // corresponde al nodo superior zj en la Red Etiqueta *Et; VariableLinguistica *Var; Var=&(Grafo.VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Nulo");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Indiferente");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Recomendado");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Importante");Et->ND->trapecio(.5,.7,.7,1.000);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Importante");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); // V: semántica provisional. bj0->VarCalculada.Nombre=wxT("bj0"); Var=&(bj0->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Muy Lejano");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); // Et->ND->trapecio(.1,.2,.3,.4) Et=new Etiqueta; Et->Label=wxT("Lejano");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Cercano");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Cercano");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); mj->VarCalculada.Nombre=wxT("mj"); Var=&(mj->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Meta");Et->ND->trapecio(.4,.5,.5,.6);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Meta Ideal");Et->ND->trapecio(.6,.7,.7,.8);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Meta Fisiologica");Et->ND->trapecio(.8,1,1,1);Var->Etiquetas.Add(Et); // vector de bj bj1->VarCalculada.Nombre=wxT("bj1"); Var=&(bj1->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Muy Lejano");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Lejano");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Cercano");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Cercano");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); bj2->VarCalculada.Nombre=wxT("bj2"); Var=&(bj2->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Muy Lejano");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Lejano");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Cercano");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Cercano");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); tj0->VarCalculada.Nombre=wxT("tj0"); Var=&(tj0->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Muy Cercano");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Cercano");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Lejano");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Lejano");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); tj1->VarCalculada.Nombre=wxT("tj1"); Var=&(tj1->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Muy Cercano");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Cercano");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Lejano");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Lejano");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); tj2->VarCalculada.Nombre=wxT("tj2"); Var=&(tj2->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Muy Cercano");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Cercano");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Lejano");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Lejano");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); RankingPosicionj->VarCalculada.Nombre=wxT("RankingPosicionj"); Var=&(RankingPosicionj->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Ultimo");Et->ND->trapecio(0,0,0,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Medio");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Primero");Et->ND->trapecio(.7,1,1,1);Var->Etiquetas.Add(Et); // Valor de wi de la Red1 // wi->VarCalculada.Nombre=wxT("wi"); // Var=&(wi->VarCalculada); // Var->limpiarListaEtiquetas(); // Et=new Etiqueta; Et->Label=wxT("Nulo");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); // Et=new Etiqueta; Et->Label=wxT("Indiferente");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); // Et=new Etiqueta; Et->Label=wxT("Recomendado");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); // Et=new Etiqueta; Et->Label=wxT("Importante");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); // Et=new Etiqueta; Et->Label=wxT("Muy Importante");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); // vector de cij int i; for(i=0;i<32;i++) { cij[i]=new NodoCalculo(); wxString tmp; tmp << wxT("cij-") << i+1; cij[i]->VarCalculada.Nombre=tmp; Var=&(cij[i]->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Fuertemente Negativa");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Negativa");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Neutra");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Positiva");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Fuertemente Positiva");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); wi[i]=new NodoCalculo(); tmp=wxT(""); tmp << wxT("wi-") << i+1; wi[i]->VarCalculada.Nombre=tmp; Var=&(wi[i]->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Nulo");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Indiferente");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Recomendado");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Importante");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Importante");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); } sjj->VarCalculada.Nombre=wxT("sjj"); Var=&(sjj->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Fuertemente Negativa");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Negativa");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Neutra");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Positiva");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Fuertemente Positiva");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); wj->VarCalculada.Nombre=wxT("wj"); Var=&(wj->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Nulo");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Indiferente");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Recomendado");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Importante");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Importante");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); RankingOrdenj->VarCalculada.Nombre=wxT("RankingOrdenj"); Var=&(RankingOrdenj->VarCalculada); Var->autodefinirRecto(4); Et=&Var->Etiquetas.Item(0); Et->Label=wxT("Nula"); Et=&Var->Etiquetas.Item(1); Et->Label=wxT("Baja"); Et=&Var->Etiquetas.Item(2); Et->Label=wxT("Alta"); Et=&Var->Etiquetas.Item(3); Et->Label=wxT("Inminente"); zi->VarCalculada.Nombre=wxT("zi"); // corresponde al nodo superior en la Red1 Var=&(zi->VarCalculada); Var->limpiarListaEtiquetas(); Et=new Etiqueta; Et->Label=wxT("Nulo");Et->ND->trapecio(0,0,0,.3);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Indiferente");Et->ND->trapecio(0,.3,.3,.5);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Recomendado");Et->ND->trapecio(.3,.5,.5,.7);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Importante");Et->ND->trapecio(.5,.7,.7,1);Var->Etiquetas.Add(Et); Et=new Etiqueta; Et->Label=wxT("Muy Importante");Et->ND->trapecio(.7,1.000,1.000,1.000);Var->Etiquetas.Add(Et); ////////////////////////////////////////////////////////////////////////////// // asignación de los nodos y funciones Funcion *F; float x[100]; Grafo.adicionarNodo(RankingPosicionj); Grafo.adicionarNodo(RankingOrdenj); Grafo.adicionarNodo(sjj); Grafo.adicionarNodo(zi); x[0]=0.08;x[1]=0.5;x[2]=0.5;x[2]=0.5; F=new CombinacionLineal(x,4,0); Grafo.asignarFuncion(F); RankingPosicionj->adicionarNodo(tj0); RankingPosicionj->adicionarNodo(tj1); RankingPosicionj->adicionarNodo(tj2); x[0]= .2;x[1]=.3;x[2]=.1; F=new CombinacionLineal(x,3,0); RankingPosicionj->asignarFuncion(F); tj0->adicionarNodo(mj); tj0->adicionarNodo(bj0); x[0]= .2;x[1]=.3; F=new CombinacionLineal(x,2,0); tj0->asignarFuncion(F); tj1->adicionarNodo(mj); tj1->adicionarNodo(bj1); x[0]= .2;x[1]=.3; F=new CombinacionLineal(x,2,0); tj1->asignarFuncion(F); tj2->adicionarNodo(mj); tj2->adicionarNodo(bj2); x[0]= .2;x[1]=.3; F=new CombinacionLineal(x,2,0); tj2->asignarFuncion(F); RankingOrdenj->adicionarNodo(wj); x[0]= .2;x[1]=.3;x[2]=.1;x[3]=.05;x[4]=.15;x[5]=.15;x[6]=.05; F=new CombinacionLineal(x,1,0); RankingOrdenj->asignarFuncion(F); for(i=0;i<32;i++) { wj->adicionarNodo(cij[i]); wj->adicionarNodo(wi[i]); x[i]=1.0/64.0; x[i+1]=1.0/64.0; } // x[0]= .2;x[1]=.3;x[2]=.1;x[3]=.05;x[4]=.15;x[5]=.15;x[6]=.05; F=new CombinacionLineal(x,64,0); wj->asignarFuncion(F); } void Estrategia::crearRedLink1() { /** * Implementación de la primera estrategia de cálculo con links */ // Generalidades // Declaración y construcción de los nodos del árbol NodoCalculo *N1_2,*N1_3; N1_2=new NodoCalculo(); N1_3=new NodoCalculo(); // Definición de Variables Grafo.VarCalculada.Nombre=wxT("N1_1"); // corresponde al nodo superior en la Red1 Etiqueta *Et; VariableLinguistica *Var; Var=&(Grafo.VarCalculada); Var->autodefinirRecto(3); Et=&Var->Etiquetas.Item(0); Et->Label=wxT("Bajo"); Et=&Var->Etiquetas.Item(1); Et->Label=wxT("Medio"); Et=&Var->Etiquetas.Item(2); Et->Label=wxT("Alto"); Var=&(N1_2->VarCalculada); Var->autodefinirRecto(3); Var->Nombre=wxT("N1_2"); Et=&Var->Etiquetas.Item(0); Et->Label=wxT("Bajo"); Et=&Var->Etiquetas.Item(1); Et->Label=wxT("Medio"); Et=&Var->Etiquetas.Item(2); Et->Label=wxT("Alto"); Var=&(N1_3->VarCalculada); Var->autodefinirRecto(3); Var->Nombre=wxT("N1_3"); Et=&Var->Etiquetas.Item(0); Et->Label=wxT("Bajo"); Et=&Var->Etiquetas.Item(1); Et->Label=wxT("Medio"); Et=&Var->Etiquetas.Item(2); Et->Label=wxT("Alto"); ////////////////////////////////////////////////////////////////////////////// // asignación de los nodos y funciones Funcion *F; float x[10]; Grafo.adicionarNodo(N1_2); Grafo.adicionarNodo(N1_3); x[0]=0.5;x[1]=0.5; F=new CombinacionLineal(x,2,0); Grafo.asignarFuncion(F); } void Estrategia::crearRedLink2() { /** * Implementación de la segunda estrategia de cálculo con links */ // Generalidades // Declaración y construcción de los nodos del árbol NodoCalculo *N2_2,*N2_3; N2_2=new NodoCalculo(); N2_3=new NodoCalculo(); // Definición de Variables Grafo.VarCalculada.Nombre=wxT("N2_1"); // corresponde al nodo superior en la Red1 Etiqueta *Et; VariableLinguistica *Var; Var=&(Grafo.VarCalculada); Var->autodefinirRecto(3); Et=&Var->Etiquetas.Item(0); Et->Label=wxT("Bajo"); Et=&Var->Etiquetas.Item(1); Et->Label=wxT("Medio"); Et=&Var->Etiquetas.Item(2); Et->Label=wxT("Alto"); Var=&(N2_2->VarCalculada); Var->autodefinirRecto(3); Var->Nombre=wxT("N2_2"); Et=&Var->Etiquetas.Item(0); Et->Label=wxT("Bajo"); Et=&Var->Etiquetas.Item(1); Et->Label=wxT("Medio"); Et=&Var->Etiquetas.Item(2); Et->Label=wxT("Alto"); Var=&(N2_3->VarCalculada); Var->autodefinirRecto(3); Var->Nombre=wxT("N2_3"); Et=&Var->Etiquetas.Item(0); Et->Label=wxT("Bajo"); Et=&Var->Etiquetas.Item(1); Et->Label=wxT("Medio"); Et=&Var->Etiquetas.Item(2); Et->Label=wxT("Alto"); ////////////////////////////////////////////////////////////////////////////// // asignación de los nodos y funciones Funcion *F; float x[10]; Grafo.adicionarNodo(N2_2); Grafo.adicionarNodo(N2_3); x[0]=0.5;x[1]=0.5; F=new CombinacionLineal(x,2,0); Grafo.asignarFuncion(F); N2_3->FormaDeCalculo=2; N2_3->EstrategiaCalculo=wxT("Metodología 1"); }
#include <bits/stdc++.h> #include <cassert> #define rep(i, N) for (int i = 0; i < (N); ++i) #define rep2(i, a, b) for (ll i = a; i <= b; ++i) #define rep3(i, a, b) for (ll i = a; i >= b; --i) #define pb push_back #define eb emplace_back #define fi first #define se second #define nl '\n' #define endl '\n' #define all(c) begin(c), end(c) #define ok() puts(ok ? "Yes" : "No"); template <class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template <class T> bool chmin(T &a, const T &b) { if (a > b) { a = b; return true; } return false; } using namespace std; using ll = long long; using vi = vector<int>; using vll = vector<ll>; using vvll = vector<vll>; using ii = pair<int, int>; using vvi = vector<vi>; using vii = vector<ii>; using vs = vector<string>; using P = pair<ll, ll>; using gt = greater<P>; using minq = priority_queue<P, vector<P>, gt>; using vP = vector<P>; template <class T> void takeUnique(vector<T> &v) { auto last = std::unique(v.begin(), v.end()); v.erase(last, v.end()); } template <class T> void print(const initializer_list<T> &il) { for (auto x : il) { cout << x << " "; } cout << "\n"; } inline void priv(vi a) { rep(i, (int)a.size()) printf("%d%c", a[i], i == (int)a.size() - 1 ? '\n' : ' '); } const ll LINF = 1e18L + 1; const int INF = 1e9 + 1; int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; int dxx[] = {0, 1, 1, 1, 0, -1, -1, -1}; int dyy[] = {1, 1, 0, -1, -1, -1, 0, 1}; // clang++ -std=c++11 -stdlib=libc++ int n; string s, x; int dp[200005][8]; int flag[200005][8]; int f(int i, int mod) { print({i, mod}); if (flag[i][mod]) return dp[i][mod]; flag[i][mod] = 1; if (x[i] == 'A') { if (i == 0) { return dp[i][mod] = s[i] == '7' || s[i] == '0'; } int pm = (2 * (s[i] - '0') % 7 + 7) % 7; int res = f(i - 1, pm) and f(i - 1, 0); return dp[i][mod] = res; } else { if (i == 0) { return dp[i][mod] = 1; } int pm = (2 * (s[i] - '0') % 7 + 7) % 7; int res = f(i - 1, pm) or f(i - 1, 0); return dp[i][mod] = res; } } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cin >> n >> s >> x; int res = f(n - 1, 0); if (res) { puts("Takahashi"); } else { puts("Aoki"); } rep(i, n) rep(j, 7) cout << dp[i][j] << nl; return 0; }
/*====================================================================* - Copyright (C) 2001 Leptonica. 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. - - 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 ANY - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *====================================================================*/ /* * tiffiostub.c * * Stubs for tiffio.c functions */ #include "allheaders.h" #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif /* HAVE_CONFIG_H */ /* --------------------------------------------*/ #if !HAVE_LIBTIFF /* defined in environ.h */ /* --------------------------------------------*/ PIX * pixReadTiff(const char *filename, l_int32 n) { return (PIX * )ERROR_PTR("function not present", "pixReadTiff", NULL); } /* ----------------------------------------------------------------------*/ PIX * pixReadStreamTiff(FILE *fp, l_int32 n) { return (PIX * )ERROR_PTR("function not present", "pixReadStreamTiff", NULL); } /* ----------------------------------------------------------------------*/ l_int32 pixWriteTiff(const char *filename, PIX *pix, l_int32 comptype, const char *modestring) { return ERROR_INT("function not present", "pixWriteTiff", 1); } /* ----------------------------------------------------------------------*/ l_int32 pixWriteTiffCustom(const char *filename, PIX *pix, l_int32 comptype, const char *modestring, NUMA *natags, SARRAY *savals, SARRAY *satypes, NUMA *nasizes) { return ERROR_INT("function not present", "pixWriteTiffCustom", 1); } /* ----------------------------------------------------------------------*/ l_int32 pixWriteStreamTiff(FILE *fp, PIX *pix, l_int32 comptype) { return ERROR_INT("function not present", "pixWriteStreamTiff", 1); } /* ----------------------------------------------------------------------*/ PIXA * pixaReadMultipageTiff(const char *filename) { return (PIXA * )ERROR_PTR("function not present", "pixaReadMultipageTiff", NULL); } /* ----------------------------------------------------------------------*/ l_int32 writeMultipageTiff(const char *dirin, const char *substr, const char *fileout) { return ERROR_INT("function not present", "writeMultipageTiff", 1); } /* ----------------------------------------------------------------------*/ l_int32 writeMultipageTiffSA(SARRAY *sa, const char *fileout) { return ERROR_INT("function not present", "writeMultipageTiffSA", 1); } /* ----------------------------------------------------------------------*/ l_int32 fprintTiffInfo(FILE *fpout, const char *tiffile) { return ERROR_INT("function not present", "fprintTiffInfo", 1); } /* ----------------------------------------------------------------------*/ l_int32 tiffGetCount(FILE *fp, l_int32 *pn) { return ERROR_INT("function not present", "tiffGetCount", 1); } /* ----------------------------------------------------------------------*/ l_int32 getTiffResolution(FILE *fp, l_int32 *pxres, l_int32 *pyres) { return ERROR_INT("function not present", "getTiffResolution", 1); } /* ----------------------------------------------------------------------*/ l_int32 readHeaderTiff(const char *filename, l_int32 n, l_int32 *pwidth, l_int32 *pheight, l_int32 *pbps, l_int32 *pspp, l_int32 *pres, l_int32 *pcmap, l_int32 *pformat) { return ERROR_INT("function not present", "readHeaderTiff", 1); } /* ----------------------------------------------------------------------*/ l_int32 freadHeaderTiff(FILE *fp, l_int32 n, l_int32 *pwidth, l_int32 *pheight, l_int32 *pbps, l_int32 *pspp, l_int32 *pres, l_int32 *pcmap, l_int32 *pformat) { return ERROR_INT("function not present", "freadHeaderTiff", 1); } /* ----------------------------------------------------------------------*/ l_int32 readHeaderMemTiff(const l_uint8 *cdata, size_t size, l_int32 n, l_int32 *pwidth, l_int32 *pheight, l_int32 *pbps, l_int32 *pspp, l_int32 *pres, l_int32 *pcmap, l_int32 *pformat) { return ERROR_INT("function not present", "readHeaderMemTiff", 1); } /* ----------------------------------------------------------------------*/ l_int32 findTiffCompression(FILE *fp, l_int32 *pcomptype) { return ERROR_INT("function not present", "findTiffCompression", 1); } /* ----------------------------------------------------------------------*/ l_int32 extractG4DataFromFile(const char *filein, l_uint8 **pdata, size_t *pnbytes, l_int32 *pw, l_int32 *ph, l_int32 *pminisblack) { return ERROR_INT("function not present", "extractG4DataFromFile", 1); } /* ----------------------------------------------------------------------*/ PIX * pixReadMemTiff(const l_uint8 *cdata, size_t size, l_int32 n) { return (PIX *)ERROR_PTR("function not present", "pixReadMemTiff", NULL); } /* ----------------------------------------------------------------------*/ l_int32 pixWriteMemTiff(l_uint8 **pdata, size_t *psize, PIX *pix, l_int32 comptype) { return ERROR_INT("function not present", "pixWriteMemTiff", 1); } /* ----------------------------------------------------------------------*/ l_int32 pixWriteMemTiffCustom(l_uint8 **pdata, size_t *psize, PIX *pix, l_int32 comptype, NUMA *natags, SARRAY *savals, SARRAY *satypes, NUMA *nasizes) { return ERROR_INT("function not present", "pixWriteMemTiffCustom", 1); } /* --------------------------------------------*/ #endif /* !HAVE_LIBTIFF */ /* --------------------------------------------*/
#include "client.h" bool Client::connect() { #if !(defined __linux__) WSADATA WsaData; int err = WSAStartup(0x0101, &WsaData); if (err == SOCKET_ERROR) { return false; exit(0); } #endif sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) return false; server = gethostbyname(syst->host); if (server == NULL) return false; memset((char *)&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; memcpy((char *)&serv_addr.sin_addr.s_addr, (char *)server->h_addr, server->h_length); serv_addr.sin_port = htons(syst->portno); #ifdef __linux__ int flags = fcntl(sockfd, F_GETFL, 0); if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) == -1) { return false; //Ошибка настройки сокета. } #else unsigned long iMode = 1; //1-включить NONBLOCK режим, 0 - выключить if (ioctlsocket(sockfd, FIONBIO, &iMode) != 0) { return false; //Ошибка настройки сокета. } #endif if (::connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) != 0) { tv.tv_sec = timeout; tv.tv_usec = 0; FD_ZERO(&rfds); FD_ZERO(&wfds); FD_SET(sockfd, &wfds); FD_SET(sockfd, &rfds); select(sockfd + 1, &rfds, &wfds, NULL, &tv); if (FD_ISSET(sockfd, &wfds) || FD_ISSET(sockfd, &rfds)) { socklen_t err_len; int error; err_len = sizeof(error); if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &err_len) < 0 || error != 0) { return false; //Ошибка соединения. } } else { return false; } } /* if (!get_data(&(syst->capture_width), 2)) return false; if (!get_data(&(syst->capture_height), 2)) return false; if (!get_data(&(syst->signarea), sizeof(Rect))) return false; if (!get_data(&(syst->linearea), sizeof(Rect))) return false; */ connectState = true; return true; } bool Client::disconnect() { #ifdef __linux__ close(sockfd); #else closesocket(sockfd); #endif } bool Client::get_data(void *dst, size_t size) { size_t i = 0; int bytes = 0; for (i = 0; i < size; i += bytes) { tv.tv_sec = timeout; tv.tv_usec = 0; FD_ZERO(&rfds); FD_SET(sockfd, &rfds); if (select(sockfd + 1, &rfds, NULL, NULL, &tv) <= 0) { //todo: проверка на выход по прерыванию printf("[E]: Connection with server closed! Bad connection.\n"); return false; } else { bytes = recv(sockfd, (char *)dst + i, size - i, 0); } } return true; } bool Client::isConnect() { return connectState; } void client_fnc(System &syst, Client &client) { //Queue<Mat> &iqueue = syst.iqueue; //vector<sign_data> locale; //sign_data sig; dataType tp; uint32_t dataSize = 0; std::vector<cv::uchar> b; //вектор для считывание изображение while (!client.isConnect()) { std::this_thread::sleep_for(std::chrono::milliseconds(30)); } while (true) { //if (syst.getExitState()) break; if (!client.get_data(&tp, sizeof(uint32_t))) break; if (!client.get_data(&dataSize, sizeof(uint32_t))) break; switch (tp) { case Image_t: { b = std::vector<cv::uchar>(dataSize); if (!client.get_data(&b[0], (size_t)dataSize)) goto thread_end; //перейти к завершению потока, если не удалось получить данные syst.setImage(imdecode(b, 1)); b.clear(); break; } case Engine_t: { Engine locale; if (!client.get_data(&locale, (size_t)dataSize)) goto thread_end; //перейти к завершению потока, если не удалось получить данные syst.engine_set(locale); break; } default: { printf("[W]: Unknown data format\n"); char *freebuffer = new char[dataSize]; if (!client.get_data(freebuffer, (size_t)dataSize)) goto thread_end; //перейти к завершению потока, если не удалось получить данные delete[] freebuffer; break; } } } /* * Метка для перехода в конец цикла. * Да, да... Это для goto и за мной уже выехали) */ thread_end: client.disconnect(); if (syst.getExitState()) { syst.setExitState(); } return; }
#include <bits/stdc++.h> using namespace std; int main() { string names[5] = {"Sheldon", "Leonard", "Penny", "Rajesh", "Howard"}; long long int a[29]; a[0] = 5; for(int i=1; i<29; i++) a[i] = a[i-1]+5*pow(2, i); long long int n, ans; cin>>n; if(n<=5) ans = n-1; else { int x = lower_bound(a, a+29, n)-a; ans = (n-a[x-1]-1)/pow(2, x); } cout<<names[ans]<<endl; }
//#include <iostream> //#include <vector> // //int main(void) //{ // std::vector<int> iv(2, 0); // std::cout << "size = " << iv.size() << "\tcapacity = " << iv.capacity() << std::endl; // iv.reserve(14); // // for (int a = 1; a <= 8; a++) { // iv.push_back(a); // std::cout << "size = " << iv.size() << "\tcapacity = " << iv.capacity() << std::endl; // } // iv.shrink_to_fit(); // std::cout << "size = " << iv.size() << "\tcapacity = " << iv.capacity() << std::endl; // iv.resize(7); // std::cout << "size = " << iv.size() << "\tcapacity = " << iv.capacity() << std::endl; // // for (std::vector<int>::iterator it = iv.begin(); it != iv.end(); it++) { // std::cout << *it << std::endl; // } // getchar(); // // return 0; //}
#ifndef __STRAWBERRY_H__ #define __STRAWBERRY_H__ #include "Abstract.h" class Strawberry : public Abstract { protected: virtual std::string bread() override; virtual std::string jam() override; }; #endif // __STRAWBERRY_H__
// This file has been generated by Py++. #ifndef TextUtils_hpp__pyplusplus_wrapper #define TextUtils_hpp__pyplusplus_wrapper void register_TextUtils_class(); #endif//TextUtils_hpp__pyplusplus_wrapper
// @copyright 2017 - 2018 Shaun Ostoic // Distributed under the MIT License. // (See accompanying file LICENSE.md or copy at https://opensource.org/licenses/MIT) #pragma once #include <boost/winapi/basic_types.hpp> #include <boost/config/platform/win32.hpp> #include <distant/support/winapi/basic_types.hpp> #if !defined (BOOST_USE_WINDOWS_H) struct PRIVILEGE_SET; BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ WINAPI PrivilegeCheck( boost::winapi::HANDLE_ ClientToken, ::PRIVILEGE_SET* RequiredPrivileges, boost::winapi::LPBOOL_ pfResult); #if !defined(BOOST_NO_ANSI_APIS) BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ WINAPI LookupPrivilegeDisplayNameA( boost::winapi::LPCSTR_ lpSystemName, boost::winapi::LPCSTR_ lpName, _Out_writes_to_opt_(*cchDisplayName, *cchDisplayName + 1) boost::winapi::LPSTR_ lpDisplayName, boost::winapi::LPDWORD_ cchDisplayName, boost::winapi::LPDWORD_ lpLanguageId); #endif BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ WINAPI LookupPrivilegeDisplayNameW( boost::winapi::LPCWSTR_ lpSystemName, boost::winapi::LPCWSTR_ lpName, _Out_writes_to_opt_(*cchDisplayName, *cchDisplayName + 1) boost::winapi::LPWSTR_ lpDisplayName, boost::winapi::LPDWORD_ cchDisplayName, boost::winapi::LPDWORD_ lpLanguageId); #if !defined(BOOST_NO_ANSI_APIS) BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ WINAPI LookupPrivilegeNameA( boost::winapi::LPCSTR_ lpSystemName, boost::winapi::PLUID_ lpLuid, _Out_writes_to_opt_(*cchDisplayName, *cchDisplayName + 1) boost::winapi::LPSTR_ lpName, boost::winapi::LPDWORD_ cchName); #endif BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ WINAPI LookupPrivilegeNameW( boost::winapi::LPCWSTR_ lpSystemName, boost::winapi::PLUID_ lpLuid, _Out_writes_to_opt_(*cchDisplayName, *cchDisplayName + 1) boost::winapi::LPWSTR_ lpName, boost::winapi::LPDWORD_ cchName); #if !defined(BOOST_NO_ANSI_APIS) BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ WINAPI LookupPrivilegeValueA( boost::winapi::LPCSTR_ lpSystemName, boost::winapi::LPCSTR_ lpName, boost::winapi::PLUID_ lpLuid); #endif BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ WINAPI LookupPrivilegeValueW( boost::winapi::LPCWSTR_ lpSystemName, boost::winapi::LPCWSTR_ lpName, boost::winapi::PLUID_ lpLuid); #endif // !defined BOOST_USE_WINDOWS_H namespace boost::winapi { #if !defined (BOOST_USE_WINDOWS_H) // // Privilege Set - This is defined for a privilege set of one. // If more than one privilege is needed, then this structure // will need to be allocated with more space. // // Note: don't change this structure without fixing the INITIAL_PRIVILEGE_SET // structure (defined in se.h) //// typedef struct _PRIVILEGE_SET_ { DWORD_ PrivilegeCount; DWORD_ Control; LUID_AND_ATTRIBUTES_ Privilege[ANYSIZE_ARRAY_]; } PRIVILEGE_SET_, *PPRIVILEGE_SET_; constexpr boost::winapi::DWORD_ SE_PRIVILEGE_ENABLED_BY_DEFAULT_ = 0x00000001L; constexpr boost::winapi::DWORD_ SE_PRIVILEGE_ENABLED_ = 0x00000002L; constexpr boost::winapi::DWORD_ SE_PRIVILEGE_REMOVED_ = 0X00000004L; constexpr boost::winapi::DWORD_ SE_PRIVILEGE_USED_FOR_ACCESS_ = 0x80000000L; constexpr boost::winapi::DWORD_ SE_PRIVILEGE_VALID_ATTRIBUTES_ = SE_PRIVILEGE_ENABLED_BY_DEFAULT_ | SE_PRIVILEGE_ENABLED_ | SE_PRIVILEGE_REMOVED_ | SE_PRIVILEGE_USED_FOR_ACCESS_; // Privilege Set Control flags constexpr boost::winapi::DWORD_ PRIVILEGE_SET_ALL_NECESSARY_ = 1; // Privilege names constexpr auto SE_CREATE_TOKEN_NAME_ = TEXT("SeCreateTokenPrivilege"); constexpr auto SE_ASSIGNPRIMARYTOKEN_NAME_ = TEXT("SeAssignPrimaryTokenPrivilege"); constexpr auto SE_LOCK_MEMORY_NAME_ = TEXT("SeLockMemoryPrivilege"); constexpr auto SE_INCREASE_QUOTA_NAME_ = TEXT("SeIncreaseQuotaPrivilege"); constexpr auto SE_UNSOLICITED_INPUT_NAME_ = TEXT("SeUnsolicitedInputPrivilege"); constexpr auto SE_MACHINE_ACCOUNT_NAME_ = TEXT("SeMachineAccountPrivilege"); constexpr auto SE_TCB_NAME_ = TEXT("SeTcbPrivilege"); constexpr auto SE_SECURITY_NAME_ = TEXT("SeSecurityPrivilege"); constexpr auto SE_TAKE_OWNERSHIP_NAME_ = TEXT("SeTakeOwnershipPrivilege"); constexpr auto SE_LOAD_DRIVER_NAME_ = TEXT("SeLoadDriverPrivilege"); constexpr auto SE_SYSTEM_PROFILE_NAME_ = TEXT("SeSystemProfilePrivilege"); constexpr auto SE_SYSTEMTIME_NAME_ = TEXT("SeSystemtimePrivilege"); constexpr auto SE_PROF_SINGLE_PROCESS_NAME_ = TEXT("SeProfileSingleProcessPrivilege"); constexpr auto SE_INC_BASE_PRIORITY_NAME_ = TEXT("SeIncreaseBasePriorityPrivilege"); constexpr auto SE_CREATE_PAGEFILE_NAME_ = TEXT("SeCreatePagefilePrivilege"); constexpr auto SE_CREATE_PERMANENT_NAME_ = TEXT("SeCreatePermanentPrivilege"); constexpr auto SE_BACKUP_NAME_ = TEXT("SeBackupPrivilege"); constexpr auto SE_RESTORE_NAME_ = TEXT("SeRestorePrivilege"); constexpr auto SE_SHUTDOWN_NAME_ = TEXT("SeShutdownPrivilege"); constexpr auto SE_DEBUG_NAME_ = TEXT("SeDebugPrivilege"); constexpr auto SE_AUDIT_NAME_ = TEXT("SeAuditPrivilege"); constexpr auto SE_SYSTEM_ENVIRONMENT_NAME_ = TEXT("SeSystemEnvironmentPrivilege"); constexpr auto SE_CHANGE_NOTIFY_NAME_ = TEXT("SeChangeNotifyPrivilege"); constexpr auto SE_REMOTE_SHUTDOWN_NAME_ = TEXT("SeRemoteShutdownPrivilege"); constexpr auto SE_UNDOCK_NAME_ = TEXT("SeUndockPrivilege"); constexpr auto SE_SYNC_AGENT_NAME_ = TEXT("SeSyncAgentPrivilege"); constexpr auto SE_ENABLE_DELEGATION_NAME_ = TEXT("SeEnableDelegationPrivilege"); constexpr auto SE_MANAGE_VOLUME_NAME_ = TEXT("SeManageVolumePrivilege"); constexpr auto SE_IMPERSONATE_NAME_ = TEXT("SeImpersonatePrivilege"); constexpr auto SE_CREATE_GLOBAL_NAME_ = TEXT("SeCreateGlobalPrivilege"); constexpr auto SE_TRUSTED_CREDMAN_ACCESS_NAME_ = TEXT("SeTrustedCredManAccessPrivilege"); constexpr auto SE_RELABEL_NAME_ = TEXT("SeRelabelPrivilege"); constexpr auto SE_INC_WORKING_SET_NAME_ = TEXT("SeIncreaseWorkingSetPrivilege"); constexpr auto SE_TIME_ZONE_NAME_ = TEXT("SeTimeZonePrivilege"); constexpr auto SE_CREATE_SYMBOLIC_LINK_NAME_ = TEXT("SeCreateSymbolicLinkPrivilege"); #else // Privilege names constexpr auto SE_CREATE_TOKEN_NAME_ = SE_CREATE_TOKEN_NAME; constexpr auto SE_ASSIGNPRIMARYTOKEN_NAME_ = SE_ASSIGNPRIMARYTOKEN_NAME; constexpr auto SE_LOCK_MEMORY_NAME_ = SE_LOCK_MEMORY_NAME; constexpr auto SE_INCREASE_QUOTA_NAME_ = SE_INCREASE_QUOTA_NAME; constexpr auto SE_UNSOLICITED_INPUT_NAME_ = SE_UNSOLICITED_INPUT_NAME; constexpr auto SE_MACHINE_ACCOUNT_NAME_ = SE_MACHINE_ACCOUNT_NAME; constexpr auto SE_TCB_NAME_ = SE_TCB_NAME; constexpr auto SE_SECURITY_NAME_ = SE_SECURITY_NAME; constexpr auto SE_TAKE_OWNERSHIP_NAME_ = SE_TAKE_OWNERSHIP_NAME; constexpr auto SE_LOAD_DRIVER_NAME_ = SE_LOAD_DRIVER_NAME; constexpr auto SE_SYSTEM_PROFILE_NAME_ = SE_SYSTEM_PROFILE_NAME; constexpr auto SE_SYSTEMTIME_NAME_ = SE_SYSTEMTIME_NAME; constexpr auto SE_PROF_SINGLE_PROCESS_NAME_ = SE_PROF_SINGLE_PROCESS_NAME; constexpr auto SE_INC_BASE_PRIORITY_NAME_ = SE_INC_BASE_PRIORITY_NAME; constexpr auto SE_CREATE_PAGEFILE_NAME_ = SE_CREATE_PAGEFILE_NAME; constexpr auto SE_CREATE_PERMANENT_NAME_ = SE_CREATE_PERMANENT_NAME; constexpr auto SE_BACKUP_NAME_ = SE_BACKUP_NAME; constexpr auto SE_RESTORE_NAME_ = SE_RESTORE_NAME; constexpr auto SE_SHUTDOWN_NAME_ = SE_SHUTDOWN_NAME; constexpr auto SE_DEBUG_NAME_ = SE_DEBUG_NAME; constexpr auto SE_AUDIT_NAME_ = SE_AUDIT_NAME; constexpr auto SE_SYSTEM_ENVIRONMENT_NAME_ = SE_SYSTEM_ENVIRONMENT_NAME; constexpr auto SE_CHANGE_NOTIFY_NAME_ = SE_CHANGE_NOTIFY_NAME; constexpr auto SE_REMOTE_SHUTDOWN_NAME_ = SE_REMOTE_SHUTDOWN_NAME; constexpr auto SE_UNDOCK_NAME_ = SE_UNDOCK_NAME; constexpr auto SE_SYNC_AGENT_NAME_ = SE_SYNC_AGENT_NAME; constexpr auto SE_ENABLE_DELEGATION_NAME_ = SE_ENABLE_DELEGATION_NAME; constexpr auto SE_MANAGE_VOLUME_NAME_ = SE_MANAGE_VOLUME_NAME; constexpr auto SE_IMPERSONATE_NAME_ = SE_IMPERSONATE_NAME; constexpr auto SE_CREATE_GLOBAL_NAME_ = SE_CREATE_GLOBAL_NAME; constexpr auto SE_TRUSTED_CREDMAN_ACCESS_NAME_ = SE_TRUSTED_CREDMAN_ACCESS_NAME; constexpr auto SE_RELABEL_NAME_ = SE_RELABEL_NAME; constexpr auto SE_INC_WORKING_SET_NAME_ = SE_INC_WORKING_SET_NAME; constexpr auto SE_TIME_ZONE_NAME_ = SE_TIME_ZONE_NAME; constexpr auto SE_CREATE_SYMBOLIC_LINK_NAME_ = SE_CREATE_SYMBOLIC_LINK_NAME; //using PRIVILEGE_SET_ = ::PRIVILEGE_SET; //using PPRIVILEGE_SET_ = ::PPRIVILEGE_SET; constexpr DWORD_ SE_PRIVILEGE_ENABLED_BY_DEFAULT_ = SE_PRIVILEGE_ENABLED_BY_DEFAULT; constexpr DWORD_ SE_PRIVILEGE_ENABLED_ = SE_PRIVILEGE_ENABLED; constexpr DWORD_ SE_PRIVILEGE_REMOVED_ = SE_PRIVILEGE_REMOVED; constexpr DWORD_ SE_PRIVILEGE_USED_FOR_ACCESS_ = SE_PRIVILEGE_USED_FOR_ACCESS; constexpr DWORD_ SE_PRIVILEGE_VALID_ATTRIBUTES_ = SE_PRIVILEGE_VALID_ATTRIBUTES; // Privilege Set Control flags constexpr DWORD_ PRIVILEGE_SET_ALL_NECESSARY_ = PRIVILEGE_SET_ALL_NECESSARY; #endif // !defined BOOST_USE_WINDOWS_H BOOST_FORCEINLINE boost::winapi::BOOL_ privilege_check( boost::winapi::HANDLE_ ClientToken, boost::winapi::PRIVILEGE_SET_* RequiredPrivileges, boost::winapi::LPBOOL_ pfResult) { return ::PrivilegeCheck(ClientToken, reinterpret_cast<PRIVILEGE_SET*>(RequiredPrivileges), pfResult); } #if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WINXP #if !defined(BOOST_NO_ANSI_APIS) using ::LookupPrivilegeDisplayNameA; #endif using ::LookupPrivilegeDisplayNameW; #if !defined(BOOST_NO_ANSI_APIS) BOOST_FORCEINLINE boost::winapi::DWORD_ lookup_privilege_name( boost::winapi::LPCSTR_ lpSystemName, boost::winapi::PLUID_ lpLuid, _Out_writes_to_opt_(*cchDisplayName, *cchDisplayName + 1) boost::winapi::LPSTR_ lpName, boost::winapi::LPDWORD_ cchName) { return ::LookupPrivilegeNameA( lpSystemName, reinterpret_cast<LUID_*>(lpLuid), lpName, cchName); } #endif BOOST_FORCEINLINE boost::winapi::DWORD_ lookup_privilege_name( boost::winapi::LPCWSTR_ lpSystemName, boost::winapi::PLUID_ lpLuid, _Out_writes_to_opt_(*cchDisplayName, *cchDisplayName + 1) boost::winapi::LPWSTR_ lpName, boost::winapi::LPDWORD_ cchName) { return ::LookupPrivilegeNameW( lpSystemName, reinterpret_cast<LUID_*>(lpLuid), lpName, cchName); } #if !defined(BOOST_NO_ANSI_APIS) BOOST_FORCEINLINE boost::winapi::DWORD_ lookup_privilege_value( boost::winapi::LPCSTR_ lpSystemName, boost::winapi::LPCSTR_ lpName, boost::winapi::PLUID_ lpLuid) { return ::LookupPrivilegeValueA( lpSystemName, lpName, reinterpret_cast<LUID_*>(lpLuid)); } #endif BOOST_FORCEINLINE boost::winapi::DWORD_ lookup_privilege_value( boost::winapi::LPCWSTR_ lpSystemName, boost::winapi::LPCWSTR_ lpName, boost::winapi::PLUID_ lpLuid) { return ::LookupPrivilegeValueW( lpSystemName, lpName, reinterpret_cast<LUID_*>(lpLuid)); } #endif } // end namespace boost::winapi
#include<iostream> #include<vector> #include<algorithm> #include<string> #include<map> #include<math.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n,x,s; cin>>n>>x>>s; int u,v; while(s--) { cin>>u>>v; if(x==u) x = v; else if(x==v) x = u; // cout<<"Position is "<<x<<endl; } cout<<x<<endl; } return 0; }
#include "ThinLensCamera.h" #include "tinyxml2.h" #include "Base/ParseHelper.h" #include "Film/Film.h" #include "Base/PCH.h" ThinLensCamera::ThinLensCamera() : Camera() , mLensRadius( 1.0 ) , mLensFocus( 1.0 ) { } ThinLensCamera::~ThinLensCamera() { } void ThinLensCamera::SetLensFocus( float LensFocus ) { mLensFocus = LensFocus; } void ThinLensCamera::SetLensRadius( float LensRadius ) { mLensRadius = LensRadius; } void ThinLensCamera::Deserialization( tinyxml2::XMLElement* RootElement ) { tinyxml2::XMLElement* pElement = nullptr; ParseVector( RootElement->FirstChildElement( "Position" )->GetText() , &mViewPosition[0] ); ParseVector( RootElement->FirstChildElement( "Target" )->GetText() , &mViewTarget[0] ); RootElement->FirstChildElement( "LensFocus" )->QueryFloatText( &mLensFocus ); pElement = RootElement->FirstChildElement( "LensRadius" ); if ( pElement ) { pElement->QueryFloatText( &mLensRadius ); } else { mLensRadius = 1.0; } pElement = RootElement->FirstChildElement( "ExposureTime" ); if ( pElement ) { pElement->QueryFloatText( &mExposureTime ); } else { mExposureTime = 0.0; } pElement = RootElement->FirstChildElement( "Fovy" ); if ( pElement ) { pElement->QueryFloatText( &mFovy ); } else { mFovy = 45.0; } if ( RootElement->FirstChildElement( "NearPlane" ) ) { RootElement->FirstChildElement( "NearPlane" )->QueryFloatText( &mNearPlane ); } else { mNearPlane = 0.0; } } void ThinLensCamera::Serialization( tinyxml2::XMLDocument& xmlDoc , tinyxml2::XMLElement* pRootElement ) { pRootElement->SetAttribute( "type" , GetName() ); { char* pText = new char[50]; sprintf( pText , "%f,%f,%f" , mViewPosition.x , mViewPosition.y , mViewPosition.z ); tinyxml2::XMLElement* pEyeElement = xmlDoc.NewElement( "Position" ); pEyeElement->SetText( pText ); pRootElement->InsertEndChild( pEyeElement ); SAFE_DELETE_ARRAY( pText ); } { char* pText = new char[50]; sprintf( pText , "%f,%f,%f" , mViewTarget.x , mViewTarget.y , mViewTarget.z ); tinyxml2::XMLElement* pTargetElement = xmlDoc.NewElement( "Target" ); pTargetElement->SetText( pText ); pRootElement->InsertEndChild( pTargetElement ); SAFE_DELETE_ARRAY( pText ); } { tinyxml2::XMLElement* pLensFocusElement = xmlDoc.NewElement( "LensFocus" ); pLensFocusElement->SetText( mLensFocus ); pRootElement->InsertEndChild( pLensFocusElement ); } { tinyxml2::XMLElement* pLensRadiusElement = xmlDoc.NewElement( "LensRadius" ); pLensRadiusElement->SetText( mLensRadius ); pRootElement->InsertEndChild( pLensRadiusElement ); } { tinyxml2::XMLElement* pExposureTimeElement = xmlDoc.NewElement( "ExposureTime" ); pExposureTimeElement->SetText( mExposureTime ); pRootElement->InsertEndChild( pExposureTimeElement ); } { tinyxml2::XMLElement* pFovyElement = xmlDoc.NewElement( "Fovy" ); pFovyElement->SetText( mFovy ); pRootElement->InsertEndChild( pFovyElement ); } { tinyxml2::XMLElement* pNearPlaneElement = xmlDoc.NewElement( "NearPlane" ); pNearPlaneElement->SetText( mNearPlane ); pRootElement->InsertEndChild( pNearPlaneElement ); } { tinyxml2::XMLElement* pFirstElement = xmlDoc.FirstChildElement(); tinyxml2::XMLElement* pFilmElement = xmlDoc.NewElement( "Film" ); pFirstElement->InsertEndChild( pFilmElement ); mFilmPtr->Serialization( xmlDoc , pFilmElement ); } }
#ifndef I2CSOFTWAREBUS_H #define I2CSOFTWAREBUS_H #include "I2CBuffer.h" #include "I2CGpioBus.h" class I2CGpioSoftwareBus : public I2CGpioBus { int _address; int _sdaPin; int _sclPin; int _baudRate; I2CBuffer _receiveBuffer; I2CBuffer _sendBuffer; public: I2CGpioSoftwareBus(int address, int sdaPin, int sclPin, int baudRate, int receiveBufferSize = 1024, int sendBufferSize = 1024); bool Initialize(); void Close(); // I2CBus interface public: Status Send(byte value) override; Status Send(byte cmd, byte value) override; Status Send(byte cmd, byte* data, int dataLen) override; Status Send(byte cmd, word value) override; Status Receive(byte& value) override; Status Receive(byte cmd, byte& value) override; Status Receive(byte cmd, byte* data, int dataLen) override; Status Receive(byte cmd, word& value) override; private: Status Transmit(int readCount = 0); void Prepare(); }; #endif //I2CSOFTWAREBUS_H
#include "../include/nbody/Integrate.h" #include "../include/nbody/System.h" #include "gtest/gtest.h" TEST(TestExpectFalse, Positive) { EXPECT_FALSE(0 > 1); }
/*************************************************************************** Copyright (c) 2020 Philip Fortier 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. ***************************************************************************/ // EditViewChildFrame.cpp : implementation file // #include "stdafx.h" #include "AppState.h" #include "ViewChildFrame.h" #include "RasterView.h" #include "ViewCelChooser.h" #include "ViewCelListBox.h" // CEditViewChildFrame IMPLEMENT_DYNCREATE(CEditViewChildFrame, CMDITabChildWnd) CEditViewChildFrame::CEditViewChildFrame() : _splitterCreated(false), _pViewMainView(nullptr), m_wndSplitter(true), m_wndSplitterLeft(false) { } CEditViewChildFrame::~CEditViewChildFrame() { } BEGIN_MESSAGE_MAP(CEditViewChildFrame, CMDITabChildWnd) ON_WM_CREATE() ON_WM_SIZE() END_MESSAGE_MAP() void CEditViewChildFrame::HookUpNonViews(CDocument *pDoc) { } int CEditViewChildFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (__super::OnCreate(lpCreateStruct) == -1) return -1; return 0; } void CEditViewChildFrame::OnSize(UINT nType, int cx, int cy) { __super::OnSize(nType, cx, cy); CRect rect; GetClientRect(&rect); if (_splitterCreated) { m_wndSplitter.SetSizes(); m_wndSplitterLeft.SetSizes(); m_wndSplitter.RecalcLayout(); m_wndSplitterLeft.RecalcLayout(); } } BOOL CEditViewChildFrame::OnCreateClient(LPCREATESTRUCT /*lpcs*/, CCreateContext* pContext) { // This is the code for a static splitter. CRect cr; GetClientRect(&cr); int widthUnit = cr.Width() / 5; CSize paneSize; int rc; m_wndSplitter.CreateStatic(this, 1, 2); rc = m_wndSplitterLeft.CreateStatic(&m_wndSplitter, 2, 1, WS_CHILD | WS_VISIBLE | WS_BORDER, m_wndSplitter.IdFromRowCol(0, 0)); if (rc == FALSE) { return rc; } int heightUnit = cr.Height() / 3; paneSize.SetSize(widthUnit * 3, heightUnit * 2); rc = m_wndSplitterLeft.CreateView(0, 0, RUNTIME_CLASS(CRasterView), paneSize, pContext); if (rc == FALSE) { return rc; } _pViewMainView = (CRasterView*)m_wndSplitterLeft.GetPane(0, 0); paneSize.SetSize(widthUnit * 3, heightUnit * 1); rc = m_wndSplitterLeft.CreateView(1, 0, RUNTIME_CLASS(ViewCelListBox), paneSize, pContext); ViewCelListBox *celListBox = (ViewCelListBox*)m_wndSplitterLeft.GetPane(1, 0); celListBox->SetHorizontal(true); if (rc == FALSE) { return rc; } paneSize.SetSize(widthUnit * 2, cr.Height()); rc = m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(ViewCelListBox), paneSize, pContext); celListBox = (ViewCelListBox*)m_wndSplitter.GetPane(0, 1); celListBox->SetHorizontal(false); m_wndSplitter.SetColumnInfo(0, widthUnit * 3, 5); m_wndSplitter.SetColumnInfo(1, widthUnit * 2, 5); m_wndSplitter.Initialize(widthUnit * 3, widthUnit * 2); m_wndSplitterLeft.SetRowInfo(0, heightUnit * 2, 5); m_wndSplitterLeft.SetRowInfo(1, heightUnit * 1, 5); m_wndSplitterLeft.Initialize(heightUnit * 2, heightUnit * 1); m_wndSplitter.RecalcLayout(); m_wndSplitterLeft.RecalcLayout(); _splitterCreated = true; return rc; } BOOL CEditViewChildFrame::OnCmdMsg(UINT nID, int nCode, void *pExtra, AFX_CMDHANDLERINFO *pHandlerInfo) { BOOL fRet = __super::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo); if (!fRet) { // If unhandled, give it the main (even if it was non-active). // NOTE: if it was active, it was already asked to handle it above. // We could optimize for that case here, if desired. if (_pViewMainView) { fRet = _pViewMainView->OnCmdMsg(nID, nCode, pExtra, pHandlerInfo); } if (!fRet) { // Give to CommandType view? } } return fRet; } // CEditViewChildFrame message handlers void CRatioSplitter::StopTracking(BOOL bAccept) { __super::StopTracking(bAccept); // We should be laid out by now. int cxMin; if (_hasColumns) { GetColumnInfo(0, _first, cxMin); GetColumnInfo(1, _second, cxMin); } else { GetRowInfo(0, _first, cxMin); GetRowInfo(1, _second, cxMin); } } void CRatioSplitter::Initialize(int first, int second) { _first = first; _second = second; } void CRatioSplitter::SetSizes() { CRect rcInside; GetInsideRect(rcInside); if (_hasColumns) { int width = rcInside.Width(); int total = _first + _second; int leftHeight = _first * width / total; int rightHeight = width - leftHeight; SetColumnInfo(0, leftHeight, 5); SetColumnInfo(1, rightHeight, 5); } else { int height = rcInside.Height(); int total = _first + _second; int upperHeight = _first * height / total; int lowerHeight = height - upperHeight; SetRowInfo(0, upperHeight, 5); SetRowInfo(1, lowerHeight, 5); } }
class Solution { public: int maxProfit(vector<int>& prices) { if (prices.empty()) { return 0; } int n = prices.size(); // f[i][0]: 手上持有股票的最大收益 // f[i][1]: 手上不持有股票,并且处于冷冻期中的累计最大收益 // f[i][2]: 手上不持有股票,并且不在冷冻期中的累计最大收益 vector<vector<int>> f(n, vector<int>(3)); f[0][0] = -prices[0]; for (int i = 1; i < n; ++i) { f[i][0] = max(f[i - 1][0], f[i - 1][2] - prices[i]); f[i][1] = f[i - 1][0] + prices[i]; f[i][2] = max(f[i - 1][1], f[i - 1][2]); } return max(f[n - 1][1], f[n - 1][2]); } };
#ifndef _System_h_ #define _System_h_ class System{ public: static void startSystem(); static void stopSystem(); static void interrupt timer(...); }; #endif
#include "MyQPainter.h"
#include <bits/stdc++.h> using namespace std; class Solution { public: int findDuplicate(vector<int> &nums) { vector<bool> seen(nums.size(), false); int i = 0, j = nums.size() - 1; while (i <= j) { if (seen[nums[i] - 1]) return nums[i]; else seen[nums[i] - 1] = true; i++; if (seen[nums[j] - 1]) return nums[j]; else seen[nums[j] - 1] = true; j--; } return -1; } };
#include <OneWire.h> #include <Time.h> #include <Wire.h> #include <SeeedOLED.h> // OneWire DS18S20, DS18B20, DS1822 Temperature Example // // http://www.pjrc.com/teensy/td_libs_OneWire.html // // The DallasTemperature library can do all this work for you! // http://milesburton.com/Dallas_Temperature_Control_Library #define TIME_HEADER "T" // Header tag for serial time sync message #define TIME_REQUEST 7 // ASCII bell character requests a time sync message OneWire ds(2); // on pin 10 (a 4.7K resistor is necessary) void setup(void) { Wire.begin(); SeeedOled.init(); //initialze SEEED OLED display DDRB|=0x21; PORTB |= 0x21; SeeedOled.clearDisplay(); //clear the screen and set start position to top left corner SeeedOled.setNormalDisplay(); //Set display to normal mode (i.e non-inverse mode) SeeedOled.setPageMode(); //Set addressing mode to Page Mode SeeedOled.setTextXY(0,0); SeeedOled.putString("iButton Reader"); //SeeedOled.setTextXY(i,0); //Set the cursor to Xth Page, Yth Column //SeeedOled.putString("0123456789ABCDEF"); Serial.begin(9600); //printMenu(); //Serial.printKeyboard.begin(); } void loop() { long lonTime = 0; String a; char b[16]; lonTime = readTime(); if (lonTime != 0) { SeeedOled.setTextXY(1,0); SeeedOled.putNumber(lonTime); setTime(lonTime - 18000); } if (timeStatus() == timeSet) { digitalWrite(13, HIGH); // LED on if synced SeeedOled.setTextXY(3,0); a = readSystemTime(); a.toCharArray(b, 16); SeeedOled.putString(b); } else { digitalWrite(13, LOW); // LED off if needs refresh } } void printMenu() { Serial.println(); Serial.println(F("DS1904 iButton Menu")); Serial.println(F("=====================================")); Serial.println(F("\t r) Read Time from iButton")); Serial.println(F("\t w) Write Time to iButton")); Serial.println(F("\t z) Read System time")); Serial.println(F("\t x) Write System time (followed immediately by time_t integer)")); Serial.println(F("\t h) Print help menu")); Serial.println(); } long readTime() { byte i; byte present = 0; byte type_s; byte data[12]; byte addr[8]; float celsius, fahrenheit; long timestamp = 0; String arduinoTime; if ( !ds.search(addr)) { //Serial.println("No more addresses."); //Serial.println(); ds.reset_search(); delay(250); return 0; } //Serial.print("ROM ="); for( i = 0; i < 8; i++) { //Serial.write(' '); if (addr[i] < 10) { //Serial.print('0'); //Serial.print(addr[i],HEX); } else { //Serial.print(addr[i], HEX); } } /* if (OneWire::crc8(addr, 7) != addr[7]) { Serial.println("CRC is not valid!"); return; } */ //Serial.println(); // the first ROM byte indicates which chip switch (addr[0]) { case 0x24: //Serial.println(" Chip = DS1904"); break; default: //Serial.println("Device unknown."); return 0; } ds.reset(); ds.select(addr); ds.write(0x66); // 0x66=Read; 0x99=Write delay(20); for ( i = 0; i < 5; i++) { // we need 5 bytes data[i] = ds.read(); //Serial.print(data[i], HEX); //Serial.print(" "); } //Serial.println(); timestamp = convertRawDS1904(&data[0]); //setArduinoTime(timestamp); //arduinoTime = getArduinoTime(); Serial.println(timestamp); return timestamp; //setDS1904(timestamp, &data[0]); delay(1000); } void setArduinoTime(long time_stamp) { setTime(time_stamp); } String getArduinoTime() { String strTime; strTime = String(month()) + String("/") + String(day()) + String("/") + String(year()) + String(" ") + String(hour()) + String(":") + String(minute()) + String(":") + String(second()); return strTime; /* Serial.print(month()); Serial.print("/"); Serial.print(day()); Serial.print("/"); Serial.print(year()); Serial.print(" "); Serial.print(hour()); printDigits(minute()); printDigits(second()); Serial.println(); */ } long convertRawDS1904(byte *d) { long a, b; a = d[4]; a = a << 24; b = d[3]; b = b << 16; a = a | b; b = d[2]; b = b << 8; a = a | b; a = a | d[1]; return a; //return (d[4] * 16777216) + (d[3] * 65536) + (d[2] * 256) + d[1]; } void writeTime() { byte i; long a; byte b; byte present = 0; byte type_s; byte data[12]; byte addr[8]; long timeStamp = 0; String arduinoTime; if ( !ds.search(addr)) { ds.reset_search(); Serial.println("Unable to find DS1904"); delay(2000); return; } for( i = 0; i < 8; i++) { if (addr[i] < 10) { //Serial.print('0'); //Serial.print(addr[i],HEX); } else { //Serial.print(addr[i], HEX); } } /* if (OneWire::crc8(addr, 7) != addr[7]) { //Serial.println("CRC is not valid!"); return; } */ switch (addr[0]) { case 0x24: Serial.println(" Chip = DS1904"); break; default: Serial.println("Device unknown."); return; } timeStamp = now(); data[0] = 0x0C; //Set control byte data[1] = timeStamp & 0xFF; a = timeStamp << 16; data[2] = a >> 24; a = timeStamp << 8; data[3] = a >> 24; data[4] = timeStamp >> 24; //Now write to the DS1904... ds.reset(); ds.select(addr); ds.write(0x99); // 0x66=Read; 0x99=Write delay(20); // maybe 750ms is enough, maybe not for (i = 0;i < 5; i++) { ds.write(data[i]); } ds.reset(); Serial.println("Set DS1904"); delay(2000); } /* void setDS1904(long timestamp, byte *d) { long a; byte b; d[0] = 0x0C; //Set control byte d[1] = timestamp & 0xFF; //LSB, DD a = timestamp << 16; //LShift 2 Bytes, CC DD 00 00 d[2] = a >> 24; // RShift 3 Bytes 00 00 00 CC a = timestamp << 8; //Lshift 1 Byte BB CC DD 00 d[3] = a >> 24; // RShift 3 Bytes 00 00 00 BB d[4] = timestamp >> 24; //RShift 3 Bytes 00 00 00 AA } */ void printDigits(int digits){ // utility function for digital clock display: prints preceding colon and leading 0 Serial.print(":"); if(digits < 10) Serial.print('0'); Serial.print(digits); } void writeSystemTime() { unsigned long pctime; const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 Serial.println("Setting time..."); for (int i; i < 20000; i++) { //Do nothing... } pctime = Serial.parseInt(); if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013) setTime(pctime); // Sync Arduino clock to the time received on the serial port } } String readSystemTime() { String a; a = getArduinoTime(); //Serial.println(a); return a; } time_t requestSync() { Serial.write(TIME_REQUEST); return 0; // the time will be sent later in response to serial mesg }
/* * SPDX-FileCopyrightText: (C) 2014-2022 Daniel Nicoletti <dantti12@gmail.com> * SPDX-License-Identifier: BSD-3-Clause */ #ifndef ROLEACL_H #define ROLEACL_H #include <Cutelyst/component.h> #include <Cutelyst/componentfactory.h> #include <Cutelyst/context.h> #include <Cutelyst/cutelyst_global.h> #include <QtCore/QVariantHash> namespace Cutelyst { class RoleACLPrivate; class CUTELYST_PLUGIN_ACTION_ROLEACL_EXPORT RoleACL final : public Component { Q_OBJECT Q_DECLARE_PRIVATE(RoleACL) public: /** * Constructs a new role ACL object with the given parent. */ explicit RoleACL(QObject *parent = nullptr); /** * Reimplemented from Component::modifiers(). */ virtual Modifiers modifiers() const override; /** * Reimplemented from Component::init(). */ virtual bool init(Application *application, const QVariantHash &args) override; /** * Reimplemented from Component::aroundExecute(). */ virtual bool aroundExecute(Context *c, QStack<Component *> stack) override; /** * Returns true if the action can be visited by the context c. */ bool canVisit(Context *c) const; protected: /** * Reimplemented from Component::dispatcherReady(). */ virtual bool dispatcherReady(const Dispatcher *dispatcher, Controller *controller) override; }; class RoleACLFactory final : public QObject , public ComponentFactory { Q_OBJECT Q_PLUGIN_METADATA(IID "org.cutelyst.ComponentFactory" FILE "metadata.json") Q_INTERFACES(Cutelyst::ComponentFactory) public: virtual Component *createComponent(QObject *parent) override { return new RoleACL(parent); } }; } // namespace Cutelyst #endif // ROLEACL_H
#include "obstruction-map.h" ObstructionMap::ObstructionMap(int size_x, int size_y) : Grid<ObstructionType>(size_x, size_y) { for (int x = 0; x < size_x; x++) for (int y = 0; y < size_y; y++) at(x, y) = OT_EMPTY; } bool ObstructionMap::isObstructed(Position position) { return at(position) == OT_OBSTRUCTED; } bool ObstructionMap::isConsidered(Position position) { return at(position) == OT_CONSIDERED; } bool ObstructionMap::isOpen(Position position) { return at(position) == OT_EMPTY; }
// Sorting techniques #include <iostream> using namespace std; // Swapping variables int swap(int *a , int *b){ int temp ; temp = *a ; *a = *b ; *b = temp ; return 0 ; } // Bubble sort // 1) Time complexity worst O(n2) // 2) Time complexity best O(n) // 3) We can make this sorting technique adaptive using a variable flag // 4) Bubble sort is stable int bubble_sort (int Arr[] , int n ){ for (int i = 0; i<n-1 ; i++){ int flag = 0; for (int j = 0; j<n-1-i ; j++){ if (Arr[j]>Arr[j+1]){ flag = 1 ; swap(Arr[j],Arr[j+1]); } } if (flag == 0 ){ break ; } } return 0 ; } // Insertion sort // 1) Time complexity worst O(n2) // 2) Time complexity best O(n) // 3) Insertion sort is adaptive by nature // 4) Insertion sort is stable int insertion_sort(int Arr [] , int n ){ for (int i = 1 ; i<n ; i++){ int x = Arr[i]; int j = i-1; while (j>-1 && Arr[j]>x){ Arr[j+1] = Arr[j]; j--; } Arr[j+1] = x; } return 0 ; } // Selection sort // 1) Time complexity worst O (n2) // 2) Time complexity best O(n2) // 3) It is not adaptive by nature // 4) It is not stable int selection_sort(int Arr[] , int n ){ for (int i =0 ; i<n ; i++){ int j = i , k =i; for (j; j<n ; j++){ if(Arr[j] < Arr[k] ){ k = j; } } swap(Arr[k] , Arr[i]); } return 0 ; } // Merge sort // Merging function void merge(int A[],int l,int mid,int h) { int i=l,j=mid+1,k=l; int B[100]; while(i<=mid && j<=h) { if(A[i]<A[j]) B[k++]=A[i++]; else B[k++]=A[j++]; } for(;i<=mid;i++) B[k++]=A[i]; for(;j<=h;j++) B[k++]=A[j]; for(i=l;i<=h;i++) A[i]=B[i]; } // Merge sort main function void IMergeSort(int A[],int n) { int p,l,h,mid,i; for(p=2;p<=n;p=p*2) { for(i=0;i+p-1<n;i=i+p) { l=i; h=i+p-1; mid=(l+h)/2; merge(A,l,mid,h); } if(n-i>p/2) { l = i; h = i+p-1; mid = (l+h)/2; merge(A, l, mid, n-1); } } if(p/2<n) { merge(A,0,p/2-1,n-1); } } // Count Sort // The best time complexity of the sort is O(n) // The worst time complexity of the sort is O(n) // It is not adaptive // It is stable sort int count_sort(int Arr[] , int n ){ int max =0 ; // Finding the maximum element for (int i = 0 ; i < n ; i++){ if (Arr[i] > max ){ max = Arr[i]; } } // Creating a new array of size max int c[max+1]; for (int i=0 ; i<max +1 ; i++){ c[i] = 0 ; } // Initializing that array with values for (int i =0 ; i<n ; i++){ c[Arr[i]] ++ ; } //Loop for sorting the array int i = 0 , j =0 ; while (i < max+1 ){ if (c[i] > 0 ){ Arr[j++] = i ; c[i]--; } else { i++; } } return 0 ; } // Class for bin sort class node { private : int data ; node * p; }; // Insertion function for insertion in a linked list int insert(){ } int bin_sort (int Arr[] , int n ){ int max = 0 ; for (int i = 0 ; i < n ; i++){ if (Arr[i] > max ){ max = Arr[i]; } } node **c ; c = new node *[max+1] ; for (int i = 0 ; i < max +1 ; i++){ c[i] = NULL; } for (int i = 0 ; i< n ; i++){ new node ; } } void merge(int A[],int l,int mid,int h, int n ) { int i=l,j=mid+1,k=l; int B[n]; while(i<=mid && j<=h) { if(A[i]<A[j]) B[k++]=A[i++]; else B[k++]=A[j++]; } for(;i<=mid;i++) B[k++]=A[i]; for(;j<=h;j++) B[k++]=A[j]; for(i=l;i<=h;i++) A[i]=B[i]; for (int i = 0 ; i< n ; i++){ cout<<B[i]<<endl ; } } int main() { int Arr[8] = {1,5,3,11,2,6,6,10}; int n =8 ; cout<<"Array before sorting " ; for (int i = 0 ; i < n ; i++){ cout<<Arr[i]<<" "; } cout<<endl; IMergeSort(Arr,8); cout<<"Array after sorting "; for (int i = 0 ; i < n ; i++){ cout<<Arr[i]<<" "; } return 0; }
/* * The IzPack Launcher * http://izpack.org/ * http://izpack.codehaus.org/ * * Copyright (c) 2004 - 2008 Julien Ponge - All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "resolve-dialog.h" ResolveDialog::ResolveDialog(QWidget* parent) : QDialog(parent) { ui.setupUi(this); connect(ui.okButton, SIGNAL(clicked()), this, SLOT(accept())); connect(ui.quitButton, SIGNAL(clicked()), this, SLOT(reject())); } ResolveChoice ResolveDialog::getResolveChoice() { if (ui.manualRadioButton->isChecked()) { return MANUAL; } else if (ui.providedRadioButton->isChecked()) { return PROVIDED; } else { return DOWNLOAD; } }
/******************************************************************************** ** Form generated from reading UI file 'gotocell.ui' ** ** Created by: Qt User Interface Compiler version 5.11.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_GOTOCELL_H #define UI_GOTOCELL_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QDialog> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_GoToCellDialog { public: QWidget *widget; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout; QLabel *label; QLineEdit *lineEdit; QHBoxLayout *horizontalLayout_2; QSpacerItem *horizontalSpacer; QPushButton *OKButton; QPushButton *CancelButton; void setupUi(QDialog *GoToCellDialog) { if (GoToCellDialog->objectName().isEmpty()) GoToCellDialog->setObjectName(QStringLiteral("GoToCellDialog")); GoToCellDialog->resize(297, 89); widget = new QWidget(GoToCellDialog); widget->setObjectName(QStringLiteral("widget")); widget->setGeometry(QRect(10, 10, 276, 70)); verticalLayout = new QVBoxLayout(widget); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); label = new QLabel(widget); label->setObjectName(QStringLiteral("label")); horizontalLayout->addWidget(label); lineEdit = new QLineEdit(widget); lineEdit->setObjectName(QStringLiteral("lineEdit")); horizontalLayout->addWidget(lineEdit); verticalLayout->addLayout(horizontalLayout); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_2->addItem(horizontalSpacer); OKButton = new QPushButton(widget); OKButton->setObjectName(QStringLiteral("OKButton")); OKButton->setEnabled(false); horizontalLayout_2->addWidget(OKButton); CancelButton = new QPushButton(widget); CancelButton->setObjectName(QStringLiteral("CancelButton")); horizontalLayout_2->addWidget(CancelButton); verticalLayout->addLayout(horizontalLayout_2); #ifndef QT_NO_SHORTCUT label->setBuddy(lineEdit); #endif // QT_NO_SHORTCUT retranslateUi(GoToCellDialog); OKButton->setDefault(true); QMetaObject::connectSlotsByName(GoToCellDialog); } // setupUi void retranslateUi(QDialog *GoToCellDialog) { GoToCellDialog->setWindowTitle(QApplication::translate("GoToCellDialog", "Go to Cell", nullptr)); label->setText(QApplication::translate("GoToCellDialog", "&Cell Location:", nullptr)); OKButton->setText(QApplication::translate("GoToCellDialog", "OK", nullptr)); CancelButton->setText(QApplication::translate("GoToCellDialog", "Cancel", nullptr)); } // retranslateUi }; namespace Ui { class GoToCellDialog: public Ui_GoToCellDialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_GOTOCELL_H
#include "Game.hpp" #include "Unit.hpp" Game::Game() {} //Return 0 for no collision, 1 for touching sideways, 2 for jumping on other int Game::collisionCheck(sf::Sprite s1, sf::Sprite s2) { sf::FloatRect r1 = s1.getGlobalBounds(); sf::FloatRect r2 = s2.getGlobalBounds(); if (!r1.intersects(r2)) { return 0; } float s1l = r1.left; float s1r = r1.left + r1.width; float s1t = r1.top; float s1b = r1.top + r1.height; float s2l = r2.left; float s2r = r2.left + r2.width; float s2t = r2.top; float s2b = r2.top + r2.height; float xDiff = s1.getPosition().x - s2.getPosition().x; std::cout << "s1 x: " << s1.getPosition().x << std::endl; std::cout << "s2 x: " << s2.getPosition().x << std::endl; if (xDiff < 10 && xDiff > -10) return 2; else return 1; } void Game::run() { //create window sf::RenderWindow window(sf::VideoMode(1400, 900), "Buper Bario"); //create view sf::View view(sf::Vector2f(600, 500), sf::Vector2f(1200, 800)); //-1 = Nothing ; //#0 = left; #1 = mid; #2 = right ; #3 = steepslope //0# = icetop; 1# = icemid; 2# = icebottom || 3# = grasstop ; 4# = grassmid ; 5# = grassbottom || etc const int level[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 30, 31, 31, 31, 31, 31, 31, 32, -1, -1, 00, 03, -1, -1, -1, -1, 40, 41, 41, 41, 41, 41, 41, 42, -1, -1, 10, 13, 01, 01, 01, 02, 40, 41, 41, 41, 41, 41, 41, 42, -1, -1, 10, 11, 11, 11, 11, 12, 40, 41, 41, 41, 41, 41, 41, 42, -1, -1, 10, 11, 11, 11, 11, 12, 50, 51, 51, 51, 51, 51, 51, 52, -1, -1, 20, 21, 21, 21, 21, 22, }; TileMap map; if(!map.load("tiles.png", sf::Vector2u(16, 16), level, 16, 28)) return; //vector for bario walking animations sf::Texture bariot; bariot.loadFromFile("smallbario.png"); //for animations /* int bstate = 0; int delay = 3; int count = 0;*/ Bario bario(bariot, &window, map, &view); //load background //make parallax sf::Texture backgroundt; backgroundt.loadFromFile("background1.png"); backgroundt.setRepeated(true); sf::Sprite background; background.setTexture(backgroundt); background.setScale(2746 / background.getLocalBounds().width, 900 / background.getLocalBounds().height); background.setPosition(0, window.getSize().y - 800); background.setTextureRect(sf::IntRect(0, 0, 4000, 900)); //Background stretches for about IntRect.x * 2.5. So background till 10000 //enemies sf::Texture koopat; koopat.loadFromFile("enemies.png"); sf::Sprite koopa; koopa.setTexture(koopat); koopa.setTextureRect(sf::IntRect(105, 12, 18, 31)); koopa.setScale(20 / koopa.getLocalBounds().width, 30 / koopa.getLocalBounds().height); koopa.setOrigin(koopa.getLocalBounds().width / 2, koopa.getLocalBounds().height / 2); koopa.setPosition(500, window.getSize().y - 45); //koopa animation int koopa_delay = 5; int koopa_count = 0; int koopa_state = 0; //game physics float gravity = 1.5; /* float barioXVel = 0.; float barioYVel = 0.; float xMax = 9.; float xAccel = .5; bool onground = true;*/ float koopaXVel = 0.; float koopaYVel = 0.; float koopaXMax = .4; float koopaXAccel = .2; bool koopa_onground = true; //game loop while(window.isOpen()) { //handle window closing event sf::Event e; while(window.pollEvent(e)) { if(e.type == sf::Event::Closed) window.close(); } //game physics koopaYVel += gravity; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { bario.jump(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { bario.moveRight(); } else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { bario.moveLeft(); } else { bario.noInput(); } bario.update(); if(koopa_onground) { koopaYVel = 0.; } //Checks if Bario is standing on any tiles //bool checkOnGround = true; //bool checkOnGround_koopa = true; //std::vector<sf::Sprite>::iterator it = tile.begin(); //while (checkOnGround && it != tile.end()) //{ // if ((*it).getPosition().x > bario.getPosition().x) // { // checkOnGround = false; // onground = false; // } // else if (bario.getPosition().x - (*it).getPosition().x < 20) // { // if ((*it).getPosition().y - bario.getPosition().y < 15) // { // checkOnGround = false; // onground = true; // } // else // { // it = ++it; // } // } // else // { // it = ++it; // } //} //if (it == tile.end()) { // onground = false; //} //it = tile.begin(); /*while(checkOnGround_koopa && it != tile.end()) { if ((*it).getPosition().x > koopa.getPosition().x) { checkOnGround_koopa = false; koopa_onground = false; } else if (koopa.getPosition().x - (*it).getPosition().x < 20) { if ((*it).getPosition().y - koopa.getPosition().y < 15) { checkOnGround_koopa = false; koopa_onground = true; } else { it = ++it; } } else { it = ++it; } } if(it == tile.end()) koopa_onground = false; if(koopa_onground) { koopa.setPosition(koopa.getPosition().x, (*it).getPosition().y - 16); } //koopa follows bario if(koopa.getPosition().x - bario.s.getPosition().x > 0) { koopaXVel -= koopaXAccel; if(koopaXVel < -koopaXMax) koopaXVel = -koopaXMax; koopa.setScale(1, 1); } else { koopaXVel += koopaXAccel; if(koopaXVel > koopaXMax) koopaXVel = koopaXMax; koopa.setScale(-1, 1); }*/ //int collision = collisionCheck(bario, koopa); //if (collision == 1 && koopa_state != 2) //{ // bario.setPosition(sf::Vector2f(20, window.getSize().y - 45)); // view.setCenter(sf::Vector2f(600, 500)); //} ////koopa death //if(collision == 2) { // koopa_state = 2; // koopaXVel = 0; // koopaXAccel = 0; //} /*koopa.move(koopaXVel, 0); //koopa animation koopa_count++; if(koopa_count > koopa_delay) { koopa_count = 0; if(koopa_state == 0) koopa_state = 1; else if(koopa_state == 1) koopa_state = 0; switch(koopa_state) { case 0: koopa.setTextureRect(sf::IntRect(105, 12, 18, 31)); break; case 1: koopa.setTextureRect(sf::IntRect(123, 12, 18, 31)); break; case 2: koopa.setTextureRect(sf::IntRect(42, 12, 18, 31)); break; } }*/ /* //view shifts when bario leaves screen if(bario.s.getPosition().x >= view.getCenter().x + 200) { view.setCenter(bario.s.getPosition().x - 200, 500); } else if(bario.s.getPosition().x <= view.getCenter().x - 200) { if(view.getCenter().x <= 600) {} else view.setCenter(bario.s.getPosition().x + 200, 500); }*/ window.clear(sf::Color::Black); window.setView(view); window.draw(background); window.draw(map); bario.draw(); window.draw(koopa); window.display(); } }
#include <iostream> using namespace std; int main() { int a, b, s = 0; cout << "첫 번째 정수: "; cin >> a; cout << "두 번째 정수: "; cin >> b; s = a + b; cout << "합: " << s; return 0; }
#include <cstdio> const int MAX_N = 100, MAX_M = 100; int N,M; char field[MAX_N][MAX_M +1]; void read(); void solve(); int main(){ read(); solve(); return 0; } void read(){ scanf("%d %d\n", &N, &M); for(int i=0; i < N; i++){ for(int j=0; j < M; j++){ scanf("%c", &field[i][j]); } scanf("\n"); } } void dfs(int x, int y){ field[x][y] = '.'; for (int dx = -1; dx <=1; dx++){ for (int dy = -1; dy <=1; dy++){ int nx = x + dx, ny = y + dy; if (0<=nx && nx<N && 0<=ny && ny<M && field[nx][ny] == 'W'){ dfs(nx,ny); } } } return ; } void solve(){ int res = 0; for(int i=0; i < N; i++){ for(int j=0; j < M; j++){ if (field[i][j] == 'W'){ dfs(i,j); res++; } } } printf("%d\n", res); }
#include "LZ77D.h" LZ77D::LZ77D(FILE* inputFile, int wb, int wl) : input(inputFile){ WB = wb, WL = wl; bitsWB = (WB == 0 ? 1 : 32 - __builtin_clz(WB)); bitsWL = (WL == 0 ? 1 : 32 - __builtin_clz(WL)); window = new uchar[MAX_WINDOW_SIZE]; windowOffset = availableBytes = 0; for(int i = 0; i < WB; ++i) window[i] = 0; } void LZ77D::close() { input.close(); } int LZ77D::decompressNextByte() { if(!availableBytes) { if(windowOffset + WB + WL >= MAX_WINDOW_SIZE) { for(int i = 0; i < WB; ++i) { window[i] = window[windowOffset+i]; } windowOffset = 0; } readToken(); } int byte = window[windowOffset+WB]; ++windowOffset, --availableBytes; return byte; } void LZ77D::readToken() { int pos = -10000000, size, mismatching; size = input.getBunchOfBits(bitsWL); if(size) pos = input.getBunchOfBits(bitsWB); mismatching = input.getBunchOfBits(8); for(int i = 0; i < size; ++i) { int newByte = window[i+pos+windowOffset]; window[windowOffset+WB+i] = newByte; } window[windowOffset+WB+size] = mismatching; availableBytes = size + 1; }
#include<iostream> #include<stack> #include<algorithm> using namespace std; bool isOperator(char ch) { if(ch=='+'|| ch=='-'|| ch=='/' ||ch=='*' ||ch=='^' ) return true; else return false; } int precedence(char ch) { if(ch=='^') return 3; else if(ch=='*'||ch=='/') return 2; else if(ch=='+'||ch=='-') return 1; else return -1; } string infixToPrefix(string infix) { stack <char> s; string prefix; reverse(infix.begin(), infix.end()); for(int i=0;i<infix.length();i++){ if(infix[i]=='(') infix[i]=')'; else if(infix[i]==')') infix[i]='('; } for(int i=0;i<infix.length();i++){ if((infix[i]>='a' && infix[i]<='z') || (infix[i]>='A' && infix[i]<='Z') ) prefix+=infix[i]; else if(infix[i]=='(') s.push(infix[i]); else if(infix[i]==')') { while(s.top()!='(' && !s.empty()) { prefix+=s.top(); s.pop(); } if(s.top()=='(') s.pop(); } else if(isOperator(infix[i])) { if(s.empty()) { s.push(infix[i]); } else { if(precedence(infix[i]) > precedence(s.top()) ) { s.push(infix[i]); } else if((precedence(infix[i]) == precedence(s.top()) ) && (infix[i]=='^')) { while((precedence(infix[i]) == precedence(s.top()) ) && (infix[i]=='^')) { prefix+=s.top(); s.pop(); } s.push(infix[i]); } else if((precedence(infix[i]) == precedence(s.top()) )) { s.push(infix[i]); } else { while((!s.empty()) && (precedence(infix[i]<precedence(s.top())))) { prefix+=s.top(); s.pop(); } s.push(infix[i]); } } } } while(!s.empty()){ prefix+=s.top(); s.pop(); } reverse(prefix.begin(), prefix.end()); return prefix; } int main(){ cout<<"\n\t output : "<<infixToPrefix("((a+b-c)*d^e^f)/g"); }
/* CTC GO! MOTION LESSON 04 - Gears and Pulleys This sketch is written to accompany activity 1 of Lesson 4 */ #include <Servo.h> Servo waterServo; int button1 = 2; int button2 = 3; int waterLevel = 0; int b1_state = 0; int b2_state = 0; void setup() { waterServo.attach(9); Serial.begin(9600); } void loop() { b1_state = digitalRead(button1); b2_state = digitalRead(button2); if (b1_state == 1 && b2_state == 1) { waterLevel = 100; } else if (b1_state == 1 && b2_state == 0) { waterLevel = 60; } else if (b1_state == 0 && b2_state == 1) { waterLevel = 30; } else { waterLevel = 0; } switch (waterLevel) { case 100: waterServo.write(180); Serial.println("Water level 100%"); break; case 60: waterServo.write(110); Serial.println("Water level 60%"); break; case 30: waterServo.write(100); Serial.println("Water level 30%"); break; default: waterServo.write(90); Serial.println("Water level 0%"); break; } }
/* NO WARRANTY * * BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO * WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE * LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS * AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT * WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO * THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD * THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL * NECESSARY SERVICING, REPAIR OR CORRECTION. * * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN * WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY * AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES, * INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL * DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM * (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING * RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES * OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER * PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED * OF THE POSSIBILITY OF SUCH DAMAGES. */ #ifndef _DRAGDROPVIEW_H_ #define _DRAGDROPVIEW_H_ #include "DragDrop.h" #include "DragDropDocument.h" #include "DragDropobject.h" #include "DragDropLink.h" #include "DragDropSelection.h" #define IDC_TEXTEDIT 999 class DragDropTextEdit; class DragDropRectangle; class DragDropPort; class DragDropView : public CScrollView{ typedef CScrollView inherited ; public: virtual DragDropDocument* GetDocument(); virtual CSize GetPixelSize() {return m_sizePixelLP;} virtual void OnPrepareDC(CDC* pDC, CPrintInfo* pInfo = NULL); //ISO (made public for DragDropText. right thing?) virtual void PopToTop(); protected: DragDropView(); virtual ~DragDropView(); CObList m_oblistObjects; // Public? float m_fdevPixelsPerUnit_x ; //ISO Number of device pixels in a centimeter float m_fdevPixelsPerUnit_y ; int m_logPixelsPerUnit ; //ISO Number of logical pixels per centimeter int m_iScale ; //ISO Scale factor as a percent DragDropObject* m_pCurrentObject; // Current Object DragDropObject* m_pMouseOverObject; // Current Object under the mouse CPoint m_pointMouseDown; // pt where mouse button went down CPoint m_pointMouseMove; // pt where mouse button last moved CSize m_offsetMove; // offset from mouse down point to object's top left. DragDropSelection* m_pSelection; // selected Objects DragDropLink* m_pTempLink; // temporary Link for Link creation drawing DragDropPort* m_pTempPortMM; // temporary Port for Link creation drawing-mouse move DragDropPort* m_pTempPortMD; // temporary Port for Link creation drawing-mouse down DragDropPort* m_pLastSnapToPort; // Port that Link "snapped" to on last mouse move CRect m_rectXOR; // temporary rect for XOR drawing int m_handlesHit; // enumerated constants ("int" because we can't extend enum's in derived classes...) enum PointerMode { PointerModeNone, PointerModeSelection, PointerModeResize, PointerModeMove, PointerModeClone, PointerModeCreateLink, PointerModeCreateLinkFrom, PointerModeDragBoxSelection, PointerModeObjectSpecific, PointerModeButton, }m_pointermode; BOOL m_bInitialized; // OnInitialUpdate has been called int m_nClearHandleCount; // printing attributes int m_nPagesWide; int m_nPagesHigh; int m_nWidthLoMM; int m_nHeightLoMM; BOOL m_bPrintPreview; // drag -n- drop attributes BOOL m_bDirtyDropView; BOOL m_bFirstMouseMove; DragDropView *m_pViewDirty; DragDropRectangle *m_pDragObject; CPoint m_PtDirty; UINT m_nLButtonDownFlags; // text editing hooks DragDropTextEdit *m_pEditText; BOOL m_bAbortInputAction; // Graphics performance knobs DWORD m_nGdiBatchLimit; DragDropHandle *m_pHandleRight; DragDropHandle *m_pHandleBottom; DragDropRectangle *m_pGrayRight; DragDropRectangle *m_pGrayBottom; HCURSOR m_hMagnifyCursor; CSize m_sizePixelLP; BOOL m_bInsideButton; class SaveRestoreDC{ protected: int m_context; CDC* m_pDC; public: SaveRestoreDC(CDC* pDC){ m_context = pDC->SaveDC(); m_pDC = pDC; }; ~SaveRestoreDC(){ m_pDC->RestoreDC(m_context); }; }; public: virtual POSITION AddObjectAtHead(DragDropObject* pObject); virtual POSITION AddObjectAtTail(DragDropObject* pObject); virtual POSITION GetFirstObjectPos() const; virtual DragDropObject* GetNextObject(POSITION& pos) const; virtual void RemoveObject(DragDropObject* pObject); virtual DragDropObject* PickInView(CClientDC* pDC, CPoint ptToCheckLP, BOOL bSelectableOnly); protected: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual void DoDrawBackgroundDecoration(CDC* pDC); // overridden to draw things like grids virtual void DoDrawDocumentObjects(DragDropDocument* pDocument, CRect rectClip, CDC* pDrawDC); virtual void DoDrawViewObjects(CRect rectClip, CDC* pDrawDC); virtual void OnInitialUpdate(); virtual void OnUpdate(CView* pSender, LPARAM lHint = 0L, CObject* pHint = NULL); virtual DragDropObject* DoPickInDocument(CClientDC* pDC, CPoint ptToCheckLP, BOOL bSelectableOnly); // Activation virtual void OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView); virtual void DragDropView::OnClickOnBackground(CPoint point); // Implementation public: void InitializeView() {OnInitialUpdate();} virtual DragDropSelection* GetSelection() const; virtual BOOL DropObjectAllowed(DragDropView* pSourceView, DragDropObject* pSourceObject, CPoint pPoint) {return TRUE;} virtual BOOL DropObject(DragDropView* pSourceView, DragDropObject* pSourceObject, CPoint pPoint, UINT nFlags); virtual BOOL DropObjectAnimateDraw(DragDropView* pSourceView, DragDropObject* pSourceObject, CPoint pPoint); virtual BOOL DropObjectAnimateClear(DragDropView* pSourceView, DragDropObject* pSourceObject, CPoint pPoint); virtual void DoDragSelection(CClientDC* pDC, CPoint pointDP, CPoint point, int nEvent); virtual void DoDropSelection(CClientDC* pDC, CPoint pointDP, CPoint point, int nEvent); virtual void DropFail(); virtual void ClearSelection(); void ScrollToPoint(CPoint pointLP); virtual void ScrollToObject(DragDropObject* pObject); virtual void CloseView(); virtual void SetScale(int percent, float clientRectFactor = 0.8) ; //ISO virtual void SetScaleToFit(int nMinScale = 6); virtual void SetScaleToShowWholeDoc(); virtual int GetScale() {return m_iScale;} virtual BOOL IsPrintPreview() {return m_bPrintPreview;} virtual void ZoomToRect(CRect* rectZoom); virtual void ZoomToSelection(); protected: // Handy helper drawing routines virtual void DrawXorRect(CClientDC* pDC, CRect* pRect); virtual void DrawXorBox(CClientDC* pDC, CPoint pt1, CPoint pt2, CRect* pRectAspect=NULL); virtual void AutoScroll(CPoint pointDP); // Selection Support virtual DragDropPort* PickNearestPort(CClientDC* pDC, CPoint pPoint, int nTolerance = -1); virtual void DoSelectionInBox (CRect* rect); virtual void DoMoveSelection(CClientDC* pDC, CPoint pointDP, CPoint pointLP, int nEvent, BOOL bAutoScroll = TRUE); virtual void MoveSelection(CSize sizeOffset, CPoint pointLP, int nEvent); virtual void CancelMoveSelection() {} virtual void GeometryUpdatedSelection(); virtual void RestoreSelectionHandles(); // restore handles after drag virtual void ClearSelectionHandles(); // erase handles for drag virtual void HandleResizing(CClientDC*, CPoint pPoint, int nEvent); virtual DragDropHandle* SelectedHandleTest(CClientDC* pDC, CPoint pPoint); virtual DragDropPort* PortTest(CClientDC* pDC, CPoint pPoint); // Link Creation hooks virtual void SetValidPorts(); virtual void SetValidPorts2(); virtual BOOL ValidSourcePort(DragDropPort* pFrom) {return TRUE;} // for override by smarter subclass virtual BOOL ValidDestinationPort(DragDropPort* pFrom) {return TRUE;} // for override by smarter subclass virtual BOOL ValidLink(DragDropPort* pFrom, DragDropPort* pTo) {return TRUE;} // for override by smarter subclass virtual DragDropLink* NewLink(DragDropPort* pFrom, DragDropPort* pTo); virtual void NoNewLink(DragDropPort* pFrom, DragDropPort* pInvalidTo); // for override // input handling functions virtual void DoLButtonDown(UINT nFlags, CPoint pointDP, CPoint pointLP, CClientDC* pDC); virtual void DoLButtonUp(UINT nFlags, CPoint pointDP, CPoint pointLP, CClientDC* pDC); virtual void DoMouseMove(UINT nFlags, CPoint pointDP, CPoint pointLP, CClientDC* pDC); virtual BOOL DoLButtonDblClk(UINT nFlags, CPoint pointDP, CPoint pointLP, CClientDC* pDC); virtual void DoUncapturedMouseMove(UINT nFlags, CPoint pointDP, CPoint pointLP, CClientDC* pDC); // virtual void DoSize(UINT nType, int cx, int cy); virtual BOOL CancelActionInProgress(UINT nFlags, CPoint pointDP); // cleanup functions virtual void DeleteContents(); // Printing support virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnPrint(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void ViewHandles(); int m_nNewControlID; DWORD m_dwLastTick; int m_nScrollDelay; UINT m_nTimerID; public: // text editing hooks virtual void SetEditControl(DragDropTextEdit* pEdit); virtual DragDropTextEdit* EditControl() {return m_pEditText;} virtual int GetTextControlId() {return IDC_TEXTEDIT;} virtual BOOL IsEditingTextControl() {return (m_pEditText != NULL);} virtual void DoEndEdit(); virtual int GetNewControlID(); virtual void SetBaseControlID(int nBase); // coordinate convenience functions virtual void GetClientRectLP(CRect* pRect); virtual void GetClientRectLPZero(CRect* pRect); virtual void GetRectDP(CRect* pRect); virtual void ClientToDoc(CPoint &pt); virtual void DocToClient(CPoint &pt); virtual void ClientToDoc(CRect* rect); virtual void DocToClient(CRect* rect); virtual void ClientToDoc(CSize &s); virtual void DocToClient(CSize &s); virtual BOOL StartNewLink(DragDropPort* pPort, CPoint pointLP); protected: // Handle new doc size virtual void NewDocSize(); virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo); //{{AFX_MSG(DragDropView) afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point); afx_msg void OnSysColorChange(); afx_msg LRESULT OnDoRefresh(WPARAM wParam, LPARAM lParam); // user message // afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnTimer(UINT nIDEvent); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); //}}AFX_MSG afx_msg void OnEnUpdate(); friend class DragDropHandle; friend class DragDropObject; friend class DragDropText; DECLARE_DYNCREATE(DragDropView) DECLARE_MESSAGE_MAP() }; inline DragDropDocument* DragDropView::GetDocument() { return(DragDropDocument*) m_pDocument; } #endif
// Copyright (C) 2005 by Piotr Hełka (piotr.helka@nd.e-wro.pl) // Linux C++ (not full) implementation of Borland's conio.h // v 1.01 // It uses Ncurses lib, so accept also its terms. // 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // ----------------------------- krotki opis ------------------ // Biblioteka obsługuje mniej lub bardziej zgodnie: // // cgets() // cputs() // clreol() // clrscr() // cprintf() // cscanf() // getch() (chyba nie wszystkie kody tak jak w conio.h) // getche() // gotoxy() // kbhit() // putch() // textbackground() // textcolor() // wherex() // wherey() // window() // // kompatbyilność w kierunku Linux CONIO.H -> DOS CONIO.H // bedzie zachowana // Aby skompilowac // $g++ nazwa_progsa.cpp -lncurses -o nazwa_progsa.o // ------------------------------- define --------------------- #ifndef __NCURSES_H #include <ncurses.h> #endif #ifndef __CONIO_H #define __CONIO_H #endif #define MAX_OKIEN 256 #define BLACK 0 #define RED 1 #define GREEN 2 #define BROWN 3 #define BLUE 4 #define MAGENTA 5 #define CYAN 6 #define LIGHTGRAY 7 #define DARKGRAY 0 #define LIGHTRED 1 #define LIGHTGREEN 2 #define YELLOW 3 #define LIGHTBLUE 4 #define PINK 5 #define LIGHTCYAN 6 #define WHITE 7 // -------------------------------- globalne ------------------ //int (* wsk_f)(void) = getch; #undef getch #define getch CURSgetch #undef getche #define getche CURSgetche void inicjuj(); class Startuj // konstruktor i destruktor klasy beda odpowiedzalni { public: // za automagiczna inicjalizacje ustawien ;-) Startuj(){ inicjuj(); } ~Startuj(){ endwin(); } } Start; // inicjuj! typedef struct { int xup; int yup; int xdown; int ydown; WINDOW* okno; } Okno; bool zainicjowane = FALSE; //czy juz po initscr() ? int znakSpecjalny = -1; //potrzebne do getch'a int n = 0; //liczba uzytych okienek short kolorTekstu = COLOR_WHITE; short kolorTla = COLOR_BLACK; short biezacaPara; Okno okienka[MAX_OKIEN]; //tablica struktur aktywnych okienek WINDOW* aktywneOkno = NULL; //wsk na aktywne okno // ----------------------------- koniec globalnych ------------ void inicjuj() { initscr(); start_color(); //wlaczmy kolorki cbreak(); //wylaczmy buforowanie wejscia noecho(); //bez wyswietlania na ekran //raw(); //nadpisywane i tak przez noecho keypad(stdscr, TRUE); scrollok(stdscr, TRUE); //domyslne okno aktywneOkno = stdscr; zainicjowane = TRUE; //utworzmy macierz 8x8 kolorow tla i tekstu short kolor = 1; for(short i=0; i<8; i++) { for(short j=0; j<8; j++, kolor++) { init_pair(kolor,i,j); if(i == COLOR_WHITE && j == COLOR_BLACK) //ustawmy czarne tlo i bialey tekst jako standard { biezacaPara = kolor; } } } wrefresh(aktywneOkno); } int simple_strlen(char* str) { char* p; for(p = str; *p != 0; p++); return p-str; } void cputs(char* str) { waddstr(aktywneOkno, str); wrefresh(aktywneOkno); } char* cgets(char* str) { // nie wiem dokladnie jak dziala orginalna f. cgets bo nie mam // do niej referencji.. if(str == NULL || *str == 0) { *(str+1) = 0; return NULL; } int max = (int)(*str); echo(); if(wgetnstr(aktywneOkno, (str + 2), max) == ERR) { *(str+1) = 0; return NULL; } noecho(); *(str+1) = (char)simple_strlen(str+2); return str+2; } void clreol() { wclrtoeol(aktywneOkno); wrefresh(aktywneOkno); } void clrscr() { if(!zainicjowane) inicjuj(); wbkgd(aktywneOkno, COLOR_PAIR(biezacaPara)); //trzeba przesunac kursor? chyba nie... wclear(aktywneOkno); } int cprintf(char *fmt, ...) // czysty hardcore ;-) { if(!zainicjowane) inicjuj(); va_list ap; va_start(ap, fmt); int i = vwprintw(aktywneOkno,fmt, ap); //jakie proste ;-) va_end(ap); wrefresh(aktywneOkno); return i; } int cscanf(char *fmt, ...) { if(!zainicjowane) inicjuj(); echo(); va_list ap; va_start(ap, fmt); int i = vwscanw(aktywneOkno, fmt, ap); va_end(ap); wrefresh(aktywneOkno); noecho(); return i; } int CURSgetch() { if(!zainicjowane) inicjuj(); int znak; if(znakSpecjalny>0) //drugi czlon znaku specjalnego 0x00 i 0x?? { //zamieniamy znak na kod DOSowy - conio.h znak = znakSpecjalny; znakSpecjalny = -1; return znak-265+59; } znak = wgetch(aktywneOkno); if(znak > 255) //to mamy znak specjalny 0x00 { znakSpecjalny = znak; return 0; } return znak; } int CURSgetche() { echo(); int znak = getch(); noecho(); return znak; } int gotoxy(int x, int y) { if(!zainicjowane) inicjuj(); wmove(aktywneOkno, y - 1, x - 1); return 0; } int kbhit() { int znak; wtimeout(aktywneOkno, 0); znak = wgetch(aktywneOkno); //wtimeout(aktywneOkno, -1); nodelay(aktywneOkno, FALSE); if (znak == ERR) return 0; ungetch(znak); return 1; } int putch(int znak) { wechochar(aktywneOkno,znak); } void textbackground(short kolor) { if(!zainicjowane) inicjuj(); kolorTla = kolor%8; short k=1; for(short i=0; i<8; i++) //wyszukajmy numer pary dla kolorow { for(short j=0; j<8; j++, k++) { if(kolorTekstu == i && kolorTla == j) { biezacaPara = k; wbkgd(aktywneOkno, COLOR_PAIR(k)); } } } wrefresh(aktywneOkno); } void textcolor(short kolor) { if(!zainicjowane) inicjuj(); kolorTekstu = kolor%8; short k=1; for(short i=0; i<8; i++) //wyszukajmy numer pary dla kolorow { for(short j=0; j<8; j++, k++) { if(kolorTekstu == i && kolorTla == j) { biezacaPara = k; wcolor_set(aktywneOkno,k, NULL); } } } wrefresh(aktywneOkno); } int wherex(void) { if(!zainicjowane) inicjuj(); int x, y; getyx(aktywneOkno, y, x); return x + 1; } int wherey(void) { if(!zainicjowane) inicjuj(); int x, y; getyx(aktywneOkno, y, x); return y + 1; } void window(int xup, int yup, int xdown, int ydown) { if( xup<1 || yup<1 || xdown>COLS || ydown>LINES) { //jesli zle dane podano... xdown = COLS - xup; ydown = LINES - yup; //return; } bool istnieje = FALSE; if(!zainicjowane) inicjuj(); /* Istnieje alternatywne rozwiazanie tworzenia nowych okien, w momencie tworzenia nowego okna, usuwa sie okno poprzednie, tzn zwalnia pamiec tego okna, komenda delwin(nzw_okna) i tworzy sie nowe okno, ustawiajac jego jako domyslne-biezace. Jednak poniewaz moze to zabierac za duzo czasu i niepotrzebnie spowolniac, majac na uwadze rozmiar dzisiejszych pamieci, postanowilem, uzyc tablicy, ktora przechowywuje wsk. na adresy okien i wykorzystuje zaalokowana juz przestrzen. Aczkolwiek mozna to w kazdej chwili zmienic. */ for(int i=0; i<n && !istnieje; i++) //sprawdzimy czy podane okno juz nie // zostalo wczesniej stworzone { if( okienka[i].xup == xup && okienka[i].yup == yup && okienka[i].xdown == xdown && okienka[i].ydown == ydown) { aktywneOkno = okienka[i].okno; istnieje = TRUE; clrscr(); } } if(!istnieje && n < MAX_OKIEN) //jesli nie ma takiego okna to tworzymy je { aktywneOkno = newwin(ydown - yup + 1, xdown - xup + 1, yup - 1, xup - 1); //nie dam glowy czy dokladnie tak wyswietla conio.h //do tablicy zapisac... okienka[n].okno = aktywneOkno; okienka[n].xup = xup; okienka[n].yup = yup; okienka[n].xdown = xdown; okienka[n].ydown = ydown; wcolor_set(aktywneOkno,biezacaPara, NULL); wbkgd(aktywneOkno, COLOR_PAIR(biezacaPara)); //przywrocenie ustawien klawiszy cbreak(); //wylaczmy buforowanie wejscia noecho(); //bez wyswietlania na ekran keypad(aktywneOkno, TRUE); //pelne kody klawiszy scrollok(aktywneOkno, TRUE); n++; } wrefresh(aktywneOkno); return; }
#include<iostream> using namespace std; template<typename T> void fun1(T tNo) { cout<<"Size of T is\n"<<sizeof(T); if(1==sizeof(T)) throw tNo; else(4==sizeof(T)); throw tNo; cout<<"Exception not found"; } int main() { try { fun1(10.2f); fun1('A'); } catch(int exception) { cout<<"Interger exception found"<<endl; } catch(float exception) { cout<<"float exception found"<<endl; } catch (char exception0) { cout<<"char exception found"<<endl; } return 0; }
#include "repository_service.h" #include <vector> #include "inventory_updater.h" #include "inventory_visitor.h" #include "location.h" namespace inventory { namespace { struct InventoryItem { const ItemType type; Amount amount; Price price; }; #define FOR_EACH(objects, action) \ for (auto& it : objects) { \ action(it); \ } #define FIND_ONE_DO(objects, pred, action) \ do { \ for (auto& it : objects) { \ if (pred(it)) { \ action(it); \ return; \ } \ } \ } while (0) struct ReposImpl { ReposImpl(Location location, std::initializer_list<InventoryItem> items) : location(location), items(items) { } void accept(InventoryVisitor& visitor, const ItemType request_item) const { FIND_ONE_DO(items, [&](auto& it) { return it.type == request_item; }, [&](auto& it) { visitor.visit(location, it.type, it.amount, it.price); }); } void accept(InventoryUpdater& visitor, const ItemType request_item) { FIND_ONE_DO(items, [&](auto& it) { return it.type == request_item; }, [&](auto& it) { visitor.visit(location, it.type, &it.amount, it.price); }); } private: Location location; std::vector<InventoryItem> items; }; struct AllRepositories { static std::vector<ReposImpl> init() { return {{Brazil, {{iPod, 100, 65}, {iPhone, 100, 100}}}, {Argentina, {{iPod, 100, 100}, {iPhone, 50, 150}}}}; } static void reset() { repos() = init(); } static std::vector<ReposImpl>& repos() { static std::vector<ReposImpl> repositories; // = init(); return repositories; } }; } // namespace void RepositoryService::accept(InventoryVisitor& visitor, const ItemType type) const { FOR_EACH(AllRepositories::repos(), [&](auto& it) { it.accept(visitor, type); }); } void RepositoryService::accept(InventoryUpdater& visitor, const ItemType type) { FOR_EACH(AllRepositories::repos(), [&](auto& it) { it.accept(visitor, type); }); } void RepositoryService::reset() { AllRepositories::reset(); } } // namespace inventory
#ifndef NEW_PROJECT_2_GAME_HPP #define NEW_PROJECT_2_GAME_HPP #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include "player.hpp" #include "field.hpp" #include "button.hpp" #include "definitions.hpp" class Game { public: Game() = default; Game(sf::RenderWindow *window); ~Game() = default; void run(); void call_rules_module(); void call_scores_module(); sf::RenderWindow *get_window() const; void set_window(sf::RenderWindow *window); Player get_left_player() const; Player get_right_player() const; Player *get_left_player_ptr(); Player *get_right_player_ptr(); void set_left_player(const Player &player_1); void set_right_player(const Player &player_2); Field get_field() const; void set_field(Field &field); bool left_player_has_won(); // to check who has won the game: true - player_1, false - player_2 private: sf::RenderWindow *window_pointer_; bool has_finished_ = false; // TODO: (nmerk) move to consructor bool rules_were_shown_ = false; bool scores_were_shown_ = false; bool player_move; Player left_player_; Player right_player_; Field field_; void handle_events(); void update(); void render(); void update_has_finished(); }; #endif // NEW_PROJECT_2_GAME_HPP
//header #include <iostream> using std::cout; void display_number(int num1); int square_number(int num);
#ifndef __Box2DRayCast__H__ #define __Box2DRayCast__H__ #include <typeinfo> enum Box2DRayCastType { Box2DRayCastType_Closest, Box2DRayCastType_AllFixtures, Box2DRayCastType_Anything, Box2DRayCastType_Ignore }; struct RayCastInformation { b2Body* m_pBody; b2Fixture* m_pFixture; b2Vec2 m_point; b2Vec2 m_normal; float32 m_fraction; }; class Box2DRayCast : public b2RayCastCallback { protected: bool m_hit; std::vector<RayCastInformation*> m_rayCastInformation; Box2DRayCastType m_rayCastType; std::vector<b2BodyType> m_bodyTypesToIgnore; public: Box2DRayCast(Box2DRayCastType aRayCastType = Box2DRayCastType_Closest); float32 ReportFixture(b2Fixture* aFixture, const b2Vec2& aPoint, const b2Vec2 &aNormal, float32 aFraction); RayCastInformation* GetRayCastInformation(unsigned int aIndex = 0); std::vector<RayCastInformation*> GetAllRayCastInformation(); void ClearAllRayCastInformation(); bool GetHit() {return m_hit; } void SetHit(bool aStatus){ m_hit = aStatus; } void AddBodyTypeToIgnore(b2BodyType aBodyType); void RemoveBodyTypeToIgnore(b2BodyType aBodyType); void SetRayCastType(Box2DRayCastType aRayCastType) { m_rayCastType = aRayCastType; } void ResetRayCast(); }; #endif
#include <iostream> #include <string> using namespace std; char table[26][26]; void GenTable() { for(int i=0;i<26;++i) { for(int j=0;j<26;++j) table[i][j]='A'+(i+j)%26; } // for(int i=0;i<26;++i) // { // for(int j=0;j<26;++j) // cout<<table[i][j]<<" "; // cout<<endl; // } } int main() { GenTable(); string key,message,ciphertext; int message_length,key_length,message_num,key_num,tp,ciphertext_length; int cip_num,cip_key_num; // key="deceptive"; // message="wearediscoveredsaveyourself"; cout<<"-------------Encode here-------------"<<endl; cout<<"Enter your key: "; cin>>key; cout<<"Enter your Message: "; cin>>message; message_length=message.length(); key_length=key.length(); tp=0; cout<<"Your ciphertext is: "; ciphertext=""; for(int i=0;i<message_length;++i) { if(i>key_length) tp=i%key_length; else tp=i; message_num=message[i]-'a'; key_num=key[tp]-'a'; ciphertext=ciphertext+table[message_num][key_num]; } cout<<ciphertext; cout<<endl; cout<<"-------------Decode here-------------"<<endl; cout<<"Enter your key: "; cin>>key; cout<<"Enter your ciphertext: "; cin>>ciphertext; tp=0; char temp; ciphertext_length=ciphertext.length(); message=""; for(int i=0;i<ciphertext_length;++i) { if(i>key_length) tp=i%key_length; else tp=i; cip_key_num=key[tp]-'a'; for (int j = 0; j < 26; ++j) { if(table[cip_key_num][j]==ciphertext[i]) { cip_num=j; temp='a'+j; message+=temp; break; } } } cout<<"Your Message is: "; cout<<message<<endl; cin>>tp; return 0; }
#ifndef WordHistogram_H #define WordHistogram_H #include "WordUnit.h" #include <vector> //Stores WordUnits #include <algorithm> //Used to sort vectors #include <iostream> //Cout, Used to debug #include <fstream> //Needed to read/write files using namespace std; class WordHistogram{ public: //Constructor explicit WordHistogram(string newFileName); //Functions relating to Words void addWord(string word); //add a Word to histogram bool checkWord(string word); //Check if a word is in the histogram WordUnit& getWord(string word); //Get a word from the histogram void makeHistogram(void); //make a histogram //Functions relating to Files void setFileName(string newFileName); //set the filename string getFileName(void); //get the filename void exportHistogram(string textFile); //export the histogram to said filename //Functions relating to sorting void sortAlphaHistogram(void); //sorts histogram alphabetically void sortFreqHistogram(void); //sorts histogram by frequency void sortFreqAlphaHistogram(void); //sorts histogram by frequency, then alphabetically //Other void printList(void); //prints list to iostream private: string filename; //filename vector<WordUnit> wordList; //Vector of words }; #endif
#pragma once #include "SwerveRotation2d.h" class SwerveTranslation2d{ protected: double m_x, m_y; public: SwerveTranslation2d(); SwerveTranslation2d(double x, double y); double Norm(); double GetX(); double GetY(); void SetX(double x); void SetY(double y); SwerveTranslation2d TranslateBy(SwerveTranslation2d other); SwerveTranslation2d RotateBy(SwerveRotation2d rotation); SwerveTranslation2d Inverse(); SwerveTranslation2d Interpolate(SwerveTranslation2d other, double x); SwerveTranslation2d Extrapolate(SwerveTranslation2d other, double x); SwerveTranslation2d FlipX(); SwerveTranslation2d FlipY(); double GetSin(); double GetCos(); };
#include<stdio.h> #include<iostream.h> void menu(); int main() { int islem; menu(); scanf("%d", &islem); if { scanf("%d", islem); } void menu(){ printf("Bankamiza hosgeldiniz. Islem secimi yapiniz:\n 1.Para Cekme\n 2. Para Yatirma\n 3. Havale\n 4. Bakiye Sorgulama\n 5. Cikis"); }
/* * SPDX-FileCopyrightText: (C) 2013-2022 Daniel Nicoletti <dantti12@gmail.com> * SPDX-License-Identifier: BSD-3-Clause */ #include "actionrest_p.h" #include "context.h" #include "controller.h" #include "dispatcher.h" #include <QDebug> #include <QUrl> using namespace Cutelyst; /*! * \class Cutelyst::ActionREST actionrest.h Cutelyst/Actions/REST/ActionREST * \brief Automated REST Method Dispatching * * \code{.h} * C_ATTR(foo, :Local :ActionClass(REST)) * void foo(Context *c); // do setup for HTTP method specific handlers * * C_ATTR(foo_GET, :Private) * void foo_GET(Context *c); // do something for GET requests * * C_ATTR(foo_PUT, :Private) * void foo_PUT(Context *c); // do something for PUT requests * \endcode * * This Action handles doing automatic method dispatching for REST requests. It takes a normal Cutelyst action, and changes * the dispatch to append an underscore and method name. First it will try dispatching to an action with the generated name, * and failing that it will try to dispatch to a regular method. * * For example, in the synopsis above, calling GET on "/foo" would result in the foo_GET method being dispatched. * * If a method is requested that is not implemented, this action will return a status 405 (Method Not Found). It will populate * the "Allow" header with the list of implemented request methods. You can override this behavior by implementing a custom * 405 handler like so: * * \code{.h} * C_ATTR(foo_not_implemented, :Private) * void foo_not_implemented(Context *c); // handle not implemented methods * \endcode * * If you do not provide an _OPTIONS method, we will automatically respond with a 200 OK. The "Allow" header will be populated * with the list of implemented request methods. If you do not provide an _HEAD either, we will auto dispatch to the _GET one * in case it exists. */ ActionREST::ActionREST(QObject *parent) : Action(new ActionRESTPrivate(this), parent) { } bool ActionREST::doExecute(Context *c) { Q_D(const ActionREST); if (!Action::doExecute(c)) { return false; } return d->dispatchRestMethod(c, c->request()->method()); } ActionRESTPrivate::ActionRESTPrivate(ActionREST *q) : q_ptr(q) { } bool ActionRESTPrivate::dispatchRestMethod(Context *c, const QString &httpMethod) const { Q_Q(const ActionREST); const QString restMethod = q->name() + u'_' + httpMethod; Controller *controller = q->controller(); Action *action = controller->actionFor(restMethod); if (!action) { // Look for non registered actions in this controller const ActionList actions = controller->actions(); for (Action *controllerAction : actions) { if (controllerAction->name() == restMethod) { action = controllerAction; break; } } } if (action) { return c->execute(action); } bool ret = false; if (httpMethod.compare(u"OPTIONS") == 0) { ret = returnOptions(c, q->name()); } else if (httpMethod.compare(u"HEAD") == 0) { // redispatch to GET ret = dispatchRestMethod(c, QStringLiteral("GET")); } else if (httpMethod.compare(u"not_implemented") != 0) { // try dispatching to foo_not_implemented ret = dispatchRestMethod(c, QStringLiteral("not_implemented")); } else { // not_implemented ret = returnNotImplemented(c, q->name()); } return ret; } bool ActionRESTPrivate::returnOptions(Context *c, const QString &methodName) const { Response *response = c->response(); response->setContentType(QStringLiteral("text/plain")); response->setStatus(Response::OK); // 200 response->setHeader(QStringLiteral("ALLOW"), getAllowedMethods(c->controller(), methodName)); response->body().clear(); return true; } bool ActionRESTPrivate::returnNotImplemented(Context *c, const QString &methodName) const { Response *response = c->response(); response->setStatus(Response::MethodNotAllowed); // 405 response->setHeader(QStringLiteral("ALLOW"), getAllowedMethods(c->controller(), methodName)); const QString body = QLatin1String("Method ") + c->req()->method() + QLatin1String(" not implemented for ") + c->uriFor(methodName).toString(); response->setBody(body); return true; } QString Cutelyst::ActionRESTPrivate::getAllowedMethods(Controller *controller, const QString &methodName) const { QStringList methods; const QString name = methodName + u'_'; const ActionList actions = controller->actions(); for (Action *action : actions) { const QString method = action->name(); if (method.startsWith(name)) { methods.append(method.mid(name.size())); } } if (methods.contains(u"GET")) { methods.append(QStringLiteral("HEAD")); } methods.removeAll(QStringLiteral("not_implemented")); methods.sort(); methods.removeDuplicates(); return methods.join(u", "); } #include "moc_actionrest.cpp"
#include "PorkParser.h" #pragma warning( push ) #pragma warning( disable : 4482 ) using std::getline; using std::stack; using namespace PorkParserSpace; // Constructor for PorkParser - requires filename PorkParser::PorkParser(string filename, string name, string author): ParserBase(filename), theGameContainer(name, author, PORKSCRIPT_STANDARD) { // Also construct the charlists for accepted chars // Alphanumerics // Enter in all numbers 0-9 for(char i=0x30;i<=0x39;i++) { alphaNum += i; } // Do all uppercase chars for(char i=0x41;i<=0x5A;i++) { alphaNum += i; } // All lowercase for(char i=0x61;i<=0x7A;i++) { alphaNum += i; } // Now for all accepted symbols symbols.append("(),.:[]+"); // Also enter the space and indent whitespace.append("\t\r\n "); acceptedChars = alphaNum + symbols + whitespace; } // Destructor PorkParser::~PorkParser() { } void PorkParser::CompilePorkScript() { string lineread; // Set the current line being parsed to 0 UINT lexLineNum = 0; // The line number the lexer is at itsCurrentLine = &lexLineNum; // Set the current line number to the lexer's line number if(!itsFile) throw xInvalidFile(NULL, itsFileName); // Lex each line for parser vector<vector<TokenPair>> lexedLines; // Vector containing all lexed lines (vector<TokenPair>) while(getline(itsFile, lineread)) { lexLineNum++; // Take out the comments SeperateComments(lineread); // Lex the line, then check if it is empty. If so, throw it out. vector<TokenPair> tempTok = Lex(lineread); if(!tempTok.empty()) lexedLines.push_back(tempTok); } // Pass the lexed line list into the Parser if(!lexedLines.empty()) Parse(lexedLines); else throw xLexicalError(0, itsFileName, "Lexeme list is empty!"); } void PorkParser::Parse(vector<vector<TokenPair>> linesToParse) { TempParseInfo sInfo; // Temporary info for an object (this is zeroed each time an object is // fully defined and committed to the GC) // Temporary secondary structures for use with sInfo (after one is filled it shall be zeroed for further usage) TempMStateInfo sState; TempMItemListInfo sItem; TempMItemDTagInfo sDTag; std::pair<string,string> currentProp; // mod.prop name std::pair<string,string> currentDynProp; UINT i = 0; // The line number itsCurrentLine = &i; stack<ParserLevels> levelStack; // Stack of levels in program (mapdef, mstatedef, mitemlistdef, etc.) // Run through every word of every line and check the keywords for syntatical correctness for(; i<linesToParse.size(); i++) { bool isLastWord = false; // Bool to tell us if this is the last word in the line PKeyword priorWord = NONE; // The word before the current word SentenceTypes lineType = tNONE; // This enum will tell us what we are setting/dealing with (once we know) for(UINT j=0;j<linesToParse[i].size();j++) { if(j == linesToParse[i].size()-1) isLastWord = true; else isLastWord = false; // Master word table switch(linesToParse[i][j].first) { case REQUIRES: { if(priorWord != NONE || !levelStack.empty()) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'requires' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'requires' keyword.", linesToParse[i]); } break; case DEF: { if(priorWord != NONE || !levelStack.empty()) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'def' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'def' keyword.", linesToParse[i]); } break; case SET: { if(priorWord != NONE || levelStack.top() != MAPDEF && levelStack.top() != ITEMDEF && levelStack.top() != MSTATESET && levelStack.top() != IMDYNSET) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'set' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set' keyword.", linesToParse[i]); } break; case ESET: { if(priorWord != NONE) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'eset' keyword.", linesToParse[i]); if(isLastWord) { if(levelStack.top() == IMDYNSET || levelStack.top() == MSTATESET || levelStack.top() == MITEMLISTSET) levelStack.pop(); else throw xSyntaxError(i, itsFileName, "Unexpected usage of 'eset' keyword.", linesToParse[i]); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of 'eset' keyword.", linesToParse[i]); } break; case EDEF: { if(priorWord != NONE) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'edef' keyword.", linesToParse[i]); if(isLastWord) { if(levelStack.top() == MAPDEF) { levelStack.pop(); InsertMapDef(&sInfo); sInfo.Zero(); } else if(levelStack.top() == ITEMDEF) { levelStack.pop(); InsertItemDef(&sInfo); sInfo.Zero(); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of 'edef' keyword.", linesToParse[i]); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of 'edef' keyword.", linesToParse[i]); } break; case DYNAMIC: { if(priorWord != SET || levelStack.top() != MAPDEF && levelStack.top() != ITEMDEF && levelStack.top() != MSTATESET) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'dynamic' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set dynamic'.", linesToParse[i]); lineType = SETDYN; } break; case STATE: { if(priorWord != SET || levelStack.top() != MAPDEF) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'state' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set state'.", linesToParse[i]); lineType = SETSTATE; } break; case DEFAULT: { if(levelStack.top() == MITEMLISTSET) { if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemlist'.", linesToParse[i]); if(priorWord != FROM) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'default' keyword.", linesToParse[i]); sItem.from = "default"; } else if(levelStack.top() == MSTATESET) { if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set state'.", linesToParse[i]); if(priorWord != STATE) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'default' keyword.", linesToParse[i]); sState.identifier = "default"; } else throw xSyntaxError(i, itsFileName, "Unexpected usage of 'default' keyword.", linesToParse[i]); } break; case RELIESON: { if(priorWord != IDENTIFIER || levelStack.top() != MITEMLISTSET) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'reliesOn' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemlist'.", linesToParse[i]); } break; case FROM: { if(priorWord != IDENTIFIER || levelStack.top() != MITEMLISTSET) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'from' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemlist'.", linesToParse[i]); } break; case TRIGGER: { if(priorWord != IDENTIFIER || lineType != SETSTATE) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'trigger' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set state'.", linesToParse[i]); } break; case PRESENT: { if(priorWord != COMMA || levelStack.top() != MITEMLISTSET) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'present' keyword.", linesToParse[i]); if(isLastWord) { sItem.condition = "present"; sInfo.itemList.push_back(sItem); sItem.Zero(); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of 'present' keyword.", linesToParse[i]); } break; case N_PRESENT: { if(priorWord != COMMA || levelStack.top() != MITEMLISTSET) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'present' keyword.", linesToParse[i]); if(isLastWord) { sItem.condition = "n_present"; sInfo.itemList.push_back(sItem); sItem.Zero(); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of 'present' keyword.", linesToParse[i]); } break; case INF: { if(priorWord != OPEN_PARA || lineType != SETITEMLIST && levelStack.top() != MITEMLISTSET) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'inf' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemlist'.", linesToParse[i]); sItem.amt = 0; } break; case FOR: { if(priorWord != ITEMDTAG || levelStack.top() != MSTATESET && levelStack.top() != MAPDEF) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'for' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemDTag'.", linesToParse[i]); } break; case DEFINITIVE: { if(priorWord != STATE || levelStack.top() != MAPDEF || lineType != SETSTATE) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'definitive' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemDTag'.", linesToParse[i]); sState.isDefinitive = true; } break; case NAME: { if(priorWord != SET || levelStack.top() != ITEMDEF && levelStack.top() != MAPDEF && levelStack.top() != MSTATESET) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'name' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set name'.", linesToParse[i]); lineType = SETNAME; } break; case DESC: { if(priorWord != SET || levelStack.top() != ITEMDEF && levelStack.top() != MAPDEF && levelStack.top() != MSTATESET) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'desc' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set desc'.", linesToParse[i]); lineType = SETDESC; } break; case MAP: { if(priorWord != DEF || !levelStack.empty()) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'map' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'def map'.", linesToParse[i]); sInfo.objType = MAPDEF; } break; case ITEM: { if(priorWord != DEF || !levelStack.empty()) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'item' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'def item'.", linesToParse[i]); sInfo.objType = ITEMDEF; } break; case ITEMLIST: { if(priorWord != SET || levelStack.top() != MAPDEF && levelStack.top() != MSTATESET) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'itemlist' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'def item'.", linesToParse[i]); lineType = SETITEMLIST; } break; case ITEMDTAG: { if(priorWord != SET || levelStack.top() != MAPDEF && levelStack.top() != MSTATESET) throw xSyntaxError(i, itsFileName, "Unexpected usage of 'itemDTag' keyword.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemDTag'.", linesToParse[i]); lineType = SETITEMDTAG; sDTag.dynPieces = CompressArgs(&linesToParse[i]); } break; case IDENTIFIER: { if(!levelStack.empty()) { // Switch statement to hold all the possible places an identifier can be used switch(levelStack.top()) { case MSTATESET: // Just drop into MAPDEF case MAPDEF: { if(lineType == tNONE) { if(priorWord != SET) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set'.", linesToParse[i]); lineType = SETMODULE; currentProp.first = linesToParse[i][j].second; } else if(lineType == SETDYN) { if(priorWord != DYNAMIC) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set dynamic'.", linesToParse[i]); lineType = SETDYNMODULE; currentProp.first = linesToParse[i][j].second; } else if(lineType == SETPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::MAP, TempProperty(currentProp, linesToParse[i][j].second))); else throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); } else if(lineType == SETDYNPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::MAP, TempProperty(currentProp, linesToParse[i][j].second))); } else if(lineType == SETSTATE) { if(levelStack.top() == MSTATESET) throw xSyntaxError(i, itsFileName, "States may not be set inside of states!", linesToParse[i]); if(priorWord == STATE || priorWord == DEFINITIVE) sState.identifier = linesToParse[i][j].second; else if(priorWord == TRIGGER) sState.trigger = linesToParse[i][j].second; else throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set state'.", linesToParse[i]); } else if(lineType == SETITEMLIST) { if(priorWord == ITEMLIST || priorWord == COMMA) sItem.name = linesToParse[i][j].second; else throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemlist'.", linesToParse[i]); } else if(lineType == SETITEMDTAG) { if(priorWord != FOR) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemDTag'.", linesToParse[i]); sDTag.forItem = linesToParse[i][j].second; } else if(lineType == SETMODULE) { if(priorWord != PERIOD) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set'.", linesToParse[i]); currentProp.second = linesToParse[i][j].second; lineType = SETPROP; } else if(lineType == SETDYNMODULE) { if(priorWord != PERIOD) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set dynamic'.", linesToParse[i]); currentProp.second = linesToParse[i][j].second; lineType = SETDYNPROP; } else throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); } break; case ITEMDEF: { if(lineType == tNONE) { if(priorWord != SET) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set'.", linesToParse[i]); lineType = SETMODULE; currentProp.first = linesToParse[i][j].second; } else if(lineType == SETDYN) { if(priorWord != DYNAMIC) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set dynamic'.", linesToParse[i]); lineType = SETDYNMODULE; currentProp.first = linesToParse[i][j].second; currentDynProp.first = linesToParse[i][j].second; } else if(lineType == SETPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::ITEM, TempProperty(currentProp, linesToParse[i][j].second))); else throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); } else if(lineType == SETDYNPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::ITEM, TempProperty(currentProp, linesToParse[i][j].second))); } else if(lineType == SETMODULE) { if(priorWord != PERIOD) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set'.", linesToParse[i]); currentProp.second = linesToParse[i][j].second; lineType = SETPROP; } else if(lineType == SETDYNMODULE) { if(priorWord != PERIOD) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set dynamic'.", linesToParse[i]); currentProp.second = linesToParse[i][j].second; lineType = SETDYNPROP; } else throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); } break; case IMDYNSET: { if(lineType == tNONE) { if(priorWord != SET) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set dynamic'.", linesToParse[i]); if(linesToParse[i][j].second != currentProp.second) throw xSyntaxError(i, itsFileName, "Unknown property set in dynamic definition.", linesToParse[i]); lineType = DYNSET; } else if(lineType == DYNSET) { if(priorWord != OPEN_BRACKET) throw xSyntaxError(i, itsFileName, "Missing '[' after identifier.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set dynamic'.", linesToParse[i]); currentDynProp.second = currentProp.second + "[" + linesToParse[i][j].second + "]"; lineType = DYNSETPROP; } else if(lineType == DYNSETPROP) { if(priorWord != CLOSE_BRACKET) throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); if(isLastWord) sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::ITEM, TempProperty(currentDynProp, linesToParse[i][j].second))); else throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); } break; case MITEMLISTSET: { if(priorWord == NONE) { if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemlist'.", linesToParse[i]); sItem.name = linesToParse[i][j].second; } else if(priorWord == RELIESON) { if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemlist'.", linesToParse[i]); sItem.reliesOn = linesToParse[i][j].second; } else if(priorWord == FROM) { if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemlist'.", linesToParse[i]); sItem.from = linesToParse[i][j].second; } else throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); } break; default: throw xSyntaxError(i, itsFileName, "Unexpected usage of identifier.", linesToParse[i]); } } //if(!levelStack.empty()) else { if(priorWord == REQUIRES) { PreparePython(linesToParse[i][j].second); } } } break; case NUMCONST: { switch(levelStack.top()) { case MSTATESET: // Just drop into MAPDEF case MAPDEF: { if(lineType == SETPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); if(isLastWord) sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::NUM, TempProperty(currentProp, linesToParse[i][j].second))); else throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); } else if(lineType == SETDYNPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::NUM, TempProperty(currentProp, linesToParse[i][j].second))); } else if(lineType == SETITEMLIST) { if(priorWord == OPEN_PARA) sItem.amt = atoi(linesToParse[i][j].second.c_str()); else throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemlist'.", linesToParse[i]); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); } break; case ITEMDEF: { if(lineType == SETPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); if(isLastWord) sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::NUM, TempProperty(currentProp, linesToParse[i][j].second))); else throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); } else if(lineType == SETDYNPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::NUM, TempProperty(currentProp, linesToParse[i][j].second))); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); } break; case IMDYNSET: { if(lineType == DYNSETPROP) { if(priorWord != CLOSE_BRACKET) throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); if(isLastWord) sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::NUM, TempProperty(currentDynProp, linesToParse[i][j].second))); else throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); } break; case MITEMLISTSET: { if(priorWord == OPEN_PARA) { if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemlist'.", linesToParse[i]); sItem.amt = atoi(linesToParse[i][j].second.c_str()); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); } break; default: throw xSyntaxError(i, itsFileName, "Unexpected usage of numconst.", linesToParse[i]); } } break; case TEXTCONST: { switch(levelStack.top()) { case MSTATESET: // Just drop into MAPDEF case MAPDEF: { if(lineType == SETPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); if(isLastWord) sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::TEXT, TempProperty(currentProp, linesToParse[i][j].second))); else throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); } else if(lineType == SETNAME) { if(priorWord != NAME) throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); if(isLastWord) sInfo.name = linesToParse[i][j].second; else throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); } else if(lineType == SETDESC) { if(priorWord != DESC) throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); if(isLastWord) sInfo.desc = linesToParse[i][j].second; else throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); } else if(lineType == SETITEMDTAG) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); if(isLastWord) sDTag.desc = linesToParse[i][j].second; } else if(lineType == SETDYNPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::TEXT, TempProperty(currentProp, linesToParse[i][j].second))); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); } break; case ITEMDEF: { if(lineType == SETPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); if(isLastWord) sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::TEXT, TempProperty(currentProp, linesToParse[i][j].second))); else throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); } else if(lineType == SETNAME) { if(priorWord != NAME) throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); if(isLastWord) sInfo.name = linesToParse[i][j].second; else throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); } else if(lineType == SETDESC) { if(priorWord != DESC) throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); if(isLastWord) sInfo.desc = linesToParse[i][j].second; else throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); } else if(lineType == SETDYNPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::TEXT, TempProperty(currentProp, linesToParse[i][j].second))); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); } break; case IMDYNSET: { if(lineType == DYNSETPROP) { if(priorWord != CLOSE_BRACKET) throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); if(isLastWord) sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::TEXT, TempProperty(currentDynProp, linesToParse[i][j].second))); else throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); } break; default: throw xSyntaxError(i, itsFileName, "Unexpected usage of textconst.", linesToParse[i]); } } break; case BOOLCONST: { switch(levelStack.top()) { case MSTATESET: // Just drop into MAPDEF case MAPDEF: { if(lineType == SETPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); if(isLastWord) sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::BOOL, TempProperty(currentProp, linesToParse[i][j].second))); else throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); } else if(lineType == SETDYNPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::BOOL, TempProperty(currentProp, linesToParse[i][j].second))); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); } break; case ITEMDEF: { if(lineType == SETPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); if(isLastWord) sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::BOOL, TempProperty(currentProp, linesToParse[i][j].second))); else throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); } else if(lineType == SETDYNPROP) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::BOOL, TempProperty(currentProp, linesToParse[i][j].second))); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); } break; case IMDYNSET: { if(lineType == DYNSETPROP) { if(priorWord != CLOSE_BRACKET) throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); if(isLastWord) sInfo.propList.insert(std::pair<GlobalTypeEnum,TempProperty>(GlobalTypeEnum::BOOL, TempProperty(currentDynProp, linesToParse[i][j].second))); else throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); } break; default: throw xSyntaxError(i, itsFileName, "Unexpected usage of boolconst.", linesToParse[i]); } } break; case OPEN_PARA: { if(levelStack.top() == MAPDEF || levelStack.top() == ITEMDEF) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of '('.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemlist'.", linesToParse[i]); } else if(levelStack.top() == MITEMLISTSET) { if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of '('.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set itemlist'.", linesToParse[i]); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of '('.", linesToParse[i]); } break; case CLOSE_PARA: { if(levelStack.top() == MAPDEF || levelStack.top() == ITEMDEF) { if(priorWord != NUMCONST) throw xSyntaxError(i, itsFileName, "Unexpected usage of ')'.", linesToParse[i]); } else if(levelStack.top() == MITEMLISTSET) { if(priorWord != NUMCONST) throw xSyntaxError(i, itsFileName, "Unexpected usage of ')'.", linesToParse[i]); if(isLastWord) { sInfo.itemList.push_back(sItem); sItem.Zero(); } } else throw xSyntaxError(i, itsFileName, "Unexpected usage of ')'.", linesToParse[i]); } break; case COMMA: { if(levelStack.top() != MSTATESET && levelStack.top() != MAPDEF || lineType != SETITEMLIST) throw xSyntaxError(i, itsFileName, "Unexpected usage of ','.", linesToParse[i]); if(priorWord != CLOSE_PARA && priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of ','.", linesToParse[i]); sInfo.itemList.push_back(sItem); sItem.Zero(); } break; case PERIOD: { if(lineType != SETDYNMODULE && lineType != SETMODULE) throw xSyntaxError(i, itsFileName, "Unexpected usage of '.'.", linesToParse[i]); if(priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of '.'.", linesToParse[i]); if(isLastWord && lineType == SETDYNMODULE) throw xSyntaxError(i, itsFileName, "Unexpected of call for 'set dynamic'.", linesToParse[i]); if(isLastWord && lineType == SETMODULE) throw xSyntaxError(i, itsFileName, "Unexpected of call for 'set'.", linesToParse[i]); } break; case COLON: { if(!isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected usage of ':'.", linesToParse[i]); if(sInfo.objType == MAPDEF) levelStack.push(MAPDEF); else if(sInfo.objType == ITEMDEF) levelStack.push(ITEMDEF); else if(sInfo.objType == NONE) { if(lineType == SETDYNPROP) levelStack.push(IMDYNSET); else if(lineType == SETITEMLIST) { if(!sInfo.itemList.empty()) throw xSyntaxError(i, itsFileName, "Itemlist is already inline! Cannot go into 'set' block.", linesToParse[i]); levelStack.push(MITEMLISTSET); } else if(lineType == SETSTATE) levelStack.push(MSTATESET); } else throw xSyntaxError(i, itsFileName, "Unexpected usage of ':'.", linesToParse[i]); } break; case OPEN_BRACKET: { if(levelStack.top() != IMDYNSET) throw xSyntaxError(i, itsFileName, "Unexpected usage of '['.", linesToParse[i]); if(lineType != DYNSET || priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of '['.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set dynamic'.", linesToParse[i]); } break; case CLOSE_BRACKET: { if(levelStack.top() != IMDYNSET) throw xSyntaxError(i, itsFileName, "Unexpected usage of ']'.", linesToParse[i]); if(lineType != DYNSETPROP || priorWord != IDENTIFIER) throw xSyntaxError(i, itsFileName, "Unexpected usage of ']'.", linesToParse[i]); if(isLastWord) throw xSyntaxError(i, itsFileName, "Unexpected end of call for 'set dynamic'.", linesToParse[i]); } break; default: throw xSyntaxError(i, itsFileName, "Unknown lexeme usage!", linesToParse[i]); } // Set this as the prior word for the next loop priorWord = linesToParse[i][j].first; } } return; } // Function to compress variable length arguments (arguments using operators such as +) vector<GameContainer::PItemDTagHelper> PorkParser::CompressArgs(vector<TokenPair> *lineToCompress) { PKeyword lvalue; // The type of the lvalue of plus vector<GameContainer::PItemDTagHelper> funcList; // Compress intrinsic functions into one value for(UINT i=0; i<lineToCompress->size(); i++) { // PItemDTagHelper struct represents our intrinsic function GameContainer::PItemDTagHelper tempHelper; // UINTs used to mark the start and end of an intrinsic function for removal from line UINT startOfFunc=0, endOfFunc=0; // If an intrinsic function is found, set its name and get args if(lineToCompress->at(i).first == P || lineToCompress->at(i).first == CURITEMAMT) { tempHelper.name = ConvertPKeywordToString(lineToCompress->at(i).first); startOfFunc = i; i++; // Next lexeme if(lineToCompress->at(i).first != OPEN_PARA) throw xSyntaxError(*itsCurrentLine, itsFileName, "Missing '(' after intrinsic function name.", *lineToCompress); i++; // Pick up each argument (and ensure they are comma seperated). Stop once we reach a ')' bool usedComma = true; while(lineToCompress->at(i).first != CLOSE_PARA) { if(lineToCompress->at(i).first == COMMA) { if(usedComma == true) throw xSyntaxError(*itsCurrentLine, itsFileName, "Comma used after another comma.", *lineToCompress); else usedComma = true; } else if(lineToCompress->at(i).first == TEXTCONST) { if(usedComma == false) throw xSyntaxError(*itsCurrentLine, itsFileName, "Missing comma before new argument.", *lineToCompress); else tempHelper.args.push_back(lineToCompress->at(i).second); } else throw xSyntaxError(*itsCurrentLine, itsFileName, "Unexpected characters used in function call.", *lineToCompress); i++; } endOfFunc = i; // Erase the function call and replace with an empty TEXTCONST vector<TokenPair>::iterator bIt = lineToCompress->begin(), eIt = lineToCompress->begin(); bIt += startOfFunc; eIt += endOfFunc; lineToCompress->erase(bIt, eIt); lineToCompress->insert(bIt, TokenPair(TEXTCONST, "")); // Check the intrinsic function for correctness (exceptions will handle errors within the function) FunctionCheck(tempHelper, lineToCompress); funcList.push_back(tempHelper); } } UINT funcNum = 0; // Used to keep track of how many functions have been concatenated (for pos) // Concatenate all the added values into one, after this the function is finished for(UINT i=0; i<lineToCompress->size(); i++) { if(lineToCompress->at(i).first == PLUS) { if(lineToCompress->at(i-1).first == TEXTCONST) lvalue = TEXTCONST; else if(lineToCompress->at(i-1).first == NUMCONST) lvalue = NUMCONST; else if(lineToCompress->at(i-1).first == BOOLCONST) lvalue = BOOLCONST; else throw xSyntaxError(*itsCurrentLine, itsFileName, "Invalid type as lvalue for + operator!", *lineToCompress); } else continue; if(lineToCompress->at(i+1).first != lvalue) throw xSyntaxError(*itsCurrentLine, itsFileName, "rvalue of + operator does not match the lvalue!", *lineToCompress); else { // Create an iterator at the rvalue's position for removal vector<TokenPair>::iterator it = lineToCompress->begin()+i; // The rvalue is an intrinsic function, we want the position here, so get the length of the lvalue if(lineToCompress->at(i+1).second.empty()) { if(funcNum > funcList.size()) throw xSyntaxError(*itsCurrentLine, itsFileName, "Concatenation of empty string detected.", *lineToCompress); funcList[funcNum].pos = lineToCompress->at(i-1).second.length(); funcNum++; } lineToCompress->at(i-1).second += lineToCompress->at(i+1).second; lineToCompress->erase(it+1); // Remove the rvalue lineToCompress->erase(it); // Remove the + } } return funcList; } void PorkParser::FunctionCheck(GameContainer::PItemDTagHelper theFunc, vector<TokenPair> *lineOfFunc) { if(theFunc.name == "p") { if(theFunc.args.size() != 1 && theFunc.args.size() != 2) throw xSyntaxError(*itsCurrentLine, itsFileName, "Incorrect number of arguments for p(). p() takes either 1 or 2 args.", *lineOfFunc); } else if(theFunc.name == "curItemAmt") { if(theFunc.args.size() != 0) throw xSyntaxError(*itsCurrentLine, itsFileName, "Incorrect number of arguments for curItemAmt(). curItemAmt() takes no args.", *lineOfFunc); } else throw xSyntaxError(*itsCurrentLine, itsFileName, theFunc.name + " is not a function!", *lineOfFunc); return; } void PorkParser::PreparePython(string scriptName) { // Use PorkPy to import module, get temporary identifier information // for ident-check later on. Upon import, each python script referenced is compiled // along with any libraries said module may have imported. // In theory, all python files should be compiled in this manner, and all .pyc // files will then be loaded into .zip/.7z/.lmza archive along with serialized GC // with AES encyption (maybe). } void PorkParser::InsertItemDef(TempParseInfo *sInfo) { // Create with basic properties theGameContainer.CreatePItem(sInfo->identifier, sInfo->name, sInfo->desc); // Property list multimap<GlobalTypeEnum, TempProperty>::iterator it = sInfo->propList.begin(); for(UINT i=0;i<sInfo->propList.size();i++,it++) { theGameContainer.GetPItem(sInfo->identifier)->SetCustomProp(it->second.first.second, it->second.second, it->second.first.first, it->first); } // Dynamic properties here return; } void PorkParser::InsertMapDef(TempParseInfo *sInfo) { // Create with basic properties theGameContainer.CreatePMap(sInfo->identifier, sInfo->name, sInfo->desc); // Property list multimap<GlobalTypeEnum, TempProperty>::iterator it = sInfo->propList.begin(); for(UINT i=0;i<sInfo->propList.size();i++,it++) { theGameContainer.GetPMap(sInfo->identifier)->SetCustomProp(it->second.first.second, it->second.second, it->second.first.first, it->first); } // Dynamic properties // Item list for(UINT i=0;i<sInfo->itemList.size();i++) { TempMItemListInfo temp = sInfo->itemList[i]; theGameContainer.GetPMap(sInfo->identifier)->AddItem(temp.name, temp.amt, temp.reliesOn, temp.from, temp.condition); } // ItemDTags for(UINT i=0;i<sInfo->itemDTagList.size();i++) { TempMItemDTagInfo temp = sInfo->itemDTagList[i]; theGameContainer.GetPMap(sInfo->identifier)->AddItemDTag(temp.forItem, temp.desc); for(UINT j=0;j<temp.dynPieces.size();j++) { theGameContainer.GetPMap(sInfo->identifier)->GetItemDTag(temp.forItem).AddDynPiece(temp.dynPieces[j]); } } // States for(UINT i=0;i<sInfo->stateList.size();i++) { TempMStateInfo temps = sInfo->stateList[i]; // Create state with basic properties theGameContainer.GetPMap(sInfo->identifier)->AddState(temps.identifier, temps.name, temps.desc, temps.isDefinitive, temps.trigger); GameContainer::PState* state = theGameContainer.GetPMap(sInfo->identifier)->GetState(temps.identifier); // Property list multimap<GlobalTypeEnum, TempProperty>::iterator it = temps.propList.begin(); for(UINT j=0;j<sInfo->propList.size();j++,it++) { state->SetCustomProp(it->second.first.second, it->second.second, it->second.first.first, it->first); } // Dynamic properties // Item list for(UINT j=0;j<sInfo->itemList.size();j++) { TempMItemListInfo temp = temps.itemList[j]; state->AddItem(temp.name, temp.amt, temp.reliesOn, temp.from, temp.condition); } // ItemDTags for(UINT j=0;j<sInfo->itemDTagList.size();j++) { TempMItemDTagInfo temp = temps.itemDTagList[j]; state->AddItemDTag(temp.forItem, temp.desc); for(UINT k=0;k<temp.dynPieces.size();k++) { state->GetItemDTag(temp.forItem).AddDynPiece(temp.dynPieces[k]); } } } return; } // Function that takes the string word and takes it into a token // If the token also needs a value, that value is added to TokenPair TokenPair PorkParser::Tokenize(string slice) { // Make a list of numbers to check against (0-9) set<char> numList; for(char i=0x30;i<=0x39;i++) numList.insert(i); bool isNumConst = false; if(slice == "requires") return TokenPair(REQUIRES, ""); else if(slice == "def") return TokenPair(DEF, ""); else if(slice == "set") return TokenPair(SET, ""); else if(slice == "edef") return TokenPair(EDEF, ""); else if(slice == "dynamic") return TokenPair(DYNAMIC, ""); else if(slice == "default") return TokenPair(DEFAULT, ""); else if(slice == "state") return TokenPair(STATE, ""); else if(slice == "true") return TokenPair(BOOLCONST, "true"); else if(slice == "false") return TokenPair(BOOLCONST, "false"); else if(slice == "eset") return TokenPair(ESET, ""); else if(slice == "reliesOn") return TokenPair(RELIESON, ""); else if(slice == "from") return TokenPair(FROM, ""); else if(slice == "trigger") return TokenPair(TRIGGER, ""); else if(slice == "present") return TokenPair(PRESENT, ""); else if(slice == "n_present") return TokenPair(N_PRESENT, ""); else if(slice == "inf") return TokenPair(INF, ""); else if(slice == "for") return TokenPair(FOR, ""); else if(slice == "definitive") return TokenPair(DEFINITIVE, ""); else if(slice == "name") return TokenPair(NAME, ""); else if(slice == "desc") return TokenPair(DESC, ""); else if(slice == "map") return TokenPair(MAP, ""); else if(slice == "item") return TokenPair(ITEM, ""); else if(slice == "itemlist") return TokenPair(ITEMLIST, ""); else if(slice == "itemDTag") return TokenPair(ITEMDTAG, ""); else if(slice == "p") return TokenPair(P, ""); else if(slice == "curItemAmt") return TokenPair(CURITEMAMT, ""); else if(slice == "\"") return TokenPair(QUOTE, ""); else if(slice == "(") return TokenPair(OPEN_PARA, ""); else if(slice == ")") return TokenPair(CLOSE_PARA, ""); else if(slice == ",") return TokenPair(COMMA, ""); else if(slice == ".") return TokenPair(PERIOD, ""); else if(slice == ":") return TokenPair(COLON, ""); else if(slice == "[") return TokenPair(OPEN_BRACKET, ""); else if(slice == "]") return TokenPair(CLOSE_BRACKET, ""); else if(slice == "+") return TokenPair(PLUS, ""); else { // This is a text constant if(slice.front() == '"' && slice.back() == '"') { // Also strip the quotes off slice.erase(slice.begin()); slice.erase(slice.end()); return TokenPair(TEXTCONST, slice); } else { // Not an textconst, so try numconst -- we must check if num isNumConst = true; // Assume it is a numconst until proven wrong string::iterator sIt = slice.begin(); for(UINT i = 0; i<slice.length(); i++, sIt++) { // This char is NOT a number, therefore it is not a num const if(numList.count(*sIt) != 1) { isNumConst = false; break; } } if(isNumConst) return TokenPair(NUMCONST, slice); else // Not any type of known constant, assume identifier return TokenPair(IDENTIFIER, slice); } } // No appropiate match found, throw error throw xLexicalError(*itsCurrentLine, itsFileName, slice+string(" is not a token!") ); } #pragma warning(pop)
#include <iostream> using namespace std; struct Line{ int n; int *a; }; /*Вариант 16 Из входного потока вводится непрямоугольная матрица целых чисел [aij], i=1,…,m, j=1,…,n. Значения m и n заранее не известны и вводятся из входного потока. Сформировать вектор {bi}, i=1,…,m, i-ый элемент которого равен сумме тех элементов i-ой строки матрицы, которые превышают соответствующий элемент предыдущей (i-1)-ой строки. Для первой строки матрицы в качестве предыдущей использовать последнюю строку матрицы. Исходную матрицу и полученный вектор вывести в выходной поток с необходимыми комментариями.*/ int input(Line *&a); //массив структур, возвращает количество строк матрицы void erase(Line *&a, int m); //очищение памяти матрицы void form_new(Line *lines, int m, int *&s); //формирование вектора int sum(int a[], int n, int b[], int m); void output(Line *lines, int m, char mes_m[], int *s, char mes_v[]); //вывод int main(){ Line *arr=NULL; int *s=NULL; int m; //Пока количество строк больше нуля while ((m = input(arr))){ form_new(arr,m,s); output(arr, m, "Source matrix: ", s, "Result vector: "); erase(arr, m); delete []s; } cin >> m; return 0; } int input(Line *&lines){ const char *pr=""; int m; //количество строк //Начало: ввод количества строк do{ cout << pr << endl; cout << "Enter number of lines: "; pr = "You are wrong; repeat, please!"; cin >> m; }while(m<0); //Конец: ввод количества строк lines = new Line[m]; for(int i = 0; i<m; i++){ pr = ""; //Начало: ввод количества столбцов для строки i do{ cout << pr << endl; cout << "Enter number of dems in line " << (i+1) << ": "; pr = "You are wrong; repeat, please!"; cin >> lines[i].n; }while(lines[i].n<1); //Конец: ввод количества столбцов для строки i lines[i].a = new int[lines[i].n]; cout << "Enter " << lines[i].n << " numbers: "; //Начало: ввод n чисел для строки i for(int j = 0; j<lines[i].n; j++) cin >> lines[i].a[j]; //Конец: ввод n чисел для строки i } return m; } void erase(Line *&lines, int m){ for(int i = 0; i<m; i++) delete []lines[i].a; delete []lines; lines = NULL; } void form_new(Line *lines, int m, int *&s){ s = new int[m]; //Начало: обработка первой и последней строки отдельно s[0] = sum(lines[0].a, lines[0].n, lines[m-1].a, lines[m-1].n); //Конец: обработка первой и последней строки отдельно //Начало: обработка второй и последующих строк for(int i = 1; i<m; i++) s[i] = sum(lines[i].a, lines[i].n, lines[i-1].a, lines[m-1].n); //Конец: обработка второй и последующих строк } int sum(int a[], int n, int b[], int m){ int s=0; //Начало: сложение чисел в строке for(int i = 0; i<n; i++) //Если есть с чем сравнивать if (i<m){ if(a[i]>b[i]) s = s+a[i]; } else s = s+a[i]; //Конец: сложение чисел в строке return s; } void output(Line *lines, int m, char mes_m[], int *s, char mes_v[]){ //Начало: вывод матрицы cout << mes_m << endl; for(int j = 0; j<m; j++){ cout << j << '\t'; for(int k = 0; k<lines[j].n; k++) cout << lines[j].a[k] << ' '; cout << endl; } //Конец: вывод матрицы //Начало: вывод вектора cout << mes_v << endl; for(int i = 0; i<m; i++) cout << s[i] << ' '; //Конец: вывод вектора }
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; const int lin=3; const int col=4; int num[lin][col]; void ingreso (int num[lin][col]){ srand(time(0)); for (int l=0;l<lin;l++) { for (int c=0;c<(col-1);c++) { num[l][c]= 1 + rand() %(100-1); } } } void numMayor(int num[][col]){ int ul=col-1; for (int l=0;l<lin;l++) { int mayor=0; for (int c=0;c<col-1;c++) { if((num[l][c])>num[l][ul]) { (num[l][ul])=num[l][c]; } } } } void Presentar (int num[lin][col]){ for (int l=0;l<lin;l++) { for (int c=0;c<col;c++) { cout<<num[l][c]<<" "; } cout<<"\n"; } } int main() { ingreso(num); numMayor(num); Presentar(num); }
// -*- C++ -*- // // Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory, // Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC // // This file is part of FreePOOMA. // // FreePOOMA is free software; you can redistribute it and/or modify it // under the terms of the Expat license. // // 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 Expat // license for more details. // // You should have received a copy of the Expat license along with // FreePOOMA; see the file LICENSE. // //----------------------------------------------------------------------------- // Functions: // makeUniformGrid utility function (in anonymous namespace - not global) // DynamicLayout non-inline non-template member function definitions. //----------------------------------------------------------------------------- #include "Layout/DynamicLayout.h" #include "Domain/Contains.h" #include "Domain/Grid.h" #include "Partition/UniformGridPartition.h" #include "Partition/GridPartition.h" #include "Utilities/PAssert.h" // For multiple-context synchronization: #include "PETE/PETE.h" // for OpSumAssign #include "Tulip/ReduceOverContexts.h" #include "Tulip/PatchSizeSyncer.h" #include <iostream> //============================================================ // Utility functions //============================================================ //----------------------------------------------------------------------------- // // Grid<1> <anonymous>::makeUniformGrid(const Interval<1> gdom, int nblocks) // // Utility function that constructs a near-uniform patch decomposition // of the domain gdom, having nblocks subdomains. The decomposition is // returned as a Grid<1> object. This Grid object is not used as a // "domain" per se. Rather, we use its blockIterator to generate the // patches that tile the global domain. This difference is important // to note since the blockIterator patches are Interval<1>(p1,p2-1), // where p1 and p2 are adjacent points in the domain. Thus, we must // construct a grid-object whose upper end point is one more than the // last point of the input domain. That is, if we are subdividing the // interval [0,19] into two blocks of 10 elements, then we want the // Grid's patch iterator to return [0,9] and [10,19]. This requires a // Grid with the points [0,10,20]. // //----------------------------------------------------------------------------- namespace { // anonymous - local linkage only Grid<1> makeUniformGrid(const Interval<1> &gdom, int nblocks) { PAssert(!gdom.empty()); // First calculate the approximate block size and the remainder. long blocksize = gdom.size() / nblocks; long remainder = gdom.size() % nblocks; if (remainder == 0) { // If the remainder is zero, then we can construct a completely // uniform grid, which can be done by constucting it with a Range // object (having one extra point). Range<1> ret(gdom.first(), gdom.last() + 1, blocksize); return Grid<1>(ret); } else { // If the remainder is non-zero, we make the last "remainder" // sub-blocks one element longer than the rest. IndirectionList<int> vertexlist(nblocks + 1); int j; vertexlist(0) = gdom.first(); for (j = 1; j < nblocks + 1 - remainder; ++j) { vertexlist(j) = vertexlist(j-1) + blocksize; } for (j = nblocks + 1 - remainder; j < nblocks + 1; ++j) { vertexlist(j) = vertexlist(j-1) + blocksize + 1; } PAssert(vertexlist(nblocks) == gdom.last() + 1); return Grid<1>(vertexlist); } } } // close anonymous namespace //============================================================ // DynamicLayoutData non-inline non-template method definitions //============================================================ //----------------------------------------------------------------------------- // // DynamicLayoutData::DynamicLayoutData() // // Default constructor for DynamicLayoutData. Initializes this object // to look like an "empty" layout, with no patches and an empty domain. // The "initialize" method can be used to complete the initialization. // //----------------------------------------------------------------------------- DynamicLayoutData::DynamicLayoutData() : Observable_t(*this), ID_m(Unique::get()), dirtyLayout_m(true) { } //----------------------------------------------------------------------------- // // DynamicLayoutData::~DynamicLayoutData() // // Destructor for DynamicLayoutData. This removes all the nodes and // then the Observable destructor will tell all users of this layout that // it is going away. // //----------------------------------------------------------------------------- DynamicLayoutData::~DynamicLayoutData() { // Delete existing nodes and clear all the lists. for (int i = 0; i < all_m.size(); ++i) delete all_m[i]; all_m.clear(); local_m.clear(); remote_m.clear(); } //----------------------------------------------------------------------------- // // Create new elements by extending the current domain of the specified // local patch by the requested number of elements. 'local' means on // this same context. The patch is referred to by a local index, // from 0 ... # local patches - 1. If patch=-1, create elements in the // last local patch. // // All observers are notified of the change, then we change our // domain value. // //----------------------------------------------------------------------------- void DynamicLayoutData::create(CreateSize_t num, PatchID_t patch) { PAssert(num >= 0); if (num == 0) return; // If the patch number is < 0, change it to the last local patch. if (patch < 0) patch = local_m.size() - 1; PAssert(patch < local_m.size()); // Let all users know of the create request. notify(CreateEvent(num, patch)); // Modify the domain for this local patch. When sync is called, // everything else will get updated. addElements(local_m[patch]->domain(), num); // Note that we will need to rebuild things. dirtyLayout_m = true; } //----------------------------------------------------------------------------- // // Perform a "multiple patch" copy, using a list of IndirectionList's // for a set of source patches, and an IndirectionList giving the // patch ID for the source patches. Copy data into the destination // patch. The source and desination patches must be specified, this // is only for "zero-based" index lists. If the last argument is // true, storage is created at the end, otherwise elements are // just copied to the end of the existing storage. // //----------------------------------------------------------------------------- void DynamicLayoutData:: copy(const IndirectionList<IndirectionList<int> > &lists, const IndirectionList<int> &fromlist, PatchID_t toPatch, bool docreate) { // If the toPatch number is < 0, change it to the last local patch. // Is this really a useful default??? if (toPatch < 0) toPatch = local_m.size() - 1; PAssert(toPatch < local_m.size()); // Let all users know of the copy request. notify(CopyPatchEvent(lists, fromlist, toPatch, docreate)); // Modify the domain for this local patch. When sync is called, // everything else will get updated. // Why is there a bool??? Why not just figure out if new allocation // is needed and if so, do it, if not, don't. (JAC) if (docreate) { int np = lists.size(); int created = 0; for (int i = 0; i < np; ++i) created += lists(i).size(); addElements(local_m[toPatch]->domain(), created); // Note that we will need to rebuild things. dirtyLayout_m = true; } } //----------------------------------------------------------------------------- // // Sync up the layout with any other contexts, taking into account // that other contexts may have performed create/destroy operations. // This will reset all the local domains to be properly contiguous, // and let all engine's using this layout reset their domains. // // The multiple-context stuff is done by syncGlobalDomains below. // //----------------------------------------------------------------------------- void DynamicLayoutData::sync() { int nContexts = Pooma::contexts(); // First check if the layout is (globally) dirty or not. if (nContexts == 1) // no communication required { if (!initialized() || !dirty()) return; } else { typedef ReduceOverContexts<int, OpAddAssign> GlobalSum_t; // Do a global reduction on the initialized and dirty flags int globalInitialized; GlobalSum_t(int(initialized())).broadcast(globalInitialized); // They'd better either all be initialized or not. PAssert(globalInitialized == 0 || globalInitialized == nContexts); if (globalInitialized == 0) return; int globalDirty; GlobalSum_t(int(dirty())).broadcast(globalDirty); if (globalDirty == 0) return; } // Recalculate and renumber the domains. If we are multi-context, // this does the global calculations to fix the global decomposition // of the current total domain. calcDomains(); // Recalculate the domain maps, if necessary. We need to do this // now since we'll need to call globalID() routines from threads in // later operations ... the alternative is to make checking and rebuilding // of the domain maps a mutually-exclusive operation. calcMaps(); // The domains & maps are up-to-date, so clear our dirty flag. dirtyLayout_m = false; // Notify all the users that they can sync up their patches. notify(SyncEvent()); } void DynamicLayoutData::syncGlobalDomains() { // First we build a Grid<1> object that represents the local // patches. The points in this Grid are the "first" points // for every subdomain, plus one past the last point of the // last subdomain (consecutive pairs of points can be considered // as begin-end pairs defining half open "intervals" in the // STL sense). We return the total number of elements. int nlocal = local_m.size(); IndirectionList<int> lgdata(nlocal+1); // Since we're not guaranteed that there are *any* local elements, // we construct a Grid that is zero-based and let the PatchSizeSyncer // figure out the final domains based on context ordering. long pos = 0; for (int i = 0; i < nlocal; ++i) { lgdata(i) = pos; pos += local_m[i]->domain().size(); } lgdata(nlocal) = pos; Grid<1> localGrid(lgdata); // Now initialize a PatchSizeSyncer object with the local data // and call the calcGlobalGrid method to do the communication // and return a global Grid object that represents the // global patch decomposition. Grid<1> globalGrid; Context_t myContext = Pooma::context(); Pooma::PatchSizeSyncer(myContext,localGrid).calcGlobalGrid(globalGrid); // The number of patches in a dynamic layout is fixed, so the number // of points in this grid had better match the number of patches // (+1). PAssert(globalGrid.size() == all_m.size() + 1); PAssert(domain_m.empty() || globalGrid.first() == domain_m.first()); // Finally, use the consecutive points in the Grid to reset the // domains for all of our Nodes. This loop relies on the global // patch ordering being such that their subdomains are contiguous. // Note the special handling for empty patches. // JCC: The assumption about Node ordering of the original code here // does not work in general. Instead, I am assuming that the global // Grid information is ordered by context. Thus we have domains for // all of the Nodes on context 0, followed by domains for all the // Nodes on context 1, etc. This ordering is independent of the // partitioning scheme or context mapper used. // Later we should add a map between the node ordering in the all_m // node list and the ordering based on context number for efficiency. Context_t numContexts = Pooma::contexts(); PatchID_t numNodes = all_m.size(); int c, i, j = 0; for (c = 0; c < numContexts; ++c) { for (i = 0; i < numNodes; ++i) { if (all_m[i]->context() == c) { int begin = globalGrid(j); int end = globalGrid(j+1); PAssert(begin <= end); Domain_t dom = Pooma::NoInit(); if (begin < end) dom = Domain_t(begin, end - 1); // [begin,end) domain else dom = Domain_t(); // empty domain all_m[i]->setDomain(dom); all_m[i]->setAllocated(dom); j++; } } } int begin = globalGrid.first(); int end = globalGrid.last(); if (begin < end) domain_m = Domain_t(begin, end - 1); else domain_m = Domain_t(); } //----------------------------------------------------------------------------- // // void DynamicLayoutData::calcDomains() // // Calculates the total domain of each patch and this total layout, since // this can change due to dynamic operations. // //----------------------------------------------------------------------------- void DynamicLayoutData::calcDomains() { // This does not check the dirty flag - that should be done prior // to calling this. Wasn't a big deal for single-context stuff, but // now this is a global reduction, so try to only do it once. // We scan through the local domains, and adjust their starting // offsets to be contiguous. We will start everyone off at // domain_m.first(). This way we can skip recalculating the domains // if we're on a single context. If we're on multiple contexts, it // doesn't matter what the set of local domains start with prior to // calling syncGlobalDomains(). int first = domain_m.first(); CreateSize_t pos = first, len = 0; for (int i = 0; i < local_m.size(); ++i) { Domain_t dom = local_m[i]->domain(); len = dom.length(); if (len > 0) { dom = Domain_t(pos, pos + len - 1); pos += len; } // Give this new domain to the Node ... it will have the same // size, but a possibly different initial offset. local_m[i]->setDomain(dom); local_m[i]->setAllocated(dom); } // Update the remote and total domains... // Add a check here for a replicated mapping of Nodes. // In this case, no global synchronization is needed. if (Pooma::contexts() > 1 && all_m[0]->context() != -1) { syncGlobalDomains(); } else { // Just update the total domain. if (pos == first) domain_m = Domain_t(); else domain_m = Interval<1>(first, pos - 1); } } //----------------------------------------------------------------------------- // // void DynamicLayoutData::calcMaps() // // Calculates the DomainMaps's for this object, based on the current // settings for the blocks, since this can change due to dynamic operations. // //----------------------------------------------------------------------------- void DynamicLayoutData::calcMaps() const { // Initialize the map... // Clear out any existing info map_m.zap(); // If this is empty, there is nothing to do. if (!domain_m.empty()) { // Initialize the map and then add each non-empty subdomain // to the map along with its global ID. map_m.initialize(domain_m); for (int j = 0; j < all_m.size(); ++j) { const Interval<1> &blockDom = all_m[j]->domain(); PAssert(j == all_m[j]->globalID()); if (!blockDom.empty()) { typedef DomainMap<Interval<1>,int>::Value_t Val_t; map_m.insert(Val_t(blockDom, j)); } } // Update the DomainMap map_m.update(); } } //----------------------------------------------------------------------------- // // globalID takes a position within the domain of the layout, and returns // the global ID for that node. // //----------------------------------------------------------------------------- int DynamicLayoutData::globalID(const Loc<1> &loc) const { PAssert(!dirtyLayout_m); // Make sure the point is in our domain. PAssert(contains(domain_m, loc)); // Find the position of the point. typedef DomainMapTouchIterator<Interval<1>,int> MapIterator_t; MapIterator_t dmti = (map_m.touch(Interval<1>(loc))).first; PAssert(dmti != MapIterator_t()); // Default constructor produces end iterator // Return the offset (dmti dereferences to an int, which is the globalID): return *dmti; } int DynamicLayoutData::globalID(int i0) const { // Call the Loc version. return globalID(Loc<1>(i0)); } //============================================================ // DynamicLayout non-inline non-template method definitions //============================================================ //----------------------------------------------------------------------------- // // Constructors and initialize methods // // See comments in the class definition (in DynamicLayout.h) // //----------------------------------------------------------------------------- DynamicLayout::DynamicLayout() : Observable<This_t>(*this), pdata_m(new LayoutData_t()) { pdata_m->attach(*this); } DynamicLayout::DynamicLayout(const Domain_t &gdom) : Observable<This_t>(*this), pdata_m( new LayoutData_t( gdom, GridPartition<1>(), UniformMapper() ) ) { pdata_m->attach(*this); } DynamicLayout::DynamicLayout(const Domain_t &gdom, int blocks) : Observable<This_t>(*this) { UniformMapper cmap(blocks); if (!gdom.empty()) { Grid<1> grid = makeUniformGrid(gdom,blocks); GridPartition<1> gpar(grid); pdata_m = new LayoutData_t(gdom, gpar, cmap); } else { Loc<1> decomp(blocks); GridPartition<1> gpar(decomp); pdata_m = new LayoutData_t(gdom, gpar, cmap); } pdata_m->attach(*this); } DynamicLayout::DynamicLayout(const Grid<1> &grid) : Observable<This_t>(*this) { Domain_t gdom(grid.first(),grid.last()-1); GridPartition<1> gpar(grid); UniformMapper cmap(gpar); pdata_m = new LayoutData_t(gdom, gpar, cmap); pdata_m->attach(*this); } DynamicLayout::DynamicLayout(const This_t &model) : Observable<This_t>(*this), pdata_m(model.pdata_m) { pdata_m->attach(*this); } //----------------------------------------------------------------------------- // // assignment operator for DynamicLayout // //----------------------------------------------------------------------------- DynamicLayout &DynamicLayout::operator=(const This_t &model) { if (this != &model) { pdata_m->detach(*this); pdata_m = model.pdata_m; pdata_m->attach(*this); } return *this; } //----------------------------------------------------------------------------- // // Initialize methods for DynamicLayout // //----------------------------------------------------------------------------- void DynamicLayout::initialize(const Domain_t &gdom) { pdata_m->initialize(gdom, GridPartition<1>(), UniformMapper()); } void DynamicLayout::initialize(const Domain_t &gdom, int blocks) { UniformMapper cmap(blocks); if (!gdom.empty()) { Grid<1> grid = makeUniformGrid(gdom,blocks); GridPartition<1> gpar(grid); pdata_m->initialize(gdom, gpar, cmap); } else { Loc<1> decomp(blocks); GridPartition<1> gpar(decomp); pdata_m->initialize(gdom, gpar, cmap); } } void DynamicLayout::initialize(const Domain_t &gdom, const Grid<1> &grid) { GridPartition<1> gpar(grid); UniformMapper cmap(gpar); pdata_m->initialize(gdom, gpar, cmap); } void DynamicLayout::initialize(const Grid<1> &grid) { Domain_t gdom(grid.first(),grid.last()-1); GridPartition<1> gpar(grid); UniformMapper cmap(gpar); pdata_m->initialize(gdom, gpar, cmap); } //----------------------------------------------------------------------------- // // Ostream inserter definitions... // //----------------------------------------------------------------------------- std::ostream &operator<<(std::ostream &ostr, const DynamicLayout &layout) { layout.print(ostr); return ostr; } std::ostream &operator<<(std::ostream &ostr, const DynamicLayoutView &layout) { layout.print(ostr); return ostr; } // } // namespace POOMA // ACL:rcsinfo // ---------------------------------------------------------------------- // $RCSfile: DynamicLayout.cmpl.cpp,v $ $Author: richard $ // $Revision: 1.10 $ $Date: 2004/11/01 18:16:54 $ // ---------------------------------------------------------------------- // ACL:rcsinfo
#include "lucuma/math.h" #include "lucuma/renderer.h" #include "lucuma/input.h" #include "lucuma/utils/page_allocator.h" #include "lucuma/debug.h" #include "lucuma/file.h" #include "lucuma/utils/macros.h" #include "lucuma/utils/loaders/obj_loader.h" #include "lucuma/renderer/mesh.h" #include "lucuma/utils/imgui/imgui_init.h" #include "lucuma/utils/array.h" #include <string.h> using namespace lu; void demo1() { RendererDevice device; RendererContext context; Window window; RenderTarget mainRenderTarget; Texture2D dsTex; DepthStencilState dss; DepthStencilTarget dst; CommandList cmds; PageAllocator pageAllocator; VertexShader vs; PixelShader ps; Buffer cb; Buffer mcb; RasterizerState rs; Mat4 model; Mat4 view; Mat4 projection; Scissor sc; Viewport vp; Mesh meshObject; DearImGuiRenderingData imguiData; struct CBuffer { Mat4 MVP; Mat4 invModel; Mat4 model; Mat4 view; Mat4 projection; Vec4 cameraPosition; } cbuffer; struct M { Vec4 roughnessMetallic; Vec4 albedo; Vec4 lightPos; Vec4 lightColorRadius; }matbuffer; #if 0 LU_ASSERT(renderer::CreateWindowAndRendererDeviceWaitForRenderDoc("Lucuma", 640, 480, &window, &device, &context, &mainRenderTarget)); #else LU_ASSERT(renderer::CreateWindowAndInitializeGraphicsAPI("Lucuma", 640, 480, &window, &device, &context, &mainRenderTarget)); #endif struct Vertex { Vec3 position; Vec2 texCoord; Vec3 normal; }; { SmallArray<int32_t, 100> a; Array<int32_t> b(&pageAllocator); b.initialize(a.getCapacity()); b.push(90); b.push(91); b.push(92); b.push(93); a.push(10); a.push(20); a.push(30); a.push(40); for (uint32_t i = 0; i < a.getSize(); ++i) { int32_t d = a[i]; debug::Log("value a: %d\n", d); } b.setArray(3, a); for (uint32_t i = 0; i < b.getSize(); ++i) { int32_t d = b[i]; debug::Log("value b: %d\n", d); } } imgui::InitializeDearImGui(&pageAllocator, device, &mainRenderTarget, imguiData); model.setIdentity(); model.scale(Vec3(0.5f)); model.translate(Vec3(0.0f, 0.0f, -3.0f)); model.rotateY(Rad(180.0f)); view.setIdentity(); projection.perspective(Rad(60.0f), (float32_t)window.width / (float32_t)window.height, 0.01f, 100.0f); //projection.orthographic(-2.0f, 2.0f, -2.0f, 2.0f, -100.0f, 100.0f); // Shaders { VertexLayout vl; vl.addAttribute(ResourceFormat::FORMAT_R32G32B32_FLOAT, LU_OFFSETOF(Vertex, position)); vl.addAttribute(ResourceFormat::FORMAT_R32G32B32_FLOAT, LU_OFFSETOF(Vertex, normal)); vl.addAttribute(ResourceFormat::FORMAT_R32G32_FLOAT, LU_OFFSETOF(Vertex, texCoord)); LU_ASSERT(resources::CreateVertexShaderFromSourceFile(&pageAllocator, device, "code/lucuma/shaders/hlsl/default.hlsl", "DefaultVS", vl, &vs)); LU_ASSERT(resources::CreatePixelShaderFromSourceFile(&pageAllocator, device, "code/lucuma/shaders/hlsl/default.hlsl", "DefaultPS", &ps)); } LU_ASSERT(loader::OpenOBJFileAndCreateMesh(device, &pageAllocator, "data/bunny.obj", &meshObject)); LU_ASSERT(resources::CreateBuffer(device, sizeof(cbuffer), BufferUsage::USAGE_DYNAMIC, BufferBind::BIND_CONSTANT_BUFFER, CPUAccess::CPU_ACCESS_WRITE, ResourceType::RESOURCE_NONE, 0, &cbuffer, &cb)); LU_ASSERT(resources::CreateBuffer(device, sizeof(matbuffer), BufferUsage::USAGE_DYNAMIC, BufferBind::BIND_CONSTANT_BUFFER, CPUAccess::CPU_ACCESS_WRITE, ResourceType::RESOURCE_NONE, 0, &matbuffer, &mcb)); LU_ASSERT(resources::CreateRasterizerState(device, lu::FillMode::SOLID, lu::CullMode::NONE, false, false, false, true, &rs)); { LU_ASSERT(resources::CreateDepthStencilState(device, DepthState::GetDefault(), StencilState::GetDefault(), DepthStencilOp::GetDefault(), DepthStencilOp::GetDefault(), &dss)); LU_ASSERT(resources::CreateTexture2D(device, ResourceFormat::FORMAT_D24_UNORM_S8_UINT, NULL, window.width, window.height, TextureBinding::DEPTH_STENCIL_BINDING, &dsTex)); LU_ASSERT(resources::CreateDepthStencilTarget(device, dsTex, &dst)); } LU_ASSERT(commands::CreateCommandList(&pageAllocator, 100, &cmds)); float32_t clearColor[] = { 0,0,0,1 }; uint32_t vbOffset = 0, vbStrides = sizeof(Vertex); sc.x = 0; sc.y = 0; sc.width = window.width; sc.height = window.height; vp.x = 0; vp.y = 0; vp.width = (float32_t)window.width; vp.height = (float32_t)window.height; vp.nearDepth = 0.0f; vp.farDepth = 1.0f; bool runProgram = true; Vec2 lastMouse; Vec3 eulerAngles; Vec3 lastRotation; Transform transform; Transform cameraTransform; //transform.scale *= 0.01f; cameraTransform.position.z -= 3.0f; float32_t time = 0.0f; matbuffer.roughnessMetallic.x = 0.5f; matbuffer.roughnessMetallic.y = 0.0f; matbuffer.albedo = 1.0f; matbuffer.lightPos = Vec4(0.0f, 1.0f, 0.5f, 0.0f); matbuffer.lightColorRadius = Vec4(2.5f, 2.5f, 10.0f, 1.0f); while (runProgram) { input::PollEvents(window); imgui::UpdateDearImGui(window, imguiData); // ImGui Rendering { ImGui::ColorEdit3("Albedo", (float32_t*)&matbuffer.albedo); ImGui::SliderFloat("Roughness", &matbuffer.roughnessMetallic.x, 0.1f, 1.0f); ImGui::SliderFloat("Metallic", &matbuffer.roughnessMetallic.y, 0.0f, 1.0f); ImGui::DragFloat3("Point Light Position", (float32_t*)&matbuffer.lightPos, 0.1f, -10.0f, 10.0f); //ImGui::ColorEdit3("Point Light Color", (float32_t*)&matbuffer.lightColorRadius, ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_Float); //ImGui::SliderFloat("Point Light Radius", &matbuffer.lightColorRadius.w, 0.0f, 10.0f); } if (renderer::ShouldResize(window)) { sc.x = 0; sc.y = 0; sc.width = window.width; sc.height = window.height; vp.x = 0; vp.y = 0; vp.width = (float32_t)window.width; vp.height = (float32_t)window.height; vp.nearDepth = 0.0f; vp.farDepth = 1.0f; resources::DestroyDepthStencilState(device, &dss); resources::DestroyTexture2D(device, &dsTex); resources::DestroyDepthStencilTarget(device, &dst); renderer::ResizeWindow(device, window.width, window.height, &window, &mainRenderTarget); projection.perspective(Rad(60.0f), (float32_t)window.width / (float32_t)window.height, 0.001f, 100.0f); LU_ASSERT(resources::CreateDepthStencilState(device, DepthState::GetDefault(), StencilState::GetDefault(), DepthStencilOp::GetDefault(), DepthStencilOp::GetDefault(), &dss)); LU_ASSERT(resources::CreateTexture2D(device, ResourceFormat::FORMAT_D24_UNORM_S8_UINT, NULL, window.width, window.height, TextureBinding::DEPTH_STENCIL_BINDING, &dsTex)); LU_ASSERT(resources::CreateDepthStencilTarget(device, dsTex, &dst)); } if (input::ShouldQuit(window) || input::IsKeyDown(window, KEY_ESC)) { runProgram = false; } { static Vec3 rotation; Vec2 m = (input::GetMousePos(window) / Vec2((float32_t)window.width, (float32_t)window.height) * 2.0 - 1.0); if (input::IsMouseButtonClick(window, MouseButton::RIGHT)) { lastMouse = m; lastRotation = rotation; } if (input::IsMouseButtonDown(window, MouseButton::RIGHT)) { m = m - lastMouse; rotation.x = lastRotation.x + m.y; rotation.y = lastRotation.y + m.x; } cameraTransform.rotation.fromEulerAngles(rotation); Mat4 r = cameraTransform.rotation.toMat4(); static Vec3 cameraVelocity; float32_t speed = .005f; cameraVelocity *= 0.9f; if (input::IsKeyDown(window, KeyCode::KEY_W)) { cameraVelocity.z += speed; } else if (input::IsKeyDown(window, KeyCode::KEY_S)) { cameraVelocity.z -= speed; } else if (input::IsKeyDown(window, KeyCode::KEY_A)) { cameraVelocity.x += speed; } else if (input::IsKeyDown(window, KeyCode::KEY_D)) { cameraVelocity.x -= speed; } if (cameraVelocity.lengthSqr() != 0.0f) { cameraTransform.position += (r.invert() * cameraVelocity.toVec4()).toVec3(); } model.setIdentity(); model.translate(transform.position); model.scale(transform.scale); model *= transform.rotation.toMat4(); view.setIdentity(); view *= cameraTransform.rotation.toMat4(); view.translate(cameraTransform.position); view.scale(cameraTransform.scale); // Save matrices cbuffer.MVP = projection * view * model; cbuffer.model = model; cbuffer.view = view; cbuffer.projection = projection; cbuffer.cameraPosition = -cameraTransform.position.toVec4(); cbuffer.invModel = model; cbuffer.invModel.invert(); cbuffer.invModel.transpose(); void* pCB = resources::MapBuffer(context, cb, MapType::MAP_WRITE_DISCARD); memcpy(pCB, &cbuffer, sizeof(cbuffer)); resources::UnmapBuffer(context, cb); } // Material { void* pCB = resources::MapBuffer(context, mcb, MapType::MAP_WRITE_DISCARD); memcpy(pCB, &matbuffer, sizeof(matbuffer)); resources::UnmapBuffer(context, mcb); } cmds.reset(); commands::SetRasterizerState(cmds, rs); commands::SetViewports(cmds, 1, &vp); commands::SetScissors(cmds, 1, &sc); commands::SetRenderTargets(cmds, 1, &mainRenderTarget, &dst); commands::SetDepthStencilState(cmds, dss, 0); commands::ClearRenderTarget(cmds, mainRenderTarget, clearColor); commands::ClearDepthStencilTarget(cmds, dst, CLEAR_DEPTH | CLEAR_STENCIL, 1.0f, 0); commands::SetVertexShader(cmds, &vs); commands::SetPixelShader(cmds, &ps); commands::SetVertexShaderConstantBuffers(cmds, 1, &cb); commands::SetPixelShaderConstantBuffers(cmds, 1, &mcb); commands::SetPrimitiveTopology(cmds, lu::PrimitiveTopology::TRIANGLE_LIST); mesh::DrawMesh(cmds, &meshObject); imgui::DrawDearImGui(device, context, cmds, imguiData); commands::ExecuteCommandList(context, cmds); renderer::Present(window, 1); time += 0.05f; } imgui::FinalizeDearImGui(device, imguiData); resources::DestroyTexture2D(device, &dsTex); resources::DestroyDepthStencilState(device, &dss); resources::DestroyDepthStencilTarget(device, &dst); commands::DestroyCommandList(&pageAllocator, &cmds); resources::DestroyVertexShader(device, &vs); resources::DestroyPixelShader(device, &ps); resources::DestroyBuffer(device, &cb); resources::DestroyMesh(device, &meshObject); resources::DestroyRasterizerState(device, &rs); resources::DestroyRenderTarget(device, &mainRenderTarget); renderer::DestroyRendererContext(device, &context); renderer::DestroyRendererDevice(&device); renderer::CloseWindow(&window); }
#pragma once //ShiftUpArrowKey.h #ifndef _SHIFTUPARROWKEY_H #define _SHIFTUPARROWKEY_H #include "KeyAction.h" class ShiftUpArrowKey :public KeyAction { public: ShiftUpArrowKey(Form *form = 0); ShiftUpArrowKey(const ShiftUpArrowKey& source); ~ShiftUpArrowKey(); ShiftUpArrowKey& operator=(const ShiftUpArrowKey& source); virtual void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); }; #endif //_SHIFTUPARROWKEY_H
#include "vrc_led.hpp" VRCLED::VRCLED(uint8_t pin, uint8_t num_pixels,neoPixelType t) : Adafruit_NeoPixel(num_pixels,pin,t) { current_color = 255 << 24; } void VRCLED::show_temp_color(uint32_t seconds) { //set up the operation temp_duration = seconds; current_color = temp_color; //make it happen set_strip_color(); temp_start = millis(); temp_running = true; } void VRCLED::set_temp_color_target(uint8_t white, uint8_t red, uint8_t green, uint8_t blue) { uint32_t c = 0; //format the color c = white << 24; c |= red << 16; c |= green << 8; c |= blue; //record the color temp_color = c; } void VRCLED::set_base_color_target(uint8_t white, uint8_t red, uint8_t green, uint8_t blue) { uint32_t c = 0; //format the color c = white << 24; c |= red << 16; c |= green << 8; c |= blue; //record the color base_color = c; } void VRCLED::set_strip_color() { //update the memory matrix for the strip color uint16_t i=0; for(i=0; i<numPixels(); i++) { setPixelColor(i, current_color); } needs_color_update = true; } void VRCLED::run(void) { //see if were running a temporary color if (temp_running) { //if we are, see if the timer has expired if (millis() - temp_start > temp_duration) { //if the timer has expired, place the base color back onto the strip temp_running = false; current_color = base_color; set_strip_color(); } } else { if(current_color != base_color) { current_color = base_color; set_strip_color(); } } //see if we need to update the strip color if ((millis() - last_strip_show > 10) && needs_color_update) { show(); needs_color_update = false; last_strip_show = millis(); } }
// MemoryManager.c // Implements memory manager. Yay! // #include "copyright.h" #include "MemoryManager.h" #include "system.h" #include "machine.h" MemoryManager::MemoryManager() { bit_mem = new BitMap(NumPhysPages); mem_size = NumPhysPages; mem_lock = new Lock("memory_lock"); DEBUG('m', "MEMORY MANAGER CREATED ================================ WITH SIZE %d\n", bit_mem->NumClear()); } MemoryManager::~MemoryManager() { delete mem_lock; delete bit_mem; } int MemoryManager::getPage() { mem_lock->Acquire(); int page_num = bit_mem->Find(); if (page_num < 0) { DEBUG('f', "Ran out of physical memory!\n"); } mem_lock->Release(); return page_num; } void MemoryManager::clearPage(int i) { mem_lock->Acquire(); if ((i > mem_size)||(i < 0)) { DEBUG('f', "Attempted to clear a non-existant physical memory page!\n"); return; } bit_mem->Clear(i); mem_lock->Release(); } int MemoryManager::freePages() { mem_lock->Acquire(); int temp = bit_mem->NumClear(); mem_lock->Release(); return temp; }
#include <string> #include "node.h" #include "btree.h" using namespace std; // B Tree of order m means maximum m children // Tree initialization btree::btree(){ root = new node(); root->setLeaf(true); root->setNumKeys(0); root->setParent(NULL); count=0; } tuple<node*, int> btree::search(node* subtree, int key){ // Implementation based on CLRS int i = 0; // Find the right key position. while ( i < subtree->getNumKeys() && key > subtree->getKeyAtIndex(i)){ i++; } // If key matches, return the result as a tuple. if (i < subtree->getNumKeys() && key == subtree->getKeyAtIndex(i)){ return make_tuple(subtree, i); } else{ // Key does not matches and is a leaf node, return NULL. if (subtree->getLeaf()){ return make_tuple(static_cast<node*>(NULL), 0); } // Search recursively the correct subtree. else return search(subtree->getChildAtIndex(i), key); } } // call this function for soft splitting void btree::insertSoft(btree *tree,int key) { //Not allowing duplicates int searchResultIndex; node *searchResult; tie(searchResult, searchResultIndex) = tree->search(tree->root, key); if(searchResult!=NULL) return; node *r=tree->root; int l; while(!r->getLeaf()) { l=r->getNumKeys()-1; while(l>=0 && key < r->getKeyAtIndex(l)) l--; r=r->getChildAtIndex(l+1); } // now we are at the leaf node if(r->getNumKeys()<(2*MIN_DEGREE-1)) { // if leaf node is not full, just insert int i=r->getNumKeys()-1; while(i>=0 && key < r->getKeyAtIndex(i)) { r->setKeyAtIndex(r->getKeyAtIndex(i),i+1); i--; } r->setKeyAtIndex(key,i+1); r->setNumKeys(r->getNumKeys()+1); } else { // if leaf node is full, we are extending array and for that we are taking a temp var int temp; if(key>r->getKeyAtIndex(r->getNumKeys()-1)) { temp=key; } else { int i=r->getNumKeys()-2; temp =r->getKeyAtIndex(i+1); while(i>=0 && key < r->getKeyAtIndex(i)) { r->setKeyAtIndex(r->getKeyAtIndex(i),i+1); i--; } r->setKeyAtIndex(key,i+1); } // node y and node z are the split nodes of r node *y=r; node *z=new node(); count++; for (int j = MIN_DEGREE+1; j <= 2*MIN_DEGREE - 2; j++){ z->setKeyAtIndex(y->getKeyAtIndex(j), j- MIN_DEGREE -1); } z->setKeyAtIndex(temp,MIN_DEGREE-2); temp=y->getKeyAtIndex(MIN_DEGREE); y->setNumKeys(MIN_DEGREE); z->setNumKeys(MIN_DEGREE-1); z->setParent(y->getParent()); z->setLeaf(true); if(y==tree->root) { node *s=new node(); s->setLeaf(false); tree->root=s; s->setParent(NULL); s->setChildAtIndex(y,0); s->setChildAtIndex(z,1); s->setKeyAtIndex(temp,0); y->setParent(s); z->setParent(s); s->setNumKeys(1); return; } node *s=y->getParent(); btree::insertNonLeaf(s,z,temp); } } void btree::insertNonLeaf(node *x,node *p,int key) { if(x->getNumKeys()<2*MIN_DEGREE -1) { // if the parent has accomodation , it's all well and good then int i=x->getNumKeys()-1; while(i>=0 && key < x->getKeyAtIndex(i)) { x->setKeyAtIndex(x->getKeyAtIndex(i),i+1); x->setChildAtIndex(x->getChildAtIndex(i+1),i+2); x->getChildAtIndex(i+2)->setParent(x); i--; } x->setKeyAtIndex(key,i+1); x->setChildAtIndex(p,i+2); x->setNumKeys(x->getNumKeys()+1); return; } int temp; node *t; node *r=x; if(key>r->getKeyAtIndex(r->getNumKeys()-1)) { temp=key; t=p; } else { int i=r->getNumKeys()-2; temp =r->getKeyAtIndex(i+1); t=r->getChildAtIndex(i+2); while(i>=0 && key < r->getKeyAtIndex(i)) { r->setKeyAtIndex(r->getKeyAtIndex(i),i+1); r->setChildAtIndex(r->getChildAtIndex(i+1),i+2); r->getChildAtIndex(i+2)->setParent(r); i--; } r->setKeyAtIndex(key,i+1); r->setChildAtIndex(p,i+2); } node *y=r; node *z=new node(); count++; for (int j = MIN_DEGREE+1; j <= 2*MIN_DEGREE - 2; j++){ z->setKeyAtIndex(y->getKeyAtIndex(j), j- MIN_DEGREE -1); z->setChildAtIndex(y->getChildAtIndex(j),j- MIN_DEGREE-1); z->getChildAtIndex(j - MIN_DEGREE-1)->setParent(z); } z->setKeyAtIndex(temp,MIN_DEGREE-2); z->setChildAtIndex(y->getChildAtIndex(2*MIN_DEGREE-1),MIN_DEGREE-2); z->getChildAtIndex(MIN_DEGREE-2)->setParent(z); z->setChildAtIndex(t,MIN_DEGREE-1); z->getChildAtIndex(MIN_DEGREE-1)->setParent(z); temp=y->getKeyAtIndex(MIN_DEGREE); y->setNumKeys(MIN_DEGREE); z->setNumKeys(MIN_DEGREE-1); z->setParent(y->getParent()); z->setLeaf(y->getLeaf()); if(y->getParent()==NULL) { node *s=new node(); s->setLeaf(false); this->root=s; s->setParent(NULL); s->setChildAtIndex(y,0); s->setChildAtIndex(z,1); s->setKeyAtIndex(temp,0); y->setParent(s); z->setParent(s); s->setNumKeys(1); return; } node *s=y->getParent(); btree::insertNonLeaf(s,z,temp); } void btree::insertSoftNbh(btree *tree,int key) { //Not allowing duplicates int searchResultIndex; node *searchResult; tie(searchResult, searchResultIndex) = tree->search(tree->root, key); if(searchResult!=NULL) return; node *r=tree->root; int l; while(!r->getLeaf()) { l=r->getNumKeys()-1; while(l>=0 && key < r->getKeyAtIndex(l)) { //root->setKeyAtIndex(root->getKeyAtIndex(l),l+1); l--; } r=r->getChildAtIndex(l+1); } //if(root->getLeaf()) //{ if(r->getNumKeys()<(2*MIN_DEGREE-1)) { int i=r->getNumKeys()-1; while(i>=0 && key < r->getKeyAtIndex(i)) { r->setKeyAtIndex(r->getKeyAtIndex(i),i+1); i--; } r->setKeyAtIndex(key,i+1); r->setNumKeys(r->getNumKeys()+1); } else { int temp; if(key>r->getKeyAtIndex(r->getNumKeys()-1)) { temp=key; } else { int i=r->getNumKeys()-2; temp =r->getKeyAtIndex(i+1); while(i>=0 && key < r->getKeyAtIndex(i)) { r->setKeyAtIndex(r->getKeyAtIndex(i),i+1); i--; } r->setKeyAtIndex(key,i+1); } node *m=r->getParent(); if(m!=NULL) { int k=r->getKeyAtIndex(0); int q=m->getNumKeys()-1; while(q>=0 && k < m->getKeyAtIndex(q)) { q--; } q++; int li=q-1; int ri=q+1; if(li>=0) { node *lc=m->getChildAtIndex(li); if(lc->getNumKeys()<2*MIN_DEGREE-1) { lc->setKeyAtIndex(m->getKeyAtIndex(q-1),lc->getNumKeys()); m->setKeyAtIndex(r->getKeyAtIndex(0),q-1); lc->setNumKeys(lc->getNumKeys()+1); // lc->setChildAtIndex(r->getChildAtIndex(0),lc->getNumKeys()); for(int j=0;j<r->getNumKeys()-1;j++) { r->setKeyAtIndex(r->getKeyAtIndex(j+1),j); } r->setKeyAtIndex(temp,r->getNumKeys()-1); return; } } if(ri<=m->getNumKeys()) { node *rc=m->getChildAtIndex(ri); if(rc->getNumKeys()<2*MIN_DEGREE-1) { for(int j=rc->getNumKeys()-1;j>=0;j--) { rc->setKeyAtIndex(rc->getKeyAtIndex(j),j+1); } rc->setKeyAtIndex(m->getKeyAtIndex(q),0); m->setKeyAtIndex(temp,q); rc->setNumKeys(rc->getNumKeys()+1); // lc->setChildAtIndex(r->getChildAtIndex(0),lc->getNumKeys()); return; } } } node *y=r; node *z=new node(); for (int j = MIN_DEGREE+1; j <= 2*MIN_DEGREE - 2; j++){ z->setKeyAtIndex(y->getKeyAtIndex(j), j- MIN_DEGREE -1); } z->setKeyAtIndex(temp,MIN_DEGREE-2); temp=y->getKeyAtIndex(MIN_DEGREE); y->setNumKeys(MIN_DEGREE); z->setNumKeys(MIN_DEGREE-1); z->setParent(y->getParent()); z->setLeaf(true); if(y==tree->root) { node *s=new node(); s->setLeaf(false); tree->root=s; s->setParent(NULL); s->setChildAtIndex(y,0); s->setChildAtIndex(z,1); s->setKeyAtIndex(temp,0); y->setParent(s); z->setParent(s); s->setNumKeys(1); return; } node *s=y->getParent(); btree::insertNonLeafNbh(s,z,temp); // btree::split(prev,l+1); } } void btree::insertNonLeafNbh(node *x,node *p,int key) { if(x->getNumKeys()<2*MIN_DEGREE -1) { int i=x->getNumKeys()-1; while(i>=0 && key < x->getKeyAtIndex(i)) { x->setKeyAtIndex(x->getKeyAtIndex(i),i+1); x->setChildAtIndex(x->getChildAtIndex(i+1),i+2); x->getChildAtIndex(i+2)->setParent(x); i--; } x->setKeyAtIndex(key,i+1); x->setChildAtIndex(p,i+2); x->setNumKeys(x->getNumKeys()+1); return; } int temp; node *t; node *r=x; if(key>r->getKeyAtIndex(r->getNumKeys()-1)) { temp=key; t=p; } else { int i=r->getNumKeys()-2; temp =r->getKeyAtIndex(i+1); t=r->getChildAtIndex(i+2); while(i>=0 && key < r->getKeyAtIndex(i)) { r->setKeyAtIndex(r->getKeyAtIndex(i),i+1); r->setChildAtIndex(r->getChildAtIndex(i+1),i+2); r->getChildAtIndex(i+2)->setParent(r); i--; } r->setKeyAtIndex(key,i+1); r->setChildAtIndex(p,i+2); } node *m=r->getParent(); if(m!=NULL) { int k=r->getKeyAtIndex(0); int q=m->getNumKeys()-1; while(q>=0 && k < m->getKeyAtIndex(q)) { q--; } q++; int li=q-1; int ri=q+1; if(li>=0) { node *lc=m->getChildAtIndex(li); if(lc->getNumKeys()<2*MIN_DEGREE-1) { lc->setKeyAtIndex(m->getKeyAtIndex(q-1),lc->getNumKeys()); m->setKeyAtIndex(r->getKeyAtIndex(0),q-1); lc->setNumKeys(lc->getNumKeys()+1); lc->setChildAtIndex(r->getChildAtIndex(0),lc->getNumKeys()); lc->getChildAtIndex(lc->getNumKeys())->setParent(lc); for(int j=0;j<r->getNumKeys()-1;j++) { r->setKeyAtIndex(r->getKeyAtIndex(j+1),j); r->setChildAtIndex(r->getChildAtIndex(j+1),j); r->getChildAtIndex(j)->setParent(r); } r->setKeyAtIndex(temp,r->getNumKeys()-1); r->setChildAtIndex(r->getChildAtIndex(r->getNumKeys()),r->getNumKeys()-1); r->getChildAtIndex(r->getNumKeys()-1)->setParent(r); r->setChildAtIndex(t,r->getNumKeys()); r->getChildAtIndex(r->getNumKeys())->setParent(r); return; } } if(ri<=m->getNumKeys()) { node *rc=m->getChildAtIndex(ri); if(rc->getNumKeys()<2*MIN_DEGREE-1) { rc->setChildAtIndex(rc->getChildAtIndex(rc->getNumKeys()),rc->getNumKeys()+1); rc->getChildAtIndex(rc->getNumKeys()+1)->setParent(rc); for(int j=rc->getNumKeys()-1;j>=0;j--) { rc->setKeyAtIndex(rc->getKeyAtIndex(j),j+1); rc->setChildAtIndex(rc->getChildAtIndex(j),j+1); rc->getChildAtIndex(j+1)->setParent(rc); } rc->setKeyAtIndex(m->getKeyAtIndex(q),0); rc->setChildAtIndex(t,0); rc->getChildAtIndex(0)->setParent(rc); m->setKeyAtIndex(temp,q); rc->setNumKeys(rc->getNumKeys()+1); return; } } } node *y=r; node *z=new node(); for (int j = MIN_DEGREE+1; j <= 2*MIN_DEGREE - 2; j++){ z->setKeyAtIndex(y->getKeyAtIndex(j), j- MIN_DEGREE -1); z->setChildAtIndex(y->getChildAtIndex(j),j- MIN_DEGREE-1); z->getChildAtIndex(j - MIN_DEGREE-1)->setParent(z); } z->setKeyAtIndex(temp,MIN_DEGREE-2); z->setChildAtIndex(y->getChildAtIndex(2*MIN_DEGREE-1),MIN_DEGREE-2); z->getChildAtIndex(MIN_DEGREE-2)->setParent(z); z->setChildAtIndex(t,MIN_DEGREE-1); z->getChildAtIndex(MIN_DEGREE-1)->setParent(z); temp=y->getKeyAtIndex(MIN_DEGREE); y->setNumKeys(MIN_DEGREE); z->setNumKeys(MIN_DEGREE-1); z->setParent(y->getParent()); z->setLeaf(y->getLeaf()); if(y->getParent()==NULL) { node *s=new node(); s->setLeaf(false); this->root=s; s->setParent(NULL); s->setChildAtIndex(y,0); s->setChildAtIndex(z,1); s->setKeyAtIndex(temp,0); y->setParent(s); z->setParent(s); s->setNumKeys(1); return; } node *s=y->getParent(); btree::insertNonLeafNbh(s,z,temp); } // call this function for proactive splitting void btree::insert(btree* tree, int key){ // Implementation based on CLRS //Not allowing duplicates int searchResultIndex; node *searchResult; tie(searchResult, searchResultIndex) = tree->search(tree->root, key); if(searchResult!=NULL) return; node* root = tree->root; // If root is full, split it. if (root->getNumKeys() == (2 * MIN_DEGREE) - 1){ node* s = new node(); tree->root = s; s->setLeaf(false); s->setNumKeys(0); s->setChildAtIndex(root, 0); root->setParent(s); btree::splitChild(s, 0); btree::insertNonFull(s, key); } else{ btree::insertNonFull(root, key); } } void btree::insertNonFull(node* x, int key){ // Implementation based on CLRS cout << "Insert node full called on " << key << endl; int i = x->getNumKeys()-1; // If the node is a leaf node, insert at the correct position. if (x->getLeaf()){ while (i >= 0 && key < x->getKeyAtIndex(i)){ x->setKeyAtIndex(x->getKeyAtIndex(i),i+1); i--; } x->setKeyAtIndex(key,i+1); x->setNumKeys(x->getNumKeys()+1); } else{ // Is the node is not a leaf node, find the candidate child. while(i >=0 && key < x->getKeyAtIndex(i)){ i--; } i++; // If the child is full, split it. if (x->getChildAtIndex(i)->getNumKeys() == (2 * MIN_DEGREE) - 1){ btree::splitChild(x,i); if (key > x->getKeyAtIndex(i)){ i++; } } btree::insertNonFull(x->getChildAtIndex(i),key); } } void btree::splitChild(node* x, int i){ // Implementation based on CLRS cout << "Splitting child at index " << i << endl; node* z = new node(); node* y = x->getChildAtIndex(i); z->setLeaf(y->getLeaf()); z->setNumKeys(MIN_DEGREE - 1); for (int j = 0; j < MIN_DEGREE - 1; j++){ z->setKeyAtIndex(y->getKeyAtIndex(j + MIN_DEGREE), j); } if (!y->getLeaf()){ for (int j = 0; j <= MIN_DEGREE; j++){ z->setChildAtIndex(y->getChildAtIndex(j+MIN_DEGREE), j); z->getChildAtIndex(j)->setParent(z); } } y->setNumKeys(MIN_DEGREE - 1); for (int j = x->getNumKeys(); j >= i + 1; j--){ x->setChildAtIndex(x->getChildAtIndex(j), j + 1); x->getChildAtIndex(j+1)->setParent(x); } x->setChildAtIndex(z, i + 1); x->getChildAtIndex(i + 1)->setParent(x); for (int j = x->getNumKeys(); j > i; j--){ x->setKeyAtIndex(x->getKeyAtIndex(j - 1), j); } x->setKeyAtIndex(y->getKeyAtIndex(MIN_DEGREE - 1), i); x->setNumKeys(x->getNumKeys() + 1); z->setParent(x); } void btree::postOrderTraversal(node* subtree, int depth){ // Print the vertical tree for debugging. // The number of times '-' illustrate the depth of the node within the tree. // Please check the provided test case. int nodesPresent = subtree->getNumKeys(); if (subtree->getLeaf()){ for (int j = nodesPresent - 1; j >= 0; j--){ cout << string(depth + 1, '-') << subtree->getKeyAtIndex(j) << endl; } } else{ for (int j = nodesPresent; j > 0; j--){ btree::postOrderTraversal(subtree->getChildAtIndex(j), depth + 1); cout << string(depth + 1, '-') << subtree->getKeyAtIndex(j - 1) << endl; } btree::postOrderTraversal(subtree->getChildAtIndex(0), depth + 1); } } void btree::inOrderTraversal(node* subtree, int depth){ // Print the vertical tree for debugging. // The number of times '-' illustrate the depth of the node within the tree. // Please check the provided test case. int nodesPresent = subtree->getNumKeys(); if (subtree->getLeaf()){ for (int j = 0; j <= nodesPresent-1; j++){ cout << string(depth + 1, '-') << subtree->getKeyAtIndex(j) << endl; } } else{ for (int j = 0; j <nodesPresent; j++){ btree::inOrderTraversal(subtree->getChildAtIndex(j), depth + 1); cout << string(depth + 1, '-') << subtree->getKeyAtIndex(j) << endl; } btree::inOrderTraversal(subtree->getChildAtIndex(nodesPresent), depth + 1); } }
#pragma once #include "NonMovable.h" #include "VertexArray.h" #include "glm/glm.hpp" class SelectedVoxelVisual : private NonCopyable, private NonMovable { public: SelectedVoxelVisual(); void setPosition(const glm::vec3& position); void setActive(bool active); void render(); private: VertexArray m_mesh; glm::vec3 m_position; bool m_active; };
#pragma once #include "Enemy.h" #include "Item.h" #include <iostream> #include <map> #include <vector> using namespace std; class Room { public: enum Size { Big, Medium, Small, Enormous, Tiny, Gigantic }; enum Lighting { Candle, Fireplace, Torch, DiscoFever, Window, Creek, Lamp, Holyball, Spotlight }; enum Furniture { Table, Bed, Seat, Closet, Bench, Lounge, Television, Trashcan }; enum Atmosfeer { Stinky, Clean, Messy, Foggy, Dense, Cloudy, Romantic, Cosy }; enum Direction { North, East, South, West }; Room(int x, int y); Room(); Room(const Room& other); // copy constructor ~Room(); string GetDescripton(); void SetDoorway(Direction direction, Room* room); int getWeigthDoorway(Direction direction); map<Room::Direction, Room*> GetAdjecentRoomsMap(); Room* GetAdjecentRoom(Direction direction); vector<Room*> GetAdjecentRooms(); bool DoesRoomHaveDoorway(Direction direction); void CollapseDoorway(Direction direction); bool isDoorwayCollapsed(Direction direction); void removeEnemy(); int GetXPosition() { return xPosition; } int GetYPosition() { return yPosition; } void setDistance(int i) { distanceFromCurrentRoom = i; } int getDistance() { return distanceFromCurrentRoom; } void setDifficulty(int i) { difficulty = i; } int getDifficulty() { return difficulty; } Room& operator=(const Room& other); // copy assignment bool operator==(const Room& other); bool operator!=(const Room& other); void setSize(Size s) { size = s; } void setAtmosfeer(Atmosfeer a) { atmosfeer = a; } void setLighting(Lighting l) { lighting = l; } void setFurniture(Furniture f) { furniture = f; } bool isVisited() { return visited; } void visitRoom(); bool isTrapped() { return trapped; } void setTrapped(bool t) { trapped = t; } bool hasEnemy() { if (enemy == nullptr) { return false; } return enemy->isAlive(); }; Enemy* getEnemy() { return enemy; }; void setEnemy(Enemy* e) { enemy = e; } private: Enemy* enemy; map<Direction, Room*> adjecentRooms; map<Direction, int> weightDoorways; int xPosition, yPosition, distanceFromCurrentRoom, difficulty; bool visited; bool trapped; Atmosfeer atmosfeer; Furniture furniture; Lighting lighting; Size size; };
/******************************************************************************** ** Form generated from reading UI file 'snakegame.ui' ** ** Created by: Qt User Interface Compiler version 5.12.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_SNAKEGAME_H #define UI_SNAKEGAME_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QGraphicsView> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QStackedWidget> #include <QtWidgets/QStatusBar> #include <QtWidgets/QToolBar> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_SnakeGame { public: QWidget *centralWidget; QStackedWidget *stackedWidget; QWidget *titlePage; QPushButton *singlePlayerButton; QWidget *singleGamePage; QGraphicsView *graphicsView; QMenuBar *menuBar; QToolBar *mainToolBar; QStatusBar *statusBar; void setupUi(QMainWindow *SnakeGame) { if (SnakeGame->objectName().isEmpty()) SnakeGame->setObjectName(QString::fromUtf8("SnakeGame")); SnakeGame->resize(800, 700); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(SnakeGame->sizePolicy().hasHeightForWidth()); SnakeGame->setSizePolicy(sizePolicy); SnakeGame->setMinimumSize(QSize(800, 700)); SnakeGame->setMaximumSize(QSize(800, 700)); centralWidget = new QWidget(SnakeGame); centralWidget->setObjectName(QString::fromUtf8("centralWidget")); sizePolicy.setHeightForWidth(centralWidget->sizePolicy().hasHeightForWidth()); centralWidget->setSizePolicy(sizePolicy); stackedWidget = new QStackedWidget(centralWidget); stackedWidget->setObjectName(QString::fromUtf8("stackedWidget")); stackedWidget->setGeometry(QRect(10, 10, 780, 650)); sizePolicy.setHeightForWidth(stackedWidget->sizePolicy().hasHeightForWidth()); stackedWidget->setSizePolicy(sizePolicy); stackedWidget->setMinimumSize(QSize(780, 650)); stackedWidget->setMaximumSize(QSize(780, 650)); titlePage = new QWidget(); titlePage->setObjectName(QString::fromUtf8("titlePage")); singlePlayerButton = new QPushButton(titlePage); singlePlayerButton->setObjectName(QString::fromUtf8("singlePlayerButton")); singlePlayerButton->setGeometry(QRect(290, 295, 200, 30)); singlePlayerButton->setMinimumSize(QSize(200, 30)); singlePlayerButton->setMaximumSize(QSize(200, 30)); stackedWidget->addWidget(titlePage); singleGamePage = new QWidget(); singleGamePage->setObjectName(QString::fromUtf8("singleGamePage")); graphicsView = new QGraphicsView(singleGamePage); graphicsView->setObjectName(QString::fromUtf8("graphicsView")); graphicsView->setGeometry(QRect(4, 5, 772, 640)); sizePolicy.setHeightForWidth(graphicsView->sizePolicy().hasHeightForWidth()); graphicsView->setSizePolicy(sizePolicy); graphicsView->setMinimumSize(QSize(772, 640)); graphicsView->setMaximumSize(QSize(772, 640)); graphicsView->setRenderHints(QPainter::Antialiasing|QPainter::TextAntialiasing); stackedWidget->addWidget(singleGamePage); SnakeGame->setCentralWidget(centralWidget); menuBar = new QMenuBar(SnakeGame); menuBar->setObjectName(QString::fromUtf8("menuBar")); menuBar->setGeometry(QRect(0, 0, 800, 17)); SnakeGame->setMenuBar(menuBar); mainToolBar = new QToolBar(SnakeGame); mainToolBar->setObjectName(QString::fromUtf8("mainToolBar")); SnakeGame->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(SnakeGame); statusBar->setObjectName(QString::fromUtf8("statusBar")); SnakeGame->setStatusBar(statusBar); retranslateUi(SnakeGame); QMetaObject::connectSlotsByName(SnakeGame); } // setupUi void retranslateUi(QMainWindow *SnakeGame) { SnakeGame->setWindowTitle(QApplication::translate("SnakeGame", "Snake", nullptr)); singlePlayerButton->setText(QApplication::translate("SnakeGame", "Single Player", nullptr)); } // retranslateUi }; namespace Ui { class SnakeGame: public Ui_SnakeGame {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_SNAKEGAME_H
// Fill out your copyright notice in the Description page of Project Settings. #include "QBERTGameMode.h" //#include "Cube.h" // include Cube h to use the class AQBERTGameMode::AQBERTGameMode() { PrimaryActorTick.bCanEverTick = true; world = GetWorld(); TopCube = 274.0f; MostLeftCube = 0.0f; RightSideCube = 0.0f; clockRedBallSpawn = 0.0f; clockGreenBallSpawn = 0.0f; clockCoilySpawn = 0.0f; CubesLeftActive = 0; // No cubes have been created we start with zero cubes active //Setup the default pawn to static class //DefaultPawnClass = AQBERTGameMode::StaticClass(); //PlayerControllerClass = ^ same as above //Find me a class with this constructor helper static ConstructorHelpers::FClassFinder<APawn> PlayerPawn(TEXT("/Script/QBert_Project.Qbert")); DefaultPawnClass = PlayerPawn.Class; } void AQBERTGameMode::MapGenerator() { //On Screen Debug for everything /*GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, FString::Printf (TEXT("Current TopCube Value %f"), TopCube));*/ for (int row = 0; row < numberOfRows; row++) { LevelReference = row; RightSideCube = MostLeftCube; //GLog->Log("ROW LOOP"); String only debug for (int col = 0; col < numberOfCols; col++) { if (mapLayout[row][col] == 0 || mapLayout[row][col] == 3) { mapArray[row][col] = nullptr; } if (mapLayout[row][col] == 1) { if (world) { //GLog->Log(TopCube); if (LevelReference == row) // Check the level reference if it is the same then move to the new level an position the left most cube { MostLeftCube -= 16.0f; TopCube = TopCube - 24.0f; LevelReference++; } else { RightSideCube += 32.0f; } FActorSpawnParameters sParams; sParams.Owner = NULL; FRotator rotator = FRotator(0.0f, 0.0f, 0.0f); FVector location = FVector(RightSideCube, 0.0f, TopCube); if (ACube* newCube = world->SpawnActor<ACube>((tempCube, location, rotator, sParams))) { mapArray[row][col] = newCube; mapArray[row][col]->SetActorLocation(location); CubesLeftActive++; } } } } } } void AQBERTGameMode::SetupUI() { FActorSpawnParameters sParams; sParams.Owner = NULL; FRotator rotator = FRotator(0.0f, 0.0f, 0.0f); FVector location = FVector(-80.0f, 2.0f, 300.0f); if (AUIElements* newUI = world->SpawnActor<AUIElements>((tempUI, location, rotator, sParams))) { UserInterFaceObj = newUI; UserInterFaceObj->SetActorLocation(location); } } void AQBERTGameMode::AddEnemies() { FActorSpawnParameters sParams; sParams.Owner = NULL; FRotator rotator = FRotator(0.0f, 0.0f, 0.0f); FVector location = FVector(0.0f, 2.0f, 0.0f); if (ARedBall* newRedBall = world->SpawnActor<ARedBall>(location, rotator, sParams)) { if (redBallCounter == 0) { EnemyRedBallObj = newRedBall; location.Z += mapArray[2][6]->GetActorLocation().Z + 300.0f; EnemyRedBallObj->SetActorLocation(location); redBallCounter++; } else if (redBallCounter >= 1) { EnemyRedBallObjTwo = newRedBall; location.Z += mapArray[2][6]->GetActorLocation().Z + 300.0f; EnemyRedBallObjTwo->SetActorLocation(location); redBallCounter = 0; } } } void AQBERTGameMode::AddPowerUps() { FActorSpawnParameters sParams; sParams.Owner = NULL; FRotator rotator = FRotator(0.0f, 0.0f, 0.0f); FVector location = FVector(16.0f, 2.0f, 537.0f); if (AGreenBall* newGreenBall = world->SpawnActor<AGreenBall>(location, rotator, sParams)) { AidGreenBallObj = newGreenBall; AidGreenBallObj->SetActorLocation(location); } } void AQBERTGameMode::AddElevators() { FActorSpawnParameters sParams; sParams.Owner = NULL; FRotator rotator = FRotator(0.0f, 0.0f, 0.0f); FVector location = FVector(-79.0f, 0.0f, 182.0f); if (AElevator* newElevator = world->SpawnActor<AElevator>(location, rotator, sParams)) { ElevatorObj = newElevator; ElevatorObj->SetActorLocation(location); } location = FVector(79.0f, 0.0f, 182.0f); if (AElevator* newElevator = world->SpawnActor<AElevator>(location, rotator, sParams)) { ElevatorObj2 = newElevator; ElevatorObj2->SetActorLocation(location); } } void AQBERTGameMode::SpawnCoily() { FActorSpawnParameters sParams; sParams.Owner = NULL; FRotator rotator = FRotator(0.0f, 0.0f, 0.0f); //FVector location = FVector(1.0f, 2.0f, 215.0f); FVector location = FVector(1.0f, 2.0f, 515.0f); if (ACoily* newCoily = world->SpawnActor<ACoily>(location, rotator, sParams)) { CoilyObj = newCoily; CoilyObj->SetActorLocation(location); } } int AQBERTGameMode::MapPosition(int row, int col) { if (mapLayout[row][col] == 0) { return mapLayout[row][col]; } else if (mapLayout[row][col] == 1) { if (mapArray[row][col]->isCubeActive()) { mapArray[row][col]->setNewSprite(); CubesLeftActive--; //UE_LOG(LogTemp, Warning, TEXT("BlockValue %d"), CubesLeftActive); return mapLayout[row][col]; } } else if (mapLayout[row][col] == 4) { mapLayout[row][col] = 0; return 4; } return 1; } // Called when the game starts or when spawned void AQBERTGameMode::BeginPlay() { Super::BeginPlay(); MapGenerator(); SetupUI(); SpawnCoily(); AddElevators(); } // Called every frame void AQBERTGameMode::Tick(float DeltaTime) { Super::Tick(DeltaTime); clockRedBallSpawn += DeltaTime; clockGreenBallSpawn += DeltaTime; if (clockRedBallSpawn >= 3.0f) { AddEnemies(); clockRedBallSpawn = 0.0f; } if (clockGreenBallSpawn >= 25.0f) { AddPowerUps(); clockGreenBallSpawn = 0.0f; } } //Receives Qberts position in the array, to pass it to coily so coily can track him down. void AQBERTGameMode::receiveQbertPosition(int row, int col) { CoilyObj->updateQbertPosition(row, col); } //Will be called when player pauses the game receiving input from Qbert void AQBERTGameMode::activatePauseOptions(bool isPaused) { UserInterFaceObj->showPausedOptions(isPaused); } //Called by Qbert when he is riding the elevator void AQBERTGameMode::QbertIsOnElevator(int col) { ElevatorChosen = col; if (col < 7) { ElevatorObj->MoveElevator(); } else { ElevatorObj2->MoveElevator(); } } //Called by Qbert once he has reached the top of the pyramid void AQBERTGameMode::callElevatorDestruction() { UE_LOG(LogTemp, Warning, TEXT("Elevator Chosen %d"), ElevatorChosen); if (ElevatorChosen < 7) { ElevatorObj->DestroyElevator(); } else { ElevatorObj2->DestroyElevator(); } }
#include<bits/stdc++.h> #include<vector> #include<map> using namespace std; struct Data { int start, ending, weight; }; bool compareData(Data i1, Data i2) { return (i1.weight < i2.weight); } void print(map<int , vector< pair<int, int > > > adjList){ for(map<int , vector< pair<int, int > > >::iterator it = adjList.begin() ; it != adjList.end() ; it++){ cout << it->first << " : "; vector<pair<int, int> > neighbours = it->second; for(int i = 0 ; i < neighbours.size() ; i++){ cout << "(" << neighbours[i].first << " " << neighbours[i].second << ")"; } cout << endl; } } int find(int parents[], int vertex){ if(parents[vertex]!=vertex) return find(parents, parents[vertex]);; return vertex; } void make_union(int parents[], int x, int y){ int x_set_parent = find(parents, x); int y_set_parent = find(parents, y); parents[y_set_parent] = x_set_parent; } int main() { map<int,vector<pair<int,int> > > graph; vector<int> vertices; int n,vertex,starting,ending,weight,m; cout<<"Enter no of vertices: "<<endl; cin>>n; for(int i=0;i<n;i++){ vertices.push_back(i+1); } vector<Data> edges; cout<<"Enter no of edges - (starting,ending,weight): "<<endl; cin>>m; cout<<"Enter edges: "<<endl; for(int i=0;i<m;i++){ cin>>starting>>ending>>weight; edges.push_back({starting,ending,weight}); graph[starting].push_back(make_pair(ending,weight)); graph[ending].push_back(make_pair(starting,weight)); } cout<<"Graph:"<<endl; print(graph); int parents[n+1]; for (int i=0; i<=n; i++) { parents[i] = i; } sort(edges.begin(), edges.end(), compareData); int minimumCost = 0; for(Data x:edges){ int x_set = find(parents, x.start); int y_set = find(parents, x.ending); if(x_set!=y_set){ make_union(parents, x_set, y_set); minimumCost+=x.weight; } } cout<<"Minimum Cost for spanning Tree is:"<<endl; cout<<minimumCost; cout<<endl; return 0; } /* Sample input:- 5 7 1 2 5 2 5 2 2 4 3 1 4 7 3 4 1 1 3 3 4 5 2 */
#include "log.h" #include "dominio.h" #include "servicio.h" #include "interfaz.h" #include "util.h" #include "configuracion.h" #include "servicioBackup.h" #include "servicioPOP3.h" #include "CrearBackupEmail.h" using namespace std; int main(int argc, char *argv[]) { //Inicializar el dominio cDominio dominio; if (!dominio.iniciar()) reportarErrorRarisimo(string("Error al iniciar el objeto dominio")); //Inicializar el servicio cServicioBackup servicio("BACKUP MAIL", &dominio); if (!servicio.iniciar()) reportarErrorRarisimo(string("Error al iniciar el objeto servicioBackup")); cServicioPOP3 servicioPOP3(&dominio); if (!servicio.iniciar()) reportarErrorRarisimo(string("Error al iniciar el objeto servicioPOP3")); //Inicializar la clase interfaz cInterfaz interfaz; //Inicializar variables miscelaneas string mensaje; string error; int derror; string errorFile(ERROR_CREAR_BACKUP_EMAIL); string okFile(OK_CREAR_BACKUP_EMAIL); //Verificar que la pagina haya sido llamada por CrearBackupEmail.php if (interfaz.verificarPagina(string("CrearBackupEmail.php")) < 0) return(-1); //Verificar si el cliente puede crear el servicio derror = servicio.verificarCrearServicio(); if (derror == 0) { error = "Su Plan no le permite crear Backups de sus Cuentas de E-Mails"; interfaz.reportarErrorComando(error, errorFile, dominio); return(-1); } //Obtener las variables string txtCompresion; if ((interfaz.obtenerVariable("txtCompresion", txtCompresion, dominio)) < 0) { interfaz.reportarErrorFatal(); return(-1); } //Borar los espacios en blanco y los newlines a los costados de los campos strtrimString(txtCompresion); //Verificar que la compresion sea valida derror = servicio.verificarCompresion(txtCompresion); if (derror > 0) { error = "La compresion " + txtCompresion + " no esta soportada"; interfaz.reportarErrorComando(error, errorFile, dominio); return(-1); } //Verificar si se puede crear el backup /*derror = servicio.verificarExisteBackupDB(dominio); if (derror < 0) { interfaz.reportarErrorFatal(); return(-1); } if (derror > 0) { error = "Solo se puede crear un Backup de E-Mails por día"; interfaz.reportarErrorComando(error, errorFile, dominio); return(-1); }*/ //Verificar si existen cuentas de email para el dominio derror = servicioPOP3.verificarExisteEmailsDB(dominio); if (derror < 0) { interfaz.reportarErrorFatal(); return(-1); } if (derror == 0) { error = "No existen Cuentas de E-Mails para su dominio"; interfaz.reportarErrorComando(error, errorFile, dominio); return(-1); } //Obtener el nombre del archivo std::string txtArchivo = servicio.getNombreArchivo(txtCompresion, dominio); //Crear el backup en el sistema derror = servicio.agregarBackup(txtCompresion, txtArchivo, dominio); if (derror < 0) { interfaz.reportarErrorFatal(); return(-1); } //Crear el backup en la base de datos derror = servicio.agregarBackupDB(txtCompresion, dominio); if (derror < 0) { interfaz.reportarErrorFatal(); return(-1); } //Agregar al historial de la base de datos mensaje = "Se creo el Backup de E-Mails"; servicio.agregarHistorial(mensaje, dominio); //Reportar el mensaje de ok al navegador std::string link = "/backups/" + dominio.getDominio() + "/" + txtArchivo; mensaje = "El Backup " + txtArchivo + " fue creado con éxito, el mismo puede bajarlo via FTP desde el directorio /backups en su Home Dir.-"; interfaz.reportarOkComandoBackup(mensaje, link, txtArchivo, okFile, dominio); return(0); }
#ifndef TRACKER_H #define TRACKER_H #include <vector> #include "KalmanFilterToolBox.h" #include "track.h" class NearNeighborDisMetric; class IDDistributor; class tracker{ /* This is the multi-target tracker. Parameters ---------- metric : nn_matching.NearestNeighborDistanceMetric A distance metric for measurement-to-track association. max_age : int Maximum number of missed misses before a track is deleted. n_init : int Number of consecutive detections before the track is confirmed. The track state is set to `Deleted` if a miss occurs within the first `n_init` frames. */ public: NearNeighborDisMetric* nnDisMetr_ptr; float max_iou_distance; int max_age; int n_init; int _next_idx; public: std::vector<Track> tracks; tracker(/*NearNeighborDisMetric* metric,*/ float max_cosine_distance, int nn_budget, float max_iou_distance = 0.9, int max_age = 10, int n_init=3); ~tracker(); // Propagate track state distributions one time step forward. This function should be called once every time step, before `update`. void predict(); // Perform measurement update and track management void update(const DETECTIONS& detections, IDDistributor* IDdis, int index, const HRYTCalibrater cali, const object::TransferType worldtype); // https://www.cnblogs.com/zhubaohua-bupt/p/7182803.html typedef DYNAMICM (tracker::* GATED_METRIC_FUNC)(std::vector<Track>& tracks, const DETECTIONS& dets, const std::vector<int>& track_indices, const std::vector<int>& detection_indices); DYNAMICM gated_matric(std::vector<Track>& tracks, const DETECTIONS& dets, const std::vector<int>& track_indices, const std::vector<int>& detection_indices); DYNAMICM iou_cost(std::vector<Track>& tracks, const DETECTIONS& dets, const std::vector<int>& track_indices, const std::vector<int>& detection_indices); Eigen::VectorXf iou(DETECTBOX& bbox, DETECTBOXSS &candidates); private: std::vector<int> targets; void _match(const DETECTIONS& detections, TRACHER_MATCHD& res); void _initiate_track(const DETECTION_ROW& detection, IDDistributor* IDdis, int index); }; #endif // TRACKER_H
/* * Copyright (c) 2016, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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 "mbed-drivers/mbed.h" #include "uif-ui-popup-alert-wrd/AlertView.h" #include "core-util/SharedPointer.h" #include "cborg/cbor.h" #include "mbed-block/BlockDynamic.h" #include "message-center/MessageCenter.h" #include "uiframework/UIFramework.h" #include "uif-matrixlcd/MatrixLCD.h" static SPI lcdspi(LCD_SPI_MOSI, NC, LCD_SPI_CLK); static uif::MatrixLCD lcd(lcdspi, LCD_CS, LCD_DISP, LCD_EXT_COM_IN); static SharedPointer<UIFramework> uiFramework; /*****************************************************************************/ static SharedPointer<BlockStatic> sendBlock; static const int OVERHEAD = 1 + 4 + 4 + 4; static const int ITEMS = 3; static const int TIMEONSCREEN = 5000; static const int DELAY = 1000; static const char title[] = "Title - the title"; static const char body[] = "Body - the body can be really long"; void sendTaskDone() { // free block sendBlock = SharedPointer<BlockStatic>(); } void popup() { // allocate memory for the message. sendBlock = SharedPointer<BlockStatic>(new BlockDynamic(OVERHEAD + sizeof(title) + sizeof(body))); // cbor encode message. Cbore encoder(sendBlock->getData(), sendBlock->getLength()); encoder.array(ITEMS) .item(TIMEONSCREEN) .item(title) .item(body); // set length of message. sendBlock->setLength(encoder.getLength()); // use message center to send messages to the popup alert view. MessageCenter::sendTask(MessageCenter::LocalHost, MessageCenter::AlertPort, *sendBlock.get(), sendTaskDone); // resend message after a short delay. minar::Scheduler::postCallback(popup) .delay(minar::milliseconds(TIMEONSCREEN + DELAY)); } void app_start(int, char *[]) { SharedPointer<UIView> view(new AlertView()); view->setWidth(128); view->setHeight(128); // UI framework uiFramework = SharedPointer<UIFramework>(new UIFramework(lcd, view)); minar::Scheduler::postCallback(popup) .delay(minar::milliseconds(DELAY)); }
#ifndef _GRAPHIC_PRINT_H_ #define _GRAPHIC_PRINT_H_ #include "graphic_manager.h" #include <string> class CGraphicString : public CGraphicObjWithRectArea { public: CGraphicString(CPixel base, alignment align = center, const char * capture = ""): CGraphicObjWithRectArea(base), _current_s(capture), _drawed_s(""),_align(align){} void set(const std::string& str){_current_s = str;} void operator= (const std::string& str){_current_s = str;} void operator= (const char* s){_current_s = s;} operator std::string(){ return _current_s; } void change_place(CPixel base, alignment align){move_to(base); _align = align; must_be_redrawed();} protected: std::string _current_s; std::string _drawed_s; alignment _align; }; #endif
#ifndef POINTSOURCE_HPP #define POINTSOURCE_HPP #include "geometry/Point3D.hpp" template <typename T, typename U> class PointSource3D { public: /* Members */ const Point3D<T> location; const U intensity; /* Constructors */ PointSource3D(const Point3D<T>& location, const U intensity) : location(location), intensity(intensity) {} PointSource3D(const PointSource3D<T, U>& point) : location(point.location), intensity(point.intensity) {} /* Friend functions */ template <typename V, typename W> friend std::ostream& operator<<(std::ostream& out, const PointSource3D<V, W>& instance); }; template <typename T, typename U> std::ostream& operator<<(std::ostream& out, const PointSource3D<T,U>& instance) { return out << "<" << instance.intensity << "@" << instance.location << ">"; } #endif
/* * Copyright (c) 2009-2012 André Tupinambá (andrelrt@gmail.com) * * 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 "server_context.h" #include "server_platform.h" #include "message/message.h" #include "message/msg_context.h" #include "composite/opencl_composite.h" #include "composite/composite_device.h" #include "composite/composite_context.h" using dcl::info::generic_device; using dcl::network::message::dcl_message; using dcl::network::message::msgCreateContextFromType; using dcl::composite::opencl_composite; using dcl::composite::composite_device; using dcl::composite::composite_context; using dcl::composite::composite_platform; //----------------------------------------------------------------------------- namespace dcl { namespace server { //----------------------------------------------------------------------------- void msgCreateContext_command::execute() { const composite_platform& platform = opencl_composite::get_instance().get_platform(); server_platform::device_manager_t& device_manager = session_context_ptr_->get_server_platform().get_device_manager(); const remote_ids_t& device_ids = message_->get_devices(); devices_t devices; devices.reserve( device_ids.size() ); for( remote_ids_t::const_iterator it = device_ids.begin(); it != device_ids.end(); ++it ) { devices.push_back( reinterpret_cast<generic_device*>( device_manager.get( *it ) ) ); } composite_context* context_ptr = reinterpret_cast<composite_context*>( platform.create_context( devices ) ); message_->set_remote_id( session_context_ptr_->get_server_platform().get_context_manager().get( context_ptr, true ) ); } //----------------------------------------------------------------------------- void msgCreateContextFromType_command::execute() { cl_device_type device_type = message_->get_device_type(); const composite_platform& platform = opencl_composite::get_instance().get_platform(); composite_context* context_ptr = reinterpret_cast<composite_context*>( platform.create_context( device_type ) ); message_->set_remote_id( session_context_ptr_->get_server_platform().get_context_manager().get( context_ptr, true ) ); } //----------------------------------------------------------------------------- void msgGetContextInfo_command::execute() { remote_id_t id = message_->get_remote_id(); composite_context* context_ptr = session_context_ptr_->get_server_platform().get_context_manager().get( id ); const devices_t& devices_ref = context_ptr->get_devices(); message_->set_device_count( static_cast<uint32_t>( devices_ref.size() ) ); devices_t::const_iterator it; for( it = devices_ref.begin(); it != devices_ref.end(); ++it ) { message_->add_device( session_context_ptr_->get_server_platform().get_device_manager().get( *it, true ) ); } } //----------------------------------------------------------------------------- }} // namespace dcl::server //-----------------------------------------------------------------------------
// // main.cpp // tensor factorization on wn18 // // Created by Vanellope on 5/19/16. // Copyright © 2016 Vanellope. All rights reserved. // #include <iostream> #include <fstream> #include <cstdlib> #include <math.h> #include <time.h> #define MAX_FACT 150000 #define MAX_ENTITY 50000 #define MAX_RELATION 20 #define F 141442 #define E 40943 #define R 18 #define RE 10 //RE=10Rr,Rr<15 #define Rr 1 #define Ita 5 #define SMP 0.001 using namespace std; int train[MAX_FACT][3]; int valid[MAX_FACT][3]; int test[MAX_FACT][3]; double a[MAX_ENTITY][Rr+1][RE+1]; double b[RE+1][MAX_RELATION][RE+1]; double c[RE+1][Rr+1][MAX_ENTITY]; double a1[MAX_ENTITY][Rr+1][RE+1]; double b1[RE+1][MAX_RELATION][RE+1]; double c1[RE+1][Rr+1][MAX_ENTITY]; FILE *tp=fopen("m3.dat","w"); void input() { FILE *fp1=fopen("/WN18/m3train.dat","r"); FILE *fp2=fopen("/WN18/m3valid.dat","r"); FILE *fp3=fopen("/WN18/m3test.dat","r"); for(long i=1;i<=F;i++) fscanf(fp1,"%d%d%d",&train[i][0],&train[i][1],&train[i][2]); for(int i=1;i<=5000;i++) fscanf(fp3,"%d%d%d",&test[i][0],&test[i][1],&test[i][2]); for(int i=1;i<=5000;i++) fscanf(fp2,"%d%d%d",&valid[i][0],&valid[i][1],&valid[i][2]); return; } void initialize(){ double ini=pow(1.0/RE/RE/Rr,1.0/3)*2; for(long s=1;s<=E;s++) for(long r=1;r<=Rr;r++) for(long o=1;o<=RE;o++) a[s][r][o]=(ini*rand())/RAND_MAX-ini; for(long s=1;s<=RE;s++) for(long r=1;r<=R;r++) for(long o=1;o<=RE;o++) b[s][r][o]=(ini*rand())/RAND_MAX-ini; for(long s=1;s<=RE;s++) for(long r=1;r<=Rr;r++) for(long o=1;o<=E;o++) c[s][r][o]=(ini*rand())/RAND_MAX-ini; return; } void initialize1(){ for(long s=1;s<=E;s++) for(long r=1;r<=Rr;r++) for(long o=1;o<=RE;o++) a1[s][r][o]=0; for(long s=1;s<=RE;s++) for(long r=1;r<=R;r++) for(long o=1;o<=RE;o++) b1[s][r][o]=0; for(long s=1;s<=RE;s++) for(long r=1;r<=Rr;r++) for(long o=1;o<=E;o++) c1[s][r][o]=0; return; } double tensor(long s,long r,long o){ double x=0; for(long r1=1;r1<=Rr;r1++) for(long o1=1;o1<=RE;o1++) for(long s1=1;s1<=RE;s1++) { x+=a[s][r1][o1]*b[s1][r][o1]*c[s1][r1][o]; } return x; } double norm(){ double x=0; for(long s=1;s<=E;s++) for(long r=1;r<=Rr;r++) for(long o=1;o<=RE;o++) x+=a1[s][r][o]*a1[s][r][o]; for(long s=1;s<=RE;s++) for(long r=1;r<=R;r++) for(long o=1;o<=RE;o++) x+=b1[s][r][o]*b1[s][r][o]; for(long s=1;s<=RE;s++) for(long r=1;r<=Rr;r++) for(long o=1;o<=E;o++) x+=c1[s][r][o]*c1[s][r][o]; return x; } void renew(double y){ for(long s=1;s<=E;s++) for(long r=1;r<=Rr;r++) for(long o=1;o<=RE;o++) a[s][r][o]+=a1[s][r][o]*y; for(long s=1;s<=RE;s++) for(long r=1;r<=R;r++) for(long o=1;o<=RE;o++) b[s][r][o]+=b1[s][r][o]*y; for(long s=1;s<=RE;s++) for(long r=1;r<=Rr;r++) for(long o=1;o<=E;o++) c[s][r][o]+=c1[s][r][o]*y; return ; } void evaluate(){ double value[MAX_ENTITY],temp; long eva=0; for(long f=1;f<=5000;f++){ long s=valid[f][0],r=valid[f][1],o=valid[f][2],num=0; temp=tensor(s,r,o); for(long o1=1;o1<=E;o1++){ if(o1!=o&&tensor(s,r,o1)>temp) num++; if(num>=10) break; } if(num<10) eva++; cout<<f<<' '<<eva<<'\n'; } // fprintf(tp,"%f\n", (double)eva/50000); cout<<"Ans= "<<(double)eva/5000<<'\n'; system("pause"); } void training() { // double pre=-1*F*SMP; // cout<<pre<<'\n'; long times=0; while(1) { times++; double loss=0; initialize1(); for(long f=1;f<=F*SMP;f++) { long temp=rand()/(double)RAND_MAX*F+1; if(temp<1||temp>F) continue; long s=train[temp][0], r=train[temp][1], o=train[temp][2]; double x=tensor(s,r,o); if(x>1) continue; loss+=(x-1)*(x-1); double y=-2*(x-1); for(long r1=1;r1<=Rr;r1++) for(long o1=1;o1<=RE;o1++) for(long s1=1;s1<=RE;s1++) { a1[s][r1][o1]+=y*b[s1][r][o1]*c[s1][r1][o]; b1[s1][r][o1]+=y*a[s][r1][o1]*c[s1][r1][o]; c1[s1][r1][o]+=y*b[s1][r][o1]*a[s][r1][o1]; } // cout<<temp<<'\n'; } for(long f=1;f<=F*SMP*Ita;f++) { long temp=rand()/(double)RAND_MAX*F+1; if(temp<1||temp>F) continue; long s=train[temp][0], r=train[temp][1], o=rand()/(double)RAND_MAX*E+1; if(o<1||o>E) continue; double x=tensor(s,r,o); double y=-2*(x+1)/Ita; if(x<-1) continue; loss+=(x+1)*(x+1)/Ita; for(long r1=1;r1<=Rr;r1++) for(long o1=1;o1<=RE;o1++) for(long s1=1;s1<=RE;s1++) { a1[s][r1][o1]+=y*b[s1][r][o1]*c[s1][r1][o]; b1[s1][r][o1]+=y*a[s][r1][o1]*c[s1][r1][o]; c1[s1][r1][o]+=y*b[s1][r][o1]*a[s][r1][o1]; } } double x=norm(),y=0.01; // if(loss>700) y=0.05; cout<<times<<' '<<loss<<' '<<x<<' '<<'\n'; renew(y); if(times%1000==0){ int a; cout<<"Evaluate now or Continue(evaluation may last more than 20 minutes)? Evaluate=1, Continue=0."; cin>>a; if (a==-1) break; if (a==0) continue; evaluate(); } } return; } int main() { srand((unsigned)(time(NULL))); input(); initialize(); training(); system("pause"); return 0; }
#include <iostream> #include <stdio.h> #include "Eigen/Core" #include "Eigen/LU" #include "opencv2/core/core.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/nonfree/nonfree.hpp" // Used Eigen 3.2.0 Library for matrix inversion [http://eigen.tuxfamily.org/index.php?title=Main_Page] // DONT USE 2x2 adjoint/inverse function of Eigen library, its incorrect // Problems: (1) Matrix calc computationally expensive // (2) Error diverging using namespace std; using namespace cv; static void help() { printf("Usage:\n ./a.out <image1> <image2>\n"); } int main(int argc, char** argv){ int N,count; float *u_old,*v_old,*u_new,*v_new; float *X_old,*Y_old,*X_new,*Y_new; float *P,*K; float **A,**B; float uo,vo,fx,fy,Z,Dx,Dy,cphi,sphi,e,num,den; float Tr[3][3]; // Intrinsic Calibration parameters for img size 320x240 uo=157.73985; vo=134.19819; fx=391.54809; fy=395.45221; if(argc != 3) { help(); return -1; } Mat img1 = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE); Mat img2 = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE); if(img1.empty() || img2.empty()) { printf("Can't read one of the images\n"); return -1; } // detecting keypoints FastFeatureDetector detector(190); vector<KeyPoint> keypoints1, keypoints2; detector.detect(img1, keypoints1); detector.detect(img2, keypoints2); // computing descriptors SurfDescriptorExtractor extractor; Mat descriptors1, descriptors2; extractor.compute(img1, keypoints1, descriptors1); extractor.compute(img2, keypoints2, descriptors2); // matching descriptors BFMatcher matcher(NORM_L2); vector<DMatch> matches; matcher.match(descriptors1, descriptors2, matches); N=matches.size(); // no of matched feature points // Old and new consecutive frames pixel coordinate u_old=new float [N]; v_old=new float [N]; u_new=new float [N]; v_new=new float [N]; // Old and new consecutive frames 3D coordinate X_old=new float [N]; Y_old=new float [N]; X_new=new float [N]; Y_new=new float [N]; A=new float* [N]; //old [X/Z Y/Z 1] B=new float* [N]; //new [Xn/Z Yn/Z 1] Eigen::MatrixXf A_mat(N,3),B_mat(N,3),Tr_mat(3,3),tmp_mat(3,3); for(int i=0; i<N; i++) { A[i] = new float [3]; B[i] = new float [3]; } // Obtaining pixel coordinates of feature points for(size_t i = 0; i < N; i++) { Point2f point1 = keypoints1[matches[i].queryIdx].pt; Point2f point2 = keypoints2[matches[i].trainIdx].pt; u_old[i]=point1.x; v_old[i]=point1.y; u_new[i]=point2.x; v_new[i]=point2.y; A[i][0] = (u_old[i]-uo)/fx; A_mat(i,0)=A[i][0]; A[i][1] = (v_old[i]-vo)/fy; A_mat(i,1)=A[i][1]; A[i][2] = 1; A_mat(i,2)=A[i][2]; B[i][0] = (u_new[i]-uo)/fx; B_mat(i,0)=B[i][0]; B[i][1] = (v_new[i]-vo)/fy; B_mat(i,1)=B[i][1]; B[i][2] = 1; B_mat(i,2)=B[i][2]; } tmp_mat=A_mat.transpose()*A_mat; Tr_mat=tmp_mat.inverse()*(A_mat.transpose())*B_mat; //cout<<N<<"\n"<<A<<"\n"<<*A<<"\n"<<**A; //cout<<Tr_mat<<"\n"; // Transformation Matrix calculation P=new float [N]; K=new float [N]; // Tr=inv(A'*A)*A'*B; cphi=(Tr_mat(0,0)+Tr_mat(1,1))/2; sphi=(Tr_mat(0,1)-Tr_mat(1,0))/2; for(size_t i = 0; i < N; i++){ P[i]=cphi*A_mat(i,0)-sphi*A_mat(i,1)-B_mat(i,0); //(Dx/Z) K[i]=sphi*A_mat(i,0)+cphi*A_mat(i,1)-B_mat(i,1);//(Dy/Z) } // Finding least error Z, Dx, Dy Z=2; //initial guess (metres) Dx=-Z*Tr_mat(2,0); Dy=-Z*Tr_mat(2,1); e=0; for(size_t i = 0; i < N; i++){ e=e+(Dx-Z*P[i])*(Dx-Z*P[i])+(Dy-Z*K[i])*(Dy-Z*K[i]); } count=0; while(e>=0.1&&count<50){ count++; //cout<<Dx<<"\t"; // Calculate Z_opt num=0;den=0; for(size_t i = 0; i < N; i++){ num=num+Dx*P[i]+Dy*K[i]; den=den+P[i]*P[i]+K[i]*K[i]; } Z=num/den;// New Z is Z_opt (min error e) and new Dx, Dy Dx=-Z*Tr_mat(2,0); Dy=-Z*Tr_mat(2,1); // Find error e=0; for(size_t i = 0; i < N; i++){ e=e+(Dx-Z*P[i])*(Dx-Z*P[i])+(Dy-Z*K[i])*(Dy-Z*K[i]); } //cout<<e<<"\t"; } //cout<<"\n"<<e<<"\t"<<Dx<<"\t"<<Dy<<"\t"<<Z<<"\n"; /* // drawing the rmatches namedWindow("matches", 1); Mat img_matches; drawMatches(img1, keypoints1, img2, keypoints2, matches, img_matches); imshow("matches", img_matches); waitKey(0); */ return 0; }
// Writing a function 'filter()' that implements a 1D Kalman Filter, // but using multi-dimensional equations //============================================================================ #include <iostream> #include "Eigen/Dense" #include <vector> //Kalman Filter variables Eigen::VectorXd x; // Object state Eigen::MatrixXd P; // Object covariance matrix Eigen::VectorXd u; // External motion Eigen::MatrixXd F; // State transition matrix Eigen::MatrixXd H; // Measurement matrix Eigen::MatrixXd R; // Measurement covariance matrix Eigen::MatrixXd I; // Identity matrix Eigen::MatrixXd Q; // Process covariance matrix std::vector<Eigen::VectorXd> measurements; void filter(Eigen::VectorXd &x, Eigen::MatrixXd &P); int main() { //design the KF with 1D motion x = Eigen::VectorXd(2); // Object state here is defined with position and velocity x << 0, 0; // initial null values for both position and velocity, initially we know nothing P = Eigen::MatrixXd(2, 2); // Object covariance/uncertainty matrix P << 1000, 0, 0, 1000; // high initial uncertanty, only diagonal terms which means initiallly there is not correlation // between position and velocity u = Eigen::VectorXd(2); // External motion is unknow, that would be for known acceleraion/deacceleration of object u << 0, 0; F = Eigen::MatrixXd(2, 2); // State transition matrix, designed for simple liner motion equations; x'=x*1+v*dt with dt=1; v'=x*0+v*1 F << 1, 1, 0, 1; H = Eigen::MatrixXd(1, 2); // Measurement matrix, designed to measurement update z=x'*1+v'*0 H << 1, 0; R = Eigen::MatrixXd(1, 1); // Measurement covariance/uncertainty, that must come based on sensor manfactured and calibration R << 1; I = Eigen::MatrixXd::Identity(2, 2); // Indentity matrix Q = Eigen::MatrixXd(2, 2); // Process covariance/uncertainty matrix, here is null, but would need to be calibrated Q << 0, 0, 0, 0; //create a list of measurements Eigen::VectorXd single_meas(1); single_meas << 1; measurements.push_back(single_meas); single_meas << 2; measurements.push_back(single_meas); single_meas << 3; measurements.push_back(single_meas); //call Kalman filter algorithm filter(x, P); return 0; } void filter(Eigen::VectorXd &x, Eigen::MatrixXd &P) { for (unsigned int n = 0; n < measurements.size(); ++n) { Eigen::VectorXd z = measurements[n]; // measurement for update Eigen::VectorXd Y; // Measurement error Eigen::MatrixXd S, K; // Weighting uncertanty and Kalman gain // KF Measurement update step /* Y = Z - H * x S = H * P * Ht + R K = P * Ht * Sinv x' = x + K*Y P' = (I - K * H ) * P */ Y = z - H * x; // Measurement error calculation S = H * P * H.transpose() + R; // weighting the uncertanty, measurement (R, noise) or prediction (P) K = P * H.transpose() * S.inverse(); // Kalman gain // new state x = x + K * Y; //new state position for the moment being, right now P = (I - K * H) * P; //new state uncertanty for the moment being, right now // KF Prediction step // x' = F * x + u // P' = F * P * Ft + Q x = F * x + u; //state position prediction for the next step P = F * P * F.transpose() + Q; //state uncertanty prediction for the next step std::cout << "x=" << std::endl << x << std::endl; std::cout << "P=" << std::endl << P << std::endl; } }
template <class Type> struct forecastSet; template <class Type> struct dataSet; struct confSet; template <class Type> struct paraSet; template <class Type> Type hcr(Type ssb, vector<Type> hcrConf); #define REPORT_F(name,F) \ if(isDouble<Type>::value && F->current_parallel_region<0) { \ Rf_defineVar(Rf_install(#name), \ PROTECT(asSEXP(name)),F->report); \ UNPROTECT(1); \ } //This function returns a vector with matrices based on a list of matrices from R template<class Type> struct listMatrixFromR : vector<matrix<Type> > { listMatrixFromR() : vector<matrix<Type> >() {}; listMatrixFromR(int n) : vector<matrix<Type> >(n) {}; listMatrixFromR(SEXP x){ (*this).resize(LENGTH(x)); for(int i=0; i<LENGTH(x); i++){ SEXP sm = VECTOR_ELT(x, i); (*this)(i) = asMatrix<Type>(sm); } } template<class T> listMatrixFromR<T> cast() const { int n = (*this).size(); listMatrixFromR<T> d(n); for(int i = 0; i < n; ++i){ matrix<T> tmp = (*this)(i).template cast<T>(); d(i) = tmp; } return d; } listMatrixFromR<Type>& operator=(const listMatrixFromR<Type>& rhs) { (*this).resize(rhs.size()); for(int i = 0; i < rhs.size(); ++i){ matrix<Type> tmp = rhs(i); (*this)(i) = tmp; } return *this; } }; #define ADREPORT_F(name,F) F->reportvector.push(name,#name); #define SIMULATE_F(F) \ if(isDouble<Type>::value && F->do_simulate) template<class Type> bool isNA(Type x){ return R_IsNA(asDouble(x)); } bool isNAINT(int x){ return R_NaInt == x; //NA_INTEGER==x; } template <class Type> struct forecastSet { enum FModelType { asFModel, useFscale, useFval, useCatchval, useNextssb, useLandval, findMSY, HCR, customHCR }; enum recModelType { asRecModel, useIID }; enum FSdTimeScaleModel { rwScale, oneScale, zeroScale }; int nYears; int nCatchAverageYears; vector<int> aveYears; vector<Type> forecastYear; vector<FModelType> FModel; vector<Type> target; vector<Type> selectivity; vector<recModelType> recModel; Type logRecruitmentMedian; Type logRecruitmentVar; vector<FSdTimeScaleModel> fsdTimeScaleModel; vector<int> simFlag; int uniroot; vector<Type> hcrConf; matrix<Type> forecastCalculatedMedian; vector<Type> forecastCalculatedLogSdCorrection; vector<Type> sel; vector<Type> selFull; Type initialFbar; void calculateForecast(array<Type>& logF, array<Type>& logN, dataSet<Type>& dat, confSet& conf, paraSet<Type>& par); // Defined after dataSet and confSet void updateForecast(int i, array<Type>& logF, array<Type>& logN, dataSet<Type>& dat, confSet& conf, paraSet<Type>& par); // Defined after dataSet and confSet forecastSet() : nYears(0) {}; forecastSet(SEXP x){ // If nYears is NULL or 0; only set nYears to 0 -> no forecast if(Rf_isNull(getListElement(x,"nYears")) || (int)*REAL(getListElement(x,"nYears")) == 0){ nYears = 0; }else{ using tmbutils::asArray; nYears = (int)*REAL(getListElement(x,"nYears")); nCatchAverageYears = (int)*REAL(getListElement(x,"nCatchAverageYears")); aveYears = asVector<int>(getListElement(x,"aveYears")); forecastYear = asVector<Type>(getListElement(x,"forecastYear")); vector<int> FModelTmp = asVector<int>(getListElement(x,"FModel")); FModel = vector<FModelType>(FModelTmp.size()); for(int i = 0; i < FModel.size(); ++i) FModel(i) = static_cast<FModelType>(FModelTmp(i)); // Fval = asVector<Type>(getListElement(x,"Fval")); // Fscale = asVector<Type>(getListElement(x,"Fscale")); target = asVector<Type>(getListElement(x,"target")); selectivity = asVector<Type>(getListElement(x,"selectivity")); vector<int> recModelTmp = asVector<int>(getListElement(x,"recModel")); recModel = vector<recModelType>(recModelTmp.size()); for(int i = 0; i < recModel.size(); ++i) recModel(i) = static_cast<recModelType>(recModelTmp(i)); logRecruitmentMedian = (Type)*REAL(getListElement(x,"logRecruitmentMedian")); logRecruitmentVar = (Type)*REAL(getListElement(x,"logRecruitmentVar")); vector<int> fsdTimeScaleModelTmp = asVector<int>(getListElement(x,"fsdTimeScaleModel")); fsdTimeScaleModel = vector<FSdTimeScaleModel>(fsdTimeScaleModelTmp.size()); for(int i = 0; i < fsdTimeScaleModel.size(); ++i) fsdTimeScaleModel(i) = static_cast<FSdTimeScaleModel>(fsdTimeScaleModelTmp(i)); simFlag = asVector<int>(getListElement(x,"simFlag")); uniroot = (int)*REAL(getListElement(x,"uniroot")); hcrConf = asVector<Type>(getListElement(x,"hcrConf")); } }; forecastSet<Type>& operator=(const forecastSet<Type>& rhs) { nYears = rhs.nYears; if(nYears == 0) return *this; nCatchAverageYears = rhs.nCatchAverageYears; aveYears = rhs.aveYears; forecastYear = rhs.forecastYear; FModel = rhs.FModel; target = rhs.target; selectivity = rhs.selectivity; recModel = rhs.recModel; logRecruitmentMedian = rhs.logRecruitmentMedian; logRecruitmentVar = rhs.logRecruitmentVar; fsdTimeScaleModel = rhs.fsdTimeScaleModel; simFlag = rhs.simFlag; uniroot = rhs.uniroot; hcrConf = rhs.hcrConf; forecastCalculatedMedian = rhs.forecastCalculatedMedian; forecastCalculatedLogSdCorrection = rhs.forecastCalculatedLogSdCorrection; sel = rhs.sel; selFull = rhs.selFull; initialFbar = rhs.initialFbar; return *this; } template<class T> forecastSet<T> cast() const { forecastSet<T> d; d.nYears = nYears; // int if(nYears == 0) return d; d.nCatchAverageYears = nCatchAverageYears; // int d.aveYears = aveYears; // <int> d.forecastYear = forecastYear.template cast<T>(); // d.FModel = FModel; // <int> d.FModel = vector<typename forecastSet<T>::FModelType>(FModel.size()); for(int i = 0; i < FModel.size(); ++i) d.FModel(i) = static_cast<typename forecastSet<T>::FModelType>((int)FModel(i)); d.target = target.template cast<T>(); d.selectivity = selectivity.template cast<T>(); // d.recModel = recModel; // <int> d.recModel = vector<typename forecastSet<T>::recModelType>(recModel.size()); for(int i = 0; i < recModel.size(); ++i) d.recModel(i) = static_cast<typename forecastSet<T>::recModelType>((int)recModel(i)); d.logRecruitmentMedian = T(logRecruitmentMedian); d.logRecruitmentVar = T(logRecruitmentVar); // d.fsdTimeScaleModel = fsdTimeScaleModel; // <int> d.fsdTimeScaleModel = vector<typename forecastSet<T>::FSdTimeScaleModel>(fsdTimeScaleModel.size()); for(int i = 0; i < fsdTimeScaleModel.size(); ++i) d.fsdTimeScaleModel(i) = static_cast<typename forecastSet<T>::FSdTimeScaleModel>((int)fsdTimeScaleModel(i)); d.simFlag = simFlag; // <int> d.uniroot = uniroot; d.hcrConf = hcrConf.template cast<T>(); d.forecastCalculatedMedian = forecastCalculatedMedian.template cast<T>(); d.forecastCalculatedLogSdCorrection = forecastCalculatedLogSdCorrection.template cast<T>(); d.sel = sel.template cast<T>(); d.selFull = selFull.template cast<T>(); d.initialFbar = T(initialFbar); return d; } }; template<class Type> struct referencepointSet { enum CatchType { totalCatch, landings, discard }; int nYears; vector<int> aveYears; vector<int> selYears; vector<Type> Fsequence; vector<Type> xPercent; vector<Type> MSYRange; CatchType catchType; int optN; referencepointSet() : nYears(0) {}; referencepointSet(SEXP x){ // If nYears is NULL or 0; only set nYears to 0 -> no forecast if(Rf_isNull(getListElement(x,"nYears")) || (int)*REAL(getListElement(x,"nYears")) == 0){ nYears = 0; optN = 1; }else{ using tmbutils::asArray; nYears = (int)*REAL(getListElement(x,"nYears")); aveYears = asVector<int>(getListElement(x,"aveYears")); selYears = asVector<int>(getListElement(x,"selYears")); Fsequence = asVector<Type>(getListElement(x,"Fsequence")); xPercent = asVector<Type>(getListElement(x,"xPercent")); catchType = static_cast<CatchType>((int)*REAL(getListElement(x,"catchType"))); MSYRange = asVector<Type>(getListElement(x,"MSYRange")); optN = (int)*REAL(getListElement(x,"optN")); } } referencepointSet<Type>& operator=(const referencepointSet<Type>& rhs) { nYears = rhs.nYears; optN = rhs.optN; if(nYears == 0) return *this; aveYears = rhs.aveYears; selYears = rhs.selYears; Fsequence = rhs.Fsequence; xPercent = rhs.xPercent; catchType = rhs.catchType; MSYRange = rhs.MSYRange; return *this; } template<class T> referencepointSet<T> cast() const { referencepointSet<T> d; d.nYears = nYears; d.optN = optN; if(nYears == 0) return d; d.aveYears = aveYears; d.selYears = selYears; d.Fsequence = Fsequence.template cast<T>(); d.xPercent = xPercent.template cast<T>(); d.catchType = static_cast<typename referencepointSet<T>::CatchType>((int)catchType); d.MSYRange = MSYRange.template cast<T>(); return d; } }; template <class Type> struct dataSet{ int noFleets; vector<int> fleetTypes; vector<Type> sampleTimes; int noYears; vector<Type> years; vector<int> minAgePerFleet; vector<int> maxAgePerFleet; int nobs; array<int> idx1; array<int> idx2; array<int> idxCor; array<int> aux; vector<Type> logobs; vector<Type> weight; // data_indicator<vector<Type>,Type> keep; array<Type> propMat; array<Type> stockMeanWeight; array<Type> catchMeanWeight; array<Type> natMor; array<Type> landFrac; array<Type> disMeanWeight; array<Type> landMeanWeight; array<Type> propF; array<Type> propM; listMatrixFromR<Type> corList; forecastSet<Type> forecast; referencepointSet<Type> referencepoint; dataSet() {}; dataSet(SEXP x) { using tmbutils::asArray; noFleets = (int)*REAL(getListElement(x,"noFleets")); fleetTypes = asVector<int>(getListElement(x,"fleetTypes")); sampleTimes = asVector<Type>(getListElement(x,"sampleTimes")); noYears = (int)*REAL(getListElement(x,"noYears")); years = asVector<Type>(getListElement(x,"years")); minAgePerFleet = asVector<int>(getListElement(x,"minAgePerFleet")); maxAgePerFleet = asVector<int>(getListElement(x,"maxAgePerFleet")); nobs = (int)*REAL(getListElement(x,"nobs")); idx1 = asArray<int>(getListElement(x,"idx1")); idx2 = asArray<int>(getListElement(x,"idx2")); idxCor = asArray<int>(getListElement(x,"idxCor")); aux = asArray<int>(getListElement(x,"aux")); logobs = asVector<Type>(getListElement(x,"logobs")); weight = asVector<Type>(getListElement(x,"weight")); propMat = asArray<Type>(getListElement(x,"propMat")); stockMeanWeight = asArray<Type>(getListElement(x,"stockMeanWeight")); catchMeanWeight = asArray<Type>(getListElement(x,"catchMeanWeight")); natMor = asArray<Type>(getListElement(x,"natMor")); landFrac = asArray<Type>(getListElement(x,"landFrac")); disMeanWeight = asArray<Type>(getListElement(x,"disMeanWeight")); landMeanWeight = asArray<Type>(getListElement(x,"landMeanWeight")); propF = asArray<Type>(getListElement(x,"propF")); propM = asArray<Type>(getListElement(x,"propM")); corList = listMatrixFromR<Type>(getListElement(x,"corList")); forecast = forecastSet<Type>(getListElement(x,"forecast")); referencepoint = referencepointSet<Type>(getListElement(x,"referencepoint")); }; dataSet<Type>& operator=(const dataSet<Type>& rhs) { noFleets = rhs.noFleets; fleetTypes = rhs.fleetTypes; sampleTimes = rhs.sampleTimes; noYears = rhs.noYears; years = rhs.years; minAgePerFleet = rhs.minAgePerFleet; maxAgePerFleet = rhs.maxAgePerFleet; nobs = rhs.nobs; idx1 = rhs.idx1; idx2 = rhs.idx2; idxCor = rhs.idxCor; aux = rhs.aux; logobs = rhs.logobs; weight = rhs.weight; // keep = rhs.keep; propMat = rhs.propMat; stockMeanWeight = rhs.stockMeanWeight; catchMeanWeight = rhs.catchMeanWeight; natMor = rhs.natMor; landFrac = rhs.landFrac; disMeanWeight = rhs.disMeanWeight; landMeanWeight = rhs.landMeanWeight; propF = rhs.propF; propM = rhs.propM; corList = rhs.corList; forecast = rhs.forecast; referencepoint = rhs.referencepoint; return *this; }; template<class T> dataSet<T> cast() const { dataSet<T> d; d.noFleets = noFleets; // int d.fleetTypes = fleetTypes; //<int> d.sampleTimes = sampleTimes.template cast<T>(); d.noYears = noYears; // int d.years = years.template cast<T>(); d.minAgePerFleet = minAgePerFleet;//<int> d.maxAgePerFleet = maxAgePerFleet;//<int> d.nobs = nobs;// int d.idx1 = idx1;//<int> d.idx2 = idx2;//<int> d.idxCor = idxCor;//<int> d.aux = aux;//<int> d.logobs = logobs.template cast<T>(); d.weight = weight.template cast<T>(); // keep = keep; // The array must be resized before copying d.propMat.initZeroArray(propMat.dim); d.propMat = propMat.template cast<T>(); d.stockMeanWeight.initZeroArray(stockMeanWeight.dim); d.stockMeanWeight = stockMeanWeight.template cast<T>(); d.catchMeanWeight.initZeroArray(catchMeanWeight.dim); d.catchMeanWeight = catchMeanWeight.template cast<T>(); d.natMor.initZeroArray(natMor.dim); d.natMor = natMor.template cast<T>(); d.landFrac.initZeroArray(landFrac.dim); d.landFrac = landFrac.template cast<T>(); d.disMeanWeight.initZeroArray(disMeanWeight.dim); d.disMeanWeight = disMeanWeight.template cast<T>(); d.landMeanWeight.initZeroArray(landMeanWeight.dim); d.landMeanWeight = landMeanWeight.template cast<T>(); d.propF.initZeroArray(propF.dim); d.propF = propF.template cast<T>(); d.propM.initZeroArray(propM.dim); d.propM = propM.template cast<T>(); d.corList = corList.template cast<T>(); d.forecast = forecast.template cast<T>(); d.referencepoint = referencepoint.template cast<T>(); return d; } }; template <class Type> void extendArray(array<Type>& x, int nModelYears, int nForecastYears, vector<int> aveYears, bool keepModelYears = true){ vector<int> dim = x.dim; array<Type> tmp((int)keepModelYears*nModelYears+nForecastYears,dim(1)); tmp.setZero(); vector<Type> ave(dim(1)); ave.setZero(); Type nave = aveYears.size(); // Calculate average for(int i = 0; i < aveYears.size(); ++i){ if(aveYears(i) < dim(0)){ for(int j = 0; j < dim(1); ++j){ ave(j) += x(aveYears(i), j); } }else{ nave -= 1.0; } } if(nave == 0) Rf_error("ave.years does not cover the data period."); ave /= nave; // Insert values in tmp for(int i = 0; i < tmp.dim(0); ++i){ for(int j = 0; j < tmp.dim(1); ++j){ if(keepModelYears && i < dim(0)){ // Take value from x tmp(i,j) = x(i,j); }else{ // Take value from ave tmp(i,j) = ave(j); } } } // Overwrite x // NOTE: x must be resized first, otherwise x=tmp will not work. x.initZeroArray(tmp.dim); x = tmp; return; } struct confSet{ int minAge; int maxAge; vector<int> maxAgePlusGroup; array<int> keyLogFsta; int corFlag; array<int> keyLogFpar; array<int> keyQpow; array<int> keyVarF; vector<int> keyVarLogN; array<int> keyVarObs; vector<int> obsCorStruct; array<int> keyCorObs; int stockRecruitmentModelCode; vector<double> constRecBreaks; int noScaledYears; vector<int> keyScaledYears; matrix<int> keyParScaledYA; vector<int> fbarRange; vector<int> keyBiomassTreat; vector<int> simFlag; int resFlag; vector<int> obsLikelihoodFlag; int fixVarToWeight; double fracMixF; double fracMixN; vector<double> fracMixObs; array<int> predVarObsLink; int stockWeightModel; vector<int> keyStockWeightMean; vector<int> keyStockWeightObsVar; int catchWeightModel; vector<int> keyCatchWeightMean; vector<int> keyCatchWeightObsVar; int matureModel; vector<int> keyMatureMean; int mortalityModel; vector<int> keyMortalityMean; vector<int> keyMortalityObsVar; matrix<int> keyXtraSd; confSet() {}; confSet(SEXP x){ using tmbutils::asArray; minAge = (int)*REAL(getListElement(x,"minAge")); maxAge = (int)*REAL(getListElement(x,"maxAge")); maxAgePlusGroup = asVector<int>(getListElement(x,"maxAgePlusGroup")); keyLogFsta = asArray<int>(getListElement(x,"keyLogFsta")); corFlag = (int)*REAL(getListElement(x,"corFlag")); keyLogFpar = asArray<int>(getListElement(x,"keyLogFpar")); keyQpow = asArray<int>(getListElement(x,"keyQpow")); keyVarF = asArray<int>(getListElement(x,"keyVarF")); keyVarLogN = asVector<int>(getListElement(x,"keyVarLogN")); keyVarObs = asArray<int>(getListElement(x,"keyVarObs")); obsCorStruct = asVector<int>(getListElement(x,"obsCorStruct")); keyCorObs = asArray<int>(getListElement(x,"keyCorObs")); stockRecruitmentModelCode = (int)*REAL(getListElement(x,"stockRecruitmentModelCode")); constRecBreaks = asVector<double>(getListElement(x,"constRecBreaks")); noScaledYears = (int)*REAL(getListElement(x,"noScaledYears")); keyScaledYears = asVector<int>(getListElement(x,"keyScaledYears")); keyParScaledYA = asMatrix<int>(getListElement(x,"keyParScaledYA")); fbarRange = asVector<int>(getListElement(x,"fbarRange")); keyBiomassTreat = asVector<int>(getListElement(x,"keyBiomassTreat")); simFlag = asVector<int>(getListElement(x,"simFlag")); resFlag = (int)*REAL(getListElement(x,"resFlag")); obsLikelihoodFlag = asVector<int>(getListElement(x,"obsLikelihoodFlag")); fixVarToWeight = (int)*REAL(getListElement(x,"fixVarToWeight")); fracMixF = (double)*REAL(getListElement(x,"fracMixF")); fracMixN = (double)*REAL(getListElement(x,"fracMixN")); fracMixObs = asVector<double>(getListElement(x,"fracMixObs")); predVarObsLink = asArray<int>(getListElement(x,"predVarObsLink")); stockWeightModel = (int)*REAL(getListElement(x,"stockWeightModel")); keyStockWeightMean = asVector<int>(getListElement(x,"keyStockWeightMean")); keyStockWeightObsVar = asVector<int>(getListElement(x,"keyStockWeightObsVar")); catchWeightModel = (int)*REAL(getListElement(x,"catchWeightModel")); keyCatchWeightMean = asVector<int>(getListElement(x,"keyCatchWeightMean")); keyCatchWeightObsVar = asVector<int>(getListElement(x,"keyCatchWeightObsVar")); matureModel = (int)*REAL(getListElement(x,"matureModel")); keyMatureMean = asVector<int>(getListElement(x,"keyMatureMean")); mortalityModel = (int)*REAL(getListElement(x,"mortalityModel")); keyMortalityMean = asVector<int>(getListElement(x,"keyMortalityMean")); keyMortalityObsVar = asVector<int>(getListElement(x,"keyMortalityObsVar")); keyXtraSd = asMatrix<int>(getListElement(x,"keyXtraSd")); }; confSet& operator=(const confSet& rhs) { minAge = rhs.minAge; maxAge = rhs.maxAge; maxAgePlusGroup = rhs.maxAgePlusGroup; keyLogFsta = rhs.keyLogFsta; keyLogFpar = rhs.keyLogFpar; corFlag = rhs.corFlag; keyQpow = rhs.keyQpow; keyVarF = rhs.keyVarF; keyVarLogN = rhs.keyVarLogN; keyVarObs = rhs.keyVarObs; obsCorStruct = rhs.obsCorStruct; keyCorObs = rhs.keyCorObs; stockRecruitmentModelCode = rhs.stockRecruitmentModelCode; constRecBreaks = rhs.constRecBreaks; noScaledYears = rhs.noScaledYears; keyScaledYears = rhs.keyScaledYears; keyParScaledYA = rhs.keyParScaledYA; fbarRange = rhs.fbarRange; keyBiomassTreat = rhs.keyBiomassTreat; simFlag = rhs.simFlag; resFlag = rhs.resFlag; obsLikelihoodFlag = rhs.obsLikelihoodFlag; fixVarToWeight = rhs.fixVarToWeight; fracMixF = rhs.fracMixF; fracMixN = rhs.fracMixN; fracMixObs = rhs.fracMixObs; predVarObsLink = rhs.predVarObsLink; stockWeightModel = rhs.stockWeightModel; keyStockWeightMean = rhs.keyStockWeightMean; keyStockWeightObsVar = rhs.keyStockWeightObsVar; catchWeightModel = rhs.catchWeightModel; keyCatchWeightMean = rhs.keyCatchWeightMean; keyCatchWeightObsVar = rhs.keyCatchWeightObsVar; matureModel = rhs.matureModel; keyMatureMean = rhs.keyMatureMean; mortalityModel = rhs.mortalityModel; keyMortalityMean = rhs.keyMortalityMean; keyMortalityObsVar = rhs.keyMortalityObsVar; keyXtraSd = rhs.keyXtraSd; return *this; }; }; template <class Type> struct paraSet{ vector<Type> logFpar; vector<Type> logQpow; vector<Type> logSdLogFsta; vector<Type> logSdLogN; vector<Type> logSdLogObs; vector<Type> logSdLogTotalObs; vector<Type> transfIRARdist; vector<Type> sigmaObsParUS; vector<Type> rec_pars; vector<Type> itrans_rho; vector<Type> logScale; vector<Type> logitReleaseSurvival; vector<Type> logitRecapturePhi; vector<Type> sepFalpha; vector<Type> sepFlogitRho; vector<Type> sepFlogSd; vector<Type> predVarObs; Type logFScaleMSY; Type implicitFunctionDelta; Type logScaleFmsy; Type logScaleFmax; Type logScaleF01; Type logScaleFcrash; Type logScaleFext; vector<Type> logScaleFxPercent; Type logScaleFlim; matrix<Type> logScaleFmsyRange; vector<Type> logPhiSW; vector<Type> logSdProcLogSW; vector<Type> meanLogSW; vector<Type> logSdLogSW; vector<Type> logPhiCW; vector<Type> logSdProcLogCW; vector<Type> meanLogCW; vector<Type> logSdLogCW; vector<Type> logPhiMO; vector<Type> logSdProcLogitMO; vector<Type> meanLogitMO; vector<Type> logSdMO; vector<Type> logPhiNM; vector<Type> logSdProcLogNM; vector<Type> meanLogNM; vector<Type> logSdLogNM; vector<Type> logXtraSd; paraSet() {}; paraSet(SEXP x){ logFpar = asVector<Type>(getListElement(x,"logFpar")); logQpow = asVector<Type>(getListElement(x,"logQpow")); logSdLogFsta = asVector<Type>(getListElement(x,"logSdLogFsta")); logSdLogN = asVector<Type>(getListElement(x,"logSdLogN")); logSdLogObs = asVector<Type>(getListElement(x,"logSdLogObs")); logSdLogTotalObs = asVector<Type>(getListElement(x,"logSdLogTotalObs")); transfIRARdist = asVector<Type>(getListElement(x,"transfIRARdist")); sigmaObsParUS = asVector<Type>(getListElement(x,"sigmaObsParUS")); rec_pars = asVector<Type>(getListElement(x,"rec_pars")); itrans_rho = asVector<Type>(getListElement(x,"itrans_rho")); logScale = asVector<Type>(getListElement(x,"logScale")); logitReleaseSurvival = asVector<Type>(getListElement(x,"logitReleaseSurvival")); logitRecapturePhi = asVector<Type>(getListElement(x,"logitRecapturePhi")); sepFalpha = asVector<Type>(getListElement(x,"sepFalpha")); sepFlogitRho = asVector<Type>(getListElement(x,"sepFlogitRho")); sepFlogSd = asVector<Type>(getListElement(x,"sepFlogSd")); logFScaleMSY = (Type)Rf_asReal(getListElement(x,"logFScaleMSY")); implicitFunctionDelta = (Type)Rf_asReal(getListElement(x,"implicitFunctionDelta")); logScaleFmsy = (Type)Rf_asReal(getListElement(x,"logScaleFmsy")); logScaleFmax = (Type)Rf_asReal(getListElement(x,"logScaleFmax")); logScaleF01 = (Type)Rf_asReal(getListElement(x,"logScaleF01")); logScaleFcrash = (Type)Rf_asReal(getListElement(x,"logScaleFcrash")); logScaleFext = (Type)Rf_asReal(getListElement(x,"logScaleFext")); logScaleFxPercent = asVector<Type>(getListElement(x,"logScaleFxPercent")); logScaleFlim = (Type)Rf_asReal(getListElement(x,"logScaleFlim")); logScaleFmsyRange = asMatrix<Type>(getListElement(x,"logScaleFmsyRange")); logPhiSW = asVector<Type>(getListElement(x,"logPhiSW")); logSdProcLogSW = asVector<Type>(getListElement(x,"logSdProcLogSW")); meanLogSW = asVector<Type>(getListElement(x,"meanLogSW")); logSdLogSW = asVector<Type>(getListElement(x,"logSdLogSW")); logPhiCW = asVector<Type>(getListElement(x,"logPhiCW")); logSdProcLogCW = asVector<Type>(getListElement(x,"logSdProcLogCW")); meanLogCW = asVector<Type>(getListElement(x,"meanLogCW")); logSdLogCW = asVector<Type>(getListElement(x,"logSdLogCW")); logPhiMO = asVector<Type>(getListElement(x,"logPhiMO")); logSdProcLogitMO = asVector<Type>(getListElement(x,"logSdProcLogitMO")); meanLogitMO = asVector<Type>(getListElement(x,"meanLogitMO")); logSdMO = asVector<Type>(getListElement(x,"logSdMO")); logPhiNM = asVector<Type>(getListElement(x,"logPhiNM")); logSdProcLogNM = asVector<Type>(getListElement(x,"logSdProcLogNM")); meanLogNM = asVector<Type>(getListElement(x,"meanLogNM")); logSdLogNM = asVector<Type>(getListElement(x,"logSdLogNM")); logXtraSd = asVector<Type>(getListElement(x,"logXtraSd")); } paraSet<Type>& operator=(const paraSet<Type>& rhs) { logFpar = rhs.logFpar; logQpow = rhs.logQpow; logSdLogFsta = rhs.logSdLogFsta; logSdLogN = rhs.logSdLogN; logSdLogObs = rhs.logSdLogObs; logSdLogTotalObs = rhs.logSdLogTotalObs; transfIRARdist = rhs.transfIRARdist; sigmaObsParUS = rhs.sigmaObsParUS; rec_pars = rhs.rec_pars; itrans_rho = rhs.itrans_rho; logScale = rhs.logScale; logitReleaseSurvival = rhs.logitReleaseSurvival; logitRecapturePhi = rhs.logitRecapturePhi; sepFalpha = rhs.sepFalpha; sepFlogitRho = rhs.sepFlogitRho; sepFlogSd = rhs.sepFlogSd; logFScaleMSY = rhs.logFScaleMSY; implicitFunctionDelta = rhs.implicitFunctionDelta; logScaleFmsy = rhs.logScaleFmsy; logScaleFmax = rhs.logScaleFmax; logScaleF01 = rhs.logScaleF01; logScaleFcrash = rhs.logScaleFcrash; logScaleFext = rhs.logScaleFext; logScaleFxPercent = rhs.logScaleFxPercent; logScaleFlim = rhs.logScaleFlim; logScaleFmsyRange = rhs.logScaleFmsyRange; logPhiSW = rhs.logPhiSW; logSdProcLogSW = rhs.logSdProcLogSW; meanLogSW = rhs.meanLogSW; logSdLogSW = rhs.logSdLogSW; logPhiCW = rhs.logPhiCW; logSdProcLogCW = rhs.logSdProcLogCW; meanLogCW = rhs.meanLogCW; logSdLogCW = rhs.logSdLogCW; logPhiMO = rhs.logPhiMO; logSdProcLogitMO = rhs.logSdProcLogitMO; meanLogitMO = rhs.meanLogitMO; logSdMO = rhs.logSdMO; logPhiNM = rhs.logPhiNM; logSdProcLogNM = rhs.logSdProcLogNM; meanLogNM = rhs.meanLogNM; logSdLogNM = rhs.logSdLogNM; logXtraSd = rhs.logXtraSd; return *this; } template<class T> paraSet<T> cast() const { paraSet<T> d; d.logFpar = logFpar.template cast<T>(); d.logQpow = logQpow.template cast<T>(); d.logSdLogFsta = logSdLogFsta.template cast<T>(); d.logSdLogN = logSdLogN.template cast<T>(); d.logSdLogObs = logSdLogObs.template cast<T>(); d.logSdLogTotalObs = logSdLogTotalObs.template cast<T>(); d.transfIRARdist = transfIRARdist.template cast<T>(); d.sigmaObsParUS = sigmaObsParUS.template cast<T>(); d.rec_pars = rec_pars.template cast<T>(); d.itrans_rho = itrans_rho.template cast<T>(); d.logScale = logScale.template cast<T>(); d.logitReleaseSurvival = logitReleaseSurvival.template cast<T>(); d.logitRecapturePhi = logitRecapturePhi.template cast<T>(); d.sepFalpha = sepFalpha.template cast<T>(); d.sepFlogitRho = sepFlogitRho.template cast<T>(); d.sepFlogSd = sepFlogSd.template cast<T>(); d.logFScaleMSY = T(logFScaleMSY); d.implicitFunctionDelta = T(implicitFunctionDelta); d.logScaleFmsy = T(logScaleFmsy); d.logScaleFmax = T(logScaleFmax); d.logScaleF01 = T(logScaleF01); d.logScaleFcrash = T(logScaleFcrash); d.logScaleFext = T(logScaleFext); d.logScaleFxPercent = logScaleFxPercent.template cast<T>(); d.logScaleFlim = T(logScaleFlim); d.logScaleFmsyRange = logScaleFmsyRange.template cast<T>(); d.logPhiSW = logPhiSW.template cast<T>(); d.logSdProcLogSW = logSdProcLogSW.template cast<T>(); d.meanLogSW = meanLogSW.template cast<T>(); d.logSdLogSW = logSdLogSW.template cast<T>(); d.logPhiCW = logPhiCW.template cast<T>(); d.logSdProcLogCW = logSdProcLogCW.template cast<T>(); d.meanLogCW = meanLogCW.template cast<T>(); d.logSdLogCW = logSdLogCW.template cast<T>(); d.logPhiMO = logPhiMO.template cast<T>(); d.logSdProcLogitMO = logSdProcLogitMO.template cast<T>(); d.meanLogitMO = meanLogitMO.template cast<T>(); d.logSdMO = logSdMO.template cast<T>(); d.logPhiNM = logPhiNM.template cast<T>(); d.logSdProcLogNM = logSdProcLogNM.template cast<T>(); d.meanLogNM = meanLogNM.template cast<T>(); d.logSdLogNM = logSdLogNM.template cast<T>(); d.logXtraSd = logXtraSd.template cast<T>(); return d; } }; template <class Type> void prepareForForecast(dataSet<Type>& dat, confSet& conf, paraSet<Type>& par, array<Type>& logF, array<Type>& logN){ int nFYears = dat.forecast.nYears; int nMYears = dat.noYears; if(nFYears == 0) return; vector<int> aveYears = dat.forecast.aveYears; // propMat extendArray(dat.propMat, nMYears, nFYears, aveYears); // stockMeanWeight extendArray(dat.stockMeanWeight, nMYears, nFYears, aveYears); // catchMeanWeight extendArray(dat.catchMeanWeight, nMYears, nFYears, aveYears); // natMor extendArray(dat.natMor, nMYears, nFYears, aveYears); // landFrac extendArray(dat.landFrac, nMYears, nFYears, aveYears); // disMeanWeight extendArray(dat.disMeanWeight, nMYears, nFYears, aveYears); // landMeanWeight extendArray(dat.landMeanWeight, nMYears, nFYears, aveYears); // propF extendArray(dat.propF, nMYears, nFYears, aveYears); // propM extendArray(dat.propM, nMYears, nFYears, aveYears); // Prepare forecastCalculated... dat.forecast.forecastCalculatedMedian = matrix<Type>(logF.rows(), nFYears); dat.forecast.forecastCalculatedMedian.setZero(); dat.forecast.forecastCalculatedLogSdCorrection = vector<Type>(nFYears); dat.forecast.forecastCalculatedLogSdCorrection.setZero(); // Calculate initial Fbar int fbarFirst = conf.fbarRange(0) - conf.minAge; int fbarLast = conf.fbarRange(1) - conf.minAge; dat.forecast.initialFbar = 0.0; for(int a = fbarFirst; a <= fbarLast; ++a){ dat.forecast.initialFbar += exp(logF(conf.keyLogFsta(0,a),dat.forecast.forecastYear.size() - nFYears - 1)); } dat.forecast.initialFbar /= Type(fbarLast - fbarFirst + 1); // Calculate selectivity dat.forecast.sel = vector<Type>(logF.rows()); dat.forecast.sel.setZero(); dat.forecast.selFull = vector<Type>(logN.rows()); dat.forecast.selFull.setZero(); // Correct input selectivity to have Fbar == 1 Type inputFbar = 0.0; if(dat.forecast.selectivity.size() > 0){ // Rcout << "Using custom selectivity!\n"; for(int a = fbarFirst; a <= fbarLast; ++a){ if(dat.forecast.selectivity.size() == logF.rows()){ inputFbar += dat.forecast.selectivity(conf.keyLogFsta(0,a)); }else if(dat.forecast.selectivity.size() == logN.rows()){ inputFbar += dat.forecast.selectivity(a); }else{ Rf_error("Wrong size of selectivity. Must match logF or logN array."); } } inputFbar /= Type(fbarLast - fbarFirst + 1); if(inputFbar != 1.0){ // Rf_warning("The input selectivity was re-scaled to have Fbar equal to one."); dat.forecast.selectivity /= inputFbar; } } for(int j = 0; j < logN.rows(); ++j){ if(conf.keyLogFsta(0,j)>(-1)){ if(dat.forecast.selectivity.size() == 0){ dat.forecast.selFull(j) = exp(logF(conf.keyLogFsta(0,j),dat.forecast.forecastYear.size() - nFYears - 1)) / dat.forecast.initialFbar; dat.forecast.sel(conf.keyLogFsta(0,j)) = dat.forecast.selFull(j); }else if(dat.forecast.selectivity.size() == logF.rows()){ dat.forecast.selFull(j) = dat.forecast.selectivity(conf.keyLogFsta(0,j)); }else if(dat.forecast.selectivity.size() == logN.rows()){ dat.forecast.selFull(j) = dat.forecast.selectivity(j); }else{ Rf_error("Wrong size of selectivity. Must match logF or logN array."); } dat.forecast.sel(conf.keyLogFsta(0,j)) = dat.forecast.selFull(j); } } return; } template<class Type> void forecastSet<Type>::calculateForecast(array<Type>& logF, array<Type>& logN, dataSet<Type>& dat, confSet& conf, paraSet<Type>& par){ if(nYears == 0){ // no forecast return; } for(int i = 0; i < nYears; ++i){ updateForecast(i, logF, logN, dat, conf, par); } return; } template<class Type> void forecastSet<Type>::updateForecast(int i, array<Type>& logF, array<Type>& logN, dataSet<Type>& dat, confSet& conf, paraSet<Type>& par){ if(nYears == 0){ // no forecast return; } int indx = forecastYear.size() - nYears + i; Type y = forecastYear(indx); Type lastSSB = ssbi(dat, conf, logN, logF, indx-1); Type calcF = 0.0; vector<Type> lastFullLogF(logN.rows()); for(int j = 0; j < logN.rows(); ++j){ if(conf.keyLogFsta(0,j)>(-1)){ if(i == 0){ lastFullLogF(j) = log(initialFbar) + log(selFull(j)); }else{ lastFullLogF(j) = forecastCalculatedMedian(conf.keyLogFsta(0,j),i-1); } }else{ lastFullLogF(j)= 0.0; } } switch(fsdTimeScaleModel(i)) { case rwScale: forecastCalculatedLogSdCorrection(i) = sqrt(y); break; case oneScale: forecastCalculatedLogSdCorrection(i) = 1.0; break; case zeroScale: forecastCalculatedLogSdCorrection(i) = 1e-6; break; default: Rf_error("F time scale model not implemented"); } // Calculate CV correction switch(FModel(i)) { // target is not used. F is a random walk case asFModel: if(fsdTimeScaleModel(i) != oneScale) Rf_warning("F time scale model is ignored when the F model is used for forecasting."); forecastCalculatedLogSdCorrection(i) = 1.0; forecastCalculatedMedian.col(i) = logF.col(indx - 1); break; case useFscale: // target is an F scale of previous F if(i == 0){ forecastCalculatedMedian.col(i) = log(target(i)) + log(initialFbar) + log(sel); }else{ forecastCalculatedMedian.col(i) = log(target(i)) + (vector<Type>)forecastCalculatedMedian.col(i-1); } break; case useFval: // target is F value forecastCalculatedMedian.col(i) = log(target(i)) + log(sel); break; case useCatchval: // target is a catch value in weight if(uniroot){ calcF = catch2F((Type)target(i), exp(lastFullLogF), (vector<Type>)dat.natMor.matrix().row(indx), exp((vector<Type>)logN.col(indx)), (vector<Type>)dat.catchMeanWeight.matrix().row(indx)); }else{ calcF = catch2F_quick((Type)target(i), exp(lastFullLogF), (vector<Type>)dat.natMor.matrix().row(indx), exp((vector<Type>)logN.col(indx)), (vector<Type>)dat.catchMeanWeight.matrix().row(indx)); } if(i == 0){ forecastCalculatedMedian.col(i) = log(calcF) + log(initialFbar) + log(sel); }else{ forecastCalculatedMedian.col(i) = log(calcF) + (vector<Type>)forecastCalculatedMedian.col(i-1); } break; case useNextssb: Rf_error("Forecast type not implemented"); case useLandval: if(uniroot){ calcF = landing2F((Type)target(i), exp(lastFullLogF), (vector<Type>)dat.natMor.matrix().row(indx), exp((vector<Type>)logN.col(indx)), (vector<Type>)dat.landMeanWeight.matrix().row(indx), (vector<Type>)dat.landFrac.matrix().row(indx)); }else{ calcF = landing2F_quick((Type)target(i), exp(lastFullLogF), (vector<Type>)dat.natMor.matrix().row(indx), exp((vector<Type>)logN.col(indx)), (vector<Type>)dat.landMeanWeight.matrix().row(indx), (vector<Type>)dat.landFrac.matrix().row(indx)); } if(i == 0){ forecastCalculatedMedian.col(i) = log(calcF) + log(initialFbar) + log(sel); }else{ forecastCalculatedMedian.col(i) = log(calcF) + (vector<Type>)forecastCalculatedMedian.col(i-1); } break; case findMSY: forecastCalculatedMedian.col(i) = par.logFScaleMSY + log(initialFbar) + log(sel); // break; case HCR: forecastCalculatedMedian.col(i) = hcr(lastSSB, hcrConf) + log(sel); // break; case customHCR: Rf_error("Forecast type not implemented"); break; default: Rf_error("Forecast type not implemented"); } return; } template<class Type> Type logspace_add_p (Type logx, Type logy, Type p) { return log((Type(1)-p)*exp(logy-logx)+p)+logx; // the order of x and y is taylored for this application } template<class Type> Type logdrobust(Type x, Type p){ Type ld1=dnorm(x,Type(0.0),Type(1.0),true); if(p<Type(1.0e-16)){ return ld1; }else{ Type ld2=dt(x,Type(3),true); Type logres=logspace_add_p(ld2,ld1,p); return logres; } } VECTORIZE2_tt(logdrobust) template <class Type> class MVMIX_t{ Type halfLogDetS; Type p1; /*fraction t3*/ matrix<Type> Sigma; vector<Type> sd; matrix<Type> L_Sigma; matrix<Type> inv_L_Sigma; public: MVMIX_t(){} MVMIX_t(matrix<Type> Sigma_, Type p1_){ setSigma(Sigma_); p1=p1_; } matrix<Type> cov(){return Sigma;} void setSigma(matrix<Type> Sigma_){ Sigma = Sigma_; sd = sqrt(vector<Type>(Sigma.diagonal())); Eigen::LLT<Eigen::Matrix<Type,Eigen::Dynamic,Eigen::Dynamic> > llt(Sigma); L_Sigma = llt.matrixL(); vector<Type> D=L_Sigma.diagonal(); halfLogDetS = sum(log(D)); inv_L_Sigma = atomic::matinv(L_Sigma); } void setSigma(matrix<Type> Sigma_, Type p1_){ setSigma(Sigma_); p1=p1_; } /** \brief Evaluate the negative log density */ Type operator()(vector<Type> x){ vector<Type> z = inv_L_Sigma*x; return -sum(logdrobust(z,p1))+halfLogDetS; } Type operator()(vector<Type> x, vector<Type> keep){ matrix<Type> S = Sigma; vector<Type> not_keep = Type(1.0) - keep; for(int i = 0; i < S.rows(); i++){ for(int j = 0; j < S.cols(); j++){ S(i,j) = S(i,j) * keep(i) * keep(j); } //S(i,i) += not_keep(i) * pow((Type(1)-p1)*sqrt(Type(0.5)/M_PI)+p1*(Type(1)/M_PI),2); //(t(1)) S(i,i) += not_keep(i) * pow((Type(1)-p1)*sqrt(Type(0.5)/M_PI)+p1*(Type(2)/(M_PI*sqrt(Type(3)))),2); } return MVMIX_t<Type>(S,p1)(x * keep); } vector<Type> simulate() { int siz = Sigma.rows(); vector<Type> x(siz); for(int i=0; i<siz; ++i){ Type u = runif(0.0,1.0); if(u<p1){ x(i) = rt(3.0); }else{ x(i) = rnorm(0.0,1.0); } } x = L_Sigma*x; return x; } }; template <class Type> MVMIX_t<Type> MVMIX(matrix<Type> Sigma, Type p1){ return MVMIX_t<Type>(Sigma,p1); } template <class Type> Type findLinkV(Type k, int n=0){ // small helper function to solve exp(v)-exp(k-v/2)-1=0 for v Type v = log(exp(k)+Type(1)); for(int i=0; i<n; ++i){ v -= (exp(v)-exp(k-0.5*v)-1.0)/(exp(v)+.5*exp(k-0.5*v)); } return v; }
#ifndef NPNHANDLE_H #define NPNHANDLE_H /// @file NpnHandle.h /// @brief NpnHandle のヘッダファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2005-2012 Yusuke Matsunaga /// All rights reserved. #include "YmTools.h" #include "NpnXform.h" BEGIN_NAMESPACE_YM ////////////////////////////////////////////////////////////////////// /// @class NpnHandle NpnHandle.h "NpnHandle.h" /// @brief NpnNode と NPN変換の組を表すクラス ////////////////////////////////////////////////////////////////////// class NpnHandle { friend class NpnNode; friend class NpnNodeMgr; public: /// @brief コンストラクタ NpnHandle(); /// @brief 内容を指定したコンストラクタ /// @param[in] id ノード番号 /// @param[in] xf NPN変換 NpnHandle(ymuint id, NpnXform xf); public: ////////////////////////////////////////////////////////////////////// // 外部インターフェイス ////////////////////////////////////////////////////////////////////// /// @brief 内容を設定する. /// @param[in] id ノード番号 /// @param[in] xf NPN変換 void set(ymuint id, NpnXform xf); /// @brief ノード番号を返す. ymuint node_id() const; /// @brief NPN変換を返す. NpnXform npn_xform() const; /// @brief 出力の反転属性を得る. bool oinv() const; /// @brief 入力の反転属性を得る. bool iinv(ymuint pos) const; /// @brief 出力を反転させる. void flip_oinv(); /// @brief 入力を反転させる. void flip_iinv(ymuint pos); /// @brief ハッシュ用の値を返す. ymuint hash() const; /// @brief 出力を反転したハンドルを返す. NpnHandle operator~() const; /// @brief 等価比較 friend bool operator==(NpnHandle left, NpnHandle right); /// @brief 大小比較 friend bool operator<(NpnHandle left, NpnHandle right); private: ////////////////////////////////////////////////////////////////////// // 内部で用いられる関数 ////////////////////////////////////////////////////////////////////// /// @brief 内容を直接指定したコンストラクタ explicit NpnHandle(ymuint32 data); private: ////////////////////////////////////////////////////////////////////// // データメンバ ////////////////////////////////////////////////////////////////////// // 本体 ymuint32 mData; }; /// @brief 等価比較 /// @param[in] left, right オペランド bool operator==(NpnHandle left, NpnHandle right); /// @brief 非等価比較 /// @param[in] left, right オペランド bool operator!=(NpnHandle left, NpnHandle right); /// @brief 大小比較 ( < ) /// @param[in] left, right オペランド bool operator<(NpnHandle left, NpnHandle right); /// @brief 大小比較 ( > ) /// @param[in] left, right オペランド bool operator>(NpnHandle left, NpnHandle right); /// @brief 大小比較 ( <= ) /// @param[in] left, right オペランド bool operator<=(NpnHandle left, NpnHandle right); /// @brief 大小比較 ( >= ) /// @param[in] left, right オペランド bool operator>=(NpnHandle left, NpnHandle right); /// @brief ストリーム出力 ostream& operator<<(ostream& s, NpnHandle handle); ////////////////////////////////////////////////////////////////////// // インライン関数の定義 ////////////////////////////////////////////////////////////////////// // @brief コンストラクタ inline NpnHandle::NpnHandle() { } // @brief 内容を指定したコンストラクタ // @param[in] id ノード番号 // @param[in] xf NPN変換 inline NpnHandle::NpnHandle(ymuint id, NpnXform xf) { set(id, xf); } // @brief 内容を直接指定したコンストラクタ inline NpnHandle::NpnHandle(ymuint32 data) : mData(data) { } // @brief 内容を設定する. // @param[in] id ノード番号 // @param[in] xf NPN変換 inline void NpnHandle::set(ymuint id, NpnXform xf) { mData = (id << 10) | xf.data(); } // @brief ノード番号を返す. inline ymuint NpnHandle::node_id() const { return mData >> 10; } // @brief NPN変換を返す. inline NpnXform NpnHandle::npn_xform() const { return NpnXform(mData & 1023U); } // @brief 出力の反転属性を得る. inline bool NpnHandle::oinv() const { return static_cast<bool>(mData & 1U); } // @brief 入力の反転属性を得る. inline bool NpnHandle::iinv(ymuint pos) const { return static_cast<bool>((mData >> (pos + 1)) & 1U); } // @brief 出力を反転させる. inline void NpnHandle::flip_oinv() { mData ^= 1U; } // @brief 入力を反転させる. inline void NpnHandle::flip_iinv(ymuint pos) { mData ^= (2U << pos); } // @brief 出力を反転したハンドルを返す. inline NpnHandle NpnHandle::operator~() const { return NpnHandle(mData ^ 1U); } // @brief ハッシュ用の値を返す. inline ymuint NpnHandle::hash() const { return mData; } // @brief 等価比較 inline bool operator==(NpnHandle left, NpnHandle right) { return left.mData == right.mData; } // @brief 非等価比較 inline bool operator!=(NpnHandle left, NpnHandle right) { return !operator==(left, right); } // @brief 大小比較 ( < ) inline bool operator<(NpnHandle left, NpnHandle right) { return left.mData < right.mData; } // @brief 大小比較 ( > ) inline bool operator>(NpnHandle left, NpnHandle right) { return operator<(right, left); } // @brief 大小比較 ( <= ) inline bool operator<=(NpnHandle left, NpnHandle right) { return !operator<(right, left); } // @brief 大小比較 ( >= ) inline bool operator>=(NpnHandle left, NpnHandle right) { return !operator<(left, right); } // @brief ストリーム出力 inline ostream& operator<<(ostream& s, NpnHandle handle) { ymuint id = handle.node_id(); NpnXform xf = handle.npn_xform(); s << xf << ": NODE#" << id; return s; } END_NAMESPACE_YM BEGIN_NAMESPACE_HASH // NpnHandle をキーにした関数クラスの定義 template <> struct hash<nsYm::NpnHandle> { ymuint operator()(nsYm::NpnHandle handle) const { return handle.hash(); } }; END_NAMESPACE_HASH #endif // NPNHANDLE_H
#include <cstdlib> #include <cstdio> #include <cmath> #include <fstream> #include <vector> #include <iostream> #include <cassert> #include <algorithm> #include <sstream> #include "Ray.h" #include "Light.h" #include "GeoObject.h" #include "Sphere.h" #include "Triangle.h" #include "Scene.h" #include "SimpleObject.h" //Right Hand Coordinate System //Took ambient light, eta for granted, TODO, need to change this //Took Camera position, center for granted, TOOD, may need to change this int main(int args, char* argv[]) { printf("Beginning...\n"); printf("Received %d Arguments: \n", args); for (int i = 0; i < args; ++i) { std::cout << argv[i] << std::endl; } SimpleOBJ::CSimpleObject inputObj; inputObj.LoadFromObj(argv[1]); Scene scene; std::vector<GeoObject*>& objects = scene.objects;; std::vector<Light>& lights = scene.lights; Vec3f color = Vec3f(0.5, 0.2, 0.3); Vec3f zero(0); Vec3f one(1); Material purple; purple = Material(color, color, color, color, zero, 10); for (int i = 0; i < inputObj.m_nTriangles; ++i) { Vec3f pos[3]; for (int index = 0; index < 3; ++index) { int k = inputObj.m_pTriangleList[i][index]; pos[index] = inputObj.m_pVertexList[k]; } Triangle *tri; tri = new Triangle( pos[0], pos[2], pos[1], purple ); objects.push_back(tri); } //objects.push_back(new Sphere(Vec3f(0.5, 1, -10), 2, purple)); Vec3f white = Vec3f(1.0); Vec3f black = Vec3f(0.0); Material mat[2]; mat[1] = Material(white, white, white, white, white, 1); mat[0] = Material(black, black, black, black, black, 1); for (int xx = -4; xx <= 3; xx++) for (int zz = -4; zz >= -11; zz--) { int flag; if ((xx + zz) & 1) flag = 1; else flag = 0; Triangle *tri; tri = new Triangle( Vec3f(xx, -1, zz), Vec3f(xx + 1, -1, zz), Vec3f(xx + 1, -1, zz - 1), mat[flag] ); objects.push_back(tri); tri = new Triangle( Vec3f(xx, -1, zz), Vec3f(xx + 1, -1, zz - 1), Vec3f(xx, -1, zz - 1), mat[flag] ); objects.push_back(tri); } for (int xx = -4; xx <= 3; ++xx) { for (int yy = -1; yy <= 6; ++yy) { int flag; if ((xx + yy) & 1) flag = 0; else flag = 1; Triangle *tri; tri = new Triangle( Vec3f(xx, yy, -12), Vec3f(xx + 1, yy, -12), Vec3f(xx + 1, yy + 1, -12), mat[flag] ); objects.push_back(tri); tri = new Triangle( Vec3f(xx, yy, -12), Vec3f(xx + 1, yy + 1, -12), Vec3f(xx, yy + 1, -12), mat[flag] ); objects.push_back(tri); } } Vec3f lpos = Vec3f(0, 8, -8); Vec3f lcolor = Vec3f(1); Light light = Light(POINT, lpos, lcolor, Vec3f(0)); lights.push_back(light); printf("%d Objects\n", (int)objects.size()); scene.camera = Camera(); scene.camera.position = Vec3f(0, 2, 5); scene.Render("./Output/Cube.ppm"); printf("Done!!!! Finished Ray Tracing %d Objects!!!!!\n", (int)objects.size()); system("pause"); return 0; } /*Vec3f trace( const Ray ray, const std::vector<GeoObject*> &objects, const std::vector<Light> &lights, int depth) { if (depth == MAX_RAY_DEPTH) return Vec3f(0); const GeoObject* hitObject = NULL; float tNear = INFINITY; ShadeRec rec; ShadeRec rectmp; for (unsigned i = 0; i < objects.size(); ++i) { float t0 = 0; if (objects[i]->intersect(ray, t0, rectmp) == true) { //printf("Hit!"); if (t0 < tNear) { tNear = t0; rec.hitPoint = rectmp.hitPoint; rec.material = rectmp.material; rec.normal = rectmp.normal; hitObject = objects[i]; } } } if (hitObject == NULL) return Vec3f(0); Vec3f ambient = rec.material.ambient * ENVIRONMENT_LIGHT; //cast a ray from every light source, Local Lighting Vec3f diffuse = Vec3f(0); Vec3f specular = Vec3f(0); for (unsigned i = 0; i < lights.size(); ++i) { Light light = lights[i]; Vec3f raydir = rec.hitPoint - light.position; float len = raydir.length(); raydir = raydir.normalize(); if (raydir.dot(rec.normal) > 0) continue; Point rayorigin = light.position; Ray ray = Ray(rayorigin, raydir); bool blocked = false; for (unsigned i = 0; i < objects.size(); ++i) { float t0 = 0; ShadeRec rectmp; if (objects[i]->intersect(ray, t0, rectmp)) { if (t0 < len - HIT_POINT_BIAS) { blocked = true; break; } } } if (!blocked) { //Calculate diffuse float cosTheta = raydir.dot(rec.normal); if (cosTheta < 0) { diffuse += -rec.material.diffuse * light.color * cosTheta; } //Calculate specular Vec3f reflectDir = - (rec.normal * (rec.normal.dot(raydir)) * 2 - raydir); cosTheta = reflectDir.dot(rec.hitPoint.normalize()); if (cosTheta > 0) { specular += rec.material.specular * light.color * pow(cosTheta, rec.material.shininess); } } } Vec3f reflectColor = Vec3f(0); Vec3f refractColor = Vec3f(0); // recursively compute EITHER reflection OR refraction if (rec.material.specular != Vec3f(0)) { Vec3f reflectOrigin = rec.hitPoint; float cosTheta = rec.normal.dot(ray.dir); Vec3f raydirection = -(rec.normal * cosTheta * 2 - ray.dir); Ray reflectRay = Ray(reflectOrigin, raydirection); reflectColor = trace(reflectRay, objects, lights, depth + 1) * rec.material.specular; } if (rec.material.transparent != Vec3f(0)) { Vec3f refractOrigin = rec.hitPoint; bool inside = false; if (ray.dir.dot(rec.normal) > 0) { //inside the object inside = true; } else { rec.normal = -rec.normal; } float eta = (!inside) ? CONST_ETA : 1 / CONST_ETA; float cos1 = rec.normal.dot(ray.dir); float k = 1 - (1 - cos1 * cos1) / (eta*eta); if (k < 0) k = 0; float cos2 = sqrt(k); Vec3f refractDir = ray.dir * (1 / eta) + rec.normal * (cos2 - cos1 / eta); refractDir = refractDir.normalize(); refractColor = trace(Ray(refractOrigin, refractDir), objects, lights, depth + 1) * rec.material.transparent; } Vec3f ret = specular + diffuse + ambient + reflectColor + refractColor; return ret.clamp(); } void render(const std::vector<GeoObject*> &objects, const std::vector<Light> &lights) { unsigned width = 640, height = 480; Vec3f *image = new Vec3f[width * height], *pixel = image; float invWidth = 1 / float(width), invHeight = 1 / float(height); float fov = 50, aspectratio = width / float(height); float angle = tan(M_PI * 0.5 * fov / 180.); // Trace rays for (unsigned y = 0; y < height; ++y) { for (unsigned x = 0; x < width; ++x, ++pixel) { float xx = (2 * ((x + 0.5) * invWidth) - 1) * angle * aspectratio; float yy = (1 - 2 * ((y + 0.5) * invHeight)) * angle; Vec3f origin(0, 0, 0); Vec3f dir(xx, yy, -1); dir = dir.normalize(); Ray ray = Ray(origin, dir); *pixel = trace(ray, objects, lights, 0); } printf("%d * %d\n", y, width); } // Save result to a PPM image (keep these flags if you compile under Windows) std::ofstream ofs("./RefractpReflect.ppm", std::ios::out | std::ios::binary); ofs << "P6\n" << width << " " << height << "\n255\n"; for (unsigned i = 0; i < width * height; ++i) { ofs << (unsigned char)(std::min(float(1), image[i].x) * 255) << (unsigned char)(std::min(float(1), image[i].y) * 255) << (unsigned char)(std::min(float(1), image[i].z) * 255); } ofs.close(); delete[] image; }*/ /*bool ReadValues(std::stringstream & s, const int num, float * values) { for (int i = 0; i < num; i++) { s >> values[i]; if (s.fail()) { std::cerr << "Failed Reading Values " << i << " Will Skip.\n"; return false; } } return true; } void parseOBJ(std::vector<GeoObject*> &objects) { std::vector<Point> points; std::ifstream file("bunny.obj"); std::string str, cmd; float values[3]; Vec3f v(1, 1, 1); Vec3f zero(0); Material material = Material(v, v, v, zero, zero, 2); while (std::getline(file, str)) { if (str[0] == '#') { continue; } std::stringstream s(str); s >> cmd; if (cmd == "v") { ReadValues(s, 3, values); points.push_back(Point(values[0] * 100, values[1] * 100, values[2] * 100)); } if (cmd == "f") { ReadValues(s, 3, values); //printf("%d\n", (int)objects.size()); Triangle *tri = new Triangle( points[(int)values[0]-1], points[(int)values[1]-1], points[(int)values[2]-1], material ); objects.push_back(tri); } } } */
/** * John Bradley (jrb@turrettech.com) */ #pragma once #include "..\JavascriptExtension.h" #include <string> class AudioPlayerExtension : public JavascriptExtension { public: AudioPlayerExtension(); public: JSValue Handle(const std::string &functionName, const Awesomium::JSArray &args); }; class AudioPlayerExtensionFactory : public JavascriptExtensionFactory { public: JavascriptExtension *Create() { return new AudioPlayerExtension(); } };
#include "Point.h" void Point::move(char dir) {// move point , down/right/left switch (dir) { case RIGHT_KEY: dir_x = 1; dir_y = 0; break; case KEEP_DOWN: dir_x = 0; dir_y = 1; break; case LEFT_KEY: dir_x = -1; dir_y = 0; break; } x += dir_x; y += dir_y; // update the cord of the points }
#ifndef __air_context_cpp__ #define __air_context_cpp__ #include "air_context.hpp" #include "diagnostic.hpp" #include "semantic.hpp" #include <llvm/Support/TargetRegistry.h> #include <llvm/Support/raw_os_ostream.h> #include <llvm/Target/TargetOptions.h> #include <llvm/IR/LegacyPassManager.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/FileSystem.h> #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/IRBuilder.h> #include <llvm/ADT/Optional.h> #include <llvm/Support/Host.h> #include <llvm/IR/Constant.h> #include <llvm/IR/Verifier.h> #include <llvm/IR/Function.h> #include <llvm/IR/Module.h> #include <llvm/IR/Type.h> namespace alioth { AirContext::AirContext( string _arch, string _plat, Diagnostics& diag ): diagnostics(diag),arch(_arch),platform(_plat),targetMachine(nullptr) { using namespace llvm; using namespace llvm::sys; TargetOptions targetOptions; std::string Error; auto CPU = "generic"; auto Features = ""; /** [TODO]: 支持更多架构 */ targetTriple = getDefaultTargetTriple(); LLVMInitializeX86TargetInfo(); LLVMInitializeX86Target(); LLVMInitializeX86TargetMC(); //LLVMInitializeX86AsmParser(); LLVMInitializeX86AsmPrinter(); auto target = TargetRegistry::lookupTarget(targetTriple, Error); if( !target ) { diagnostics["llvm"]("81", Error ); throw runtime_error("llvm error"); } auto RM = Optional<Reloc::Model>(); targetMachine = target->createTargetMachine( targetTriple, CPU, Features, targetOptions, RM); } AirContext::~AirContext() { if( targetMachine ) delete targetMachine; targetMachine = nullptr; } bool AirContext::operator()( $module semantic, ostream& os ) { auto success = translateModule(semantic); string source_names; auto cctx = semantic->getCompilerContext(); auto space = cctx.getSpaceEngine(); for( auto [doc,rec] : semantic->sig->docs ) source_names += (string)space.getUri(doc) + "; "; module->setSourceFileName( source_names ); string error; auto errrso = llvm::raw_string_ostream(error); module->setTargetTriple(targetTriple); module->setDataLayout(targetMachine->createDataLayout()); for( auto& fun : module->getFunctionList() ) if( error.clear(); llvm::verifyFunction(fun, &errrso) ) diagnostics[semantic->sig->name]("81", error), success = false; if( error.clear(); llvm::verifyModule(*module, &errrso) ) diagnostics[semantic->sig->name]("81", error), success = false; if( !success ) return false; llvm::legacy::PassManager pass; auto ros = llvm::raw_os_ostream(os); auto rpos = llvm::buffer_ostream(ros); targetMachine->addPassesToEmitFile(pass, rpos, nullptr, llvm::TargetMachine::CGFT_ObjectFile ); pass.run(*module); return true; } bool AirContext::translateModule( $module semantic ) { module = llvm::make_unique<llvm::Module>((string)semantic->sig->name, *this); bool success = true; for( auto def : semantic->defs ) success = translateDefinition(def) and success; if( success ) for( auto impl : semantic->impls ) success = translateImplementation(impl) and success; if( semantic->sig->entry ) { success = generateStartFunction() and success; } return success; } bool AirContext::translateDefinition( $definition def ) { if( !def ) return false; else if( auto d = ($classdef)def; d ) return translateClassDefinition(d); else if( auto d = ($enumdef)def; d ) return translateEnumDefinition(d); else if( auto d = ($metdef)def; d ) return translateMethodDefinition(d); else if( auto d = ($opdef)def; d ) return translateOperatorDefinition(d); else return true; } bool AirContext::translateImplementation( $implementation impl ) { if( !impl ) return false; else if( auto i = ($metimpl)impl; i ) return translateMethodImplementation(i); else if( auto i = ($opimpl)impl; i ) return translateOperatorImplementation(i); else return false; } bool AirContext::translateClassDefinition( $classdef ) { bool success = true; return success; } bool AirContext::translateEnumDefinition( $enumdef ) { bool success = true; return success; } bool AirContext::translateMethodDefinition( $metdef ) { bool success = true; return success; } bool AirContext::translateOperatorDefinition( $opdef ) { bool success = true; return success; } bool AirContext::translateMethodImplementation( $metimpl ) { bool success = true; return success; } bool AirContext::translateOperatorImplementation( $opimpl ) { bool success = true; return success; } bool AirContext::generateStartFunction() { bool success = true; return success; } } #endif
// // Recorder - a GPS logger app for Windows Mobile // Copyright (C) 2006-2019 Michael Fink // /// \file BluetoothActivator.hpp Bluetooth activator // #pragma once #include <bthutil.h> /// \brief activates bluetooth connection /// The class activates a certain bluetooth mode and on destruction restores the /// previous mode. The bluetooth connection can be in one of the following modes: /// - BTH_CONNECTABLE: turns on bluetooth radio /// - BTH_DISCOVERABLE: turns on bluetooth and makes device discoverable /// - BTH_POWER_OFF: turns off bluetooth /// All enums are available via <bthutil.h> class CBluetoothActivator { public: /// ctor; activates bluetooth mode CBluetoothActivator(DWORD dwMode = BTH_CONNECTABLE); /// dtor; restores the last mode ~CBluetoothActivator(); /// returns current mode static DWORD GetCurrentMode(); /// returns if bluetooth is available static bool IsBluetoothAvail(); private: /// saved mode DWORD m_dwLastMode; };
#include"Game.h" void Game::instructions() { cout << "Controls:" << endl; cout << "w - Start moving up" << " "; cout << "a - Start moving left" << endl; cout << "s - Start moving down" << " "; cout << "d - Start moving right" << endl; cout << "Space - Start/Stop moving" << endl; } Game::Game() :score(0) {} void Game::start() { bool gameover = false; Direction old_dir = RIGHT; bool eaten = false; while (!gameover) { grid.set_grid(); system("cls"); instructions(); grid.print_grid(); cout << "Score: " << score << endl; if (_kbhit()) { char c = _getch(); if (grid.snake.can_change_dir(c)) { grid.snake.change_dir(c, old_dir); } } if (grid.snake.get_dir() != STOP) { old_dir = grid.snake.get_dir(); } if (!grid.next()->can_pass_through() && grid.next() != grid.snake_tail_end()) { gameover = true; } if (eaten) { if (grid.snake.get_dir() != STOP) { grid.snake.enlarge(); eaten = false; score += 100; } } else { switch (grid.snake.get_dir()) { case UP:grid.snake.move_up(); break; case LEFT:grid.snake.move_left(); break; case DOWN:grid.snake.move_down(); break; case RIGHT:grid.snake.move_right(); break; default:break; } } if (grid.get_food()->get_X() == grid.snake.head()->get_X() && grid.get_food()->get_Y() == grid.snake.head()->get_Y()) { eaten = true; } Sleep(100); } grid.set_grid(); system("cls"); instructions(); grid.print_grid(); cout << "GAME OVER" << endl; cout << "Your score: " << score << endl; }
#include<iostream> #include<stack> using namespace std; struct Node { char data; struct Node* next; }; struct Node* newNode(char data){ struct Node* node = new Node(); node->data = data; node->next = NULL; } void printList(struct Node* head){ while(head!=NULL){ cout << head->data; head=head->next; } cout <<endl; } bool checkPalin(struct Node* head , int len){ struct Node* node = head; stack<char> mystack; while(node!=NULL){ mystack.push(node->data); node=node->next; } node=head; while(node!=NULL){ char temp =mystack.top(); if(temp!=node->data) return false; node=node->next; mystack.pop(); } return true; } int main(){ char str[] = "MADAM"; int len = sizeof(str)/sizeof(str[0]); struct Node* head = newNode(str[0]); head->next = newNode(str[1]); head->next->next = newNode(str[2]); head->next->next->next = newNode(str[3]); head->next->next->next->next = newNode(str[4]); printList(head); cout << "String is Palindrome :: " <<checkPalin(head,len); return 0; }
#include <bits/stdc++.h> using namespace std; const int MAX_INT = std::numeric_limits<int>::max(); const int MIN_INT = std::numeric_limits<int>::min(); const int INF = 1000000000; const int NEG_INF = -1000000000; #define max(a,b)((a)>(b)?(a):(b)) #define min(a,b)(a<b?a:b) #define MEM(arr,val)memset(arr,val, sizeof arr) #define PI acos(0)*2.0 #define eps 1.0e-9 #define are_equal(a,b)fabs(a-b)<eps #define LS(b)(b& (-b)) // Least significant bit #define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians typedef long long ll; typedef pair<int,int> ii; typedef pair<int,char> ic; typedef pair<long,char> lc; typedef vector<int> vi; typedef vector<ii> vii; int gcd(int a,int b){return b == 0 ? a : gcd(b,a%b);} int lcm(int a,int b){return a*(b/gcd(a,b));} int M, N, X, Y; char m[21][21]; int r[] = {1, 0, -1, 0}; int c[] = {0, 1, 0, -1}; void dfs(int x, int y, char a, char b){ if (y < 0) y = N - 1; if (y >= N) y = 0; if (x < 0 || x >= M) return; if (m[x][y] != a) return; m[x][y] = b; for (int i = 0; i < 4; i++) dfs(x + r[i], y + c[i], a, b); } int floodfill(int x, int y, char a, char b){ if (y < 0) y = N - 1; if (y >= N) y = 0; if (x < 0 || x >= M) return 0; if (m[x][y] != a) return 0; m[x][y] = b; int ans = 1; for (int i = 0; i < 4; i++){ ans += floodfill(x + r[i], y + c[i], a, b); } return ans; } int main(){ while (cin >> M >> N){ for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) cin >> m[i][j]; cin >> X >> Y; char a = m[X][Y]; char b = 'a'; for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) if (m[i][j] != a) b = m[i][j]; dfs(X, Y, a, b); // for (int i = 0; i < M; i++){ // for (int j = 0; j < N; j++) // cout << m[i][j]; // cout << endl; // } int mx = 0; for (int i = 0; i < M; i++) for (int j = 0; j < N; j++){ int ans = floodfill(i, j, a, b); mx = max(mx, ans); } cout << mx << endl; } return 0; }
#include "jsonunitbox.h" #include "window.h" #define defaultWidth JsonUnitBox::DEFAULT_WIDTH #define defaultHeight JsonUnitBox::DEFAULT_HEIGHT #include <QDebug> #include <QWidget> #include <QLinkedList> #include <QPalette> JsonUnitBox::JsonUnitBox(QWidget *parent) : JsonUnitBox("", parent) {} JsonUnitBox::JsonUnitBox(const QString &text, QWidget *parent) : QPushButton(text, parent) { subBox = NULL; setFixedWidth(defaultWidth); setMinimumHeight(defaultHeight); QFont font; font.setPixelSize(20); setFont(font); QFontMetrics fm(font); QString newText = "", lineString = ""; for(int i = 0; i < text.length(); i++) { if(text[i].unicode() == 10) { newText += lineString + "\n" ; lineString = ""; }else { if(fm.width(lineString + text[i]) >= width() - 20) { newText += lineString + "\n"; lineString = ""; } lineString += text[i]; } } newText += lineString; setText(newText); if(parent) { layout = dynamic_cast <QVBoxLayout *>(parent->layout()); } QObject::connect(this, &JsonUnitBox::pressed, [=]() { printPath(); if(subBox) { if(subBox->isVisible()) { //subBox->setVisible(false); //dynamic_cast <ContentBox *>(parent)->resizeBySizeHint(true); layout->removeWidget(subBox); subBox->setVisible(false); }else { if(subBox->getBoxNumber() != 0) { layout->insertWidget(layout->indexOf(this) + 1, subBox); subBox->setVisible(true); } //dynamic_cast <ContentBox *>(parent)->resizeBySizeHint(false); } //JsonUnitBox *newBox = new JsonUnitBox("box"); } }); } void JsonUnitBox::addSubBox(const QJsonValue &json) { if(!layout) return; subBox = new ContentBox(json, parentWidget()); subBox->setParentBox(this); //layout->insertWidget(layout->indexOf(this) + 1, subBox); layout->setSizeConstraint(QLayout::SetFixedSize); subBox->setVisible(false); //dynamic_cast <ContentBox *>(parentWidget())->resizeBySizeHint(false); } //Public Slots void JsonUnitBox::printPath() { ContentBox *parentBox = dynamic_cast <ContentBox *>(parent()); if(!parentBox->isBasedBox()) { parentBox->getParentBox()->printPath(); } qDebug() << text(); } void JsonUnitBox::setLayout(QVBoxLayout *layout) { this->layout = layout; }
// // channel.cpp // CRsim // // Created by Ji on 15/2/25. // Copyright (c) 2015年 lj. All rights reserved. // #include "channel.h" bool cmpID(const CRchannel &x, const CRchannel &y) { return x.ID < y.ID; }; bool cmpConAvaiTime(const CRchannel &x, const CRchannel &y) { return x.curConAvaiTime < y.curConAvaiTime; }; bool cmpConAvaiTimeReverse(const CRchannel &x, const CRchannel &y) { if (x.curConAvaiTime == y.curConAvaiTime) { return x.ID < y.ID; } else { return x.curConAvaiTime > y.curConAvaiTime; } } bool cmp(int &x, int &y) { return x > y; } void CRchannel::printSortedAllConAvaiTime() { sort(allConAvaiTime.begin(), allConAvaiTime.end(), cmp); printVector(allConAvaiTime); sort(allConAvaiTime.begin(), allConAvaiTime.end()); } double CRchannel::getAverConAvaiTime() { averageConAvaiTime = averValOfVector(allConAvaiTime); return averageConAvaiTime; }
#include<iostream> using namespace std; bool used[101]; int main() { int n; int l,r,k; int recl,recr; int ans=0; cin >>n; for(int i=0;i<=100;i++) { used[i]=false; } for(int i=0;i<n;i++) { cin >>l>>r; if(i==0) { recl=l; recr=r; } else { for(int k=l;k<=r;k++) { used[k]=true; } } } for(int i=recl;i<=recr;i++) { if(used[i]==false) { ans++; cout <<i<<" "; } } cout <<ans<<endl; return 0; }
class Solution { public: int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) // 滑动窗口 { int n = customers.size(); int satisfied = 0; for (int i = 0; i < n; ++i) { // 统计店主不使用“不生气”技能就可以让顾客满意的数量 if (grumpy[i] == 0) { satisfied += customers[i]; } } int angry2satisfied = 0; // 统计使用技能之后,让顾客态度转变的数量 for (int i = 0; i < X; ++i) { // 在X大小的滑窗下,顾客态度转变的数量 if (grumpy[i] == 1) { angry2satisfied += customers[i]; } } int temp = angry2satisfied; for (int i = X; i < n; ++i) { // 滑窗移动,计算最大态度变化数量 if (grumpy[i] == 1) { angry2satisfied += customers[i]; } if (grumpy[i - X] == 1) { // 如果滑窗左端是1,要减去对应数值 angry2satisfied -= customers[i - X]; } temp = max(temp, angry2satisfied); } return satisfied + temp; } }; // reference https://leetcode-cn.com/problems/grumpy-bookstore-owner/solution/hua-dong-chuang-kou-xiang-xi-jiang-jie-z-80ni/
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CompressibleExponentialLaw.hpp" template<unsigned DIM> CompressibleExponentialLaw<DIM>::CompressibleExponentialLaw() { mA = 0.88; // kPa double bff = 18.5; // dimensionless double bss = 3.58; // dimensionless double bnn = 3.58; // dimensionless double bfn = 2.8; // etc double bfs = 2.8; double bsn = 2.8; mCompressibilityParam = 100.0; mB.resize(DIM); for (unsigned i=0; i<DIM; i++) { mB[i].resize(DIM); } mB[0][0] = bff; mB[0][1] = mB[1][0] = bfs; mB[1][1] = bss; if (DIM > 2) { mB[2][2] = bnn; mB[0][2] = mB[2][0] = bfn; mB[2][1] = mB[1][2] = bsn; } for (unsigned M=0; M<DIM; M++) { for (unsigned N=0; N<DIM; N++) { mIdentity(M,N) = M==N ? 1.0 : 0.0; } } } template<unsigned DIM> void CompressibleExponentialLaw<DIM>::ComputeStressAndStressDerivative(c_matrix<double,DIM,DIM>& rC, c_matrix<double,DIM,DIM>& rInvC, double pressure /* not used */, c_matrix<double,DIM,DIM>& rT, FourthOrderTensor<DIM,DIM,DIM,DIM>& rDTdE, bool computeDTdE) { static c_matrix<double,DIM,DIM> C_transformed; static c_matrix<double,DIM,DIM> invC_transformed; // The material law parameters are set up assuming the fibre direction is (1,0,0) // and sheet direction is (0,1,0), so we have to transform C,inv(C),and T. // Let P be the change-of-basis matrix P = (\mathbf{m}_f, \mathbf{m}_s, \mathbf{m}_n). // The transformed C for the fibre/sheet basis is C* = P^T C P. // We then compute T* = T*(C*), and then compute T = P T* P^T. this->ComputeTransformedDeformationTensor(rC, rInvC, C_transformed, invC_transformed); // Compute T* c_matrix<double,DIM,DIM> E = 0.5*(C_transformed - mIdentity); double QQ = 0; for (unsigned M=0; M<DIM; M++) { for (unsigned N=0; N<DIM; N++) { QQ += mB[M][N]*E(M,N)*E(M,N); } } assert(QQ < 10.0);///\todo #2193 This line is to trap for large deformations which lead to blow up in the exponential Uysk model double multiplier = mA*exp(QQ); rDTdE.Zero(); double J = sqrt(Determinant(rC)); for (unsigned M=0; M<DIM; M++) { for (unsigned N=0; N<DIM; N++) { rT(M,N) = multiplier*mB[M][N]*E(M,N) + mCompressibilityParam * J*log(J)*invC_transformed(M,N); if (computeDTdE) { for (unsigned P=0; P<DIM; P++) { for (unsigned Q=0; Q<DIM; Q++) { rDTdE(M,N,P,Q) = multiplier * mB[M][N] * (M==P)*(N==Q) + 2*multiplier*mB[M][N]*mB[P][Q]*E(M,N)*E(P,Q) + mCompressibilityParam * (J*log(J) + J) * invC_transformed(M,N) * invC_transformed(P,Q) - mCompressibilityParam * 2*J*log(J) * invC_transformed(M,P) * invC_transformed(Q,N); } } } } } // Now do: T = P T* P^T and dTdE_{MNPQ} = P_{Mm}P_{Nn}P_{Pp}P_{Qq} dT*dE*_{mnpq} this->TransformStressAndStressDerivative(rT, rDTdE, computeDTdE); } // Explicit instantiation template class CompressibleExponentialLaw<2>; template class CompressibleExponentialLaw<3>;
// Initialize constants for input pins const int x_pin = A0; const int y_pin = A5; const int clear_button = 4; void setup() { // Put analog pins in input mode pinMode(x_pin, INPUT); pinMode(y_pin, INPUT); // Put digital pin in input mode (default: high) pinMode(clear_button, INPUT_PULLUP); Serial.begin(9600); } void loop() { // Read from potentiometers connected to analog pins int x = analogRead(x_pin); int y = analogRead(y_pin); // Invert value of button (FALSE = pushed, TRUE = not pushed) int clear_screen = !digitalRead(clear_button); // Send values over Serial connection Serial.print(x); Serial.print(","); Serial.print(y); Serial.print(","); Serial.print(clear_screen); Serial.println(); // Wait for short time before looping delay(100); }
// 问题描述 //   在数列 a[1], a[2], ..., a[n] 中,如果对于下标 i, j, k 满足 0<i<j<k<n+1 且 a[i]<a[j]<a[k],则称 a[i], a[j], a[k] 为一组递增三元组,a[j]为递增三元组的中心。 //   给定一个数列,请问数列中有多少个元素可能是递增三元组的中心。 // 输入格式 //   输入的第一行包含一个整数 n。 //   第二行包含 n 个整数 a[1], a[2], ..., a[n],相邻的整数间用空格分隔,表示给定的数列。 // 输出格式 //   输出一行包含一个整数,表示答案。 // 样例输入 // 5 // 1 2 5 3 5 // 样例输出 // 2 // 样例说明 //  a[2] 和 a[4] 可能是三元组的中心。 #include <bits/stdc++.h> using namespace std; const int N = 10005; int main() { int a[N]; int n = 0; int sum = 0; cin >> n; for (int i = 0; i < n; ++ i) { cin >> a[i]; } for ( int i = 0; i < n; ++ i) { for (int j = i + 1; j < n - 1; ++ j) { for (int k = j + 1; k < n; ++ k) { if (a[i] < a[j] && a[j] < a[k]) { sum ++; a[j] = 0; break; } } } } cout << sum << endl; return 0; }
//std string -> const char*, char*, 배열 형태의 문자열을 할당 받을 수 있다. //덧셈 기호를 이용해서 문자열 이어붙이기가 가능하다. #define _CRT_SECURE_NO_WARNINGS #include <cstdio> #include <string> #include <iostream> //std::string은 사용자가 메모리 관리, 배열 관리를 하지않고 편안하게 쓰려고 만들었다. int main() { std::string myStr = "Hello World!"; // 연산자 오버로딩 myStr = myStr + "Hello C++!"; //std::string* myStrPointer;// 위의 이유로 만들었는데 동적할당??? printf("%s\n", myStr.c_str()); //std::cout << myStr; return 0; }
/************************************************************* * > File Name : P1733.cpp * > Author : Tony * > Created Time : 2020/05/08 07:42:58 * > Algorithm : 交互 二分 **************************************************************/ #include <bits/stdc++.h> using namespace std; int l = 1, r = 1000000000, mid, res; int main() { while (l <= r) { mid = (l + r) >> 1; printf("%d\n", mid); fflush(stdout); scanf("%d", &res); if (res == 0) { return 0; } else if (res == 1) { r = mid - 1; } else { l = mid + 1; } } return 0; }
#include "Principal.h" char SystemTitle[16]; char SystemVersion[6]; char SystemSerial[17]; char SystemIP[15]; int hpbar; void Customs() { GetPrivateProfileStringA("B&W","SystemTitle","PGBrasil",SystemTitle,sizeof(SystemTitle),BWINI); GetPrivateProfileStringA("B&W","SystemVersion","22459",SystemVersion,sizeof(SystemVersion),BWINI); GetPrivateProfileStringA("B&W","SystemSerial","PGBrasilMuOnline",SystemSerial,sizeof(SystemSerial),BWINI); GetPrivateProfileStringA("B&W","SystemIP","35.247.195.183",SystemIP,sizeof(SystemIP),BWINI); hpbar = GetPrivateProfileIntA("B&W","HPBar", 1,BWINI); // - Serial do Main memset((int*)(0x0066FEF0), 0x00, 17); memcpy((int*)(0x0066FEF0), SystemSerial, 17); memset((int*)(0x0067DF28), 0x00, 17); memcpy((int*)(0x0067DF28), SystemSerial, 17); // - Versão do main Exp: 1.00.00 memset((int*)(0x0066FEE8), 0x00, 6); memcpy((int*)(0x0066FEE8), SystemVersion, 6); // - IP do main memset((int*)(0x0067F3E2), 0x00, 15); memcpy((int*)(0x0067F3E2), SystemIP, sizeof(SystemIP)); // - Nome da Janela memcpy((int*)(0x00660FE0), SystemTitle, sizeof(SystemTitle)); BYTE NovoJanelaNome[] = {0x68, 0xE0, 0x0F, 0x66, 0x00}; memcpy((int*)0x004A6FF2, NovoJanelaNome, sizeof(NovoJanelaNome)); memcpy((int*)0x004A7022, NovoJanelaNome, sizeof(NovoJanelaNome)); // - Screenshots char SSNovo[] = "../ScreenShots/Screen_(%02d_%02d-%02d_%02d)-%04d.jpg"; _mkdir("../ScreenShots"); memcpy((int*)(0x00660F9B), SSNovo, sizeof(SSNovo)); BYTE NovoSSPath[] = {0x68, 0x9B, 0x0F, 0x66, 0x00}; memcpy((int*)0x0060BE08, NovoSSPath, sizeof(NovoSSPath)); // - Liberar Itens *(BYTE*)(0x005E3C27+2) = 0x50; *(BYTE*)(0x005E3D48+2) = 0x50; *(BYTE*)(0x005E3D73+2) = 0x50; *(BYTE*)(0x005E3DB7+2) = 0x50; *(BYTE*)(0x005E3DE2+2) = 0x50; *(BYTE*)(0x005E3E26+2) = 0x50; *(BYTE*)(0x005E3E80+2) = 0x50; *(BYTE*)(0x005E3F43+2) = 0x50; *(BYTE*)(0x005E3F6E+2) = 0x50; *(BYTE*)(0x005E4827+2) = 0x20; *(BYTE*)(0x005E48E8+2) = 0x20; *(BYTE*)(0x005E21A8+2) = 0x50; *(BYTE*)(0x005E26A5+2) = 0x50; *(BYTE*)(0x005E2732+2) = 0x50; *(BYTE*)(0x005E27B4+2) = 0x50; *(BYTE*)(0x005E2226+2) = 0x50; *(BYTE*)(0x005E260E+2) = 0x50; // - Acentuação memset((int*)(0x66F318),0xA0,1); // - Remover Recuo *(BYTE*)(0x4DEE00) = 0xC3; // - Brilho dos itens *(BYTE*)(0x4F7A0E+1) = 0x8C; *(BYTE*)(0x5E005B+2) = 0x10; // - Excellent Wings Level 1 *(BYTE*)(0x52CDBA + 3) = 0x80; *(BYTE*)(0x52D1F8 + 3) = 0x80; *(BYTE*)(0x52D40E + 3) = 0x80; *(BYTE*)(0x52D46E + 3) = 0x80; *(BYTE*)(0x58A889 + 3) = 0x80; *(BYTE*)(0x58AE18 + 1) = 0x80; *(BYTE*)(0x58B881 + 3) = 0x80; *(BYTE*)(0x58CF46 + 3) = 0x80; *(BYTE*)(0x590C0D + 3) = 0x80; *(BYTE*)(0x59127D + 3) = 0x80; *(BYTE*)(0x5943B3 + 2) = 0x80; *(BYTE*)(0x5D2A7E + 2) = 0x80; *(BYTE*)(0x52D8E4 + 1) = 0x12; *(BYTE*)(0x52D8EA + 1) = 0x1A; *(BYTE*)(0x52D8F0 + 1) = 0x22; // - Fix Mover Cursor (Quando abre o NPC) *(BYTE*)(0x4BEEF7) = 0x90; for (DWORD i = 0x4BEF15; i <= 0x4BEF1B; i++) { *(BYTE*)(i) = 0x90; } // - Fix Uso do CPU *(BYTE*)(0x60C269) = 0x6A; *(BYTE*)(0x60C269 + 1) = 0x01; *(BYTE*)(0x60C269 + 2) = 0xFF; *(BYTE*)(0x60C269 + 3) = 0x15; *(BYTE*)(0x60C269 + 4) = 0x38; *(BYTE*)(0x60C269 + 5) = 0x11; *(BYTE*)(0x60C269 + 6) = 0x66; *(BYTE*)(0x60C269 + 7) = 0x00; for (DWORD i = 0x60C271; i <= 0x60C27A; i++) { *(BYTE*)(i) = 0x90; } *(BYTE*)(0x60C27B) = 0xEB; *(BYTE*)(0x60C27B + 1) = 0xD1; // - Skills do Siege *(BYTE*)(0x57F129+1) = 0x2B; *(BYTE*)(0x57F12E+1) = 0x26; *(BYTE*)(0x57F133+1) = 0x21; *(BYTE*)(0x57F138+1) = 0x1C; *(BYTE*)(0x57F13D+1) = 0x17; *(BYTE*)(0x57F142) = 0xEB; *(BYTE*)(0x57F600+2) = 0x00; *(BYTE*)(0x57F605+2) = 0x00; *(BYTE*)(0x57F60A+2) = 0x00; *(BYTE*)(0x57F60F+2) = 0x00; *(BYTE*)(0x57F614+2) = 0x00; *(BYTE*)(0x57F619+2) = 0x00; // - Fonte BYTE FixFonte[4] = {0x6A, 0x05, 0x90, 0x90}; FixFonte[1] = 12; // - Fonte Normal memcpy((BYTE*)0x004A85E2, FixFonte, 4); // - Fonte Bold 1 memcpy((BYTE*)0x004A8623, FixFonte, 4); // - Fonte Bold 2 memset((BYTE*)0x004A8664, 0x90, 6); memcpy((BYTE*)0x004A8664, FixFonte, 4); // - Protocol ProtocolHook(); // - Preview _obj_preview.Loading(); // - HP Bar Ex700 //Hook(0xE8,0x580846,(DWORD)(&HPBar.DrawHealthBar)); // - HP Bar Original Hook(0xE8,0x580846,(DWORD)(&HPBar.DrawHealthBar)); // - WndProc *(DWORD*)(0x4A6F3D) = (DWORD)&WndProcEx; // - Zen *(BYTE*)(0x5FFBF1+1) = 9; *(BYTE*)(0x5F6EEB) = 0xEB; // - Change Folder _mkdir(ErrorDir); char cTempLog[40] = ErrorLog; DWORD *offsetLog = (DWORD*)(0x0066E980); memset(&offsetLog[0],0,40); memcpy(&offsetLog[0],cTempLog,strlen(cTempLog)); char cTempDump[40] = DumpLog; DWORD *offsetDump = (DWORD*)(0x0066FD7C); memset(&offsetDump[0],0,40); memcpy(&offsetDump[0],cTempDump,strlen(cTempDump)); BYTE DecriptLog[5] = {0x90, 0x90, 0x90, 0x90, 0x90}; memcpy((int*)0x0041CD3A, DecriptLog, sizeof(DecriptLog)); memcpy((int*)0x0041CE87, DecriptLog, sizeof(DecriptLog)); //------------------------------------------------------------------------ // - Mu.exe (Abrir main sem Launcher - ON EB OFF 00) //------------------------------------------------------------------------ *(BYTE*)(0x004A7D68) = 0xEB; //------------------------------------------------------------------------ // FIX Open 2 MU (Abrir Dois main - ON EB OFF 00) //------------------------------------------------------------------------ *(BYTE*)(0x004A7CF7) = 0xEB; *(BYTE*)(0x004A7CDB) = 0xEB; //------------------------------------------------------------------------ // Other(Chat Color) //------------------------------------------------------------------------ BYTE ChatObtainedColor[] = { 0x6A, 0x02 }; WriteMemory( (PVOID) 0x004BD661, & ChatObtainedColor, sizeof( ChatObtainedColor ) ); BYTE ChatObtainedZenColor[] = { 0x6A, 0x01 }; WriteMemory( (PVOID) 0x004BD5C7, & ChatObtainedZenColor, sizeof( ChatObtainedZenColor ) ); //------------------------------------------------------------------------ // Resolution Fix widescreen //------------------------------------------------------------------------ ScreenFix(); } void ScreenFix() { HKEY hKey; DWORD buffer=0; LONG result; unsigned long type=REG_DWORD, size=1024; result = RegOpenKeyEx(HKEY_CURRENT_USER,"software\\Webzen\\Mu\\Config",0,KEY_READ,&hKey); if(result == ERROR_SUCCESS) { RegQueryValueEx(hKey,"WideScreenMode",NULL,&type,(LPBYTE)&buffer,&size); RegCloseKey(hKey); } if(buffer == 1){ *(DWORD*)(0x4A750E+6)=0x500; *(DWORD*)(0x4A7518+6)=0x2D0; *(DWORD*)(0x4A7524+6)=0x556; *(DWORD*)(0x4A752E+6)=0x300; *(DWORD*)(0x4A854F+6)=0x500; *(DWORD*)(0x4A855B+6)=0x556; } } void ChkParametro() { char * Parametro = "/chkBWTeam"; LPWSTR *lpszArgv; int nArgc; lpszArgv = CommandLineToArgvW(GetCommandLineW(), &nArgc); size_t nSize1 = 1 + strlen( Parametro ); LPWSTR wUserName = new WCHAR[nSize1]; mbstowcs( wUserName, Parametro, nSize1 ); if(_wcsicmp(wUserName,lpszArgv[4]) != 0) { MessageBoxA(NULL, "Abra o jogo pelo launcher!!! \nAtenção: Você So Pode Abrir o Jogo Pelo Launcher Original.", "Error 1", MB_OK | MB_ICONSTOP); ExitProcess(0); } delete []wUserName; /* if (lpszArgv == NULL){ MessageBoxW(NULL, L"Unable to parse command line", L"Error", MB_OK); } for(int i = 0; i < nArgc; i++) { MessageBoxW(NULL, lpszArgv[i], L"Arglist contents", MB_OK); } LocalFree(lpszArgv); */ } void Initialize() { Monsters.Init(); //ChkParametro(); //ProtectionMain(); Customs(); Joias(); LoadAddons(); HookMiniMap(); ExperienceBar(); m_Glow = LoadLibrary("./Data/Customs/Plugin/Glow.dll"); //m_Cam = LoadLibrary("./Data/Customs/Plugin/Camera.dll"); m_Min = LoadLibrary("./Data/Customs/Plugin/Min.dll"); m_Keyboard = SetWindowsHookEx(WH_KEYBOARD,KeyboardHookProc,NULL,GetCurrentThreadId()); } void Finalize() { UnhookWindowsHookEx(m_Keyboard); if (m_Glow) { FreeLibrary(m_Glow); } if (m_Cam) { FreeLibrary(m_Cam); } if (m_Min) { FreeLibrary(m_Min); } } HWND Window = NULL; HHOOK m_Keyboard = NULL; HMODULE m_Glow = NULL; HMODULE m_Cam = NULL; HMODULE m_Min = NULL; BYTE MouseState = NULL; bool FireTeam = false; bool RunningFG = false; bool AutoClick[3] = { false, false, false }; LRESULT CALLBACK KeyboardHookProc(int Code, WPARAM wParam, LPARAM lParam) { if (((lParam >> 31) & 1) && (Code == HC_ACTION)) { if (wParam == VK_F8) { if (!RunningFG) { FogOn(); } else { FogOff(); } } if (wParam == VK_F10) { if (AutoClick[1] == false) // Right { AutoClick[0] = !AutoClick[0]; AutoClick[2] = false; if (AutoClick[0] == false) // Left { KillTimer(Window, AUTOCLICK_LEFT); SendMessage(Window, WM_LBUTTONUP, NULL, NULL); } else { SetTimer(Window, AUTOCLICK_LEFT, 100, NULL); } } } if (wParam == VK_F11) { if (AutoClick[0] == false) // Left { AutoClick[1] = !AutoClick[1]; AutoClick[2] = false; if (AutoClick[1] == false) // Right { KillTimer(Window, AUTOCLICK_RIGHT); SendMessage(Window, WM_RBUTTONUP, NULL, NULL); } else { SetTimer(Window, AUTOCLICK_RIGHT, 100, NULL); } } } } return CallNextHookEx(m_Keyboard, Code, wParam, lParam); } LRESULT CALLBACK WndProcEx(HWND Window, UINT Message, WPARAM W, LPARAM L) { if (::Window == NULL) { ::Window = Window; } switch (Message) { case WM_NCACTIVATE: { return 0; } break; case WM_RBUTTONDOWN: { if (MouseState == 2) { return 0; } MouseState = 1; } break; case WM_RBUTTONUP: { if (MouseState == 1) { MouseState = 0; } } break; case WM_LBUTTONDOWN: { if (MouseState == 1) { return 0; } MouseState = 2; } break; case WM_LBUTTONUP: { if (MouseState == 2) { MouseState = 0; } } break; case WM_TIMER: { switch (W) { case AUTOCLICK_LEFT: { if (AutoClick[0] == true) { SendMessage(Window, (AutoClick[2] == true) ? WM_LBUTTONUP : WM_LBUTTONDOWN, NULL, NULL); AutoClick[2] = !AutoClick[2]; } } break; case AUTOCLICK_RIGHT: { if (AutoClick[1] == true) { SendMessage(Window, (AutoClick[2] == true) ? WM_RBUTTONUP : WM_RBUTTONDOWN, NULL, NULL); AutoClick[2] = !AutoClick[2]; } } break; } } break; } return CallWindowProc(WndProc,Window,Message,W,L); }
#include<iostream> using namespace std; // //函数的定义 // 1.返回值类型 // 2.函数名 // 3.参数列表 // 4.函数体语句 // 5.return 表达式 //////////////////////////////////// // 返回值类型 函数名(参数列表) // { // 函数体语句; // return表达式; // } //////////////// //注意函数需要写在main函数前 int sum(int a1,int b1) { //此处的a,b在函数定义时,并没有实际的数据,只是一个形式上的参数,所以被成为形参 return a1+b1; } int main() { int a = 0; int b = 1; //此处的a,b才是实参,当调用函数时,实参的值回传给形参 int c = sum(a,b); cout<<c<<endl; return 0; }
/******************************************************************************** ** Form generated from reading UI file 'note_abs.ui' ** ** Created by: Qt User Interface Compiler version 5.14.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_NOTE_ABS_H #define UI_NOTE_ABS_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QDialog> #include <QtWidgets/QGroupBox> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QTabWidget> #include <QtWidgets/QTableView> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_Note_Abs { public: QTabWidget *tabWidget; QWidget *tab; QGroupBox *groupBox_3; QVBoxLayout *verticalLayout_3; QHBoxLayout *horizontalLayout_12; QLabel *label_9; QLineEdit *texte_CNE_Abs; QHBoxLayout *horizontalLayout_13; QLabel *label_10; QLineEdit *texte_Id_Abs; QHBoxLayout *horizontalLayout_14; QLabel *label_11; QLineEdit *texte_Nbr_Abs; QWidget *horizontalLayoutWidget_3; QHBoxLayout *horizontalLayout_11; QPushButton *pushButton_ajouter_3; QPushButton *pushButton_modifier_3; QPushButton *pushButton_supprimer_3; QPushButton *pushButton_afficher_3; QWidget *tab_2; QGroupBox *groupBox_4; QVBoxLayout *verticalLayout_4; QHBoxLayout *horizontalLayout_16; QLabel *label_13; QLineEdit *texte_CNE_Note; QHBoxLayout *horizontalLayout_17; QLabel *label_14; QLineEdit *texte_Id_Note; QHBoxLayout *horizontalLayout_18; QLabel *label_15; QLineEdit *texte_Note; QWidget *horizontalLayoutWidget_4; QHBoxLayout *horizontalLayout_20; QPushButton *pushButton_ajouter_4; QPushButton *pushButton_modifier_4; QPushButton *pushButton_supprimer_4; QPushButton *pushButton_afficher_4; QTableView *tableView; void setupUi(QDialog *Note_Abs) { if (Note_Abs->objectName().isEmpty()) Note_Abs->setObjectName(QString::fromUtf8("Note_Abs")); Note_Abs->resize(1047, 383); tabWidget = new QTabWidget(Note_Abs); tabWidget->setObjectName(QString::fromUtf8("tabWidget")); tabWidget->setGeometry(QRect(10, 20, 481, 321)); tab = new QWidget(); tab->setObjectName(QString::fromUtf8("tab")); groupBox_3 = new QGroupBox(tab); groupBox_3->setObjectName(QString::fromUtf8("groupBox_3")); groupBox_3->setGeometry(QRect(10, 10, 441, 181)); verticalLayout_3 = new QVBoxLayout(groupBox_3); verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3")); horizontalLayout_12 = new QHBoxLayout(); horizontalLayout_12->setObjectName(QString::fromUtf8("horizontalLayout_12")); label_9 = new QLabel(groupBox_3); label_9->setObjectName(QString::fromUtf8("label_9")); horizontalLayout_12->addWidget(label_9); texte_CNE_Abs = new QLineEdit(groupBox_3); texte_CNE_Abs->setObjectName(QString::fromUtf8("texte_CNE_Abs")); horizontalLayout_12->addWidget(texte_CNE_Abs); verticalLayout_3->addLayout(horizontalLayout_12); horizontalLayout_13 = new QHBoxLayout(); horizontalLayout_13->setObjectName(QString::fromUtf8("horizontalLayout_13")); label_10 = new QLabel(groupBox_3); label_10->setObjectName(QString::fromUtf8("label_10")); horizontalLayout_13->addWidget(label_10); texte_Id_Abs = new QLineEdit(groupBox_3); texte_Id_Abs->setObjectName(QString::fromUtf8("texte_Id_Abs")); horizontalLayout_13->addWidget(texte_Id_Abs); verticalLayout_3->addLayout(horizontalLayout_13); horizontalLayout_14 = new QHBoxLayout(); horizontalLayout_14->setObjectName(QString::fromUtf8("horizontalLayout_14")); label_11 = new QLabel(groupBox_3); label_11->setObjectName(QString::fromUtf8("label_11")); horizontalLayout_14->addWidget(label_11); texte_Nbr_Abs = new QLineEdit(groupBox_3); texte_Nbr_Abs->setObjectName(QString::fromUtf8("texte_Nbr_Abs")); horizontalLayout_14->addWidget(texte_Nbr_Abs); verticalLayout_3->addLayout(horizontalLayout_14); horizontalLayoutWidget_3 = new QWidget(tab); horizontalLayoutWidget_3->setObjectName(QString::fromUtf8("horizontalLayoutWidget_3")); horizontalLayoutWidget_3->setGeometry(QRect(10, 200, 441, 71)); horizontalLayout_11 = new QHBoxLayout(horizontalLayoutWidget_3); horizontalLayout_11->setObjectName(QString::fromUtf8("horizontalLayout_11")); horizontalLayout_11->setContentsMargins(0, 0, 0, 0); pushButton_ajouter_3 = new QPushButton(horizontalLayoutWidget_3); pushButton_ajouter_3->setObjectName(QString::fromUtf8("pushButton_ajouter_3")); horizontalLayout_11->addWidget(pushButton_ajouter_3); pushButton_modifier_3 = new QPushButton(horizontalLayoutWidget_3); pushButton_modifier_3->setObjectName(QString::fromUtf8("pushButton_modifier_3")); horizontalLayout_11->addWidget(pushButton_modifier_3); pushButton_supprimer_3 = new QPushButton(horizontalLayoutWidget_3); pushButton_supprimer_3->setObjectName(QString::fromUtf8("pushButton_supprimer_3")); horizontalLayout_11->addWidget(pushButton_supprimer_3); pushButton_afficher_3 = new QPushButton(horizontalLayoutWidget_3); pushButton_afficher_3->setObjectName(QString::fromUtf8("pushButton_afficher_3")); horizontalLayout_11->addWidget(pushButton_afficher_3); tabWidget->addTab(tab, QString()); tab_2 = new QWidget(); tab_2->setObjectName(QString::fromUtf8("tab_2")); groupBox_4 = new QGroupBox(tab_2); groupBox_4->setObjectName(QString::fromUtf8("groupBox_4")); groupBox_4->setGeometry(QRect(10, 10, 441, 181)); verticalLayout_4 = new QVBoxLayout(groupBox_4); verticalLayout_4->setObjectName(QString::fromUtf8("verticalLayout_4")); horizontalLayout_16 = new QHBoxLayout(); horizontalLayout_16->setObjectName(QString::fromUtf8("horizontalLayout_16")); label_13 = new QLabel(groupBox_4); label_13->setObjectName(QString::fromUtf8("label_13")); horizontalLayout_16->addWidget(label_13); texte_CNE_Note = new QLineEdit(groupBox_4); texte_CNE_Note->setObjectName(QString::fromUtf8("texte_CNE_Note")); horizontalLayout_16->addWidget(texte_CNE_Note); verticalLayout_4->addLayout(horizontalLayout_16); horizontalLayout_17 = new QHBoxLayout(); horizontalLayout_17->setObjectName(QString::fromUtf8("horizontalLayout_17")); label_14 = new QLabel(groupBox_4); label_14->setObjectName(QString::fromUtf8("label_14")); horizontalLayout_17->addWidget(label_14); texte_Id_Note = new QLineEdit(groupBox_4); texte_Id_Note->setObjectName(QString::fromUtf8("texte_Id_Note")); horizontalLayout_17->addWidget(texte_Id_Note); verticalLayout_4->addLayout(horizontalLayout_17); horizontalLayout_18 = new QHBoxLayout(); horizontalLayout_18->setObjectName(QString::fromUtf8("horizontalLayout_18")); label_15 = new QLabel(groupBox_4); label_15->setObjectName(QString::fromUtf8("label_15")); horizontalLayout_18->addWidget(label_15); texte_Note = new QLineEdit(groupBox_4); texte_Note->setObjectName(QString::fromUtf8("texte_Note")); horizontalLayout_18->addWidget(texte_Note); verticalLayout_4->addLayout(horizontalLayout_18); horizontalLayoutWidget_4 = new QWidget(tab_2); horizontalLayoutWidget_4->setObjectName(QString::fromUtf8("horizontalLayoutWidget_4")); horizontalLayoutWidget_4->setGeometry(QRect(10, 200, 441, 71)); horizontalLayout_20 = new QHBoxLayout(horizontalLayoutWidget_4); horizontalLayout_20->setObjectName(QString::fromUtf8("horizontalLayout_20")); horizontalLayout_20->setContentsMargins(0, 0, 0, 0); pushButton_ajouter_4 = new QPushButton(horizontalLayoutWidget_4); pushButton_ajouter_4->setObjectName(QString::fromUtf8("pushButton_ajouter_4")); horizontalLayout_20->addWidget(pushButton_ajouter_4); pushButton_modifier_4 = new QPushButton(horizontalLayoutWidget_4); pushButton_modifier_4->setObjectName(QString::fromUtf8("pushButton_modifier_4")); horizontalLayout_20->addWidget(pushButton_modifier_4); pushButton_supprimer_4 = new QPushButton(horizontalLayoutWidget_4); pushButton_supprimer_4->setObjectName(QString::fromUtf8("pushButton_supprimer_4")); horizontalLayout_20->addWidget(pushButton_supprimer_4); pushButton_afficher_4 = new QPushButton(horizontalLayoutWidget_4); pushButton_afficher_4->setObjectName(QString::fromUtf8("pushButton_afficher_4")); horizontalLayout_20->addWidget(pushButton_afficher_4); tabWidget->addTab(tab_2, QString()); tableView = new QTableView(Note_Abs); tableView->setObjectName(QString::fromUtf8("tableView")); tableView->setGeometry(QRect(525, 51, 501, 291)); retranslateUi(Note_Abs); tabWidget->setCurrentIndex(0); QMetaObject::connectSlotsByName(Note_Abs); } // setupUi void retranslateUi(QDialog *Note_Abs) { Note_Abs->setWindowTitle(QCoreApplication::translate("Note_Abs", "Dialog", nullptr)); groupBox_3->setTitle(QCoreApplication::translate("Note_Abs", "Cordonn\303\251es", nullptr)); label_9->setText(QCoreApplication::translate("Note_Abs", "CNE", nullptr)); texte_CNE_Abs->setInputMask(QString()); texte_CNE_Abs->setText(QString()); label_10->setText(QCoreApplication::translate("Note_Abs", "Id de la mati\303\250re", nullptr)); label_11->setText(QCoreApplication::translate("Note_Abs", "Nombres d'heures", nullptr)); pushButton_ajouter_3->setText(QCoreApplication::translate("Note_Abs", "Ajouter", nullptr)); pushButton_modifier_3->setText(QCoreApplication::translate("Note_Abs", "Modifier", nullptr)); pushButton_supprimer_3->setText(QCoreApplication::translate("Note_Abs", "Supprimer", nullptr)); pushButton_afficher_3->setText(QCoreApplication::translate("Note_Abs", "Afficher ", nullptr)); tabWidget->setTabText(tabWidget->indexOf(tab), QCoreApplication::translate("Note_Abs", "Abscence", nullptr)); groupBox_4->setTitle(QCoreApplication::translate("Note_Abs", "Cordonn\303\251es", nullptr)); label_13->setText(QCoreApplication::translate("Note_Abs", "CNE", nullptr)); texte_CNE_Note->setInputMask(QString()); texte_CNE_Note->setText(QString()); label_14->setText(QCoreApplication::translate("Note_Abs", "Id de la mati\303\250re", nullptr)); label_15->setText(QCoreApplication::translate("Note_Abs", "La note", nullptr)); pushButton_ajouter_4->setText(QCoreApplication::translate("Note_Abs", "Ajouter", nullptr)); pushButton_modifier_4->setText(QCoreApplication::translate("Note_Abs", "Modifier", nullptr)); pushButton_supprimer_4->setText(QCoreApplication::translate("Note_Abs", "Supprimer", nullptr)); pushButton_afficher_4->setText(QCoreApplication::translate("Note_Abs", "Afficher ", nullptr)); tabWidget->setTabText(tabWidget->indexOf(tab_2), QCoreApplication::translate("Note_Abs", "Evaluation", nullptr)); } // retranslateUi }; namespace Ui { class Note_Abs: public Ui_Note_Abs {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_NOTE_ABS_H
#pragma once #include "..\DXTK\pch.h" #include "..\capture\all_inc.h" #include "..\Win32\all_inc.h" #include "..\imageIcon\imageIcons.h" #include "..\common\general.h" class Anime { private: HWND hwnd; gdImageIcons icons; bool exit_step = 0; public: bool init(ID3D11DeviceContext1* context, HWND set_hwnd) { hwnd = set_hwnd; // Box2D初期化 if (icons.init(hwnd, context)) return 1; return 0; } void setWallObj(HWND set_hwnd) { icons.setWallObj(set_hwnd); } bool render() { // 描画 if (exit_step == 1) PostMessage(gdHwndManager::mine, WM_CLOSE, NULL, NULL); if (icons.update()) exit_step = 1; if (exit_step == 0) icons.render(); // 処理の終了 return 0; } };
#include "xpowydialog.h" XPowYDialog::XPowYDialog(QWidget *parent) : QDialog(parent), ui(new Ui::XPowYDialog) { ui->setupUi(this); } XPowYDialog::~XPowYDialog() { delete ui; }
#include <benchmark/benchmark.h> #include "PerformanceTestsUtil.hpp" #include <deus/unicode_view_impl/UTF8Impl.hpp> //------------------------------------------------------------------------------ // SHORT //------------------------------------------------------------------------------ //------------------------------------NAIVE------------------------------------- static void BM_utf8_compute_byte_length_short_naive(benchmark::State& state) { deus_perf_util::gen_rand_dyn_strs( deus::Encoding::kUTF8, deus_perf_util::StringSize::kShort ); for(auto _ : state) { // generate std::size_t dummy = 0; const char* s = deus_perf_util::get_next_rand_dyn_str(dummy); // call std::size_t byte_length = 0; deus::utf8_inl::compute_byte_length_naive(s, byte_length); } } BENCHMARK(BM_utf8_compute_byte_length_short_naive); //------------------------------------STRLEN------------------------------------ static void BM_utf8_compute_byte_length_short_strlen(benchmark::State& state) { deus_perf_util::gen_rand_dyn_strs( deus::Encoding::kUTF8, deus_perf_util::StringSize::kShort ); for(auto _ : state) { // generate std::size_t dummy = 0; const char* s = deus_perf_util::get_next_rand_dyn_str(dummy); // call std::size_t byte_length = 0; deus::utf8_inl::compute_byte_length_strlen(s, byte_length); } } BENCHMARK(BM_utf8_compute_byte_length_short_strlen); //------------------------------------------------------------------------------ // MEDIUM //------------------------------------------------------------------------------ //------------------------------------NAIVE------------------------------------- static void BM_utf8_compute_byte_length_medium_naive(benchmark::State& state) { deus_perf_util::gen_rand_dyn_strs( deus::Encoding::kUTF8, deus_perf_util::StringSize::kMedium ); for(auto _ : state) { // generate std::size_t dummy = 0; const char* s = deus_perf_util::get_next_rand_dyn_str(dummy); // call std::size_t byte_length = 0; deus::utf8_inl::compute_byte_length_naive(s, byte_length); } } BENCHMARK(BM_utf8_compute_byte_length_medium_naive); //------------------------------------STRLEN------------------------------------ static void BM_utf8_compute_byte_length_medium_strlen(benchmark::State& state) { deus_perf_util::gen_rand_dyn_strs( deus::Encoding::kUTF8, deus_perf_util::StringSize::kMedium ); for(auto _ : state) { // generate std::size_t dummy = 0; const char* s = deus_perf_util::get_next_rand_dyn_str(dummy); // call std::size_t byte_length = 0; deus::utf8_inl::compute_byte_length_strlen(s, byte_length); } } BENCHMARK(BM_utf8_compute_byte_length_medium_strlen); //------------------------------------------------------------------------------ // LONG //------------------------------------------------------------------------------ //------------------------------------NAIVE------------------------------------- static void BM_utf8_compute_byte_length_long_naive(benchmark::State& state) { deus_perf_util::gen_rand_dyn_strs( deus::Encoding::kUTF8, deus_perf_util::StringSize::kLong ); for(auto _ : state) { // generate std::size_t dummy = 0; const char* s = deus_perf_util::get_next_rand_dyn_str(dummy); // call std::size_t byte_length = 0; deus::utf8_inl::compute_byte_length_naive(s, byte_length); } } BENCHMARK(BM_utf8_compute_byte_length_long_naive); //------------------------------------STRLEN------------------------------------ static void BM_utf8_compute_byte_length_long_strlen(benchmark::State& state) { deus_perf_util::gen_rand_dyn_strs( deus::Encoding::kUTF8, deus_perf_util::StringSize::kLong ); for(auto _ : state) { // generate std::size_t dummy = 0; const char* s = deus_perf_util::get_next_rand_dyn_str(dummy); // call std::size_t byte_length = 0; deus::utf8_inl::compute_byte_length_strlen(s, byte_length); } } BENCHMARK(BM_utf8_compute_byte_length_long_strlen); //------------------------------------------------------------------------------ // EXTRA LONG //------------------------------------------------------------------------------ //------------------------------------NAIVE------------------------------------- static void BM_utf8_compute_byte_length_xlong_naive(benchmark::State& state) { deus_perf_util::gen_rand_dyn_strs( deus::Encoding::kUTF8, deus_perf_util::StringSize::kExtraLong ); for(auto _ : state) { // generate std::size_t dummy = 0; const char* s = deus_perf_util::get_next_rand_dyn_str(dummy); // call std::size_t byte_length = 0; deus::utf8_inl::compute_byte_length_naive(s, byte_length); } } BENCHMARK(BM_utf8_compute_byte_length_xlong_naive); //------------------------------------STRLEN------------------------------------ // The results of this will be wrong, but we still want to use it as a benchmark // to get as close as possible to static void BM_utf8_compute_byte_length_xlong_strlen(benchmark::State& state) { deus_perf_util::gen_rand_dyn_strs( deus::Encoding::kUTF8, deus_perf_util::StringSize::kExtraLong ); for(auto _ : state) { // generate std::size_t dummy = 0; const char* s = deus_perf_util::get_next_rand_dyn_str(dummy); // call std::size_t byte_length = 0; deus::utf8_inl::compute_byte_length_strlen(s, byte_length); } } BENCHMARK(BM_utf8_compute_byte_length_xlong_strlen); //------------------------------------------------------------------------------ // MIXED //------------------------------------------------------------------------------ //------------------------------------NAIVE------------------------------------- static void BM_utf8_compute_byte_length_mixed_naive(benchmark::State& state) { deus_perf_util::gen_rand_dyn_strs( deus::Encoding::kUTF8, deus_perf_util::StringSize::kMixed ); for(auto _ : state) { // generate std::size_t dummy = 0; const char* s = deus_perf_util::get_next_rand_dyn_str(dummy); // call std::size_t byte_length = 0; deus::utf8_inl::compute_byte_length_naive(s, byte_length); } } BENCHMARK(BM_utf8_compute_byte_length_mixed_naive); //------------------------------------STRLEN------------------------------------ // The results of this will be wrong, but we still want to use it as a benchmark // to get as close as possible to static void BM_utf8_compute_byte_length_mixed_strlen(benchmark::State& state) { deus_perf_util::gen_rand_dyn_strs( deus::Encoding::kUTF8, deus_perf_util::StringSize::kMixed ); for(auto _ : state) { // generate std::size_t dummy = 0; const char* s = deus_perf_util::get_next_rand_dyn_str(dummy); // call std::size_t byte_length = 0; deus::utf8_inl::compute_byte_length_strlen(s, byte_length); } } BENCHMARK(BM_utf8_compute_byte_length_mixed_strlen);
// // Created by Sweet Acid on 01.05.2021. // #pragma once #include <GLFW/glfw3.h> #include <Snow/Window.h> namespace Snow { class Renderer { public: static void swap_buffers(Snow::Impl::Window* window) { SNOW_CORE_ASSERT(window != nullptr, "Attempted to swap buffers but there's no window..?"); auto glfw_window = window->get_window(); SNOW_CORE_ASSERT(glfw_window != nullptr, "Attempted to swap buffers but there's no window..?"); glfwSwapBuffers(glfw_window); } }; }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once WINRT_EXPORT namespace winrt { namespace ABI::Windows::Phone::Management::Deployment { struct IEnterprise; struct IEnterpriseEnrollmentManager; struct IEnterpriseEnrollmentResult; struct IInstallationManagerStatics; struct IInstallationManagerStatics2; struct IPackageInstallResult; struct IPackageInstallResult2; struct Enterprise; struct EnterpriseEnrollmentResult; struct PackageInstallResult; } namespace Windows::Phone::Management::Deployment { struct IEnterprise; struct IEnterpriseEnrollmentManager; struct IEnterpriseEnrollmentResult; struct IInstallationManagerStatics; struct IInstallationManagerStatics2; struct IPackageInstallResult; struct IPackageInstallResult2; struct Enterprise; struct EnterpriseEnrollmentManager; struct EnterpriseEnrollmentResult; struct InstallationManager; struct PackageInstallResult; } namespace Windows::Phone::Management::Deployment { template <typename T> struct impl_IEnterprise; template <typename T> struct impl_IEnterpriseEnrollmentManager; template <typename T> struct impl_IEnterpriseEnrollmentResult; template <typename T> struct impl_IInstallationManagerStatics; template <typename T> struct impl_IInstallationManagerStatics2; template <typename T> struct impl_IPackageInstallResult; template <typename T> struct impl_IPackageInstallResult2; } namespace Windows::Phone::Management::Deployment { enum class EnterpriseEnrollmentStatus { Success = 0, CancelledByUser = 1, UnknownFailure = 2, }; enum class EnterpriseStatus { Enrolled = 0, Disabled = 1, Revoked = 2, Expired = 3, }; } }
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <string.h> //void bubble_sort(int arr[], int sz) //{ // int i = 0; // for (i = 0; i <= sz - 1; i++) // { // int j = 0; // int temp = 0; // for (j = 0; j <= sz - 1 - i; j++) // { // if (arr[j]<arr[j + 1]) // { // temp = arr[j]; // arr[j] = arr[j + 1]; // arr[j + 1] = temp; // } // } // } //} //void printf_arr(int arr[], int sz) //{ // int i = 0; // for (i = 0; i < sz; i++) // { // printf("%d ", arr[i]); // } // printf("\n" ); //} //int main() //{ // int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // int sz = sizeof(arr) / sizeof(arr[0]); // bubble_sort(arr, sz); // printf_arr(arr, sz); // return 0; //} //int main() //{ // int arr1[] = { 1, 2, 3, 4, 5, 6 }; // int* pa = &arr1; // //int arr2[10] = { 1, 2, 3, 4, 5, 6 }; // //char ch1[5] = { 'a', 'b', 'c', 'd' }; // printf("%d\n", &arr1); // //printf("%d\n", sizeof(arr2)); // //printf("%d\n", strlen(ch1)); // //printf("%d\n", sizeof(ch1)); // return 0; //} //int main() //{ // int i = 0; // int j = 0; // int sum = 0; // for (i = 1; i <= 9; i++) // { // for (j = 1; j <= i; j++) // { // sum = j*i; // printf("%d=%d*%d", sum,j,i); // } // printf("\n"); // } // return 0; //} //void result_arr(int arr[]) //{ // int* pa = arr; // int i; // int ARR = 0; // for (i = 0; i < 9; i++) // { // int ARR = *(pa + i); // printf("%d", ARR); // } //} //int main() //{ // int arr[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // result_arr(arr); // //int* pa = arr; // //int i = 0; // //for (i = 0; i < 9; i++) // //{ // // printf("%d", *(pa+i)); // //} // return 0; // //} //int main() //{ // int i = 0; // for (i = 0; i < 100000; i++) // { // if () // } // return 0; //} //int main() //{ // int i = 0; // for (i = 1000; i <= 2000; i++) // { // if (i % 4 == 0 && i % 100 != 0) // printf("%d ", i); // // } // return 0; //} //int main() //{ // int a = 0, b = 0; // for (a = 1, b = 1; a <= 100; a++) // { // if (b >= 20) break; // if (b % 3 == 1) // { // b = b + 3; // continue; // } // b = b - 5; // } // printf("%d\n", a); // return 0; //} //int main() //{ // int m = 0; // int n = 0; // int count = 0; // scanf("%d%d", &m, &n); // int i = 0; // for (i = 0; i < 32; i++) // { // if ((m >> i) & 1) != ((n >> i) & 1) // { // conu++; // } // } // printf("%d", count); // return 0; //} //if (((m >> i) & 1) != ((n >> i) & 1)) //{ // count++; // //} //int main() //{ // int n = 0; // scanf("%d", &n); // int i = 0; // for (i = 1; i <= 31; i += 2) // { // printf("%d", ((n >> i) & 1)); // } // printf("\n"); // for (i = 2; i <= 32; i += 2) // { // printf("%d", ((n >> i) & 1)); // } // return 0; //int main() //{ // int i = 0; // int count = 0; // for (i = 0; i < 100; i++) // { // if (i % 10 == 9 || i / 10 == 9) // { // printf("%d ", i); // count++; // } // } // printf("%d", count); // return 0; // //} //#include <string.h> //struct Book //{ // char name[20]; // short price; //}; //int main() //{ // struct Book b = { "¸كت‎", 30 }; // // printf("%s %d", b.name, b.price); // return 0; //}
#include<string> using namespace std; const int MAX_N = 1000; //INPUT int N, A[MAX_N]; int rev[MAX_N * 2], sa[MAX_N * 2]; int n,k; int myrank[MAX_N + 1]; int tmp[MAX_N + 1]; // compare (myrank[i], myrank[i+k]) vs (myrank[j], myrank[j+k]) bool compare_sa(int i, int j){ if(myrank[i] != myrank[j]) return myrank[i] < myrank[j]; else { int ri = i+k <=n ? myrank[i+k] : -1; int rj = j+k <=n ? myrank[j+k] : -1; return ri < rj; } } void construct_sa(int *S, int n, int *sa){ // n = (sizeof S) / (sizeof S[0]); // start length-1, rank is character code for (int i=0; i <=n; i++){ sa[i] = i; myrank[i] = i < n ? S[i] : -1; } //k -> 2k for (k=1; k <= n; k *=2) { sort (sa, sa+n+1, compare_sa); // once computed in tmp and move to rank tmp[sa[0]] = 0; for (int i=1; i <= n; i++){ tmp[sa[i]] = tmp[sa[i-1]] + (compare_sa(sa[i-1], sa[i]) ? 1 : 0); } for(int i=0; i<=n; i++){ myrank[i] = tmp[i]; } } } void solve(){ // inverse A and construct its Suffix Array; reverse_copy(A, A+N, rev); construct_sa(rev, N, sa); // for interger array // first separation (A1 | A2) int p1; for (int i=0; i < N; i++){ p1 = N - sa[i]; if(p1 >= 1 && N - p1 >=2) break; } // for A2|A3. reverse & double & SA int m = N - p1; reverse_copy(A+p1, A+N, rev); reverse_copy(A+p1, A+N, rev+m); construct_sa(rev, m * 2, sa); // find separation on A2|A3. int p2; for (int i=0; i<=2 * m; i++){ p2 = p1 + m - sa[i]; if (p2 - p1 >= 1 && N - p2 >=1) break; } reverse(A, A+p1); reverse(A+p1, A+p2); reverse(A+p2, A+N); for(int i=0; i<N; i++) printf("%d\n", A[i]); } int main(){ N=5; A[0]=10, A[1]=1, A[2]=2, A[3]=3, A[4]=4; solve(); }
/* bayesdfa 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. bayesdfa 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 bayesdfa. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MODELS_HPP #define MODELS_HPP #define STAN__SERVICES__COMMAND_HPP #include <rstan/rstaninc.hpp> // Code generated by Stan version 2.19.1 #include <stan/model/model_header.hpp> namespace model_dfa_namespace { using std::istream; using std::string; using std::stringstream; using std::vector; using stan::io::dump; using stan::math::lgamma; using stan::model::prob_grad; using namespace stan::math; static int current_statement_begin__; stan::io::program_reader prog_reader__() { stan::io::program_reader reader; reader.add_event(0, 0, "start", "model_dfa"); reader.add_event(278, 276, "end", "model_dfa"); return reader; } #include <meta_header.hpp> class model_dfa : public prob_grad { private: int N; int P; int K; int nZ; std::vector<int> row_indx; std::vector<int> col_indx; int nVariances; std::vector<int> varIndx; int nZero; std::vector<int> row_indx_z; std::vector<int> col_indx_z; int n_pos; std::vector<int> row_indx_pos; std::vector<int> col_indx_pos; std::vector<double> y; int n_na; std::vector<int> row_indx_na; std::vector<int> col_indx_na; double nu_fixed; int estimate_nu; int use_normal; int est_cor; int est_phi; int est_theta; int num_obs_covar; int n_obs_covar; std::vector<std::vector<int> > obs_covar_index; std::vector<double> obs_covar_value; int num_pro_covar; int n_pro_covar; std::vector<std::vector<int> > pro_covar_index; std::vector<double> pro_covar_value; int n_pcor; int n_loglik; vector_d zeros; public: model_dfa(stan::io::var_context& context__, std::ostream* pstream__ = 0) : prob_grad(0) { ctor_body(context__, 0, pstream__); } model_dfa(stan::io::var_context& context__, unsigned int random_seed__, std::ostream* pstream__ = 0) : prob_grad(0) { ctor_body(context__, random_seed__, pstream__); } void ctor_body(stan::io::var_context& context__, unsigned int random_seed__, std::ostream* pstream__) { typedef double local_scalar_t__; boost::ecuyer1988 base_rng__ = stan::services::util::create_rng(random_seed__, 0); (void) base_rng__; // suppress unused var warning current_statement_begin__ = -1; static const char* function__ = "model_dfa_namespace::model_dfa"; (void) function__; // dummy to suppress unused var warning size_t pos__; (void) pos__; // dummy to suppress unused var warning std::vector<int> vals_i__; std::vector<double> vals_r__; local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning try { // initialize data block variables from context__ current_statement_begin__ = 2; context__.validate_dims("data initialization", "N", "int", context__.to_vec()); N = int(0); vals_i__ = context__.vals_i("N"); pos__ = 0; N = vals_i__[pos__++]; check_greater_or_equal(function__, "N", N, 0); current_statement_begin__ = 3; context__.validate_dims("data initialization", "P", "int", context__.to_vec()); P = int(0); vals_i__ = context__.vals_i("P"); pos__ = 0; P = vals_i__[pos__++]; check_greater_or_equal(function__, "P", P, 0); current_statement_begin__ = 4; context__.validate_dims("data initialization", "K", "int", context__.to_vec()); K = int(0); vals_i__ = context__.vals_i("K"); pos__ = 0; K = vals_i__[pos__++]; check_greater_or_equal(function__, "K", K, 0); current_statement_begin__ = 5; context__.validate_dims("data initialization", "nZ", "int", context__.to_vec()); nZ = int(0); vals_i__ = context__.vals_i("nZ"); pos__ = 0; nZ = vals_i__[pos__++]; check_greater_or_equal(function__, "nZ", nZ, 0); current_statement_begin__ = 6; validate_non_negative_index("row_indx", "nZ", nZ); context__.validate_dims("data initialization", "row_indx", "int", context__.to_vec(nZ)); row_indx = std::vector<int>(nZ, int(0)); vals_i__ = context__.vals_i("row_indx"); pos__ = 0; size_t row_indx_k_0_max__ = nZ; for (size_t k_0__ = 0; k_0__ < row_indx_k_0_max__; ++k_0__) { row_indx[k_0__] = vals_i__[pos__++]; } size_t row_indx_i_0_max__ = nZ; for (size_t i_0__ = 0; i_0__ < row_indx_i_0_max__; ++i_0__) { check_greater_or_equal(function__, "row_indx[i_0__]", row_indx[i_0__], 0); } current_statement_begin__ = 7; validate_non_negative_index("col_indx", "nZ", nZ); context__.validate_dims("data initialization", "col_indx", "int", context__.to_vec(nZ)); col_indx = std::vector<int>(nZ, int(0)); vals_i__ = context__.vals_i("col_indx"); pos__ = 0; size_t col_indx_k_0_max__ = nZ; for (size_t k_0__ = 0; k_0__ < col_indx_k_0_max__; ++k_0__) { col_indx[k_0__] = vals_i__[pos__++]; } size_t col_indx_i_0_max__ = nZ; for (size_t i_0__ = 0; i_0__ < col_indx_i_0_max__; ++i_0__) { check_greater_or_equal(function__, "col_indx[i_0__]", col_indx[i_0__], 0); } current_statement_begin__ = 8; context__.validate_dims("data initialization", "nVariances", "int", context__.to_vec()); nVariances = int(0); vals_i__ = context__.vals_i("nVariances"); pos__ = 0; nVariances = vals_i__[pos__++]; check_greater_or_equal(function__, "nVariances", nVariances, 0); current_statement_begin__ = 9; validate_non_negative_index("varIndx", "P", P); context__.validate_dims("data initialization", "varIndx", "int", context__.to_vec(P)); varIndx = std::vector<int>(P, int(0)); vals_i__ = context__.vals_i("varIndx"); pos__ = 0; size_t varIndx_k_0_max__ = P; for (size_t k_0__ = 0; k_0__ < varIndx_k_0_max__; ++k_0__) { varIndx[k_0__] = vals_i__[pos__++]; } size_t varIndx_i_0_max__ = P; for (size_t i_0__ = 0; i_0__ < varIndx_i_0_max__; ++i_0__) { check_greater_or_equal(function__, "varIndx[i_0__]", varIndx[i_0__], 0); } current_statement_begin__ = 10; context__.validate_dims("data initialization", "nZero", "int", context__.to_vec()); nZero = int(0); vals_i__ = context__.vals_i("nZero"); pos__ = 0; nZero = vals_i__[pos__++]; check_greater_or_equal(function__, "nZero", nZero, 0); current_statement_begin__ = 11; validate_non_negative_index("row_indx_z", "nZero", nZero); context__.validate_dims("data initialization", "row_indx_z", "int", context__.to_vec(nZero)); row_indx_z = std::vector<int>(nZero, int(0)); vals_i__ = context__.vals_i("row_indx_z"); pos__ = 0; size_t row_indx_z_k_0_max__ = nZero; for (size_t k_0__ = 0; k_0__ < row_indx_z_k_0_max__; ++k_0__) { row_indx_z[k_0__] = vals_i__[pos__++]; } size_t row_indx_z_i_0_max__ = nZero; for (size_t i_0__ = 0; i_0__ < row_indx_z_i_0_max__; ++i_0__) { check_greater_or_equal(function__, "row_indx_z[i_0__]", row_indx_z[i_0__], 0); } current_statement_begin__ = 12; validate_non_negative_index("col_indx_z", "nZero", nZero); context__.validate_dims("data initialization", "col_indx_z", "int", context__.to_vec(nZero)); col_indx_z = std::vector<int>(nZero, int(0)); vals_i__ = context__.vals_i("col_indx_z"); pos__ = 0; size_t col_indx_z_k_0_max__ = nZero; for (size_t k_0__ = 0; k_0__ < col_indx_z_k_0_max__; ++k_0__) { col_indx_z[k_0__] = vals_i__[pos__++]; } size_t col_indx_z_i_0_max__ = nZero; for (size_t i_0__ = 0; i_0__ < col_indx_z_i_0_max__; ++i_0__) { check_greater_or_equal(function__, "col_indx_z[i_0__]", col_indx_z[i_0__], 0); } current_statement_begin__ = 13; context__.validate_dims("data initialization", "n_pos", "int", context__.to_vec()); n_pos = int(0); vals_i__ = context__.vals_i("n_pos"); pos__ = 0; n_pos = vals_i__[pos__++]; check_greater_or_equal(function__, "n_pos", n_pos, 0); current_statement_begin__ = 14; validate_non_negative_index("row_indx_pos", "n_pos", n_pos); context__.validate_dims("data initialization", "row_indx_pos", "int", context__.to_vec(n_pos)); row_indx_pos = std::vector<int>(n_pos, int(0)); vals_i__ = context__.vals_i("row_indx_pos"); pos__ = 0; size_t row_indx_pos_k_0_max__ = n_pos; for (size_t k_0__ = 0; k_0__ < row_indx_pos_k_0_max__; ++k_0__) { row_indx_pos[k_0__] = vals_i__[pos__++]; } size_t row_indx_pos_i_0_max__ = n_pos; for (size_t i_0__ = 0; i_0__ < row_indx_pos_i_0_max__; ++i_0__) { check_greater_or_equal(function__, "row_indx_pos[i_0__]", row_indx_pos[i_0__], 0); } current_statement_begin__ = 15; validate_non_negative_index("col_indx_pos", "n_pos", n_pos); context__.validate_dims("data initialization", "col_indx_pos", "int", context__.to_vec(n_pos)); col_indx_pos = std::vector<int>(n_pos, int(0)); vals_i__ = context__.vals_i("col_indx_pos"); pos__ = 0; size_t col_indx_pos_k_0_max__ = n_pos; for (size_t k_0__ = 0; k_0__ < col_indx_pos_k_0_max__; ++k_0__) { col_indx_pos[k_0__] = vals_i__[pos__++]; } size_t col_indx_pos_i_0_max__ = n_pos; for (size_t i_0__ = 0; i_0__ < col_indx_pos_i_0_max__; ++i_0__) { check_greater_or_equal(function__, "col_indx_pos[i_0__]", col_indx_pos[i_0__], 0); } current_statement_begin__ = 16; validate_non_negative_index("y", "n_pos", n_pos); context__.validate_dims("data initialization", "y", "double", context__.to_vec(n_pos)); y = std::vector<double>(n_pos, double(0)); vals_r__ = context__.vals_r("y"); pos__ = 0; size_t y_k_0_max__ = n_pos; for (size_t k_0__ = 0; k_0__ < y_k_0_max__; ++k_0__) { y[k_0__] = vals_r__[pos__++]; } current_statement_begin__ = 17; context__.validate_dims("data initialization", "n_na", "int", context__.to_vec()); n_na = int(0); vals_i__ = context__.vals_i("n_na"); pos__ = 0; n_na = vals_i__[pos__++]; check_greater_or_equal(function__, "n_na", n_na, 0); current_statement_begin__ = 18; validate_non_negative_index("row_indx_na", "n_na", n_na); context__.validate_dims("data initialization", "row_indx_na", "int", context__.to_vec(n_na)); row_indx_na = std::vector<int>(n_na, int(0)); vals_i__ = context__.vals_i("row_indx_na"); pos__ = 0; size_t row_indx_na_k_0_max__ = n_na; for (size_t k_0__ = 0; k_0__ < row_indx_na_k_0_max__; ++k_0__) { row_indx_na[k_0__] = vals_i__[pos__++]; } size_t row_indx_na_i_0_max__ = n_na; for (size_t i_0__ = 0; i_0__ < row_indx_na_i_0_max__; ++i_0__) { check_greater_or_equal(function__, "row_indx_na[i_0__]", row_indx_na[i_0__], 0); } current_statement_begin__ = 19; validate_non_negative_index("col_indx_na", "n_na", n_na); context__.validate_dims("data initialization", "col_indx_na", "int", context__.to_vec(n_na)); col_indx_na = std::vector<int>(n_na, int(0)); vals_i__ = context__.vals_i("col_indx_na"); pos__ = 0; size_t col_indx_na_k_0_max__ = n_na; for (size_t k_0__ = 0; k_0__ < col_indx_na_k_0_max__; ++k_0__) { col_indx_na[k_0__] = vals_i__[pos__++]; } size_t col_indx_na_i_0_max__ = n_na; for (size_t i_0__ = 0; i_0__ < col_indx_na_i_0_max__; ++i_0__) { check_greater_or_equal(function__, "col_indx_na[i_0__]", col_indx_na[i_0__], 0); } current_statement_begin__ = 20; context__.validate_dims("data initialization", "nu_fixed", "double", context__.to_vec()); nu_fixed = double(0); vals_r__ = context__.vals_r("nu_fixed"); pos__ = 0; nu_fixed = vals_r__[pos__++]; check_greater_or_equal(function__, "nu_fixed", nu_fixed, 1); current_statement_begin__ = 21; context__.validate_dims("data initialization", "estimate_nu", "int", context__.to_vec()); estimate_nu = int(0); vals_i__ = context__.vals_i("estimate_nu"); pos__ = 0; estimate_nu = vals_i__[pos__++]; current_statement_begin__ = 22; context__.validate_dims("data initialization", "use_normal", "int", context__.to_vec()); use_normal = int(0); vals_i__ = context__.vals_i("use_normal"); pos__ = 0; use_normal = vals_i__[pos__++]; current_statement_begin__ = 23; context__.validate_dims("data initialization", "est_cor", "int", context__.to_vec()); est_cor = int(0); vals_i__ = context__.vals_i("est_cor"); pos__ = 0; est_cor = vals_i__[pos__++]; current_statement_begin__ = 24; context__.validate_dims("data initialization", "est_phi", "int", context__.to_vec()); est_phi = int(0); vals_i__ = context__.vals_i("est_phi"); pos__ = 0; est_phi = vals_i__[pos__++]; current_statement_begin__ = 25; context__.validate_dims("data initialization", "est_theta", "int", context__.to_vec()); est_theta = int(0); vals_i__ = context__.vals_i("est_theta"); pos__ = 0; est_theta = vals_i__[pos__++]; current_statement_begin__ = 26; context__.validate_dims("data initialization", "num_obs_covar", "int", context__.to_vec()); num_obs_covar = int(0); vals_i__ = context__.vals_i("num_obs_covar"); pos__ = 0; num_obs_covar = vals_i__[pos__++]; check_greater_or_equal(function__, "num_obs_covar", num_obs_covar, 0); current_statement_begin__ = 27; context__.validate_dims("data initialization", "n_obs_covar", "int", context__.to_vec()); n_obs_covar = int(0); vals_i__ = context__.vals_i("n_obs_covar"); pos__ = 0; n_obs_covar = vals_i__[pos__++]; check_greater_or_equal(function__, "n_obs_covar", n_obs_covar, 0); current_statement_begin__ = 28; validate_non_negative_index("obs_covar_index", "num_obs_covar", num_obs_covar); validate_non_negative_index("obs_covar_index", "3", 3); context__.validate_dims("data initialization", "obs_covar_index", "int", context__.to_vec(num_obs_covar,3)); obs_covar_index = std::vector<std::vector<int> >(num_obs_covar, std::vector<int>(3, int(0))); vals_i__ = context__.vals_i("obs_covar_index"); pos__ = 0; size_t obs_covar_index_k_0_max__ = num_obs_covar; size_t obs_covar_index_k_1_max__ = 3; for (size_t k_1__ = 0; k_1__ < obs_covar_index_k_1_max__; ++k_1__) { for (size_t k_0__ = 0; k_0__ < obs_covar_index_k_0_max__; ++k_0__) { obs_covar_index[k_0__][k_1__] = vals_i__[pos__++]; } } current_statement_begin__ = 29; validate_non_negative_index("obs_covar_value", "num_obs_covar", num_obs_covar); context__.validate_dims("data initialization", "obs_covar_value", "double", context__.to_vec(num_obs_covar)); obs_covar_value = std::vector<double>(num_obs_covar, double(0)); vals_r__ = context__.vals_r("obs_covar_value"); pos__ = 0; size_t obs_covar_value_k_0_max__ = num_obs_covar; for (size_t k_0__ = 0; k_0__ < obs_covar_value_k_0_max__; ++k_0__) { obs_covar_value[k_0__] = vals_r__[pos__++]; } current_statement_begin__ = 30; context__.validate_dims("data initialization", "num_pro_covar", "int", context__.to_vec()); num_pro_covar = int(0); vals_i__ = context__.vals_i("num_pro_covar"); pos__ = 0; num_pro_covar = vals_i__[pos__++]; check_greater_or_equal(function__, "num_pro_covar", num_pro_covar, 0); current_statement_begin__ = 31; context__.validate_dims("data initialization", "n_pro_covar", "int", context__.to_vec()); n_pro_covar = int(0); vals_i__ = context__.vals_i("n_pro_covar"); pos__ = 0; n_pro_covar = vals_i__[pos__++]; check_greater_or_equal(function__, "n_pro_covar", n_pro_covar, 0); current_statement_begin__ = 32; validate_non_negative_index("pro_covar_index", "num_pro_covar", num_pro_covar); validate_non_negative_index("pro_covar_index", "3", 3); context__.validate_dims("data initialization", "pro_covar_index", "int", context__.to_vec(num_pro_covar,3)); pro_covar_index = std::vector<std::vector<int> >(num_pro_covar, std::vector<int>(3, int(0))); vals_i__ = context__.vals_i("pro_covar_index"); pos__ = 0; size_t pro_covar_index_k_0_max__ = num_pro_covar; size_t pro_covar_index_k_1_max__ = 3; for (size_t k_1__ = 0; k_1__ < pro_covar_index_k_1_max__; ++k_1__) { for (size_t k_0__ = 0; k_0__ < pro_covar_index_k_0_max__; ++k_0__) { pro_covar_index[k_0__][k_1__] = vals_i__[pos__++]; } } current_statement_begin__ = 33; validate_non_negative_index("pro_covar_value", "num_pro_covar", num_pro_covar); context__.validate_dims("data initialization", "pro_covar_value", "double", context__.to_vec(num_pro_covar)); pro_covar_value = std::vector<double>(num_pro_covar, double(0)); vals_r__ = context__.vals_r("pro_covar_value"); pos__ = 0; size_t pro_covar_value_k_0_max__ = num_pro_covar; for (size_t k_0__ = 0; k_0__ < pro_covar_value_k_0_max__; ++k_0__) { pro_covar_value[k_0__] = vals_r__[pos__++]; } // initialize transformed data variables current_statement_begin__ = 36; n_pcor = int(0); stan::math::fill(n_pcor, std::numeric_limits<int>::min()); current_statement_begin__ = 37; n_loglik = int(0); stan::math::fill(n_loglik, std::numeric_limits<int>::min()); current_statement_begin__ = 38; validate_non_negative_index("zeros", "K", K); zeros = Eigen::Matrix<double, Eigen::Dynamic, 1>(K); stan::math::fill(zeros, DUMMY_VAR__); // execute transformed data statements current_statement_begin__ = 40; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 41; stan::model::assign(zeros, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), 0, "assigning variable zeros"); } current_statement_begin__ = 44; if (as_bool(logical_eq(est_cor, 0))) { current_statement_begin__ = 45; stan::math::assign(n_loglik, (P * N)); } else { current_statement_begin__ = 47; stan::math::assign(n_loglik, N); } current_statement_begin__ = 50; if (as_bool(logical_eq(est_cor, 0))) { current_statement_begin__ = 51; stan::math::assign(n_pcor, P); current_statement_begin__ = 52; if (as_bool(logical_lt(nVariances, 2))) { current_statement_begin__ = 53; stan::math::assign(n_pcor, 2); } } else { current_statement_begin__ = 56; stan::math::assign(n_pcor, P); } // validate transformed data // validate, set parameter ranges num_params_r__ = 0U; param_ranges_i__.clear(); current_statement_begin__ = 60; validate_non_negative_index("devs", "K", K); validate_non_negative_index("devs", "(N - 1)", (N - 1)); num_params_r__ += (K * (N - 1)); current_statement_begin__ = 61; validate_non_negative_index("x0", "K", K); num_params_r__ += K; current_statement_begin__ = 62; validate_non_negative_index("psi", "K", K); num_params_r__ += K; current_statement_begin__ = 63; validate_non_negative_index("z", "nZ", nZ); num_params_r__ += nZ; current_statement_begin__ = 64; validate_non_negative_index("zpos", "K", K); num_params_r__ += K; current_statement_begin__ = 65; validate_non_negative_index("b_obs", "n_obs_covar", n_obs_covar); validate_non_negative_index("b_obs", "P", P); num_params_r__ += (n_obs_covar * P); current_statement_begin__ = 66; validate_non_negative_index("b_pro", "n_pro_covar", n_pro_covar); validate_non_negative_index("b_pro", "K", K); num_params_r__ += (n_pro_covar * K); current_statement_begin__ = 67; validate_non_negative_index("sigma", "nVariances", nVariances); num_params_r__ += (1 * nVariances); current_statement_begin__ = 68; validate_non_negative_index("nu", "estimate_nu", estimate_nu); num_params_r__ += (1 * estimate_nu); current_statement_begin__ = 69; validate_non_negative_index("ymiss", "n_na", n_na); num_params_r__ += (1 * n_na); current_statement_begin__ = 70; validate_non_negative_index("phi", "(est_phi * K)", (est_phi * K)); num_params_r__ += (1 * (est_phi * K)); current_statement_begin__ = 71; validate_non_negative_index("theta", "(est_theta * K)", (est_theta * K)); num_params_r__ += (1 * (est_theta * K)); current_statement_begin__ = 72; validate_non_negative_index("Lcorr", "n_pcor", n_pcor); validate_non_negative_index("Lcorr", "n_pcor", n_pcor); num_params_r__ += ((n_pcor * (n_pcor - 1)) / 2); } catch (const std::exception& e) { stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__()); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } } ~model_dfa() { } void transform_inits(const stan::io::var_context& context__, std::vector<int>& params_i__, std::vector<double>& params_r__, std::ostream* pstream__) const { typedef double local_scalar_t__; stan::io::writer<double> writer__(params_r__, params_i__); size_t pos__; (void) pos__; // dummy call to supress warning std::vector<double> vals_r__; std::vector<int> vals_i__; current_statement_begin__ = 60; if (!(context__.contains_r("devs"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable devs missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("devs"); pos__ = 0U; validate_non_negative_index("devs", "K", K); validate_non_negative_index("devs", "(N - 1)", (N - 1)); context__.validate_dims("parameter initialization", "devs", "matrix_d", context__.to_vec(K,(N - 1))); Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> devs(K, (N - 1)); size_t devs_j_2_max__ = (N - 1); size_t devs_j_1_max__ = K; for (size_t j_2__ = 0; j_2__ < devs_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < devs_j_1_max__; ++j_1__) { devs(j_1__, j_2__) = vals_r__[pos__++]; } } try { writer__.matrix_unconstrain(devs); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable devs: ") + e.what()), current_statement_begin__, prog_reader__()); } current_statement_begin__ = 61; if (!(context__.contains_r("x0"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable x0 missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("x0"); pos__ = 0U; validate_non_negative_index("x0", "K", K); context__.validate_dims("parameter initialization", "x0", "vector_d", context__.to_vec(K)); Eigen::Matrix<double, Eigen::Dynamic, 1> x0(K); size_t x0_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < x0_j_1_max__; ++j_1__) { x0(j_1__) = vals_r__[pos__++]; } try { writer__.vector_unconstrain(x0); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable x0: ") + e.what()), current_statement_begin__, prog_reader__()); } current_statement_begin__ = 62; if (!(context__.contains_r("psi"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable psi missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("psi"); pos__ = 0U; validate_non_negative_index("psi", "K", K); context__.validate_dims("parameter initialization", "psi", "vector_d", context__.to_vec(K)); Eigen::Matrix<double, Eigen::Dynamic, 1> psi(K); size_t psi_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < psi_j_1_max__; ++j_1__) { psi(j_1__) = vals_r__[pos__++]; } try { writer__.vector_lb_unconstrain(0, psi); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable psi: ") + e.what()), current_statement_begin__, prog_reader__()); } current_statement_begin__ = 63; if (!(context__.contains_r("z"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable z missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("z"); pos__ = 0U; validate_non_negative_index("z", "nZ", nZ); context__.validate_dims("parameter initialization", "z", "vector_d", context__.to_vec(nZ)); Eigen::Matrix<double, Eigen::Dynamic, 1> z(nZ); size_t z_j_1_max__ = nZ; for (size_t j_1__ = 0; j_1__ < z_j_1_max__; ++j_1__) { z(j_1__) = vals_r__[pos__++]; } try { writer__.vector_unconstrain(z); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable z: ") + e.what()), current_statement_begin__, prog_reader__()); } current_statement_begin__ = 64; if (!(context__.contains_r("zpos"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable zpos missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("zpos"); pos__ = 0U; validate_non_negative_index("zpos", "K", K); context__.validate_dims("parameter initialization", "zpos", "vector_d", context__.to_vec(K)); Eigen::Matrix<double, Eigen::Dynamic, 1> zpos(K); size_t zpos_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < zpos_j_1_max__; ++j_1__) { zpos(j_1__) = vals_r__[pos__++]; } try { writer__.vector_unconstrain(zpos); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable zpos: ") + e.what()), current_statement_begin__, prog_reader__()); } current_statement_begin__ = 65; if (!(context__.contains_r("b_obs"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable b_obs missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("b_obs"); pos__ = 0U; validate_non_negative_index("b_obs", "n_obs_covar", n_obs_covar); validate_non_negative_index("b_obs", "P", P); context__.validate_dims("parameter initialization", "b_obs", "matrix_d", context__.to_vec(n_obs_covar,P)); Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> b_obs(n_obs_covar, P); size_t b_obs_j_2_max__ = P; size_t b_obs_j_1_max__ = n_obs_covar; for (size_t j_2__ = 0; j_2__ < b_obs_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < b_obs_j_1_max__; ++j_1__) { b_obs(j_1__, j_2__) = vals_r__[pos__++]; } } try { writer__.matrix_unconstrain(b_obs); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable b_obs: ") + e.what()), current_statement_begin__, prog_reader__()); } current_statement_begin__ = 66; if (!(context__.contains_r("b_pro"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable b_pro missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("b_pro"); pos__ = 0U; validate_non_negative_index("b_pro", "n_pro_covar", n_pro_covar); validate_non_negative_index("b_pro", "K", K); context__.validate_dims("parameter initialization", "b_pro", "matrix_d", context__.to_vec(n_pro_covar,K)); Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> b_pro(n_pro_covar, K); size_t b_pro_j_2_max__ = K; size_t b_pro_j_1_max__ = n_pro_covar; for (size_t j_2__ = 0; j_2__ < b_pro_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < b_pro_j_1_max__; ++j_1__) { b_pro(j_1__, j_2__) = vals_r__[pos__++]; } } try { writer__.matrix_unconstrain(b_pro); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable b_pro: ") + e.what()), current_statement_begin__, prog_reader__()); } current_statement_begin__ = 67; if (!(context__.contains_r("sigma"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable sigma missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("sigma"); pos__ = 0U; validate_non_negative_index("sigma", "nVariances", nVariances); context__.validate_dims("parameter initialization", "sigma", "double", context__.to_vec(nVariances)); std::vector<double> sigma(nVariances, double(0)); size_t sigma_k_0_max__ = nVariances; for (size_t k_0__ = 0; k_0__ < sigma_k_0_max__; ++k_0__) { sigma[k_0__] = vals_r__[pos__++]; } size_t sigma_i_0_max__ = nVariances; for (size_t i_0__ = 0; i_0__ < sigma_i_0_max__; ++i_0__) { try { writer__.scalar_lb_unconstrain(0, sigma[i_0__]); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable sigma: ") + e.what()), current_statement_begin__, prog_reader__()); } } current_statement_begin__ = 68; if (!(context__.contains_r("nu"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable nu missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("nu"); pos__ = 0U; validate_non_negative_index("nu", "estimate_nu", estimate_nu); context__.validate_dims("parameter initialization", "nu", "double", context__.to_vec(estimate_nu)); std::vector<double> nu(estimate_nu, double(0)); size_t nu_k_0_max__ = estimate_nu; for (size_t k_0__ = 0; k_0__ < nu_k_0_max__; ++k_0__) { nu[k_0__] = vals_r__[pos__++]; } size_t nu_i_0_max__ = estimate_nu; for (size_t i_0__ = 0; i_0__ < nu_i_0_max__; ++i_0__) { try { writer__.scalar_lb_unconstrain(2, nu[i_0__]); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable nu: ") + e.what()), current_statement_begin__, prog_reader__()); } } current_statement_begin__ = 69; if (!(context__.contains_r("ymiss"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable ymiss missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("ymiss"); pos__ = 0U; validate_non_negative_index("ymiss", "n_na", n_na); context__.validate_dims("parameter initialization", "ymiss", "double", context__.to_vec(n_na)); std::vector<double> ymiss(n_na, double(0)); size_t ymiss_k_0_max__ = n_na; for (size_t k_0__ = 0; k_0__ < ymiss_k_0_max__; ++k_0__) { ymiss[k_0__] = vals_r__[pos__++]; } size_t ymiss_i_0_max__ = n_na; for (size_t i_0__ = 0; i_0__ < ymiss_i_0_max__; ++i_0__) { try { writer__.scalar_unconstrain(ymiss[i_0__]); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable ymiss: ") + e.what()), current_statement_begin__, prog_reader__()); } } current_statement_begin__ = 70; if (!(context__.contains_r("phi"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable phi missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("phi"); pos__ = 0U; validate_non_negative_index("phi", "(est_phi * K)", (est_phi * K)); context__.validate_dims("parameter initialization", "phi", "double", context__.to_vec((est_phi * K))); std::vector<double> phi((est_phi * K), double(0)); size_t phi_k_0_max__ = (est_phi * K); for (size_t k_0__ = 0; k_0__ < phi_k_0_max__; ++k_0__) { phi[k_0__] = vals_r__[pos__++]; } size_t phi_i_0_max__ = (est_phi * K); for (size_t i_0__ = 0; i_0__ < phi_i_0_max__; ++i_0__) { try { writer__.scalar_lub_unconstrain(-(1), 1, phi[i_0__]); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable phi: ") + e.what()), current_statement_begin__, prog_reader__()); } } current_statement_begin__ = 71; if (!(context__.contains_r("theta"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable theta missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("theta"); pos__ = 0U; validate_non_negative_index("theta", "(est_theta * K)", (est_theta * K)); context__.validate_dims("parameter initialization", "theta", "double", context__.to_vec((est_theta * K))); std::vector<double> theta((est_theta * K), double(0)); size_t theta_k_0_max__ = (est_theta * K); for (size_t k_0__ = 0; k_0__ < theta_k_0_max__; ++k_0__) { theta[k_0__] = vals_r__[pos__++]; } size_t theta_i_0_max__ = (est_theta * K); for (size_t i_0__ = 0; i_0__ < theta_i_0_max__; ++i_0__) { try { writer__.scalar_lub_unconstrain(-(1), 1, theta[i_0__]); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable theta: ") + e.what()), current_statement_begin__, prog_reader__()); } } current_statement_begin__ = 72; if (!(context__.contains_r("Lcorr"))) stan::lang::rethrow_located(std::runtime_error(std::string("Variable Lcorr missing")), current_statement_begin__, prog_reader__()); vals_r__ = context__.vals_r("Lcorr"); pos__ = 0U; validate_non_negative_index("Lcorr", "n_pcor", n_pcor); validate_non_negative_index("Lcorr", "n_pcor", n_pcor); context__.validate_dims("parameter initialization", "Lcorr", "matrix_d", context__.to_vec(n_pcor,n_pcor)); Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Lcorr(n_pcor, n_pcor); size_t Lcorr_j_2_max__ = n_pcor; size_t Lcorr_j_1_max__ = n_pcor; for (size_t j_2__ = 0; j_2__ < Lcorr_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < Lcorr_j_1_max__; ++j_1__) { Lcorr(j_1__, j_2__) = vals_r__[pos__++]; } } try { writer__.cholesky_factor_corr_unconstrain(Lcorr); } catch (const std::exception& e) { stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable Lcorr: ") + e.what()), current_statement_begin__, prog_reader__()); } params_r__ = writer__.data_r(); params_i__ = writer__.data_i(); } void transform_inits(const stan::io::var_context& context, Eigen::Matrix<double, Eigen::Dynamic, 1>& params_r, std::ostream* pstream__) const { std::vector<double> params_r_vec; std::vector<int> params_i_vec; transform_inits(context, params_i_vec, params_r_vec, pstream__); params_r.resize(params_r_vec.size()); for (int i = 0; i < params_r.size(); ++i) params_r(i) = params_r_vec[i]; } template <bool propto__, bool jacobian__, typename T__> T__ log_prob(std::vector<T__>& params_r__, std::vector<int>& params_i__, std::ostream* pstream__ = 0) const { typedef T__ local_scalar_t__; local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN()); (void) DUMMY_VAR__; // dummy to suppress unused var warning T__ lp__(0.0); stan::math::accumulator<T__> lp_accum__; try { stan::io::reader<local_scalar_t__> in__(params_r__, params_i__); // model parameters current_statement_begin__ = 60; Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, Eigen::Dynamic> devs; (void) devs; // dummy to suppress unused var warning if (jacobian__) devs = in__.matrix_constrain(K, (N - 1), lp__); else devs = in__.matrix_constrain(K, (N - 1)); current_statement_begin__ = 61; Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1> x0; (void) x0; // dummy to suppress unused var warning if (jacobian__) x0 = in__.vector_constrain(K, lp__); else x0 = in__.vector_constrain(K); current_statement_begin__ = 62; Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1> psi; (void) psi; // dummy to suppress unused var warning if (jacobian__) psi = in__.vector_lb_constrain(0, K, lp__); else psi = in__.vector_lb_constrain(0, K); current_statement_begin__ = 63; Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1> z; (void) z; // dummy to suppress unused var warning if (jacobian__) z = in__.vector_constrain(nZ, lp__); else z = in__.vector_constrain(nZ); current_statement_begin__ = 64; Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1> zpos; (void) zpos; // dummy to suppress unused var warning if (jacobian__) zpos = in__.vector_constrain(K, lp__); else zpos = in__.vector_constrain(K); current_statement_begin__ = 65; Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, Eigen::Dynamic> b_obs; (void) b_obs; // dummy to suppress unused var warning if (jacobian__) b_obs = in__.matrix_constrain(n_obs_covar, P, lp__); else b_obs = in__.matrix_constrain(n_obs_covar, P); current_statement_begin__ = 66; Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, Eigen::Dynamic> b_pro; (void) b_pro; // dummy to suppress unused var warning if (jacobian__) b_pro = in__.matrix_constrain(n_pro_covar, K, lp__); else b_pro = in__.matrix_constrain(n_pro_covar, K); current_statement_begin__ = 67; std::vector<local_scalar_t__> sigma; size_t sigma_d_0_max__ = nVariances; sigma.reserve(sigma_d_0_max__); for (size_t d_0__ = 0; d_0__ < sigma_d_0_max__; ++d_0__) { if (jacobian__) sigma.push_back(in__.scalar_lb_constrain(0, lp__)); else sigma.push_back(in__.scalar_lb_constrain(0)); } current_statement_begin__ = 68; std::vector<local_scalar_t__> nu; size_t nu_d_0_max__ = estimate_nu; nu.reserve(nu_d_0_max__); for (size_t d_0__ = 0; d_0__ < nu_d_0_max__; ++d_0__) { if (jacobian__) nu.push_back(in__.scalar_lb_constrain(2, lp__)); else nu.push_back(in__.scalar_lb_constrain(2)); } current_statement_begin__ = 69; std::vector<local_scalar_t__> ymiss; size_t ymiss_d_0_max__ = n_na; ymiss.reserve(ymiss_d_0_max__); for (size_t d_0__ = 0; d_0__ < ymiss_d_0_max__; ++d_0__) { if (jacobian__) ymiss.push_back(in__.scalar_constrain(lp__)); else ymiss.push_back(in__.scalar_constrain()); } current_statement_begin__ = 70; std::vector<local_scalar_t__> phi; size_t phi_d_0_max__ = (est_phi * K); phi.reserve(phi_d_0_max__); for (size_t d_0__ = 0; d_0__ < phi_d_0_max__; ++d_0__) { if (jacobian__) phi.push_back(in__.scalar_lub_constrain(-(1), 1, lp__)); else phi.push_back(in__.scalar_lub_constrain(-(1), 1)); } current_statement_begin__ = 71; std::vector<local_scalar_t__> theta; size_t theta_d_0_max__ = (est_theta * K); theta.reserve(theta_d_0_max__); for (size_t d_0__ = 0; d_0__ < theta_d_0_max__; ++d_0__) { if (jacobian__) theta.push_back(in__.scalar_lub_constrain(-(1), 1, lp__)); else theta.push_back(in__.scalar_lub_constrain(-(1), 1)); } current_statement_begin__ = 72; Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, Eigen::Dynamic> Lcorr; (void) Lcorr; // dummy to suppress unused var warning if (jacobian__) Lcorr = in__.cholesky_factor_corr_constrain(n_pcor, lp__); else Lcorr = in__.cholesky_factor_corr_constrain(n_pcor); // transformed parameters current_statement_begin__ = 75; validate_non_negative_index("pred", "P", P); validate_non_negative_index("pred", "N", N); Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, Eigen::Dynamic> pred(P, N); stan::math::initialize(pred, DUMMY_VAR__); stan::math::fill(pred, DUMMY_VAR__); current_statement_begin__ = 76; validate_non_negative_index("Z", "P", P); validate_non_negative_index("Z", "K", K); Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, Eigen::Dynamic> Z(P, K); stan::math::initialize(Z, DUMMY_VAR__); stan::math::fill(Z, DUMMY_VAR__); current_statement_begin__ = 78; validate_non_negative_index("yall", "P", P); validate_non_negative_index("yall", "N", N); Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, Eigen::Dynamic> yall(P, N); stan::math::initialize(yall, DUMMY_VAR__); stan::math::fill(yall, DUMMY_VAR__); current_statement_begin__ = 79; validate_non_negative_index("sigma_vec", "P", P); Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1> sigma_vec(P); stan::math::initialize(sigma_vec, DUMMY_VAR__); stan::math::fill(sigma_vec, DUMMY_VAR__); current_statement_begin__ = 80; validate_non_negative_index("phi_vec", "K", K); Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1> phi_vec(K); stan::math::initialize(phi_vec, DUMMY_VAR__); stan::math::fill(phi_vec, DUMMY_VAR__); current_statement_begin__ = 81; validate_non_negative_index("theta_vec", "K", K); Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1> theta_vec(K); stan::math::initialize(theta_vec, DUMMY_VAR__); stan::math::fill(theta_vec, DUMMY_VAR__); current_statement_begin__ = 82; validate_non_negative_index("x", "K", K); validate_non_negative_index("x", "N", N); Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, Eigen::Dynamic> x(K, N); stan::math::initialize(x, DUMMY_VAR__); stan::math::fill(x, DUMMY_VAR__); current_statement_begin__ = 83; validate_non_negative_index("indicator", "K", K); Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1> indicator(K); stan::math::initialize(indicator, DUMMY_VAR__); stan::math::fill(indicator, DUMMY_VAR__); current_statement_begin__ = 84; validate_non_negative_index("psi_root", "K", K); Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1> psi_root(K); stan::math::initialize(psi_root, DUMMY_VAR__); stan::math::fill(psi_root, DUMMY_VAR__); // transformed parameters block statements current_statement_begin__ = 87; if (as_bool(logical_eq(est_phi, 1))) { current_statement_begin__ = 88; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 88; stan::model::assign(phi_vec, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), get_base1(phi, k, "phi", 1), "assigning variable phi_vec"); } } else { current_statement_begin__ = 90; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 90; stan::model::assign(phi_vec, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), 1, "assigning variable phi_vec"); } } current_statement_begin__ = 94; if (as_bool(logical_eq(est_theta, 1))) { current_statement_begin__ = 95; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 95; stan::model::assign(theta_vec, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), get_base1(theta, k, "theta", 1), "assigning variable theta_vec"); } } else { current_statement_begin__ = 97; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 97; stan::model::assign(theta_vec, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), 0, "assigning variable theta_vec"); } } current_statement_begin__ = 100; for (int p = 1; p <= P; ++p) { current_statement_begin__ = 101; stan::model::assign(sigma_vec, stan::model::cons_list(stan::model::index_uni(p), stan::model::nil_index_list()), get_base1(sigma, get_base1(varIndx, p, "varIndx", 1), "sigma", 1), "assigning variable sigma_vec"); } current_statement_begin__ = 105; for (int i = 1; i <= n_pos; ++i) { current_statement_begin__ = 106; stan::model::assign(yall, stan::model::cons_list(stan::model::index_uni(get_base1(row_indx_pos, i, "row_indx_pos", 1)), stan::model::cons_list(stan::model::index_uni(get_base1(col_indx_pos, i, "col_indx_pos", 1)), stan::model::nil_index_list())), get_base1(y, i, "y", 1), "assigning variable yall"); } current_statement_begin__ = 109; if (as_bool(logical_gt(n_na, 0))) { current_statement_begin__ = 110; for (int i = 1; i <= n_na; ++i) { current_statement_begin__ = 111; stan::model::assign(yall, stan::model::cons_list(stan::model::index_uni(get_base1(row_indx_na, i, "row_indx_na", 1)), stan::model::cons_list(stan::model::index_uni(get_base1(col_indx_na, i, "col_indx_na", 1)), stan::model::nil_index_list())), get_base1(ymiss, i, "ymiss", 1), "assigning variable yall"); } } current_statement_begin__ = 115; for (int i = 1; i <= nZ; ++i) { current_statement_begin__ = 116; stan::model::assign(Z, stan::model::cons_list(stan::model::index_uni(get_base1(row_indx, i, "row_indx", 1)), stan::model::cons_list(stan::model::index_uni(get_base1(col_indx, i, "col_indx", 1)), stan::model::nil_index_list())), get_base1(z, i, "z", 1), "assigning variable Z"); } current_statement_begin__ = 119; if (as_bool(logical_gt(nZero, 2))) { current_statement_begin__ = 120; for (int i = 1; i <= (nZero - 2); ++i) { current_statement_begin__ = 121; stan::model::assign(Z, stan::model::cons_list(stan::model::index_uni(get_base1(row_indx_z, i, "row_indx_z", 1)), stan::model::cons_list(stan::model::index_uni(get_base1(col_indx_z, i, "col_indx_z", 1)), stan::model::nil_index_list())), 0, "assigning variable Z"); } } current_statement_begin__ = 125; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 126; stan::model::assign(Z, stan::model::cons_list(stan::model::index_uni(k), stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list())), get_base1(zpos, k, "zpos", 1), "assigning variable Z"); } current_statement_begin__ = 130; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 131; if (as_bool(logical_lt(get_base1(zpos, k, "zpos", 1), 0))) { current_statement_begin__ = 132; stan::model::assign(indicator, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), -(1), "assigning variable indicator"); } else { current_statement_begin__ = 134; stan::model::assign(indicator, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), 1, "assigning variable indicator"); } current_statement_begin__ = 136; stan::model::assign(psi_root, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), stan::math::sqrt(get_base1(psi, k, "psi", 1)), "assigning variable psi_root"); current_statement_begin__ = 137; for (int p = 1; p <= P; ++p) { current_statement_begin__ = 138; stan::model::assign(Z, stan::model::cons_list(stan::model::index_uni(p), stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list())), ((get_base1(Z, p, k, "Z", 1) * get_base1(indicator, k, "indicator", 1)) * (1 / get_base1(psi_root, k, "psi_root", 1))), "assigning variable Z"); } } current_statement_begin__ = 143; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 144; stan::model::assign(x, stan::model::cons_list(stan::model::index_uni(k), stan::model::cons_list(stan::model::index_uni(1), stan::model::nil_index_list())), get_base1(x0, k, "x0", 1), "assigning variable x"); current_statement_begin__ = 148; for (int t = 2; t <= N; ++t) { current_statement_begin__ = 149; stan::model::assign(x, stan::model::cons_list(stan::model::index_uni(k), stan::model::cons_list(stan::model::index_uni(t), stan::model::nil_index_list())), ((get_base1(phi_vec, k, "phi_vec", 1) * get_base1(x, k, (t - 1), "x", 1)) + get_base1(devs, k, (t - 1), "devs", 1)), "assigning variable x"); } } current_statement_begin__ = 153; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 155; for (int t = 1; t <= N; ++t) { current_statement_begin__ = 156; stan::model::assign(x, stan::model::cons_list(stan::model::index_uni(k), stan::model::cons_list(stan::model::index_uni(t), stan::model::nil_index_list())), ((get_base1(x, k, t, "x", 1) * get_base1(indicator, k, "indicator", 1)) * get_base1(psi_root, k, "psi_root", 1)), "assigning variable x"); } } current_statement_begin__ = 161; if (as_bool(logical_gt(num_pro_covar, 0))) { current_statement_begin__ = 162; for (int i = 1; i <= num_pro_covar; ++i) { current_statement_begin__ = 164; stan::model::assign(x, stan::model::cons_list(stan::model::index_uni(get_base1(get_base1(pro_covar_index, i, "pro_covar_index", 1), 2, "pro_covar_index", 2)), stan::model::cons_list(stan::model::index_uni(get_base1(get_base1(pro_covar_index, i, "pro_covar_index", 1), 1, "pro_covar_index", 2)), stan::model::nil_index_list())), (get_base1(x, get_base1(get_base1(pro_covar_index, i, "pro_covar_index", 1), 2, "pro_covar_index", 2), get_base1(get_base1(pro_covar_index, i, "pro_covar_index", 1), 1, "pro_covar_index", 2), "x", 1) + (get_base1(b_pro, get_base1(get_base1(pro_covar_index, i, "pro_covar_index", 1), 3, "pro_covar_index", 2), get_base1(get_base1(pro_covar_index, i, "pro_covar_index", 1), 2, "pro_covar_index", 2), "b_pro", 1) * get_base1(pro_covar_value, i, "pro_covar_value", 1))), "assigning variable x"); } } current_statement_begin__ = 170; stan::math::assign(pred, multiply(Z, x)); current_statement_begin__ = 173; if (as_bool(logical_gt(num_obs_covar, 0))) { current_statement_begin__ = 174; for (int i = 1; i <= num_obs_covar; ++i) { current_statement_begin__ = 176; stan::model::assign(pred, stan::model::cons_list(stan::model::index_uni(get_base1(get_base1(obs_covar_index, i, "obs_covar_index", 1), 2, "obs_covar_index", 2)), stan::model::cons_list(stan::model::index_uni(get_base1(get_base1(obs_covar_index, i, "obs_covar_index", 1), 1, "obs_covar_index", 2)), stan::model::nil_index_list())), (get_base1(pred, get_base1(get_base1(obs_covar_index, i, "obs_covar_index", 1), 2, "obs_covar_index", 2), get_base1(get_base1(obs_covar_index, i, "obs_covar_index", 1), 1, "obs_covar_index", 2), "pred", 1) + (get_base1(b_obs, get_base1(get_base1(obs_covar_index, i, "obs_covar_index", 1), 3, "obs_covar_index", 2), get_base1(get_base1(obs_covar_index, i, "obs_covar_index", 1), 2, "obs_covar_index", 2), "b_obs", 1) * get_base1(obs_covar_value, i, "obs_covar_value", 1))), "assigning variable pred"); } } // validate transformed parameters const char* function__ = "validate transformed params"; (void) function__; // dummy to suppress unused var warning current_statement_begin__ = 75; size_t pred_j_1_max__ = P; size_t pred_j_2_max__ = N; for (size_t j_1__ = 0; j_1__ < pred_j_1_max__; ++j_1__) { for (size_t j_2__ = 0; j_2__ < pred_j_2_max__; ++j_2__) { if (stan::math::is_uninitialized(pred(j_1__, j_2__))) { std::stringstream msg__; msg__ << "Undefined transformed parameter: pred" << "(" << j_1__ << ", " << j_2__ << ")"; stan::lang::rethrow_located(std::runtime_error(std::string("Error initializing variable pred: ") + msg__.str()), current_statement_begin__, prog_reader__()); } } } current_statement_begin__ = 76; size_t Z_j_1_max__ = P; size_t Z_j_2_max__ = K; for (size_t j_1__ = 0; j_1__ < Z_j_1_max__; ++j_1__) { for (size_t j_2__ = 0; j_2__ < Z_j_2_max__; ++j_2__) { if (stan::math::is_uninitialized(Z(j_1__, j_2__))) { std::stringstream msg__; msg__ << "Undefined transformed parameter: Z" << "(" << j_1__ << ", " << j_2__ << ")"; stan::lang::rethrow_located(std::runtime_error(std::string("Error initializing variable Z: ") + msg__.str()), current_statement_begin__, prog_reader__()); } } } current_statement_begin__ = 78; size_t yall_j_1_max__ = P; size_t yall_j_2_max__ = N; for (size_t j_1__ = 0; j_1__ < yall_j_1_max__; ++j_1__) { for (size_t j_2__ = 0; j_2__ < yall_j_2_max__; ++j_2__) { if (stan::math::is_uninitialized(yall(j_1__, j_2__))) { std::stringstream msg__; msg__ << "Undefined transformed parameter: yall" << "(" << j_1__ << ", " << j_2__ << ")"; stan::lang::rethrow_located(std::runtime_error(std::string("Error initializing variable yall: ") + msg__.str()), current_statement_begin__, prog_reader__()); } } } current_statement_begin__ = 79; size_t sigma_vec_j_1_max__ = P; for (size_t j_1__ = 0; j_1__ < sigma_vec_j_1_max__; ++j_1__) { if (stan::math::is_uninitialized(sigma_vec(j_1__))) { std::stringstream msg__; msg__ << "Undefined transformed parameter: sigma_vec" << "(" << j_1__ << ")"; stan::lang::rethrow_located(std::runtime_error(std::string("Error initializing variable sigma_vec: ") + msg__.str()), current_statement_begin__, prog_reader__()); } } current_statement_begin__ = 80; size_t phi_vec_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < phi_vec_j_1_max__; ++j_1__) { if (stan::math::is_uninitialized(phi_vec(j_1__))) { std::stringstream msg__; msg__ << "Undefined transformed parameter: phi_vec" << "(" << j_1__ << ")"; stan::lang::rethrow_located(std::runtime_error(std::string("Error initializing variable phi_vec: ") + msg__.str()), current_statement_begin__, prog_reader__()); } } current_statement_begin__ = 81; size_t theta_vec_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < theta_vec_j_1_max__; ++j_1__) { if (stan::math::is_uninitialized(theta_vec(j_1__))) { std::stringstream msg__; msg__ << "Undefined transformed parameter: theta_vec" << "(" << j_1__ << ")"; stan::lang::rethrow_located(std::runtime_error(std::string("Error initializing variable theta_vec: ") + msg__.str()), current_statement_begin__, prog_reader__()); } } current_statement_begin__ = 82; size_t x_j_1_max__ = K; size_t x_j_2_max__ = N; for (size_t j_1__ = 0; j_1__ < x_j_1_max__; ++j_1__) { for (size_t j_2__ = 0; j_2__ < x_j_2_max__; ++j_2__) { if (stan::math::is_uninitialized(x(j_1__, j_2__))) { std::stringstream msg__; msg__ << "Undefined transformed parameter: x" << "(" << j_1__ << ", " << j_2__ << ")"; stan::lang::rethrow_located(std::runtime_error(std::string("Error initializing variable x: ") + msg__.str()), current_statement_begin__, prog_reader__()); } } } current_statement_begin__ = 83; size_t indicator_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < indicator_j_1_max__; ++j_1__) { if (stan::math::is_uninitialized(indicator(j_1__))) { std::stringstream msg__; msg__ << "Undefined transformed parameter: indicator" << "(" << j_1__ << ")"; stan::lang::rethrow_located(std::runtime_error(std::string("Error initializing variable indicator: ") + msg__.str()), current_statement_begin__, prog_reader__()); } } current_statement_begin__ = 84; size_t psi_root_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < psi_root_j_1_max__; ++j_1__) { if (stan::math::is_uninitialized(psi_root(j_1__))) { std::stringstream msg__; msg__ << "Undefined transformed parameter: psi_root" << "(" << j_1__ << ")"; stan::lang::rethrow_located(std::runtime_error(std::string("Error initializing variable psi_root: ") + msg__.str()), current_statement_begin__, prog_reader__()); } } // model body current_statement_begin__ = 182; lp_accum__.add(normal_log<propto__>(x0, 0, 1)); current_statement_begin__ = 183; lp_accum__.add(gamma_log<propto__>(psi, 2, 1)); current_statement_begin__ = 187; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 188; if (as_bool(logical_eq(use_normal, 0))) { current_statement_begin__ = 189; for (int t = 1; t <= 1; ++t) { current_statement_begin__ = 190; if (as_bool(logical_eq(estimate_nu, 1))) { current_statement_begin__ = 191; lp_accum__.add(student_t_log<propto__>(get_base1(devs, k, t, "devs", 1), get_base1(nu, 1, "nu", 1), 0, 1)); } else { current_statement_begin__ = 193; lp_accum__.add(student_t_log<propto__>(get_base1(devs, k, t, "devs", 1), nu_fixed, 0, 1)); } } current_statement_begin__ = 196; for (int t = 2; t <= (N - 1); ++t) { current_statement_begin__ = 198; if (as_bool(logical_eq(estimate_nu, 1))) { current_statement_begin__ = 199; lp_accum__.add(student_t_log<propto__>(get_base1(devs, k, t, "devs", 1), get_base1(nu, 1, "nu", 1), (get_base1(theta_vec, k, "theta_vec", 1) * get_base1(devs, k, (t - 1), "devs", 1)), 1)); } else { current_statement_begin__ = 201; lp_accum__.add(student_t_log<propto__>(get_base1(devs, k, t, "devs", 1), nu_fixed, (get_base1(theta_vec, k, "theta_vec", 1) * get_base1(devs, k, (t - 1), "devs", 1)), 1)); } } } else { current_statement_begin__ = 205; lp_accum__.add(normal_log<propto__>(get_base1(devs, k, 1, "devs", 1), 0, 1)); current_statement_begin__ = 206; for (int t = 2; t <= (N - 1); ++t) { current_statement_begin__ = 208; lp_accum__.add(normal_log<propto__>(get_base1(devs, k, t, "devs", 1), (get_base1(theta_vec, k, "theta_vec", 1) * get_base1(devs, k, (t - 1), "devs", 1)), 1)); } } } current_statement_begin__ = 215; if (as_bool(logical_eq(estimate_nu, 1))) { current_statement_begin__ = 216; lp_accum__.add(gamma_log<propto__>(get_base1(nu, 1, "nu", 1), 2, 0.1)); } current_statement_begin__ = 219; if (as_bool(logical_eq(est_phi, 1))) { current_statement_begin__ = 220; lp_accum__.add(uniform_log<propto__>(phi, 0, 1)); } current_statement_begin__ = 223; if (as_bool(logical_eq(est_theta, 1))) { current_statement_begin__ = 224; lp_accum__.add(uniform_log<propto__>(theta, 0, 1)); } current_statement_begin__ = 228; lp_accum__.add(normal_log<propto__>(z, 0, 1)); current_statement_begin__ = 229; lp_accum__.add(normal_log<propto__>(zpos, 0, 1)); current_statement_begin__ = 232; lp_accum__.add(student_t_log<propto__>(sigma, 3, 0, 2)); current_statement_begin__ = 233; if (as_bool(logical_eq(est_cor, 1))) { current_statement_begin__ = 234; lp_accum__.add(lkj_corr_cholesky_log<propto__>(Lcorr, 1)); } current_statement_begin__ = 238; if (as_bool(logical_eq(est_cor, 0))) { current_statement_begin__ = 239; for (int i = 1; i <= P; ++i) { current_statement_begin__ = 240; lp_accum__.add(normal_log(get_base1(yall, i, "yall", 1), get_base1(pred, i, "pred", 1), get_base1(sigma_vec, i, "sigma_vec", 1))); } } else { current_statement_begin__ = 244; for (int i = 1; i <= N; ++i) { current_statement_begin__ = 245; lp_accum__.add(multi_normal_cholesky_log(col(yall, i), col(pred, i), diag_pre_multiply(sigma_vec, Lcorr))); } } } catch (const std::exception& e) { stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__()); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } lp_accum__.add(lp__); return lp_accum__.sum(); } // log_prob() template <bool propto, bool jacobian, typename T_> T_ log_prob(Eigen::Matrix<T_,Eigen::Dynamic,1>& params_r, std::ostream* pstream = 0) const { std::vector<T_> vec_params_r; vec_params_r.reserve(params_r.size()); for (int i = 0; i < params_r.size(); ++i) vec_params_r.push_back(params_r(i)); std::vector<int> vec_params_i; return log_prob<propto,jacobian,T_>(vec_params_r, vec_params_i, pstream); } void get_param_names(std::vector<std::string>& names__) const { names__.resize(0); names__.push_back("devs"); names__.push_back("x0"); names__.push_back("psi"); names__.push_back("z"); names__.push_back("zpos"); names__.push_back("b_obs"); names__.push_back("b_pro"); names__.push_back("sigma"); names__.push_back("nu"); names__.push_back("ymiss"); names__.push_back("phi"); names__.push_back("theta"); names__.push_back("Lcorr"); names__.push_back("pred"); names__.push_back("Z"); names__.push_back("yall"); names__.push_back("sigma_vec"); names__.push_back("phi_vec"); names__.push_back("theta_vec"); names__.push_back("x"); names__.push_back("indicator"); names__.push_back("psi_root"); names__.push_back("log_lik"); names__.push_back("Omega"); names__.push_back("Sigma"); names__.push_back("j"); } void get_dims(std::vector<std::vector<size_t> >& dimss__) const { dimss__.resize(0); std::vector<size_t> dims__; dims__.resize(0); dims__.push_back(K); dims__.push_back((N - 1)); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(K); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(K); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(nZ); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(K); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(n_obs_covar); dims__.push_back(P); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(n_pro_covar); dims__.push_back(K); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(nVariances); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(estimate_nu); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(n_na); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back((est_phi * K)); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back((est_theta * K)); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(n_pcor); dims__.push_back(n_pcor); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(P); dims__.push_back(N); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(P); dims__.push_back(K); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(P); dims__.push_back(N); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(P); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(K); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(K); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(K); dims__.push_back(N); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(K); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(K); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(n_loglik); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(n_pcor); dims__.push_back(n_pcor); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(n_pcor); dims__.push_back(n_pcor); dimss__.push_back(dims__); dims__.resize(0); dimss__.push_back(dims__); } template <typename RNG> void write_array(RNG& base_rng__, std::vector<double>& params_r__, std::vector<int>& params_i__, std::vector<double>& vars__, bool include_tparams__ = true, bool include_gqs__ = true, std::ostream* pstream__ = 0) const { typedef double local_scalar_t__; vars__.resize(0); stan::io::reader<local_scalar_t__> in__(params_r__, params_i__); static const char* function__ = "model_dfa_namespace::write_array"; (void) function__; // dummy to suppress unused var warning // read-transform, write parameters Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> devs = in__.matrix_constrain(K, (N - 1)); size_t devs_j_2_max__ = (N - 1); size_t devs_j_1_max__ = K; for (size_t j_2__ = 0; j_2__ < devs_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < devs_j_1_max__; ++j_1__) { vars__.push_back(devs(j_1__, j_2__)); } } Eigen::Matrix<double, Eigen::Dynamic, 1> x0 = in__.vector_constrain(K); size_t x0_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < x0_j_1_max__; ++j_1__) { vars__.push_back(x0(j_1__)); } Eigen::Matrix<double, Eigen::Dynamic, 1> psi = in__.vector_lb_constrain(0, K); size_t psi_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < psi_j_1_max__; ++j_1__) { vars__.push_back(psi(j_1__)); } Eigen::Matrix<double, Eigen::Dynamic, 1> z = in__.vector_constrain(nZ); size_t z_j_1_max__ = nZ; for (size_t j_1__ = 0; j_1__ < z_j_1_max__; ++j_1__) { vars__.push_back(z(j_1__)); } Eigen::Matrix<double, Eigen::Dynamic, 1> zpos = in__.vector_constrain(K); size_t zpos_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < zpos_j_1_max__; ++j_1__) { vars__.push_back(zpos(j_1__)); } Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> b_obs = in__.matrix_constrain(n_obs_covar, P); size_t b_obs_j_2_max__ = P; size_t b_obs_j_1_max__ = n_obs_covar; for (size_t j_2__ = 0; j_2__ < b_obs_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < b_obs_j_1_max__; ++j_1__) { vars__.push_back(b_obs(j_1__, j_2__)); } } Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> b_pro = in__.matrix_constrain(n_pro_covar, K); size_t b_pro_j_2_max__ = K; size_t b_pro_j_1_max__ = n_pro_covar; for (size_t j_2__ = 0; j_2__ < b_pro_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < b_pro_j_1_max__; ++j_1__) { vars__.push_back(b_pro(j_1__, j_2__)); } } std::vector<double> sigma; size_t sigma_d_0_max__ = nVariances; sigma.reserve(sigma_d_0_max__); for (size_t d_0__ = 0; d_0__ < sigma_d_0_max__; ++d_0__) { sigma.push_back(in__.scalar_lb_constrain(0)); } size_t sigma_k_0_max__ = nVariances; for (size_t k_0__ = 0; k_0__ < sigma_k_0_max__; ++k_0__) { vars__.push_back(sigma[k_0__]); } std::vector<double> nu; size_t nu_d_0_max__ = estimate_nu; nu.reserve(nu_d_0_max__); for (size_t d_0__ = 0; d_0__ < nu_d_0_max__; ++d_0__) { nu.push_back(in__.scalar_lb_constrain(2)); } size_t nu_k_0_max__ = estimate_nu; for (size_t k_0__ = 0; k_0__ < nu_k_0_max__; ++k_0__) { vars__.push_back(nu[k_0__]); } std::vector<double> ymiss; size_t ymiss_d_0_max__ = n_na; ymiss.reserve(ymiss_d_0_max__); for (size_t d_0__ = 0; d_0__ < ymiss_d_0_max__; ++d_0__) { ymiss.push_back(in__.scalar_constrain()); } size_t ymiss_k_0_max__ = n_na; for (size_t k_0__ = 0; k_0__ < ymiss_k_0_max__; ++k_0__) { vars__.push_back(ymiss[k_0__]); } std::vector<double> phi; size_t phi_d_0_max__ = (est_phi * K); phi.reserve(phi_d_0_max__); for (size_t d_0__ = 0; d_0__ < phi_d_0_max__; ++d_0__) { phi.push_back(in__.scalar_lub_constrain(-(1), 1)); } size_t phi_k_0_max__ = (est_phi * K); for (size_t k_0__ = 0; k_0__ < phi_k_0_max__; ++k_0__) { vars__.push_back(phi[k_0__]); } std::vector<double> theta; size_t theta_d_0_max__ = (est_theta * K); theta.reserve(theta_d_0_max__); for (size_t d_0__ = 0; d_0__ < theta_d_0_max__; ++d_0__) { theta.push_back(in__.scalar_lub_constrain(-(1), 1)); } size_t theta_k_0_max__ = (est_theta * K); for (size_t k_0__ = 0; k_0__ < theta_k_0_max__; ++k_0__) { vars__.push_back(theta[k_0__]); } Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Lcorr = in__.cholesky_factor_corr_constrain(n_pcor); size_t Lcorr_j_2_max__ = n_pcor; size_t Lcorr_j_1_max__ = n_pcor; for (size_t j_2__ = 0; j_2__ < Lcorr_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < Lcorr_j_1_max__; ++j_1__) { vars__.push_back(Lcorr(j_1__, j_2__)); } } double lp__ = 0.0; (void) lp__; // dummy to suppress unused var warning stan::math::accumulator<double> lp_accum__; local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning if (!include_tparams__ && !include_gqs__) return; try { // declare and define transformed parameters current_statement_begin__ = 75; validate_non_negative_index("pred", "P", P); validate_non_negative_index("pred", "N", N); Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> pred(P, N); stan::math::initialize(pred, DUMMY_VAR__); stan::math::fill(pred, DUMMY_VAR__); current_statement_begin__ = 76; validate_non_negative_index("Z", "P", P); validate_non_negative_index("Z", "K", K); Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Z(P, K); stan::math::initialize(Z, DUMMY_VAR__); stan::math::fill(Z, DUMMY_VAR__); current_statement_begin__ = 78; validate_non_negative_index("yall", "P", P); validate_non_negative_index("yall", "N", N); Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> yall(P, N); stan::math::initialize(yall, DUMMY_VAR__); stan::math::fill(yall, DUMMY_VAR__); current_statement_begin__ = 79; validate_non_negative_index("sigma_vec", "P", P); Eigen::Matrix<double, Eigen::Dynamic, 1> sigma_vec(P); stan::math::initialize(sigma_vec, DUMMY_VAR__); stan::math::fill(sigma_vec, DUMMY_VAR__); current_statement_begin__ = 80; validate_non_negative_index("phi_vec", "K", K); Eigen::Matrix<double, Eigen::Dynamic, 1> phi_vec(K); stan::math::initialize(phi_vec, DUMMY_VAR__); stan::math::fill(phi_vec, DUMMY_VAR__); current_statement_begin__ = 81; validate_non_negative_index("theta_vec", "K", K); Eigen::Matrix<double, Eigen::Dynamic, 1> theta_vec(K); stan::math::initialize(theta_vec, DUMMY_VAR__); stan::math::fill(theta_vec, DUMMY_VAR__); current_statement_begin__ = 82; validate_non_negative_index("x", "K", K); validate_non_negative_index("x", "N", N); Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> x(K, N); stan::math::initialize(x, DUMMY_VAR__); stan::math::fill(x, DUMMY_VAR__); current_statement_begin__ = 83; validate_non_negative_index("indicator", "K", K); Eigen::Matrix<double, Eigen::Dynamic, 1> indicator(K); stan::math::initialize(indicator, DUMMY_VAR__); stan::math::fill(indicator, DUMMY_VAR__); current_statement_begin__ = 84; validate_non_negative_index("psi_root", "K", K); Eigen::Matrix<double, Eigen::Dynamic, 1> psi_root(K); stan::math::initialize(psi_root, DUMMY_VAR__); stan::math::fill(psi_root, DUMMY_VAR__); // do transformed parameters statements current_statement_begin__ = 87; if (as_bool(logical_eq(est_phi, 1))) { current_statement_begin__ = 88; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 88; stan::model::assign(phi_vec, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), get_base1(phi, k, "phi", 1), "assigning variable phi_vec"); } } else { current_statement_begin__ = 90; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 90; stan::model::assign(phi_vec, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), 1, "assigning variable phi_vec"); } } current_statement_begin__ = 94; if (as_bool(logical_eq(est_theta, 1))) { current_statement_begin__ = 95; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 95; stan::model::assign(theta_vec, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), get_base1(theta, k, "theta", 1), "assigning variable theta_vec"); } } else { current_statement_begin__ = 97; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 97; stan::model::assign(theta_vec, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), 0, "assigning variable theta_vec"); } } current_statement_begin__ = 100; for (int p = 1; p <= P; ++p) { current_statement_begin__ = 101; stan::model::assign(sigma_vec, stan::model::cons_list(stan::model::index_uni(p), stan::model::nil_index_list()), get_base1(sigma, get_base1(varIndx, p, "varIndx", 1), "sigma", 1), "assigning variable sigma_vec"); } current_statement_begin__ = 105; for (int i = 1; i <= n_pos; ++i) { current_statement_begin__ = 106; stan::model::assign(yall, stan::model::cons_list(stan::model::index_uni(get_base1(row_indx_pos, i, "row_indx_pos", 1)), stan::model::cons_list(stan::model::index_uni(get_base1(col_indx_pos, i, "col_indx_pos", 1)), stan::model::nil_index_list())), get_base1(y, i, "y", 1), "assigning variable yall"); } current_statement_begin__ = 109; if (as_bool(logical_gt(n_na, 0))) { current_statement_begin__ = 110; for (int i = 1; i <= n_na; ++i) { current_statement_begin__ = 111; stan::model::assign(yall, stan::model::cons_list(stan::model::index_uni(get_base1(row_indx_na, i, "row_indx_na", 1)), stan::model::cons_list(stan::model::index_uni(get_base1(col_indx_na, i, "col_indx_na", 1)), stan::model::nil_index_list())), get_base1(ymiss, i, "ymiss", 1), "assigning variable yall"); } } current_statement_begin__ = 115; for (int i = 1; i <= nZ; ++i) { current_statement_begin__ = 116; stan::model::assign(Z, stan::model::cons_list(stan::model::index_uni(get_base1(row_indx, i, "row_indx", 1)), stan::model::cons_list(stan::model::index_uni(get_base1(col_indx, i, "col_indx", 1)), stan::model::nil_index_list())), get_base1(z, i, "z", 1), "assigning variable Z"); } current_statement_begin__ = 119; if (as_bool(logical_gt(nZero, 2))) { current_statement_begin__ = 120; for (int i = 1; i <= (nZero - 2); ++i) { current_statement_begin__ = 121; stan::model::assign(Z, stan::model::cons_list(stan::model::index_uni(get_base1(row_indx_z, i, "row_indx_z", 1)), stan::model::cons_list(stan::model::index_uni(get_base1(col_indx_z, i, "col_indx_z", 1)), stan::model::nil_index_list())), 0, "assigning variable Z"); } } current_statement_begin__ = 125; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 126; stan::model::assign(Z, stan::model::cons_list(stan::model::index_uni(k), stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list())), get_base1(zpos, k, "zpos", 1), "assigning variable Z"); } current_statement_begin__ = 130; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 131; if (as_bool(logical_lt(get_base1(zpos, k, "zpos", 1), 0))) { current_statement_begin__ = 132; stan::model::assign(indicator, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), -(1), "assigning variable indicator"); } else { current_statement_begin__ = 134; stan::model::assign(indicator, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), 1, "assigning variable indicator"); } current_statement_begin__ = 136; stan::model::assign(psi_root, stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list()), stan::math::sqrt(get_base1(psi, k, "psi", 1)), "assigning variable psi_root"); current_statement_begin__ = 137; for (int p = 1; p <= P; ++p) { current_statement_begin__ = 138; stan::model::assign(Z, stan::model::cons_list(stan::model::index_uni(p), stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list())), ((get_base1(Z, p, k, "Z", 1) * get_base1(indicator, k, "indicator", 1)) * (1 / get_base1(psi_root, k, "psi_root", 1))), "assigning variable Z"); } } current_statement_begin__ = 143; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 144; stan::model::assign(x, stan::model::cons_list(stan::model::index_uni(k), stan::model::cons_list(stan::model::index_uni(1), stan::model::nil_index_list())), get_base1(x0, k, "x0", 1), "assigning variable x"); current_statement_begin__ = 148; for (int t = 2; t <= N; ++t) { current_statement_begin__ = 149; stan::model::assign(x, stan::model::cons_list(stan::model::index_uni(k), stan::model::cons_list(stan::model::index_uni(t), stan::model::nil_index_list())), ((get_base1(phi_vec, k, "phi_vec", 1) * get_base1(x, k, (t - 1), "x", 1)) + get_base1(devs, k, (t - 1), "devs", 1)), "assigning variable x"); } } current_statement_begin__ = 153; for (int k = 1; k <= K; ++k) { current_statement_begin__ = 155; for (int t = 1; t <= N; ++t) { current_statement_begin__ = 156; stan::model::assign(x, stan::model::cons_list(stan::model::index_uni(k), stan::model::cons_list(stan::model::index_uni(t), stan::model::nil_index_list())), ((get_base1(x, k, t, "x", 1) * get_base1(indicator, k, "indicator", 1)) * get_base1(psi_root, k, "psi_root", 1)), "assigning variable x"); } } current_statement_begin__ = 161; if (as_bool(logical_gt(num_pro_covar, 0))) { current_statement_begin__ = 162; for (int i = 1; i <= num_pro_covar; ++i) { current_statement_begin__ = 164; stan::model::assign(x, stan::model::cons_list(stan::model::index_uni(get_base1(get_base1(pro_covar_index, i, "pro_covar_index", 1), 2, "pro_covar_index", 2)), stan::model::cons_list(stan::model::index_uni(get_base1(get_base1(pro_covar_index, i, "pro_covar_index", 1), 1, "pro_covar_index", 2)), stan::model::nil_index_list())), (get_base1(x, get_base1(get_base1(pro_covar_index, i, "pro_covar_index", 1), 2, "pro_covar_index", 2), get_base1(get_base1(pro_covar_index, i, "pro_covar_index", 1), 1, "pro_covar_index", 2), "x", 1) + (get_base1(b_pro, get_base1(get_base1(pro_covar_index, i, "pro_covar_index", 1), 3, "pro_covar_index", 2), get_base1(get_base1(pro_covar_index, i, "pro_covar_index", 1), 2, "pro_covar_index", 2), "b_pro", 1) * get_base1(pro_covar_value, i, "pro_covar_value", 1))), "assigning variable x"); } } current_statement_begin__ = 170; stan::math::assign(pred, multiply(Z, x)); current_statement_begin__ = 173; if (as_bool(logical_gt(num_obs_covar, 0))) { current_statement_begin__ = 174; for (int i = 1; i <= num_obs_covar; ++i) { current_statement_begin__ = 176; stan::model::assign(pred, stan::model::cons_list(stan::model::index_uni(get_base1(get_base1(obs_covar_index, i, "obs_covar_index", 1), 2, "obs_covar_index", 2)), stan::model::cons_list(stan::model::index_uni(get_base1(get_base1(obs_covar_index, i, "obs_covar_index", 1), 1, "obs_covar_index", 2)), stan::model::nil_index_list())), (get_base1(pred, get_base1(get_base1(obs_covar_index, i, "obs_covar_index", 1), 2, "obs_covar_index", 2), get_base1(get_base1(obs_covar_index, i, "obs_covar_index", 1), 1, "obs_covar_index", 2), "pred", 1) + (get_base1(b_obs, get_base1(get_base1(obs_covar_index, i, "obs_covar_index", 1), 3, "obs_covar_index", 2), get_base1(get_base1(obs_covar_index, i, "obs_covar_index", 1), 2, "obs_covar_index", 2), "b_obs", 1) * get_base1(obs_covar_value, i, "obs_covar_value", 1))), "assigning variable pred"); } } if (!include_gqs__ && !include_tparams__) return; // validate transformed parameters const char* function__ = "validate transformed params"; (void) function__; // dummy to suppress unused var warning // write transformed parameters if (include_tparams__) { size_t pred_j_2_max__ = N; size_t pred_j_1_max__ = P; for (size_t j_2__ = 0; j_2__ < pred_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < pred_j_1_max__; ++j_1__) { vars__.push_back(pred(j_1__, j_2__)); } } size_t Z_j_2_max__ = K; size_t Z_j_1_max__ = P; for (size_t j_2__ = 0; j_2__ < Z_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < Z_j_1_max__; ++j_1__) { vars__.push_back(Z(j_1__, j_2__)); } } size_t yall_j_2_max__ = N; size_t yall_j_1_max__ = P; for (size_t j_2__ = 0; j_2__ < yall_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < yall_j_1_max__; ++j_1__) { vars__.push_back(yall(j_1__, j_2__)); } } size_t sigma_vec_j_1_max__ = P; for (size_t j_1__ = 0; j_1__ < sigma_vec_j_1_max__; ++j_1__) { vars__.push_back(sigma_vec(j_1__)); } size_t phi_vec_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < phi_vec_j_1_max__; ++j_1__) { vars__.push_back(phi_vec(j_1__)); } size_t theta_vec_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < theta_vec_j_1_max__; ++j_1__) { vars__.push_back(theta_vec(j_1__)); } size_t x_j_2_max__ = N; size_t x_j_1_max__ = K; for (size_t j_2__ = 0; j_2__ < x_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < x_j_1_max__; ++j_1__) { vars__.push_back(x(j_1__, j_2__)); } } size_t indicator_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < indicator_j_1_max__; ++j_1__) { vars__.push_back(indicator(j_1__)); } size_t psi_root_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < psi_root_j_1_max__; ++j_1__) { vars__.push_back(psi_root(j_1__)); } } if (!include_gqs__) return; // declare and define generated quantities current_statement_begin__ = 250; validate_non_negative_index("log_lik", "n_loglik", n_loglik); Eigen::Matrix<double, Eigen::Dynamic, 1> log_lik(n_loglik); stan::math::initialize(log_lik, DUMMY_VAR__); stan::math::fill(log_lik, DUMMY_VAR__); current_statement_begin__ = 251; validate_non_negative_index("Omega", "n_pcor", n_pcor); validate_non_negative_index("Omega", "n_pcor", n_pcor); Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Omega(n_pcor, n_pcor); stan::math::initialize(Omega, DUMMY_VAR__); stan::math::fill(Omega, DUMMY_VAR__); current_statement_begin__ = 252; validate_non_negative_index("Sigma", "n_pcor", n_pcor); validate_non_negative_index("Sigma", "n_pcor", n_pcor); Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Sigma(n_pcor, n_pcor); stan::math::initialize(Sigma, DUMMY_VAR__); stan::math::fill(Sigma, DUMMY_VAR__); current_statement_begin__ = 253; int j; (void) j; // dummy to suppress unused var warning stan::math::fill(j, std::numeric_limits<int>::min()); // generated quantities statements current_statement_begin__ = 254; stan::math::assign(j, 0); current_statement_begin__ = 256; if (as_bool(logical_eq(est_cor, 1))) { current_statement_begin__ = 257; stan::math::assign(Omega, multiply_lower_tri_self_transpose(Lcorr)); current_statement_begin__ = 258; stan::math::assign(Sigma, quad_form_diag(Omega, sigma_vec)); } current_statement_begin__ = 262; if (as_bool(logical_eq(est_cor, 0))) { current_statement_begin__ = 263; stan::math::assign(j, 0); current_statement_begin__ = 264; for (int n = 1; n <= N; ++n) { current_statement_begin__ = 265; for (int p = 1; p <= P; ++p) { current_statement_begin__ = 266; stan::math::assign(j, (j + 1)); current_statement_begin__ = 267; stan::model::assign(log_lik, stan::model::cons_list(stan::model::index_uni(j), stan::model::nil_index_list()), normal_log(get_base1(yall, p, n, "yall", 1), get_base1(pred, p, n, "pred", 1), get_base1(sigma_vec, p, "sigma_vec", 1)), "assigning variable log_lik"); } } } else { current_statement_begin__ = 272; for (int i = 1; i <= N; ++i) { current_statement_begin__ = 273; stan::model::assign(log_lik, stan::model::cons_list(stan::model::index_uni(i), stan::model::nil_index_list()), multi_normal_cholesky_log(col(yall, i), col(pred, i), diag_pre_multiply(sigma_vec, Lcorr)), "assigning variable log_lik"); } } // validate, write generated quantities current_statement_begin__ = 250; size_t log_lik_j_1_max__ = n_loglik; for (size_t j_1__ = 0; j_1__ < log_lik_j_1_max__; ++j_1__) { vars__.push_back(log_lik(j_1__)); } current_statement_begin__ = 251; size_t Omega_j_2_max__ = n_pcor; size_t Omega_j_1_max__ = n_pcor; for (size_t j_2__ = 0; j_2__ < Omega_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < Omega_j_1_max__; ++j_1__) { vars__.push_back(Omega(j_1__, j_2__)); } } current_statement_begin__ = 252; size_t Sigma_j_2_max__ = n_pcor; size_t Sigma_j_1_max__ = n_pcor; for (size_t j_2__ = 0; j_2__ < Sigma_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < Sigma_j_1_max__; ++j_1__) { vars__.push_back(Sigma(j_1__, j_2__)); } } current_statement_begin__ = 253; check_greater_or_equal(function__, "j", j, 0); vars__.push_back(j); } catch (const std::exception& e) { stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__()); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } } template <typename RNG> void write_array(RNG& base_rng, Eigen::Matrix<double,Eigen::Dynamic,1>& params_r, Eigen::Matrix<double,Eigen::Dynamic,1>& vars, bool include_tparams = true, bool include_gqs = true, std::ostream* pstream = 0) const { std::vector<double> params_r_vec(params_r.size()); for (int i = 0; i < params_r.size(); ++i) params_r_vec[i] = params_r(i); std::vector<double> vars_vec; std::vector<int> params_i_vec; write_array(base_rng, params_r_vec, params_i_vec, vars_vec, include_tparams, include_gqs, pstream); vars.resize(vars_vec.size()); for (int i = 0; i < vars.size(); ++i) vars(i) = vars_vec[i]; } static std::string model_name() { return "model_dfa"; } void constrained_param_names(std::vector<std::string>& param_names__, bool include_tparams__ = true, bool include_gqs__ = true) const { std::stringstream param_name_stream__; size_t devs_j_2_max__ = (N - 1); size_t devs_j_1_max__ = K; for (size_t j_2__ = 0; j_2__ < devs_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < devs_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "devs" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t x0_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < x0_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "x0" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t psi_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < psi_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "psi" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t z_j_1_max__ = nZ; for (size_t j_1__ = 0; j_1__ < z_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "z" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t zpos_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < zpos_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "zpos" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t b_obs_j_2_max__ = P; size_t b_obs_j_1_max__ = n_obs_covar; for (size_t j_2__ = 0; j_2__ < b_obs_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < b_obs_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "b_obs" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t b_pro_j_2_max__ = K; size_t b_pro_j_1_max__ = n_pro_covar; for (size_t j_2__ = 0; j_2__ < b_pro_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < b_pro_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "b_pro" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t sigma_k_0_max__ = nVariances; for (size_t k_0__ = 0; k_0__ < sigma_k_0_max__; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "sigma" << '.' << k_0__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t nu_k_0_max__ = estimate_nu; for (size_t k_0__ = 0; k_0__ < nu_k_0_max__; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "nu" << '.' << k_0__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t ymiss_k_0_max__ = n_na; for (size_t k_0__ = 0; k_0__ < ymiss_k_0_max__; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "ymiss" << '.' << k_0__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t phi_k_0_max__ = (est_phi * K); for (size_t k_0__ = 0; k_0__ < phi_k_0_max__; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "phi" << '.' << k_0__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t theta_k_0_max__ = (est_theta * K); for (size_t k_0__ = 0; k_0__ < theta_k_0_max__; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "theta" << '.' << k_0__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t Lcorr_j_2_max__ = n_pcor; size_t Lcorr_j_1_max__ = n_pcor; for (size_t j_2__ = 0; j_2__ < Lcorr_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < Lcorr_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "Lcorr" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } if (!include_gqs__ && !include_tparams__) return; if (include_tparams__) { size_t pred_j_2_max__ = N; size_t pred_j_1_max__ = P; for (size_t j_2__ = 0; j_2__ < pred_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < pred_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "pred" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t Z_j_2_max__ = K; size_t Z_j_1_max__ = P; for (size_t j_2__ = 0; j_2__ < Z_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < Z_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "Z" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t yall_j_2_max__ = N; size_t yall_j_1_max__ = P; for (size_t j_2__ = 0; j_2__ < yall_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < yall_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "yall" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t sigma_vec_j_1_max__ = P; for (size_t j_1__ = 0; j_1__ < sigma_vec_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "sigma_vec" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t phi_vec_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < phi_vec_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "phi_vec" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t theta_vec_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < theta_vec_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "theta_vec" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t x_j_2_max__ = N; size_t x_j_1_max__ = K; for (size_t j_2__ = 0; j_2__ < x_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < x_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "x" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t indicator_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < indicator_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "indicator" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t psi_root_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < psi_root_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "psi_root" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } } if (!include_gqs__) return; size_t log_lik_j_1_max__ = n_loglik; for (size_t j_1__ = 0; j_1__ < log_lik_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "log_lik" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t Omega_j_2_max__ = n_pcor; size_t Omega_j_1_max__ = n_pcor; for (size_t j_2__ = 0; j_2__ < Omega_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < Omega_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "Omega" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t Sigma_j_2_max__ = n_pcor; size_t Sigma_j_1_max__ = n_pcor; for (size_t j_2__ = 0; j_2__ < Sigma_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < Sigma_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "Sigma" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } param_name_stream__.str(std::string()); param_name_stream__ << "j"; param_names__.push_back(param_name_stream__.str()); } void unconstrained_param_names(std::vector<std::string>& param_names__, bool include_tparams__ = true, bool include_gqs__ = true) const { std::stringstream param_name_stream__; size_t devs_j_2_max__ = (N - 1); size_t devs_j_1_max__ = K; for (size_t j_2__ = 0; j_2__ < devs_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < devs_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "devs" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t x0_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < x0_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "x0" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t psi_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < psi_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "psi" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t z_j_1_max__ = nZ; for (size_t j_1__ = 0; j_1__ < z_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "z" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t zpos_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < zpos_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "zpos" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t b_obs_j_2_max__ = P; size_t b_obs_j_1_max__ = n_obs_covar; for (size_t j_2__ = 0; j_2__ < b_obs_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < b_obs_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "b_obs" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t b_pro_j_2_max__ = K; size_t b_pro_j_1_max__ = n_pro_covar; for (size_t j_2__ = 0; j_2__ < b_pro_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < b_pro_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "b_pro" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t sigma_k_0_max__ = nVariances; for (size_t k_0__ = 0; k_0__ < sigma_k_0_max__; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "sigma" << '.' << k_0__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t nu_k_0_max__ = estimate_nu; for (size_t k_0__ = 0; k_0__ < nu_k_0_max__; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "nu" << '.' << k_0__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t ymiss_k_0_max__ = n_na; for (size_t k_0__ = 0; k_0__ < ymiss_k_0_max__; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "ymiss" << '.' << k_0__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t phi_k_0_max__ = (est_phi * K); for (size_t k_0__ = 0; k_0__ < phi_k_0_max__; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "phi" << '.' << k_0__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t theta_k_0_max__ = (est_theta * K); for (size_t k_0__ = 0; k_0__ < theta_k_0_max__; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "theta" << '.' << k_0__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t Lcorr_j_1_max__ = ((n_pcor * (n_pcor - 1)) / 2); for (size_t j_1__ = 0; j_1__ < Lcorr_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "Lcorr" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } if (!include_gqs__ && !include_tparams__) return; if (include_tparams__) { size_t pred_j_2_max__ = N; size_t pred_j_1_max__ = P; for (size_t j_2__ = 0; j_2__ < pred_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < pred_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "pred" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t Z_j_2_max__ = K; size_t Z_j_1_max__ = P; for (size_t j_2__ = 0; j_2__ < Z_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < Z_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "Z" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t yall_j_2_max__ = N; size_t yall_j_1_max__ = P; for (size_t j_2__ = 0; j_2__ < yall_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < yall_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "yall" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t sigma_vec_j_1_max__ = P; for (size_t j_1__ = 0; j_1__ < sigma_vec_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "sigma_vec" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t phi_vec_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < phi_vec_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "phi_vec" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t theta_vec_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < theta_vec_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "theta_vec" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t x_j_2_max__ = N; size_t x_j_1_max__ = K; for (size_t j_2__ = 0; j_2__ < x_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < x_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "x" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t indicator_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < indicator_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "indicator" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t psi_root_j_1_max__ = K; for (size_t j_1__ = 0; j_1__ < psi_root_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "psi_root" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } } if (!include_gqs__) return; size_t log_lik_j_1_max__ = n_loglik; for (size_t j_1__ = 0; j_1__ < log_lik_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "log_lik" << '.' << j_1__ + 1; param_names__.push_back(param_name_stream__.str()); } size_t Omega_j_2_max__ = n_pcor; size_t Omega_j_1_max__ = n_pcor; for (size_t j_2__ = 0; j_2__ < Omega_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < Omega_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "Omega" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } size_t Sigma_j_2_max__ = n_pcor; size_t Sigma_j_1_max__ = n_pcor; for (size_t j_2__ = 0; j_2__ < Sigma_j_2_max__; ++j_2__) { for (size_t j_1__ = 0; j_1__ < Sigma_j_1_max__; ++j_1__) { param_name_stream__.str(std::string()); param_name_stream__ << "Sigma" << '.' << j_1__ + 1 << '.' << j_2__ + 1; param_names__.push_back(param_name_stream__.str()); } } param_name_stream__.str(std::string()); param_name_stream__ << "j"; param_names__.push_back(param_name_stream__.str()); } }; // model } // namespace typedef model_dfa_namespace::model_dfa stan_model; #endif
#include "state_log.h" #include "log.h" uint32_t StateLog::fail_count_arr[MAX_GAME_ID]; uint32_t StateLog::suc_count_arr[MAX_GAME_ID]; int StateLog::cache_size_arr[MAX_GAME_ID]; extern std::vector<int> g_game_id_vec; // 打印失败信息和流量信息 void StateLog::PrintStateInfo() { std::vector<int>::iterator it = g_game_id_vec.begin(); NOTI_LOG("----------------------failed--------------------------"); for (; it != g_game_id_vec.end(); ++it) { NOTI_LOG("game_id : %d, failed_count : %d", *it, fail_count_arr[*it]); fail_count_arr[*it] = 0; } it = g_game_id_vec.begin(); NOTI_LOG("----------------------success--------------------------"); for (; it != g_game_id_vec.end(); ++it) { NOTI_LOG("game_id : %d, success_count : %d", *it, suc_count_arr[*it]); suc_count_arr[*it] = 0; } } // 记录一次失败次数 void StateLog::RecordFailCount(int game_id) { fail_count_arr[game_id] ++; } // 记录一次成功次数 void StateLog::RecordSucCount(int game_id) { suc_count_arr[game_id] ++; } // 记录队列长度 // 在每次遍历处理的时候进行统计 void StateLog::IncreaseCacheListSize(int game_id) { // 遍历操作 cache_size_arr[game_id] ++; } // TODO 增加对game_id范围的限制, 刚开始进行限制 int StateLog::GetCurrentCacheListSize(int game_id) { return cache_size_arr[game_id]; } void StateLog::ResetCacheListSize(int game_id) { cache_size_arr[game_id] = 0; }
#include<iostream> using namespace std; #include "11_C++Primer4h.h" /* enum {MAX = 10}; // constant specific to class int * pitems; // holds stack items int size; // number of elements in stack int top; // index for top stack item */ Stack::Stack(int n) : size(n), top(0) // creates stack with n elements { if(n > 10 || n < 1) { cerr << "Bad stack size -- must be 1-10\n"; exit(1); } pitems = new int[size]; } Stack::Stack(const Stack & st) : size(st.size), top(st.top) { pitems = new int[size]; for(int i = 0; i < st.top; i++) pitems[i] = st.pitems[i]; } Stack::~Stack() { delete[] pitems; } bool Stack::isempty() const { return top == 0; } bool Stack::isfull() const { return top == size; } // push() returns false if stack already is full, true otherwise bool Stack::push(const int & item) { if(top == size) return false; pitems[top++] = item; return true; } bool Stack::pop(int & item) { if(top == 0) return false; item = pitems[--top]; return true; } Stack & Stack::operator=(const Stack & st) { top = st.top; size = st.size; pitems = new int[size]; for(int i = 0; i < st.top; i++) pitems[i] = st.pitems[i]; } int main() { Stack first; Stack second(7); int ray[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int ray1[10]; cout << "Ray: "; for(int i = 0; i < 10; i++) cout << ray[i] << " "; cout << "Ray1 is empty.\n\n"; for(int i = 0; first.push(ray[i]); i++) cout << "Adding " << ray[i] << " to first from ray!\n"; for(int i = 0; first.pop(ray1[i]); i++) cout << ray1[i] << " popped from first into ray1!\n"; for(int i = 0; second.push(ray1[i]); i++) cout << "Adding " << ray1[i] << " to second from ray1!\n"; for(int i = 0; second.pop(ray[i]); i++) cout << ray[i] << " popped from second into ray!\n"; cout << "\nRay: "; for(int i = 0; i < 10; i++) cout << ray[i] << " "; cout << endl << "\nRay1: "; for(int i = 0; i < 10; i++) cout << ray1[i] << " "; }
#ifndef STADIUMMODIFY_H #define STADIUMMODIFY_H #include <QDialog> namespace Ui { class stadiumModify; } class stadiumModify : public QDialog { Q_OBJECT public: explicit stadiumModify(QWidget *parent = 0,QString selectedStad = " "); ~stadiumModify(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); private: Ui::stadiumModify *ui; QString selectedStadium; }; #endif // STADIUMMODIFY_H