text
stringlengths
8
6.88M
#include "widget.h" #include "ui_widget.h" #include <QFileDialog> #include <QMessageBox> #include <QTextStream> #include <QFile> #include <QDebug> #include <QDesktopServices> Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); diaintro = new DialogIntroduction(this); } Widget::~Widget() { delete ui; } QString Widget::createmodbustxt() { QString text; QFile file("modbus.xml"); if(!file.open(QIODevice::ReadOnly)) { QMessageBox::warning(NULL,"告警窗","modbus.xml文件不存在"); return text; } QDomDocument doc; if(!doc.setContent(&file)) { file.close(); return text; } file.close(); // uchar *sort = ui->modbuswdg->groupuchar; QDomNode fristnode = doc.firstChild(); // qDebug()<<fristnode.nodeName() << fristnode.nodeValue(); text.append("[名称]\n"); text.append(filename + "\n"); text.append("\n[类型]\n"); text.append("保护测控\n"); QDomElement root = doc.documentElement(); QDomNode node = root.firstChild(); QDomElement elem; int group = 0; if(node.isElement()) { elem = node.toElement(); if(elem.tagName() == QString("基本配置")) { QDomNode n = elem.firstChild(); if(n.isElement()) { QDomElement ne = n.toElement(); group =ne.attribute("召唤分组数").toInt(); } } if(group ==0) { return QString(); } } for (int i = 0;i <70;i++) { findelement(root,elem,QString(),QString("index"),QString::number(i+1)); // findwithtype(root,elem,QString(),i+1); if(elem.isNull()) { continue; } QDomNode n = elem.firstChild(); n = n.nextSibling(); if(n.isNull()) { continue; } text.append("\n["+elem.tagName()+"]\n"); while(!n.isNull()) { if(n.isElement()) { QDomElement ne = n.toElement(); if(ne.tagName() == QString("描述")) { text.append(QString("%1,%2,%3,%4,,5,,\n") .arg(ne.attribute("no")).arg(elem.attribute("index")) .arg(ne.attribute("no")).arg(ne.attribute("text"))); } } n = n.nextSibling(); } } text.append("\n[特殊遥信]\n"); text.append("1,255,1,网络状态A,,5,通,断\n"); text.append("2,255,2,网络状态B,,5,通,断\n"); return text; } QString Widget::createmodbuscfg() { QString text; QFile file("modbus.xml"); if(!file.open(QIODevice::ReadOnly)) { QMessageBox::warning(NULL,"告警窗","modbus.xml文件不存在"); return text; } QDomDocument doc; if(!doc.setContent(&file)) { file.close(); return text; } file.close(); QDomNode fristnode = doc.firstChild(); // qDebug()<<fristnode.nodeName() << fristnode.nodeValue(); text.append("[属性]\n"); text.append("名称=" +filename + "\n"); text.append("默认规约=modbus装置规约\n"); text.append("版本号=v1.00\n"); text.append("可变选项组数=1\n"); text.append("[数据分类]\n"); text.append("数目=19\n"); text.append("数据名称=遥测,遥信,遥脉,遥控,遥调,模拟量,动作元件,运行告警,装置自检,硬压板,软压板,故障信息,扰动数据说明,定值,定值区号,特殊遥信,保护测量,装置参数,档位\n"); text.append("遥测=YC\n"); text.append("遥信=YX\n"); text.append("遥脉=YM\n"); text.append("遥控=YK\n"); text.append("遥调=YT\n"); text.append("模拟量=YC\n"); text.append("动作元件=YX\n"); text.append("运行告警=YX\n"); text.append("装置自检=YX\n"); text.append("硬压板=YX\n"); text.append("软压板=YXYK\n"); text.append("故障信息=OTHER\n"); text.append("扰动数据说明=OTHER\n"); text.append("定值=OTHER\n"); text.append("定值区号=OTHER\n"); text.append("特殊遥信=YX\n"); text.append("保护测量=YC\n"); text.append("装置参数=OTHER\n"); text.append("档位=YP\n"); text.append("[相关信息]\n"); text.append("数目=0\n"); text.append("[可变选项1]\n"); text.append("名称=可变选项1\n"); text.append("维数=1\n"); QDomElement root = doc.documentElement(); QDomNode node = root.firstChild(); QDomElement elem; int group = 0; if(node.isElement()) { elem = node.toElement(); if(elem.tagName() == QString("基本配置")) { QDomNode n = elem.firstChild(); if(n.isElement()) { QDomElement ne = n.toElement(); group =ne.attribute("召唤分组数").toInt(); } } if(group ==0) { return QString(); } } int num = 4 + group * 11; int yknum=0; findelement(root,elem,"遥控"); if(!elem.isNull()) { node = elem.lastChild(); if(node.isElement()) { elem = node.toElement(); if(elem.tagName() == QString("描述")) { yknum = elem.attribute("no").toInt(); } } } int ytnum=0; findelement(root,elem,"遥调"); if(!elem.isNull()) { node = elem.lastChild(); if(node.isElement()) { elem = node.toElement(); if(elem.tagName() == QString("描述")) { ytnum = elem.attribute("no").toInt(); } } } if(yknum) num += 4+yknum*4; if(ytnum) num += 1+ytnum; text.append("数目="+QString::number(num)+"\n"); int No = 1; if(yknum) { findelement(root,elem,"遥控"); if(!elem.isNull()) { node = elem.firstChild(); if(node.isElement()) { QDomElement yk = node.toElement(); text.append("选项"+QString::number(No++)+"=遥控功能码,INT,"+yk.attribute("遥控功能码")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥控预置,INT,"+yk.attribute("遥控预置")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=控合命令字,INT,"+yk.attribute("控合命令字")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=控分命令字,INT,"+yk.attribute("控分命令字")+"(0-65535)\n"); yk = yk.nextSiblingElement(); while (!yk.isNull()) { text.append("选项"+QString::number(No++)+"=遥控"+yk.attribute("no")+"控合预置地址,INT,"+yk.attribute("控合预置地址")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥控"+yk.attribute("no")+"控合地址,INT,"+yk.attribute("控合地址")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥控"+yk.attribute("no")+"控分预置地址,INT,"+yk.attribute("控分预置地址")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥控"+yk.attribute("no")+"控分地址,INT,"+yk.attribute("控分地址")+"(0-65535)\n"); yk = yk.nextSiblingElement(); } } } } if(ytnum) { findelement(root,elem,"遥调"); if(!elem.isNull()) { node = elem.firstChild(); if(node.isElement()) { QDomElement yt = node.toElement(); text.append("选项"+QString::number(No++)+"=遥调功能码,INT,"+yt.attribute("遥调功能码")+"(0-65535)\n"); yt = yt.nextSiblingElement(); while (!yt.isNull()) { text.append("选项"+QString::number(No++)+"=遥调"+yt.attribute("no")+"设置地址,INT,"+yt.attribute("设置地址")+"(0-65535)\n"); yt = yt.nextSiblingElement(); } } } } text.append("选项"+QString::number(No++)+"=召唤分组数,INT,"+QString::number(group)+"(0-65535)\n"); uchar *sort = ui->modbuswdg->groupuchar; int index = 0; while (index < group * 3) { if(sort[index]) { findelement(root,elem,QString("遥测"),QString("index"),QString::number(sort[index])); QDomElement yc; findelement(elem,yc,QString("选项")); if(!yc.isNull()) { text.append("选项"+QString::number(No++)+"=遥测寄存器个数,INT,"+yc.attribute("遥测寄存器个数")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥测四字节,INT,"+yc.attribute("遥测四字节")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥测功能码,INT,"+yc.attribute("遥测功能码")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥测起始地址,INT,"+yc.attribute("遥测起始地址")+"(0-65535)\n"); } } else { text.append("选项"+QString::number(No++)+"=遥测寄存器个数,INT,0(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥测四字节,INT,0(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥测功能码,INT,0(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥测起始地址,INT,0(0-65535)\n"); } index++; if(sort[index]) { findelement(root,elem,QString("遥信"),QString("index"),QString::number(sort[index])); QDomElement yx; findelement(elem,yx,QString("选项")); if(!yx.isNull()) { text.append("选项"+QString::number(No++)+"=遥信寄存器个数,INT,"+yx.attribute("遥信寄存器个数")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥信寄存器BIT长度,INT,"+yx.attribute("遥信寄存器BIT长度")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥信功能码,INT,"+yx.attribute("遥信功能码")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥信起始地址,INT,"+yx.attribute("遥信起始地址")+"(0-65535)\n"); } } else { text.append("选项"+QString::number(No++)+"=遥信寄存器个数,INT,0(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥信寄存器BIT长度,INT,0(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥信功能码,INT,0(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥信起始地址,INT,0(0-65535)\n"); } index++; if(sort[index]) { findelement(root,elem,QString("遥脉"),QString("index"),QString::number(sort[index])); QDomElement ym; findelement(elem,ym,QString("选项")); if(!ym.isNull()) { text.append("选项"+QString::number(No++)+"=遥脉寄存器个数,INT,"+ym.attribute("遥脉寄存器个数")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥脉功能码,INT,"+ym.attribute("遥脉功能码")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥脉起始地址,INT,"+ym.attribute("遥脉起始地址")+"(0-65535)\n"); } } else { text.append("选项"+QString::number(No++)+"=遥脉寄存器个数,INT,0(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥脉功能码,INT,0(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥脉起始地址,INT,0(0-65535)\n"); } index++; } findelement(root,elem,QString("基本配置")); QDomElement base; findelement(elem,base,QString("选项")); if(!base.isNull()) { text.append("选项"+QString::number(No++)+"=遥脉低字节寄存器在前,INT,"+base.attribute("遥脉低字节寄存器在前")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=遥脉BCD码格式,INT,"+base.attribute("遥脉BCD码格式")+"(0-65535)\n"); text.append("选项"+QString::number(No++)+"=从机应答报文读取数据长度字节个数,INT,"+base.attribute("从机应答报文读取数据长度字节个数")+"(1-2)\n"); } return text; } QString Widget::createxml() { QString text; if(ui->CB_protocol->currentText() == QString("modbus装置规约")) { text = ui->modbuswdg->checkerror(); if(!text.contains("出错")) { ui->modbuswdg->writeXml(); } } return text; } QString Widget::createtxt() { QString text; if(ui->CB_protocol->currentText() == QString("modbus装置规约")) { text.append(createmodbustxt()); } return text; } QString Widget::createcfg() { QString text; if(ui->CB_protocol->currentText() == QString("modbus装置规约")) { text.append(createmodbuscfg()); } return text; } //void Widget::findwithtype(QDomElement &root, QDomElement &elem,QString type, int index) //{ // QDomNodeList list = root.childNodes(); // for (int i =0;i<list.count();i++) // { // QDomNode node = list.at(i); // if(node.isElement()) // { // elem = node.toElement(); // if((type.isEmpty()||elem.tagName() == type) && elem.attribute("index") == QString::number(index)) // { // return; // } // } // } // elem.clear(); // return; //} void Widget::findelement(QDomElement &root, QDomElement &elem, QString tagname, QString attr, QString attrvalue) { QDomNode node = root.firstChild(); while (!node.isNull()) { if(node.isElement()) { elem = node.toElement(); if((tagname.isEmpty()||elem.tagName() == tagname)&&(attr.isEmpty()||attrvalue.isEmpty()|| elem.attribute(attr) ==attrvalue) ) { return; } } node = node.nextSibling(); } elem.clear(); return; } /***********************选择文件****************************/ void Widget::on_PB_selectfile_clicked() { QString filedir = QFileDialog::getSaveFileName(this,tr("保存对话框"),"",tr("文本文件(*txt)")); if(filedir.isEmpty()) { return; } filedir.remove(".txt"); filename = filedir.split('/').last(); filetxtdir = filedir + ".txt"; filecfgdir = filedir + ".cfg"; ui->LE_filedir->setText(filetxtdir); } /***********************导出文件****************************/ void Widget::on_PB_out_clicked() { QString fileDir = ui->LE_filedir->text(); if(fileDir.isEmpty()) { int ret = QMessageBox::question(this,tr("对话框"),tr("路径为空,是否先选择文件 "), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape); if(ret == QMessageBox::Yes) { on_PB_selectfile_clicked(); } else { return; } } if(fileDir.isEmpty()) { return; } QString err =createxml(); if(err.contains("出错")) { QMessageBox::warning(this,tr("警告对话框"),err+" "); return; } QFile filetxt(filetxtdir); if(!filetxt.open(QIODevice::WriteOnly|QIODevice::Text)) { QMessageBox::warning(this,tr("警告对话框"),tr("txt文件打开失败 ")); return; } QTextStream outtxt(&filetxt); outtxt.setCodec("GB18030"); outtxt << createtxt() ; filetxt.close(); QFile filecfg(filecfgdir); if(!filecfg.open(QIODevice::WriteOnly|QIODevice::Text)) { QMessageBox::warning(this,tr("警告对话框"),tr("cfg文件打开失败 ")); return; } QTextStream outcfg(&filecfg); outcfg.setCodec("GB18030"); outcfg << createcfg() ; filecfg.close(); // QMessageBox::information(this,tr("提示对话框"),tr("已完成 ")); int ret = QMessageBox::question(this,tr("对话框"),tr("已完成,是否打开文件目录 "), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape); if(ret == QMessageBox::Yes) { QString tmpDir = fileDir; tmpDir.remove(tmpDir.split("/").last()); QDesktopServices::openUrl(QUrl::fromLocalFile(tmpDir)); } } void Widget::on_pbintro_clicked() { diaintro->exec(); }
#include "../include/Tool.h" void CAE::Tool::SetAsset(std::shared_ptr <AnimationAsset> asset) { this->asset = asset; assetUpdated(); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. ** It may not be distributed under any circumstances. */ #ifndef IMAGEDECODERJPG_H #define IMAGEDECODERJPG_H #include "modules/img/image.h" #ifdef USE_JAYPEG #include "modules/jaypeg/jayimage.h" #include "modules/jaypeg/jaydecoder.h" class ImageDecoderJpg : public ImageDecoder, public JayImage { public: ImageDecoderJpg(); ~ImageDecoderJpg(); virtual OP_STATUS DecodeData(const BYTE* data, INT32 numBytes, BOOL more, int& resendBytes, BOOL load_all = FALSE); virtual void SetImageDecoderListener(ImageDecoderListener* imageDecoderListener); int init(int width, int height, int numComponents, BOOL progressive); void scanlineReady(int scanline, const unsigned char *imagedata); #ifdef IMAGE_METADATA_SUPPORT void exifDataFound(unsigned int exif, const char* data); #endif // IMAGE_METADATA_SUPPORT #ifdef EMBEDDED_ICC_SUPPORT void iccDataFound(const UINT8* data, unsigned datalen); #endif // EMBEDDED_ICC_SUPPORT private: ImageDecoderListener* m_imageDecoderListener; JayDecoder *decoder; UINT32 width, height; UINT8 components; BOOL progressive; BOOL startFrame; UINT32 *linedata; }; #endif // USE_JAYPEG #ifdef USE_SYSTEM_JPEG extern "C" { #define XMD_H XMD_H #include <jerror.h> #include <jpeglib.h> #undef XMD_H } typedef struct { struct jpeg_source_mgr pub; JOCTET* buffer; int buf_len; BOOL more; long skip_len; } jpg_img_src_mgr; enum JPEG_ERROR { JPEGERR_NOERROR, // everything is allright JPEGERR_HEADER, // not a jpeg or a corrupted image JPEGERR_OUT_OF_MEMORY, // out of memory JPEGERR_DECOMPRESS // something went wrong during decompress }; class ImageDecoderJpg : public ImageDecoder { public: enum DCT_METHOD { DCT_INTEGER, DCT_FAST_INTEGER, DCT_FLOAT}; enum DITHERING_MODE { DITHERING_NONE, DITHERING_FLOYD_STEINBERG, DITHERING_ORDERED}; ImageDecoderJpg(BOOL progressive, BOOL smooth, BOOL one_pass, DCT_METHOD dct_method, DITHERING_MODE dithering_mode); ~ImageDecoderJpg(); virtual OP_STATUS DecodeData(const BYTE* data, INT32 numBytes, BOOL more, int& resendBytes, BOOL load_all = FALSE); virtual void SetImageDecoderListener(ImageDecoderListener* imageDecoderListener); public: ImageDecoderListener* m_imageDecoderListener; //Preferences BOOL progressive; BOOL smooth; BOOL one_pass; DCT_METHOD dct_method; DITHERING_MODE dithering_mode; //Misc stuff, used by the decoder BOOL initialized; BOOL finished; BOOL header_loaded; BOOL want_indexed; BOOL quantize; unsigned char ** colormap; OP_STATUS abort_status; BOOL is_progressive; BOOL decompress_started; int bits_per_pixel; int start_scan; unsigned char* scratch_buffer; BOOL reading_data; BOOL need_start; int current_scanline; unsigned char* bitmap_array; //Temporary data for a line used by the jpeglib unsigned char* bitmap_lineRGBA; //Temporary data for a row of RGBA struct jpeg_decompress_struct cinfo; jpeg_error_mgr jerr_pub; jpg_img_src_mgr jsrc; UINT32 width, height; private: int GetNrOfBits(UINT32 nr); BOOL IsSizeTooLarge(UINT32 width, UINT32 height); }; #endif // USE_SYSTEM_JPEG #endif // IMAGEDECODERJPG_H
// Created on: 1998-06-17 // Created by: data exchange team // Copyright (c) 1998-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ShapeFix_Edge_HeaderFile #define _ShapeFix_Edge_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <Standard_Transient.hxx> #include <ShapeExtend_Status.hxx> class ShapeConstruct_ProjectCurveOnSurface; class TopoDS_Edge; class TopoDS_Face; class Geom_Surface; class TopLoc_Location; class ShapeAnalysis_Surface; class ShapeBuild_ReShape; // resolve name collisions with X11 headers #ifdef Status #undef Status #endif class ShapeFix_Edge; DEFINE_STANDARD_HANDLE(ShapeFix_Edge, Standard_Transient) //! Fixing invalid edge. //! Geometrical and/or topological inconsistency: //! - no 3d curve or pcurve, //! - mismatching orientation of 3d curve and pcurve, //! - incorrect SameParameter flag (curve deviation is greater than //! edge tolerance), //! - not adjacent curves (3d or pcurve) to the vertices. class ShapeFix_Edge : public Standard_Transient { public: //! Empty constructor Standard_EXPORT ShapeFix_Edge(); //! Returns the projector used for recomputing missing pcurves //! Can be used for adjusting parameters of projector Standard_EXPORT Handle(ShapeConstruct_ProjectCurveOnSurface) Projector(); Standard_EXPORT Standard_Boolean FixRemovePCurve (const TopoDS_Edge& edge, const TopoDS_Face& face); //! Removes the pcurve(s) of the edge if it does not match the //! vertices //! Check is done //! Use : It is to be called when pcurve of an edge can be wrong //! (e.g., after import from IGES) //! Returns: True, if does not match, removed (status DONE) //! False, (status OK) if matches or (status FAIL) if no pcurve, //! nothing done Standard_EXPORT Standard_Boolean FixRemovePCurve (const TopoDS_Edge& edge, const Handle(Geom_Surface)& surface, const TopLoc_Location& location); //! Removes 3d curve of the edge if it does not match the vertices //! Returns: True, if does not match, removed (status DONE) //! False, (status OK) if matches or (status FAIL) if no 3d curve, //! nothing done Standard_EXPORT Standard_Boolean FixRemoveCurve3d (const TopoDS_Edge& edge); //! See method below for information Standard_EXPORT Standard_Boolean FixAddPCurve (const TopoDS_Edge& edge, const TopoDS_Face& face, const Standard_Boolean isSeam, const Standard_Real prec = 0.0); //! See method below for information Standard_EXPORT Standard_Boolean FixAddPCurve (const TopoDS_Edge& edge, const Handle(Geom_Surface)& surface, const TopLoc_Location& location, const Standard_Boolean isSeam, const Standard_Real prec = 0.0); //! See method below for information Standard_EXPORT Standard_Boolean FixAddPCurve (const TopoDS_Edge& edge, const TopoDS_Face& face, const Standard_Boolean isSeam, const Handle(ShapeAnalysis_Surface)& surfana, const Standard_Real prec = 0.0); //! Adds pcurve(s) of the edge if missing (by projecting 3d curve) //! Parameter isSeam indicates if the edge is a seam. //! The parameter <prec> defines the precision for calculations. //! If it is 0 (default), the tolerance of the edge is taken. //! Remark : This method is rather for internal use since it accepts parameter //! <surfana> for optimization of computations //! Use : It is to be called after FixRemovePCurve (if removed) or in any //! case when edge can have no pcurve //! Returns: True if pcurve was added, else False //! Status : //! OK : Pcurve exists //! FAIL1: No 3d curve //! FAIL2: fail during projecting //! DONE1: Pcurve was added //! DONE2: specific case of pcurve going through degenerated point on //! sphere encountered during projection (see class //! ShapeConstruct_ProjectCurveOnSurface for more info) Standard_EXPORT Standard_Boolean FixAddPCurve (const TopoDS_Edge& edge, const Handle(Geom_Surface)& surface, const TopLoc_Location& location, const Standard_Boolean isSeam, const Handle(ShapeAnalysis_Surface)& surfana, const Standard_Real prec = 0.0); //! Tries to build 3d curve of the edge if missing //! Use : It is to be called after FixRemoveCurve3d (if removed) or in any //! case when edge can have no 3d curve //! Returns: True if 3d curve was added, else False //! Status : //! OK : 3d curve exists //! FAIL1: BRepLib::BuildCurve3d() has failed //! DONE1: 3d curve was added Standard_EXPORT Standard_Boolean FixAddCurve3d (const TopoDS_Edge& edge); Standard_EXPORT Standard_Boolean FixVertexTolerance (const TopoDS_Edge& edge, const TopoDS_Face& face); //! Increases the tolerances of the edge vertices to comprise //! the ends of 3d curve and pcurve on the given face //! (first method) or all pcurves stored in an edge (second one) //! Returns: True, if tolerances have been increased, otherwise False //! Status: //! OK : the original tolerances have not been changed //! DONE1: the tolerance of first vertex has been increased //! DONE2: the tolerance of last vertex has been increased Standard_EXPORT Standard_Boolean FixVertexTolerance (const TopoDS_Edge& edge); Standard_EXPORT Standard_Boolean FixReversed2d (const TopoDS_Edge& edge, const TopoDS_Face& face); //! Fixes edge if pcurve is directed opposite to 3d curve //! Check is done by call to the function //! ShapeAnalysis_Edge::CheckCurve3dWithPCurve() //! Warning: For seam edge this method will check and fix the pcurve in only //! one direction. Hence, it should be called twice for seam edge: //! once with edge orientation FORWARD and once with REVERSED. //! Returns: False if nothing done, True if reversed (status DONE) //! Status: OK - pcurve OK, nothing done //! FAIL1 - no pcurve //! FAIL2 - no 3d curve //! DONE1 - pcurve was reversed Standard_EXPORT Standard_Boolean FixReversed2d (const TopoDS_Edge& edge, const Handle(Geom_Surface)& surface, const TopLoc_Location& location); //! Tries to make edge SameParameter and sets corresponding //! tolerance and SameParameter flag. //! First, it makes edge same range if SameRange flag is not set. //! //! If flag SameParameter is set, this method calls the //! function ShapeAnalysis_Edge::CheckSameParameter() that //! calculates the maximal deviation of pcurves of the edge from //! its 3d curve. If deviation > tolerance, the tolerance of edge //! is increased to a value of deviation. If deviation < tolerance //! nothing happens. //! //! If flag SameParameter is not set, this method chooses the best //! variant (one that has minimal tolerance), either //! a. only after computing deviation (as above) or //! b. after calling standard procedure BRepLib::SameParameter //! and computing deviation (as above). If <tolerance> > 0, it is //! used as parameter for BRepLib::SameParameter, otherwise, //! tolerance of the edge is used. //! //! Use : Is to be called after all pcurves and 3d curve of the edge are //! correctly computed //! Remark : SameParameter flag is always set to True after this method //! Returns: True, if something done, else False //! Status : OK - edge was initially SameParameter, nothing is done //! FAIL1 - computation of deviation of pcurves from 3d curve has failed //! FAIL2 - BRepLib::SameParameter() has failed //! DONE1 - tolerance of the edge was increased //! DONE2 - flag SameParameter was set to True (only if //! BRepLib::SameParameter() did not set it) //! DONE3 - edge was modified by BRepLib::SameParameter() to SameParameter //! DONE4 - not used anymore //! DONE5 - if the edge resulting from BRepLib has been chosen, i.e. variant b. above //! (only for edges with not set SameParameter) Standard_EXPORT Standard_Boolean FixSameParameter (const TopoDS_Edge& edge, const Standard_Real tolerance = 0.0); //! Tries to make edge SameParameter and sets corresponding //! tolerance and SameParameter flag. //! First, it makes edge same range if SameRange flag is not set. //! //! If flag SameParameter is set, this method calls the //! function ShapeAnalysis_Edge::CheckSameParameter() that //! calculates the maximal deviation of pcurves of the edge from //! its 3d curve. If deviation > tolerance, the tolerance of edge //! is increased to a value of deviation. If deviation < tolerance //! nothing happens. //! //! If flag SameParameter is not set, this method chooses the best //! variant (one that has minimal tolerance), either //! a. only after computing deviation (as above) or //! b. after calling standard procedure BRepLib::SameParameter //! and computing deviation (as above). If <tolerance> > 0, it is //! used as parameter for BRepLib::SameParameter, otherwise, //! tolerance of the edge is used. //! //! Use : Is to be called after all pcurves and 3d curve of the edge are //! correctly computed //! Remark : SameParameter flag is always set to True after this method //! Returns: True, if something done, else False //! Status : OK - edge was initially SameParameter, nothing is done //! FAIL1 - computation of deviation of pcurves from 3d curve has failed //! FAIL2 - BRepLib::SameParameter() has failed //! DONE1 - tolerance of the edge was increased //! DONE2 - flag SameParameter was set to True (only if //! BRepLib::SameParameter() did not set it) //! DONE3 - edge was modified by BRepLib::SameParameter() to SameParameter //! DONE4 - not used anymore //! DONE5 - if the edge resulting from BRepLib has been chosen, i.e. variant b. above //! (only for edges with not set SameParameter) Standard_EXPORT Standard_Boolean FixSameParameter (const TopoDS_Edge& edge, const TopoDS_Face& face, const Standard_Real tolerance = 0.0); //! Returns the status (in the form of True/False) of last Fix Standard_EXPORT Standard_Boolean Status (const ShapeExtend_Status status) const; //! Sets context Standard_EXPORT void SetContext (const Handle(ShapeBuild_ReShape)& context); //! Returns context Standard_EXPORT Handle(ShapeBuild_ReShape) Context() const; DEFINE_STANDARD_RTTIEXT(ShapeFix_Edge,Standard_Transient) protected: Handle(ShapeBuild_ReShape) myContext; Standard_Integer myStatus; Handle(ShapeConstruct_ProjectCurveOnSurface) myProjector; private: }; #endif // _ShapeFix_Edge_HeaderFile
// Copyright (c) 2019, tlblanc <tlblanc1490 at gmail dot com> #include "status/status.hpp" extern Status ConfigLineNoValue; extern Status ConfigNotFoundKey; extern Status ConfigParseValue;
//********************************************************************************* // Universidad de Costa Rica // Estructuras de Computadores Digitales II // Tarea 2: Paralelizacion de Clustering Data Mining // I Ciclo 2017 // // Functions.h // // Prof: Francisco Rivera // Authors: Pablo Avila B30724 // Guido Armas B30647 //********************************************************************************* #include <string> #include <fstream> #include <iostream> using namespace std; //Obtenido de http://www.columbia.edu/~vjd1/Solar%20Spectrum%20Ex.html //Wavelength de los elementos conocidos #define Oxygen_WL 723.05 #define Hydro_a_WL 656.30 #define Sodium_WL 589.33 #define Iron_WL 527.00 #define Hydro_b_WL 486.10 #define Calcium_WL 393.40 //Tolerancia de wavelength de los elementos conocidos #define Oxygen_TL 51.55 #define Hydro_a_TL 33.35 #define Sodium_TL 31.30 #define Iron_TL 21.50 #define Hydro_b_TL 19.40 #define Calcium_TL 36.65 #ifndef FUNCTIONS_H #define FUNCTIONS_H class Functions{ public: Functions(); ~Functions(); // Esta funcion devuelve un int con la cantidad de lineas en un archivo // @Paramentro file: Archivo el cual se le cuentan las lineas int getFileLines(string &file); // La funcion getfileData devuelve un arreglo de floats, donde la primer posicion // es la longitud de onda obtenida y el segundo se refiere a la irradianza de esa // longitud de onda, datos obtenidos con espectroscopia de absorsion. // @Parametro file: archivo del cual se extrae la informacion. // @Parametro size: Numero de lineas del archivo a leer. float** getFileData(string &file, int &size); // La funcion getElements devuelve un arreglo de strings, compuesto por los // nombres de los elementos encontrados al procesar los datos de Wavelength // @Parametro dataArray: lista de wavelengths a procesar // @Parametro size: Numero de lineas del archivo a leer // string* getElement(float** dataArray, int &size); }; #endif
/****************************************************************************** * $Id$ * * Project: libLAS - http://liblas.org - A BSD library for LAS format data. * Purpose: LAS Schema implementation for C++ libLAS * Author: Howard Butler, hobu.inc@gmail.com * ****************************************************************************** * Copyright (c) 2010, Howard Butler * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided * with the distribution. * * Neither the name of the Martin Isenburg or Iowa Department * of Natural Resources nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #ifndef LIBLAS_SCHEMA_HPP_INCLUDED #define LIBLAS_SCHEMA_HPP_INCLUDED #include <liblas/version.hpp> #include <liblas/external/property_tree/ptree.hpp> #include <liblas/variablerecord.hpp> #include <liblas/dimension.hpp> #include <liblas/export.hpp> // boost #include <boost/any.hpp> #include <boost/shared_ptr.hpp> #include <boost/foreach.hpp> #include <boost/array.hpp> #include <boost/optional.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index/mem_fun.hpp> #include <boost/multi_index/random_access_index.hpp> // std #include <iosfwd> #include <limits> #include <string> #include <vector> #include <algorithm> #include <boost/unordered_map.hpp> namespace liblas { typedef std::vector<Dimension> DimensionArray; struct name{}; struct position{}; struct index{}; typedef boost::multi_index::multi_index_container< Dimension, boost::multi_index::indexed_by< // sort by Dimension::operator< boost::multi_index::ordered_unique<boost::multi_index::tag<position>, boost::multi_index::identity<Dimension> >, // Random access boost::multi_index::random_access<boost::multi_index::tag<index> >, // sort by less<string> on GetName boost::multi_index::hashed_unique<boost::multi_index::tag<name>, boost::multi_index::const_mem_fun<Dimension,std::string const&,&Dimension::GetName> > > > IndexMap; typedef IndexMap::index<name>::type index_by_name; typedef IndexMap::index<position>::type index_by_position; typedef IndexMap::index<index>::type index_by_index; /// Schema definition class LAS_DLL Schema { public: // Schema(); Schema(PointFormatName data_format_id); Schema(std::vector<VariableRecord> const& vlrs); Schema& operator=(Schema const& rhs); bool operator==(const Schema& other) const; bool operator!=(const Schema& other) const { return !(*this == other); } Schema(Schema const& other); ~Schema() {} /// Fetch byte size std::size_t GetByteSize() const; std::size_t GetBitSize() const; void CalculateSizes(); /// Get the base size (only accounting for Time, Color, etc ) std::size_t GetBaseByteSize() const; PointFormatName GetDataFormatId() const { return m_data_format_id; } void SetDataFormatId(PointFormatName const& value); void AddDimension(Dimension const& dim); boost::optional< Dimension const& > GetDimension(std::string const& n) const; boost::optional< Dimension const& > GetDimension(index_by_index::size_type t) const; // DimensionPtr GetDimension(std::size_t index) const; void RemoveDimension(Dimension const& dim); void SetDimension(Dimension const& dim); std::vector<std::string> GetDimensionNames() const; IndexMap const& GetDimensions() const { return m_index; } liblas::property_tree::ptree GetPTree() const; uint16_t GetSchemaVersion() const { return m_schemaversion; } void SetSchemaVersion(uint16_t v) { m_schemaversion = v; } bool IsCustom() const; VariableRecord GetVLR() const; protected: PointFormatName m_data_format_id; uint32_t m_nextpos; std::size_t m_bit_size; std::size_t m_base_bit_size; uint16_t m_schemaversion; private: IndexMap m_index; void add_record0_dimensions(); void add_time(); void add_color(); void update_required_dimensions(PointFormatName data_format_id); bool IsSchemaVLR(VariableRecord const& vlr); liblas::property_tree::ptree LoadPTree(VariableRecord const& v); IndexMap LoadDimensions(liblas::property_tree::ptree tree); }; bool inline sort_dimensions(Dimension i, Dimension j) { return i < j; } LAS_DLL std::ostream& operator<<(std::ostream& os, liblas::Schema const&); } // namespace liblas #endif // LIBLAS_SCHEMA_HPP_INCLUDED
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 100 #define INF 0x3f3f3f3f #define DEVIATION 0.00000005 typedef long long LL; int Price(int cwh){ int price = 0; price += min(max(0, cwh*2), 2*100); cwh -= 100; price += min(max(0, cwh*3), 3*(10000-100)); cwh -= (10000-100); price += min(max(0, cwh*5), 5*(1000000-10000)); cwh -= (1000000-10000); price += max(0, cwh*7); return price; } int Cwh(int price){ int cwh = 0; cwh += min(max(0, price/2), 100); price -= 2*100; cwh += min(max(0, price/3), (10000-100)); price -= 3*(10000-100); cwh += min(max(0, price/5), (1000000-10000)); price -= 5*(1000000-10000); cwh += max(0, price/7); return cwh; } int main(int argc, char const *argv[]) { int A,B; while( ~scanf("%d %d", &A, &B) && (A|B) ){ int total = Cwh(A); int L = 0, R = total; int ans = 0; while( L < R ){ int M = (L+R)/2; int diff = Price(total-M)-Price(M); if( diff == B ){ ans = M; break; } if( diff < B ) R = M; else L = M; } printf("%d\n", Price(ans)); } return 0; }
#include <iostream> #include "SceneObject.hh" #include "PlaneObject.hh" #include "SphereObject.hh" #include "Vector3F.hh" #include "RGBColor.hh" #include "Light.hh" #include "Camera.hh" #include "Scene.hh" #define IMGSIZE 512 int main(void){ // Configure the plane Vector3F planeSurfaceNormal(0, 1, 0); RGBColor planeColor(0.5, 0, 0.5); PlaneObject* plane = new PlaneObject(planeSurfaceNormal, 0); plane->set_surfaceColor(planeColor); // Configure the objects (three spheres - red, green and blue) /* float sphereRadius = 0.5; Vector3F rSphereCenter(-1.2, 0.5, 0); RGBColor rSphereColor(1, 0, 0); SphereObject* rSphere = new SphereObject(rSphereCenter, sphereRadius); rSphere->set_surfaceColor(rSphereColor); Vector3F gSphereCenter(0, 0.5, 0); RGBColor gSphereColor(0, 1, 0); SphereObject gSphere(gSphereCenter, sphereRadius); gSphere.set_surfaceColor(gSphereColor); Vector3F bSphereCenter(1.2, 0.5, 0); RGBColor bSphereColor(0, 0, 1); SphereObject bSphere(bSphereCenter, sphereRadius); bSphere.set_surfaceColor(bSphereColor); */ // Configure the light sources (two lights - a and b) Vector3F lightAPos(-10, 10, 5); RGBColor lightAColor(0.8, 0.8, 0.8); Light* lightA = new Light(lightAPos, lightAColor); Vector3F lightBPos(5, 3, 5); RGBColor lightBColor(0.3, 0.3, 0.3); Light* lightB = new Light(lightBPos, lightBColor); // Configure the camera Vector3F cameraPos(-1.5, 1, 3); Vector3F cameraLookAt(-0.3, 0.5, 0); Vector3F cameraUp(0, 1, 0); Camera camera(cameraPos, cameraLookAt, cameraUp); // Configure the scene Scene scene; scene.addSceneObject(plane); /* scene.addSceneObject(rSphere); scene.addSceneObject(&gSphere); scene.addSceneObject(&bSphere); */ scene.addLight(lightA); scene.addLight(lightB); // Render! scene.render(camera, IMGSIZE, std::cout); return 0; } // To compile // g++ -Wall -Werror -o rt rt.cc SceneObject.cc PlaneObject.cc SphereObject.cc Vector3F.cc RGBColor.cc Light.cc Camera.cc Scene.cc Ray.cc
#include "Publisher.hpp" #include <glog/logging.h> void Publisher::publish(std::string topic, std::string msg) { Protocol pro("pub", topic, msg); Message pub_msg = pro.serialization(); conn_->sendmsg(pub_msg); topic_.push_back(topic); LOG(INFO) << "A message of topic" << topic <<" is publishing!"; } void Publisher::unpublish(std::string topic) { Protocol pro("unpub", topic, ""); Message pub_msg = pro.serialization(); conn_->sendmsg(pub_msg); //todo delete topic //topic_.move(topic); LOG(INFO) << "A topic " << topic << "will be unpublished!"; }
#pragma once enum KeyboardEve { enEnter = 0x0D, enBackSpace = 0x08, enDelete = 0x2E, }; namespace Keyboard { //入力されたキーに対応するcharを返す。 char GetKeyChar(); //指定したキーが入力されているか。 //arg: // ke: キーの指定 bool isTrriger(KeyboardEve ke); extern int Key; }
#include "mumble_channelcounter.h" MumbleChannelThreasholdProvider::MumbleChannelThreasholdProvider(MumbleData * data, std::string name, int thres) { _data = data; _prov = data; _name = name; _thres = thres; channelId = -1; } MumbleChannelThreasholdProvider::MumbleChannelThreasholdProvider(MumbleData * data, int channel, int thres) { _data = data; _prov = data; _name = ""; _thres = thres; channelId = channel; } MumbleChannelThreasholdProvider::MumbleChannelThreasholdProvider(const MumbleData * data, EventProvider * prov, std::string name, int thres) { _data = data; _prov = prov; _name = name; _thres = thres; channelId = -1; } MumbleChannelThreasholdProvider::MumbleChannelThreasholdProvider(const MumbleData * data, EventProvider * prov, int channel, int thres) { _data = data; _prov = prov; _name = ""; _thres = thres; channelId = channel; } MumbleChannelThreasholdProvider::~MumbleChannelThreasholdProvider() { _prov->remove_Listener(this); } bool MumbleChannelThreasholdProvider::connect() { _prov->add_Listener(this,ChannelCount); if (channelId < 0) { channelId = _data->findChannelName(_name.c_str()); } return channelId >= 0; } void MumbleChannelThreasholdProvider::notify(int msg) { MumbleChannel c = _data->getChannel(channelId); if(c.id == -1) return; //channel not found if(c.userCount >= _thres) { update(MumbleChannelThreasholdProvider::OVEREQU); } else { update(MumbleChannelThreasholdProvider::UNDER); } }
/*input 2 50 2053 3 6 2 3 */ #include <iostream> #include <vector> #include <cstdio> #include <cmath> #include <cstring> #include <string> #include <cassert> #include <algorithm> #include <cstdlib> #include <numeric> #include <utility> #include <tuple> #include <climits> #include <fstream> #include <bitset> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <stack> #include <queue> #include <random> #include <chrono> #include <ios> #include <iomanip> #include <functional> #include <array> using namespace std; #define FOR(i, a, b) for (int i = a; i <= b; ++i) #define FORA(i, a) for (auto &i : a) #define FORB(i, a, b) for (int i = a; i >= b; --i) #define SZ(a) ((int) a.size()) #define ALL(a) begin(a), end(a) typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vl; #define fi first #define se second // start of code struct MaximumMatching { int N; vector<int> matchX, matchY, prv, root; vector<vector<int>> adj; void init(int _N) { N = _N; adj.assign(N, vector<int>(0)); } void addEdge(int x, int y) { adj[x].push_back(y); } void solve() { matchX.assign(N, -1); matchY.assign(N, -1); // greedy matching // FOR(x, 0, N - 1) { // FORA(y, adj[x]) { // if (!~matchY[y]) { // matchX[x] = y, matchY[y] = x; // break; // } // } // } bool run = true; while (run) { prv.assign(N, -1); root.assign(N, -1); run = false; queue<int> qu; FOR(x, 0, N - 1) if (!~matchX[x]) root[x] = x, qu.push(x); while (!qu.empty()) { int x = qu.front(); qu.pop(); if (~matchX[root[x]]) continue; for (int y : adj[x]) { if (~matchY[y]) { int nxt = matchY[y]; if (!~root[nxt]) { prv[y] = x; root[nxt] = root[x]; qu.push(nxt); } } else { run = true; for (int i = matchX[x]; ~i; swap(i, matchX[matchY[i] = prv[i]])); matchX[x] = y, matchY[y] = x; break; } } } } } int get(int x) { return matchX[x]; } } matching; void check(vector<vector<int>> A, int N, int K) { assert(SZ(A) == N && SZ(A[0]) == N); FOR(i, 0, N - 1) K -= A[i][i]; assert(K == 0); FOR(i, 0, N - 1) { vi cnt(N, 0); FOR(j, 0, N - 1) cnt[A[i][j] - 1] = 1; assert(count(ALL(cnt), 1) == N); } FOR(i, 0, N - 1) { vi cnt(N, 0); FOR(j, 0, N - 1) cnt[A[j][i] - 1] = 1; assert(count(ALL(cnt), 1) == N); } } vector<vector<int>> solve(int N, int K) { vector<vector<int>> A(N, vector<int>(N, 0)); if (K % N == 0) { int X = K / N; FOR(i, 0, N - 1) FOR(j, 0, N - 1) { A[i][j] = (X + i - j + N - 1) % N + 1; } return A; } int X = -1, Y, Z; FOR(x, 1, N) FOR(y, 1, N) { int z = K - x * (N - 2) - y; if (1 <= z && z <= N && x != y && x != z) { X = x, Y = y, Z = z; } } assert(~X); FOR(i, 2, N - 1) A[i][i] = X; A[0][0] = Y, A[1][1] = Z, A[0][1] = A[1][0] = X; auto fillA = [&](int x) { matching.init(N); vector<int> usedRow(N, 0), usedCol(N, 0); FOR(i, 0, N - 1) FOR(j, 0, N - 1) if (A[i][j] == x) usedRow[i] = usedCol[j] = 1; FOR(i, 0, N - 1) FOR(j, 0, N - 1) if (!usedRow[i] && !usedCol[j] && !A[i][j]) { matching.addEdge(i, j); } matching.solve(); FOR(i, 0, N - 1) if (!usedRow[i]) { // cout << i << flush; A[i][matching.get(i)] = x; } }; fillA(Y); // FOR(i, 0, N - 1) FOR(j, 0, N - 1) cout << A[i][j] << " \n"[j == N - 1]; cout << flush; if (Y != Z) fillA(Z); FOR(i, 1, N) if (i != X && i != Y && i != Z) fillA(i); // FOR(i, 0, N - 1) FOR(j, 0, N - 1) cout << A[i][j] << " \n"[j == N - 1]; cout << flush; // check(A, N, K); return A; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); // solve(5, 9); // FOR(N, 2, 50) { // cout << "try " << N << endl; // FOR(K, N, N * N) { // cout << "cur " << K << endl; // if (K != N + 1 && K != N * N - 1 && (N != 3 || K % N == 0)) solve(N, K); // } // } // return 0; int T; cin >> T; FOR(t, 1, T) { int N, K; cin >> N >> K; cout << "Case #" << t << ": "; if (K == N + 1 || K == N * N - 1 || (N == 3 && K % N != 0)) cout << "IMPOSSIBLE\n"; else { cout << "POSSIBLE\n"; auto ans = solve(N, K); FOR(i, 0, N - 1) { FOR(j, 0, N - 1) { cout << ans[i][j] << ' '; } cout << '\n'; } } } return 0; }
/* This file is part of SMonitor. Copyright 2015~2016 by: rayx email rayx.cn@gmail.com SMonitor 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. SMonitor 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ #include "stdafx.h" #include "databasemanager.h" #include "NetClass.h" #include "CSoftUpgradeWidget.h" #include <QFile> #include <QSqlQuery> #include <QStringList> #include <QVariant> #include <QtCore/QCoreApplication> #include <QMessageBox> #include <QDir> #include <QUuid> #define RELEASESQL(x) {if(NULL != (x)){ delete (x); (x) = NULL; }} DatabaseManager* DatabaseManager::m_Instance = NULL; DatabaseManager* DatabaseManager::Instance() { if (NULL == m_Instance) { m_Instance = new DatabaseManager(); Q_ASSERT(m_Instance); } return m_Instance; } DatabaseManager::DatabaseManager() : QObject(qApp) , m_strDatabasePath("") , m_bFull(false) { m_pSqlDatabase = NULL; } DatabaseManager::~DatabaseManager() { CloseDatabase(); } //加载数据库文件 //bCreateIfInExist - true 如果数据库不存在会自动创建 - false 数据库不存在,会创建失败,返回false bool DatabaseManager::LoadDatabase(const QString& strFilePath, bool bCreateIfInExist/* = true*/) { QString dirPath = QFileInfo(strFilePath).absolutePath(); QDir dir; if(!dir.mkpath(dirPath)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库目录[%1]创建失败,请确认目标磁盘是否空间已满").arg(dirPath), QString::fromLocal8Bit("确定")); return false; } m_bFull = false; QMutexLocker locker(&m_DateLock); RELEASESQL(m_pSqlDatabase); if(!bCreateIfInExist && !QFile::exists(strFilePath)) return false; QSqlDatabase tmp = QSqlDatabase::addDatabase("QSQLITE"); if(!tmp.isValid()) {//打开SQLITE驱动失败 QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("打开SQLITE驱动失败, 请确认驱动是否已安装"), QString::fromLocal8Bit("确定")); return false; } tmp.setDatabaseName(strFilePath); if(!tmp.isValid()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库打开失败,错误信息:[%1]").arg(tmp.lastError().text()), QString::fromLocal8Bit("确定")); return false; } m_pSqlDatabase = new QSqlDatabase(tmp); if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("内存不足,数据库打开失败"), QString::fromLocal8Bit("确定")); return false; } if(!m_pSqlDatabase->open()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库打开失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库打开失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } //创建User表 QSqlQuery sql(*m_pSqlDatabase); if(!sql.exec("CREATE TABLE IF NOT EXISTS UserInfo(name char(522), password char(512));")) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("打开UserInfo表失败,错误信息:[%1]").arg(sql.lastError().text()), QString::fromLocal8Bit("确定")); return false; } //创建ClientInfo表 if(!sql.exec("CREATE TABLE IF NOT EXISTS ClientInfo(id char(256), version char(256));")) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("打开ClientInfo表失败,错误信息:[%1]").arg(sql.lastError().text()), QString::fromLocal8Bit("确定")); return false; } //创建Software表 if(!sql.exec("CREATE TABLE IF NOT EXISTS Software(name char(256), version char(256), url char(512), brand char(512), category char(256) \ , location char(256), mainExe char(512), installNum char(256), uninstalledNum char(256), packType char(32));")) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("打开Software表失败,错误信息:[%1]").arg(sql.lastError().text()), QString::fromLocal8Bit("确定")); return false; } //创建安装信息表 if(!sql.exec("CREATE TABLE IF NOT EXISTS LastInstallHitory(id char(256), name char(256), version char(256), datetime char(256));")) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("打开History表失败,错误信息:[%1]").arg(sql.lastError().text()), QString::fromLocal8Bit("确定")); return false; } //创建帮助信息表 if(!sql.exec("CREATE TABLE IF NOT EXISTS HelpInfo(title char(512), info char(1024));")) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("打开HelpInfo表失败,错误信息:[%1]").arg(sql.lastError().text()), QString::fromLocal8Bit("确定")); return false; } //创建门店数据表 if(!sql.exec("CREATE TABLE IF NOT EXISTS StatisticsInfo(regional char(512), unitnum char(256), unitname char(512), shopid char(256), shopname char(512), install char(256));")) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("打开StatisticsInfo表失败,错误信息:[%1]").arg(sql.lastError().text()), QString::fromLocal8Bit("确定")); return false; } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库打开失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } return true; } //检测用户名和密码是否存在 bool DatabaseManager::IsUserExist(const QString& strUserName, const QString& strPassword) { if(NULL == m_pSqlDatabase) return false; bool bOk = false; QString str = ""; QString strSql = QString::fromLocal8Bit("SELECT * FROM UserInfo WHERE name = '%1' AND password = '%2';").arg(strUserName).arg(strPassword); QSqlQuery query(strSql, *m_pSqlDatabase); if(query.next()) { return true; } return false; } //通过门店编号判断客户端是否存在 bool DatabaseManager::IsClientExist(const QString& clientId) { if(NULL == m_pSqlDatabase) return false; bool bOk = false; QString str = ""; QString strSql = QString::fromLocal8Bit("SELECT * FROM ClientInfo WHERE id = '%1';").arg(clientId); QSqlQuery query(strSql, *m_pSqlDatabase); if(query.next()) { return true; } return false; } //判断帮助信息是否存在 bool DatabaseManager::IsHelpInfoExist(const QString& title) { if(NULL == m_pSqlDatabase) return false; bool bOk = false; QString strSql = QString::fromLocal8Bit("SELECT * FROM HelpInfo WHERE title = '%1';").arg(title); QSqlQuery query(strSql, *m_pSqlDatabase); if(query.next()) { return true; } return false; } //读取帮助信息 bool DatabaseManager::ReadHelpInfos(HelpInfoMap& helpInfoMap) { helpInfoMap.clear(); if(NULL == m_pSqlDatabase) return false; //QString strSql = QString::fromLocal8Bit("SELECT * FROM Info WHERE pic_id = '%1' AND proj_id = '%2' ORDER BY rc_t_TextType, rc_t_TextNum;").arg(strID).arg(strProjID); QString strSql = QString::fromLocal8Bit("SELECT * FROM HelpInfo;"); QSqlQuery query(strSql, *m_pSqlDatabase); while(query.next()) { helpInfoMap.insert(query.value("title").toString(), query.value("info").toString()); } return helpInfoMap.count() != 0; } //保存帮助信息 bool DatabaseManager::SaveHelpInfos(const HelpInfoMap& helpInfoMap) { if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库未打开,无法保存"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = QString::fromLocal8Bit("DELETE FROM HelpInfo;"); QSqlQuery deleteQuery(*m_pSqlDatabase); if(!deleteQuery.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(deleteQuery.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } foreach(auto key, helpInfoMap.keys()) { QSqlQuery insertQuery(*m_pSqlDatabase); insertQuery.prepare("INSERT INTO HelpInfo (title, info) VALUES (:title, :info);"); insertQuery.bindValue(":title", key); insertQuery.bindValue(":info", helpInfoMap.value(key)); if(!insertQuery.exec()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(insertQuery.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } return true; } //获取门店软件安装结果 bool DatabaseManager::GetCrosslinkRunInstalledResult(const QString& strShopId, QString& strResult) { strResult = ""; if(NULL == m_pSqlDatabase) return false; QString strSql = QString::fromLocal8Bit("SELECT install FROM StatisticsInfo WHERE shopid = '%1';").arg(strShopId); QSqlQuery query(strSql, *m_pSqlDatabase); if(query.next()) { strResult = query.value("install").toString(); return true; } return false; } //读取门店数据 bool DatabaseManager::ReadShopInfoHash(QHash<int, QStringList>& data) { data.clear(); if(NULL == m_pSqlDatabase) return false; QString strSql = QString::fromLocal8Bit("SELECT * FROM StatisticsInfo;"); QSqlQuery query(strSql, *m_pSqlDatabase); int nIndex = 0; while(query.next()) { QStringList strValueList; strValueList << query.value("regional").toString(); strValueList << query.value("unitnum").toString(); strValueList << query.value("unitname").toString(); strValueList << query.value("shopid").toString(); strValueList << query.value("shopname").toString(); strValueList << query.value("install").toString(); data.insert(nIndex++, strValueList); } return true; } //判断软件是否存在 bool DatabaseManager::IsSoftwareExist(const QString& strSoftwatename) { if(NULL == m_pSqlDatabase) return false; QString strSql = QString::fromLocal8Bit("SELECT * FROM Software WHERE name = '%1';").arg(strSoftwatename); QSqlQuery query(strSql, *m_pSqlDatabase); if(query.next()) { return true; } return false; } //判断软件和版本是否一致 bool DatabaseManager::IsSoftwareExist(const QString& strSoftwareName, const QString& strVersion) { if(NULL == m_pSqlDatabase) return false; QString strSql = QString::fromLocal8Bit("SELECT * FROM Software WHERE name = '%1' AND version = '%2';").arg(strSoftwareName).arg(strVersion); QSqlQuery query(strSql, *m_pSqlDatabase); if(query.next()) { return true; } return false; } //判断软件安装通知信息是否存在 bool DatabaseManager::IsSoftInstallInfoExist(const QString& clientId, const QString& name, const QString& version) { if(NULL == m_pSqlDatabase) return false; QString strSql = QString::fromLocal8Bit("SELECT * FROM LastInstallHitory WHERE id = '%1' AND name = '%2' AND version = '%3';").arg(clientId).arg(name).arg(version); QSqlQuery query(strSql, *m_pSqlDatabase); if(query.next()) { return true; } return false; } //修改密码 bool DatabaseManager::ModifyPassword(const QString& strUserName, const QString& strPassword) { if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库未打开"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = QString::fromLocal8Bit("UPDATE UserInfo SET password = '%1' WHERE name = '%2';").arg(strPassword).arg(strUserName); QSqlQuery excete(*m_pSqlDatabase); if(!excete.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(excete.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } return true; } //添加用户 bool DatabaseManager::AddUser(const QString& strUserName, const QString& strPassword) { if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库未打开,无法保存"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = QString::fromLocal8Bit("DELETE FROM UserInfo WHERE name = '%1';").arg(strUserName); QSqlQuery deleteQuery(*m_pSqlDatabase); if(!deleteQuery.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(deleteQuery.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } QSqlQuery insertQuery(*m_pSqlDatabase); insertQuery.prepare("INSERT INTO UserInfo (name, password) VALUES (:name, :password);"); insertQuery.bindValue(":name", strUserName); insertQuery.bindValue(":password", strPassword); if(!insertQuery.exec()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(insertQuery.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } return true; } //添加客户端信息 bool DatabaseManager::AddClientInfo(const ClientInfo& clientInfo) { if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库未打开,无法保存"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = QString::fromLocal8Bit("DELETE FROM ClientInfo WHERE id = '%1';").arg(clientInfo.id); QSqlQuery deleteQuery(*m_pSqlDatabase); if(!deleteQuery.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(deleteQuery.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } QSqlQuery insertQuery(*m_pSqlDatabase); insertQuery.prepare("INSERT INTO ClientInfo (id, version) VALUES (:id, :version);"); insertQuery.bindValue(":id", clientInfo.id); insertQuery.bindValue(":version", clientInfo.version); if(!insertQuery.exec()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(insertQuery.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } //数据存储成功,更新主数据库 return true; } //添加软件信息 bool DatabaseManager::AddSoftwareInfo(const SoftwareInfo& softwareInfo) { if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库未打开,无法保存"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = QString::fromLocal8Bit("DELETE FROM Software WHERE name = '%1';").arg(softwareInfo.name); QSqlQuery deleteQuery(*m_pSqlDatabase); if(!deleteQuery.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(deleteQuery.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } QSqlQuery insertQuery(*m_pSqlDatabase); insertQuery.prepare("INSERT INTO Software (name, version, url, brand, category, location, mainExe, installNum, uninstalledNum, packType) \ VALUES (:name, :version, :url, :brand, :category, :location, :mainExe, :installNum, :uninstalledNum, :packType);"); insertQuery.bindValue(":name", softwareInfo.name); insertQuery.bindValue(":version", softwareInfo.version); insertQuery.bindValue(":url", softwareInfo.url); insertQuery.bindValue(":brand", softwareInfo.brand); insertQuery.bindValue(":category", softwareInfo.category); insertQuery.bindValue(":location", softwareInfo.location); insertQuery.bindValue(":mainExe", softwareInfo.mainExe); insertQuery.bindValue(":installNum", QString::fromLocal8Bit("%1").arg(softwareInfo.installNum)); insertQuery.bindValue(":uninstalledNum", QString::fromLocal8Bit("%1").arg(softwareInfo.uninstalledNum)); insertQuery.bindValue(":packType", QString::fromLocal8Bit("%1").arg(softwareInfo.packType)); if(!insertQuery.exec()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(insertQuery.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } //数据存储成功,更新主数据库 return true; } //保存软件信息 bool DatabaseManager::SaveSoftwareInfos(const SoftwareinfoVector& softwareInfoVector) { if(softwareInfoVector.count() == 0) return true; if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库未打开,无法保存"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = QString::fromLocal8Bit("DELETE FROM Software;"); QSqlQuery deleteQuery(*m_pSqlDatabase); if(!deleteQuery.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(deleteQuery.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } int nCount = softwareInfoVector.count(); for (int i = 0; i < nCount; i++) { const SoftwareInfo& softwareInfo = softwareInfoVector.at(i); QSqlQuery insertQuery(*m_pSqlDatabase); insertQuery.prepare("INSERT INTO Software (name, version, url, brand, category, location, mainExe, installNum, uninstalledNum, packType) \ VALUES (:name, :version, :url, :brand, :category, :location, :mainExe, :installNum, :uninstalledNum, :packType);"); insertQuery.bindValue(":name", softwareInfo.name); insertQuery.bindValue(":version", softwareInfo.version); insertQuery.bindValue(":url", softwareInfo.url); insertQuery.bindValue(":brand", softwareInfo.brand); insertQuery.bindValue(":category", softwareInfo.category); insertQuery.bindValue(":location", softwareInfo.location); insertQuery.bindValue(":mainExe", softwareInfo.mainExe); insertQuery.bindValue(":installNum", QString::fromLocal8Bit("%1").arg(softwareInfo.installNum)); insertQuery.bindValue(":uninstalledNum", QString::fromLocal8Bit("%1").arg(softwareInfo.uninstalledNum)); insertQuery.bindValue(":packType", QString::fromLocal8Bit("%1").arg(softwareInfo.packType)); if(!insertQuery.exec()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(insertQuery.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } return true; } //修改软件信息,不存在则为添加 通过packType来定义类型 0 - insert 1 - updatewithoutnum 2 - updateall 3 - remove bool DatabaseManager::UpdateSoftwareInfos(const SoftwareinfoVector& softwareInfoVector) { if(softwareInfoVector.count() == 0) return true; if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库未打开,无法保存"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = "select count(*) from clientinfo"; QSqlQuery query(strSql, *m_pSqlDatabase); int nClientNum = 0; if(query.next()) { nClientNum = query.value(0).toInt(); } int nCount = softwareInfoVector.count(); for (int i = 0; i < nCount; i++) { const SoftwareInfo& softwareInfo = softwareInfoVector.at(i); if(0 == softwareInfo.packType) {// insert QSqlQuery insertQuery(*m_pSqlDatabase); insertQuery.prepare("INSERT INTO Software (name, version, url, brand, category, location, mainExe, installNum, uninstalledNum, packType) \ VALUES (:name, :version, :url, :brand, :category, :location, :mainExe, :installNum, :uninstalledNum, :packType);"); insertQuery.bindValue(":name", softwareInfo.name); insertQuery.bindValue(":version", softwareInfo.version); insertQuery.bindValue(":url", softwareInfo.url); insertQuery.bindValue(":brand", softwareInfo.brand); insertQuery.bindValue(":category", softwareInfo.category); insertQuery.bindValue(":location", softwareInfo.location); insertQuery.bindValue(":mainExe", softwareInfo.mainExe); insertQuery.bindValue(":installNum", QString::fromLocal8Bit("%1").arg(softwareInfo.installNum)); insertQuery.bindValue(":uninstalledNum", QString::fromLocal8Bit("%1").arg(nClientNum)); insertQuery.bindValue(":packType", QString::fromLocal8Bit("%1").arg(softwareInfo.packType)); if(!insertQuery.exec()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(insertQuery.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } } else { QString strSql; if(1 == softwareInfo.packType) {//1 - updatewithoutnum strSql = QString::fromLocal8Bit("UPDATE Software SET version = '%1', url = '%2', brand = '%3', category = '%4', location = '%5', mainExe = '%6',\ packType = '%7' WHERE name = '%8';").arg(softwareInfo.version).arg(softwareInfo.url).arg(softwareInfo.brand) .arg(softwareInfo.category).arg(softwareInfo.location).arg(softwareInfo.mainExe).arg(softwareInfo.packType).arg(softwareInfo.name); } else if(2 == softwareInfo.packType) {//2 - updateall strSql = QString::fromLocal8Bit("UPDATE Software SET version = '%1', url = '%2', brand = '%3', category = '%4', location = '%5', mainExe = '%6',\ installNum = '%7', uninstalledNum = '%8', packType = '%9' WHERE name = '%10';").arg(softwareInfo.version).arg(softwareInfo.url).arg(softwareInfo.brand) .arg(softwareInfo.category).arg(softwareInfo.location).arg(softwareInfo.mainExe).arg(0).arg(nClientNum).arg(softwareInfo.packType).arg(softwareInfo.name); } else {//3 - remove strSql = QString::fromLocal8Bit("DELETE FROM Software WHERE name = '%1';").arg(softwareInfo.name); } QSqlQuery excete(*m_pSqlDatabase); if(!excete.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(excete.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } } } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } return true; } //更新客户信息 bool DatabaseManager::UpdateClientInfo(const ClientInfo& clientInfo) { if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库未打开"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = QString::fromLocal8Bit("UPDATE ClientInfo SET version = '%1' WHERE id = '%2';").arg(clientInfo.version).arg(clientInfo.id); QSqlQuery excete(*m_pSqlDatabase); if(!excete.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(excete.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } return true; } //更新软件信息 bool DatabaseManager::UpdateSoftwareInfo(const SoftwareInfo& softwareInfo) { if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("主数据库未打开"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = QString::fromLocal8Bit("UPDATE Software SET version = '%1', url = '%2', brand = '%3', category = '%4', location = '%5', mainExe = '%6'\ installNum = '%7', uninstalledNum = '%8', packType = '%9' WHERE name = '%10';").arg(softwareInfo.version).arg(softwareInfo.url).arg(softwareInfo.brand) .arg(softwareInfo.category).arg(softwareInfo.location).arg(softwareInfo.mainExe).arg(softwareInfo.installNum).arg(softwareInfo.uninstalledNum).arg(softwareInfo.packType).arg(softwareInfo.name); QSqlQuery excete(*m_pSqlDatabase); if(!excete.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(excete.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } return true; } //更新软件信息 bool DatabaseManager::UpdateSoftwareInfoWithOuInstallNum(const SoftwareInfo& softwareInfo) { if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("主数据库未打开"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = QString::fromLocal8Bit("UPDATE Software SET version = '%1', url = '%2', brand = '%3', category = '%4', location = '%5', mainExe = '%6'\ packType = '%7' WHERE name = '%8';").arg(softwareInfo.version).arg(softwareInfo.url).arg(softwareInfo.brand) .arg(softwareInfo.category).arg(softwareInfo.location).arg(softwareInfo.mainExe).arg(softwareInfo.packType).arg(softwareInfo.name); QSqlQuery excete(*m_pSqlDatabase); if(!excete.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(excete.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } return true; } //增加软件安装数 bool DatabaseManager::AddSoftwareInstallNum(const QString& name, int nAddNums/* = 1*/) { if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("主数据库未打开"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = QString::fromLocal8Bit("UPDATE Software SET installNum = installNum + %1 WHERE name = '%2';").arg(nAddNums).arg(name); QSqlQuery excete(*m_pSqlDatabase); if(!excete.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(excete.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } return true; } //增加软件未安装数 bool DatabaseManager::AddSoftwareUninstalledNum(const QString& name, int nAddNums/* = 1*/) { if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("主数据库未打开"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = QString::fromLocal8Bit("UPDATE Software SET uninstalledNum = uninstalledNum + %1 WHERE name = '%2';").arg(nAddNums).arg(name); QSqlQuery excete(*m_pSqlDatabase); if(!excete.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(excete.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } return true; } //读取所有软件信息 bool DatabaseManager::ReadAllSoftwareInfo(SoftwareinfoVector& softwareInfoVector) { softwareInfoVector.clear(); if(NULL == m_pSqlDatabase) return false; // m_SoftwareInstallInfoMap.clear(); //QString strSql = QString::fromLocal8Bit("SELECT * FROM Info WHERE pic_id = '%1' AND proj_id = '%2' ORDER BY rc_t_TextType, rc_t_TextNum;").arg(strID).arg(strProjID); QString strSql = QString::fromLocal8Bit("SELECT * FROM Software;"); QSqlQuery query(strSql, *m_pSqlDatabase); while(query.next()) { SoftwareInfo software; readSoftwareItem(software, query); softwareInfoVector.append(software); // SoftwareInstallInfo installInfo; // installInfo.name = software.name; // installInfo.version = software.version; // installInfo.installNum = software.installNum; // installInfo.uninstalledNum = software.uninstalledNum; // m_SoftwareInstallInfoMap.insert(installInfo.name, installInfo); } return softwareInfoVector.count() != 0; } //读取指定软件名称信息 bool DatabaseManager::ReadSoftwareInfo(const QString& name, SoftwareInfo& softwareInfo) { if(NULL == m_pSqlDatabase) return false; //QString strSql = QString::fromLocal8Bit("SELECT * FROM Info WHERE pic_id = '%1' AND proj_id = '%2' ORDER BY rc_t_TextType, rc_t_TextNum;").arg(strID).arg(strProjID); QString strSql = QString::fromLocal8Bit("SELECT * FROM Software WHERE name = '%1';").arg(name); QSqlQuery query(strSql, *m_pSqlDatabase); while(query.next()) { readSoftwareItem(softwareInfo, query); return true; } return false; } //删除软件 bool DatabaseManager::RemoveSoftware(const QString& name) { if(NULL == m_pSqlDatabase) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("主数据库未打开"), QString::fromLocal8Bit("确定")); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); return false; } QString strSql = QString::fromLocal8Bit("DELETE FROM Software WHERE name = '%1';").arg(name); QSqlQuery deleteQuery(*m_pSqlDatabase); if(!deleteQuery.exec(strSql)) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库保存失败,错误信息:[%1]").arg(deleteQuery.lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } if(!m_pSqlDatabase->commit()) { QMessageBox::warning(NULL, tr("Error"), QString::fromLocal8Bit("数据库操作失败,错误信息:[%1]").arg(m_pSqlDatabase->lastError().text()), QString::fromLocal8Bit("确定")); m_pSqlDatabase->rollback(); return false; } return true; } //写入数据 bool DatabaseManager::WriteDataMotionList(const DataMotionVector& dataMotionVector) { if(NULL == m_pSqlDatabase) { ServerLogger->AddLog("NULL == m_pSqlDatabase 数据库未打开"); return false; } QMutexLocker locker(&m_DateLock); if(!m_pSqlDatabase->transaction()) { ServerLogger->AddLog("m_pSqlDatabase->transaction() 数据库操作失败,错误信息:[%s]", m_pSqlDatabase->lastError().text().toStdString().c_str()); return false; } SoftwareinfoMap localSoftwareInfoMap; if(NetClass->m_pSoftUpgradeWidget != NULL) { localSoftwareInfoMap = NetClass->m_pSoftUpgradeWidget->GetSoftwareInfoMap(true); } int nCount = dataMotionVector.count(); int nInstallAppNum = 0; QString strPrevAppName = ""; for (int i = 0; i < nCount; i++) { const DataMotion& dataMotion = dataMotionVector[i]; QString strSql = ""; if(EMSG_REGISTERID == dataMotion.msg) { QSqlQuery insertQuery(*m_pSqlDatabase); insertQuery.prepare("INSERT INTO ClientInfo (id, version) VALUES (:id, :version);"); insertQuery.bindValue(":id", dataMotion.clientInfo.id); insertQuery.bindValue(":version", dataMotion.clientInfo.version); if(!insertQuery.exec()) { ServerLogger->AddLog("执行语句[%s] 数据库操作失败,错误信息:[%s]", insertQuery.lastQuery().toStdString().c_str(), insertQuery.lastError().text().toStdString().c_str()); m_pSqlDatabase->rollback(); return false; } //注册一个新的门店编号时,表示这是一个新的客户端,需要将所有软件的未安装数加1 strSql = QString::fromLocal8Bit("UPDATE Software SET uninstalledNum = uninstalledNum + %1;").arg(1); if(!excuteSql(strSql)) { return false; } nInstallAppNum = 2; } else if(EMSG_MODIFYID == dataMotion.msg) { strSql = QString::fromLocal8Bit("UPDATE ClientInfo SET id = '%1' WHERE id = '%2';").arg(dataMotion.clientInfo.id).arg(dataMotion.clientInfo.version); if(!excuteSql(strSql)) { return false; } } else if(EMSG_SOFTINSTALL == dataMotion.msg) { strSql = QString::fromLocal8Bit("DELETE FROM LastInstallHitory WHERE id = '%1' AND name = '%2';").arg(dataMotion.clientInfo.id).arg(dataMotion.softwareInfo.name); if(!excuteSql(strSql)) { return false; } QString strCurTime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"); QSqlQuery insertQuery(*m_pSqlDatabase); insertQuery.prepare("INSERT INTO LastInstallHitory (id, name, version, datetime) VALUES(:id, :name, :version, :datetime);"); insertQuery.bindValue(":id", dataMotion.clientInfo.id); insertQuery.bindValue(":name", dataMotion.softwareInfo.name); insertQuery.bindValue(":version", dataMotion.softwareInfo.version); insertQuery.bindValue(":datetime", strCurTime); if(!insertQuery.exec()) { ServerLogger->AddLog("执行语句[%s] 数据库操作失败,错误信息:[%s]", insertQuery.lastQuery().toStdString().c_str(), insertQuery.lastError().text().toStdString().c_str()); m_pSqlDatabase->rollback(); return false; } strSql = QString::fromLocal8Bit("UPDATE Software SET installNum = installNum + %1 WHERE name = '%2' AND version = '%3';").arg(1).arg(dataMotion.softwareInfo.name).arg(dataMotion.softwareInfo.version); if(!excuteSql(strSql)) { return false; } strSql = QString::fromLocal8Bit("UPDATE Software SET uninstalledNum = uninstalledNum - %1 WHERE name = '%2' AND version = '%3';").arg(1).arg(dataMotion.softwareInfo.name).arg(dataMotion.softwareInfo.version); if(!excuteSql(strSql)) { return false; } if(0 == nInstallAppNum || strPrevAppName != dataMotion.softwareInfo.name) { strPrevAppName = dataMotion.softwareInfo.name; nInstallAppNum++; } } else if(EMSG_SOFTUPLOAD == dataMotion.msg) { strSql = QString::fromLocal8Bit("DELETE FROM LastInstallHitory WHERE id = '%1';").arg(dataMotion.clientInfo.id); if(!excuteSql(strSql)) { return false; } int nNewSoftCount = dataMotion.softwareInfoVector.count(); for (int i = 0; i < nNewSoftCount; i++) { const SoftwareInfo& softwareInfo = dataMotion.softwareInfoVector[i]; if(softwareInfo.category == QString::fromLocal8Bit("网页")) continue; if(localSoftwareInfoMap.contains(softwareInfo.name)) { const SoftwareInfo& localSoftwareInfo = localSoftwareInfoMap[softwareInfo.name]; if(softwareInfo.category != QString::fromLocal8Bit("驱动")) {//其他类型比较版本号 if(softwareInfo.version != localSoftwareInfo.version) { continue; } } } QString strCurTime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"); QSqlQuery insertQuery(*m_pSqlDatabase); insertQuery.prepare("INSERT INTO LastInstallHitory (id, name, version, datetime) VALUES(:id, :name, :version, :datetime);"); insertQuery.bindValue(":id", dataMotion.clientInfo.id); insertQuery.bindValue(":name", softwareInfo.name); insertQuery.bindValue(":version", softwareInfo.version); insertQuery.bindValue(":datetime", strCurTime); if(!insertQuery.exec()) { ServerLogger->AddLog("执行语句[%s] 数据库操作失败,错误信息:[%s]", insertQuery.lastQuery().toStdString().c_str(), insertQuery.lastError().text().toStdString().c_str()); m_pSqlDatabase->rollback(); return false; } } if(0 == nInstallAppNum || strPrevAppName != dataMotion.softwareInfo.name) { strPrevAppName = dataMotion.softwareInfo.name; nInstallAppNum++; } } else if(EMSG_CROSSRUNINFO == dataMotion.msg) { int nMotion = dataMotion.userInfoMap.value("Motion", "0").toInt(); QString strUnitNum = dataMotion.userInfoMap.value("UnitNum", ""); QString strUnitName = dataMotion.userInfoMap.value("UnitName", ""); QString strCrosslinkRunInstalledState = dataMotion.userInfoMap.value("CrosslinkRunInstalledState", ""); if(strUnitNum.isEmpty()) continue; if(2 == nMotion) {//插入 //插入之前需要select一下看是否存在,存在则更新 strSql = QString::fromLocal8Bit("SELECT * FROM StatisticsInfo WHERE shopid = '%1';").arg(strUnitNum); QSqlQuery query(strSql, *m_pSqlDatabase); if(query.next()) {//存在,随后执行更新流程 nMotion = 1; } else {//插入 QSqlQuery insertQuery(*m_pSqlDatabase); insertQuery.prepare("INSERT INTO StatisticsInfo (regional, unitnum, unitname, shopid, shopname, install) VALUES (:regional, :unitnum, :unitname, :shopid, :shopname, :install);"); insertQuery.bindValue(":regional", ""); insertQuery.bindValue(":unitnum", ""); insertQuery.bindValue(":unitname", ""); insertQuery.bindValue(":shopid", strUnitNum); insertQuery.bindValue(":shopname", strUnitName); insertQuery.bindValue(":install", strCrosslinkRunInstalledState); if(!insertQuery.exec()) { ServerLogger->AddLog("执行语句[%s] 数据库操作失败,错误信息:[%s]", insertQuery.lastQuery().toStdString().c_str(), insertQuery.lastError().text().toStdString().c_str()); m_pSqlDatabase->rollback(); return false; } } } if(1 == nMotion) {//更新 strSql = QString::fromLocal8Bit("UPDATE StatisticsInfo SET install = '%1' WHERE shopid = '%2';").arg(strCrosslinkRunInstalledState).arg(strUnitNum); if(!excuteSql(strSql)) { return false; } } } else { ServerLogger->AddLog("getDataMotionSql 检测到无效数据添加 数据消息为[%d]", dataMotion.msg); continue; } } if(nInstallAppNum > 0) { QString strSql = "select count(*) from clientinfo"; QSqlQuery query(strSql, *m_pSqlDatabase); int nClientNum = 0; if(query.next()) { nClientNum = query.value(0).toInt(); } QMapIterator<QString, SoftwareInfo> iter(localSoftwareInfoMap); while(iter.hasNext()) { iter.next(); const SoftwareInfo& software = iter.value(); if(software.category != QString::fromLocal8Bit("网页")) { int nInstallCount = 0; QString strSql = ""; if(software.category == QString::fromLocal8Bit("驱动")) { strSql = QString::fromLocal8Bit("SELECT COUNT(*) FROM LastInstallHitory WHERE name = '%1'").arg(software.name); } else { strSql = QString::fromLocal8Bit("SELECT COUNT(*) FROM LastInstallHitory WHERE name = '%1' AND version = '%2'").arg(software.name).arg(software.version); } QSqlQuery query(strSql, *m_pSqlDatabase); if(query.next()) { nInstallCount = query.value(0).toInt(); } int nUnInstall = nClientNum - nInstallCount; if(nUnInstall < 0) { ServerLogger->AddLog("发现软件[%s]未安装数为[%d] 客户端[%d]", software.name, nUnInstall, nClientNum); nUnInstall = 0; } strSql = QString::fromLocal8Bit("UPDATE Software SET installNum = %1, uninstalledNum = %2 WHERE name = '%3';").arg(nInstallCount).arg(nUnInstall).arg(software.name); if(!excuteSql(strSql)) { return false; } } } emit sig_initData(); } // if(1 == nInstallAppNum) // { // QString strSql = QString::fromLocal8Bit("SELECT * FROM Software WHERE name = '%1';").arg(strPrevAppName); // QSqlQuery query(strSql, *m_pSqlDatabase); // while(query.next()) // { // SoftwareInfo software; // readSoftwareItem(software, query); // emit sig_updateAllNumData(software.name, software.version, software.installNum, software.uninstalledNum); // break; // } // } // else if(nInstallAppNum > 1) // { // emit sig_initData(); // } if(!m_pSqlDatabase->commit()) { ServerLogger->AddLog("m_pSqlDatabase->commit() 数据库操作失败,错误信息:[%s]", m_pSqlDatabase->lastError().text().toStdString().c_str()); m_pSqlDatabase->rollback(); return false; } return true; } //关闭数据库 void DatabaseManager::CloseDatabase() { if(NULL != m_pSqlDatabase && m_pSqlDatabase->isOpen()) m_pSqlDatabase->close(); RELEASESQL(m_pSqlDatabase); } //获取当前使用的数据库路径 QString DatabaseManager::GetDatabasePath() { return m_strDatabasePath; } void DatabaseManager::readSoftwareItem(SoftwareInfo &software, QSqlQuery &query) { software.name = query.value("name").toString(); software.brand = query.value("brand").toString(); software.category = query.value("category").toString(); software.location = query.value("location").toString(); software.mainExe = query.value("mainExe").toString(); software.url = query.value("url").toString(); software.version = query.value("version").toString(); bool bOk = false; software.installNum = query.value("installNum").toInt(&bOk); if(!bOk) software.installNum = 0; software.uninstalledNum = query.value("uninstalledNum").toInt(&bOk); if(!bOk) software.uninstalledNum = 0; software.packType = query.value("packType").toInt(&bOk); if(!bOk) software.packType = 0; } QString DatabaseManager::getDataMotionSql(const DataMotion& dataMotion) { //此函数不再使用 QString strSql = ""; switch(dataMotion.msg) { case EMSG_REGISTERID: strSql = QString::fromLocal8Bit("INSERT INTO ClientInfo (id, version) VALUES('%1', '%2');").arg(dataMotion.clientInfo.id).arg(dataMotion.clientInfo.version); break; case EMSG_MODIFYID: strSql = QString::fromLocal8Bit("UPDATE ClientInfo SET id = '%1' WHERE id = '%2';").arg(dataMotion.clientInfo.id).arg(dataMotion.clientInfo.version); break; case EMSG_SOFTINSTALL: strSql = QString::fromLocal8Bit("UPDATE Software SET installNum = installNum + %1 WHERE name = '%2';").arg(1).arg(dataMotion.softwareInfo.name); break; default: break; } return strSql; } bool DatabaseManager::excuteSql(const QString& strSQL) { if(NULL == m_pSqlDatabase || strSQL.isEmpty()) return false; QSqlQuery excete(*m_pSqlDatabase); if(!excete.exec(strSQL)) { ServerLogger->AddLog("执行语句[%s] 数据库操作失败,错误信息:[%s]", strSQL.toStdString().c_str(), excete.lastError().text().toStdString().c_str()); m_pSqlDatabase->rollback(); return false; } return true; }
#ifndef __SANDBOX_FINALIZE_WORKER_H__ #define __SANDBOX_FINALIZE_WORKER_H__ #include <nan.h> #include "sandbox-wrap.h" class SandboxFinalizeWorker : public Nan::AsyncWorker { public: SandboxFinalizeWorker(Nan::Callback *callback, SandboxWrap *sandbox); virtual ~SandboxFinalizeWorker(); void Execute() override; void HandleOKCallback() override; private: SandboxWrap *sandbox_; }; #endif
#include "Auth/LoginManager.h" using namespace m2::server; HttpResponse::Code LoginManager::doAction(const std::string &data, std::string &response) { StringsPair info; try { info = deserialize(data); response = createResponse(info.serverString, info.clientString); } catch (const pt::ptree_error &e) { std::cout << e.what() << std::endl; response = createError("client_string and decrypted server_string"); return HttpResponse::Code::FORBIDEN; } response = createResponse(info.serverString, info.clientString); //m2::data::user::AUsers users; //TODO save return HttpResponse::Code::OK; } Manager::StringsPair LoginManager::deserialize(const std::string &data) { pt::ptree request; StringsPair info; std::stringstream stream; stream << data; boost::property_tree::read_json(stream, request); info.serverString = request.get<std::string>("server_string"); info.clientString = request.get<std::string>("client_string"); return info; } std::string LoginManager::createResponse(const std::string &server_string, const std::string &client_string) { std::string session_id = "test"; //TODO pt::ptree tree; std::stringstream stream; tree.put("session_id", session_id); boost::property_tree::write_json(stream, tree); return std::string(); } LoginManager::LoginManager(Database *database) : Manager(database) { }
#pragma once #include "Record.h" #include <memory> #include <vector> namespace OpenFlight { class AncillaryRecord; class LongIdRecord; //------------------------------------------------------------------------- // Explication sur le refcount... // // class OFR_API PrimaryRecord : public Record { public: PrimaryRecord() = delete; explicit PrimaryRecord(PrimaryRecord* ipParent); PrimaryRecord(const PrimaryRecord&) = delete; PrimaryRecord& operator=(const PrimaryRecord&) = delete; virtual ~PrimaryRecord(); void addAncillaryRecord(AncillaryRecord*); void addChild(PrimaryRecord*); int decrementUseCount(); AncillaryRecord* getAncillaryRecord(int) const; PrimaryRecord* getChild(int) const; LongIdRecord* getLongIdRecord() const; int getNumberOfAncillaryRecords() const; int getNumberOfChilds() const; PrimaryRecord* getParent() const; int getUseCount() const; bool hasLongIdRecord() const; bool isExternalReference() const; void incrementUseCount(); protected: virtual bool parseRecord(std::ifstream& iRawRecord, int iVersion) = 0; virtual void handleAddedAncillaryRecord(AncillaryRecord*); void incrementUseCount(PrimaryRecord*, int); std::vector<AncillaryRecord*> mAncillaryRecords; std::vector< PrimaryRecord* > mChilds; PrimaryRecord* mpParent; // ancillary records // These are just convenient pointers to data into mAncillaryRecords. // LongIdRecord *mpLongId; //owned in mAncillaryRecords // comment // longId // transformation // matrix // rotate... // cheap way of ref counting... see openflightReader::parseExternalReference // int mUseCount; }; }
/************************************************************************ * @project : sloth * @class : WaterShader * @version : v1.0.0 * @description : 和水面着色器(water)的 uniform 变量相对应,用于修改着色器变量 * @author : Oscar Shen * @creat : 2017年2月13日18:41:57 * @revise : ************************************************************************ * Copyright @ OscarShen 2017. All rights reserved. ************************************************************************/ #pragma once #ifndef SLOTH_WATER_SHADER_H_ #define SLOTH_WATER_SHADER_H_ #include "shader.h" #include "../entities/light.hpp" #include <memory> namespace sloth { class WaterShader : public Shader { typedef std::shared_ptr<WaterShader> WaterShader_s; private: static WaterShader_s m_Inst; int m_LocModel; int m_LocView; int m_LocProjection; int m_LocReflectionTexture; int m_LocRefractionTexture; int m_LocDudvMap; int m_LocMoveFactor; int m_LocCameraPosition; int m_LocNormalMap; int m_LocLightColor; int m_LocLightPosition; int m_LocDepthMap; public: static WaterShader_s inst(); virtual ~WaterShader(); /*********************************************************************** * @description : 加载model矩阵 * @author : Oscar Shen * @creat : 2017年2月13日18:40:33 ***********************************************************************/ void loadModelMatrix(const glm::mat4 &model); /*********************************************************************** * @description : 加载view矩阵 * @author : Oscar Shen * @creat : 2017年2月13日18:40:33 ***********************************************************************/ void loadViewMatrix(const RawCamera &camera); /*********************************************************************** * @description : 加载projection矩阵 * @author : Oscar Shen * @creat : 2017年2月13日18:40:33 ***********************************************************************/ void loadProjectionMatrix(const glm::mat4 &projection); /*********************************************************************** * @description : 设定水波荡漾的程度 * @author : Oscar Shen * @creat : 2017年2月20日14:31:16 ***********************************************************************/ void loadMoveFactor(float factor); /*********************************************************************** * @description : 输入相机位置,计算 Fresnel Effect * @author : Oscar Shen * @creat : 2017年2月20日15:14:12 ***********************************************************************/ void loadCameraPosition(const RawCamera &camera); /*********************************************************************** * @description : 载入灯光 * @author : Oscar Shen * @creat : 2017年2月20日20:30:40 ***********************************************************************/ void loadLight(const Light &light); /*********************************************************************** * @description : 绑定采样器单元——反射纹理、折射纹理、dudv map * @author : Oscar Shen * @creat : 2017年2月17日16:44:26 ***********************************************************************/ void connectTextureUnit(); private: WaterShader(); /*********************************************************************** * @description : 初始化时获取所有变量的 uniform location * @author : Oscar Shen * @creat : 2017年2月13日18:37:28 ***********************************************************************/ virtual void getAllUniformLocation() override; }; } #endif // !SLOTH_WATER_SHADER_H_
#include "DUISystem.h" DUISystem::DUISystem(void) { currentFocusedElement = NULL; } DUISystem::~DUISystem(void) { } void DUISystem::Init() { } void DUISystem::Update() { if(currentFocusedElement != NULL) { if(input.keyboard.arrowDown.tapped && currentFocusedElement->bottomLink != NULL) { SetFocus(currentFocusedElement->bottomLink); } else if(input.keyboard.arrowUp.tapped && currentFocusedElement->topLink != NULL) { SetFocus(currentFocusedElement->topLink); } else if(input.keyboard.arrowLeft.tapped && currentFocusedElement->leftLink != NULL) { SetFocus(currentFocusedElement->leftLink); } else if(input.keyboard.arrowRight.tapped && currentFocusedElement->rightLink != NULL) { SetFocus(currentFocusedElement->rightLink); } else if(input.keyboard.spacebar.tapped || input.keyboard.enter.tapped) { currentFocusedElement->OnClick(); } } } void DUISystem::SetFocus(duiElement* newElement) { if(newElement) { currentFocusedElement->SetFocus(false); newElement->SetFocus(true); currentFocusedElement = newElement; } }
#include<iostream> #include<cassert> #include<errno.h> #include<cstring> #include<type_traits> #include<signal.h> #include<sys/socket.h> #include<cstdio> #include<unistd.h> #include<cstdlib> #include<sys/ipc.h> #include<sys/types.h> #include<string> #include<arpa/inet.h> using namespace std; //#define INET_ADDRSTRLEN 16 bool stop=false; namespace { const unsigned int BUFSIZE=40; } int main(int argc, char **argv){ if(argc!=3){ printf("error argu"); } int sock=socket(PF_INET,SOCK_STREAM, 0 ); assert(sock>=0); struct sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_family=AF_INET; const string ip=argv[1]; int port=atoi(argv[2]); inet_pton(AF_INET, ip.c_str(), &address.sin_addr); address.sin_port=htons(port); int connId=connect(sock, (sockaddr*)&address, sizeof(address)); if(connId<0){ cout<<errno<<endl; }else{ //string send_str( "hellookska"); char * buf=new char[BUFSIZE]; string wol("anmsadfjaklfjkklfaldse"); //recv(sock, buf,BUFSIZE, 0); send(sock, wol.c_str(), sizeof(wol), 0); recv(sock, buf, BUFSIZE, 0); cout<<buf<<endl; close(sock); } return 0; }
#include <iostream> #include <algorithm> using namespace std; int main() { int N, K; cin >> N >> K; int h[N + 1]; for (int i = 0; i < N; ++i) cin >> h[i]; h[N] = 200010; sort(h, h + N + 1); int itr = 0, ans = 0, add = 0; for (int H = h[0]; itr < N; ++H) { while (h[itr] <= H) ++itr; add += N - itr; if (add > K) { // 1つ手前で切る ++ans; add = N - itr; } } if (add > 0) ++ans; cout << ans << endl; return 0; }
#ifndef __HOT__COMMONS__ALGORITHMS__ #define __HOT__COMMONS__ALGORITHMS__ #include <immintrin.h> #include <bitset> #include <cassert> #include <iostream> namespace hot { namespace commons { inline uint32_t getBytesUsedInExtractionMask( uint64_t successiveExtractionMask) { uint32_t const unsetBytes = _mm_movemask_pi8(_mm_cmpeq_pi8( _mm_and_si64((__m64)(successiveExtractionMask), (__m64)(UINT64_MAX)), _mm_setzero_si64())); // 8 - numberUnsetBytes return 8 - _mm_popcnt_u32(unsetBytes); } inline uint16_t getMaximumMaskByteIndex(uint16_t bitsUsed) { return (bitsUsed - 1) / 8; } template <uint numberExtractionMasks> inline std::array<uint64_t, numberExtractionMasks> getUsedExtractionBitsForMask( uint32_t usedBits, uint64_t const* extractionMask); template <uint numberExtractionMasks> inline __m256i extractionMaskToRegister( std::array<uint64_t, numberExtractionMasks> const& extractionData); template <> inline __m256i extractionMaskToRegister<1>( std::array<uint64_t, 1> const& extractionData) { return _mm256_set_epi64x(extractionData[0], 0ul, 0ul, 0ul); }; template <> inline __m256i extractionMaskToRegister<2>( std::array<uint64_t, 2> const& extractionData) { return _mm256_set_epi64x(extractionData[0], extractionData[1], 0ul, 0ul); } template <> inline __m256i extractionMaskToRegister<4>( std::array<uint64_t, 4> const& extractionData) { return _mm256_loadu_si256( reinterpret_cast<__m256i const*>(extractionData.data())); } template <size_t numberBytes> inline std::array<uint8_t, numberBytes> extractSuccesiveFromRandomBytes( uint8_t const* bytes, uint8_t const* bytePositions) { std::array<uint8_t, numberBytes> succesiveBytes; for (uint i = 0; i < numberBytes; ++i) { succesiveBytes[i] = bytes[bytePositions[i]]; } return std::move(succesiveBytes); } /** * Given a bitindex this function returns its corresponding byte index * * @param bitIndex the bit index to convert to byte Level * @return the byte index */ inline unsigned int getByteIndex(unsigned int bitIndex) { return bitIndex / 8; } /** * gets the number of bytes needed to represent the successive bytes from * (inclusive) the byte containing the mostSignificantBitIndex until (inclusive) * the byte containing the leastSignificantBitIndex * * @param mostSignificantBitIndex the index of the most significant bit * @param leastSignificantBitIndex the index of the least significant bit * @return the size of the range in bytes */ inline uint getByteRangeSize(uint mostSignificantBitIndex, uint leastSignificantBitIndex) { return getByteIndex(leastSignificantBitIndex) - getByteIndex(mostSignificantBitIndex); } constexpr inline uint16_t convertBytesToBits(uint16_t const byteIndex) { return byteIndex * 8; } constexpr inline uint16_t bitPositionInByte(uint16_t const absolutBitPosition) { return absolutBitPosition % 8; } constexpr uint64_t HIGHEST_UINT64_BIT = (1ul << 63); inline uint getSuccesiveByteOffsetForMostRightByte(uint mostRightByte) { return std::max(0, ((int)mostRightByte) - 7); } inline bool isNoMissmatch( std::pair<uint8_t const*, uint8_t const*> const& missmatch, uint8_t const* key1, uint8_t const* key2, size_t keyLength) { return missmatch.first == (key1 + keyLength) && missmatch.second == (key2 + keyLength); } inline bool isBitSet(uint8_t const* existingRawKey, uint16_t const mAbsoluteBitIndex) { return (existingRawKey[getByteIndex(mAbsoluteBitIndex)] & (0b10000000 >> bitPositionInByte(mAbsoluteBitIndex))) > 0; } inline uint16_t getLeastSignificantBitIndexInByte(uint8_t byte) { return (7 - _tzcnt_u32(byte)); } inline uint16_t getMostSignificantBitIndexInByte(uint8_t byte) { assert(byte > 0); return _lzcnt_u32(byte) - 24; } inline __attribute__((always_inline)) int getMostSignificantBitIndex( uint32_t number) { int msb; asm("bsr %1,%0" : "=r"(msb) : "r"(number)); return msb; } } // namespace commons } // namespace hot #endif
#include <conio.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> #include <math.h> #include <locale.h> #include <ctype.h> char s[5]; char m[5] = "m"; char f[5] = "f"; int retorno; int main() { ret: printf("\nInsira f ou m, para feminino e masculino\n"); scanf("%s",&s); retorno = strcmp(s,m); if(retorno !=0) { retorno = strcmp(s,f); if(retorno !=0) { printf("\nInsira somente f ou m\n"); goto ret; } else { goto ret; } } else { goto ret; } }
#ifndef _ORIENTAL_GENIUS_H #define _ORIENTAL_GENIUS_H #include "Enemy.h" #include "Path.h" class OrientalGenius : public Enemy { private: iPoint original_pos; Path path; Animation back; Animation up1, up2, up3; Animation stay; Animation shoot; public: OrientalGenius(int x, int y, int type); void Move(); }; #endif
#include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; int maxis=0,flag=0; int a[n]; for(int i=0;i<n;i++) { cin>>a[i]; } for(int i=0;i<n;i++) { if(a[i]!=0) { flag++; if(flag>maxis) { maxis=flag; } } else{ flag=0; } } cout<<"THE MAXIMUM LENGTH IS "<<maxis; }
// Copyright 2014 Sebastian Zwierzchowski <sebastian.zwierzchowski<at>gmail<dot>com> // // 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 "Controller.h" // RGBdriver Driver(CLK,DIO); OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); RCSwitch wSwitch = RCSwitch(); /* * Constructor */ const byte LED_PIN = 13; Controller::Controller() { pinMode(LED_PIN,OUTPUT); //Serial.begin(9600); this->inS.reserve(200); } void Controller::setupCtrl() { this->startTime = 0; this->led.report(); wSwitch.enableTransmit(WIRELESS_TRANSMITER_PIN); wSwitch.enableReceive(WIRELESS_RECIVER_PIN); sensors.begin(); sensors.requestTemperatures(); } /* * Sending wireless singal 433Mhz */ int Controller::sendWireless(String code) { //code.protocol String tmp = ""; //code to send unsigned long sendCode; //protocol int p = 1; //bit length int bit = 24; //get value form code int idx = code.indexOf('.'); tmp = code.substring(0,idx); sendCode = tmp.toInt(); tmp = code.substring(idx+1); p = tmp.toInt(); if ( p == 1) { bit = 24; wSwitch.setProtocol(1); wSwitch.setPulseLength(203); wSwitch.setRepeatTransmit(5); wSwitch.send(sendCode,24); } else if ( p == 2) { bit = 32; wSwitch.setProtocol(2); wSwitch.send(sendCode,32); } return 0; } int Controller::getCode() { unsigned long value = wSwitch.getReceivedValue(); if (value != 0) { Serial.print("OW."); Serial.println(value); } wSwitch.resetAvailable(); return 0; } /* * Get temperature from sensor */ float Controller::getTemp(int num) { sensors.requestTemperatures(); delay(50); return sensors.getTempCByIndex(num); } void Controller::reportAllTemp() { int count = sensors.getDeviceCount(); sensors.requestTemperatures(); delay(50); int i; for (i = 0; i < count; i++) { this->tempReport(sensors.getTempCByIndex(i), i); } } void Controller::tempReport(float temp, int id) { String s_temp = String(temp); String s_id = String(id); String ret = String("{\"cmd\": \"report\", \"model\": \"dallastemp\", \"sid\": \"dallasDS" + s_id + "\", \"data\": {\"temp\": " + s_temp + "}}"); Serial.println(ret); } void Controller::echo(String s) { Serial.println(s); } int Controller::command(String s) { //Serial.println(s); if (s == "ping") { Serial.println("pong"); return 0; } int idx = s.indexOf('.'); if (idx == -1) {return 0;} String cmd = ""; String code = ""; cmd = s.substring(0,idx); code = s.substring(idx+1); if (cmd == "" or code == "" or cmd.length() > 1) { return -1; } switch (cmd[0]) { case 'W': this->sendWireless(code); break; case 'B': this->led.set_bright(code.toInt()); this->led.report(); break; case 'C': this->led.set_rgb(code.toInt()); this->led.report(); break; case 'P': this->led.set_power(code.toInt()); this->led.report(); break; case 'T': this->getTemp(code.toInt()); break; } return 0; } void Controller::listen(bool echo) { /* if (wSwitch.available()) { this->getCode(); } */ unsigned long currentTime = millis(); if (currentTime - this->startTime > 60000) { this->reportAllTemp(); this->startTime = currentTime; } while (Serial.available()) { char inC = Serial.read(); if (inC == '\n') { if (echo) { Serial.println(this->inS); } this->command(inS); this->inS = ""; break; } this->inS += inC; } }
/* 两堆石头,分别为n,m.两人轮流从一堆石头中拿,也可以拿走两堆中相同数量的石头.最后拿完的人赢. */ /*奇异局势(必败)返回0*/ int wzf(int n,int m) { if(n>m) swap(n,m); int k=m-n; int a=(k*(1.0+sqrt(5.0))/2.0); return a==n?0:1; } int main () { int a, b; while(scanf("%d%d", &a, &b)) { if (a == 0 && b == 0) break; int k = b - a; int n = (1 + sqrt(5.0)) / 2 * k; if (a == n) puts("0"); else { puts("1"); if (a - n == b - n - k) printf("%d %d\n", n, n + k); //两者之间的差值不变 if (a == 0) puts("0 0"); //如果a等于0了,差值只能为0,即为(0,0)。 for (int i = 1; i <= b; i++) { //枚举a和b之间的差值,可能从1一直到b - 1 n = (1 + sqrt(5.0)) / 2 * i; int tmp = n + i; if (n == a) printf("%d %d\n", n, tmp); if (tmp == a) printf("%d %d\n", n, tmp); if (tmp == b) printf("%d %d\n", n, b); } } } return 0; }
#ifndef WATCHER_H #define WATCHER_H #include<QObject> #include<QAction> #include<QEvent> #include "iocoingui.h" class Watcher : public QObject { Q_OBJECT public: explicit Watcher(QObject * parent = Q_NULLPTR); virtual bool eventFilter(QObject * watched, QEvent * event) Q_DECL_OVERRIDE; }; #endif
#pragma once #include "Core/ComponentPool.h" #include "Core/ComponentRegister.h" namespace Hourglass { class ISystem { protected: template <typename T> void ComponentPoolInit( StrID name, T* data, ComponentPool<T>* pool, unsigned int size, unsigned int flags = CompRegFlags::kNone ); }; template<typename T> inline void ISystem::ComponentPoolInit( StrID name, T * data, ComponentPool<T>* pool, unsigned int size, unsigned int flags ) { ComponentRegister<T> reg( name, pool, flags ); pool->Init( data, size ); } }
// Created on: 2013-09-20 // Created by: Denis BOGOLEPOV // Copyright (c) 2013-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Graphic3d_ShaderProgram_HeaderFile #define _Graphic3d_ShaderProgram_HeaderFile #include <Graphic3d_RenderTransparentMethod.hxx> #include <Graphic3d_ShaderAttribute.hxx> #include <Graphic3d_ShaderObject.hxx> #include <Graphic3d_ShaderVariable.hxx> #include <Graphic3d_TextureParams.hxx> #include <NCollection_Sequence.hxx> //! List of shader objects. typedef NCollection_Sequence<Handle(Graphic3d_ShaderObject)> Graphic3d_ShaderObjectList; //! List of custom uniform shader variables. typedef NCollection_Sequence<Handle(Graphic3d_ShaderVariable)> Graphic3d_ShaderVariableList; //! List of custom vertex shader attributes typedef NCollection_Sequence<Handle(Graphic3d_ShaderAttribute)> Graphic3d_ShaderAttributeList; //! This class is responsible for managing shader programs. class Graphic3d_ShaderProgram : public Standard_Transient { DEFINE_STANDARD_RTTIEXT(Graphic3d_ShaderProgram, Standard_Transient) public: //! Default value of THE_MAX_LIGHTS macros within GLSL program (see Declarations.glsl). static const Standard_Integer THE_MAX_LIGHTS_DEFAULT = 8; //! Default value of THE_MAX_CLIP_PLANES macros within GLSL program (see Declarations.glsl). static const Standard_Integer THE_MAX_CLIP_PLANES_DEFAULT = 8; //! Default value of THE_NB_FRAG_OUTPUTS macros within GLSL program (see Declarations.glsl). static const Standard_Integer THE_NB_FRAG_OUTPUTS = 1; public: //! Creates new empty program object. Standard_EXPORT Graphic3d_ShaderProgram(); //! Releases resources of program object. Standard_EXPORT virtual ~Graphic3d_ShaderProgram(); //! Checks if the program object is valid or not. Standard_EXPORT virtual Standard_Boolean IsDone() const; //! Returns unique ID used to manage resource in graphic driver. const TCollection_AsciiString& GetId() const { return myID; } //! Sets unique ID used to manage resource in graphic driver. //! WARNING! Graphic3d_ShaderProgram constructor generates a unique id for proper resource management; //! however if application overrides it, it is responsibility of application to avoid name collisions. void SetId (const TCollection_AsciiString& theId) { myID = theId; } //! Returns GLSL header (version code and extensions). const TCollection_AsciiString& Header() const { return myHeader; } //! Setup GLSL header containing language version code and used extensions. //! Will be prepended to the very beginning of the source code. //! Example: //! @code //! #version 300 es //! #extension GL_ARB_bindless_texture : require //! @endcode void SetHeader (const TCollection_AsciiString& theHeader) { myHeader = theHeader; } //! Append line to GLSL header. void AppendToHeader (const TCollection_AsciiString& theHeaderLine) { if (!myHeader.IsEmpty()) { myHeader += "\n"; } myHeader += theHeaderLine; } //! Return the length of array of light sources (THE_MAX_LIGHTS), //! to be used for initialization occLightSources. //! Default value is THE_MAX_LIGHTS_DEFAULT. Standard_Integer NbLightsMax() const { return myNbLightsMax; } //! Specify the length of array of light sources (THE_MAX_LIGHTS). void SetNbLightsMax (Standard_Integer theNbLights) { myNbLightsMax = theNbLights; } //! Return the length of array of shadow maps (THE_NB_SHADOWMAPS); 0 by default. Standard_Integer NbShadowMaps() const { return myNbShadowMaps; } //! Specify the length of array of shadow maps (THE_NB_SHADOWMAPS). void SetNbShadowMaps (Standard_Integer theNbMaps) { myNbShadowMaps = theNbMaps; } //! Return the length of array of clipping planes (THE_MAX_CLIP_PLANES), //! to be used for initialization occClipPlaneEquations. //! Default value is THE_MAX_CLIP_PLANES_DEFAULT. Standard_Integer NbClipPlanesMax() const { return myNbClipPlanesMax; } //! Specify the length of array of clipping planes (THE_MAX_CLIP_PLANES). void SetNbClipPlanesMax (Standard_Integer theNbPlanes) { myNbClipPlanesMax = theNbPlanes; } //! Attaches shader object to the program object. Standard_EXPORT Standard_Boolean AttachShader (const Handle(Graphic3d_ShaderObject)& theShader); //! Detaches shader object from the program object. Standard_EXPORT Standard_Boolean DetachShader (const Handle(Graphic3d_ShaderObject)& theShader); //! Returns list of attached shader objects. const Graphic3d_ShaderObjectList& ShaderObjects() const { return myShaderObjects; } //! The list of currently pushed but not applied custom uniform variables. //! This list is automatically cleared after applying to GLSL program. const Graphic3d_ShaderVariableList& Variables() const { return myVariables; } //! Return the list of custom vertex attributes. const Graphic3d_ShaderAttributeList& VertexAttributes() const { return myAttributes; } //! Assign the list of custom vertex attributes. //! Should be done before GLSL program initialization. Standard_EXPORT void SetVertexAttributes (const Graphic3d_ShaderAttributeList& theAttributes); //! Returns the number (1+) of Fragment Shader outputs to be written to //! (more than 1 can be in case of multiple draw buffers); 1 by default. Standard_Integer NbFragmentOutputs() const { return myNbFragOutputs; } //! Sets the number of Fragment Shader outputs to be written to. //! Should be done before GLSL program initialization. void SetNbFragmentOutputs (const Standard_Integer theNbOutputs) { myNbFragOutputs = theNbOutputs; } //! Return true if Fragment Shader should perform alpha test; FALSE by default. Standard_Boolean HasAlphaTest() const { return myHasAlphaTest; } //! Set if Fragment Shader should perform alpha test. //! Note that this flag is designed for usage with - custom shader program may discard fragment regardless this flag. void SetAlphaTest (Standard_Boolean theAlphaTest) { myHasAlphaTest = theAlphaTest; } //! Return TRUE if standard program header should define default texture sampler occSampler0; TRUE by default for compatibility. Standard_Boolean HasDefaultSampler() const { return myHasDefSampler; } //! Set if standard program header should define default texture sampler occSampler0. void SetDefaultSampler (Standard_Boolean theHasDefSampler) { myHasDefSampler = theHasDefSampler; } //! Return if Fragment Shader color should output to OIT buffers; OFF by default. Graphic3d_RenderTransparentMethod OitOutput() const { return myOitOutput; } //! Set if Fragment Shader color should output to OIT buffers. //! Note that weighted OIT also requires at least 2 Fragment Outputs (color + coverage), //! and Depth Peeling requires at least 3 Fragment Outputs (depth + front color + back color), void SetOitOutput (Graphic3d_RenderTransparentMethod theOutput) { myOitOutput = theOutput; } //! Return TRUE if standard program header should define functions and variables used in PBR pipeline. //! FALSE by default. Standard_Boolean IsPBR() const { return myIsPBR; } //! Sets whether standard program header should define functions and variables used in PBR pipeline. void SetPBR (Standard_Boolean theIsPBR) { myIsPBR = theIsPBR; } //! Return texture units declared within the program, @sa Graphic3d_TextureSetBits. Standard_Integer TextureSetBits() const { return myTextureSetBits; } //! Set texture units declared within the program. void SetTextureSetBits (Standard_Integer theBits) { myTextureSetBits = theBits; } //! Pushes custom uniform variable to the program. //! The list of pushed variables is automatically cleared after applying to GLSL program. //! Thus after program recreation even unchanged uniforms should be pushed anew. template<class T> Standard_Boolean PushVariable (const TCollection_AsciiString& theName, const T& theValue); //! Removes all custom uniform variables from the program. Standard_EXPORT void ClearVariables(); //! Pushes float uniform. Standard_Boolean PushVariableFloat (const TCollection_AsciiString& theName, const float theValue) { return PushVariable (theName, theValue); } //! Pushes vec2 uniform. Standard_Boolean PushVariableVec2 (const TCollection_AsciiString& theName, const Graphic3d_Vec2& theValue) { return PushVariable (theName, theValue); } //! Pushes vec3 uniform. Standard_Boolean PushVariableVec3 (const TCollection_AsciiString& theName, const Graphic3d_Vec3& theValue) { return PushVariable (theName, theValue); } //! Pushes vec4 uniform. Standard_Boolean PushVariableVec4 (const TCollection_AsciiString& theName, const Graphic3d_Vec4& theValue) { return PushVariable (theName, theValue); } //! Pushes int uniform. Standard_Boolean PushVariableInt (const TCollection_AsciiString& theName, const int theValue) { return PushVariable (theName, theValue); } //! Pushes vec2i uniform. Standard_Boolean PushVariableVec2i (const TCollection_AsciiString& theName, const Graphic3d_Vec2i& theValue) { return PushVariable (theName, theValue); } //! Pushes vec3i uniform. Standard_Boolean PushVariableVec3i (const TCollection_AsciiString& theName, const Graphic3d_Vec3i& theValue) { return PushVariable (theName, theValue); } //! Pushes vec4i uniform. Standard_Boolean PushVariableVec4i (const TCollection_AsciiString& theName, const Graphic3d_Vec4i& theValue) { return PushVariable (theName, theValue); } public: //! The path to GLSL programs determined from CSF_ShadersDirectory or CASROOT environment variables. //! @return the root folder with default GLSL programs. Standard_EXPORT static const TCollection_AsciiString& ShadersFolder(); private: TCollection_AsciiString myID; //!< the unique identifier of program object Graphic3d_ShaderObjectList myShaderObjects; //!< the list of attached shader objects Graphic3d_ShaderVariableList myVariables; //!< the list of custom uniform variables Graphic3d_ShaderAttributeList myAttributes; //!< the list of custom vertex attributes TCollection_AsciiString myHeader; //!< GLSL header with version code and used extensions Standard_Integer myNbLightsMax; //!< length of array of light sources (THE_MAX_LIGHTS) Standard_Integer myNbShadowMaps; //!< length of array of shadow maps (THE_NB_SHADOWMAPS) Standard_Integer myNbClipPlanesMax; //!< length of array of clipping planes (THE_MAX_CLIP_PLANES) Standard_Integer myNbFragOutputs; //!< length of array of Fragment Shader outputs (THE_NB_FRAG_OUTPUTS) Standard_Integer myTextureSetBits;//!< texture units declared within the program, @sa Graphic3d_TextureSetBits Graphic3d_RenderTransparentMethod myOitOutput; //!< flag indicating that Fragment Shader includes OIT outputs Standard_Boolean myHasDefSampler; //!< flag indicating that program defines default texture sampler occSampler0 Standard_Boolean myHasAlphaTest; //!< flag indicating that Fragment Shader performs alpha test Standard_Boolean myIsPBR; //!< flag indicating that program defines functions and variables used in PBR pipeline }; DEFINE_STANDARD_HANDLE (Graphic3d_ShaderProgram, Standard_Transient) // ======================================================================= // function : PushVariable // purpose : Pushes custom uniform variable to the program // ======================================================================= template<class T> inline Standard_Boolean Graphic3d_ShaderProgram::PushVariable (const TCollection_AsciiString& theName, const T& theValue) { Handle(Graphic3d_ShaderVariable) aVariable = Graphic3d_ShaderVariable::Create (theName, theValue); if (aVariable.IsNull() || !aVariable->IsDone()) { return Standard_False; } myVariables.Append (aVariable); return Standard_True; } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2006 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "adjunct/quick/dialogs/AskPluginDownloadDialog.h" #ifdef WIDGET_RUNTIME_SUPPORT #include "adjunct/widgetruntime/GadgetStartup.h" #include "adjunct/widgetruntime/pi/PlatformGadgetUtils.h" #include "modules/pi/system/OpPlatformViewers.h" #endif // WIDGET_RUNTIME_SUPPORT #include "modules/pi/system/OpPlatformViewers.h" #include "modules/locale/locale-enum.h" #include "modules/locale/oplanguagemanager.h" #include "modules/prefs/prefsmanager/collections/pc_ui.h" OP_STATUS AskPluginDownloadDialog::Init(DesktopWindow* parent_window, const uni_char* plugin, const uni_char* downloadurl, Str::LocaleString message_format_id, BOOL is_widget) { m_is_widget = is_widget; OpString title; OpString format; OpString message; g_languageManager->GetString(Str::D_PLUGIN_DOWNLOAD_RESOURCE_TITLE, format); RETURN_IF_ERROR(title.AppendFormat(format.CStr(), plugin)); g_languageManager->GetString(message_format_id, format); RETURN_IF_ERROR(message.AppendFormat(format.CStr(), plugin, plugin)); RETURN_IF_ERROR(m_askplugindownloadurl.Set(downloadurl)); return SimpleDialog::Init(WINDOW_NAME_ASK_PLUGIN_DOWNLOAD, title, message, parent_window, TYPE_OK_CANCEL, IMAGE_QUESTION); } UINT32 AskPluginDownloadDialog::OnOk() { if (IsDoNotShowDialogAgainChecked()) g_pcui->WriteIntegerL(PrefsCollectionUI::AskAboutFlashDownload, FALSE); // FIXME: Long term solution for this problem is to automatically install // flash from within Opera browser or Widget Runtime. Currently we're opening // Opera or default browser and redirecting to flash download site. It would // be nice to open default browser here on all platforms, but because of // DSK-268209 (problems with IE and flash plugin download) we can't do it // on windows. // FIXME: We should use OpPlatformViewers::OpenInOpera here, but // before we can do that it has to be implemented differently in // different kind of products (currently we have browser and gadget // products). Current general implementation of OpenInOpera doesn't work // for gadget product. if (m_is_widget) { #ifdef _UNIX_DESKTOP_ RETURN_VALUE_IF_ERROR(g_op_platform_viewers->OpenInDefaultBrowser( m_askplugindownloadurl.CStr()), 0); #else OpString command; RETURN_VALUE_IF_ERROR(PlatformGadgetUtils::GetOperaExecPath(command), 0); OpStatus::Ignore(g_op_system_info->ExecuteApplication(command.CStr(), m_askplugindownloadurl.CStr())); #endif // _UNIX_DESKTOP_ } else { g_application->GoToPage(m_askplugindownloadurl.CStr(), TRUE); } return 1; } void AskPluginDownloadDialog::OnCancel() { if (IsDoNotShowDialogAgainChecked()) g_pcui->WriteIntegerL(PrefsCollectionUI::AskAboutFlashDownload, FALSE); }
#include <iostream> #include <iomanip> #include <cstdlib> #include <ctime> int main(){ const int arraySize = 7; //such that: [0,...,6] int frequency[ arraySize ] = {}; //set frequencies to zero std::srand(std::time(NULL)); //seed to random time //rolling ten thousand times for ( int roll = 1; roll <= 10000; ++roll ){ ++frequency[ 1 + rand() % 6 ]; //incrementing one to the index } std::cout << "Face" << std::setw( 13 ) << "Frequency" << std::endl; //header //outputting the frequencies for ( int face = 1; face < arraySize; ++face ){ std::cout << std::setw(4) << face << std::setw(13) << frequency[face] << std::endl; }//for } // end main
#include "tcpserverwidget.h" #include "ui_tcpserverwidget.h" #include <QMessageBox> #include <QSqlDatabase> #include <QSqlError> #include <QDebug> #include <QSqlQuery> TCPServerWidget::TCPServerWidget(QWidget *parent) : QWidget(parent) , ui(new Ui::TCPServerWidget) { ui->setupUi(this); setWindowTitle("门禁服务器"); db = QSqlDatabase::addDatabase("QMYSQL","mainwindow_login"); //连接数据库 db.setHostName("127.0.0.1"); db.setUserName("root"); db.setPassword("guang135792468"); db.setDatabaseName("entrance_guard"); //打开数据库 if(!db.open()){ QMessageBox::warning(this, "错误",db.lastError().text()); this->close(); } tcpServer=NULL; tcpSocket=NULL; tcpServer = new QTcpServer(this); tcpServer->listen(QHostAddress("192.168.43.6"),1454); connect(tcpServer,&QTcpServer::newConnection, [=]() { //取出连接好的套接字 tcpSocket = tcpServer->nextPendingConnection(); //取得对方的IP和断开 QString itsip = tcpSocket->peerAddress().toString(); qint16 itsport = tcpSocket->peerPort(); QString temp = QString("[%1:%2]:成功连接").arg(itsip).arg(itsport); ui->textEditRead->setText(temp); connect(tcpSocket, &QTcpSocket::readyRead, [=]() { QByteArray array = tcpSocket->readAll(); ui->textEditRead->append(array); getinformation(array); databasewindow.on_buttonGetnew_clicked(); } ); } ); } TCPServerWidget::~TCPServerWidget() { delete ui; } bool TCPServerWidget::checkid(QString checkid) { QString tempid; QSqlQuery query(db); bool flag = false; query.exec("select card_id from student"); qDebug() << "select card_id from student"; while(query.next()){ tempid = query.value(0).toString(); if(checkid == tempid){ flag = true; break; } } return flag; } QString TCPServerWidget::getid(QString sno) { QString id; id = "0not_stu"; QSqlQuery query(db); query.exec("select card_id from student where sno='"+sno+"'"); qDebug() << "select card_id from student where sno='"+sno+"'"; while(query.next()){ id = query.value(0).toString(); } return id; } QString TCPServerWidget::gethowlong(QString in_time,QString tempera) { QString howlong1,howlong2; QString order1="pass"; int howlong3,tempera1; QSqlQuery query(db); query.exec("SELECT TIME_TO_SEC('"+in_time+"')-TIME_TO_SEC(out_time),SEC_TO_TIME(TIME_TO_SEC('"+in_time+"')-TIME_TO_SEC(out_time)) " "FROM goout WHERE TIME_TO_SEC(out_time)<=TIME_TO_SEC('"+in_time+"') ORDER BY TIME_TO_SEC(out_time) DESC"); qDebug() << "SELECT TIME_TO_SEC('"+in_time+"')-TIME_TO_SEC(out_time),SEC_TO_TIME(TIME_TO_SEC('"+in_time+"')-TIME_TO_SEC(out_time)) " "FROM goout WHERE TIME_TO_SEC(out_time)<=TIME_TO_SEC('"+in_time+"') ORDER BY TIME_TO_SEC(out_time) DESC"; if(query.next()){ howlong1 = query.value(0).toString(); howlong2 = query.value(1).toString(); }else { howlong1 = "1"; howlong2 = "00:00:01"; } howlong3 = howlong1.toInt(); tempera1 = tempera.toInt(); if(howlong3 > 3) { order1 = "2time_over"; } if(tempera1>28) { order1 = "1high_temp"; } if(howlong3 > 3 && tempera1 > 28) { order1 = "3time_over;high_temp"; } if(order1 == "pass") { tcpSocket->write(order1.toUtf8().data()); }else { tcpSocket->write(order1.toUtf8().data()); } qDebug() << howlong1 <<howlong2 <<order1; return howlong2; } void TCPServerWidget::getinformation(QByteArray arr) { QString str(arr); QString temp,id,time,howlong,temperature,sno; //接受到的字符串进行裁剪 if(str.startsWith("OUT:")) { temp=str.mid(4); id = temp.mid(3,(temp.indexOf(";time.")-3)); if(checkid(id)) { ui->textEditRead->append(id); temp = temp.mid(temp.indexOf(";time.")); time = temp.mid(6,(temp.indexOf(";temperature.")-6)); ui->textEditRead->append(time); temp = temp.mid(temp.indexOf(";temperature.")); temperature = temp.mid(13); ui->textEditRead->append(temperature); QSqlQuery query2(db); query2.exec("insert into goout(out_card_id,out_time,out_temperature) values('" + id + "','"+time+"','"+temperature+"')"); qDebug() << "insert into goout(out_card_id,out_time,out_temperature) values('" + id + "','"+time+"','"+temperature+"')"; } else { QMessageBox::critical(this,"错误","没有这个id号("+id+")。","确定"); return; } }else if(str.startsWith("IN:")) { temp=str.mid(3); id = temp.mid(3,(temp.indexOf(";time.")-3)); if(checkid(id)) { ui->textEditRead->append(id); temp = temp.mid(temp.indexOf(";time.")); time = temp.mid(6,(temp.indexOf(";howlong.")-6)); ui->textEditRead->append(time); temp = temp.mid(temp.indexOf(";howlong.")); howlong = temp.mid(9,(temp.indexOf(";temperature.")-9)); ui->textEditRead->append(howlong); temp = temp.mid(temp.indexOf(";temperature.")); temperature = temp.mid(13); ui->textEditRead->append(temperature); QSqlQuery query2(db); query2.exec("insert into enter(in_card_id,in_time,howlong,in_temperature) values('" + id + "','"+time+"','"+howlong+"','"+temperature+"')"); qDebug() << "insert into enter(in_card_id,in_time,howlong,in_temperature) values('" + id + "','"+time+"','"+howlong+"','"+temperature+"')"; } else { QMessageBox::critical(this,"错误","没有这个id号("+id+")。","确定"); return; } }else if(str.startsWith("SNOOUT:")) { temp=str.mid(7); sno = temp.mid(4,(temp.indexOf(";time.")-4)); id = getid(sno); if(id == "0not_stu") { tcpSocket->write(id.toUtf8().data()); }else { ui->textEditRead->append(id); temp = temp.mid(temp.indexOf(";time.")); time = temp.mid(6,(temp.indexOf(";temperature.")-6)); ui->textEditRead->append(time); temp = temp.mid(temp.indexOf(";temperature.")); temperature = temp.mid(13); bool ok; int temprea = temperature.toInt(&ok); QString order; if(temprea > 28) { order = "1high_temp"; tcpSocket->write(order.toUtf8().data()); }else { order = "pass"; tcpSocket->write(order.toUtf8().data()); } ui->textEditRead->append(temperature); QSqlQuery query2(db); query2.exec("insert into goout(out_card_id,out_time,out_temperature) values('" + id + "','"+time+"','"+temperature+"')"); qDebug() << "insert into goout(out_card_id,out_time,out_temperature) values('" + id + "','"+time+"','"+temperature+"')"; } }else if(str.startsWith("SNOIN:")) { temp=str.mid(6); sno = temp.mid(4,(temp.indexOf(";time.")-4)); id = getid(sno); if(id == "0not_stu") { tcpSocket->write(id.toUtf8().data()); }else { ui->textEditRead->append(id); temp = temp.mid(temp.indexOf(";time.")); time = temp.mid(6,(temp.indexOf(";temperature.")-6)); ui->textEditRead->append(time); temp = temp.mid(temp.indexOf(";temperature.")); temperature = temp.mid(13); ui->textEditRead->append(temperature); howlong = gethowlong(time,temperature); QSqlQuery query2(db); query2.exec("insert into enter(in_card_id,in_time,howlong,in_temperature) values('" + id + "','"+time+"','"+howlong+"','"+temperature+"')"); qDebug() << "insert into enter(in_card_id,in_time,howlong,in_temperature) values('" + id + "','"+time+"','"+howlong+"','"+temperature+"')"; } }else if(str.startsWith("LK:")) { temp=str.mid(3); id = temp.mid(3,(temp.indexOf(";sno.")-3)); ui->textEditRead->append(id); temp = temp.mid(temp.indexOf(";sno.")); sno = temp.mid(5); ui->textEditRead->append(sno); QSqlQuery query2(db); query2.exec("insert into student(card_id,sno) values('" + id + "','"+sno+"')"); qDebug() << "insert into student(card_id,sno) values('" + id + "','"+sno+"')"; QSqlQuery query3(db); query3.exec("select card_id from student where sno='"+sno+"'"); qDebug() << "select card_id from student where sno='"+sno+"'"; QString idtest; while(query3.next()){ idtest = query3.value(0).toString(); } if(idtest == id) { QString order4 = "inputsno"; tcpSocket->write(order4.toUtf8().data()); } } } void TCPServerWidget::on_buttonSend_clicked() { if(NULL==tcpSocket) { return; } //获取编辑区内容 QString str = ui->textEditWrite->toPlainText(); //给对方发送数据 tcpSocket->write(str.toUtf8().data()); } void TCPServerWidget::on_buttonShowDB_clicked() { databasewindow.show(); }
/* le bouton poussoir est connecté au pin 2 pour un mode INPUT_PULLUP la Led est connectée au pins 4 avec une résistance de 220Ω */ //déclaration des variables int pinBouton, pinLed; boolean etatAllumage; void setup() { //initialisation des variables Serial.begin(9600); pinBouton = 8; pinLed = 9; etatAllumage=0; //définition des modes pinMode(pinBouton, INPUT_PULLUP); pinMode(pinLed, OUTPUT); } void loop() { Serial.print(etatAllumage); if (etatAllumage) //on teste si etatAllumage est à 1 { digitalWrite(pinLed, HIGH);//on allume la LED } else //sinon { digitalWrite(pinLed, LOW); //on éteint la LED } //lecture de l'état du bouton et stockage dans etatBouton boolean etatPinBouton = digitalRead(pinBouton); Serial.println(etatPinBouton); //test des conditions if (!etatPinBouton)//si bouton appuyé (donc le pin indique 0 car il est en mode INPUT_PULLUP) { if (etatAllumage) //si etatAllumage à 1 { etatAllumage=0; //on le passe à 0 } else //sinon { etatAllumage=1; //on le passe à 1 } } delay(130); }
// ___________________________________________________________________________ // ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ? // FILENAME WinShell.cpp // // CREATED DG-191298 // // DESCRIPION Win95/NT4.0 ++ shell interface functions // I.e. stuff using the IShellFolder object, etc. // // Win32 only // ___________________________________________________________________________ // ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ? #include "core/pch.h" #include <limits.h> #include "platforms/windows/win_handy.h" #include "platforms/windows/windows_ui/winshell.h" #include "platforms/windows/windows_ui/registry.h" #include "platforms/windows_common/utils/fileinfo.h" #include "platforms/windows/utils/com_helpers.h" #include "platforms/windows/utils/win_icon.h" #include "platforms/windows/WindowsShortcut.h" #include "adjunct/desktop_util/shortcuts/DesktopShortcutInfo.h" #include "modules/util/str.h" #include "modules/util/gen_str.h" #include "modules/util/opfile/opfile.h" #include "modules/url/url_man.h" extern HINSTANCE hInst; // ___________________________________________________________________________ // ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ? // GetShellProtocolHandler // ___________________________________________________________________________ // BOOL GetShellProtocolHandler ( IN const uni_char* pszProtocol, // IN e.g "mailto" (an opt. trailing colon is ok) OUT uni_char * pszAppDescription, // OUT e.g "Eudora" (not always awailable) IN int nMaxAppDescriptionLen, // IN max strlen() for 'pszAppDescription' OUT uni_char * pszOpenCommand, // OUT value of HKEY_CLASSES_ROOT/shell/open/command IN int nMaxOpenCommandLen // IN max strlen() for 'pszOpenCommand' ) { OpString protocol; if (OpStatus::IsError(protocol.Set(pszProtocol))) return FALSE; // // Reset // if (pszAppDescription && nMaxAppDescriptionLen>0) *pszAppDescription = 0; if (pszOpenCommand && nMaxOpenCommandLen>0) *pszOpenCommand = 0; // // Get rid of trailing ':' if present // if (IsStr(protocol)) uni_strtok(protocol, UNI_L(": /\\")); // // Verify params // if (protocol.IsEmpty()) return FALSE; // // Get the HKEY_CLASSES_ROOT/shell/open/command value // uni_char szKeyName[MAX_PATH] = UNI_L(""); uni_char szText[MAX_PATH] = UNI_L(""); uni_char szCommand[MAX_PATH] = UNI_L(""); if (OpRegReadStrValue(HKEY_CLASSES_ROOT, protocol.CStr(), UNI_L("URL Protocol"), szText, sizeof(szText)) != ERROR_SUCCESS) return FALSE; uni_sprintf(szKeyName, UNI_L("%s\\shell\\open\\command"), protocol.CStr()); if (OpRegReadStrValue( HKEY_CLASSES_ROOT, szKeyName, NULL, szCommand, sizeof(szCommand)) != ERROR_SUCCESS || !IsStr(szCommand)) return FALSE; // // Protcol handler command found // if (pszOpenCommand) { OpString application; if (!application.Reserve(MAX_PATH)) return TRUE; ExpandEnvironmentStrings(szCommand, application, application.Capacity()); uni_strlcpy(pszOpenCommand, application, nMaxOpenCommandLen); } // // Try to find the description. // if (pszAppDescription) { BOOL fClientFound= TRUE; BOOL fIsMailto = uni_strni_eq(protocol, "MAILTO", 7); // BOOL fIsNews = uni_strni_eq(protocol, "NEWS", 5); // BOOL fIsNntp = uni_strni_eq(protocol, "NNTP", 5); uni_strcpy(szKeyName, UNI_L("SOFTWARE\\Clients")); if (fIsMailto) uni_strcat(szKeyName, UNI_L("\\Mail")); else fClientFound = FALSE; // DGTODO - don't know how to handle this properly if (fClientFound) { // // Enum all clients to find the matching one. // OpAutoHKEY keyClients; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_READ, &keyClients) == ERROR_SUCCESS) { DWORD index = 0; bool fStopEnum = false; do { uni_char szClient[MAX_PATH] = UNI_L(""); DWORD size = MAX_PATH; if (RegEnumKeyEx(keyClients, index, szClient, &size, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) break; uni_char szCmd[MAX_PATH] = UNI_L(""); uni_char szKey[MAX_PATH] = UNI_L(""); uni_snprintf(szKey, MAX_PATH, UNI_L("%s\\Protocols\\%s\\shell\\open\\command"), szClient, protocol); if ( OpRegReadStrValue( keyClients, szKey, NULL, szCmd, sizeof(szCmd)) == ERROR_SUCCESS) { if (uni_stricmp(szCmd, szCommand) == 0) { // // found it // OpRegReadStrValue( keyClients, szClient, NULL, pszAppDescription, nMaxAppDescriptionLen); fStopEnum = true; } } ++ index; } while (!fStopEnum ); } } else { //Just try to extract the description directly from the application OpString applicationpath; if (!applicationpath.Reserve(MAX_PATH)) return TRUE; uni_sprintf(szKeyName, UNI_L("%s\\shell\\open\\command"), protocol.CStr()); if (OpRegReadStrValue( HKEY_CLASSES_ROOT, szKeyName, NULL, applicationpath, applicationpath.Capacity()) == ERROR_SUCCESS) { //The applicationpath string can contain parameters etc. try to strip these OpString application; if (!application.Reserve(MAX_PATH)) return TRUE; uni_char *applicationpath_stripped = szCommand; OpString app; if(applicationpath.FindFirstOf('\"') == 0) { OpStringC app_tmp(applicationpath.CStr()+1); int pos2 = app_tmp.FindFirstOf('\"'); if(pos2 != KNotFound) { app.Set(app_tmp, pos2); applicationpath_stripped = app.CStr(); } } ExpandEnvironmentStrings(applicationpath_stripped, application, application.Capacity()); OpString desc; if (!desc.Reserve(MAX_PATH)) return TRUE; GetFileDescription(application, &desc); if (desc.HasContent()) { uni_strlcpy(pszAppDescription, desc, nMaxAppDescriptionLen); } } } } return TRUE; } enum { ASSOCF_INIT_NOREMAPCLSID = 0x00000001, // do not remap clsids to progids ASSOCF_INIT_BYEXENAME = 0x00000002, // executable is being passed in ASSOCF_OPEN_BYEXENAME = 0x00000002, // executable is being passed in ASSOCF_INIT_DEFAULTTOSTAR = 0x00000004, // treat "*" as the BaseClass ASSOCF_INIT_DEFAULTTOFOLDER = 0x00000008, // treat "Folder" as the BaseClass ASSOCF_NOUSERSETTINGS = 0x00000010, // dont use HKCU ASSOCF_NOTRUNCATE = 0x00000020, // dont truncate the return string ASSOCF_VERIFY = 0x00000040, // verify data is accurate (DISK HITS) ASSOCF_REMAPRUNDLL = 0x00000080, // actually gets info about rundlls target if applicable ASSOCF_NOFIXUPS = 0x00000100, // attempt to fix errors if found ASSOCF_IGNOREBASECLASS = 0x00000200, // dont recurse into the baseclass ASSOCF_INIT_IGNOREUNKNOWN = 0x00000400, // dont use the "Unknown" progid, instead fail }; typedef DWORD ASSOCF; typedef enum { ASSOCSTR_COMMAND = 1, // shell\verb\command string ASSOCSTR_EXECUTABLE, // the executable part of command string ASSOCSTR_FRIENDLYDOCNAME, // friendly name of the document type ASSOCSTR_FRIENDLYAPPNAME, // friendly name of executable ASSOCSTR_NOOPEN, // noopen value ASSOCSTR_SHELLNEWVALUE, // query values under the shellnew key ASSOCSTR_DDECOMMAND, // template for DDE commands ASSOCSTR_DDEIFEXEC, // DDECOMMAND to use if just create a process ASSOCSTR_DDEAPPLICATION, // Application name in DDE broadcast ASSOCSTR_DDETOPIC, // Topic Name in DDE broadcast ASSOCSTR_INFOTIP, // info tip for an item, or list of properties to create info tip from ASSOCSTR_QUICKTIP, // same as ASSOCSTR_INFOTIP, except, this list contains only quickly retrievable properties ASSOCSTR_TILEINFO, // similar to ASSOCSTR_INFOTIP - lists important properties for tileview ASSOCSTR_CONTENTTYPE, // MIME Content type ASSOCSTR_DEFAULTICON, // Default icon source ASSOCSTR_SHELLEXTENSION, // Guid string pointing to the Shellex\Shellextensionhandler value. ASSOCSTR_MAX // last item in enum... } ASSOCSTR; typedef HRESULT (STDAPICALLTYPE *LPFNASSOCQUERYSTRING)(ASSOCF, ASSOCSTR, LPCWSTR, LPCWSTR, LPWSTR, DWORD *); LPFNASSOCQUERYSTRING s_AssocQueryString = NULL; HMODULE s_shlwapi = NULL; /*************************************** Get application associated to a filename ****************************************/ OP_STATUS GetShellFileHandler ( const uni_char* file_name, // IN e.g "mp3" *or* "C:\metallica - sad but true.mp3" OpString& app_name // OUT e.g "C:\Program Files\winamp.exe ) { if (!s_shlwapi) { // This API was introduced with Internet Explorer 5, // and we sure don't want to depend on that, so load it on demand HMODULE shlwapi = WindowsUtils::SafeLoadLibrary(UNI_L("SHLWAPI.DLL")); if (!shlwapi) shlwapi = (HMODULE)-1; else s_AssocQueryString = (LPFNASSOCQUERYSTRING)GetProcAddress(shlwapi, "AssocQueryStringW"); s_shlwapi = shlwapi; } OpString extension; extension.Set(file_name); if (extension.IsEmpty()) return OpStatus::ERR; int ext_start = extension.FindLastOf('.'); if(ext_start > 0) { extension.Delete(0,ext_start); } else if (ext_start < 0) { extension.Insert(0, UNI_L("."), 1); } if (s_AssocQueryString) { DWORD size; HRESULT ret = s_AssocQueryString(ASSOCF_NOTRUNCATE | ASSOCF_INIT_IGNOREUNKNOWN, ASSOCSTR_COMMAND, extension.CStr(), NULL, NULL, &size); if (ret != S_FALSE) return OpStatus::ERR; if(!app_name.Reserve(size)) return OpStatus::ERR_NO_MEMORY; ret = s_AssocQueryString(ASSOCF_NOTRUNCATE | ASSOCF_INIT_IGNOREUNKNOWN, ASSOCSTR_COMMAND, extension.CStr(), NULL, app_name.CStr(), &size); if (ret != S_OK) return OpStatus::ERR; if (app_name.Compare(UNI_L("%1"),2) == 0 || app_name.Compare(UNI_L("\"%1\""),4) == 0) { app_name.Empty(); RETURN_IF_ERROR(app_name.AppendFormat(UNI_L("\"%s\""), file_name)); } else ParseShellCommand(app_name); return OpStatus::OK; } else { uni_char szTmpDir[_MAX_PATH]; uni_char szTmpFile[_MAX_PATH]; GetTempPath(_MAX_PATH, szTmpDir); UINT ret = GetTempFileName(szTmpDir, UNI_L("Opr"), 1818 , szTmpFile); if(ret != 0) { OpString szTmpFileExt; RETURN_VALUE_IF_ERROR(szTmpFileExt.Set(szTmpFile), FALSE); RETURN_VALUE_IF_ERROR(szTmpFileExt.Append(extension), FALSE); HANDLE hExtFile = CreateFile(szTmpFileExt,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_ARCHIVE | FILE_FLAG_DELETE_ON_CLOSE, NULL); if (hExtFile != INVALID_HANDLE_VALUE) { if(app_name.Reserve(MAX_PATH) == NULL) { CloseHandle(hExtFile); return OpStatus::ERR_NO_MEMORY; } HINSTANCE fRes = FindExecutable(szTmpFileExt, NULL, app_name.CStr()); if (fRes > (HINSTANCE)32) { DWORD res = GetShortPathName(szTmpFileExt, szTmpFile, MAX_PATH); CloseHandle(hExtFile); if (res == 0 || res > MAX_PATH) return OpStatus::ERR; if (app_name.CompareI(szTmpFile) == 0) RETURN_IF_ERROR(app_name.Set(file_name)); RETURN_IF_ERROR(app_name.Insert(0, "\"")); return app_name.Append("\""); } CloseHandle(hExtFile); } } return GetMainShellFileHandler (extension, app_name); } } LPITEMIDLIST GetPidlFromPath( HWND hWndOwner, IShellFolder *pIShellFolder, LPCTSTR tchPath) { ITEMIDLIST * pidl = NULL; // return value WCHAR * pwchPathToUse; // Make sure we have an unicode string pwchPathToUse = (WCHAR*)tchPath; OP_ASSERT( pwchPathToUse); if( pwchPathToUse) { // // Get the pidl from that path. // ULONG nCharsParsed; pIShellFolder->ParseDisplayName( hWndOwner, NULL, pwchPathToUse, &nCharsParsed, &pidl, NULL); // if the string was allocated then free it. if( pwchPathToUse != (WCHAR*)tchPath) delete [] pwchPathToUse; } return pidl; } ULONG GetRefCount( IUnknown * pIUnknown) { pIUnknown->AddRef(); return pIUnknown->Release(); } void SplitPath( const uni_char *szPath, uni_char *szDirectory, uni_char *szFileName) { uni_char * szFileNamePtr; OP_ASSERT( szPath && szDirectory && szFileName); uni_strlcpy( szDirectory, szPath, _MAX_PATH); szFileNamePtr = StringFileName( szDirectory); uni_strlcpy( szFileName, szFileNamePtr, _MAX_FNAME); *szFileNamePtr = 0; } // *** DG-201298 // ___________________________________________________________________________ // ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ? // GetShortcutTarget // // Get's the accosiated path (and description) for a shortcut file. // If the file is not a shortcut or an error occurs the link file name is // used. // ___________________________________________________________________________ // HRESULT GetShortcutTarget ( HWND hWndParent, // The shell might want to display some messages LPCTSTR pszShortcutFile, // Path to shortcutfile BOOL fResolve, // Resolve broken shortcuts ? LPTSTR pszPath, // OUT: Resolved path to the file pointed to by the shortcut int cbPath, // Size in bytes of 'pszPath' LPTSTR pszDescription, // OUT: Filedescription (use NULL if not needed) int cbDescription // Size in bytes of 'szDescription' ) { HRESULT hres; IShellLink* psl; WIN32_FIND_DATA wfd; // We return the filename if the file si not a shortcut. int len = min((size_t)cbPath, uni_strlen(pszShortcutFile)); memmove(pszPath, pszShortcutFile, UNICODE_SIZE(len)); // Memmove because they might overlap. pszPath[len] = 0; // Get a pointer to the IShellLink interface. hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&psl); if (SUCCEEDED(hres)) { IPersistFile* ppf; // Get a pointer to the IPersistFile interface. hres = psl->QueryInterface(IID_IPersistFile, (void**)&ppf); if (SUCCEEDED(hres)) { // Ensure shortcutpath is Unicode. unsigned short wsz[MAX_PATH]; uni_strcpy(wsz, pszShortcutFile); // Load the shell link. hres = ppf->Load( wsz, STGM_READ); if (SUCCEEDED(hres)) { // Resolve the link ? if( fResolve) hres = psl->Resolve(hWndParent, SLR_ANY_MATCH); if (SUCCEEDED(hres)) { // Get the path to the link target. hres = psl->GetPath( pszPath, cbPath, (WIN32_FIND_DATA *)&wfd, 0); if( SUCCEEDED(hres) && pszDescription ) { // Get the description of the target. hres = psl->GetDescription( pszDescription, cbDescription); } } } // Release pointer to IPersistFile interface. ppf->Release(); } // Release pointer to IShellLink interface. psl->Release(); } return hres; } BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCTSTR lpszType, LPTSTR lpszName, LONG_PTR lParam) { LONG_PTR *res_name_or_id = (LONG_PTR *)lParam; if (IS_INTRESOURCE(lpszName)) { *res_name_or_id = (LONG_PTR)lpszName; } else { OpString *res_name = (OpString*)*res_name_or_id; res_name->Set(lpszName); } //We need only the first icon return FALSE; } OP_STATUS GetFirstIconFromBinary(const uni_char* binary, OpBitmap** icon, INT32 icon_size) { DWORD flags; if (IsSystemWinVista()) flags = LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE; else flags = DONT_RESOLVE_DLL_REFERENCES; // DSK-337506 //Open the binary file HMODULE module = LoadLibraryEx(binary, NULL, flags); if (!module) return OpStatus::ERR_FILE_NOT_FOUND; HICON res_icon = NULL; do { OpString res_name; LONG_PTR res_id_or_name = (LONG_PTR)&res_name; //Find the first RT_GROUP_ICON //forget about the return value - it will return FALSE, indicating an error according to the documentation, //but it actually does that because EnumResNameProc tells it to stop, not because it failed EnumResourceNames(module, RT_GROUP_ICON, EnumResNameProc, (LONG_PTR)&res_id_or_name); if (res_id_or_name == (INTPTR)&res_name && res_name.IsEmpty()) break; //Find the address of the first RT_GROUP_ICON HRSRC res_info = FindResource(module, (res_id_or_name == (INTPTR)&res_name)?res_name.CStr():MAKEINTRESOURCE((int)res_id_or_name), RT_GROUP_ICON); if (!res_info) break; //Load the RT_GROUP_ICON from previously obtained address HGLOBAL res_data = LoadResource(module, res_info); if (!res_data) break; LPBYTE resource = (LPBYTE)LockResource(res_data); if (!resource) break; //Gets the id of the icon in the group that has is closest to the current color depth and the required size int res_id = LookupIconIdFromDirectoryEx(resource, TRUE, icon_size, icon_size, LR_DEFAULTCOLOR); if (!res_id) break; //Gets the address of that icon res_info = FindResource(module, MAKEINTRESOURCE(res_id), RT_ICON); if (!res_info) break; //Load the icon from previously obtained address res_data = LoadResource(module, res_info); if (!res_data) break; resource = (LPBYTE)LockResource(res_data); if (!resource) break; //Copies the icon from the resource, making it usable res_icon = CreateIconFromResourceEx(resource, SizeofResource(module, res_info), TRUE, 0x00030000, icon_size, icon_size, LR_DEFAULTCOLOR); } while (0); FreeLibrary(module); if (!res_icon) { return OpStatus::ERR; } OP_STATUS err = IconUtils::CreateIconBitmap(icon, res_icon); DestroyIcon(res_icon); return err; } OP_STATUS GetFileHandlerInfo(const uni_char* handler, OpString *filedescription, OpBitmap** icon, INT32 icon_size) { // unquote handler's name (ParseShellCommand() ensures that it is quoted at this point) uni_char* position = (uni_char*)handler + 1; uni_char* file_end = uni_strchr(position, '"'); *file_end = 0; // if handler is rundll32 and is followed by quoted argument then get info about that argument instead if (uni_stristr(position, UNI_L("rundll32")) != NULL) { uni_char* arg_start = uni_strchr(file_end + 1, '"'); if (arg_start) { ++ arg_start; uni_char* arg_end = uni_strchr(arg_start, '"'); if (arg_end) { *file_end = '"'; position = arg_start; file_end = arg_end; *file_end = 0; } } } OP_STATUS err1 = GetFileDescription(position, filedescription); OP_STATUS err2 = GetFirstIconFromBinary(position, icon, icon_size); *file_end = '"'; if (OpStatus::IsError(err1)) filedescription->Empty(); if (OpStatus::IsError(err2)) *icon = NULL; RETURN_IF_ERROR(err1); return err2; } OP_STATUS GetFileDescription(const uni_char* file, OpString* filedescription, OpString* productName) { // DWORD filetype = 0; // GetBinaryType(file, &filetype); if (!file) return OpStatus::ERR; WindowsCommonUtils::FileInformation fileinfo; UniString description; UniString prod_name; if (OpStatus::IsSuccess(fileinfo.Construct(file))) { if (filedescription) if (OpStatus::IsError(fileinfo.GetInfoItem(UNI_L("FileDescription"), description))) OpStatus::Ignore(fileinfo.GetInfoItem(UNI_L("FileDescription"), description, UNI_L("040904E4"))); if (productName) if (OpStatus::IsError(fileinfo.GetInfoItem(UNI_L("ProductName"), prod_name))) OpStatus::Ignore(fileinfo.GetInfoItem(UNI_L("ProductName"), prod_name, UNI_L("040904E4"))); } //(julienp)Couldn't find resource information in the file. //We just return the filename without extension. OpString filename; const uni_char* name = uni_strrchr(file, '\\'); RETURN_IF_ERROR(filename.Set(name? name + 1: file)); uni_char* ext = uni_strrchr(filename.CStr(), '.'); if(ext) *ext=0; if (filedescription && description.IsEmpty()) { RETURN_IF_ERROR(filedescription->Set(filename)); } else if (filedescription) { const uni_char* description_str; RETURN_IF_ERROR(description.CreatePtr(&description_str, TRUE)); //TODO: Use UniString to OpString conversion function when available RETURN_IF_ERROR(filedescription->Set(description_str)); } if (productName && prod_name.IsEmpty()) { RETURN_IF_ERROR(productName->Set(filename)); } else if (productName) { const uni_char* prod_name_str; RETURN_IF_ERROR(prod_name.CreatePtr(&prod_name_str, TRUE)); //TODO: Use UniString to OpString conversion function when available RETURN_IF_ERROR(productName->Set(prod_name_str)); } return OpStatus::OK; } OP_STATUS GetShellDefaultIcon (const uni_char* file_name, OpBitmap** icon, INT32 icon_size) { uni_char szTmpDir[_MAX_PATH]; uni_char szTmpFile[_MAX_PATH]; OpString extension; extension.Set(file_name); if (extension.IsEmpty()) return OpStatus::ERR; int ext_start = extension.FindLastOf('.'); if (ext_start > 0) { extension.Delete(0,ext_start); } UINT ret = GetTempPath(_MAX_PATH, szTmpDir); if (ret == 0 || ret > _MAX_PATH) return OpStatus::ERR; ret = GetTempFileName(szTmpDir, UNI_L("Opr"), 1818 , szTmpFile); if(ret == 0) return OpStatus::ERR; OpString szTmpFileExt; RETURN_IF_ERROR(szTmpFileExt.Set(szTmpFile)); RETURN_IF_ERROR(szTmpFileExt.Append(extension)); HANDLE hExtFile = CreateFile(szTmpFileExt.CStr(),GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_ARCHIVE | FILE_FLAG_DELETE_ON_CLOSE, NULL); if (hExtFile == INVALID_HANDLE_VALUE) return OpStatus::ERR; OP_STATUS err = IconUtils::CreateIconBitmap(icon, szTmpFileExt.CStr(), icon_size); CloseHandle(hExtFile); return err; /* OpString ext; ext.Set(file_name); int ext_start = ext.FindLastOf('.'); if(ext_start > -1) { ext.Set(ext.SubString(ext_start)); } WCHAR filetype[256]; // registry name for this filetype LONG filetypelen = sizeof(filetype); // length of above if(RegQueryValueW(HKEY_CLASSES_ROOT, ext.CStr(), filetype, &filetypelen) == ERROR_SUCCESS) { filetypelen /= sizeof(WCHAR); filetype[filetypelen] = '\0'; OpString typekey; OpString icon_string; LONG commandlen = _MAX_PATH; if (!icon_string.Reserve(commandlen)) return OpStatus::ERR_NO_MEMORY; typekey.Set(filetype); typekey.Append(UNI_L("\\DefaultIcon")); // Check registry, HKEY_CLASS_ROOT\<filetype>\DefaultIcon if (RegQueryValueW(HKEY_CLASSES_ROOT, typekey.CStr(), icon_string.CStr(), &commandlen) == ERROR_SUCCESS) { const uni_char comma[2]=UNI_L(","); int comma_position = icon_string.FindLastOf(comma[0]); if (get_big_icon) { if (comma_position != KNotFound && ExtractIconEx(icon_string.SubString(0,comma_position).CStr(), uni_atoi(icon_string.SubString(comma_position+1)), &icon, NULL, 1)==1) return OpStatus::OK; } else { if (comma_position != KNotFound && ExtractIconEx(icon_string.SubString(0,comma_position).CStr(), uni_atoi(icon_string.SubString(comma_position+1)), NULL, &icon, 1)==1) return OpStatus::OK; } } }*/ } OP_STATUS GetMainShellFileHandler (const OpString& extension, OpString& app_command) { OpString filetype; RETURN_IF_ERROR(OpSafeRegQueryValue(HKEY_CLASSES_ROOT, extension.CStr(), filetype)); return GetShellCommand(filetype, app_command); } OP_STATUS AddAppToList(OpString *app_command, OpVector<OpString>& app_name_list, OpString *excluded_app) { OpAutoPtr<OpString> app_command_ap(app_command); if (app_command->IsEmpty()) return OpStatus::OK; if (!excluded_app || (excluded_app && app_command->FindI(*excluded_app) == KNotFound)) { for (UINT32 i = 0; i < app_name_list.GetCount() ; i++) if (!app_command->CompareI(*(app_name_list.Get(i)))) return OpStatus::OK; RETURN_IF_ERROR(app_name_list.Add(app_command)); app_command_ap.release(); } else if (excluded_app) { int excl_len = excluded_app->Length(); if (excl_len >= 5 && !excluded_app->SubString(excl_len-5, 4).CompareI(".dll") && excluded_app->CompareI("rundll", 6)) { excluded_app->Set(*app_command); } } return OpStatus::OK; } OP_STATUS ExtractOpenWithData(HKEY root_key, const uni_char* key_name, BOOL from_value_datas, BOOL from_key_names, BOOL as_prog_id, OpVector<OpString>& app_name_list, OpString *excluded_app) { OpAutoHKEY extregkey; if (RegOpenKeyEx(root_key, key_name, 0, KEY_READ, &extregkey) == ERROR_SUCCESS) { DWORD n_subkeys; DWORD max_key_name_length; DWORD n_values; DWORD max_name_length; DWORD max_data_length; if (RegQueryInfoKey(extregkey, NULL, NULL, NULL, &n_subkeys, &max_key_name_length, NULL, &n_values, &max_name_length, &max_data_length, NULL, NULL) == ERROR_SUCCESS) { OpString value_name; RETURN_OOM_IF_NULL(value_name.Reserve(max_name_length+1)); OpString value_data; if (from_value_datas) { RETURN_OOM_IF_NULL(value_data.Reserve(max_data_length/sizeof(uni_char))); } for (UINT32 i = 0; i<n_values; i++) { DWORD name_length = max_name_length+1; DWORD data_length = max_data_length; DWORD value_type; if (RegEnumValue(extregkey, i, value_name.CStr(), &name_length, NULL, &value_type, from_value_datas ? (LPBYTE)value_data.CStr() : NULL, from_value_datas ? &data_length : NULL) == ERROR_SUCCESS && (!from_value_datas || value_type== REG_SZ && value_name.Length()==1 /* exclude "MRUList" */)) { OpString* app_command = new OpString; RETURN_OOM_IF_NULL(app_command); OP_STATUS err; if (from_value_datas) if (as_prog_id) err = GetShellCommand(value_data, *app_command); else err = GetAppCommand(value_data, *app_command); else if (as_prog_id) err = GetShellCommand(value_name, *app_command); else err = GetAppCommand(value_name, *app_command); if (OpStatus::IsSuccess(err)) { RETURN_IF_ERROR(AddAppToList(app_command, app_name_list, excluded_app)); } else delete app_command; } } if (from_key_names) { OpString key_name; RETURN_OOM_IF_NULL(key_name.Reserve(max_key_name_length+1)); for (UINT32 i=0;i<n_subkeys;i++) { DWORD name_length = max_key_name_length+1; if (RegEnumKeyEx(extregkey, i, key_name.CStr(), &name_length, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { OpString* app_command = new OpString; RETURN_OOM_IF_NULL(app_command); OP_STATUS err; if (as_prog_id) err = GetShellCommand(key_name, *app_command); else err = GetAppCommand(key_name, *app_command); if (OpStatus::IsSuccess(err)) { RETURN_IF_ERROR(AddAppToList(app_command, app_name_list, excluded_app)); } else delete app_command; } } } } } return OpStatus::OK; } OP_STATUS GetAllShellFileHandlers (const uni_char* file_name, OpVector<OpString>& app_name_list, OpString *excluded_app) { OpString extkey; extkey.Set(file_name); if (extkey.IsEmpty()) return OpStatus::ERR; int ext_start = extkey.FindLastOf('.'); if (ext_start > 0) { extkey.Delete(0,ext_start); } OpAutoPtr<OpString> main_handler = new OpString; RETURN_OOM_IF_NULL(main_handler.get()); if (OpStatus::IsSuccess(GetMainShellFileHandler(extkey, *main_handler))) { if (main_handler->HasContent() && (!excluded_app || main_handler->FindI(*excluded_app) == KNotFound)) { RETURN_IF_ERROR(app_name_list.Add(main_handler.get())); main_handler.release(); } else if (main_handler->HasContent() && excluded_app && !excluded_app->SubString(excluded_app->Length()-5, 4).CompareI(".dll") && excluded_app->SubString(0, 6).CompareI("rundll")) { RETURN_IF_ERROR(excluded_app->Set(*main_handler)); } } OpString open_with_key; RETURN_IF_ERROR(open_with_key.Set(extkey)); RETURN_IF_ERROR(open_with_key.Append("\\OpenWithList")); RETURN_IF_ERROR(ExtractOpenWithData(HKEY_CLASSES_ROOT, open_with_key.CStr(), FALSE, TRUE, FALSE, app_name_list, excluded_app)); RETURN_IF_ERROR(open_with_key.Insert(0,"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\")); RETURN_IF_ERROR(ExtractOpenWithData(HKEY_CURRENT_USER, open_with_key.CStr(), TRUE, FALSE, FALSE, app_name_list, excluded_app)); RETURN_IF_ERROR(open_with_key.Set(extkey)); RETURN_IF_ERROR(open_with_key.Append("\\OpenWithProgids")); RETURN_IF_ERROR(ExtractOpenWithData(HKEY_CLASSES_ROOT, open_with_key.CStr(), FALSE, FALSE, TRUE, app_name_list, excluded_app)); RETURN_IF_ERROR(open_with_key.Insert(0,"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\")); return ExtractOpenWithData(HKEY_CURRENT_USER, open_with_key.CStr(), FALSE, FALSE, TRUE, app_name_list, excluded_app); } OP_STATUS GetAppCommand(const OpString& app_name, OpString& app_command) { OpString appkey; RETURN_IF_ERROR(appkey.Set("Applications\\")); RETURN_IF_ERROR(appkey.Append(app_name)); return GetShellCommand(appkey, app_command); } OP_STATUS GetShellCommand(const OpString& key, OpString& app_command) { OpString typekey; RETURN_IF_ERROR(typekey.Set(key)); RETURN_IF_ERROR(typekey.Append(UNI_L("\\shell"))); OpString verb; if (OpStatus::IsSuccess(OpSafeRegQueryValue(HKEY_CLASSES_ROOT, typekey.CStr(), verb)) && verb.HasContent()) { RETURN_IF_ERROR(typekey.Append("\\")); RETURN_IF_ERROR(typekey.Append(verb)); RETURN_IF_ERROR(typekey.Append("\\command")); if (OpStatus::IsSuccess(OpSafeRegQueryValue(HKEY_CLASSES_ROOT, typekey.CStr(), app_command))) { ParseShellCommand(app_command); return OpStatus::OK; } } RETURN_IF_ERROR(typekey.Set(key)); RETURN_IF_ERROR(typekey.Append(UNI_L("\\shell\\open\\command"))); if (OpStatus::IsSuccess(OpSafeRegQueryValue(HKEY_CLASSES_ROOT, typekey.CStr(), app_command))) { ParseShellCommand(app_command); } else { RETURN_IF_ERROR(typekey.Set(key)); RETURN_IF_ERROR(typekey.Append(UNI_L("\\shell\\play\\command"))); if (OpStatus::IsSuccess(OpSafeRegQueryValue(HKEY_CLASSES_ROOT, typekey.CStr(), app_command))) { ParseShellCommand(app_command); } else { RETURN_IF_ERROR(typekey.Set(key)); RETURN_IF_ERROR(typekey.Append(UNI_L("\\shell\\edit\\command"))); if (OpStatus::IsSuccess(OpSafeRegQueryValue(HKEY_CLASSES_ROOT, typekey.CStr(), app_command))) { ParseShellCommand(app_command); } else { RETURN_IF_ERROR(typekey.Set(key)); RETURN_IF_ERROR(typekey.Append(UNI_L("\\shell"))); DWORD key_name_length = 255; uni_char key_name[255]; OP_STATUS status = OpStatus::ERR; OpAutoHKEY typeregkey; if (RegOpenKeyEx(HKEY_CLASSES_ROOT, typekey, 0, KEY_READ, &typeregkey) == ERROR_SUCCESS) { if (RegEnumKeyEx(typeregkey, 0, key_name, &key_name_length, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { RETURN_IF_ERROR(typekey.Append("\\")); RETURN_IF_ERROR(typekey.Append(key_name)); RETURN_IF_ERROR(typekey.Append("\\command")); status = OpSafeRegQueryValue(HKEY_CLASSES_ROOT, typekey.CStr(), app_command); } } if (OpStatus::IsSuccess(status)) { ParseShellCommand(app_command); } else { app_command.Empty(); return status; } } } } return OpStatus::OK; } /** Adds Chrome application command to AppList * * This function fixes DSK-301447 - Web page right click menu item "Open With" * does not show Chrome installation. * * When Chrome is not installed as a default Internet browser then application * command is not added to regular registry entries for Internet clients. * This function search Chrome specific entry. If Chrome application command * is already added to the list it will be not added second time (see * AddAppToList). * * @param app_name_list List to which will be added Chrome application command * * @return OpStatus::OK if error has not occurred */ OP_STATUS AddChromeToURLHandlers(OpVector<OpString>& app_name_list) { OpString* app_command = new OpString; RETURN_OOM_IF_NULL(app_command); if (OpStatus::IsSuccess(OpSafeRegQueryValue(HKEY_CLASSES_ROOT, UNI_L("ChromeHTML\\shell\\open\\command"), *app_command))) { ParseShellCommand(*app_command); RETURN_IF_ERROR(AddAppToList(app_command, app_name_list, NULL)); } else { delete app_command; } return OpStatus::OK; } OP_STATUS GetURLHandlers (OpVector<OpString>& app_name_list) { OpString first_key; OpString key_name; OpString commandkey; if (OpStatus::IsSuccess(OpSafeRegQueryValue(HKEY_LOCAL_MACHINE, UNI_L("SOFTWARE\\Clients\\StartMenuInternet"), key_name))) { RETURN_IF_ERROR(commandkey.Set("SOFTWARE\\Clients\\StartMenuInternet\\")); RETURN_IF_ERROR(commandkey.Append(key_name)); RETURN_IF_ERROR(commandkey.Append("\\shell\\open\\command")); RETURN_IF_ERROR(first_key.Set(key_name)); OpString* app_command = new OpString; RETURN_OOM_IF_NULL(app_command); if (OpStatus::IsSuccess(OpSafeRegQueryValue(HKEY_LOCAL_MACHINE, commandkey.CStr(), *app_command))) { ParseShellCommand(*app_command); RETURN_IF_ERROR(AddAppToList(app_command, app_name_list, NULL)); } else { delete app_command; } } OpAutoHKEY browsersregkey; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, UNI_L("SOFTWARE\\Clients\\StartMenuInternet"), 0, KEY_READ, &browsersregkey) == ERROR_SUCCESS) { DWORD n_subkeys; DWORD max_name_length; if (RegQueryInfoKey(browsersregkey, NULL, NULL, NULL, &n_subkeys, &max_name_length, NULL, NULL, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { RETURN_OOM_IF_NULL(key_name.Reserve(max_name_length+1)); for (UINT32 i=0;i<n_subkeys;i++) { DWORD name_length= max_name_length+1; if (RegEnumKeyEx(browsersregkey, i, key_name.CStr(), &name_length, NULL, NULL, NULL, NULL) == ERROR_SUCCESS && (first_key.IsEmpty() || key_name.Compare(first_key))) { RETURN_IF_ERROR(commandkey.Set("SOFTWARE\\Clients\\StartMenuInternet\\")); RETURN_IF_ERROR(commandkey.Append(key_name)); RETURN_IF_ERROR(commandkey.Append("\\shell\\open\\command")); OpString* app_command = new OpString; RETURN_OOM_IF_NULL(app_command); if (OpStatus::IsSuccess(OpSafeRegQueryValue(HKEY_LOCAL_MACHINE, commandkey.CStr(), *app_command))) { ParseShellCommand(*app_command); RETURN_IF_ERROR(AddAppToList(app_command, app_name_list, NULL)); } else { delete app_command; } } } } } RETURN_IF_ERROR(AddChromeToURLHandlers(app_name_list)); return OpStatus::OK; } void ParseShellCommand(OpString& app_command) { OP_ASSERT(app_command.HasContent()); if (app_command.IsEmpty()) return; uni_char expanded_command[MAX_PATH]; ExpandEnvironmentStrings(app_command.CStr(), expanded_command, MAX_PATH); app_command.Set(expanded_command); //No need to do any fancy stuff if this is directly a correct path (except quoting) if (PathFileExists(app_command.CStr())) { app_command.Insert(0,UNI_L("\"")); app_command.Append(UNI_L("\"")); return; } app_command.Strip(TRUE, TRUE); OpString app_parameters; BOOL quoted = app_command[0] == '"'; if(quoted) { app_command.Delete(0,1); int app_end = app_command.FindFirstOf('"'); if (app_end != KNotFound) { uni_char *quote_pos = app_command.CStr()+app_end; app_parameters.Set(quote_pos+1); *quote_pos = 0; } } else { int app_end = app_command.FindFirstOf(' '); if (app_end != KNotFound) { uni_char *space_pos = app_command.CStr()+app_end; app_parameters.Set(space_pos); *space_pos = 0; } } while (!PathFileExists(app_command)) { UINT full_exe_len = SearchPath(NULL, app_command, UNI_L(".exe"), 0, NULL, NULL); if (full_exe_len == 0) { uni_char *first_param_end; if (quoted || app_parameters.IsEmpty() || (first_param_end = uni_strchr(app_parameters.CStr()+1, ' ')) == NULL) { app_command.Empty(); return; } int next_param_pos = first_param_end - app_parameters.CStr(); app_command.Append(app_parameters, next_param_pos); app_parameters.Delete(0, next_param_pos); } else { OpString full_app_command; // Reserve two extra characters for the quotes that will be added later if (!full_app_command.Reserve(full_exe_len+1)) { app_command.Empty(); return; } SearchPath(NULL, app_command, UNI_L(".exe"), full_exe_len, full_app_command, NULL); app_command.TakeOver(full_app_command); break; } } app_command.Insert(0,UNI_L("\"")); app_command.Append(UNI_L("\"")); if (app_command.FindI(UNI_L("rundll32")) != KNotFound) { OpString dll_name; dll_name.TakeOver(app_parameters); dll_name.Strip(TRUE, TRUE); if (dll_name[0] == '"') { dll_name.Delete(0,1); int dll_end = dll_name.FindFirstOf('"'); if (dll_end != KNotFound) { uni_char *quote_pos = dll_name.CStr()+dll_end; app_parameters.Set(quote_pos+1); *quote_pos = 0; } } else { int dll_end = dll_name.FindFirstOf(' '); if (dll_end != KNotFound) { uni_char *space_pos = dll_name.CStr()+dll_end; app_parameters.Set(space_pos); *space_pos = 0; dll_end = dll_name.FindLastOf(','); if (dll_end != KNotFound) { uni_char *comma_pos = dll_name.CStr()+dll_end; app_parameters.Insert(0, comma_pos); *comma_pos = 0; } } } if (!PathFileExists(dll_name)) { int full_dll_len = SearchPath(NULL, dll_name, UNI_L(".dll"), 0, NULL, NULL); if (full_dll_len == 0) { app_command.Empty(); return; } OpString full_dll; if (!full_dll.Reserve(full_dll_len)) { app_command.Empty(); return; } SearchPath(NULL, dll_name, UNI_L(".dll"), full_dll_len, full_dll, NULL); dll_name.TakeOver(full_dll); } app_command.AppendFormat(UNI_L(" \"%s\""), dll_name.CStr()); } if (app_command.FindI(UNI_L("explorer.exe")) != KNotFound) { // This fixes DSK-331765 - "Opening zip archives with native Windows association". // The default app_command for .zip files looks like this : // %SystemRoot%\Explorer.exe /idlist,%I,%L // This string is located in registry here : HKEY_CLASSES_ROOT\CompressedFolder\shell\Open\Command // Documentation about %I : http://www.geoffchappell.com/studies/windows/shell/explorer/cmdline.htm // We are not using an ITEMIDLIST method, so the simplest way to fix is to replace it. app_parameters.ReplaceAll(UNI_L("/idlist,%I,%L"), UNI_L("%s"), 1); } uni_char* position = app_parameters.CStr(); if (position) { while ((position = uni_strchr(position, '%')) != NULL) { position++; switch (*position) { case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '*': app_parameters.Delete(position-app_parameters.CStr()-1, 2); break; case '1': case 'L': case 'l': *position = 's'; break; } } app_command.Append(app_parameters); } }
#include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; struct BankAccount { int balance = 0; int overdraft_limit = -500; void deposit(int amount) { balance += amount; cout << "deposited " << amount << ", balance now " << balance << "\n"; } void withdraw(int amount) { if (balance - amount >= overdraft_limit) { balance -= amount; cout << "withdrew " << amount << ", balance now " << balance << "\n"; } } }; struct ICommand { virtual ~ICommand() = default; virtual void call() const = 0; virtual void undo() const = 0; }; struct Command : ICommand { BankAccount& account; enum Action { deposit, withdraw } action; int amount; Command(BankAccount& account, const Action action, const int amount) : account(account), action(action), amount(amount) {} void call() const override { switch (action) { case deposit: account.deposit(amount); break; case withdraw: account.withdraw(amount); break; default: break; } } void undo() const override { switch (action) { case withdraw: account.deposit(amount); break; case deposit: account.withdraw(amount); break; default: break; } } }; struct CommandList : vector<Command>, ICommand { CommandList(const ::std::initializer_list<value_type>& _Ilist) : vector<Command>(_Ilist) {} void call() const override { for (auto& cmd : *this) cmd.call(); } void undo() const override { for_each(rbegin(), rend(), [](const Command& cmd) { cmd.undo(); }); } }; void printBalance(BankAccount& bankAccount) { cout << "Balance: " << bankAccount.balance << "\n\n"; } int main() { BankAccount ba; // Composite command. CommandList commands{Command{ba, Command::deposit, 100}, Command{ba, Command::withdraw, 200}}; printBalance(ba); commands.call(); printBalance(ba); commands.undo(); printBalance(ba); return 0; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; int main() { int a[10]; for (int i = 0;i < 6; i++) scanf("%d",&a[i]); sort(a,a+6); int x,y,t = 0; if (a[0] == a[3]) {x = a[4];y = a[5];t = 1;} if (a[1] == a[4]) {x = a[0];y = a[5];t = 1;} if (a[2] == a[5]) {x = a[0];y = a[1];t = 1;} if (x > y || t == 0) printf("Alien\n"); else { if (x < y) printf("Bear\n"); if (x == y) printf("Elephant\n"); } return 0; }
// you can use includes, for example: // #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; #include <limits.h> int solution(int N) { // write your code in C++14 (g++ 6.2.0) int i = 1; int min_ans=INT_MAX ; for (; i*i<N; i++){ if (N%i==0) min_ans = min(min_ans, 2*(i+N/i)); } if (i*i==N) min_ans = min(min_ans, 2*(i+N/i)); return min_ans; }
#include "cryptutil.h" #include <QCryptographicHash> #include <QDateTime> QByteArray CryptAdaptor::hashData(QByteArray text, QCryptographicHash::Algorithm alg, bool lower) { QByteArray data = QCryptographicHash::hash(text, alg); if(lower) { return data.toHex(); } return data.toHex().toUpper(); } QByteArray CryptAdaptor::cryptMd5(QByteArray text, bool lower) { QCryptographicHash hash(QCryptographicHash::Md5); hash.addData(text); QByteArray result = hash.result(); if(lower) { return result.toHex(); } return result.toHex().toUpper(); } QByteArray CryptAdaptor::cryptSha1(QByteArray text, bool lower) { QCryptographicHash hash(QCryptographicHash::Sha1); hash.addData(text); QByteArray result = hash.result(); if(lower) { return result.toHex(); } return result.toHex().toUpper(); } QByteArray CryptAdaptor::cryptSha256(QByteArray text, bool lower) { QCryptographicHash hash(QCryptographicHash::Sha256); hash.addData(text); QByteArray result = hash.result(); if(lower) { return result.toHex(); } return result.toHex().toUpper(); } QByteArray CryptAdaptor::cryptMd4(QByteArray text, bool lower) { QCryptographicHash hash(QCryptographicHash::Md4); hash.addData(text); QByteArray result = hash.result(); if(lower) { return result.toHex(); } return result.toHex().toUpper(); } QByteArray CryptAdaptor::toBase64(QByteArray text) { return text.toBase64(); }
#ifndef SCENE_FLOW_CONSTRUCTOR__SCENE_FLOW_CONSTRUCTOR_H_ #define SCENE_FLOW_CONSTRUCTOR__SCENE_FLOW_CONSTRUCTOR_H_ #include <cv_bridge/cv_bridge.h> #include <disparity_image_proc/disparity_image_processor.h> #include <dynamic_reconfigure/server.h> #include <geometry_msgs/TransformStamped.h> #include <image_geometry/pinhole_camera_model.h> #include <image_transport/image_transport.h> #include <image_transport/subscriber_filter.h> #include <message_filters/subscriber.h> #include <message_filters/time_synchronizer.h> #include <pwc_net/pwc_net.h> #include <ros/ros.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/CameraInfo.h> #include <sgm_gpu/sgm_gpu.h> #include <stereo_msgs/DisparityImage.h> #include <scene_flow_constructor/pcl_point_xyz_velocity.h> #include <scene_flow_constructor/SceneFlowConstructorConfig.h> #include <tf2/LinearMath/Transform.h> #include <tf2_ros/transform_broadcaster.h> #include <tf2_ros/transform_listener.h> #include <viso_stereo.h> #include <pcl_ros/point_cloud.h> #include <pcl/point_types.h> #include <thread> namespace scene_flow_constructor{ class SceneFlowConstructor { public: SceneFlowConstructor(); private: std::shared_ptr<image_transport::ImageTransport> image_transport_; /** * \brief Thread to execute construct() */ std::thread construct_thread_; /** * \brief Publisher for optical flow of left image */ ros::Publisher optflow_pub_; /** * \brief Publisher for disparity at now frame */ ros::Publisher depth_pub_; ros::Publisher pc_with_velocity_pub_; ros::Publisher static_flow_pub_; // Stereo image and camera info subscribers image_transport::SubscriberFilter left_image_sub_; image_transport::SubscriberFilter right_image_sub_; message_filters::Subscriber<sensor_msgs::CameraInfo> left_caminfo_sub_; message_filters::Subscriber<sensor_msgs::CameraInfo> right_caminfo_sub_; using StereoSynchronizer = message_filters::TimeSynchronizer<sensor_msgs::Image, sensor_msgs::Image, sensor_msgs::CameraInfo, sensor_msgs::CameraInfo>; /** * \brief Time synchronizer of stereo image and camera info */ std::shared_ptr<StereoSynchronizer> stereo_synchronizer_; using ReconfigureServer = dynamic_reconfigure::Server<scene_flow_constructor::SceneFlowConstructorConfig>; std::shared_ptr<ReconfigureServer> reconfigure_server_; ReconfigureServer::CallbackType reconfigure_func_; /** * \brief Difference[pixel] between optical flow and calculated static optical flow treated as dynamic pixel */ int dynamic_flow_diff_; /** * \brief Parameter used by visualization of velocity pc on image plane * When velocity of point is faster than this parameter, maximum color intensity is assigned at corresponded pixel */ double max_color_velocity_; sensor_msgs::ImageConstPtr previous_left_image_; std::shared_ptr<DisparityImageProcessor> disparity_previous_; std::shared_ptr<DisparityImageProcessor> disparity_now_; std::shared_ptr<cv_bridge::CvImage> left_flow_; geometry_msgs::TransformPtr transform_prev2now_; std::string camera_frame_id_; int image_width_; int image_height_; std::shared_ptr<image_geometry::PinholeCameraModel> left_cam_model_; /** * \brief Stereo visual odometry class from libviso2 */ std::shared_ptr<VisualOdometryStereo> visual_odometer_; /** * \brief Parameters used to initialize visual_odometer_ */ VisualOdometryStereo::parameters visual_odometer_params_; // Frame IDs for visual odometry std::string base_link_frame_id_; std::string odom_frame_id_; tf2_ros::TransformBroadcaster tf_broadcaster_; tf2_ros::Buffer tf_buffer_; std::shared_ptr<tf2_ros::TransformListener> tf_listener_; /** * \brief Camera pose which camera motions of each frame are cumulated */ tf2::Transform integrated_pose_; std::shared_ptr<sgm_gpu::SgmGpu> sgm_gpu_; pwc_net::PwcNet pwc_net_; /** * \brief Calculate optical flow of left frame with static assumption */ void calculateStaticOpticalFlow(const pcl::PointCloud<pcl::PointXYZ> &pc_previous_transformed, cv::Mat &left_static_flow); /** * \brief construct various data from disparity prev/now, left optical flow and camera movement */ void construct ( std::shared_ptr<DisparityImageProcessor> disparity_now, std::shared_ptr<DisparityImageProcessor> disparity_previous, std::shared_ptr<cv_bridge::CvImage> left_flow, geometry_msgs::TransformPtr transform_prev2now ); /** * \brief Calculate velocity of each point and construct pointcloud. */ void constructVelocityPC ( const pcl::PointCloud<pcl::PointXYZ> &pc_now, const pcl::PointCloud<pcl::PointXYZ> &pc_previous_transformed, cv_bridge::CvImage &left_flow, cv::Mat &left_static_flow, DisparityImageProcessor &disparity_now, DisparityImageProcessor &disparity_previous, pcl::PointCloud<pcl::PointXYZVelocity> &velocity_pc ); /** * \brief Estimate left camera motion by LIBVISO2 */ void estimateCameraMotion(const sensor_msgs::ImageConstPtr& left_image, const sensor_msgs::ImageConstPtr& right_image, const sensor_msgs::CameraInfoConstPtr& left_camera_info, const sensor_msgs::CameraInfoConstPtr& right_camera_info); /** * \brief Estimate disparity by SGM */ void estimateDisparity(const sensor_msgs::ImageConstPtr& left_image, const sensor_msgs::ImageConstPtr& right_image, const sensor_msgs::CameraInfoConstPtr& left_camera_info, const sensor_msgs::CameraInfoConstPtr& right_camera_info); /** * \brief Estimate optical flow by PWC-Net */ void estimateOpticalFlow(const sensor_msgs::ImageConstPtr& left_image); /** * \brief Get points in 3 images (left previous, right now and right previous frame) which match to a point in left now image * * \param left_now A point in left now image. * \param left_previous A point in left previous image matched to left_now. * \param right_now A point in right now image matched to left_now. * \param right_previous A point in right previous image matched to left_now. * * \return Return false if there aren't three match points or matching error is bigger than matching_tolerance_. */ inline bool getMatchPoints ( const cv::Point2i &left_now, cv::Point2i &left_previous, cv::Point2i &right_now, cv::Point2i &right_previous, cv_bridge::CvImage &left_flow, DisparityImageProcessor &disparity_now, DisparityImageProcessor &disparity_previous ) { if (!getPreviousPoint(left_now, left_previous, left_flow)) return false; if (!getRightPoint(left_now, right_now, disparity_now)) return false; if (!getRightPoint(left_previous, right_previous, disparity_previous)) return false; return true; } inline bool getPreviousPoint ( const cv::Point2i &now, cv::Point2i &previous, cv_bridge::CvImage &flow ) { if (now.x < 0 || now.x >= image_width_ || now.y < 0 || now.y >= image_height_) return false; const cv::Vec2f &flow_at_point = flow.image.at<cv::Vec2f>(now); if (std::isnan(flow_at_point[0]) || std::isnan(flow_at_point[1])) return false; previous.x = std::round(now.x - flow_at_point[0]); previous.y = std::round(now.y - flow_at_point[1]); return true; } inline bool getRightPoint(const cv::Point2i &left, cv::Point2i &right, DisparityImageProcessor &disparity_processor) { float disparity; if (!disparity_processor.getDisparity(left.x, left.y, disparity)) return false; if (std::isnan(disparity) || std::isinf(disparity) || disparity < 0) return false; right.x = std::round(left.x - disparity); right.y = left.y; return true; } void initializeOdometer(const sensor_msgs::CameraInfo& l_info_msg, const sensor_msgs::CameraInfo& r_info_msg); /** * \brief Resize velocity pointcloud and fill each point by default value * * \param velocity_pc Target velocity pointcloud */ void initializeVelocityPC(pcl::PointCloud<pcl::PointXYZVelocity> &velocity_pc); void integrateAndBroadcastTF(const tf2::Transform& delta_transform, const ros::Time& timestamp); inline bool isValid(const pcl::PointXYZ &point) { if (std::isnan(point.x)) return false; if (std::isinf(point.x)) return false; return true; } void publishDepthImage(ros::Publisher& depth_pub, cv::Mat& depth_image, ros::Time timestamp); template <typename PointT> void publishPointcloud ( const ros::Publisher &publisher, const pcl::PointCloud<PointT> &pointcloud, const std_msgs::Header &header ); void reconfigureCB(scene_flow_constructor::SceneFlowConstructorConfig& config, uint32_t level); /** * \brief Callback function of stereo_synchronizer_ */ void stereoCallback(const sensor_msgs::ImageConstPtr& left_image, const sensor_msgs::ImageConstPtr& right_image, const sensor_msgs::CameraInfoConstPtr& left_camera_info, const sensor_msgs::CameraInfoConstPtr& right_camera_info); /** * \brief Transform pointcloud of previous frame to now frame * * \param pc_previous Pointcloud of previous frame * \param pc_previous_transformed Transformed pointcloud of previous frame * \param previous_to_now Transform from now frame to previous frame */ void transformPCPreviousToNow(const pcl::PointCloud<pcl::PointXYZ> &pc_previous, pcl::PointCloud<pcl::PointXYZ> &pc_previous_transformed, const geometry_msgs::Transform &previous_to_now); }; } // namespace scene_flow_constructor #endif // SCENE_FLOW_CONSTRUCTOR__SCENE_FLOW_CONSTRUCTOR_H_
#include "simframe.h" SimFrame::SimFrame() { clearSimFrame(); } SimFrame & SimFrame::operator=(const SimFrame &v_src) { for(int row = 0; row < yLen; ++row) for(int col = 0; col < xLen; ++col) m_frameData[row][col] = v_src.m_frameData[row][col]; return *this; } SimFrame & SimFrame::operator|=(const SimFrame &v_src) { for(int row = 0; row < yLen; ++row) for(int col = 0; col < xLen; ++col) m_frameData[row][col] |= v_src.m_frameData[row][col]; return *this; } SimFrame & SimFrame::operator&=(const SimFrame &v_src) { for(int row = 0; row < yLen; ++row) for(int col = 0; col < xLen; ++col) m_frameData[row][col] &= v_src.m_frameData[row][col]; return *this; } SimFrame & SimFrame::operator^=(const SimFrame &v_src) { for(int row = 0; row < yLen; ++row) for(int col = 0; col < xLen; ++col) m_frameData[row][col] ^= v_src.m_frameData[row][col]; return *this; } SimFrame & SimFrame::invert(void) { for(int row = 0; row < yLen; ++row) for(int col = 0; col < xLen; ++col) m_frameData[row][col] = ~m_frameData[row][col]; return *this; } SimFrame &SimFrame::clearSimFrame() { for(int row = 0; row < yLen; ++row) for(int col = 0; col < xLen; ++col) m_frameData[row][col] = 0; return *this; } void SimFrame::setPixel(int v_row, int v_col, bool v_val) { if(v_val) this->setByte(v_row, v_col/8, this->getByte(v_row, v_col/8) | (0x80 >> (v_col % 8))); else this->setByte(v_row, v_col/8, this->getByte(v_row, v_col/8) & ~(0x80 >> (v_col % 8))); } bool SimFrame::getPixel(int v_row, int v_col) const { return (this->getByte(v_row, v_col/8) & (0x80 >> (v_col % 8))) == (0x80 >> (v_col % 8)); } int SimFrame::rows(void) const { return yLen; } int SimFrame::cols(void) const { return xLen*8; }
#include "MinerWife.h" bool MinerWife::HandleMessage(const Telegram& msg) { return m_pStateMachine->HandleMessage(msg); } void MinerWife::Update() { m_pStateMachine->Update(); }
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> pthread_cond_t work_01 = PTHREAD_COND_INITIALIZER; pthread_cond_t work_02 = PTHREAD_COND_INITIALIZER; pthread_cond_t work_03 = PTHREAD_COND_INITIALIZER; pthread_mutex_t work_mtx = PTHREAD_MUTEX_INITIALIZER; void* do_work_01(void* arg) { printf("Starting work_01 thread\n"); pthread_mutex_lock(&work_mtx); printf("Signalling work_03\n"); pthread_cond_signal(&work_03); printf("Waiting for work_01\n"); pthread_cond_wait(&work_01, &work_mtx); pthread_mutex_unlock(&work_mtx); printf("Exiting work_01 thread\n"); pthread_exit((void*)NULL); } void* do_work_02(void* arg) { printf("Starting work_02 thread\n"); pthread_mutex_lock(&work_mtx); printf("Waiting for work_02\n"); pthread_cond_wait(&work_02, &work_mtx); printf("Signalling work_01\n"); pthread_cond_signal(&work_01); pthread_mutex_unlock(&work_mtx); printf("Exiting work_02 thread\n"); pthread_exit((void*)NULL); } void* do_work_03(void* arg) { printf("Starting work_03 thread\n"); pthread_mutex_lock(&work_mtx); printf("Waiting for work_03\n"); pthread_cond_wait(&work_03, &work_mtx); printf("Signalling work_02\n"); pthread_cond_signal(&work_02); pthread_mutex_unlock(&work_mtx); printf("Exiting work_03 thread\n"); pthread_exit((void*)NULL); } int main() { pthread_t thread_1; pthread_t thread_2; pthread_t thread_3; pthread_attr_t attr; int rc; void* status; /* Create Thread attribute object */ rc = pthread_attr_init(&attr); if(rc) { fprintf(stderr, "ERROR: while creating thread attribute object"); return 1; } /* Create a new POSIX Thread */ rc = pthread_create(&thread_3, &attr, do_work_03, (void*) NULL); /* Cleanup pthread_attr_t object, we don't need it anymore */ pthread_attr_destroy(&attr); if(rc) { fprintf(stderr, "ERROR: while creating thread"); return 2; } sleep(1); /* Create a new POSIX Thread */ rc = pthread_create(&thread_2, &attr, do_work_02, (void*) NULL); /* Cleanup pthread_attr_t object, we don't need it anymore */ pthread_attr_destroy(&attr); if(rc) { fprintf(stderr, "ERROR: while creating thread"); return 2; } sleep(1); /* Create a new POSIX Thread */ rc = pthread_create(&thread_1, &attr, do_work_01, (void*) NULL); /* Cleanup pthread_attr_t object, we don't need it anymore */ pthread_attr_destroy(&attr); if(rc) { fprintf(stderr, "ERROR: while creating thread"); return 2; } sleep(1); rc = pthread_join(thread_1, &status); if(rc) { fprintf(stderr, "ERROR: while waiting for thread to join"); return 3; } rc = pthread_join(thread_2, &status); if(rc) { fprintf(stderr, "ERROR: while waiting for thread to join"); return 3; } rc = pthread_join(thread_3, &status); if(rc) { fprintf(stderr, "ERROR: while waiting for thread to join"); return 3; } printf("Exiting main thread\n"); return 0; }
/* * **************************************************************************** * * * * * Copyright 2008, xWorkshop Inc. * * * All rights reserved. * * * Redistribution and use in source and binary forms, with or without * * * modification, are permitted provided that the following conditions are * * * met: * * * * Redistributions of source code must retain the above copyright * * * notice, this list of conditions and the following disclaimer. * * * * 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 xWorkshop Inc. nor the names of its * * * contributors may be used to endorse or promote products derived from * * * this software without specific prior written permission. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * * * Author: stoneyrh@163.com * * * * * **************************************************************************** */ #include "xcrash_handler_win.hxx" #include "xdump_file_provider.hxx" #include "xlogger.hxx" #include "xlocale.hxx" #pragma comment(lib, "dbghelp.lib") namespace xws { xcrash_handler_win::xcrash_handler_win() { SetUnhandledExceptionFilter(xcrash_handler_win::dump_handler); } xcrash_handler_win::~xcrash_handler_win() { } LONG WINAPI xcrash_handler_win::dump_handler(__in struct _EXCEPTION_POINTERS* info) { if (info) { xdump_file_provider dump_file_provider; xstring dump_to(dump_file_provider.dump_file_name()); bool success = dump_exception(info, dump_to); return EXCEPTION_EXECUTE_HANDLER; } // Should never comes here return EXCEPTION_CONTINUE_SEARCH; } bool xcrash_handler_win::dump_exception(__in struct _EXCEPTION_POINTERS* info, const xstring& to) { if (info && !to.empty()) { HANDLE handle = CreateFile(to.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (handle != INVALID_HANDLE_VALUE) { MINIDUMP_EXCEPTION_INFORMATION mei; ZeroMemory(&mei, sizeof(mei)); mei.ThreadId = GetCurrentThreadId(); mei.ExceptionPointers = info; MINIDUMP_CALLBACK_INFORMATION mci; ZeroMemory(&mci, sizeof(mci)); mci.CallbackRoutine = xcrash_handler_win::mini_dump_callback; bool success = (bool)MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), handle, MiniDumpNormal, &mei, NULL, &mci); CloseHandle(handle); return success; } else { xlog_error(xchar_format(xtr(_X("Failed to create dump file \"{1}\"."))) % to); } } return false; } BOOL CALLBACK xcrash_handler_win::mini_dump_callback(PVOID, CONST PMINIDUMP_CALLBACK_INPUT, PMINIDUMP_CALLBACK_OUTPUT) { return TRUE; } } // namespace xws
#include <iostream> #include <string> #include <algorithm> using namespace std; int main(){ string line; int n, i, j; int minInd, maxInd; int caseNumber = 0; char first; bool same; while((cin >> line) && (line.length() != 0)){ caseNumber++; cout << "Case " << caseNumber << ":" << endl; cin >> n; while(n > 0){ n--; same = true; cin >> i >> j; minInd = min(i, j); maxInd = max(i, j); first = line[minInd]; for (int i = minInd+1; i <= maxInd; ++i){ if (line[i] != first){ same = false; break; } } if(same){ cout << "Yes" << endl; } else { cout << "No" << endl; } } } return 0; }
#include "login_mgr_class.hpp" #include "login.hpp" #include "login/log.hpp" #include "utils/service_thread.hpp" #include "utils/exception.hpp" #include "utils/assert.hpp" #include "utils/game_def.hpp" #include "proto/config_options.pb.h" #include "config/options_ptts.hpp" #include "utils/server_process_mgr.hpp" #include "gm/yunying_mgr.hpp" #include "proto/ss_login.pb.h" #include "admin_mgr_class.hpp" namespace nora { namespace gm { using login_mgr = server_process_mgr<login>; login_mgr_class::login_mgr_class() { name_ = "login_mgr_class"; st_ = make_shared<service_thread>("login_mgr_class"); st_->start(); } void login_mgr_class::start() { const auto& ptt = PTTS_GET(options, 1); login_mgr::static_init(); login_mgr::instance().init(ptt.gm_info().id()); } void login_mgr_class::add_to_white_list(uint32_t sid, int server_id, const set<string>& ips) { st_->async_call( [this, sid, server_id, ips] { ASSERT(st_->check_in_thread()); ps::base msg; auto *req = msg.MutableExtension(ps::g2l_add_to_white_list_req::gatwlr); req->set_sid(sid); req->set_server_id(static_cast<uint32_t>(server_id)); const auto& ptt = PTTS_GET(options, 1); req->set_gmd_id(ptt.gm_info().id()); for (const auto& i: ips) { req->add_ips(i); } login_mgr::instance().broadcast_msg(msg); sids_.insert(sid); }); } pd::white_list_array login_mgr_class::get_white_lists(uint32_t sid, uint32_t server_id) { pd::white_list_array ret; if (sid2white_lists_.count(sid) > 0) { if (server_id != 0) { set<string> white_lists; for (const auto& i : sid2white_lists_.at(sid).white_lists()) { if (white_lists.count(i.ip()) <= 0 && server_id == i.serverid()) { white_lists.insert(i.ip()); auto *white_list = ret.add_white_lists(); white_list->set_serverid(i.serverid()); white_list->set_ip(i.ip()); } } } else { map<uint32_t, set<string>> serd2whs; for (const auto& i : sid2white_lists_.at(sid).white_lists()) { if (serd2whs.count(i.serverid()) > 0) { if (serd2whs.at(i.serverid()).count(i.ip()) > 0) { continue; } } serd2whs[i.serverid()].insert(i.ip()); auto *white_list = ret.add_white_lists(); white_list->set_serverid(i.serverid()); white_list->set_ip(i.ip()); } } } return ret; } void login_mgr_class::add_to_white_list_done(uint32_t sid, pd::result result) { st_->async_call( [this, sid, result] { ASSERT(st_->check_in_thread()); if (sids_.count(sid) > 0) { if (sid <= MAX_GMD_SID) { yunying_mgr::instance().add_to_white_list_done(sid, result); } else { admin_mgr_class::instance().admin_edit_white_list_done(sid, true, result); } sids_.erase(sid); } }); } void login_mgr_class::login_gonggao(uint32_t sid, const pd::gonggao& gonggao) { st_->async_call( [this, sid, gonggao] { ASSERT(st_->check_in_thread()); ps::base msg; auto *req = msg.MutableExtension(ps::g2l_gonggao_req::ggr); const auto& ptt = PTTS_GET(options, 1); req->set_gmd_id(ptt.gm_info().id()); req->set_sid(sid); *req->mutable_gonggao() = gonggao; login_mgr::instance().broadcast_msg(msg); sids_.insert(sid); }); } void login_mgr_class::login_gonggao_done(uint32_t sid) { st_->async_call( [this, sid] { ASSERT(st_->check_in_thread()); if (sids_.count(sid) > 0) { yunying_mgr::instance().login_gonggao_done(sid); sids_.erase(sid); } }); } void login_mgr_class::remove_from_white_list(uint32_t sid, int server_id, const set<string>& ips) { st_->async_call( [this, sid, server_id, ips] { ASSERT(st_->check_in_thread()); ps::base msg; auto *req = msg.MutableExtension(ps::g2l_remove_from_white_list_req::grfwlr); req->set_sid(sid); req->set_server_id(static_cast<uint32_t>(server_id)); const auto& ptt = PTTS_GET(options, 1); req->set_gmd_id(ptt.gm_info().id()); for (auto i : ips) { req->add_ips(i); } login_mgr::instance().broadcast_msg(msg); sids_.insert(sid); }); } void login_mgr_class::remove_from_white_list_done(uint32_t sid, pd::result result) { st_->async_call( [this, sid, result] { ASSERT(st_->check_in_thread()); if (sids_.count(sid) > 0) { if (sid <= MAX_GMD_SID) { yunying_mgr::instance().remove_from_white_list_done(sid, result); } else { admin_mgr_class::instance().admin_edit_white_list_done(sid, false, result); } sids_.erase(sid); } }); } void login_mgr_class::fetch_white_list(uint32_t sid, int server_id) { st_->async_call( [this, sid, server_id] { ASSERT(st_->check_in_thread()); ps::base msg; auto *req = msg.MutableExtension(ps::g2l_fetch_white_list_req::gfwlr); req->set_sid(sid); const auto& ptt = PTTS_GET(options, 1); req->set_gmd_id(ptt.gm_info().id()); req->set_server_id(server_id); login_mgr::instance().broadcast_msg(msg); sids_.insert(sid); ADD_TIMER( st_, ([this, sid, server_id] (auto canceled, const auto& timer) { if (!canceled && sids_.count(sid) > 0) { if (sid <= MAX_GMD_SID) { yunying_mgr::instance().fetch_white_list_done(sid, pd::OK, this->get_white_lists(sid, server_id)); } else { admin_mgr_class::instance().admin_fetch_white_list_done(sid, pd::OK, this->get_white_lists(sid, server_id)); } sids_.erase(sid); this->clear_returnd_white_lists(sid); } }), 3s); }); } void login_mgr_class::fetch_white_list_done(uint32_t sid, pd::result result, const pd::white_list_array& white_lists) { st_->async_call( [this, sid, result, white_lists] { ASSERT(st_->check_in_thread()); if (sids_.count(sid) > 0) { if (sid2white_lists_.count(sid) > 0) { for (const auto& i : white_lists.white_lists()) { *sid2white_lists_.at(sid).add_white_lists() = i; } } else { sid2white_lists_[sid] = white_lists; } } }); } void login_mgr_class::fetch_gonggao_list_req(uint32_t conn_id) { st_->async_call( [this, conn_id] { ASSERT(st_->check_in_thread()); ps::base msg; auto *req = msg.MutableExtension(ps::g2l_fetch_gonggao_list_req::gfglr); req->set_aid(conn_id); const auto& ptt = PTTS_GET(options, 1); req->set_gmd_id(ptt.gm_info().id()); login_mgr::instance().random_send_msg(msg); }); } void login_mgr_class::stop() { if (st_) { st_->stop(); } LOGIN_DLOG << *this << " stop"; } ostream& operator<<(ostream& os, const login_mgr_class& lm) { return os << lm.name_; } } }
//--------------------------------------------------------- // // Project: dada // Module: core // File: Log.h // Author: Viacheslav Pryshchepa // // Description: // //--------------------------------------------------------- #ifndef DADA_CORE_LOG_H #define DADA_CORE_LOG_H #include "dada/core/common.h" namespace dada { class endl_t {}; static endl_t endl; class Log { }; Log& operator << (Log& log, const char* str); Log& operator << (Log& log, char ch); Log& operator << (Log& log, int8_t val); Log& operator << (Log& log, uint8_t val); Log& operator << (Log& log, int16_t val); Log& operator << (Log& log, uint16_t val); Log& operator << (Log& log, int32_t val); Log& operator << (Log& log, uint32_t val); Log& operator << (Log& log, int64_t val); Log& operator << (Log& log, uint64_t val); Log& operator << (Log& log, float val); Log& operator << (Log& log, double val); Log& operator << (Log& log, endl_t endl); inline Log& getLog() { static Log log; return log; } } // dada #endif // DADA_CORE_LOG_H
#pragma once #include "jsfunctioncall.h" namespace jsscript { namespace jsfunction_detail { #pragma region jsfunction_base class jsfunction_base { public: jsval fun; JSObject* par; JSContext* cx; }; template <int arity, typename T> class jsfunction_baseN { jsfunction_baseN() { BOOST_STATIC_ASSERT(!"arity not supported"); } }; template<typename T> class jsfunction_baseN<0, T> : public jsfunction_base { public: inline typename jsfunctioncall<T>::result_type operator()() { return jsfunctioncall<T>()(cx, par, fun); } }; #define JSFUNCTION_BASEN_TYPEDEF_ARG(z, n, text) \ BOOST_PP_COMMA_IF(BOOST_PP_DEC(n)) typename boost::call_traits<typename boost::function_traits<T>::arg ## n ##_type>::param_type arg ## n #define JSFUNCTION_BASEN_FORWARD_ARG(z, n, text) \ BOOST_PP_COMMA_IF(BOOST_PP_DEC(n)) arg ## n #define JSFUNCTION_BASEN_IMPL(z, n, text) \ template<typename T> \ class jsfunction_baseN<n, T> : public jsfunction_base \ { \ public: \ inline typename boost::function_traits<T>::result_type operator()( \ BOOST_PP_REPEAT_FROM_TO_ ## z(1, BOOST_PP_INC(n), JSFUNCTION_BASEN_TYPEDEF_ARG, null) \ ) \ { \ return jsfunctioncall<T>()(cx, par, fun, \ BOOST_PP_REPEAT_FROM_TO_ ## z(1, BOOST_PP_INC(n), JSFUNCTION_BASEN_FORWARD_ARG, null) \ ); \ } \ }; \ BOOST_PP_REPEAT_FROM_TO(1, JSFUNCTIONCALL_MAX_ARITY, JSFUNCTION_BASEN_IMPL, null) #pragma endregion } template<typename T> class jsfunction : public jsfunction_detail::jsfunction_baseN<boost::function_traits<T>::arity, T> { public: jsfunction(JSContext* cx, JSObject* par, jsval fun) { this->cx = cx; this->fun = fun; this->par = par ? par : JS_GetParent(cx, JSVAL_TO_OBJECT(fun)); acquire_locks(); } jsfunction(JSContext* cx, jsval fun) { this->cx = cx; this->fun = fun; this->par = JS_GetParent(cx, JSVAL_TO_OBJECT(fun)); acquire_locks(); } jsfunction(JSContext* cx, const string& function_name) { this->fun = JSVAL_VOID; this->cx = cx; JSObject* fo = script::GetObject(function_name); ASSERT(fo); if (JS_ObjectIsFunction(cx, fo)) { this->fun = OBJECT_TO_JSVAL(fo); this->par = JS_GetParent(cx, JSVAL_TO_OBJECT(fun)); } ASSERT(fun != JSVAL_VOID); acquire_locks(); } void acquire_locks() { JS_AddValueRoot(cx, &fun); if (par) JS_AddObjectRoot(cx, &par); } ~jsfunction() { JS_RemoveValueRoot(cx, &fun); if (par) JS_RemoveObjectRoot(cx, &par); } }; }
#include<stdio.h> int main() { int a,b,c; scanf("%d%d%d",&a,&b,&c); if(a>=b) printf("Chocolate\n"); else if(a<b && a<c) printf("Chocolate\n"); else if(a<b || a<c) printf("Ice-cream\n"); return 0; }
#include "FlyCam.h" FlyCam::FlyCam() { FlyCamStart(); Camera::Start(); } FlyCam::~FlyCam() { } FlyCam::FlyCam(float windowHeight, float windowLength) { FlyCamStart(); Camera::Start(windowHeight, windowLength); } void FlyCam::FlyCamStart() { speed = 5; lookSpeed = 0.1f; aie::Input* input = aie::Input::getInstance(); } void FlyCam::Update(float deltaTime) { aie::Input* input = aie::Input::getInstance(); vec3 direction; float speedMultiplier =1; if (input->isKeyDown(aie::INPUT_KEY_W)) { direction = direction + GetWorldTransform()[2].xyz *-1; } else if (input->isKeyDown(aie::INPUT_KEY_S)) { direction = direction + GetWorldTransform()[2].xyz; } if (input->isKeyDown(aie::INPUT_KEY_A)) { direction = direction + GetWorldTransform()[0].xyz *-1; } else if (input->isKeyDown(aie::INPUT_KEY_D)) { direction = direction + GetWorldTransform()[0].xyz; } if (input->isKeyDown(aie::INPUT_KEY_LEFT_SHIFT)) { speedMultiplier = 3; } else if (input->isKeyDown(aie::INPUT_KEY_LEFT_CONTROL)) { speedMultiplier = 0.5; } direction = direction *deltaTime * speed * speedMultiplier; SetPos(vec3(GetWorldTransform()[3].xyz + direction)); MouseLookUpdate(deltaTime); } void FlyCam::MouseLookUpdate(float deltaTime) { aie::Input* input = aie::Input::getInstance(); if (input->wasKeyPressed(aie::INPUT_KEY_LEFT_ALT)) { lockRot = !lockRot; } if (lockRot) { vec2 mousePosThisUpdate = vec2(input->getMouseX(), input->getMouseY()); if (mousePosLastUpdate == vec2(0, 0)) { mousePosLastUpdate = mousePosThisUpdate; } mat4 currentTransform = GetWorldTransform(); currentTransform[3] = vec4(0, 0, 0, 1); mat4 rotation; rotation = glm::rotate(rotation, (mousePosLastUpdate.x - mousePosThisUpdate.x)*deltaTime*lookSpeed, vec3(0, 1, 0)); rotation *= glm::rotate((mousePosLastUpdate.y - mousePosThisUpdate.y)*deltaTime*-lookSpeed, GetRow(0)); currentTransform = rotation * currentTransform; currentTransform[3] = GetWorldTransform()[3]; SetWorldTransform(currentTransform); mousePosLastUpdate = mousePosThisUpdate; } else { mousePosLastUpdate = vec2(input->getMouseX(), input->getMouseY()); } } void FlyCam::SetSpeed(float speed) { }
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int price[111111]; vector<int> g[111111]; int cnt[111111]; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); int T; cin >> T; while (T--) { int n, m; cin >> n >> m; for (int i = 0; i < n; ++i) { int k; cin >> k; g[i].clear(); for (int j = 0; j < k; ++j) { int x; cin >> x; g[i].push_back(x); } cin >> price[i]; } for (int i = 1; i <= m; ++i) cin >> cnt[i]; LL ans = 0; for (int i = 0; i < n; ++i) { int mi = 2e9; for (size_t j = 0; j < g[i].size(); ++j) { mi = min(cnt[g[i][j]], mi); } ans += LL(price[i]) * mi; } cout << ans << endl; } return 0; }
#ifndef GUI_EXCEPTIONS_H #define GUI_EXCEPTIONS_H #include <exception> #include <stdio.h> #include <stdlib.h> namespace GUI { class GUIException: public std::exception { public: virtual const char* what() const throw() { return "Basic GUI Exception"; } }; class NoFunctionOnButtonException: public GUIException { private: char* m_msg; int m_id; public: NoFunctionOnButtonException(int id) : m_id(id) {} const char* what() const throw() { char* msg_buf = (char*) malloc(sizeof(char)*64); sprintf(msg_buf, "Button pressed with no function assigned - Button ID: %d", m_id); return msg_buf; } }; } #endif
#include "Includes.h" #include <iostream> #include <fstream> #include <vector> #include <cmath> using namespace std; int solver(const vector<vector<int> > &sumsRows, const int &n); void uva108Main() { int n; while(scanf("%d", &n) != EOF) { vector<vector<int> > sumsRows(n, vector<int>(n, 0)); int x; for(int i=0; i<n; i++) { int sum = 0; for(int j=0; j<n; j++) { cin>>x; sum+=x; sumsRows[i][j]+=sum; } } printf("%d RESULT\n", solver(sumsRows, n)); sumsRows.clear(); } } int solver(const vector<vector<int> > &sumsRows, const int &n) { int maxSum = -128; for(int i=0; i<n; i++) { for(int x1=0; x1 < n; x1++) { int actualSum = 0; for(int y1=x1; y1<n; y1++) { actualSum += sumsRows[y1][x1]; if(actualSum > maxSum) maxSum = actualSum; } } } return maxSum; }
#include "simpleElementGenerator.h" #include "../../smartLine.h" using namespace qReal; using namespace robots::generator; void SimpleElementGenerator::generateMethodBody() { generateBodyWithoutNextElementCall(); IdList const outgoingConnectedElements = mNxtGen->mApi->outgoingConnectedElements(mElementId); if (outgoingConnectedElements.size() > 1) { mNxtGen->mErrorReporter.addError(QObject::tr("Too many outgoing connections!"), mElementId); return; } //if (outgoingConnectedElements.size() == 0) - case of last loop element, for example if (outgoingConnectedElements.size() == 1) { Id nextElement = outgoingConnectedElements.at(0); if (!mNxtGen->mApi->isLogicalElement(nextElement)) { nextElement = mNxtGen->mApi->logicalId(nextElement); } QString const methodName = mNxtGen->mIdToMethodNameMap[nextElement.toString()]; mNxtGen->mGeneratedStrings.append(SmartLine(methodName + "();", mElementId)); } }
#ifndef __CHATTY_SOCKET_H__ #define __CHATTY_SOCKET_H__ namespace chatty { namespace net { class Socket { public: explicit Socket(int fd); int accept(); int fd() const { return fd_; }; private: int fd_; }; } // namespace net } // namespace chatty #endif // __CHATTY_SOCKET_H__
#include<iostream> using namespace std; struct BiNode { char data; struct BiNode *lchild,*rchild; }; class BiTree { public: struct BiNode *root; public: BiTree()//构造函数,初始化根结点; {root=NULL;} void GreetTree()//创建二叉树 {root=Creat(root);} ~BiTree()//析构函数。销毁二叉树 {Release(root);} void PreOrder(BiNode *bt)//前序遍历 { /*PreOrder(root);*/ if(bt==NULL)return; else { cout<<bt->data; PreOrder(bt->lchild); PreOrder(bt->rchild); } } void LeverOrder()//层序遍历 {LeverOrder(root);} void BiTreeDepth()//树的深度 {cout<<"树的深度:"<<BiTreeDepth(root)<<endl;} void BiTreeLeapNum()//叶子节点数目 {cout<<"叶子结点数目:"<<LeapNum(root)<<endl;} void BiTreeLeve()//指定结点的层数: { char le; cout<<"输入结点信息:"; cin>>le; cout<<le<<"的层数是:"<<getfloor(root,le)<<endl; } void InsertChild()//插入结点 { char child1,parent1; cout<<"输入孩子信息:";cin>>child1; cout<<"输入双亲结点信息:";cin>>parent1; InsertLeftChild(child1,parent1,root); cout<<"插入后结果:(层序输出)"<<endl; LeverOrder(root); } void DeleteNode()//删除结点: { char node; cout<<"输入删除的结点信息:";cin>>node; deleteNode(root,node); cout<<"删除后的结果:(层序输出)"<<endl; LeverOrder(root); } void deleteNode(BiNode *T,char delchar)//删除节点及其子节点 { if (T!=NULL)//如果根节点不为空 { if (T->data==delchar)//如果根节点为要删除的节点 { delete T->lchild;//删除左孩子节点 T->lchild=NULL;//左指针指向NULL delete T->rchild;//删除右孩子节点 T->rchild=NULL;//右指针指向NULL delete T;//删除节点T }else if (T->lchild!=NULL&&T->lchild->data==delchar)//如果左孩子为要删除的节点 { delete T->lchild->lchild;//先删除左孩子的左孩子 delete T->lchild->rchild;//再删除左孩子的右孩子 delete T->lchild;//最后删除左孩子 T->lchild=NULL;//左指针置空 } else if (T->rchild!=NULL&&T->rchild->data==delchar)//如果右孩子为要删除的节点 { delete T->rchild->lchild;//先删除右孩子的左孩子 delete T->rchild->rchild;//再删除右孩子的右孩子 delete T->rchild;//最后删除右孩子 T->rchild=NULL;//右指针置空 }else { if(T->lchild!=NULL)//如果左孩子不为空 { deleteNode(T->lchild,delchar);//递归删除左孩子结点 } if(T->rchild!=NULL)//如果右孩子不为空 { deleteNode(T->rchild,delchar);//递归删除右孩子节点 } } } } void ChangeNode() { ChangeNode(root); cout<<"交换左右子树后:(层序输出)"<<endl; LeverOrder(root); } void ChangeNode(BiNode *bt)//交换左右子树 { if(bt!=NULL) { if(bt->lchild!=NULL&&bt->rchild!=NULL)//左右子树都不为空 { BiNode *p; p=bt->lchild; bt->lchild=bt->rchild; bt->rchild=p; } else if(bt->lchild==NULL&&bt->rchild!=NULL)//左空 右不空 { bt->lchild=bt->rchild; bt->rchild=NULL; }else if(bt->lchild!=NULL&&bt->rchild==NULL)//右空 左不空 { bt->rchild=bt->lchild; bt->lchild=NULL; } ChangeNode(bt->lchild);//递归 ChangeNode(bt->rchild); }else return; } BiNode *TreeFindNode(BiNode *bt,char data)//按照结点信息查找结点 { BiNode *ptr; if(bt==NULL)return NULL;//空树 else if(bt->data==data)return bt;//递归结束条件 else { if(ptr=TreeFindNode(bt->lchild,data))//递归,从左子树开始找 return ptr; else if(ptr=TreeFindNode(bt->rchild,data))//递归,从右子树开始找 return ptr; } } BiNode *Creat(BiNode *bt)//前序建立二叉树 { char ch; cin>>ch; if(ch=='#')bt=NULL; else { bt=new BiNode;bt->data=ch; bt->lchild=Creat(bt->lchild); bt->rchild=Creat(bt->rchild); } return bt; } int BiTreeDepth(BiNode *bt)//树的深度 { if(bt==NULL)return 0; return BiTreeDepth(bt->lchild)>BiTreeDepth(bt->rchild)?BiTreeDepth(bt->lchild)+1:BiTreeDepth(bt->rchild)+1; } int LeapNum(BiNode *bt)//叶子节点 { if(bt==NULL)return 0; else if(bt->lchild==NULL&&bt->rchild==NULL)return 1; else return LeapNum(bt->lchild)+LeapNum(bt->rchild); } int getfloor(BiNode *p,char x)//求指定结点的层数 { int num1,num2,n; if(p==NULL) return 0; else { if(p->data==x) return 1; num1=getfloor(p->lchild,x); num2=getfloor(p->rchild,x); n=num1+num2; if(num1!=0||num2!=0) n++; return n; } } void InsertLeftChild(char child1,char parent1,BiNode *bt)//插入新结点到指定结点的左或右子树 { BiNode *parent; BiNode *child=new BiNode;//建立新结点 child->data=child1;//初始化新结点 child->lchild=NULL;child->rchild=NULL;//新结点左右子树都为空 parent=TreeFindNode(root,parent1);//寻找双亲结点 if(!parent) { cout<<"没有找到双亲!"<<endl;delete child;return; } else { cout<<"已经找到双亲结点!"<<endl; char direction; cout<<"输入插入方向:L or R"<<endl; cin>>direction; if(direction=='L')//左插 { if(parent->lchild) cout<<"双亲左子树不为空!无法插入!"<<endl; else { parent->lchild=child;cout<<"插入左子树成功!!"<<endl; } } else if(direction=='R')//右插 { if(parent->rchild) cout<<"双亲右子树不为空!无法插入!"<<endl; else { parent->rchild=child;cout<<"插入右子树成功!!"<<endl; } } } } void LeverOrder(BiNode *bt)//层序遍历 { BiNode *queue[50];//队列存储二叉树的结点 BiNode *p; int front,rear; front=rear=-1; if(bt==NULL)return; queue[++rear]=bt; //根结点入队 while(front!=rear) //队列非空时 { p=queue[++front]; //出队,取队头元素 cout<<p->data; if(p->lchild!=NULL) //左孩子不为空 queue[++rear]=p->lchild; //左孩子入队 if(p->rchild!=NULL) //右孩子不为空 queue[++rear]=p->rchild; //右孩子入队 } } /*void PreOrder(BiNode *bt)//前序遍历 { if(bt==NULL)return; else { cout<<bt->data; PreOrder(bt->lchild); PreOrder(bt->rchild); } }*/ void Release(BiNode *bt)//销毁二叉树 { if(bt!=NULL) { cout<<"销毁二叉树!"<<endl; Release(bt->lchild); Release(bt->rchild); delete bt; } } }; int main() { BiTree b; int order; int flag=1; cout<<" ****************命令如下**************"<<endl; cout<<" 1,前序创建二叉树:"<<endl; cout<<" 2,前序遍历输出:"<<endl; cout<<" 3,中序遍历输出:"<<endl; cout<<" 4,后序遍历输出:"<<endl; cout<<" 5,层序遍历输出:"<<endl; cout<<" 6,求树的深度:"<<endl; cout<<" 7,求叶子节点的数目:"<<endl; cout<<" 8,求指定结点的层数:"<<endl; cout<<" 9,在指定结点插入左或右子树:"<<endl; cout<<" 10,交换左右子树:"<<endl; cout<<" 11,删除指定结点及其子树:"<<endl; cout<<" 12,结束程序:"<<endl; cout<<"输入命令序号:"<<endl; cin>>order; while(order) { switch(order) { case 1: { cout<<"输入前序创建二叉树:"<<endl; b.GreetTree(); cout<<endl; }break; case 2: { if(b.root==NULL)cout<<"二叉树为空!请先创建二叉树:"<<endl; else { cout<<"前序遍历输出:"<<endl; b.PreOrder(b.root); cout<<endl; }break; } case 3: { if(b.root==NULL)cout<<"二叉树为空!请先创建二叉树:"<<endl; else { cout<<"中序遍历输出:"<<endl; cout<<endl; } }break; case 4: { if(b.root==NULL)cout<<"二叉树为空!请先创建二叉树:"<<endl; else { cout<<"后序遍历输出:"<<endl; cout<<endl; } }break; case 5: { if(b.root==NULL)cout<<"二叉树为空!请先创建二叉树:"<<endl; else { cout<<"层序遍历输出:"<<endl; b.LeverOrder(); cout<<endl; } }break; case 6: { if(b.root==NULL)cout<<"二叉树为空!请先创建二叉树:"<<endl; else { cout<<"树的深度为: "<<endl; b.BiTreeDepth(); cout<<endl; } }break; case 7: { if(b.root==NULL)cout<<"二叉树为空!请先创建二叉树:"<<endl; else { cout<<"叶子结点的数目为:"<<endl; b.BiTreeLeapNum(); cout<<endl; } }break; case 8: { if(b.root==NULL)cout<<"二叉树为空!请先创建二叉树:"<<endl; else { cout<<"求指定结点的层数:"<<endl; b.BiTreeLeve(); cout<<endl; } }break; case 9: { if(b.root==NULL)cout<<"二叉树为空!请先创建二叉树:"<<endl; else { cout<<"在指定结点下插入左或右子树:"<<endl; b.InsertChild(); cout<<endl; } }break; case 10: { if(b.root==NULL)cout<<"二叉树为空!请先创建二叉树:"<<endl; else { cout<<"交换左右子树:"<<endl; b.ChangeNode(); cout<<endl; } }break; case 11: { if(b.root==NULL)cout<<"二叉树为空!请先创建二叉树:"<<endl; else { cout<<"删除指定结点及其子树:"<<endl; b.DeleteNode(); cout<<endl; } }break; case 12: { flag=0; }break; default:cout<<"输入非法!重新输入:"<<endl; } if(flag==0)break; else { cout<<"输入命令序号:"<<endl; cin>>order; } } /* cout<<"前序建立二叉树:"<<endl; cout<<"前序遍历:"<<endl; b.PreOrder(); cout<<endl; cout<<"层序遍历:"<<endl; b.LeverOrder(); cout<<endl; b.BiTreeDepth();//求树的深度 b.BiTreeLeapNum();//求叶子结点数目 cout<<endl; b.BiTreeLeve();//求指定结点的层数 cout<<endl; b.InsertChild();//在指定结点下面插入左或者右子树 cout<<endl; b.ChangeNode();//交换左右子树 cout<<endl; b.DeleteNode();//删除指定结点 cout<<endl;*/ return 0; }
/* 46450368 - 48579580 */ // Nicolás Saliba - Gonzalo Nicolari. // Instituto de Computación - Facultad de Ingeniería, Laboratorio de Programación 2. #include "../include/cadena.h" #include "../include/info.h" #include <stdio.h> #include <string.h> #include <assert.h> struct nodo { nodo *anterior; info_t dato; nodo *siguiente; }; struct rep_cadena { nodo *inicio; nodo *final; }; cadena_t crear_cadena() { rep_cadena *nueva = new rep_cadena; nueva->inicio = NULL; nueva->final = NULL; return nueva; } cadena_t insertar_al_final(info_t i, cadena_t cad) { nodo *nuevo = new nodo; nuevo->dato = i; nuevo->siguiente = NULL; nuevo->anterior = cad->final; if (cad->final == NULL) { assert(cad->inicio == NULL); cad->inicio = nuevo; } else { assert(cad->inicio != NULL); cad->final->siguiente = nuevo; } cad->final = nuevo; return cad; } cadena_t insertar_antes(info_t i, localizador_t loc, cadena_t cad) { nodo *nuevo = new nodo; nuevo->dato = i; nuevo->siguiente = NULL; nuevo->anterior = NULL; if (cad->inicio == NULL) cad->inicio = nuevo; else if (es_inicio_cadena(loc, cad)) { cad->inicio = nuevo; nuevo->siguiente = loc; loc->anterior = nuevo; } else { nuevo->anterior = anterior(loc, cad); nuevo->siguiente = loc; loc->anterior->siguiente = nuevo; loc->anterior = nuevo; } return cad; } cadena_t insertar_segmento_despues(cadena_t &sgm, localizador_t loc, cadena_t cad) { assert(es_vacia_cadena(cad) || localizador_en_cadena(loc, cad)); if (es_vacia_cadena(cad)) { cad->inicio = sgm->inicio; cad->final = sgm->final; } else { if (!es_vacia_cadena(sgm)) { sgm->inicio->anterior = loc; sgm->final->siguiente = loc->siguiente; if (es_final_cadena(loc, cad)) cad->final = sgm->final; else loc->siguiente->anterior = sgm->final; loc->siguiente = sgm->inicio; } } sgm->inicio = sgm->final = NULL; return cad; } cadena_t copiar_segmento(localizador_t desde, localizador_t hasta, cadena_t cad) { cadena_t res = crear_cadena(); if (!es_vacia_cadena(cad)) { localizador_t locCad = desde; while (locCad != hasta) { res = insertar_al_final(copia_info(locCad->dato), res); locCad = siguiente(locCad, cad); } res = insertar_al_final(copia_info(hasta->dato), res); } return res; } cadena_t cortar_segmento(localizador_t desde, localizador_t hasta, cadena_t cad) { // Si es vacìa. if (es_vacia_cadena(cad)) return cad; // Si solo se corta un elemento. else if (desde == hasta) return remover_de_cadena(desde, cad); // Si el segmento a cortar es toda la cadena. else if (es_inicio_cadena(desde, cad) && es_final_cadena(hasta, cad)) return liberar_cadena(cad); // Si el segmento a cortar está al inicio. else if (es_inicio_cadena(desde, cad)) { cad->inicio = siguiente(hasta, cad); cad->inicio->anterior = NULL; localizador_t loc = desde; while (loc != cad->inicio) { nodo *a_borrar = loc; loc = siguiente(loc, cad); liberar_info(a_borrar->dato); delete(a_borrar); } loc = NULL; return cad; } else if (es_final_cadena(hasta, cad)) { // Si el segmento a cortar està al final. cad->final = anterior(desde, cad); cad->final->siguiente = NULL; localizador_t loc = desde; while (es_localizador(loc)) { nodo *a_borrar = loc; loc = siguiente(loc, cad); liberar_info(a_borrar->dato); delete(a_borrar); } return cad; } else { // Si el segmento està al medio. localizador_t loc1 = anterior(desde, cad); localizador_t loc2 = siguiente(hasta, cad); loc1->siguiente = loc2; loc2->anterior = loc1; localizador_t loc = desde; while (loc != loc2) { nodo *a_borrar = loc; loc = siguiente(loc, cad); liberar_info(a_borrar->dato); delete(a_borrar); } return cad; } } cadena_t remover_de_cadena(localizador_t &loc, cadena_t cad) { nodo *a_borrar = loc; if (es_inicio_cadena(loc, cad) && es_final_cadena(loc, cad)) { // Si es el único elemento. cad->inicio = NULL; cad->final = NULL; } else if (es_inicio_cadena(loc, cad)) { // Si está al inicio. cad->inicio = siguiente(loc, cad); cad->inicio->anterior = NULL; } else if (es_final_cadena(loc, cad)) { // Si está al final. cad->final = anterior(loc, cad); cad->final->siguiente = NULL; } else { // Si está en el medio. loc->anterior->siguiente = siguiente(loc, cad); loc->siguiente->anterior = anterior(loc, cad); } // Libero memoria. liberar_info(a_borrar->dato); delete(a_borrar); loc = NULL; return cad; } cadena_t liberar_cadena(cadena_t cad) { nodo *a_borrar; while (cad->inicio != NULL) { a_borrar = cad->inicio; cad->inicio = cad->inicio->siguiente; liberar_info(a_borrar->dato); delete(a_borrar); } delete cad; return cad; } bool es_localizador(localizador_t loc) { return loc != NULL; } bool es_vacia_cadena(cadena_t cad) { return (cad->inicio == NULL) && (cad->final == NULL); } bool es_final_cadena(localizador_t loc, cadena_t cad) { return (!es_vacia_cadena(cad) && localizador_en_cadena(loc, cad) && loc->siguiente == NULL); } bool es_inicio_cadena(localizador_t loc, cadena_t cad) { return (!es_vacia_cadena(cad) && localizador_en_cadena(loc, cad) && loc->anterior == NULL); } bool localizador_en_cadena(localizador_t loc, cadena_t cad) { localizador_t locMove = inicio_cadena(cad); while (es_localizador(locMove) && (locMove != loc)) locMove = siguiente(locMove, cad); return es_localizador(locMove); } bool precede_en_cadena(localizador_t loc1, localizador_t loc2, cadena_t cad) { if (es_vacia_cadena(cad)) return false; else if (loc1 == loc2) return true; else { localizador_t locAux = loc2; while (es_localizador(locAux) && (locAux != loc1)) locAux = anterior(locAux, cad); return locAux == loc1; } } localizador_t inicio_cadena(cadena_t cad) { localizador_t loc; if (es_vacia_cadena(cad)) loc = NULL; else loc = cad->inicio; return loc; } localizador_t final_cadena(cadena_t cad) { localizador_t loc; if (es_vacia_cadena(cad)) loc = NULL; else loc = cad->final; return loc; } localizador_t kesimo(nat k, cadena_t cad) { localizador_t loc = NULL; if (!es_vacia_cadena(cad) && (k > 0)) { nat i = 1; loc = inicio_cadena(cad); while (i < k && es_localizador(loc)) { loc = siguiente(loc, cad); i++; } } return loc; } localizador_t siguiente(localizador_t loc, cadena_t cad) { if (!es_final_cadena(loc, cad)) return loc->siguiente; else return NULL; } localizador_t anterior(localizador_t loc, cadena_t cad) { if (!es_inicio_cadena(loc, cad)) return loc->anterior; else return NULL; } localizador_t menor_en_cadena(localizador_t loc, cadena_t cad) { localizador_t res = loc; localizador_t locMove = loc; while (es_localizador(locMove)) { if (numero_info(info_cadena(locMove, cad)) < numero_info(info_cadena(res, cad))) res = locMove; locMove = siguiente(locMove, cad); } return res; } localizador_t siguiente_clave(int clave, localizador_t loc, cadena_t cad) { localizador_t res = loc; if(es_vacia_cadena(cad)) res = NULL; else while (es_localizador(res) && numero_info(info_cadena(res, cad)) != clave) res = siguiente(res, cad); return res; } info_t info_cadena(localizador_t loc, cadena_t cad) { info_t info = loc->dato; return info; } cadena_t cambiar_en_cadena(info_t i, localizador_t loc, cadena_t cad) { loc->dato = i; return cad; } cadena_t intercambiar(localizador_t loc1, localizador_t loc2, cadena_t cad) { if (loc1 != loc2) { info_t info = copia_info(loc2->dato); liberar_info(loc2->dato); loc2->dato = loc1->dato; loc1->dato = info; } return cad; } void imprimir_cadena(cadena_t cad) { if (!es_vacia_cadena(cad)) { localizador_t loc = inicio_cadena(cad); while (loc != NULL) { char *info = info_a_texto(info_cadena(loc, cad)); printf("%s", info); loc = siguiente(loc, cad); delete[] info; } } printf("\n"); }
#ifndef ITERATOR_H #define ITERATOR_H template <class Object> class Iterator { public: virtual void first() = 0; virtual void next() = 0; virtual bool isDone() const = 0; virtual Object currentItem() = 0; }; template <class Object> class NullIterator : public Iterator<Object> { public: void first() {} void next() {} bool isDone() const {return true;} Object currentItem() {return Object();} }; #endif
#include<iostream> #include <ctime> #include<stdio.h> #include<conio.h> using namespace std; int main() { clock_t c_start = clock(); int i, j, n, min, temp, k; cout<<"Enter the Number of Elements: "; cin>>n; int arr[n]; cout<<"Enter the elements: "; for(i = 0;i < n;i++) { cin>>arr[i]; } for(i = 0;i < n-1;i++) { temp = i; for(j = i+1;j < n;j++) { if(arr[temp] > arr[j]) { temp = j; } } min = arr[temp]; arr[temp] = arr[i]; arr[i] = min; } cout<<"Sorted Array using Selection sort: "<<endl; for(i = 0;i < n;i++) { cout<<arr[i]<<" "; } clock_t c_end = clock(); long double time_elapsed_ms = 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC; cout << "\nCPU time used: " << time_elapsed_ms << " ms\n"; }
#pragma once #include <array> struct Color; struct ColorToggle; struct ColorToggleRounding; struct ColorToggleThickness; struct ColorToggleThicknessRounding; namespace ImGuiCustom { void colorPopup(const char* name, std::array<float, 4>& color, bool* rainbow = nullptr, float* rainbowSpeed = nullptr, bool* enable = nullptr, float* thickness = nullptr, float* rounding = nullptr) noexcept; void colorPicker(const char* name, Color& colorConfig, bool* enable = nullptr, float* thickness = nullptr) noexcept; void colorPicker(const char* name, ColorToggle& colorConfig) noexcept; void colorPicker(const char* name, ColorToggleRounding& colorConfig) noexcept; void colorPicker(const char* name, ColorToggleThickness& colorConfig) noexcept; void colorPicker(const char* name, ColorToggleThicknessRounding& colorConfig) noexcept; } namespace ImGui { bool smallButtonFullWidth(const char* label, bool disabled = false) noexcept; void textUnformattedCentered(const char* text) noexcept; void progressBarFullWidth(float fraction, float height) noexcept; // table that inherits ImGuiWindowFlags_NoInputs from parent window for its scrolling region bool beginTable(const char* str_id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f) noexcept; bool beginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f) noexcept; void textEllipsisInTableCell(const char* text) noexcept; }
/** Kabuki SDK @file /.../Source/Kabuki_SDK/_Com/MIDI/Port.cpp @author Cale McCollough @copyright Copyright © 2016 Cale McCollough © @license Read accompanying /.../README.md or online at http://www.boost.org/LICENSE_1_0.txt */ #include "Port.h" #include "Kabuki SDK.h" #include "_Com/MIDI/Message.h" using namespace _Com.MIDI; Port::Port(Type InOrOut, int InitQueueSize): portNum(0), msgQueueSize(defaultQueueSize), readIndex(0), queueIndex(0) { // Perform error checking on initQueueSize if(InitQueueSize < minQueueSize) msgQueueSize = minQueueSize; msgQueueSize = defaultQueueSize; queue = new Message *[msgQueueSize]; for(int i=0; i < msgQueueSize; ++i) queue[i] = NULL; } Port::~Port() { deleteQueue(); } int Port::GetQueueSize () { return msgQueueSize; } void Port::ResizeQueue(int newSize) { if( newSize < minQueueSize || newSize == msgQueueSize) return; // Not sure if I want this funciton to return false if newSize is ou of bounds. deleteQueue(); queue = new Message *[msgQueueSize]; for(int i=0; i < msgQueueSize; ++i) queue[i] = NULL; } int Port::GetNumMessages() { return numMsgs; } void Port::IncreaseQueueSize() { ResizeQueue(msgQueueSize+queueSizeIncrease); } void Port::Encue(Message *AMessage) { if(queueIndex == msgQueueSize) queueIndex = 0; if(queueIndex == readIndex-1) // Oops! We over ran the buffer! { resizeQueue(readIndex+queueSizeIncrease); } } Message* Port::DecueNextMessage() { if(numMsgs == 0) // Then queue is empty. return NULL; Message * temp; temp = queue[readIndex]; queue[readIndex] = NULL; --numMsgs; ++readIndex; if(readIndex == msgQueueSize) // Wrap around to the begining of the queue. readIndex = 0; return temp; } int Port::GetPortIndex() { return portNum; } void Port::SetPortIndex(int newIndex) { if(newIndex < 0) return; portNum = newIndex; } void Port::Reset() { // We only need to delete the messages in between the head and tail indecies. for(int i=0; i <= msgQueueSize; ++i) { if(queue[i]) { delete queue[i]; queue[i] = NULL; } } } void Port::DeleteQueue() { // This function is pretty much the same as reset() only it does not // set indecies to NULL and it deletes the queue pointer. for(int i=0; i <= msgQueueSize; ++i) { if(queue[i]) { delete queue[i]; queue[i] = NULL; } } delete queue; }
#include <iostream> #include <fstream> #include <string> #include <stdlib.h> #define TAMANHO 11 #define NOME_ARQUIVO "dados_modelo.dat" using namespace std; struct no { int id; char termo[50]; char sig[50]; }; void menu(); void cadastrar_termo(); void exibirTermo(); void gera_arquivo_modelo(); void buscarTermo(); void gera_arquivo_vazio(); void remover(); int main () { system("cls"); int i, opcao; menu(); do { cout << "|Entre com uma opcao: "; cin >> opcao;; cout << endl; switch (opcao) { case 0: system("cls"); menu(); gera_arquivo_modelo(); break; case 1: system("cls"); menu(); gera_arquivo_vazio(); break; case 2: system("cls"); menu(); cadastrar_termo(); break; case 3: system("cls"); menu(); remover(); break; case 4: system("cls"); menu(); buscarTermo(); break; case 5: system("cls"); menu(); exibirTermo(); break; case 6: break; default: system("cls"); menu(); cout << "Opcao invalida! Utilize menu.\n"; } } while (opcao != 6); cout << "S A I N D O . . . " << endl; return 0; } //********************************************************************************* void menu() { cout << "|===============================================|\n"; cout << "|\t\tSISTEMA GLOSSARIO v0.01 \t|\n"; cout << "|===============================================|\n"; cout << "|0 - Criar arquivo de modelo \t\t\t|\n"; cout << "|1 - Gera arquivo vazio \t\t\t|\n"; cout << "|2 - Inserir termo \t\t\t\t|\n"; cout << "|3 - Remover termo \t\t\t\t|\n"; cout << "|4 - Buscar termo no arquivo\t\t\t|\n"; cout << "|5 - Exibir todos os termos\t\t\t|\n"; cout << "|6 - Sair\t\t\t\t\t|\n"; cout << "|-----------------------------------------------|\n"; } //********************************************************************************* void cadastrar_termo(){ no no; fstream arquivo(NOME_ARQUIVO, ios::in| ios::out | ios::binary ); if (!arquivo) { cerr << "Arquivo não pode ser aberto."; exit(1); } cout << "|ID: "; cin.get(); cin >> no.id; cout << "|Termo: "; cin.get(); cin.getline(no.termo, 50); cout << "|Significado: "; cin.getline(no.sig, 50); arquivo.seekp(( no.id % TAMANHO ) * sizeof(no)); arquivo.write( reinterpret_cast<const char*>(&no), sizeof(no) ); arquivo.close(); cout << "|Termo \'" << no.termo << "\' inserido na posicao " << (no.id % TAMANHO ) << " \t\t\t\t" << endl; cout << "|-----------------------------------------------|" << endl; } //********************************************************************************* void remover(){ int chave; fstream arquivo(NOME_ARQUIVO, ios::in| ios::out | ios::binary ); cout << "|ID a remover: "; cin.get(); cin >> chave; arquivo.seekp((chave % 11) * sizeof(no)); // ainda não detecta colisao, até pq quem vai fazer isso vai ser a arvore // não precisa alteração. no no = {-1, "", ""}; arquivo.write( reinterpret_cast<const char*>(&no), sizeof(no) ); cout << "|Termo \'" << chave << "\' removido com sucesso!\t\t\t\t" << endl; cout << "|-----------------------------------------------|" << endl; } void exibirTermo() { no no; ifstream leitura; leitura.open(NOME_ARQUIVO, ios::binary ); // abre arquivo para leitura if (!leitura) { // verifica se o arquivo existe/nome correto cerr << "Arquivo nao pode ser aberto para leitura!" << endl; return; } cout << "|ID\t" << "|TERMO\t\t" << "|SIGNIFICADO\t\t|" << endl; cout << "|-----------------------------------------------|" << endl; leitura.seekg(0); leitura.read((char*)&no, sizeof(no)); while ((leitura) && (!leitura.eof())) { // varre o arquvo binario e armazena cada no(struct) na variavel no e exibe na tela ate encontrar eof cout << "|" << no.id << "\t" << no.termo << "\t\t" << no.sig << "\t\t" << endl; leitura.read((char*)&no, sizeof(no)); } cout << "|-----------------------------------------------\n"; leitura.close(); // fecha arquivo } //********************************************************************************* void buscarTermo(){ int chave; cin >> chave; //na minha implementaçao, eu simplesmente faço o calculo com mod 11 // no trabalho final, é aqui que o metodo de busca na arvore binaria // vai acontecer... ele vai procurar a posicao onde a chave se encontra //e vai me informar pra que eu possa dizer onde posicionar o ponteiro // vai ficar assim: // int posicao = buscaPosicao( chave ); // esse metodo usa a arvore binaria pra achar o dado int posicao = (chave % 11) * sizeof(no);// por enquanto vai ficar assim no no; ifstream leitura; leitura.open( NOME_ARQUIVO, ios::binary ); // abre arquivo para leitura if (!leitura) { // verifica se o arquivo existe/nome correto cerr << "Arquivo nao pode ser aberto para leitura!" << endl; return; } cout << "|ID\t" << "|TERMO\t\t" << "|SIGNIFICADO\t\t|" << endl; cout << "|-----------------------------------------------|" << endl; leitura.seekg(posicao);//posiciono o ponteiro no registro que desejo leitura.read((char*)&no, sizeof(no)); cout << "|" << no.id << "\t" << no.termo << "\t\t" << no.sig << "\t\t" << endl; leitura.read((char*)&no, sizeof(no)); cout << "|-----------------------------------------------\n"; leitura.close(); // fecha arquivo } //********************************************************************************* void gera_arquivo_modelo(){ // esse arquivo será o modelo para pesquisa e alterações // os nos estão na ordem e posicao que se encontram nos // slides que o prof usou em sala de aula no no0 = {41, "Mancebo", "Moco, velador, cabide para roupa"}; no no1 = {39, "Politipo", "Que tem muitos tipos"}; no no2 = {13, "Conego", "Dignidade eclesiastica"}; no no3 = {0, "", ""}; no no4 = {0, "", ""}; no no5 = {27, "Glandado", "Que termina em glande"}; no no6 = {16, "Redil", "Curral, aprisco, gremio, paroquia"}; no no7 = {18, "Tosta", "Torrada, Bolo em forma de torrada"}; no no8 = {17, "Urural", "Especie de jacare de papo amarelo"}; no no9 = {19, "Esquiça", "Batoque do buraco nas vasilhas de vinho"}; no no10 = {28, "Napeias", "Ninfa dos bosques e dos prados."}; ofstream arquivo; // define objeto para escrita no arquivo arquivo.open( NOME_ARQUIVO, ios::out | ios::binary ); // abre arquivo para escrita if (!arquivo) { // verifica se nao ha erro na abertura do arquivo cerr << "Arquivo nao pode ser aberto para gravacao!" << endl; exit(1); } arquivo.write((char*)&no0, sizeof(no) ); arquivo.write((char*)&no1, sizeof(no) ); arquivo.write((char*)&no2, sizeof(no) ); arquivo.write((char*)&no3, sizeof(no) ); arquivo.write((char*)&no4, sizeof(no) ); arquivo.write((char*)&no5, sizeof(no) ); arquivo.write((char*)&no6, sizeof(no) ); arquivo.write((char*)&no7, sizeof(no) ); arquivo.write((char*)&no8, sizeof(no) ); arquivo.write((char*)&no9, sizeof(no) ); arquivo.write((char*)&no10, sizeof(no) ); cout << "|Arquivo modelo usado para o trabalho criado!\t|" << endl; cout << "|-----------------------------------------------|" << endl; arquivo.close(); } //********************************************************************************* void gera_arquivo_vazio(){ ofstream arquivo; arquivo.open( NOME_ARQUIVO, ios::binary ); no no = {0,"",""}; for( int i = 0; i < TAMANHO; i++) arquivo.write((char*)&no,(sizeof(struct no))); cout << "|Arquivo vazio usado para o trabalho criado!\t|" << endl; cout << "|-----------------------------------------------|" << endl; }
#include <iostream> #include "std_lib_facilities.h" void main() { std::cout << "What is your first Name? \n"; string first_name; std::cin >> first_name; std::cout << "Hello," << first_name << "!\n"; }
#include "cpp_native.hpp" #include <iostream> namespace CppApp { void MyCpp::testMyCpp() { std::cout << "#message from CppApp" << std::endl; } }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <quic/client/handshake/ClientHandshake.h> #include <quic/client/handshake/ClientHandshakeFactory.h> #include <quic/common/QuicAsyncUDPSocketWrapper.h> #include <quic/congestion_control/QuicCubic.h> #include <quic/flowcontrol/QuicFlowController.h> #include <quic/handshake/TransportParameters.h> #include <quic/state/QuicStateFunctions.h> #include <quic/state/StateData.h> namespace quic { struct CachedServerTransportParameters; struct PendingClientData { NetworkDataSingle networkData; folly::SocketAddress peer; PendingClientData( NetworkDataSingle networkDataIn, folly::SocketAddress peerIn) : networkData(std::move(networkDataIn)), peer(std::move(peerIn)) {} }; struct QuicClientConnectionState : public QuicConnectionStateBase { ~QuicClientConnectionState() override = default; // Zero rtt write header cipher. std::unique_ptr<PacketNumberCipher> zeroRttWriteHeaderCipher; // Write cipher for 0-RTT data std::unique_ptr<Aead> zeroRttWriteCipher; // The stateless reset token sent by the server. folly::Optional<StatelessResetToken> statelessResetToken; // The retry token sent by the server. std::string retryToken; // The new token that potentially verifies the address of the // client. std::string newToken; // This is the destination connection id that will be sent in the outgoing // client initial packet. It is modified in the event of a retry. folly::Optional<ConnectionId> initialDestinationConnectionId; // This is the original destination connection id. It is the same as the // initialDestinationConnectionId when there is no retry involved. When // there is retry involved, this is the value of the destination connection // id sent in the very first initial packet. folly::Optional<ConnectionId> originalDestinationConnectionId; std::shared_ptr<ClientHandshakeFactory> handshakeFactory; ClientHandshake* clientHandshakeLayer; folly::Optional<TimePoint> lastCloseSentTime; // Save the server transport params here so that client can access the value // when it wants to write the values to psk cache // TODO Save TicketTransportParams here instead of in QuicClientTransport bool serverInitialParamsSet_{false}; uint64_t peerAdvertisedInitialMaxData{0}; uint64_t peerAdvertisedInitialMaxStreamDataBidiLocal{0}; uint64_t peerAdvertisedInitialMaxStreamDataBidiRemote{0}; uint64_t peerAdvertisedInitialMaxStreamDataUni{0}; uint64_t peerAdvertisedInitialMaxStreamsBidi{0}; uint64_t peerAdvertisedInitialMaxStreamsUni{0}; struct HappyEyeballsState { // Delay timer QuicTimerCallback* connAttemptDelayTimeout{nullptr}; // IPv6 peer address folly::SocketAddress v6PeerAddress; // IPv4 peer address folly::SocketAddress v4PeerAddress; // The address that this socket will try to connect to after connection // attempt delay timeout fires folly::SocketAddress secondPeerAddress; // The UDP socket that will be used for the second connection attempt std::unique_ptr<QuicAsyncUDPSocketType> secondSocket; // Whether should write to the first UDP socket bool shouldWriteToFirstSocket{true}; // Whether should write to the second UDP socket bool shouldWriteToSecondSocket{false}; // Whether HappyEyeballs has finished // The signal of finishing is first successful decryption of a packet bool finished{false}; }; HappyEyeballsState happyEyeballsState; // Short header packets we received but couldn't yet decrypt. std::vector<PendingClientData> pendingOneRttData; // Handshake packets we received but couldn't yet decrypt. std::vector<PendingClientData> pendingHandshakeData; // Whether 0-rtt has been rejected in this connection. // The value should be set after the handshake if 0-rtt was attempted folly::Optional<bool> zeroRttRejected; explicit QuicClientConnectionState( std::shared_ptr<ClientHandshakeFactory> handshakeFactoryIn) : QuicConnectionStateBase(QuicNodeType::Client), handshakeFactory(std::move(handshakeFactoryIn)) { cryptoState = std::make_unique<QuicCryptoState>(); congestionController = std::make_unique<Cubic>(*this); connectionTime = Clock::now(); originalVersion = QuicVersion::MVFST; DCHECK(handshakeFactory); auto tmpClientHandshake = std::move(*handshakeFactory).makeClientHandshake(this); clientHandshakeLayer = tmpClientHandshake.get(); handshakeLayer = std::move(tmpClientHandshake); // We shouldn't normally need to set this until we're starting the // transport, however writing unit tests is much easier if we set this here. updateFlowControlStateWithSettings(flowControlState, transportSettings); streamManager = std::make_unique<QuicStreamManager>( *this, this->nodeType, transportSettings); transportSettings.selfActiveConnectionIdLimit = kDefaultActiveConnectionIdLimit; } }; /** * Undos the clients state to be the original state of the client. */ std::unique_ptr<QuicClientConnectionState> undoAllClientStateForRetry( std::unique_ptr<QuicClientConnectionState> conn); void processServerInitialParams( QuicClientConnectionState& conn, const ServerTransportParameters& serverParams, PacketNum packetNum); void cacheServerInitialParams( QuicClientConnectionState& conn, uint64_t peerAdvertisedInitialMaxData, uint64_t peerAdvertisedInitialMaxStreamDataBidiLocal, uint64_t peerAdvertisedInitialMaxStreamDataBidiRemote, uint64_t peerAdvertisedInitialMaxStreamDataUni, uint64_t peerAdvertisedInitialMaxStreamsBidi, uint64_t peerAdvertisedInitialMaxStreamUni, bool peerAdvertisedKnobFrameSupport); CachedServerTransportParameters getServerCachedTransportParameters( const QuicClientConnectionState& conn); void updateTransportParamsFromCachedEarlyParams( QuicClientConnectionState& conn, const CachedServerTransportParameters& transportParams); } // namespace quic
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. ** It may not be distributed under any circumstances. */ // ----------------------------------------------------------------------- #include "core/pch.h" #ifdef ASYNC_IMAGE_DECODERS_EMULATION #include "modules/img/src/ImageDecoderAsync.h" #include "modules/hardcore/mh/mh.h" #include "modules/pi/OpBitmap.h" #include <cassert> // ----------------------------------------------------------------------- ImageDecoderAsync::Buffer::Buffer() : m_buf(NULL), m_size(0) {} OP_STATUS ImageDecoderAsync::Buffer::Append(const char* buf, size_t size) { assert(((m_buf != NULL) && (m_size > 0)) || // either not empty with nonzero size ((m_buf == NULL) && (m_size == 0))); // or empty with zero size assert(((buf != NULL) && (size > 0)) || // either not empty with nonzero size ((buf == NULL) && (size == 0))); // or empty with zero size if (buf == NULL) { return OpStatus::ERR; } size_t old_size = m_size; size_t new_size = old_size + size; char* old_buf = m_buf; char* new_buf = OP_NEWA(char, new_size); if (new_buf == NULL) return OpStatus::ERR_NO_MEMORY; op_memcpy(new_buf, old_buf, old_size); op_memcpy(new_buf + old_size, buf, size); OP_DELETEA(old_buf); m_buf = new_buf; m_size = new_size; return OpStatus::OK; } OP_STATUS ImageDecoderAsync::Buffer::Consume(size_t size) { size_t old_size = m_size; size_t new_size = old_size - size; char* old_buf = m_buf; char* new_buf = (new_size != 0 ? OP_NEWA(char, new_size) : NULL); if (new_size != 0) { op_memcpy(new_buf, old_buf + size, new_size); } OP_DELETEA(old_buf); m_buf = new_buf; m_size = new_size; return OpStatus::OK; } const char* ImageDecoderAsync::Buffer::GetContent() const { return m_buf; } size_t ImageDecoderAsync::Buffer::GetSize() const { return m_size; } OP_STATUS ImageDecoderAsync::Buffer::Clear() { OP_DELETEA(m_buf); m_buf = NULL; m_size = 0; return OpStatus::OK; } bool ImageDecoderAsync::Buffer::IsEmpty() { assert(((m_buf != NULL) && (m_size > 0)) || // either not empty with nonzero size ((m_buf == NULL) && (m_size == 0))); // or empty with zero size return (m_size == 0); } // ----------------------------------------------------------------------- ImageDecoderAsync::ImageDecoderAsync(ImageDecoder* impl) : m_image_decoder_listener(NULL), m_impl(impl), m_message_pending(false), m_buf() { m_impl->SetImageDecoderListener(this); g_main_message_handler->SetCallBack(this, MSG_ASYNC_DECODER, (int)this, 0); } ImageDecoderAsync::~ImageDecoderAsync() { g_main_message_handler->UnsetCallBack(this, MSG_ASYNC_DECODER); OP_DELETE(m_impl); // delete m_bitmap; -- deleted by ImageFrame } // ----------------------------------------------------------------------- // ImageDecoder OP_STATUS ImageDecoderAsync::DecodeData(const BYTE* data, UINT32 size, BOOL more, int& resendBytes, BOOL/* load_all = FALSE*/) { resendBytes = 0; // here we don't want to have to copy the data. OP_STATUS ret = m_buf.Append((char*)data, size); if (!m_message_pending) { g_main_message_handler->PostDelayedMessage(MSG_ASYNC_DECODER, (int)this, 0, 1000); m_message_pending = true; } return ret; } void ImageDecoderAsync::SetImageDecoderListener(ImageDecoderListener* listener) { m_listener = listener; } // ----------------------------------------------------------------------- void ImageDecoderAsync::HandleCallback(int msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { if ((ImageDecoderAsync*)par1 != this) { return; } if (msg != MSG_ASYNC_DECODER) { // error! return; } m_message_pending = false; // consume some data and post a new message if (!m_buf.IsEmpty()) { // consume at most 4k at a time size_t bytes_to_consume = min(4096, m_buf.GetSize()); int resendBytes; m_impl->DecodeData(m_buf.GetContent(), bytes_to_consume, TRUE, resendBytes); m_buf.Consume(bytes_to_consume); OnPortionDecoded(); } if (!m_buf.IsEmpty()) { g_main_message_handler->PostDelayedMessage(MSG_ASYNC_DECODER, (int)this, 0, 1000); m_message_pending = true; } } // ----------------------------------------------------------------------- // ImageDecoderListener void ImageDecoderAsync::GetLineFromBitmap(void* data, UINT32 line, UINT32 lineHeight) { m_listener->GetLineFromBitmap(data, line, lineHeight); } void ImageDecoderAsync::OnLineDecoded(void* data, UINT32 line, UINT32 lineHeight) { m_listener->OnLineDecoded(data, line, lineHeight); } void ImageDecoderAsync::OnInitMainFrame(UINT32 width, UINT32 height) { m_listener->OnInitMainFrame(width, height); } void ImageDecoderAsync::OnNewFrame(OpBitmap* bitmap) { m_listener->OnNewFrame(bitmap); } void ImageDecoderAsync::OnNewFrame(UINT32 width, UINT32 height, INT32 x, INT32 y , BOOL interlaced, BOOL transparent, BOOL alpha, UINT32 duration, DisposalMethod disposalMethod, UINT32 bitsPerPixel) { m_listener->OnNewFrame(width, height, x, y, interlaced, transparent, alpha, duration, disposalMethod, bitsPerPixel); } void ImageDecoderAsync::OnAnimationInfo(INT32 nrOfRepeats) { m_listener->OnAnimationInfo(nrOfRepeats); } void ImageDecoderAsync::OnDecodingFinished() { m_listener->OnDecodingFinished(); } OpBitmap* ImageDecoderAsync::GetCurrentBitmap() { return m_listener->GetCurrentBitmap(); } void ImageDecoderAsync::OnPortionDecoded() { m_listener->OnPortionDecoded(); } // ----------------------------------------------------------------------- #endif // ASYNC_IMAGE_DECODERS_EMULATION
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "accelerator_library.hpp" #include <stdexcept> #include "sorting_module_setup.hpp" using orkhestrafs::dbmstodspi::AcceleratorLibrary; auto AcceleratorLibrary::IsIncompleteOperationSupported(QueryOperationType operation_type) -> bool { auto* driver = GetDriver(operation_type); return driver->IsIncompleteNodeExecutionSupported(); } void AcceleratorLibrary::SetupOperation( const AcceleratedQueryNode& node_parameters) { auto* driver = GetDriver(node_parameters.operation_type); recent_setup_modules_.clear(); // TODO(Kaspar): Put into a for loop for composed modules. auto current_module = driver->CreateModule( memory_manager_, node_parameters.operation_module_location); driver->SetupModule(*current_module, node_parameters); recent_setup_modules_.push_back(std::move(current_module)); } auto AcceleratorLibrary::GetDMAModule() -> std::unique_ptr<DMAInterface> { return dma_setup_->CreateDMAModule(memory_manager_); } auto AcceleratorLibrary::ExportLastModulesIfReadback() -> std::vector<std::unique_ptr<ReadBackModule>> { std::vector<std::unique_ptr<ReadBackModule>> resulting_vector; for (auto& recent_setup_module : recent_setup_modules_) { auto* cast_check = dynamic_cast<ReadBackModule*>(recent_setup_module.get()); if (cast_check) { std::unique_ptr<ReadBackModule> my_new_pointer( dynamic_cast<ReadBackModule*>( std::move(recent_setup_module).release())); resulting_vector.push_back(std::move(my_new_pointer)); } } recent_setup_modules_.clear(); return resulting_vector; } auto AcceleratorLibrary::GetDMAModuleSetup() -> DMASetupInterface& { return *dma_setup_; } auto AcceleratorLibrary::GetILAModule() -> std::unique_ptr<ILA> { // return std::make_unique<ILA>(memory_manager_.get()); return nullptr; } auto AcceleratorLibrary::IsMultiChannelStream(bool is_input, int stream_index, QueryOperationType operation_type) -> bool { auto* driver = GetDriver(operation_type); return driver->IsMultiChannelStream(is_input, stream_index); } auto AcceleratorLibrary::GetMultiChannelParams( bool is_input, int stream_index, QueryOperationType operation_type, const std::vector<std::vector<int>>& operation_parameters) -> std::pair<int, std::vector<int>> { auto* driver = GetDriver(operation_type); return driver->GetMultiChannelParams(is_input, stream_index, operation_parameters); } auto AcceleratorLibrary::GetDriver(QueryOperationType operation_type) -> AccelerationModuleSetupInterface* { auto search = module_driver_library_.find(operation_type); if (search != module_driver_library_.end()) { return search->second.get(); } throw std::runtime_error("Operator driver not found!"); } auto AcceleratorLibrary::GetNodeCapacity( QueryOperationType operation_type, const std::vector<std::vector<int>>& operation_parameters) -> std::vector<int> { auto* driver = GetDriver(operation_type); return driver->GetCapacityRequirement(operation_parameters); } auto AcceleratorLibrary::IsNodeConstrainedToFirstInPipeline( QueryOperationType operation_type) -> bool { auto* driver = GetDriver(operation_type); return driver->IsConstrainedToFirstInPipeline(); } auto AcceleratorLibrary::IsOperationSorting(QueryOperationType operation_type) -> bool { auto* driver = GetDriver(operation_type); return driver->IsSortingInputTable(); } auto AcceleratorLibrary::GetMinSortingRequirements( QueryOperationType operation_type, const TableMetadata& table_data) -> std::vector<int> { auto* driver = dynamic_cast<SortingModuleSetup*>(GetDriver(operation_type)); if (driver) { return driver->GetMinSortingRequirementsForTable(table_data); } throw std::runtime_error("Non sorting operation given!"); } auto AcceleratorLibrary::GetWorstCaseProcessedTables( QueryOperationType operation_type, const std::vector<int>& min_capacity, const std::vector<std::string>& input_tables, const std::map<std::string, TableMetadata>& data_tables, const std::vector<std::string>& output_table_names) -> std::map<std::string, TableMetadata> { auto* driver = GetDriver(operation_type); return driver->GetWorstCaseProcessedTables(min_capacity, input_tables, data_tables, output_table_names); } auto AcceleratorLibrary::UpdateDataTable( QueryOperationType operation_type, const std::vector<int>& module_capacity, const std::vector<std::string>& input_table_names, std::map<std::string, TableMetadata>& resulting_tables) -> bool { auto* driver = GetDriver(operation_type); return driver->UpdateDataTable(module_capacity, input_table_names, resulting_tables); } auto AcceleratorLibrary::SetMissingFunctionalCapacity( const std::vector<int>& bitstream_capacity, std::vector<int>& missing_capacity, const std::vector<int>& node_capacity, bool is_composed, QueryOperationType operation_type) -> bool { auto* driver = GetDriver(operation_type); return driver->SetMissingFunctionalCapacity( bitstream_capacity, missing_capacity, node_capacity, is_composed); } auto AcceleratorLibrary::IsInputSupposedToBeSorted( QueryOperationType operation_type) -> bool { auto* driver = GetDriver(operation_type); return driver->InputHasToBeSorted(); } auto AcceleratorLibrary::GetResultingTables( QueryOperationType operation, const std::vector<std::string>& table_names, const std::map<std::string, TableMetadata>& tables) -> std::vector<std::string> { auto* driver = GetDriver(operation); return driver->GetResultingTables(tables, table_names); } auto AcceleratorLibrary::IsOperationReducingData(QueryOperationType operation) -> bool { auto* driver = GetDriver(operation); return driver->IsReducingData(); } auto AcceleratorLibrary::IsOperationDataSensitive(QueryOperationType operation) -> bool { auto* driver = GetDriver(operation); return driver->IsDataSensitive(); } auto AcceleratorLibrary::GetEmptyModuleNode(QueryOperationType operation, int module_position, const std::vector<int>& module_capacity) -> AcceleratedQueryNode { auto* driver = GetDriver(operation); AcceleratedQueryNode passthrough_module_node = driver->GetPassthroughInitParameters(module_capacity); passthrough_module_node.operation_type = operation; passthrough_module_node.operation_module_location = module_position; passthrough_module_node.composed_module_locations = {}; return passthrough_module_node; } auto AcceleratorLibrary::GetWorstCaseNodeCapacity( QueryOperationType operation_type, const std::vector<int>& min_capacity, const std::vector<std::string>& input_tables, const std::map<std::string, TableMetadata>& data_tables, QueryOperationType next_operation_type) -> std::vector<int> { auto* driver = GetDriver(operation_type); return driver->GetWorstCaseNodeCapacity(min_capacity, input_tables, data_tables, next_operation_type); }
//Phoenix_RK /* Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules: In the beginning, you have the permutation P=[1,2,3,...,m]. For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i]. Return an array containing the result for the given queries. */ class Solution { public: vector<int> processQueries(vector<int>& queries, int m) { vector<int> res; map<int,int> ind; for(int i=1;i<=m;i++) ind[i]=i-1; for(int it=0;it<queries.size();it++) { int currindex=ind[queries[it]]; for(int i=1;i<=m;i++) { if(i==queries[it]) { res.push_back(currindex); ind[queries[it]]=0; } else if(ind[i]<currindex) ind[i]++; } /* for(int i=1;i<=m;i++) cout<<i<<" "; cout<<endl; for(int i=1;i<=m;i++) cout<<ind[i]<<" "; cout<<endl<<endl; */ } return res; } }; /* 1 2 3 4 5 0 3 1 4 5 3 1 2 1 res 2 1 map 1 2 3 4 5 6 7 8 4 0 5 1 6 7 2 3 8 7 4 2 8 1 7 7 res 7 7 5 4 */
// // numbers.hpp // DataStructures // // Created by Tri Khuu on 2/14/18. // Copyright © 2018 TK. All rights reserved. // #ifndef numbers_hpp #define numbers_hpp #include <cstdint> #include <iostream> #include <string> using std::string; using std::cout; using std::endl; namespace Number { static const uint64_t _max_unsigned_int_word = 999999999999999999; static const string _single_num_words[] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; static const string _teen_num_words[] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; static const string _double_num_words[] = {"", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"}; static const string _power_num_words[] = {"", "thousand", "million", "billion", "trillion", "quadrillion"}; static const string _hyphen = "-"; static const string _space = " "; class AbsNumber { public: virtual string ToWord() const = 0; }; class UnsignedInteger : public Number::AbsNumber { uint64_t _value; // Convert a number with less than or equal to 3 digits to words string _ToWord3Digits(uint64_t&) const; public: UnsignedInteger(); UnsignedInteger(const uint64_t&); UnsignedInteger(const UnsignedInteger&); ~UnsignedInteger(); UnsignedInteger& operator = (const UnsignedInteger&); string ToWord() const; }; }; #endif /* numbers_hpp */
#include "EmonLib.h" //INCLUSÃO DE BIBLIOTECA #define CURRENT_CAL 12.50 //VALOR DE CALIBRAÇÃO (DEVE SER AJUSTADO EM PARALELO COM UM MULTÍMETRO MEDINDO A CORRENTE DA CARGA) #define tensao 110 const int pinoSensor = A2; //PINO ANALÓGICO EM QUE O SENSOR ESTÁ CONECTADO float ruido = 0.08; //RUÍDO PRODUZIDO NA SAÍDA DO SENSOR (DEVE SER AJUSTADO COM A CARGA DESLIGADA APÓS CARREGAMENTO DO CÓDIGO NO ARDUINO) unsigned long d_tempo = 0; double consumo; double consumo_Wh; EnergyMonitor emon1; //CRIA UMA INSTÂNCIA void setup(){ Serial.begin(9600); //INICIALIZA A SERIAL emon1.current(pinoSensor, CURRENT_CAL); //PASSA PARA A FUNÇÃO OS PARÂMETROS (PINO ANALÓGIO / VALOR DE CALIBRAÇÃO) } void loop(){ emon1.calcVI(20,100); //FUNÇÃO DE CÁLCULO (20 SEMICICLOS / TEMPO LIMITE PARA FAZER A MEDIÇÃO) double currentDraw = emon1.Irms; //VARIÁVEL RECEBE O VALOR DE CORRENTE RMS OBTIDO currentDraw = currentDraw-ruido; //VARIÁVEL RECEBE O VALOR RESULTANTE DA CORRENTE RMS MENOS O RUÍDO if(currentDraw < 0){ //SE O VALOR DA VARIÁVEL FOR MENOR QUE 0, FAZ currentDraw = 0; //VARIÁVEL RECEBE 0 } if(millis()- d_tempo > 1000){ consumo += (currentDraw*tensao)/3600000; //CONSUMO PELA VARIAÇÃO DE UM SEGUNDO. CONVERSÃO PARA kWh consumo_Wh += (currentDraw*tensao)/3600; //CONSUMO PELA VARIAÇÃO DE UM SEGUNDO. CONVERSÃO PARA Wh d_tempo = millis(); Serial.println("Rodei - consumo"); } Serial.print("Corrente medida: "); //IMPRIME O TEXTO NA SERIAL Serial.print(currentDraw); //IMPRIME NA SERIAL O VALOR DE CORRENTE MEDIDA Serial.println("A"); //IMPRIME O TEXTO NA SERIAL Serial.print("Potencia calculada: "); //IMPRIME O TEXTO NA SERIAL Serial.print(currentDraw*tensao); ////IMPRIME NA SERIAL O VALOR DA CORRENTE MEDIDA * A TENSÃO NOMINAL DA TOMADA Serial.println("W"); //IMPRIME O TEXTO NA SERIAL Serial.print("Consumo: "); //IMPRIME O TEXTO NA SERIAL Serial.print(consumo_Wh); ////IMPRIME NA SERIAL O VALOR DA CORRENTE MEDIDA * A TENSÃO NOMINAL DA TOMADA Serial.println("Wh"); Serial.print("Consumo: "); //IMPRIME O TEXTO NA SERIAL Serial.print(consumo); ////IMPRIME NA SERIAL O VALOR DA CORRENTE MEDIDA * A TENSÃO NOMINAL DA TOMADA Serial.println("kWh"); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2009 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ /* NOTE! ** This is the old geolocation PI interface. This interface is now ** 100% core-internal. No platforms should implement any of this. */ #ifndef MODULES_GEOLOCATION_GEOLOCATION_H #define MODULES_GEOLOCATION_GEOLOCATION_H #ifdef GEOLOCATION_SUPPORT class OpGeolocationListener; class OpGeolocation { public: /** @short Bitfield specifying the different methods than can be used to find the users positon. */ enum Type { /* Position can be/was obtained through whatever provider was available. */ ANY = -1, /* Position should be/was obtained through GPS */ GPS = 0x01, /* Position was should be/was obtained through WIFI triangulation */ WIFI = 0x02, /* Position was should be/was obtained through cell tower triangulation */ RADIO = 0x04 }; /** @short Object holding geograpical location and possibly more. */ struct Position { /** @short Bitfield describing which fields in this class are valid. */ enum Capabilities { /** Only the mandatory fields are supplied. */ STANDARD = 0x00, /** 'altitude' field is valid */ HAS_ALTITUDE = 0x01, /** 'altitude_accuracy' field is valid */ HAS_ALTITUDEACCURACY = 0x02, /** 'heading' field is valid */ HAS_HEADING = 0x04, /** 'velocity' field is valid */ HAS_VELOCITY = 0x08 }; /** Bitmask of Capabilities specifying which fields are valid */ int capabilities; /** The time the geographic location was aquired in milliseconds since 1970-01-01 00:00 UTC (GMT) (MANDATORY) */ double timestamp; /** Latitude in degrees (MANDATORY) */ double latitude; /** Longitude in degrees (MANDATORY) */ double longitude; /** Latitude and longitude accuracy in meters (MANDATORY) */ double horizontal_accuracy; /** Meters above sea level */ double altitude; /** Altitude accuracy in meters */ double vertical_accuracy; /** Direction in degrees counting clockwise from true north */ double heading; /** Ground speed in meters per second */ double velocity; /** Bitmask of Type specifying what data was used to measure this location. */ int type; /** Depending on what is specified in Position::type, one or more of the * following may contain data. (Currently we only have additional data for radio) */ struct { struct { /** Cell ID (Cell ID (CID) for GSM and Base Station ID (BID) for CDMA). */ int cell_id; } radio; } type_info; OP_STATUS CopyFrom(struct OpGpsData &source, double source_timestamp); }; /** @short Request options to use with StartReception(). */ struct Options { Options() : one_shot(FALSE), high_accuracy(FALSE), timeout(LONG_MAX), maximum_age(0), type (ANY) { } /** One shot or continuous. * * If one_shot == TRUE we only want one set of coordinates, * if it's FALSE we're in continuous mode and want subsequent * calls to OnGeolocationUpdate. */ BOOL one_shot; /** If TRUE, prefer the results as accurate as possible, even if this * means that the request will take longer. */ BOOL high_accuracy; /** Timeout value for initial reception, in milliseconds. */ long timeout; /* Used for caching purposes. Return chached position if it's age * is no more that maximum_age milliseconds old. If maximum_age == * infinity, return cached position regardless of age, OR return new * position if there is no cached position. */ long maximum_age; /* Used to specify that this request should be resolved only via * the specified type of provider. * * default: ANY */ int type; }; /** @short Possible errors that are interesting for core. */ struct Error { enum ErrorCode { /** No error */ ERROR_NONE, /** Generic error */ GENERIC_ERROR, /** Request was denied by user, or something similar */ PERMISSION_ERROR, /** Request failed. GPS receiver returned error or is disabled or similar */ PROVIDER_ERROR, /** The position of the device could not be determined */ POSITION_NOT_FOUND, /** Request timed out */ TIMEOUT_ERROR }; /* Type of error */ ErrorCode error; /* Used to specify what provider caused this error. * * default: ANY */ int type; Error(ErrorCode error, int type) : error(error) , type(type) { } }; /** @short Destructor. * * Cancels the ongoing request, if any. No listener method calls should be * made from the destructor. */ virtual ~OpGeolocation() { } /** @short Start reception of geographical position. * * The core code will asynchronously retrieve new coordinates from the * location provider. Could be WIFI triangulation, GSM triangulation or anything. * The result will be posted back to core by calling * listener->OnGeolocationUpdate() in intervals as specified by * options.update_interval. * * Only one operation at a time is allowed per listener; if a previous call to * StartReception() has not completeid or has not yet been cancelled by StopReception() * previous operation will now be autmatically stopped and replaced by this * one. * * If an error occurs, listener->OnGeolocationError() is called. * Subsequent calls to OnGeolocationError() are allowed. If the request * times out, as defined by options.timeout, * OnGeolocationError(GEOLOCATION_TIMEOUT_ERROR) is called. * * It's okay to ignore the return code from this function. The listener * will be called regardless. * * @param options the requested options for this aqusition. See Options for * details. * @param listener Listener for this operation * @return OK on success, ERR_NO_MEMORY on OOM and ERR on other errors. */ virtual OP_STATUS StartReception(const Options &options, OpGeolocationListener *listener) = 0; /** @short Stop continuous reception of geographical position. * * @param listener Listener for this operation */ virtual void StopReception(OpGeolocationListener *listener) = 0; /** @short Returns current ready state of the geolocation implementation. * * If the next call to StartReception is going to fail this function will * return FALSE. This could happen if there are no data providers available * to feed the geolocation core. * * @return TRUE if ready, FALSE if not. */ virtual BOOL IsReady() = 0; /** @short Returns current state of geolocation availability. * * @return TRUE if geolocation is enabled, FALSE if not. */ virtual BOOL IsEnabled() = 0; /** @short Returns TRUE if the listener is in use, FALSE if not. * * @param listener The listener in question. */ virtual BOOL IsListenerInUse(OpGeolocationListener *listener) = 0; }; /** @short Geolocation listener. * * Methods will be called as a response to a continuous reception of * geographical position issued by OpGeolocation::ReceivePosition(). * * An object of this type serves two purposes: * * - report location updates to to core * - report errors to core */ class OpGeolocationListener { public: virtual ~OpGeolocationListener() { } /** @short New geographical location is available. * * When core has successfully received a new position from the * positioning device, this method is called with the new position. * * @param position The new geographical location */ virtual void OnGeolocationUpdated(const OpGeolocation::Position &position) = 0; /** @short Geographical location reception failed. * * This will cancel the ongoing continuous reception of geographical * position previously requested by OpGeolocation::StartReception(). * * @param error Type of error that occurred. */ virtual void OnGeolocationError(const OpGeolocation::Error &error) = 0; }; #endif // GEOLOCATION_SUPPORT #endif // MODULES_GEOLOCATION_GEOLOCATION_H
#include <iostream> #include<random> #include<time.h> #include <vector> using namespace std; class Group { public: Group() { for (int i = 0; i < count; i++) { group.push_back(i + 1); } } int size() { return group.size(); } void selectCouple(); private: vector<int> group; int count = 12; }; void Group::selectCouple() { int p,q,A,B; p=rand()%group.size(); A=group.at(p); group.erase(group.begin()+p); q=rand()%group.size(); B=group.at(q); group.erase(group.begin()+q); cout<<A<<" VS "<<B<<endl; } int main() { Group G; srand(time(0)); while (G.size()) { G.selectCouple(); } system("pause"); return 0; }
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) Triad National Security, LLC. This file is part of the // Tusas code (LA-CC-17-001) and is subject to the revised BSD license terms // in the LICENSE file found in the top-level directory of this distribution. // ///////////////////////////////////////////////////////////////////////////// #ifndef NOX_THYRA_MODEL_EVALUATOR_TPETRA_DEF_HPP #define NOX_THYRA_MODEL_EVALUATOR_TPETRA_DEF_HPP #include <Teuchos_DefaultComm.hpp> #include <Teuchos_Describable.hpp> #include <Teuchos_ArrayViewDecl.hpp> #include <Teuchos_TimeMonitor.hpp> #include <Teuchos_ParameterList.hpp> #include <Teuchos_XMLParameterListCoreHelpers.hpp> #include "Teuchos_AbstractFactoryStd.hpp" //#include <Kokkos_View.hpp> #include <Kokkos_Vector.hpp> #include <Kokkos_Core.hpp> //#include <Kokkos_CrsMatrix.hpp> #include <Tpetra_Core.hpp> #include <Tpetra_Map.hpp> #include <Tpetra_Map_decl.hpp> #include <Tpetra_Import.hpp> #include <Tpetra_replaceDiagonalCrsMatrix_decl.hpp> #include <Thyra_TpetraThyraWrappers.hpp> #include <Thyra_VectorBase.hpp> #include "Thyra_PreconditionerFactoryBase.hpp" #include <Thyra_TpetraLinearOp_decl.hpp> #include "Thyra_DetachedSpmdVectorView.hpp" //#include <MueLu_ParameterListInterpreter_decl.hpp> //#include <MueLu_MLParameterListInterpreter_decl.hpp> //#include <MueLu_ML2MueLuParameterTranslator.hpp> //#include <MueLu_HierarchyManager.hpp> //#include <MueLu_Hierarchy_decl.hpp> #include <MueLu_CreateTpetraPreconditioner.hpp> #include "Thyra_MueLuPreconditionerFactory.hpp" //#include <Stratimikos_MueLuHelpers.hpp> #include "NOX_Thyra_MatrixFreeJacobianOperator.hpp" #include "NOX_MatrixFree_ModelEvaluatorDecorator.hpp" #include <algorithm> //#include <string> #include "function_def.hpp" #include "ParamNames.h" #define TUSAS_RUN_ON_CPU // IMPORTANT!!! this macro should be set to TUSAS_MAX_NUMEQS * BASIS_NODES_PER_ELEM #define TUSAS_MAX_NUMEQS_X_BASIS_NODES_PER_ELEM 40 std::string getmypidstring(const int mypid, const int numproc); template<class Scalar> class tusasjfnkOp :virtual public NOX::Thyra::MatrixFreeJacobianOperator<Scalar>, public Thyra::ScaledLinearOpBase<Scalar> { public: tusasjfnkOp(Teuchos::ParameterList &printParams):NOX::Thyra::MatrixFreeJacobianOperator<Scalar>(printParams), Thyra::ScaledLinearOpBase<Scalar>() {}; ~tusasjfnkOp(){}; bool supportsScaleLeftImpl() const {return true;}; bool supportsScaleRightImpl() const {return false;}; Teuchos::RCP< ::Thyra::VectorBase<Scalar> > scaling; void scaleLeftImpl (const VectorBase< Scalar > &row_scaling){ // using Teuchos::rcpFromRef; // const RCP<const Tpetra::Vector<Scalar,Tpetra::Vector<>::local_ordinal_type,Tpetra::Vector<>::global_ordinal_type,Tpetra::Vector<>::node_type> > rs = // TpetraOperatorVectorExtraction<Scalar,Tpetra::Vector<>::local_ordinal_type,Tpetra::Vector<>::global_ordinal_type,Tpetra::Vector<>::node_type>::getConstTpetraVector(rcpFromRef(row_scaling)); // Teuchos::RCP< Thyra::VectorBase< double > > f = NOX::Thyra::MatrixFreeJacobianOperator<Scalar>::f_perturb_; // RCP<Tpetra::Vector<Scalar,Tpetra::Vector<>::local_ordinal_type,Tpetra::Vector<>::global_ordinal_type,Tpetra::Vector<>::node_type> > fs = // TpetraOperatorVectorExtraction<Scalar,Tpetra::Vector<>::local_ordinal_type,Tpetra::Vector<>::global_ordinal_type,Tpetra::Vector<>::node_type>::getTpetraVector(f); // fs->scale(1.,*rs); // Scalar delta = this->getDelta(); // std::cout<<"scaleLeftImpl "<<norm(row_scaling)<<std::endl; // ele_wise_scale(row_scaling,f.ptr()); //probably want scaling = row_scaling*scaling here, ie ele_wise_scale(row_scaling,scaling.ptr()); //scaling = row_scaling.clone_v(); }; void scaleRightImpl (const VectorBase< Scalar > &col_scaling){}; RCP< const VectorSpaceBase< Scalar > > range() const {return NOX::Thyra::MatrixFreeJacobianOperator<Scalar>::range();}; RCP< const VectorSpaceBase< Scalar > > domain() const {return NOX::Thyra::MatrixFreeJacobianOperator<Scalar>::domain();}; bool opSupportedImpl(EOpTransp M_trans) const {return false;}; void applyImpl(const EOpTransp M_trans, const MultiVectorBase< Scalar > &X, const Ptr< MultiVectorBase< Scalar > > &Y, const Scalar alpha, const Scalar beta) const { //std::cout<<"applyImpl"<<std::endl; NOX::Thyra::MatrixFreeJacobianOperator<Scalar>::applyImpl(M_trans, X, Y, alpha, beta); if (nonnull(scaling)) ele_wise_scale(*scaling,(Y->col(0)).ptr()); }; }; template<class Scalar> Teuchos::RCP<ModelEvaluatorTPETRA<Scalar> > modelEvaluatorTPETRA( const Teuchos::RCP<const Epetra_Comm>& comm, Mesh *mesh, Teuchos::ParameterList plist ) { return Teuchos::rcp(new ModelEvaluatorTPETRA<Scalar>(mesh,plist)); } // Constructor template<class Scalar> ModelEvaluatorTPETRA<Scalar>:: ModelEvaluatorTPETRA( const Teuchos::RCP<const Epetra_Comm>& comm, Mesh *mesh, Teuchos::ParameterList plist ) : paramList(plist), mesh_(mesh), Comm(comm) { dt_ = paramList.get<double> (TusasdtNameString); dtold_ = dt_; t_theta_ = paramList.get<double> (TusasthetaNameString); t_theta2_ = 0.; numsteps_ = 0; predictor_step = false; corrector_step = false; set_test_case(); auto comm_ = Teuchos::DefaultComm<int>::getComm(); //comm_->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); if( 0 == comm_->getRank()) { if (sizeof(Mesh::mesh_lint_t) != sizeof(global_ordinal_type) ){ std::cout<<"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<std::endl; std::cout<<"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<std::endl; std::cout<<" WARNING:: sizeof(Mesh::mesh_lint_t) != sizeof(global_ordinal_type)"<<std::endl; std::cout<<"sizeof(Mesh::mesh_lint_t) = "<<sizeof(Mesh::mesh_lint_t)<<std::endl; std::cout<<"sizeof(long long) = "<<sizeof(long long)<<std::endl; std::cout<<"<sizeof(global_ordinal_type) = "<<sizeof(global_ordinal_type)<<std::endl<<std::endl; std::cout<<"This is due to incompatablility with global_ordinal_type in Trilinos"<<std::endl; std::cout<<"Mesh::mesh_lint_t in Tusas. Can be addressed via -DNO_MESH_64."<<std::endl; std::cout<<"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<std::endl; std::cout<<"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<std::endl; } } //mesh_ = Teuchos::rcp(new Mesh(*mesh)); mesh_->compute_nodal_adj(); std::vector<Mesh::mesh_lint_t> node_num_int(mesh_->get_node_num_map()); std::vector<Mesh::mesh_lint_t>::iterator max; std::vector<Mesh::mesh_lint_t>::iterator min; max = std::max_element(node_num_int.begin(), node_num_int.end()); min = std::min_element(node_num_int.begin(), node_num_int.end()); if(*min < (Mesh::mesh_lint_t) 0){ if( 0 == comm_->getRank()){ std::cout<<"node_num_int: bad min value"<<std::endl<<std::endl; } //std::cout<<*min<<" "<<*max<<" "<<LLONG_MAX<<" "<<node_num_int.max_size()<<std::endl; exit(0); } if( 0 == comm_->getRank()) std::cout<<"node_num_int constructed"<<std::endl; //std::vector<global_ordinal_type> node_num_map(node_num_int.begin(),node_num_int.end()); std::vector<global_ordinal_type> node_num_map(node_num_int.size()); for( int i = 0; i < node_num_int.size(); i++ ) node_num_map[i] = (global_ordinal_type)node_num_int[i]; std::vector<global_ordinal_type>::iterator maxg; std::vector<global_ordinal_type>::iterator ming; maxg = std::max_element(node_num_map.begin(), node_num_map.end()); ming = std::min_element(node_num_map.begin(), node_num_map.end()); if(*ming < (global_ordinal_type) 0){ if( 0 == comm_->getRank()){ std::cout<<"node_num_map: bad min value"<<std::endl<<std::endl; } //std::cout<<*min<<" "<<*max<<" "<<LLONG_MAX<<" "<<node_num_int.max_size()<<std::endl; exit(0); } if( 0 == comm_->getRank()) std::cout<<"node_num_map constructed"<<std::endl; std::vector<global_ordinal_type> my_global_nodes(numeqs_*node_num_map.size()); for(int i = 0; i < node_num_map.size(); i++){ global_ordinal_type ngid = node_num_map[i]; for( int k = 0; k < numeqs_; k++ ){ my_global_nodes[numeqs_*i+k] = numeqs_*ngid+k; //my_global_nodes[numeqs_*i+k] = (global_ordinal_type)numeqs_*(global_ordinal_type)node_num_int[i]+(global_ordinal_type)k; } } const global_size_t numGlobalEntries = Teuchos::OrdinalTraits<Tpetra::global_size_t>::invalid(); const global_ordinal_type indexBase = 0; const Teuchos::ArrayView<global_ordinal_type> AV(my_global_nodes); x_overlap_map_ = Teuchos::rcp(new map_type(numGlobalEntries, AV, indexBase, comm_ )); //x_overlap_map_ ->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); GreedyTieBreak<local_ordinal_type,global_ordinal_type> greedy_tie_break; x_owned_map_ = Teuchos::rcp(new map_type(*(Tpetra::createOneToOne(x_overlap_map_,greedy_tie_break)))); //x_owned_map_ ->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); importer_ = Teuchos::rcp(new import_type(x_owned_map_, x_overlap_map_)); //exporter_ = Teuchos::rcp(new export_type(x_owned_map_, x_overlap_map_)); exporter_ = Teuchos::rcp(new export_type(x_overlap_map_, x_owned_map_)); num_owned_nodes_ = x_owned_map_->getNodeNumElements()/numeqs_; num_overlap_nodes_ = x_overlap_map_->getNodeNumElements()/numeqs_; Teuchos::ArrayView<global_ordinal_type> NV(node_num_map); node_overlap_map_ = Teuchos::rcp(new map_type(numGlobalEntries, NV, indexBase, comm_ )); node_owned_map_ = Teuchos::rcp(new map_type(*(Tpetra::createOneToOne(node_overlap_map_,greedy_tie_break)))); //cn we could store previous time values in a multivector u_old_ = Teuchos::rcp(new vector_type(x_owned_map_)); u_old_->putScalar(Teuchos::ScalarTraits<scalar_type>::zero()); u_old_old_ = Teuchos::rcp(new vector_type(x_owned_map_)); u_old_old_->putScalar(Teuchos::ScalarTraits<scalar_type>::zero()); u_new_ = Teuchos::rcp(new vector_type(x_owned_map_)); u_new_->putScalar(Teuchos::ScalarTraits<scalar_type>::zero()); pred_temp_ = Teuchos::rcp(new vector_type(x_owned_map_)); pred_temp_->putScalar(Teuchos::ScalarTraits<scalar_type>::zero()); x_ = Teuchos::rcp(new vector_type(node_overlap_map_)); y_ = Teuchos::rcp(new vector_type(node_overlap_map_)); z_ = Teuchos::rcp(new vector_type(node_overlap_map_)); //Teuchos::ArrayRCP<scalar_type> xv = x_->get1dViewNonConst(); { auto xv = x_->get1dViewNonConst(); auto yv = y_->get1dViewNonConst(); auto zv = z_->get1dViewNonConst(); const size_t localLength = node_overlap_map_->getNodeNumElements(); //for (size_t nn=0; nn < localLength; nn++) { Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultHostExecutionSpace>(0,localLength),[=](const int& nn){ xv[nn] = mesh_->get_x(nn); yv[nn] = mesh_->get_y(nn); zv[nn] = mesh_->get_z(nn); }); } x_space_ = Thyra::createVectorSpace<scalar_type>(x_owned_map_); f_space_ = x_space_; //x0_ = Thyra::createMember(x_space_); x0_ = Teuchos::rcp(new vector_type(x_owned_map_)); x0_->putScalar(Teuchos::ScalarTraits<scalar_type>::zero()); bool precon = paramList.get<bool> (TusaspreconNameString); if(precon){ // Initialize the graph for W CrsMatrix object W_graph_ = createGraph(); W_overlap_graph_ = createOverlapGraph(); P = rcp(new matrix_type(W_overlap_graph_)); P_ = rcp(new matrix_type(W_graph_)); P->setAllToScalar((scalar_type)1.0); P->fillComplete(); //P->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); //cn we need to fill the matrix for muelu init_P_(); //P_->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); Teuchos::ParameterList mueluParamList; std::string optionsFile = "mueluOptions.xml"; Teuchos::updateParametersFromXmlFileAndBroadcast(optionsFile,Teuchos::Ptr<Teuchos::ParameterList>(&mueluParamList), *P_->getComm()); if( mueluParamList.get<bool>("repartition: enable",false) ){ muelucoords_ = Teuchos::rcp(new mv_type(node_owned_map_, (size_t)3)); auto xv = x_->get1dViewNonConst(); auto yv = y_->get1dViewNonConst(); auto zv = z_->get1dViewNonConst(); const size_t localLength = node_owned_map_->getNodeNumElements(); //for(int i = 0; i< localLength; i++){ Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultHostExecutionSpace>(0,localLength),[=](const int& i){ const global_ordinal_type gid = (node_owned_map_->getGlobalElement(i)); const global_ordinal_type lid = node_overlap_map_->getLocalElement(gid); //std::cout<<gid<<" "<<lid<<" "<<xv[lid]<<std::endl; muelucoords_->replaceLocalValue ((local_ordinal_type)i, (size_t) 0, xv[lid]); muelucoords_->replaceLocalValue ((local_ordinal_type)i, (size_t) 1, yv[lid]); muelucoords_->replaceLocalValue ((local_ordinal_type)i, (size_t) 2, zv[lid]); }); //}//i //muelucoords_->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); Teuchos::ParameterList &userDataList = mueluParamList.sublist("user data"); userDataList.set<RCP<mv_type> >("Coordinates",muelucoords_); mueluParamList.set("number of equations",numeqs_); } if( 0 == comm_->getRank() ){ std::cout << "\nReading MueLu parameter list from the XML file \""<<optionsFile<<"\" ...\n"; mueluParamList.print(std::cout, 2, true, true ); } //prec_ = MueLu::CreateTpetraPreconditioner<scalar_type,local_ordinal_type, global_ordinal_type, node_type>(P_, mueluParamList); prec_ = MueLu::CreateTpetraPreconditioner<scalar_type,local_ordinal_type, global_ordinal_type, node_type> ((Teuchos::RCP<Tpetra::Operator<scalar_type,local_ordinal_type, global_ordinal_type, node_type> >)P_, mueluParamList); if( 0 == comm_->getRank() ){ std::cout <<" MueLu preconditioner created"<<std::endl<<std::endl; } } Thyra::ModelEvaluatorBase::InArgsSetup<scalar_type> inArgs; inArgs.setModelEvalDescription(this->description()); inArgs.setSupports(Thyra::ModelEvaluatorBase::IN_ARG_x); prototypeInArgs_ = inArgs; Thyra::ModelEvaluatorBase::OutArgsSetup<scalar_type> outArgs; outArgs.setModelEvalDescription(this->description()); outArgs.setSupports(Thyra::ModelEvaluatorBase::OUT_ARG_f); outArgs.setSupports(Thyra::ModelEvaluatorBase::OUT_ARG_W_prec); prototypeOutArgs_ = outArgs; nominalValues_ = inArgs; //nominalValues_.set_x(x0_); nominalValues_.set_x(Thyra::createVector(x0_, x_space_)); time_=0.; ts_time_import= Teuchos::TimeMonitor::getNewTimer("Tusas: Total Import Time"); ts_time_resfill= Teuchos::TimeMonitor::getNewTimer("Tusas: Total Residual Fill Time"); ts_time_precfill= Teuchos::TimeMonitor::getNewTimer("Tusas: Total Preconditioner Fill Time"); ts_time_nsolve= Teuchos::TimeMonitor::getNewTimer("Tusas: Total Nonlinear Solver Time"); ts_time_view= Teuchos::TimeMonitor::getNewTimer("Tusas: Total View Time"); ts_time_iowrite= Teuchos::TimeMonitor::getNewTimer("Tusas: Total IO Write Time"); ts_time_temperr= Teuchos::TimeMonitor::getNewTimer("Tusas: Total Temporal Error Est Time"); ts_time_predsolve= Teuchos::TimeMonitor::getNewTimer("Tusas: Total Predictor Solve Time"); //ts_time_ioread= Teuchos::TimeMonitor::getNewTimer("Tusas: Total IO Read Time"); //HACK //cn 8-28-18 currently elem_color takes an epetra_mpi_comm.... //there are some epetra_maps and a routine that does mpi calls for off proc comm const //Comm = Teuchos::rcp(new Epetra_MpiComm( MPI_COMM_WORLD )); bool dorestart = paramList.get<bool> (TusasrestartNameString); Elem_col = Teuchos::rcp(new elem_color(Comm,mesh,dorestart)); if( paramList.get<bool>(TusasrandomDistributionNameString) ){ const int LTP_quadrature_order = paramList.get<int> (TusasltpquadordNameString); randomdistribution = Teuchos::rcp(new random_distribution(Comm, mesh_, LTP_quadrature_order)); } std::vector<int> indices = (Teuchos::getArrayFromStringParameter<int>(paramList, TusaserrorestimatorNameString)).toVector(); std::vector<int>::iterator it; for(it = indices.begin();it != indices.end(); ++it){ //std::cout<<*it<<" "<<std::endl; int error_index = *it; Error_est.push_back(new error_estimator(Comm,mesh_,numeqs_,error_index)); } //initialize(); init_nox(); // Teuchos::ParameterList *atsList; // atsList = &paramList.sublist (TusasatslistNameString, false ); // //initial solve need by second derivative error estimate // //and for lagged coupled time derivatives // //ie get a solution at u_{-1} // if(((atsList->get<std::string> (TusasatstypeNameString) == "second derivative") // &&paramList.get<bool> (TusasestimateTimestepNameString)) // ||((atsList->get<std::string> (TusasatstypeNameString) == "predictor corrector") // &&paramList.get<bool> (TusasestimateTimestepNameString)&&t_theta_ < 1.) // ||paramList.get<bool> (TusasinitialSolveNameString)){ // initialsolve(); // }//if } template<class Scalar> Teuchos::RCP<Tpetra::CrsMatrix<>::crs_graph_type> ModelEvaluatorTPETRA<Scalar>::createGraph() { Teuchos::RCP<crs_graph_type> W_graph; int numind = 17*numeqs_;//this is an approximation 17 for lquad; 25?? for qquad; 81*3 for lhex; 25*3 for qhex; 6 ltris ??, tets ?? //this was causing problems with clang if(3 == mesh_->get_num_dim() ) numind = 81*numeqs_; size_t ni = numind; W_graph = Teuchos::rcp(new crs_graph_type(x_owned_map_, ni)); for(int blk = 0; blk < mesh_->get_num_elem_blks(); blk++){ int n_nodes_per_elem = mesh_->get_num_nodes_per_elem_in_blk(blk); for (int ne=0; ne < mesh_->get_num_elem_in_blk(blk); ne++) { for (int i=0; i< n_nodes_per_elem; i++) { int row = numeqs_*( mesh_->get_global_node_id(mesh_->get_node_id(blk, ne, i)) ); for(int j=0;j < n_nodes_per_elem; j++) { int column = numeqs_*(mesh_->get_global_node_id(mesh_->get_node_id(blk, ne, j))); for( int k = 0; k < numeqs_; k++ ){ global_ordinal_type row1 = row + k; global_ordinal_type column1 = column + k; Teuchos::ArrayView<global_ordinal_type> CV(&column1,1); //W_graph->InsertGlobalIndices((int)1,&row1, (int)1, &column1); //W_graph->insertGlobalIndices(row1, (local_ordinal_type)1, column1); W_graph->insertGlobalIndices(row1, CV); } } } } } W_graph->fillComplete(); //W_graph->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); //exit(0); return W_graph; } template<class Scalar> Teuchos::RCP<Tpetra::CrsMatrix<>::crs_graph_type> ModelEvaluatorTPETRA<Scalar>::createOverlapGraph() { // auto comm_ = Teuchos::DefaultComm<int>::getComm(); // int mypid = comm_->getRank() ; // if( 0 == mypid ) // std::cout<<std::endl<<"createOverlapGraph() started."<<std::endl<<std::endl; Teuchos::RCP<crs_graph_type> W_graph; int numind = 17*numeqs_;//this is an approximation 9 for lquad; 25 for qquad; 9*3 for lhex; 25*3 for qhex; 6 ltris ??, tets ?? //this was causing problems with clang if(3 == mesh_->get_num_dim() ) numind = 81*numeqs_; size_t ni = numind; W_graph = Teuchos::rcp(new crs_graph_type(x_overlap_map_, ni)); for(int blk = 0; blk < mesh_->get_num_elem_blks(); blk++){ const int n_nodes_per_elem = mesh_->get_num_nodes_per_elem_in_blk(blk); const int num_elem = (*mesh_->get_elem_num_map()).size(); for (int ne=0; ne < num_elem; ne++) { for (int i=0; i< n_nodes_per_elem; i++) { const global_ordinal_type row = numeqs_*( mesh_->get_global_node_id(mesh_->get_node_id(blk, ne, i)) ); for(int j=0;j < n_nodes_per_elem; j++) { const global_ordinal_type column = numeqs_*(mesh_->get_global_node_id(mesh_->get_node_id(blk, ne, j))); for( int k = 0; k < numeqs_; k++ ){ const global_ordinal_type row1 = row + k; global_ordinal_type column1 = column + k; Teuchos::ArrayView<global_ordinal_type> CV(&column1,1); //W_graph->InsertGlobalIndices((int)1,&row1, (int)1, &column1); //W_graph->insertGlobalIndices(row1, (local_ordinal_type)1, column1); W_graph->insertGlobalIndices(row1, CV); } } } } } W_graph->fillComplete(); //W_graph->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME );; //exit(0); // if( 0 == mypid ) // std::cout<<std::endl<<"createOverlapGraph() ended."<<std::endl<<std::endl; return W_graph; } template<class Scalar> void ModelEvaluatorTPETRA<Scalar>::evalModelImpl( const Thyra::ModelEvaluatorBase::InArgs<Scalar> &inArgs, const Thyra::ModelEvaluatorBase::OutArgs<Scalar> &outArgs ) const { //inArgs.describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); //std::cout<<inArgs.description()<<std::endl;; //exit(0); //cn the easiest way probably to do the sum into off proc nodes is to load a //vector(overlap_map) the export with summation to the f_vec(owned_map) //after summing into. ie import is uniquely-owned to multiply-owned //export is multiply-owned to uniquely-owned auto comm_ = Teuchos::DefaultComm<int>::getComm(); typedef Thyra::TpetraOperatorVectorExtraction<Scalar,int> ConverterT; const Teuchos::RCP<const vector_type > x_vec = ConverterT::getConstTpetraVector(inArgs.get_x()); Teuchos::RCP<vector_type > u = Teuchos::rcp(new vector_type(x_overlap_map_)); Teuchos::RCP<vector_type > uold = Teuchos::rcp(new vector_type(x_overlap_map_)); Teuchos::RCP<vector_type > uoldold = Teuchos::rcp(new vector_type(x_overlap_map_)); { Teuchos::TimeMonitor ImportTimer(*ts_time_import); u->doImport(*x_vec,*importer_,Tpetra::INSERT); uold->doImport(*u_old_,*importer_,Tpetra::INSERT); uoldold->doImport(*u_old_old_,*importer_,Tpetra::INSERT); } auto x_view = x_->getLocalViewDevice(Tpetra::Access::ReadOnly); auto y_view = y_->getLocalViewDevice(Tpetra::Access::ReadOnly); auto z_view = z_->getLocalViewDevice(Tpetra::Access::ReadOnly); //using RandomAccess should give better memory performance on better than tesla gpus (guido is tesla and does not show performance increase) //this will utilize texture memory not available on tesla or earlier gpus Kokkos::View<const double*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> x_1dra = Kokkos::subview (x_view, Kokkos::ALL (), 0); Kokkos::View<const double*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> y_1dra = Kokkos::subview (y_view, Kokkos::ALL (), 0); Kokkos::View<const double*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> z_1dra = Kokkos::subview (z_view, Kokkos::ALL (), 0); auto u_view = u->getLocalViewDevice(Tpetra::Access::ReadOnly); Kokkos::View<const double*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> u_1dra = Kokkos::subview (u_view, Kokkos::ALL (), 0); const int blk = 0; const int n_nodes_per_elem = mesh_->get_num_nodes_per_elem_in_blk(blk);//shared const int num_color = Elem_col->get_num_color(); Kokkos::View<int*,Kokkos::DefaultExecutionSpace> meshc_1d("meshc_1d",((mesh_->connect)[0]).size()); for(int i = 0; i<((mesh_->connect)[0]).size(); i++) { meshc_1d(i)=(mesh_->connect)[0][i]; } Kokkos::View<const int*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> meshc_1dra(meshc_1d); const double dt = dt_; //cuda 8 lambdas dont capture private data const double dtold = dtold_; //cuda 8 lambdas dont capture private data const double t_theta = t_theta_; //cuda 8 lambdas dont capture private data const double t_theta2 = t_theta2_; //cuda 8 lambdas dont capture private data const double time = time_; //cuda 8 lambdas dont capture private data const int numeqs = numeqs_; //cuda 8 lambdas dont capture private data const int LTP_quadrature_order = paramList.get<int> (TusasltpquadordNameString); if (4 < LTP_quadrature_order ){ if( 0 == comm_->getRank() ){ std::cout<<std::endl<<std::endl<<"4 < LTP_quadrature_order" <<std::endl<<std::endl<<std::endl; } exit(0); } const int num_elem = (*mesh_->get_elem_num_map()).size(); int ngp = 0; //LTP_quadrature_order; if(4 == n_nodes_per_elem) { ngp = LTP_quadrature_order*LTP_quadrature_order; }else{ ngp = LTP_quadrature_order*LTP_quadrature_order*LTP_quadrature_order; } Kokkos::View<double**,Kokkos::DefaultExecutionSpace> randomdistribution_2d("randomdistribution_2d", num_elem, ngp); if( paramList.get<bool>(TusasrandomDistributionNameString) ){ //std::vector<std::vector<double> > vals(randomdistribution->get_gauss_vals()); for( int i=0; i<num_elem; i++){ for(int ig=0;ig<ngp;ig++){ //randomdistribution_2d(i,ig) = vals[i][ig]; randomdistribution_2d(i,ig) = randomdistribution->get_gauss_val(i,ig); //randomdistribution_2d(i,ig) = 0.; } } }else{ for( int i=0; i<num_elem; i++){ for(int ig=0;ig<ngp;ig++){ randomdistribution_2d(i,ig) = 0.; } } }//if if (nonnull(outArgs.get_f())){ const Teuchos::RCP<vector_type> f_vec = ConverterT::getTpetraVector(outArgs.get_f()); Teuchos::RCP<vector_type> f_overlap = Teuchos::rcp(new vector_type(x_overlap_map_)); f_vec->scale(0.); f_overlap->scale(0.); Teuchos::TimeMonitor ResFillTimer(*ts_time_resfill); // std::string elem_type=mesh_->get_blk_elem_type(blk); // std::string * elem_type_p = &elem_type; auto uold_view = uold->getLocalViewDevice(Tpetra::Access::ReadOnly); auto uoldold_view = uoldold->getLocalViewDevice(Tpetra::Access::ReadOnly); auto f_view = f_overlap->getLocalViewDevice(Tpetra::Access::ReadWrite); auto f_1d = Kokkos::subview (f_view, Kokkos::ALL (), 0); //Kokkos::View<double*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> f_1d = Kokkos::subview (f_view, Kokkos::ALL (), 0); //using RandomAccess should give better memory performance on better than tesla gpus (guido is tesla and does not show performance increase) //this will utilize texture memory not available on tesla or earlier gpus Kokkos::View<const double*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> uold_1dra = Kokkos::subview (uold_view, Kokkos::ALL (), 0); Kokkos::View<const double*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> uoldold_1dra = Kokkos::subview (uoldold_view, Kokkos::ALL (), 0); RESFUNC * h_rf; h_rf = (RESFUNC*)malloc(numeqs_*sizeof(RESFUNC)); #ifdef TUSAS_HAVE_CUDA RESFUNC * d_rf; cudaMalloc((double**)&d_rf,numeqs_*sizeof(RESFUNC)); if("heat" == paramList.get<std::string> (TusastestNameString)){ //cn this will need to be done for each equation cudaMemcpyFromSymbol( &h_rf[0], tpetra::residual_heat_test_dp_, sizeof(RESFUNC)); }else if("NLheatIMR" == paramList.get<std::string> (TusastestNameString)){ //cn this will need to be done for each equation cudaMemcpyFromSymbol( &h_rf[0], tpetra::residual_nlheatimr_test_dp_, sizeof(RESFUNC)); }else if("NLheatCN" == paramList.get<std::string> (TusastestNameString)){ //cn this will need to be done for each equation cudaMemcpyFromSymbol( &h_rf[0], tpetra::residual_nlheatcn_test_dp_, sizeof(RESFUNC)); }else if("heat2" == paramList.get<std::string> (TusastestNameString)){ cudaMemcpyFromSymbol( &h_rf[0], tpetra::residual_heat_test_dp_, sizeof(RESFUNC)); cudaMemcpyFromSymbol( &h_rf[1], tpetra::residual_heat_test_dp_, sizeof(RESFUNC)); }else if("farzadi" == paramList.get<std::string> (TusastestNameString)){ cudaMemcpyFromSymbol( &h_rf[0], tpetra::farzadi3d::residual_conc_farzadi_dp_, sizeof(RESFUNC)); cudaMemcpyFromSymbol( &h_rf[1], tpetra::farzadi3d::residual_phase_farzadi_dp_, sizeof(RESFUNC)); }else if("farzadi_test" == paramList.get<std::string> (TusastestNameString)){ cudaMemcpyFromSymbol( &h_rf[0], tpetra::farzadi3d::residual_conc_farzadi_dp_, sizeof(RESFUNC)); cudaMemcpyFromSymbol( &h_rf[1], tpetra::farzadi3d::residual_phase_farzadi_dp_, sizeof(RESFUNC)); }else if("pfhub3" == paramList.get<std::string> (TusastestNameString)){ cudaMemcpyFromSymbol( &h_rf[0], tpetra::pfhub3::residual_heat_pfhub3_dp_, sizeof(RESFUNC)); cudaMemcpyFromSymbol( &h_rf[1], tpetra::pfhub3::residual_phase_pfhub3_dp_, sizeof(RESFUNC)); }else if("pfhub2kks" == paramList.get<std::string> (TusastestNameString)){ cudaMemcpyFromSymbol( &h_rf[0], tpetra::pfhub2::residual_c_kks_dp_, sizeof(RESFUNC)); cudaMemcpyFromSymbol( &h_rf[1], tpetra::pfhub2::residual_eta_kks_dp_, sizeof(RESFUNC)); } else { if( 0 == comm_->getRank() ){ std::cout<<std::endl<<std::endl<<"Test case: "<<paramList.get<std::string> (TusastestNameString) <<" residual function not found. (void ModelEvaluatorTPETRA<Scalar>::evalModelImpl(...))" <<std::endl<<std::endl<<std::endl; } exit(0); } cudaMemcpy(d_rf,h_rf,numeqs_*sizeof(RESFUNC),cudaMemcpyHostToDevice); #else //it seems that evaluating the function via pointer ie h_rf[0] is way faster that evaluation via (*residualfunc_)[0] h_rf = &(*residualfunc_)[0]; #endif for(int c = 0; c < num_color; c++){ //std::vector<int> elem_map = colors[c]; const std::vector<int> elem_map = Elem_col->get_color(c);//local const int num_elem = elem_map.size(); Kokkos::View<int*,Kokkos::DefaultExecutionSpace> elem_map_1d("elem_map_1d",num_elem); //Kokkos::vector<int> elem_map_k(num_elem); for(int i = 0; i<num_elem; i++) { //elem_map_k[i] = elem_map[i]; elem_map_1d(i) = elem_map[i]; } //exit(0); //auto elem_map_2d = Kokkos::subview(elem_map_1d, Kokkos::ALL (), Kokkos::ALL (), 0); //std::cout<<elem_map_2d.extent(0)<<" "<<elem_map_2d.extent(1)<<std::endl; //for (int ne=0; ne < num_elem; ne++) { //#define USE_TEAM #ifdef USE_TEAM #ifdef TUSAS_HAVE_CUDA int team_size = 512;//this is teamsize (#of threads in team) < 1024; preferably 256 #else int team_size = 1;//openmp #endif int num_teams = (num_elem/team_size)+1;//this is # of thread teams (also league size); unlimited Kokkos::View<const int*,Kokkos::DefaultExecutionSpace> elem_map_1dConst(elem_map_1d); // int strides[1]; // any integer type works in stride() // elem_map_1dConst.stride (strides); // std::cout<<strides[0]<<std::endl; typedef Kokkos::TeamPolicy<Kokkos::DefaultExecutionSpace>::member_type member_type; //TeamPolicy <ExecutionSpace >( numberOfTeams , teamSize) Kokkos::TeamPolicy<Kokkos::DefaultExecutionSpace> policy (num_teams, team_size ); //std::cout<<policy.league_size()<<" "<<policy.team_size()<<std::endl; Kokkos::parallel_for (policy, KOKKOS_LAMBDA (member_type team_member) { // Calculate a global thread id int ne = team_member.league_rank () * team_member.team_size () + team_member.team_rank (); if(ne < num_elem) { const int elem = elem_map_1dConst(ne); #else //Kokkos::View<GPUBasisLHex *,Kokkos::DefaultExecutionSpace> bh_view("bh_view"); Kokkos::parallel_for(num_elem,KOKKOS_LAMBDA(const int& ne){//this loop is fine for openmp re access to elem_map //for(int ne =0; ne<num_elem; ne++){ const int elem = elem_map_1d(ne); #endif //GPUBasisLHex * dummy = new (bh_view) GPUBasisLHex(LTP_quadrature_order); GPUBasis * BGPU[TUSAS_MAX_NUMEQS]; //IMPORTANT: if TUSAS_MAX_NUMEQS is increased the following lines (and below in prec fill) //need to be adjusted GPUBasisLQuad Bq[TUSAS_MAX_NUMEQS] = {GPUBasisLQuad(LTP_quadrature_order), GPUBasisLQuad(LTP_quadrature_order), GPUBasisLQuad(LTP_quadrature_order), GPUBasisLQuad(LTP_quadrature_order), GPUBasisLQuad(LTP_quadrature_order)}; GPUBasisLHex Bh[TUSAS_MAX_NUMEQS] = {GPUBasisLHex(LTP_quadrature_order), GPUBasisLHex(LTP_quadrature_order), GPUBasisLHex(LTP_quadrature_order), GPUBasisLHex(LTP_quadrature_order), GPUBasisLHex(LTP_quadrature_order)}; if(4 == n_nodes_per_elem) { for( int neq = 0; neq < numeqs; neq++ ) BGPU[neq] = &Bq[neq]; }else{ for( int neq = 0; neq < numeqs; neq++ ) BGPU[neq] = &Bh[neq]; } const int ngp = BGPU[0]->ngp(); double xx[BASIS_NODES_PER_ELEM]; double yy[BASIS_NODES_PER_ELEM]; double zz[BASIS_NODES_PER_ELEM]; double uu[TUSAS_MAX_NUMEQS_X_BASIS_NODES_PER_ELEM]; double uu_old[TUSAS_MAX_NUMEQS_X_BASIS_NODES_PER_ELEM]; double uu_oldold[TUSAS_MAX_NUMEQS_X_BASIS_NODES_PER_ELEM]; const int elemrow = elem*n_nodes_per_elem; for(int k = 0; k < n_nodes_per_elem; k++){ const int nodeid = meshc_1dra(elemrow+k);//cn this is the local id xx[k] = x_1dra(nodeid); yy[k] = y_1dra(nodeid); zz[k] = z_1dra(nodeid); //zz[k] = z_view(nodeid,0); //std::cout<<k<<" "<<xx[k]<<" "<<yy[k]<<" "<<zz[k]<<" "<<nodeid<<std::endl; for( int neq = 0; neq < numeqs; neq++ ){ //std::cout<<numeqs*k+neq<<" "<<n_nodes_per_elem*neq+k <<" "<<nodeid<<" "<<numeqs_*nodeid+neq<<std::endl; uu[n_nodes_per_elem*neq+k] = u_1dra(numeqs*nodeid+neq); uu_old[n_nodes_per_elem*neq+k] = uold_1dra(numeqs*nodeid+neq); uu_oldold[n_nodes_per_elem*neq+k] = uoldold_1dra(numeqs*nodeid+neq); }//neq }//k for( int neq = 0; neq < numeqs; neq++ ){ BGPU[neq]->computeElemData(&xx[0], &yy[0], &zz[0]); //Bh[neq].computeElemData(&xx[0], &yy[0], &zz[0]); }//neq for(int gp=0; gp < ngp; gp++) {//gp double jacwt = 0.; for( int neq = 0; neq < numeqs; neq++ ){ //we need a basis object that stores all equations here.. jacwt = BGPU[neq]->getBasis(gp, &xx[0], &yy[0], &zz[0], &uu[neq*n_nodes_per_elem], &uu_old[neq*n_nodes_per_elem],&uu_oldold[neq*n_nodes_per_elem]); }//neq const double vol = BGPU[0]->vol();//this can probably be computed in computeElemData, with some of the mapping terms moved there for (int i=0; i< n_nodes_per_elem; i++) {//i //const int lrow = numeqs*meshc[elemrow+i]; const int lrow = numeqs*meshc_1dra(elemrow+i); const double rand = randomdistribution_2d(elem, gp); for( int neq = 0; neq < numeqs; neq++ ){ #ifdef TUSAS_HAVE_CUDA //const double val = 0.;//BGPUarr[0].jac*BGPUarr[0].wt*(d_rf[0](&(BGPUarr[0]),i,dt,t_theta,time,neq)); const double val = jacwt*((d_rf[neq])(BGPU,i,dt,dtold,t_theta,t_theta2,time,neq,vol,rand)); #else //const double val = BGPU->jac*BGPU->wt*(*residualfunc_)[0](BGPU,i,dt,1.,0.,0); //const double val = BGPU->jac*BGPU->wt*(tusastpetra::residual_heat_test_(BGPU,i,dt,1.,0.,0));//cn call directly double val = jacwt*(h_rf[neq](BGPU,i,dt,dtold,t_theta,t_theta2,time,neq,vol,rand)); #endif //cn this works because we are filling an overlap map and exporting to a node map below... const int lid = lrow+neq; f_1d[lid] += val; //printf("%d %le %le %d\n",lid,jacwt*((h_rf[neq])(BGPU,i,dt,t_theta,time,neq)),f_1d[lid],c); }//neq }//i }//gp #ifdef USE_TEAM }//if ne #else #endif });//parallel_for //};//ne }//c #ifdef TUSAS_HAVE_CUDA cudaFree(d_rf); free(h_rf); #endif //exit(0); { Teuchos::TimeMonitor ImportTimer(*ts_time_import); f_vec->doExport(*f_overlap, *exporter_, Tpetra::ADD); //f_vec->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); } }//get_f if (nonnull(outArgs.get_f())) { if (NULL != neumannfunc_) { //we would need to utilize coloring and implement a view for: //mesh_->get_side_set_node_list(ss_id) //in order to get this working with kokkos on openmp, gpu //with a kokkos function for the nbc function // if( (0==elem_type.compare("HEX8")) // || (0==elem_type.compare("HEX")) // || (0==elem_type.compare("hex8")) // || (0==elem_type.compare("hex")) ){ // linear hex // } if(8 == n_nodes_per_elem) { // linear hex-- we need to port the bar element for quads } else { exit(0); } const Teuchos::RCP<vector_type> f_vec = ConverterT::getTpetraVector(outArgs.get_f()); Teuchos::RCP<vector_type> f_overlap = Teuchos::rcp(new vector_type(x_overlap_map_)); //we zero nodes on the nonowning proc here, so that we do not add in the values twice //this also does no communication { Teuchos::TimeMonitor ImportTimer(*ts_time_import); f_overlap->doImport(*f_vec,*importer_,Tpetra::ZERO); } //on host only right now.. auto f_view = f_overlap->getLocalViewHost(Tpetra::Access::ReadWrite); auto f_1d = Kokkos::subview (f_view, Kokkos::ALL (), 0); //this sould be ok //auto u_view = u->getLocalViewHost(Tpetra::Access::ReadOnly); //Kokkos::View<const double*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> // u_1dra = Kokkos::subview (u_view, Kokkos::ALL (), 0); auto uold_view = uold->getLocalViewHost(Tpetra::Access::ReadOnly); Kokkos::View<const double*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> uold_1dra = Kokkos::subview (uold_view, Kokkos::ALL (), 0); auto uoldold_view = uoldold->getLocalViewHost(Tpetra::Access::ReadOnly); Kokkos::View<const double*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> uoldold_1dra = Kokkos::subview (uoldold_view, Kokkos::ALL (), 0); GPUBasisLQuad Bq = GPUBasisLQuad(LTP_quadrature_order); GPUBasis * BGPU = &Bq; const int num_node_per_side = 4; const int ngp = BGPU->ngp(); std::map<int,NBCFUNC>::iterator it; for( int k = 0; k < numeqs_; k++ ){ for(it = (*neumannfunc_)[k].begin();it != (*neumannfunc_)[k].end(); ++it){ //if there are not as many sisesets as there are physical sides, we need to find the sideset id const int index = it->first; int ss_id = -99; mesh_->side_set_found(index, ss_id); //loop over element faces--this will be the parallel loop eventually //we would need toto know coloring on the sideset or switch to scattered mesh for ( int j = 0; j < mesh_->get_side_set(ss_id).size(); j++ ){//loop over element faces--this will be the parallel loop double xx[BASIS_NODES_PER_ELEM]; double yy[BASIS_NODES_PER_ELEM]; double zz[BASIS_NODES_PER_ELEM]; double uu[BASIS_NODES_PER_ELEM]; double uu_old[BASIS_NODES_PER_ELEM]; double uu_oldold[BASIS_NODES_PER_ELEM]; for ( int ll = 0; ll < num_node_per_side; ll++){//loop over nodes in each face const int lid = mesh_->get_side_set_node_list(ss_id)[j*num_node_per_side+ll]; xx[ll] = x_1dra(lid); yy[ll] = y_1dra(lid); zz[ll] = z_1dra(lid); uu[ll] = u_1dra(numeqs_*lid+k); uu_old[ll] = uold_1dra(numeqs_*lid+k); uu_oldold[ll] = uoldold_1dra(numeqs_*lid+k); }//ll BGPU->computeElemData(&xx[0], &yy[0], &zz[0]); for ( int gp = 0; gp < ngp; gp++){ const double jacwt = BGPU->getBasis(gp, &xx[0], &yy[0], &zz[0], &uu[0], &uu_old[0], &uu_oldold[0]); for( int i = 0; i < num_node_per_side; i++ ){ const int lid = mesh_->get_side_set_node_list(ss_id)[j*num_node_per_side+i]; const int row = numeqs_*lid + k; const double val = -jacwt*(it->second)(BGPU,i,dt,dtold,t_theta,t_theta2,time); f_1d[row] += val; }//i }//gp }//j }//it }//k { Teuchos::TimeMonitor ImportTimer(*ts_time_import); f_vec->doExport(*f_overlap, *exporter_, Tpetra::ADD); } }//neumann }//get_f if (nonnull(outArgs.get_f()) && NULL != dirichletfunc_){ const Teuchos::RCP<vector_type> f_vec = ConverterT::getTpetraVector(outArgs.get_f()); //std::vector<Mesh::mesh_lint_t> node_num_map(mesh_->get_node_num_map()); std::map<int,DBCFUNC>::iterator it; Teuchos::RCP<vector_type> f_overlap = Teuchos::rcp(new vector_type(x_overlap_map_)); { Teuchos::TimeMonitor ImportTimer(*ts_time_import); f_overlap->doImport(*f_vec,*importer_,Tpetra::INSERT); } //u is already imported to overlap_map here //auto u_view = u->getLocalView<Kokkos::DefaultExecutionSpace>(); //on host only right now //auto f_view = f_overlap->getLocalView<Kokkos::DefaultHostExecutionSpace>(); auto f_view = f_overlap->getLocalViewHost(Tpetra::Access::ReadWrite); //auto u_1d = Kokkos::subview (u_view, Kokkos::ALL (), 0); //Kokkos::View<const double*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> u_1dra = Kokkos::subview (u_view, Kokkos::ALL (), 0); auto f_1d = Kokkos::subview (f_view, Kokkos::ALL (), 0); for( int k = 0; k < numeqs_; k++ ){ for(it = (*dirichletfunc_)[k].begin();it != (*dirichletfunc_)[k].end(); ++it){ const int index = it->first; int ns_id = -99; mesh_->node_set_found(index, ns_id); const int num_node_ns = mesh_->get_node_set(ns_id).size(); size_t ns_size = (mesh_->get_node_set(ns_id)).size(); Kokkos::View <int*> node_set_view("nsv",ns_size); for (size_t i = 0; i < ns_size; ++i) { node_set_view(i) = (mesh_->get_node_set(ns_id))[i]; } #ifdef TUSAS_RUN_ON_CPU for ( int j = 0; j < num_node_ns; j++ ){ #else Kokkos::parallel_for(num_node_ns,KOKKOS_LAMBDA (const size_t& j){ #endif const int lid = node_set_view(j);//could use Kokkos::vector here... #ifdef TUSAS_RUN_ON_CPU const double xx = x_1dra(lid); const double yy = y_1dra(lid); const double zz = z_1dra(lid); const double val1 = (it->second)(xx,yy,zz,time); #else const double val1 = tusastpetra::dbc_zero_(0.,0.,0.,time); #endif const double val = u_1dra(numeqs_*lid + k) - val1; f_1d(numeqs_*lid + k) = val; #ifdef TUSAS_RUN_ON_CPU }//j #else });//parallel_for #endif }//it }//k { Teuchos::TimeMonitor ImportTimer(*ts_time_import); f_vec->doExport(*f_overlap, *exporter_, Tpetra::REPLACE);//REPLACE ??? } }//get_f if( nonnull(outArgs.get_W_prec() )){ Teuchos::TimeMonitor PrecFillTimer(*ts_time_precfill); P_->resumeFill(); P_->setAllToScalar((scalar_type)0.0); P->resumeFill(); P->setAllToScalar((scalar_type)0.0); auto PV = P->getLocalMatrix();//this is a KokkosSparse::CrsMatrix<scalar_type,local_ordinal_type, node_type> PV = P->getLocalMatrix(); PREFUNC * h_pf; h_pf = (PREFUNC*)malloc(numeqs_*sizeof(PREFUNC)); #ifdef TUSAS_HAVE_CUDA PREFUNC * d_pf; cudaMalloc((double**)&d_pf,numeqs_*sizeof(PREFUNC)); if("heat" == paramList.get<std::string> (TusastestNameString)){ //cn this will need to be done for each equation cudaMemcpyFromSymbol( &h_pf[0], tpetra::prec_heat_test_dp_, sizeof(PREFUNC)); }else if("heat2" == paramList.get<std::string> (TusastestNameString)){ cudaMemcpyFromSymbol( &h_pf[0], tpetra::prec_heat_test_dp_, sizeof(PREFUNC)); cudaMemcpyFromSymbol( &h_pf[1], tpetra::prec_heat_test_dp_, sizeof(PREFUNC)); }else if("farzadi" == paramList.get<std::string> (TusastestNameString)){ cudaMemcpyFromSymbol( &h_pf[0], tpetra::farzadi3d::prec_conc_farzadi_dp_, sizeof(PREFUNC)); cudaMemcpyFromSymbol( &h_pf[1], tpetra::farzadi3d::prec_phase_farzadi_dp_, sizeof(PREFUNC)); }else if("farzadi_test" == paramList.get<std::string> (TusastestNameString)){ cudaMemcpyFromSymbol( &h_pf[0], tpetra::farzadi3d::prec_conc_farzadi_dp_, sizeof(PREFUNC)); cudaMemcpyFromSymbol( &h_pf[1], tpetra::farzadi3d::prec_phase_farzadi_dp_, sizeof(PREFUNC)); }else if("pfhub3" == paramList.get<std::string> (TusastestNameString)){ cudaMemcpyFromSymbol( &h_pf[0], tpetra::pfhub3::prec_heat_pfhub3_dp_, sizeof(PREFUNC)); cudaMemcpyFromSymbol( &h_pf[1], tpetra::pfhub3::prec_phase_pfhub3_dp_, sizeof(PREFUNC)); }else if("NLheatCN" == paramList.get<std::string> (TusastestNameString)){ cudaMemcpyFromSymbol( &h_pf[0], tpetra::prec_nlheatcn_test_dp_, sizeof(PREFUNC)); }else if("NLheatIMR" == paramList.get<std::string> (TusastestNameString)){ cudaMemcpyFromSymbol( &h_pf[0], tpetra::prec_nlheatcn_test_dp_, sizeof(PREFUNC)); } else { if( 0 == comm_->getRank() ){ std::cout<<std::endl<<std::endl<<"Test case: "<<paramList.get<std::string> (TusastestNameString) <<" precon function not found. (void ModelEvaluatorTPETRA<Scalar>::evalModelImpl(...))" <<std::endl<<std::endl<<std::endl; } exit(0); } cudaMemcpy(d_pf,h_pf,numeqs_*sizeof(PREFUNC),cudaMemcpyHostToDevice); #else h_pf = &(*preconfunc_)[0]; #endif for(int c = 0; c < num_color; c++){ //std::vector<int> elem_map = colors[c]; std::vector<int> elem_map = Elem_col->get_color(c); const int num_elem = elem_map.size(); Kokkos::View<int*,Kokkos::DefaultExecutionSpace> elem_map_1d("elem_map_1d",num_elem); //Kokkos::vector<int> elem_map_k(num_elem); for(int i = 0; i<num_elem; i++) { //elem_map_k[i] = elem_map[i]; elem_map_1d(i) = elem_map[i]; //std::cout<<comm_->getRank()<<" "<<c<<" "<<i<<" "<<elem_map_k[i]<<std::endl; } //exit(0); Kokkos::parallel_for(num_elem,KOKKOS_LAMBDA(const int& ne){ //an array of pointers to GPUBasis GPUBasis * BGPU[TUSAS_MAX_NUMEQS]; GPUBasisLQuad Bq[TUSAS_MAX_NUMEQS] = {GPUBasisLQuad(LTP_quadrature_order), GPUBasisLQuad(LTP_quadrature_order), GPUBasisLQuad(LTP_quadrature_order), GPUBasisLQuad(LTP_quadrature_order), GPUBasisLQuad(LTP_quadrature_order)}; GPUBasisLHex Bh[TUSAS_MAX_NUMEQS] = {GPUBasisLHex(LTP_quadrature_order), GPUBasisLHex(LTP_quadrature_order), GPUBasisLHex(LTP_quadrature_order), GPUBasisLHex(LTP_quadrature_order), GPUBasisLHex(LTP_quadrature_order)}; if(4 == n_nodes_per_elem) { for( int neq = 0; neq < numeqs; neq++ ) BGPU[neq] = &Bq[neq]; }else{ for( int neq = 0; neq < numeqs; neq++ ) BGPU[neq] = &Bh[neq]; } const int ngp = BGPU[0]->ngp(); //const int elem = elem_map_k[ne]; const int elem = elem_map_1d(ne); double xx[BASIS_NODES_PER_ELEM]; double yy[BASIS_NODES_PER_ELEM]; double zz[BASIS_NODES_PER_ELEM]; double uu[TUSAS_MAX_NUMEQS_X_BASIS_NODES_PER_ELEM]; const int elemrow = elem*n_nodes_per_elem; for(int k = 0; k < n_nodes_per_elem; k++){ //const int nodeid = meshc[elemrow+k]; const int nodeid = meshc_1d(elemrow+k); xx[k] = x_1dra(nodeid); yy[k] = y_1dra(nodeid); zz[k] = z_1dra(nodeid); for( int neq = 0; neq < numeqs; neq++ ){ uu[n_nodes_per_elem*neq+k] = u_1dra(numeqs*nodeid+neq); //we can add uu_old, uu_oldold }//neq }//k for( int neq = 0; neq < numeqs; neq++ ){ BGPU[neq]->computeElemData(&xx[0], &yy[0], &zz[0]); }//neq for(int gp=0; gp < ngp; gp++) {//gp double jacwt = 0.; for( int neq = 0; neq < numeqs; neq++ ){ jacwt = BGPU[neq]->getBasis(gp, &xx[0], &yy[0], &zz[0], &uu[neq*n_nodes_per_elem], NULL,NULL);//we can add uu_old, uu_oldold }//neq for (int i=0; i< n_nodes_per_elem; i++) {//i //const local_ordinal_type lrow = numeqs*meshc[elemrow+i]; const local_ordinal_type lrow = numeqs*meshc_1d(elemrow+i); for(int j=0;j < n_nodes_per_elem; j++) { //local_ordinal_type lcol[1] = {numeqs*meshc[elemrow+j]}; local_ordinal_type lcol[1] = {numeqs*meshc_1d(elemrow+j)}; for( int neq = 0; neq < numeqs; neq++ ){ #ifdef TUSAS_HAVE_CUDA scalar_type val[1] = {jacwt*d_pf[neq](*BGPU,i,j,dt,t_theta,neq)}; #else scalar_type val[1] = {jacwt*h_pf[neq](*BGPU,i,j,dt,t_theta,neq)}; #endif //cn probably better to fill a view for val and lcol for each column const local_ordinal_type row = lrow +neq; local_ordinal_type col[1] = {lcol[0] + neq}; //P->sumIntoLocalValues(lrow,(local_ordinal_type)1,val,lcol,false); PV.sumIntoValues (row, col,(local_ordinal_type)1,val); }//neq }//j }//i }//gp });//parallel_for }//c #ifdef TUSAS_HAVE_CUDA cudaFree(d_pf); free(h_pf); #endif //cn we need to do a similar comm here... P->fillComplete(); //P->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); { Teuchos::TimeMonitor ImportTimer(*ts_time_import); P_->doExport(*P, *exporter_, Tpetra::ADD); } P_->fillComplete(); //P_->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); //exit(0); }//outArgs.get_W_prec() if(nonnull(outArgs.get_W_prec() ) && NULL != dirichletfunc_){ Teuchos::TimeMonitor PrecFillTimer(*ts_time_precfill); P->resumeFill();//this is overlap, P_ is owned // local nodeset ids are on overlap #ifdef TUSAS_RUN_ON_CPU auto PV = P->getLocalMatrix(); std::vector<Mesh::mesh_lint_t> node_num_map(mesh_->get_node_num_map()); std::map<int,DBCFUNC>::iterator it; for( int k = 0; k < numeqs_; k++ ){ for(it = (*dirichletfunc_)[k].begin();it != (*dirichletfunc_)[k].end(); ++it){ const int ns_id = it->first; const int num_node_ns = mesh_->get_node_set(ns_id).size(); size_t ns_size = (mesh_->get_node_set(ns_id)).size(); Kokkos::View <int*> node_set_view("nsv",ns_size); for (size_t i = 0; i < ns_size; ++i) { node_set_view(i) = (mesh_->get_node_set(ns_id))[i]; } for ( int j = 0; j < num_node_ns; j++ ){ //Kokkos::parallel_for(num_node_ns,KOKKOS_LAMBDA(const size_t j){ const int lid_overlap = node_set_view(j); //const global_ordinal_type gid_overlap = x_overlap_map_->getGlobalElement(lid_overlap); //const local_ordinal_type lrow = x_owned_map_->getLocalElement(gid_overlap); const local_ordinal_type lrow = (local_ordinal_type)lid_overlap; size_t ncol = 0; const local_ordinal_type row = numeqs*lrow + k; auto RV = PV.row(row); //const Kokkos::SparseRowView<Kokkos::CrsMatrix> RV = PV.row(row); ncol = RV.length; scalar_type * vals = new scalar_type[ncol]; local_ordinal_type * inds = new local_ordinal_type[ncol]; for(int i = 0; i<(int)ncol; i++){ inds[i] = RV.colidx(i); vals[i] = 0.0; ( inds[i] == row ) ? ( vals[i] = 1.0 ) : ( vals[i] = 0.0 ); //std::cout<<row<<" "<<inds[i]<<" "<<vals[i]<<std::endl; RV.value(i) = vals[i]; } //P_->replaceLocalValues(row, ncol, vals, inds ); //PV.replaceValues(row, inds, ncol, vals ); delete[] vals; delete[] inds; //});//parallel_for }//j }//it }//k #else #endif P->fillComplete(); //P->fillComplete(); //P->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); // exit(0); P_->resumeFill(); { Teuchos::TimeMonitor ImportTimer(*ts_time_import); P_->doExport(*P, *exporter_, Tpetra::REPLACE); } P_->fillComplete(); //P_->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); }//outArgs.get_W_prec() && dirichletfunc_ if( nonnull(outArgs.get_W_prec() )){ MueLu::ReuseTpetraPreconditioner( P_, *prec_ ); }//outArgs.get_W_prec() // if (time_ < 1.e-9 && predictor_step == true) // exit(0); return; } //==================================================================== template<class scalar_type> void ModelEvaluatorTPETRA<scalar_type>::init_nox() { auto comm_ = Teuchos::DefaultComm<int>::getComm(); int mypid = comm_->getRank() ; if( 0 == mypid ) std::cout<<std::endl<<"init_nox() started."<<std::endl<<std::endl; nnewt_=0; ::Stratimikos::DefaultLinearSolverBuilder builder; Teuchos::RCP<Teuchos::ParameterList> lsparams = Teuchos::rcp(new Teuchos::ParameterList(paramList.sublist(TusaslsNameString))); //::Stratimikos::enableMueLu<local_ordinal_type,global_ordinal_type, node_type>(builder); using Base = Thyra::PreconditionerFactoryBase<scalar_type>; using Impl = Thyra::MueLuPreconditionerFactory<scalar_type,local_ordinal_type,global_ordinal_type, node_type>; builder.setPreconditioningStrategyFactory(Teuchos::abstractFactoryStd<Base,Impl>(), "MueLu"); builder.setParameterList(lsparams); if( 0 == mypid ) builder.getParameterList()->print(std::cout); Teuchos::RCP< ::Thyra::LinearOpWithSolveFactoryBase<double> > lowsFactory = builder.createLinearSolveStrategy(""); // Setup output stream and the verbosity level Teuchos::RCP<Teuchos::FancyOStream> out = Teuchos::VerboseObjectBase::getDefaultOStream(); lowsFactory->setOStream(out); lowsFactory->setVerbLevel(Teuchos::VERB_EXTREME); this->set_W_factory(lowsFactory); // Create the initial guess Teuchos::RCP< ::Thyra::VectorBase<double> > initial_guess = this->getNominalValues().get_x()->clone_v(); bool do_scaling = paramList.get<bool> (TusasleftScalingNameString); if(do_scaling){ scaling_ = Thyra::createMember(this->get_x_space()); update_left_scaling(); }else{ scaling_ = Teuchos::null; } Thyra::V_S(initial_guess.ptr(),Teuchos::ScalarTraits<double>::one()); // Create the JFNK operator //Teuchos::ParameterList printParams;//cn this is empty??? for now // Teuchos::RCP<NOX::Thyra::MatrixFreeJacobianOperator<double> > jfnkOp = // Teuchos::rcp(new NOX::Thyra::MatrixFreeJacobianOperator<double>(printParams)); //Teuchos::RCP<NOX::Thyra::MatrixFreeJacobianOperator<double> > jfnkOp = thyraModel->create_W_Op(); //Teuchos::rcp(new tusasjfnkOp<double>(printParams)); // Teuchos::RCP<Teuchos::ParameterList> jfnkParams = Teuchos::rcp(new Teuchos::ParameterList(paramList.sublist(TusasjfnkNameString))); // jfnkOp->setParameterList(jfnkParams); // if( 0 == mypid ) // jfnkParams->print(std::cout); Teuchos::RCP< ::Thyra::ModelEvaluator<double> > Model = Teuchos::rcpFromRef(*this); // Wrap the model evaluator in a JFNK Model Evaluator Teuchos::RCP< ::Thyra::ModelEvaluator<double> > thyraModel = Teuchos::rcp(new NOX::MatrixFreeModelEvaluatorDecorator<double>(Model)); Teuchos::RCP<NOX::Thyra::MatrixFreeJacobianOperator<double> > jfnkOp = Teuchos::rcp_dynamic_cast<NOX::Thyra::MatrixFreeJacobianOperator<double> >(thyraModel->create_W_op()); // Create the NOX::Thyra::Group bool precon = paramList.get<bool> (TusaspreconNameString); Teuchos::RCP<NOX::Thyra::Group> nox_group; Teuchos::RCP< ::Thyra::PreconditionerBase<double> > precOp; if(precon){ precOp = thyraModel->create_W_prec(); } if(do_scaling){ nox_group = // Teuchos::rcp(new NOX::Thyra::Group(*initial_guess, thyraModel, jfnkOp, lowsFactory, precOp, Teuchos::null, scaling_, Teuchos::null)); Teuchos::rcp(new NOX::Thyra::Group(*initial_guess, thyraModel, scaling_, Teuchos::null, Teuchos::null)); }else{ nox_group = Teuchos::rcp(new NOX::Thyra::Group(*initial_guess, thyraModel, jfnkOp, lowsFactory, precOp, Teuchos::null, scaling_, Teuchos::null)); } nox_group->computeF(); // VERY IMPORTANT!!! jfnk object needs base evaluation objects. // This creates a circular dependency, so use a weak pointer. jfnkOp->setBaseEvaluationToNOXGroup(nox_group.create_weak()); // Create the NOX status tests and the solver // Create the convergence tests Teuchos::RCP<NOX::StatusTest::NormF> absresid = Teuchos::rcp(new NOX::StatusTest::NormF(1.0e-8)); double relrestol = 1.0e-6; relrestol = paramList.get<double> (TusasnoxrelresNameString); Teuchos::RCP<NOX::StatusTest::NormF> relresid = Teuchos::rcp(new NOX::StatusTest::NormF(*nox_group.get(), relrestol)); Teuchos::RCP<NOX::StatusTest::NormWRMS> wrms = Teuchos::rcp(new NOX::StatusTest::NormWRMS(1.0e-2, 1.0e-8)); Teuchos::RCP<NOX::StatusTest::Combo> converged = Teuchos::rcp(new NOX::StatusTest::Combo(NOX::StatusTest::Combo::AND)); //converged->addStatusTest(absresid); converged->addStatusTest(relresid); //converged->addStatusTest(wrms); int maxit = 200; maxit = paramList.get<int> (TusasnoxmaxiterNameString); Teuchos::RCP<NOX::StatusTest::MaxIters> maxiters = Teuchos::rcp(new NOX::StatusTest::MaxIters(maxit));//200 Teuchos::RCP<NOX::StatusTest::FiniteValue> fv = Teuchos::rcp(new NOX::StatusTest::FiniteValue); Teuchos::RCP<NOX::StatusTest::Combo> combo = Teuchos::rcp(new NOX::StatusTest::Combo(NOX::StatusTest::Combo::OR)); //combo->addStatusTest(fv); combo->addStatusTest(converged); combo->addStatusTest(maxiters); Teuchos::RCP<Teuchos::ParameterList> nl_params = Teuchos::rcp(new Teuchos::ParameterList(paramList.sublist(TusasnlsNameString))); if( 0 == mypid ) nl_params->print(std::cout); Teuchos::ParameterList& nlPrintParams = nl_params->sublist("Printing"); nlPrintParams.set("Output Information", NOX::Utils::OuterIteration + // NOX::Utils::OuterIterationStatusTest + NOX::Utils::InnerIteration + NOX::Utils::Details //+ //NOX::Utils::LinearSolverDetails ); //nlPrintParams.set("Output Information",0); // Create the solver solver_ = NOX::Solver::buildSolver(nox_group, combo, nl_params); if(paramList.get<bool> (TusasestimateTimestepNameString)){ Teuchos::ParameterList *atsList; atsList = &paramList.sublist (TusasatslistNameString, false ); if(atsList->get<std::string> (TusasatstypeNameString) == "predictor corrector"){ //init_predictor(); Teuchos::ParameterList printParams; Teuchos::RCP<Teuchos::ParameterList> jfnkParams = Teuchos::rcp(new Teuchos::ParameterList(paramList.sublist(TusasjfnkNameString))); Teuchos::RCP<NOX::Thyra::MatrixFreeJacobianOperator<double> > jfnkOp1 = Teuchos::rcp(new NOX::Thyra::MatrixFreeJacobianOperator<double>(printParams)); jfnkOp1->setParameterList(jfnkParams); Teuchos::RCP<NOX::Thyra::Group> noxpred_group = Teuchos::rcp(new NOX::Thyra::Group(*initial_guess, thyraModel, jfnkOp1, lowsFactory, Teuchos::null, Teuchos::null, Teuchos::null, Teuchos::null)); jfnkOp1->setBaseEvaluationToNOXGroup(noxpred_group.create_weak()); noxpred_group->computeF(); atsList = &paramList.sublist (TusasatslistNameString, false ); double relrestolp = 1.e-6; relrestolp = atsList->get<double>(TusaspredrelresNameString,1.e-6); int predmaxit = 20; predmaxit = paramList.get<int> (TusaspredmaxiterNameString,20); Teuchos::RCP<NOX::StatusTest::MaxIters> maxiters1 = Teuchos::rcp(new NOX::StatusTest::MaxIters(predmaxit)); Teuchos::RCP<NOX::StatusTest::NormF>relresid1 = Teuchos::rcp(new NOX::StatusTest::NormF(*noxpred_group.get(), relrestolp));//1.0e-6 for paper //Teuchos::rcp(new NOX::StatusTest::NormF(*noxpred_group.get(), relrestol));//1.0e-6 for paper Teuchos::RCP<NOX::StatusTest::Combo> converged1 = Teuchos::rcp(new NOX::StatusTest::Combo(NOX::StatusTest::Combo::OR)); converged1->addStatusTest(relresid1); converged1->addStatusTest(maxiters1); //combo->addStatusTest(converged1); //converged1->print(std::cout); Teuchos::RCP<Teuchos::ParameterList> nl_params1 = Teuchos::rcp(new Teuchos::ParameterList); nl_params1->set("Nonlinear Solver", "Line Search Based"); nl_params1->sublist("Direction").sublist("Newton").set("Forcing Term Method", "Type 2"); nl_params1->sublist("Direction").sublist("Newton").set("Forcing Term Initial Tolerance", 1.0e-1); nl_params1->sublist("Direction").sublist("Newton").set("Forcing Term Maximum Tolerance", 1.0e-2); nl_params1->sublist("Direction").sublist("Newton").set("Forcing Term Minimum Tolerance", 1.0e-5); Teuchos::ParameterList& nlPrintParams1 = nl_params1->sublist("Printing"); nlPrintParams1.set("Output Information", NOX::Utils::OuterIteration + // NOX::Utils::OuterIterationStatusTest + NOX::Utils::InnerIteration + NOX::Utils::Details //+ //NOX::Utils::LinearSolverDetails ); predictor_ = NOX::Solver::buildSolver(noxpred_group, converged1, nl_params1); } } if( 0 == mypid ) std::cout<<std::endl<<"init_nox() completed."<<std::endl<<std::endl; } template<class Scalar> void ModelEvaluatorTPETRA<Scalar>:: set_W_factory(const Teuchos::RCP<const ::Thyra::LinearOpWithSolveFactoryBase<Scalar> >& W_factory) { W_factory_ = W_factory; } template<class Scalar> Teuchos::RCP< ::Thyra::PreconditionerBase<Scalar> > ModelEvaluatorTPETRA<Scalar>::create_W_prec() const { //cn prec_ is MueLu::TpetraOperator //cn which inherits from Tpetra::Operator //cn need to cast prec_ to a Tpetra::Operator Teuchos::RCP<Tpetra::Operator<scalar_type,local_ordinal_type, global_ordinal_type, node_type> > Tprec = Teuchos::rcp_dynamic_cast<Tpetra::Operator<scalar_type,local_ordinal_type, global_ordinal_type, node_type> >(prec_,true); const Teuchos::RCP<Thyra::LinearOpBase< scalar_type > > P_op = Thyra::tpetraLinearOp<scalar_type,local_ordinal_type, global_ordinal_type, node_type>(f_space_,x_space_,Tprec); Teuchos::RCP<Thyra::DefaultPreconditioner<Scalar> > prec = Teuchos::rcp(new Thyra::DefaultPreconditioner<Scalar>(Teuchos::null,P_op)); //prec->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); //exit(0); return prec; } template<class Scalar> Teuchos::RCP< ::Thyra::LinearOpBase< Scalar > > ModelEvaluatorTPETRA<Scalar>::create_W_op() const { // Create the JFNK operator Teuchos::ParameterList printParams;//cn this is empty??? for now // Teuchos::RCP<NOX::Thyra::MatrixFreeJacobianOperator<double> > jfnkOp = // Teuchos::rcp(new NOX::Thyra::MatrixFreeJacobianOperator<double>(printParams)); Teuchos::RCP<NOX::Thyra::MatrixFreeJacobianOperator<double> > jfnkOp = Teuchos::rcp(new tusasjfnkOp<double>(printParams)); Teuchos::RCP<Teuchos::ParameterList> jfnkParams = Teuchos::rcp(new Teuchos::ParameterList(paramList.sublist(TusasjfnkNameString))); jfnkOp->setParameterList(jfnkParams); auto comm_ = Teuchos::DefaultComm<int>::getComm(); int mypid = comm_->getRank() ; if( 0 == mypid ) jfnkParams->print(std::cout); return jfnkOp; } template<class scalar_type> Thyra::ModelEvaluatorBase::OutArgs<scalar_type> ModelEvaluatorTPETRA<scalar_type>::createOutArgsImpl() const { return prototypeOutArgs_; } template<class scalar_type> double ModelEvaluatorTPETRA<scalar_type>::advance() { auto comm_ = Teuchos::DefaultComm<int>::getComm(); const int mypid = comm_->getRank(); //There was some concern that the temporal error is zero. //This can happen since the predictor solution is currently given as the //guess to the corrector. IE if the predictor solution is a good enough //guess for the corrector, and the corrector does not take an iteration //then these solutions are the same. //Ie we are in a realm where we should just be taking explicit steps. //We could force an iteration of the corrector to get a non zero solution here. int maxiter = 1; bool timeadapt = paramList.get<bool>(TusasadaptiveTimestepNameString); Teuchos::ParameterList *atsList; atsList = &paramList.sublist (TusasatslistNameString, false ); if( timeadapt ) maxiter = atsList->get<int>(TusasatsmaxiterNameString); // std::cout<<maxiter<<std::endl; // exit(0); if( paramList.get<bool>(TusasrandomDistributionNameString) ){ randomdistribution->compute_random(numsteps_); //randomdistribution->print(); //exit(0); } bool do_scaling = paramList.get<bool> (TusasleftScalingNameString); if(do_scaling){ update_left_scaling(); } double dtpred = dt_; int numit = 0; for(int iter = 0; iter<maxiter; iter++){ { Teuchos::RCP< Thyra::VectorBase< double > > guess; guess = Thyra::createVector(u_old_,x_space_); Teuchos::TimeMonitor NSolveTimer(*ts_time_nsolve); if(paramList.get<bool> (TusasestimateTimestepNameString)){ Teuchos::ParameterList *atsList; atsList = &paramList.sublist (TusasatslistNameString, false ); if(atsList->get<std::string> (TusasatstypeNameString) == "predictor corrector"){ predictor(); guess = Thyra::createVector(pred_temp_,x_space_); }//if }//if if( 0 == mypid ) std::cout<<" Corrector step started"<<std::endl; corrector_step = true; NOX::Thyra::Vector thyraguess(*guess); solver_->reset(thyraguess); NOX::StatusTest::StatusType solvStatus = solver_->solve(); if( !(NOX::StatusTest::Converged == solvStatus)) { if( 0 == mypid ) std::cout<<" NOX solver failed to converge. Status = "<<solvStatus<<std::endl<<std::endl; if(paramList.get<bool> (TusasnoxacceptNameString)){ if( 0 == mypid ) std::cout<<" Accepting step since "<<TusasnoxacceptNameString<<" is true."<<std::endl<<std::endl; }else{ exit(0); } }//if if( 0 == mypid ) std::cout<<" Corrector step ended"<<std::endl; numit++; corrector_step = false; }//timer nnewt_ += solver_->getNumIterations(); if(paramList.get<bool> (TusasprintNormsNameString)) print_norms(); const Thyra::VectorBase<double> * sol = &(dynamic_cast<const NOX::Thyra::Vector&>( solver_->getSolutionGroup().getX() ).getThyraVector() ); Thyra::ConstDetachedSpmdVectorView<double> x_vec(sol->col(0)); Teuchos::ArrayRCP<const scalar_type> vals = x_vec.values(); const size_t localLength = num_owned_nodes_; //we need x_vec as a kokkos view for the parallel_for to work on gpu auto un_view = u_new_->getLocalViewHost(Tpetra::Access::ReadWrite); auto un_1d = Kokkos::subview (un_view, Kokkos::ALL (), 0); //for (int nn=0; nn < localLength; nn++) {//cn figure out a better way here... Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultHostExecutionSpace>(0,localLength),[=](const int& nn){ for( int k = 0; k < numeqs_; k++ ){ //u_new_->replaceLocalValue(numeqs_*nn+k,x_vec[numeqs_*nn+k]); //u_new_->replaceLocalValue(numeqs_*nn+k,vals[numeqs_*nn+k]); un_1d[numeqs_*nn+k] = vals[numeqs_*nn+k]; } } );//parallel_for if(localprojectionindices_.size() > 0 ){ if( 0 == mypid)std::cout<<" Performing local projection "<<std::endl; //right now,4-12-23 we make some assumptions and simplifications // we define the P1(v) as the projection of v onto the *direction* of q // P1(v) = q (q, v) // we want p1(v) to have norm=1, with ||P1(v))|| = (q,v)||q|| // P(v) = q (q,v) / ( (q,v) ||q||) = q/||q|| // // ie any vector projected onto q with norm=1 is q/||q|| // //also see section III.1 of //https://www.unige.ch/~hairer/poly-sde-mani.pdf //Solving Differential Equations on Manifolds //Ernst Hairer //Universite de Geneve June 2011 //Section de mathematiques //2-4 rue du Lievre, CP 64 //CH-1211 Geneve 4 auto un_view = u_new_->getLocalViewHost(Tpetra::Access::ReadWrite); auto un_1d = Kokkos::subview (un_view, Kokkos::ALL (), 0); //for (int nn=0; nn < localLength; nn++) {//cn figure out a better way here... Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultHostExecutionSpace>(0,localLength),[=](const int& nn){ double norm = 0.; //std::cout<<nn<<std::endl; for( auto k : localprojectionindices_ ){ norm = norm + un_1d[numeqs_*nn+k]*un_1d[numeqs_*nn+k]; //std::cout<<" "<<k<<" "<<numeqs_*nn+k<<" "<<un_1d[numeqs_*nn+k]<<" "; } //std::cout<<"norm = "<<norm<<std::endl; for( auto k : localprojectionindices_ ){ un_1d[numeqs_*nn+k] = un_1d[numeqs_*nn+k]/sqrt(norm); } } );//parallel_for }//if if((paramList.get<bool> (TusasestimateTimestepNameString)) && !timeadapt){ const double d = estimatetimestep(); }//if if(timeadapt){ dtpred = estimatetimestep(); }//if if( timeadapt ){ if(dtpred < dt_){ dt_ = dtpred; if( 0 == mypid)std::cout<<" advance() step NOT ACCEPTED with dt = "<<std::scientific<<dt_ <<"; new dt = "<<dtpred <<"; and iterations = "<<numit<<std::endl<<std::defaultfloat; }else{ if( 0 == mypid)std::cout<<" advance() step accepted with dt = "<<std::scientific<<dt_ <<"; new dt = "<<dtpred <<"; and iterations = "<<numit<<std::endl<<std::defaultfloat; break; }//if }//if }//iter dtold_ = dt_; time_ += dt_; postprocess(); //*u_old_old_ = *u_old_; u_old_old_->update(1.,*u_old_,0.); //*u_old_ = *u_new_; u_old_->update(1.,*u_new_,0.); for(boost::ptr_vector<error_estimator>::iterator it = Error_est.begin();it != Error_est.end();++it){ //it->test_lapack(); it->estimate_gradient(u_old_); it->estimate_error(u_old_); } ++numsteps_; dt_ = dtpred; return dtold_; } template<class scalar_type> void ModelEvaluatorTPETRA<scalar_type>::initialize() { auto comm_ = Teuchos::DefaultComm<int>::getComm(); if( 0 == comm_->getRank()) std::cout<<std::endl<<"initialize started"<<std::endl<<std::endl; bool dorestart = paramList.get<bool> (TusasrestartNameString); if (!dorestart){ init(u_old_); //*u_old_old_ = *u_old_; u_old_old_->scale(1.,*u_old_); #if 1 Teuchos::ParameterList *atsList; atsList = &paramList.sublist (TusasatslistNameString, false ); //initial solve need by second derivative error estimate //and for lagged coupled time derivatives //ie get a solution at u_{-1} if(((atsList->get<std::string> (TusasatstypeNameString) == "second derivative") &&paramList.get<bool> (TusasestimateTimestepNameString)) ||((atsList->get<std::string> (TusasatstypeNameString) == "predictor corrector") &&paramList.get<bool> (TusasestimateTimestepNameString)&&t_theta_ < 1.) ||paramList.get<bool> (TusasinitialSolveNameString)){ initialsolve(); }//if #endif int mypid = comm_->getRank(); int numproc = comm_->getSize(); if( 1 == numproc ){//cn for now //if( 0 == mypid ){ outfilename = "results.e"; ex_id_ = mesh_->create_exodus(outfilename.c_str());//this calls ex_open } else{ //std::string decompPath="decomp/"; std::string decompPath=paramList.get<std::string> (TusasoutputpathNameString); std::string mypidstring(getmypidstring(mypid,numproc)); outfilename = decompPath+"/results.e."+std::to_string(numproc)+"."+mypidstring; ex_id_ = mesh_->create_exodus(outfilename.c_str()); }//if numproc mesh_->close_exodus(ex_id_); for( int k = 0; k < numeqs_; k++ ){ mesh_->add_nodal_field((*varnames_)[k]); } #if 1 if(paramList.get<bool> (TusasestimateTimestepNameString)){ setadaptivetimestep(); } #endif output_step_ = 1; write_exodus(); }//if !dorestart else{ restart(u_old_);//,u_old_old_); for( int k = 0; k < numeqs_; k++ ){ mesh_->add_nodal_field((*varnames_)[k]); } #if 1 Teuchos::ParameterList *atsList; atsList = &paramList.sublist (TusasatslistNameString, false ); //initial solve need by second derivative error estimate //and for lagged coupled time derivatives //ie get a solution at u_{-1} if(((atsList->get<std::string> (TusasatstypeNameString) == "second derivative") &&paramList.get<bool> (TusasestimateTimestepNameString)) ||((atsList->get<std::string> (TusasatstypeNameString) == "predictor corrector") &&paramList.get<bool> (TusasestimateTimestepNameString)&&t_theta_ < 1.) ||paramList.get<bool> (TusasinitialSolveNameString)){ initialsolve(); }//if if(paramList.get<bool> (TusasestimateTimestepNameString)){ setadaptivetimestep(); } #endif }//if dorestart #if 0 Teuchos::ParameterList *atsList; atsList = &paramList.sublist (TusasatslistNameString, false ); //initial solve need by second derivative error estimate //and for lagged coupled time derivatives //ie get a solution at u_{-1} if(((atsList->get<std::string> (TusasatstypeNameString) == "second derivative") &&paramList.get<bool> (TusasestimateTimestepNameString)) ||((atsList->get<std::string> (TusasatstypeNameString) == "predictor corrector") &&paramList.get<bool> (TusasestimateTimestepNameString)&&t_theta_ < 1.) ||paramList.get<bool> (TusasinitialSolveNameString)){ initialsolve(); }//if if(paramList.get<bool> (TusasestimateTimestepNameString)){ setadaptivetimestep(); } #endif if( 0 == comm_->getRank()) std::cout<<std::endl<<"initialize finished"<<std::endl<<std::endl; } template<class scalar_type> void ModelEvaluatorTPETRA<scalar_type>::init(Teuchos::RCP<vector_type> u) { //ArrayRCP<scalar_type> uv = u->get1dViewNonConst(); //on host only now auto u_view = u->getLocalViewHost(Tpetra::Access::ReadWrite); auto u_1d = Kokkos::subview (u_view, Kokkos::ALL (), 0); const size_t localLength = num_owned_nodes_; for( int k = 0; k < numeqs_; k++ ){ //#pragma omp parallel for //for (size_t nn=0; nn < localLength; nn++) { Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultHostExecutionSpace>(0,localLength),[=](const int& nn){ const global_ordinal_type gid_node = x_owned_map_->getGlobalElement(nn*numeqs_); const local_ordinal_type lid_overlap = (x_overlap_map_->getLocalElement(gid_node))/numeqs_; const double x = mesh_->get_x(lid_overlap); const double y = mesh_->get_y(lid_overlap); const double z = mesh_->get_z(lid_overlap); #ifdef TUSAS_RUN_ON_CPU u_1d[numeqs_*nn+k] = (*initfunc_)[k](x,y,z,k); #else u_1d[numeqs_*nn+k] = tusastpetra::init_heat_test_(x,y,z,k); #endif } );//parallel_for }//k if(localprojectionindices_.size() > 0 ){ auto comm_ = Teuchos::DefaultComm<int>::getComm(); const int mypid = comm_->getRank(); if( 0 == mypid)std::cout<<" Performing local projection "<<std::endl; //right now,4-12-23 we make some assumptions and simplifications // we define the P1(v) as the projection of v onto the *direction* of q // P1(v) = q (q, v) // we want p1(v) to have norm=1, with ||P1(v))|| = (q,v)||q|| // P(v) = q (q,v) / ( (q,v) ||q||) = q/||q|| // // ie any vector projected onto q with norm=1 is q/||q|| // //also see section III.1 of //https://www.unige.ch/~hairer/poly-sde-mani.pdf //Solving Differential Equations on Manifolds //Ernst Hairer //Universite de Geneve June 2011 //Section de mathematiques //2-4 rue du Lievre, CP 64 //CH-1211 Geneve 4 auto un_view = u_new_->getLocalViewHost(Tpetra::Access::ReadWrite); auto un_1d = Kokkos::subview (un_view, Kokkos::ALL (), 0); //for (int nn=0; nn < localLength; nn++) {//cn figure out a better way here... Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultHostExecutionSpace>(0,localLength),[=](const int& nn){ double norm = 0.; //std::cout<<nn<<std::endl; for( auto k : localprojectionindices_ ){ norm = norm + un_1d[numeqs_*nn+k]*un_1d[numeqs_*nn+k]; //std::cout<<" "<<k<<" "<<numeqs_*nn+k<<" "<<un_1d[numeqs_*nn+k]<<" "; } //std::cout<<"norm = "<<norm<<std::endl; for( auto k : localprojectionindices_ ){ un_1d[numeqs_*nn+k] = un_1d[numeqs_*nn+k]/sqrt(norm); } } );//parallel_for }//if //exit(0); } template<class scalar_type> void ModelEvaluatorTPETRA<scalar_type>::set_test_case() { bool dorestart = paramList.get<bool> (TusasrestartNameString); auto comm_ = Teuchos::DefaultComm<int>::getComm(); if( 0 == comm_->getRank()) std::cout<<std::endl<<"set_test_case started"<<std::endl<<std::endl; paramfunc_.resize(0); if("heat" == paramList.get<std::string> (TusastestNameString)){ // numeqs_ number of variables(equations) numeqs_ = 1; residualfunc_ = new std::vector<RESFUNC>(numeqs_); //(*residualfunc_)[0] = &tusastpetra::residual_heat_test_; (*residualfunc_)[0] = tpetra::heat::residual_heat_test_dp_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::heat::prec_heat_test_dp_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::heat::init_heat_test_; dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); // cubit nodesets start at 1; exodus nodesets start at 0, hence off by one here // [numeq][nodeset id] // [variable index][nodeset index] (*dirichletfunc_)[0][0] = &dbc_zero_; (*dirichletfunc_)[0][1] = &dbc_zero_; (*dirichletfunc_)[0][2] = &dbc_zero_; (*dirichletfunc_)[0][3] = &dbc_zero_; paramfunc_.resize(1); paramfunc_[0] = &tpetra::heat::param_; neumannfunc_ = NULL; post_proc.push_back(new post_process(Comm,mesh_,(int)0)); post_proc[0].postprocfunc_ = &tpetra::heat::postproc_; }else if("radconvbc" == paramList.get<std::string> (TusastestNameString)){ // numeqs_ number of variables(equations) numeqs_ = 1; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = tpetra::heat::residual_heat_test_dp_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::heat::prec_heat_test_dp_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::radconvbc::init_heat_; dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); // cubit nodesets start at 1; exodus nodesets start at 0, hence off by one here // [numeq][nodeset id] // [variable index][nodeset index] //(*dirichletfunc_)[0][0] = &dbc_zero_; (*dirichletfunc_)[0][1] = &tpetra::radconvbc::dbc_; //(*dirichletfunc_)[0][2] = &dbc_zero_; (*dirichletfunc_)[0][3] = &tpetra::radconvbc::dbc_; paramfunc_.resize(2); paramfunc_[0] = &tpetra::heat::param_;//heat paramfunc_[1] = &tpetra::radconvbc::param_; // numeqs_ number of variables(equations) neumannfunc_ = new std::vector<std::map<int,NBCFUNC>>(numeqs_); //neumannfunc_ = NULL; (*neumannfunc_)[0][2] = &tpetra::radconvbc::nbc_; //post_proc.push_back(new post_process(Comm,mesh_,(int)0)); //post_proc[0].postprocfunc_ = &tpetra::postproc_; }else if("NLheatIMR" == paramList.get<std::string> (TusastestNameString)){ // numeqs_ number of variables(equations) numeqs_ = 1; residualfunc_ = new std::vector<RESFUNC>(numeqs_); //(*residualfunc_)[0] = &tusastpetra::residual_heat_test_; (*residualfunc_)[0] = tpetra::residual_nlheatimr_test_dp_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::heat::prec_heat_test_dp_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::heat::init_heat_test_; dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); // cubit nodesets start at 1; exodus nodesets start at 0, hence off by one here // [numeq][nodeset id] // [variable index][nodeset index] (*dirichletfunc_)[0][0] = &dbc_zero_; (*dirichletfunc_)[0][1] = &dbc_zero_; (*dirichletfunc_)[0][2] = &dbc_zero_; (*dirichletfunc_)[0][3] = &dbc_zero_; paramfunc_.resize(1); paramfunc_[0] = &tpetra::heat::param_; neumannfunc_ = NULL; post_proc.push_back(new post_process(Comm,mesh_,(int)0)); post_proc[0].postprocfunc_ = &tpetra::heat::postproc_; }else if("NLheatCN" == paramList.get<std::string> (TusastestNameString)){ // numeqs_ number of variables(equations) numeqs_ = 1; residualfunc_ = new std::vector<RESFUNC>(numeqs_); //(*residualfunc_)[0] = &tusastpetra::residual_heat_test_; (*residualfunc_)[0] = tpetra::residual_nlheatcn_test_dp_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::prec_nlheatcn_test_dp_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::heat::init_heat_test_; dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); // cubit nodesets start at 1; exodus nodesets start at 0, hence off by one here // [numeq][nodeset id] // [variable index][nodeset index] (*dirichletfunc_)[0][0] = &dbc_zero_; (*dirichletfunc_)[0][1] = &dbc_zero_; (*dirichletfunc_)[0][2] = &dbc_zero_; (*dirichletfunc_)[0][3] = &dbc_zero_; paramfunc_.resize(1); paramfunc_[0] = &tpetra::heat::param_; neumannfunc_ = NULL; post_proc.push_back(new post_process(Comm,mesh_,(int)0)); post_proc[0].postprocfunc_ = &tpetra::heat::postproc_; }else if("heat2" == paramList.get<std::string> (TusastestNameString)){ numeqs_ = 2; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = tpetra::heat::residual_heat_test_dp_; (*residualfunc_)[1] = tpetra::heat::residual_heat_test_dp_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::heat::prec_heat_test_dp_; (*preconfunc_)[1] = tpetra::heat::prec_heat_test_dp_; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::heat::init_heat_test_; (*initfunc_)[1] = &tpetra::heat::init_heat_test_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; (*varnames_)[1] = "phi"; //dirichletfunc_ = NULL; dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); // cubit nodesets start at 1; exodus nodesets start at 0, hence off by one here // [numeq][nodeset id] // [variable index][nodeset index] (*dirichletfunc_)[0][0] = &dbc_zero_; (*dirichletfunc_)[0][1] = &dbc_zero_; (*dirichletfunc_)[0][2] = &dbc_zero_; (*dirichletfunc_)[0][3] = &dbc_zero_; (*dirichletfunc_)[1][0] = &dbc_zero_; (*dirichletfunc_)[1][1] = &dbc_zero_; (*dirichletfunc_)[1][2] = &dbc_zero_; (*dirichletfunc_)[1][3] = &dbc_zero_; neumannfunc_ = NULL; }else if("cummins" == paramList.get<std::string> (TusastestNameString)){ numeqs_ = 2; residualfunc_ = new std::vector<RESFUNC>(numeqs_); // (*residualfunc_)[0] = &cummins::residual_heat_; // (*residualfunc_)[1] = &cummins::residual_phase_; (*residualfunc_)[0] = tpetra::heat::residual_heat_test_dp_; (*residualfunc_)[1] = tpetra::heat::residual_heat_test_dp_; // preconfunc_ = new std::vector<PREFUNC>(numeqs_); // (*preconfunc_)[0] = &cummins::prec_heat_; // (*preconfunc_)[1] = &cummins::prec_phase_; initfunc_ = new std::vector<INITFUNC>(numeqs_); //(*initfunc_)[0] = &cummins::init_heat_; //(*initfunc_)[1] = &cummins::init_phase_; (*initfunc_)[0] = &tpetra::heat::init_heat_test_; (*initfunc_)[1] = &tpetra::heat::init_heat_test_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; (*varnames_)[1] = "phi"; dirichletfunc_ = NULL; neumannfunc_ = NULL; paramfunc_.resize(1); paramfunc_[0] = &cummins::param_; }else if("farzadi" == paramList.get<std::string> (TusastestNameString)){ //farzadi test if(paramList.get<double> (TusasthetaNameString) < .49) exit(0); numeqs_ = 2; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::farzadi3d::init_conc_farzadi_; (*initfunc_)[1] = &tpetra::farzadi3d::init_phase_farzadi_; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = tpetra::farzadi3d::residual_conc_farzadi_dp_; (*residualfunc_)[1] = tpetra::farzadi3d::residual_phase_farzadi_uncoupled_dp_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::farzadi3d::prec_conc_farzadi_dp_; (*preconfunc_)[1] = tpetra::farzadi3d::prec_phase_farzadi_dp_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; (*varnames_)[1] = "phi"; dirichletfunc_ = NULL; post_proc.push_back(new post_process(Comm,mesh_,(int)0)); post_proc[0].postprocfunc_ = &tpetra::farzadi3d::postproc_c_; post_proc.push_back(new post_process(Comm,mesh_,(int)1)); post_proc[1].postprocfunc_ = &tpetra::farzadi3d::postproc_t_; paramfunc_.resize(1); paramfunc_[0] = &tpetra::farzadi3d::param_; neumannfunc_ = NULL; }else if("fullycoupled" == paramList.get<std::string> (TusastestNameString)){ //farzadi test //if(paramList.get<double> (TusasthetaNameString) < .49) exit(0); numeqs_ = 3; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::fullycoupled::init_conc_farzadi_; (*initfunc_)[1] = &tpetra::fullycoupled::init_phase_farzadi_; (*initfunc_)[2] = &tpetra::fullycoupled::init_heat_; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = tpetra::farzadi3d::residual_conc_farzadi_activated_dp_; (*residualfunc_)[1] = tpetra::farzadi3d::residual_phase_farzadi_coupled_activated_dp_; (*residualfunc_)[2] = tpetra::goldak::residual_coupled_test_dp_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::farzadi3d::prec_conc_farzadi_dp_; (*preconfunc_)[1] = tpetra::farzadi3d::prec_phase_farzadi_dp_; (*preconfunc_)[2] = tpetra::goldak::prec_test_dp_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; (*varnames_)[1] = "phi"; (*varnames_)[2] = "theta"; dirichletfunc_ = NULL; post_proc.push_back(new post_process(Comm,mesh_,(int)0)); post_proc[0].postprocfunc_ = &tpetra::farzadi3d::postproc_c_; post_proc.push_back(new post_process(Comm,mesh_,(int)1)); post_proc[1].postprocfunc_ = &tpetra::fullycoupled::postproc_t_; paramfunc_.resize(5); paramfunc_[0] = &tpetra::farzadi3d::param_; paramfunc_[1] = &tpetra::heat::param_; paramfunc_[2] = &tpetra::radconvbc::param_; paramfunc_[3] = &tpetra::goldak::param_; paramfunc_[4] = &tpetra::fullycoupled::param_; neumannfunc_ = new std::vector<std::map<int,NBCFUNC>>(numeqs_); //(*neumannfunc_)[2][4] = &tpetra::radconvbc::nbc_; (*neumannfunc_)[2][4] = &tpetra::nbc_one_; }else if("farzadiexp" == paramList.get<std::string> (TusastestNameString)){ //farzadi test if(paramList.get<double> (TusasthetaNameString) < .49) exit(0); numeqs_ = 2; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::farzadi3d::init_conc_farzadi_; (*initfunc_)[1] = &tpetra::farzadi3d::init_phase_farzadi_; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = tpetra::farzadi3d::residual_conc_farzadi_dp_; (*residualfunc_)[1] = tpetra::farzadi3d::residual_phase_farzadi_dp_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::farzadi3d::prec_conc_farzadi_dp_; (*preconfunc_)[1] = tpetra::farzadi3d::prec_phase_farzadi_dp_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; (*varnames_)[1] = "phi"; dirichletfunc_ = NULL; paramfunc_.resize(1); paramfunc_[0] = &tpetra::farzadi3d::param_; //paramfunc_ = &farzadi::param_; neumannfunc_ = NULL; }else if("farzadi_test" == paramList.get<std::string> (TusastestNameString)){ //farzadi test numeqs_ = 2; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::farzadi3d::init_conc_farzadi_; (*initfunc_)[1] = &tpetra::farzadi3d::init_phase_farzadi_test_; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = tpetra::farzadi3d::residual_conc_farzadi_dp_; (*residualfunc_)[1] = tpetra::farzadi3d::residual_phase_farzadi_uncoupled_dp_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::farzadi3d::prec_conc_farzadi_dp_; (*preconfunc_)[1] = tpetra::farzadi3d::prec_phase_farzadi_dp_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; (*varnames_)[1] = "phi"; dirichletfunc_ = NULL; post_proc.push_back(new post_process(Comm,mesh_,(int)0)); post_proc[0].postprocfunc_ = &tpetra::farzadi3d::postproc_c_; post_proc.push_back(new post_process(Comm,mesh_,(int)1)); post_proc[1].postprocfunc_ = &tpetra::farzadi3d::postproc_t_; paramfunc_.resize(1); paramfunc_[0] = &tpetra::farzadi3d::param_; neumannfunc_ = NULL; }else if("pfhub3" == paramList.get<std::string> (TusastestNameString)){ numeqs_ = 2; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::pfhub3::init_heat_pfhub3_; (*initfunc_)[1] = &tpetra::pfhub3::init_phase_pfhub3_; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = tpetra::pfhub3::residual_heat_pfhub3_dp_; (*residualfunc_)[1] = tpetra::pfhub3::residual_phase_pfhub3_dp_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::pfhub3::prec_heat_pfhub3_dp_; (*preconfunc_)[1] = tpetra::pfhub3::prec_phase_pfhub3_dp_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; (*varnames_)[1] = "phi"; dirichletfunc_ = NULL; paramfunc_.resize(1); paramfunc_[0] = &tpetra::pfhub3::param_; neumannfunc_ = NULL; }else if("pfhub3noise" == paramList.get<std::string> (TusastestNameString)){ numeqs_ = 2; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::pfhub3::init_heat_pfhub3_; (*initfunc_)[1] = &tpetra::pfhub3::init_phase_pfhub3_; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = tpetra::pfhub3::residual_heat_pfhub3_dp_; (*residualfunc_)[1] = tpetra::pfhub3::residual_phase_pfhub3_noise_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::pfhub3::prec_heat_pfhub3_dp_; (*preconfunc_)[1] = tpetra::pfhub3::prec_phase_pfhub3_dp_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; (*varnames_)[1] = "phi"; dirichletfunc_ = NULL; paramfunc_.resize(1); paramfunc_[0] = &tpetra::pfhub3::param_; neumannfunc_ = NULL; }else if("pfhub2kks" == paramList.get<std::string> (TusastestNameString)){ Teuchos::ParameterList *problemList; problemList = &paramList.sublist ( "ProblemParams", false ); int numeta = problemList->get<int>("N"); numeqs_ = numeta+1; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = tpetra::pfhub2::residual_c_kks_dp_; (*residualfunc_)[1] = tpetra::pfhub2::residual_eta_kks_dp_; #if 0 if( 4 == numeta){ (*residualfunc_)[2] = &pfhub2::residual_eta_kks_; (*residualfunc_)[3] = &pfhub2::residual_eta_kks_; (*residualfunc_)[4] = &pfhub2::residual_eta_kks_; } #endif preconfunc_ = NULL; #if 0 preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = &pfhub2::prec_c_; (*preconfunc_)[1] = &pfhub2::prec_eta_; if( 4 == numeta){ (*preconfunc_)[2] = &pfhub2::prec_eta_; (*preconfunc_)[3] = &pfhub2::prec_eta_; (*preconfunc_)[4] = &pfhub2::prec_eta_; } #endif initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &pfhub2::init_c_; (*initfunc_)[1] = &pfhub2::init_eta_; if( 4 == numeta){ (*initfunc_)[2] = &pfhub2::init_eta_; (*initfunc_)[3] = &pfhub2::init_eta_; (*initfunc_)[4] = &pfhub2::init_eta_; } varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "c"; (*varnames_)[1] = "eta0"; if( 4 == numeta){ (*varnames_)[2] = "eta1"; (*varnames_)[3] = "eta2"; (*varnames_)[4] = "eta3"; } // numeqs_ number of variables(equations) //dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); dirichletfunc_ = NULL; neumannfunc_ = NULL; paramfunc_.resize(1); paramfunc_[0] = &tpetra::pfhub2::param_; post_proc.push_back(new post_process(Comm,mesh_,(int)0)); post_proc[0].postprocfunc_ = &pfhub2::postproc_c_b_; post_proc.push_back(new post_process(Comm,mesh_,(int)1)); post_proc[1].postprocfunc_ = &tpetra::pfhub2::postproc_c_a_; }else if("pfhub2" == paramList.get<std::string> (TusastestNameString)){ Teuchos::ParameterList *problemList; problemList = &paramList.sublist ( "ProblemParams", false ); int numeta = problemList->get<int>("N"); numeqs_ = numeta+2; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = tpetra::pfhub2::residual_c_dp_; (*residualfunc_)[1] = tpetra::pfhub2::residual_mu_dp_; (*residualfunc_)[2] = tpetra::pfhub2::residual_eta_dp_; if( 4 == numeta){ (*residualfunc_)[3] = tpetra::pfhub2::residual_eta_dp_; (*residualfunc_)[4] = tpetra::pfhub2::residual_eta_dp_; (*residualfunc_)[5] = tpetra::pfhub2::residual_eta_dp_; } preconfunc_ = NULL; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = &tpetra::pfhub2::prec_ut_; (*preconfunc_)[1] = &tpetra::pfhub2::prec_ut_; (*preconfunc_)[2] = &tpetra::pfhub2::prec_eta_; if( 4 == numeta){ (*preconfunc_)[3] = &tpetra::pfhub2::prec_eta_; (*preconfunc_)[4] = &tpetra::pfhub2::prec_eta_; (*preconfunc_)[5] = &tpetra::pfhub2::prec_eta_; } initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &::pfhub2::init_c_; (*initfunc_)[1] = &tpetra::pfhub2::init_mu_; (*initfunc_)[2] = &tpetra::pfhub2::init_eta_; if( 4 == numeta){ (*initfunc_)[3] = &tpetra::pfhub2::init_eta_; (*initfunc_)[4] = &tpetra::pfhub2::init_eta_; (*initfunc_)[5] = &tpetra::pfhub2::init_eta_; } varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "c"; (*varnames_)[1] = "mu"; (*varnames_)[2] = "eta0"; if( 4 == numeta){ (*varnames_)[2] = "eta1"; (*varnames_)[4] = "eta2"; (*varnames_)[5] = "eta3"; } // numeqs_ number of variables(equations) //dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); dirichletfunc_ = NULL; neumannfunc_ = NULL; paramfunc_.resize(1); paramfunc_[0] = &tpetra::pfhub2::param_; // post_proc.push_back(new post_process(Comm,mesh_,(int)0)); // post_proc[0].postprocfunc_ = &pfhub2::postproc_c_b_; // post_proc.push_back(new post_process(Comm,mesh_,(int)1)); // post_proc[1].postprocfunc_ = &tpetra::pfhub2::postproc_c_a_; }else if("pfhub2trans" == paramList.get<std::string> (TusastestNameString)){ Teuchos::ParameterList *problemList; problemList = &paramList.sublist ( "ProblemParams", false ); int numeta = problemList->get<int>("N"); numeqs_ = numeta+2; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = tpetra::pfhub2::residual_c_dp_; (*residualfunc_)[1] = tpetra::pfhub2::residual_mu_dp_; (*residualfunc_)[2] = tpetra::pfhub2::residual_eta_dp_; if( 4 == numeta){ (*residualfunc_)[3] = tpetra::pfhub2::residual_eta_dp_; (*residualfunc_)[4] = tpetra::pfhub2::residual_eta_dp_; (*residualfunc_)[5] = tpetra::pfhub2::residual_eta_dp_; } preconfunc_ = NULL; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = &tpetra::pfhub2::prec_mu_; (*preconfunc_)[1] = &tpetra::pfhub2::prec_c_; (*preconfunc_)[2] = &tpetra::pfhub2::prec_eta_; if( 4 == numeta){ (*preconfunc_)[3] = &tpetra::pfhub2::prec_eta_; (*preconfunc_)[4] = &tpetra::pfhub2::prec_eta_; (*preconfunc_)[5] = &tpetra::pfhub2::prec_eta_; } initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::pfhub2::init_mu_; (*initfunc_)[1] = &::pfhub2::init_c_; (*initfunc_)[2] = &tpetra::pfhub2::init_eta_; if( 4 == numeta){ (*initfunc_)[3] = &tpetra::pfhub2::init_eta_; (*initfunc_)[4] = &tpetra::pfhub2::init_eta_; (*initfunc_)[5] = &tpetra::pfhub2::init_eta_; } varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "mu"; (*varnames_)[1] = "c"; (*varnames_)[2] = "eta0"; if( 4 == numeta){ (*varnames_)[2] = "eta1"; (*varnames_)[4] = "eta2"; (*varnames_)[5] = "eta3"; } // numeqs_ number of variables(equations) //dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); dirichletfunc_ = NULL; neumannfunc_ = NULL; paramfunc_.resize(1); paramfunc_[0] = &tpetra::pfhub2::param_trans_; // post_proc.push_back(new post_process(Comm,mesh_,(int)0)); // post_proc[0].postprocfunc_ = &pfhub2::postproc_c_b_; // post_proc.push_back(new post_process(Comm,mesh_,(int)1)); // post_proc[1].postprocfunc_ = &tpetra::pfhub2::postproc_c_a_; }else if("cahnhilliard" == paramList.get<std::string> (TusastestNameString)){ //std::cout<<"cahnhilliard"<<std::endl; numeqs_ = 2; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::cahnhilliard::init_c_; (*initfunc_)[1] = &tpetra::cahnhilliard::init_mu_; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = &tpetra::cahnhilliard::residual_c_; (*residualfunc_)[1] = &tpetra::cahnhilliard::residual_mu_; preconfunc_ = NULL; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "c"; (*varnames_)[1] = "mu"; // numeqs_ number of variables(equations) dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); // cubit nodesets start at 1; exodus nodesets start at 0, hence off by one here // [numeq][nodeset id] // [variable index][nodeset index] (*dirichletfunc_)[0][1] = &dbc_zero_; (*dirichletfunc_)[0][3] = &dbc_zero_; (*dirichletfunc_)[1][1] = &dbc_zero_; (*dirichletfunc_)[1][3] = &dbc_zero_; neumannfunc_ = NULL; paramfunc_.resize(1); paramfunc_[0] = tpetra::cahnhilliard::param_; //exit(0); }else if("cahnhilliardtrans" == paramList.get<std::string> (TusastestNameString)){ //std::cout<<"cahnhilliard"<<std::endl; numeqs_ = 2; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::cahnhilliard::init_mu_; (*initfunc_)[1] = &tpetra::cahnhilliard::init_c_; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = &tpetra::cahnhilliard::residual_mu_trans_; (*residualfunc_)[1] = &tpetra::cahnhilliard::residual_c_trans_; preconfunc_ = NULL; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = &tpetra::cahnhilliard::prec_mu_trans_; (*preconfunc_)[1] = &tpetra::cahnhilliard::prec_c_trans_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "mu"; (*varnames_)[1] = "c"; // numeqs_ number of variables(equations) dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); // cubit nodesets start at 1; exodus nodesets start at 0, hence off by one here // [numeq][nodeset id] // [variable index][nodeset index] (*dirichletfunc_)[0][1] = &dbc_zero_; (*dirichletfunc_)[0][3] = &dbc_zero_; (*dirichletfunc_)[1][1] = &dbc_zero_; (*dirichletfunc_)[1][3] = &dbc_zero_; neumannfunc_ = NULL; paramfunc_.resize(1); paramfunc_[0] = tpetra::cahnhilliard::param_; //exit(0); }else if("robin" == paramList.get<std::string> (TusastestNameString)){ numeqs_ = 1; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = &tpetra::robin::residual_robin_test_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = &tpetra::robin::prec_robin_test_; initfunc_ = new std::vector<INITFUNC>(numeqs_); //(*initfunc_)[0] = &init_neumann_test_; (*initfunc_)[0] = &tpetra::robin::init_robin_test_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; // numeqs_ number of variables(equations) dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); // cubit nodesets start at 1; exodus nodesets start at 0, hence off by one here // [numeq][nodeset id] // [variable index][nodeset index] //(*dirichletfunc_)[0][0] = &dbc_zero_; //(*dirichletfunc_)[0][1] = &dbc_zero_; //(*dirichletfunc_)[0][2] = &dbc_zero_; (*dirichletfunc_)[0][3] = &dbc_zero_; // numeqs_ number of variables(equations) neumannfunc_ = new std::vector<std::map<int,NBCFUNC>>(numeqs_); //neumannfunc_ = NULL; //(*neumannfunc_)[0][0] = &nbc_one_; (*neumannfunc_)[0][1] = &tpetra::robin::nbc_robin_test_; //(*neumannfunc_)[0][1] = &nbc_zero_; //(*neumannfunc_)[0][2] = &nbc_zero_; //(*neumannfunc_)[0][3] = &nbc_zero_; post_proc.push_back(new post_process(Comm,mesh_,(int)0)); post_proc[0].postprocfunc_ = &tpetra::robin::postproc_robin_; }else if("timeonly" == paramList.get<std::string> (TusastestNameString)){ numeqs_ = 1; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = &tpetra::timeonly::residual_test_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = &tpetra::heat::prec_heat_test_; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &timeonly::init_test_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; // numeqs_ number of variables(equations) dirichletfunc_ = NULL; neumannfunc_ = NULL; }else if("autocatalytic4" == paramList.get<std::string> (TusastestNameString)){ numeqs_ = 4; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = &tpetra::autocatalytic4::residual_a_; (*residualfunc_)[1] = &tpetra::autocatalytic4::residual_b_; (*residualfunc_)[2] = &tpetra::autocatalytic4::residual_ab_; (*residualfunc_)[3] = &tpetra::autocatalytic4::residual_c_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = &tpetra::heat::prec_heat_test_; (*preconfunc_)[1] = &tpetra::heat::prec_heat_test_; (*preconfunc_)[2] = &tpetra::heat::prec_heat_test_; (*preconfunc_)[3] = &tpetra::heat::prec_heat_test_; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &autocatalytic4::init_a_; (*initfunc_)[1] = &autocatalytic4::init_b_; (*initfunc_)[2] = &autocatalytic4::init_ab_; (*initfunc_)[3] = &autocatalytic4::init_c_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "a"; (*varnames_)[1] = "b"; (*varnames_)[2] = "ab"; (*varnames_)[3] = "c"; // numeqs_ number of variables(equations) dirichletfunc_ = NULL; neumannfunc_ = NULL; }else if("localprojection" == paramList.get<std::string> (TusastestNameString)){ numeqs_ = 2; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = &tpetra::localprojection::residual_u1_; (*residualfunc_)[1] = &tpetra::localprojection::residual_u2_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = &tpetra::heat::prec_heat_test_; (*preconfunc_)[1] = &tpetra::heat::prec_heat_test_; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::localprojection::init_u1_; (*initfunc_)[1] = &tpetra::localprojection::init_u2_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u1"; (*varnames_)[1] = "u2"; // numeqs_ number of variables(equations) dirichletfunc_ = NULL; neumannfunc_ = NULL; post_proc.push_back(new post_process(Comm,mesh_,(int)0, post_process::NORMINF,dorestart)); post_proc[0].postprocfunc_ = &tpetra::localprojection::postproc_u1_; post_proc.push_back(new post_process(Comm,mesh_,(int)1, post_process::NORMINF,dorestart)); post_proc[1].postprocfunc_ = &tpetra::localprojection::postproc_u2_; post_proc.push_back(new post_process(Comm,mesh_,(int)2, post_process::NORMINF,dorestart)); post_proc[2].postprocfunc_ = &tpetra::localprojection::postproc_norm_; post_proc.push_back(new post_process(Comm,mesh_,(int)3, post_process::NORMINF,dorestart)); post_proc[3].postprocfunc_ = &tpetra::localprojection::postproc_u1err_; post_proc.push_back(new post_process(Comm,mesh_,(int)4, post_process::NORMINF,dorestart)); post_proc[4].postprocfunc_ = &tpetra::localprojection::postproc_u2err_; localprojectionindices_.push_back(0); localprojectionindices_.push_back(1); }else if("goldak" == paramList.get<std::string> (TusastestNameString)){ // numeqs_ number of variables(equations) numeqs_ = 1; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = tpetra::goldak::residual_uncoupled_test_dp_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::goldak::prec_test_dp_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::goldak::init_heat_; dirichletfunc_ = NULL; //dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); // cubit nodesets start at 1; exodus nodesets start at 0, hence off by one here // [numeq][nodeset id] // [variable index][nodeset index] // (*dirichletfunc_)[0][0] = &tpetra::goldak::dbc_; // (*dirichletfunc_)[0][1] = &tpetra::goldak::dbc_; // (*dirichletfunc_)[0][2] = &tpetra::goldak::dbc_; // (*dirichletfunc_)[0][3] = &tpetra::goldak::dbc_; paramfunc_.resize(3); paramfunc_[0] = &tpetra::heat::param_; paramfunc_[1] = &tpetra::radconvbc::param_; paramfunc_[2] = &tpetra::goldak::param_; // numeqs_ number of variables(equations) // neumannfunc_ = NULL; neumannfunc_ = new std::vector<std::map<int,NBCFUNC>>(numeqs_); (*neumannfunc_)[0][4] = &tpetra::radconvbc::nbc_; post_proc.push_back(new post_process(Comm,mesh_,(int)0, post_process::MAXVALUE,dorestart)); post_proc[0].postprocfunc_ = &tpetra::goldak::postproc_qdot_; post_proc.push_back(new post_process(Comm,mesh_,(int)1, post_process::MAXVALUE,dorestart)); post_proc[1].postprocfunc_ = &tpetra::goldak::postproc_u_; }else if("randomtest" == paramList.get<std::string> (TusastestNameString)){ // numeqs_ number of variables(equations) numeqs_ = 1; residualfunc_ = new std::vector<RESFUNC>(numeqs_); //(*residualfunc_)[0] = &tusastpetra::residual_heat_test_; (*residualfunc_)[0] = tpetra::random::residual_test_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = tpetra::heat::prec_heat_test_dp_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "u"; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::heat::init_heat_test_; dirichletfunc_ = new std::vector<std::map<int,DBCFUNC>>(numeqs_); // cubit nodesets start at 1; exodus nodesets start at 0, hence off by one here // [numeq][nodeset id] // [variable index][nodeset index] (*dirichletfunc_)[0][0] = &dbc_zero_; (*dirichletfunc_)[0][1] = &dbc_zero_; (*dirichletfunc_)[0][2] = &dbc_zero_; (*dirichletfunc_)[0][3] = &dbc_zero_; paramfunc_.resize(1); paramfunc_[0] = &tpetra::heat::param_; neumannfunc_ = NULL; //post_proc.push_back(new post_process(Comm,mesh_,(int)0)); //post_proc[0].postprocfunc_ = &tpetra::heat::postproc_; }else if("quaternion" == paramList.get<std::string> (TusastestNameString)){ numeqs_ = 5; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = &tpetra::quaternion::residual_; (*residualfunc_)[1] = &tpetra::quaternion::residual_; (*residualfunc_)[2] = &tpetra::quaternion::residual_; (*residualfunc_)[3] = &tpetra::quaternion::residual_; (*residualfunc_)[4] = &tpetra::quaternion::residual_phi_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = &tpetra::quaternion::precon_; (*preconfunc_)[1] = &tpetra::quaternion::precon_; (*preconfunc_)[2] = &tpetra::quaternion::precon_; (*preconfunc_)[3] = &tpetra::quaternion::precon_; (*preconfunc_)[4] = &tpetra::quaternion::precon_phi_; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::quaternion::initq0s_; (*initfunc_)[1] = &tpetra::quaternion::initq1s_; (*initfunc_)[2] = &tpetra::quaternion::initq2_; (*initfunc_)[3] = &tpetra::quaternion::initq3_; (*initfunc_)[4] = &tpetra::quaternion::initphi_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "q0"; (*varnames_)[1] = "q1"; (*varnames_)[2] = "q2"; (*varnames_)[3] = "q3"; (*varnames_)[4] = "phi"; // numeqs_ number of variables(equations) dirichletfunc_ = NULL; neumannfunc_ = NULL; post_proc.push_back(new post_process(Comm,mesh_,(int)0, post_process::MAXVALUE)); post_proc[0].postprocfunc_ = &tpetra::quaternion::postproc_normq_; post_proc.push_back(new post_process(Comm,mesh_,(int)1, post_process::MAXVALUE)); post_proc[1].postprocfunc_ = &tpetra::quaternion::postproc_qdotqt_; post_proc.push_back(new post_process(Comm,mesh_,(int)2)); post_proc[2].postprocfunc_ = &tpetra::quaternion::postproc_rgb_r_; post_proc.push_back(new post_process(Comm,mesh_,(int)3)); post_proc[3].postprocfunc_ = &tpetra::quaternion::postproc_rgb_g_; post_proc.push_back(new post_process(Comm,mesh_,(int)4)); post_proc[4].postprocfunc_ = &tpetra::quaternion::postproc_rgb_b_; #if 0 post_proc.push_back(new post_process(Comm,mesh_,(int)2, post_process::NORM2)); post_proc[1].postprocfunc_ = &tpetra::quaternion::postproc_normphi_; post_proc.push_back(new post_process(Comm,mesh_,(int)3)); post_proc[3].postprocfunc_ = &tpetra::quaternion::postproc_ea0_; post_proc.push_back(new post_process(Comm,mesh_,(int)4)); post_proc[4].postprocfunc_ = &tpetra::quaternion::postproc_ea1_; post_proc.push_back(new post_process(Comm,mesh_,(int)5)); post_proc[5].postprocfunc_ = &tpetra::quaternion::postproc_ea2_; #endif #if 0 localprojectionindices_.push_back(0); localprojectionindices_.push_back(1); localprojectionindices_.push_back(2); localprojectionindices_.push_back(3); #endif }else if("quaternionphase" == paramList.get<std::string> (TusastestNameString)){ numeqs_ = 1; residualfunc_ = new std::vector<RESFUNC>(numeqs_); (*residualfunc_)[0] = &tpetra::quaternion::residual_phase_; preconfunc_ = new std::vector<PREFUNC>(numeqs_); (*preconfunc_)[0] = &tpetra::quaternion::precon_phi_; initfunc_ = new std::vector<INITFUNC>(numeqs_); (*initfunc_)[0] = &tpetra::quaternion::initphi_; varnames_ = new std::vector<std::string>(numeqs_); (*varnames_)[0] = "phi"; // numeqs_ number of variables(equations) dirichletfunc_ = NULL; neumannfunc_ = NULL; } else { auto comm_ = Teuchos::DefaultComm<int>::getComm(); if( 0 == comm_->getRank() ){ std::cout<<std::endl<<std::endl<<"Test case: "<<paramList.get<std::string> (TusastestNameString) <<" not found. (void ModelEvaluatorTPETRA<scalar_type>::set_test_case())" <<std::endl<<std::endl<<std::endl; } exit(0); } if(numeqs_ > TUSAS_MAX_NUMEQS){ auto comm_ = Teuchos::DefaultComm<int>::getComm(); if( 0 == comm_->getRank() ){ std::cout<<std::endl<<std::endl<<"numeqs_ > TUSAS_MAX_NUMEQS; 1. increase TUSAS_MAX_NUMEQS to " <<numeqs_<<" ; 2. adjust TUSAS_MAX_NUMEQS_X_BASIS_NODES_PER_ELEM appropriately and recompile." <<std::endl<<std::endl<<std::endl; } exit(0); } //set the params in the test case now... Teuchos::ParameterList *problemList; problemList = &paramList.sublist ( "ProblemParams", false ); for( int k = 0; k < paramfunc_.size(); k++ ){ paramfunc_[k](problemList); } if( 0 == comm_->getRank()){ if(0 < numeqs_){ std::cout<<" numeqs_ = "<<numeqs_<<std::endl; }else{ std::cout<<" numeqs < 0. Exiting."<<std::endl; exit(0); } if(NULL != residualfunc_){ std::cout<<" residualfunc_ with size "<<residualfunc_->size()<<" found."<<std::endl; }else{ std::cout<<" residualfunc_ not found. Exiting."<<std::endl; exit(0); } if(NULL != preconfunc_){ std::cout<<" preconfunc_ with size "<<preconfunc_->size()<<" found."<<std::endl; } if(NULL != initfunc_){ std::cout<<" initfunc_ with size "<<initfunc_->size()<<" found."<<std::endl; }else{ std::cout<<" initfunc_ not found. Exiting."<<std::endl; exit(0); } if(NULL != varnames_){ std::cout<<" varnames_ with size "<<varnames_->size()<<" found."<<std::endl; }else{ std::cout<<" varnames_ not found. Exiting."<<std::endl; exit(0); } if(NULL != dirichletfunc_){ std::cout<<" dirichletfunc_ with size "<<dirichletfunc_->size()<<" found."<<std::endl; std::map<int,DBCFUNC>::iterator it; for( int k = 0; k < numeqs_; k++ ){ for(it = (*dirichletfunc_)[k].begin();it != (*dirichletfunc_)[k].end(); ++it){ int ns_id = it->first; std::cout<<" Equation: "<<k<<" nodeset: "<<ns_id<<std::endl; if(mesh_->node_set_found(ns_id)){ std::cout<<" Nodeset: "<<ns_id<<" found "<<std::endl; }else{ std::cout<<" Nodeset: "<<ns_id<<" NOT FOUND exiting... "<<std::endl; exit(0); }//if }//it }//k }//if if(NULL != neumannfunc_){ std::cout<<" neumannfunc_ with size "<<neumannfunc_->size()<<" found."<<std::endl; std::map<int,NBCFUNC>::iterator it; for( int k = 0; k < numeqs_; k++ ){ for(it = (*neumannfunc_)[k].begin();it != (*neumannfunc_)[k].end(); ++it){ const int ss_id = it->first; std::cout<<" Equation: "<<k<<" sideset: "<<ss_id<<std::endl; if(mesh_->side_set_found(ss_id)){ std::cout<<" Sideset: "<<ss_id<<" found "<<std::endl; }else{ std::cout<<" Sideset: "<<ss_id<<" NOT FOUND exiting... "<<std::endl; exit(0); }//if }//it }//k }//if if(post_proc.size() > 0 ){ std::cout<<" post_proc with size "<<post_proc.size()<<" found."<<std::endl; } std::cout<<std::endl<<"set_test_case ended"<<std::endl<<std::endl; } } template<class scalar_type> void ModelEvaluatorTPETRA<scalar_type>::write_exodus() //void ModelEvaluatorNEMESIS<scalar_type>::write_exodus(const int output_step) { update_mesh_data(); //not sre what the bug is here... Teuchos::TimeMonitor IOWriteTimer(*ts_time_iowrite); mesh_->open_exodus(outfilename.c_str(),Mesh::WRITE); mesh_->write_exodus(ex_id_,output_step_,time_); mesh_->close_exodus(ex_id_); output_step_++; } template<class scalar_type> int ModelEvaluatorTPETRA<scalar_type>:: update_mesh_data() { //std::cout<<"update_mesh_data()"<<std::endl; auto comm_ = Teuchos::DefaultComm<int>::getComm(); //std::vector<int> node_num_map(mesh_->get_node_num_map()); //cn 8-28-18 we need an overlap map with mpi, since shared nodes live // on the decomposed mesh----fix this later Teuchos::RCP<vector_type> temp; if( 1 == comm_->getSize() ){ temp = Teuchos::rcp(new vector_type(*u_old_)); } else{ temp = Teuchos::rcp(new vector_type(x_overlap_map_));//cn might be better to have u_old_ live on overlap map temp->doImport(*u_old_, *importer_, Tpetra::INSERT); } //cn 8-28-18 we need an overlap map with mpi, since shared nodes live // on the decomposed mesh----fix this later int num_nodes = num_overlap_nodes_; std::vector<std::vector<double>> output(numeqs_, std::vector<double>(num_nodes)); const Teuchos::ArrayRCP<scalar_type> uv = temp->get1dViewNonConst(); //const size_t localLength = num_owned_nodes_; for( int k = 0; k < numeqs_; k++ ){ //#pragma omp parallel for for (int nn=0; nn < num_nodes; nn++) { //output[k][nn]=(*temp)[numeqs_*nn+k]; output[k][nn]=uv[numeqs_*nn+k]; //std::cout<<uv[numeqs_*nn+k]<<std::endl; } } int err = 0; for( int k = 0; k < numeqs_; k++ ){ mesh_->update_nodal_data((*varnames_)[k], &output[k][0]); } boost::ptr_vector<error_estimator>::iterator it; for(it = Error_est.begin();it != Error_est.end();++it){ it->update_mesh_data(); } boost::ptr_vector<post_process>::iterator itp; for(itp = post_proc.begin();itp != post_proc.end();++itp){ itp->scalar_reduction(); itp->update_mesh_data(); itp->update_scalar_data(time_); } for(itp = temporal_est.begin();itp != temporal_est.end();++itp){ itp->scalar_reduction(); itp->update_mesh_data(); itp->update_scalar_data(time_); } for(itp = temporal_norm.begin();itp != temporal_norm.end();++itp){ itp->scalar_reduction(); itp->update_mesh_data(); itp->update_scalar_data(time_); } for(itp = temporal_dyn.begin();itp != temporal_dyn.end();++itp){ itp->scalar_reduction(); itp->update_mesh_data(); itp->update_scalar_data(time_); } Elem_col->update_mesh_data(); return err; } template<class scalar_type> void ModelEvaluatorTPETRA<scalar_type>::finalize() { auto comm_ = Teuchos::DefaultComm<int>::getComm(); int mypid = comm_->getRank(); int numproc = comm_->getSize(); bool dorestart = paramList.get<bool> (TusasrestartNameString); write_exodus(); //std::cout<<(solver_->getList()).sublist("Direction").sublist("Newton").sublist("Linear Solver")<<std::endl; int ngmres = 0; comm_->barrier(); if ( (solver_->getList()).sublist("Direction").sublist("Newton").sublist("Linear Solver") .isSublist("Output") == true){ if ( (solver_->getList()).sublist("Direction").sublist("Newton").sublist("Linear Solver") .sublist("Output").getEntryPtr("Cumulative Iteration Count") != NULL){ ngmres = ((solver_->getList()).sublist("Direction").sublist("Newton").sublist("Linear Solver") .sublist("Output").getEntry("Cumulative Iteration Count")).getValue(&ngmres); } } if( 0 == mypid ){ //int numstep = paramList.get<int> (TusasntNameString) - this->start_step; int numstep = numsteps_; std::cout<<std::endl <<"Total number of Newton iterations: "<<nnewt_<<std::endl <<"Total number of GMRES iterations: "<<ngmres<<std::endl <<"Total number of Timesteps: "<<numstep<<std::endl <<"Average number of Newton per Timestep: "<<(float)nnewt_/(float)(numstep)<<std::endl <<"Average number of GMRES per Newton: "<<(float)ngmres/(float)nnewt_<<std::endl <<"Average number of GMRES per Timestep: "<<(float)ngmres/(float)(numstep)<<std::endl; if( dorestart ) std::cout<<"============THIS IS A RESTARTED RUN============"<<std::endl; std::ofstream outfile; outfile.open("jfnk.dat"); outfile <<"Total number of Newton iterations: "<<nnewt_<<std::endl <<"Total number of GMRES iterations: "<<ngmres<<std::endl <<"Total number of Timesteps: "<<numstep<<std::endl <<"Average number of Newton per Timestep: "<<(float)nnewt_/(float)(numstep)<<std::endl <<"Average number of GMRES per Newton: "<<(float)ngmres/(float)nnewt_<<std::endl <<"Average number of GMRES per Timestep: "<<(float)ngmres/(float)(numstep)<<std::endl; if( dorestart ) outfile<<"============THIS IS A RESTARTED RUN============"<<std::endl; outfile.close(); } #if 0 if(!x_space_.is_null()) x_space_=Teuchos::null; if(!x_owned_map_.is_null()) x_owned_map_=Teuchos::null; if(!f_owned_map_.is_null()) f_owned_map_=Teuchos::null; if(!W_graph_.is_null()) W_graph_=Teuchos::null; if(!W_factory_.is_null()) W_factory_=Teuchos::null; if(!x0_.is_null()) x0_=Teuchos::null; if(!P_.is_null()) P_=Teuchos::null; if(!prec_.is_null()) prec_=Teuchos::null; //if(!solver_.is_null()) solver_=Teuchos::null; if(!u_old_.is_null()) u_old_=Teuchos::null; if(!dudt_.is_null()) dudt_=Teuchos::null; #endif delete residualfunc_; delete preconfunc_; delete initfunc_; delete varnames_; if( NULL != dirichletfunc_) delete dirichletfunc_; #if 0 #ifdef PERIODIC_BC #else if( NULL != periodicbc_) delete periodicbc_; #endif //if( NULL != postprocfunc_) delete postprocfunc_; #endif } template<class scalar_type> void ModelEvaluatorTPETRA<scalar_type>::restart(Teuchos::RCP<vector_type> u)//,Teuchos::RCP<vector_type> u_old) { //cn we need to get u_old_ and u_old_old_ //and start_time and start_step and modify time_ auto comm_ = Teuchos::DefaultComm<int>::getComm(); const int mypid = comm_->getRank(); const int numproc = comm_->getSize(); if( 0 == mypid ) std::cout<<std::endl<<"Entering restart: PID "<<mypid<<" NumProcs "<<numproc<<std::endl<<std::endl; if( 1 == numproc ){//cn for now //if( 0 == mypid ){ outfilename = "results.e"; ex_id_ = mesh_->open_exodus(outfilename.c_str(),Mesh::READ); std::cout<<" Opening file for restart; ex_id_ = "<<ex_id_<<" filename = "<<outfilename<<std::endl; } else{ std::string decompPath="decomp/"; std::string mypidstring(getmypidstring(mypid,numproc)); outfilename = decompPath+"results.e."+std::to_string(numproc)+"."+mypidstring; ex_id_ = mesh_->open_exodus(outfilename.c_str(),Mesh::READ); std::cout<<" Opening file for restart; ex_id_ = "<<ex_id_<<" filename = "<<outfilename<<std::endl; //cn we want to check the number of procs listed in the nem file as well int nem_proc = -99; int error = mesh_->read_num_proc_nemesis(ex_id_, &nem_proc); if( 0 > error ) { std::cout<<"Error obtaining restart num procs in file"<<std::endl; exit(0); } if( nem_proc != numproc ){ std::cout<<"Error restart nem_proc = "<<nem_proc<<" does not equal numproc = "<<numproc<<std::endl; exit(0); } } int step = -99; int error = mesh_->read_last_step_exodus(ex_id_,step); if( 0 == mypid ) std::cout<<" Reading restart last step = "<<step<<std::endl; if( 0 > error ) { std::cout<<"Error obtaining restart last step"<<std::endl; exit(0); } double time = -99.99; error = mesh_->read_time_exodus(ex_id_, step, time); if( 0 == mypid ) std::cout<<" Reading restart last time = "<<time<<std::endl; if( 0 > error ) { std::cout<<"Error obtaining restart last time; mypid = "<<mypid<<"; time = "<<time<<std::endl; exit(0); } double min_time = 1.e12; Teuchos::reduceAll<int,double>(*comm_,Teuchos::REDUCE_MIN, 1, &time, &min_time); double max_time = 1.e-12; Teuchos::reduceAll<int,double>(*comm_,Teuchos::REDUCE_MAX, 1, &time, &max_time); //this is probably fixed by setting time = min_time and reading that timestep. //care may need to be taken when overwriting the max_time step, may need a clobber/noclobber //dt_/4 is arbitrary if(fabs(max_time-min_time)>dt_/4.){ if( 0 == mypid ){ std::cout<<" Error reading restart min and max time differ"<<std::endl; std::cout<<" Reading restart min time = "<<min_time<<std::endl; std::cout<<" Reading restart max time = "<<max_time<<std::endl; std::cout<<" Reading restart difference = "<<fabs(max_time-min_time)<<std::endl; } exit(0); } const double dt = paramList.get<double> (TusasdtNameString); const int numSteps = paramList.get<int> (TusasntNameString); if( step > numSteps || time >numSteps*dt ){ if( 0 == mypid ){ std::cout<<" Error reading restart last time = "<<time<<std::endl; std::cout<<" is greater than "<<numSteps*dt<<std::endl<<std::endl<<std::endl; exit(0); } } std::vector<std::vector<double>> inputu(numeqs_,std::vector<double>(num_overlap_nodes_)); for( int k = 0; k < numeqs_; k++ ){ error = mesh_->read_nodal_data_exodus(ex_id_,step,(*varnames_)[k],&inputu[k][0]); if( 0 > error ) { std::cout<<"Error reading u at step "<<step<<std::endl; exit(0); } } mesh_->close_exodus(ex_id_); //cn for now just put current values into old values, //cn ie just start with an initial condition //cn lets not worry about two different time steps for normal simulations Teuchos::RCP< vector_type> u_temp = Teuchos::rcp(new vector_type(x_overlap_map_)); //Teuchos::RCP< Epetra_Vector> u_old_temp = Teuchos::rcp(new Epetra_Vector(*x_overlap_map_)); //on host only now auto u_view = u_temp->getLocalViewHost(Tpetra::Access::ReadWrite); auto u_1d = Kokkos::subview (u_view, Kokkos::ALL (), 0); for( int k = 0; k < numeqs_; k++ ){ //for (int nn=0; nn < num_overlap_nodes_; nn++) { Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultHostExecutionSpace>(0,num_overlap_nodes_),[=](const int& nn){ u_1d[numeqs_*nn+k] = inputu[k][nn]; //(*u_old_temp)[numeqs_*nn+k] = inputu[k][nn]; //std::cout<<u_1d[numeqs_*nn+k]<<" "<<inputu[k][nn]<<" "<<k<<" "<<nn<<std::endl; } ); }//k u->doExport(*u_temp,*exporter_, Tpetra::INSERT); //u_old->doExport(*u_temp,*exporter_, Tpetra::INSERT); step = step - 1; this->start_time = time; //start_step is not quite accurate here if adaptive int ntstep = (int)(time/dt_); this->start_step = ntstep; time_=time; output_step_ = step+1; // u->Print(std::cout); // exit(0); if( 0 == mypid ){ std::cout<<"Restarting at time = "<<time<<" and step = "<<step<<std::endl<<std::endl; std::cout<<"Exiting restart"<<std::endl<<std::endl; } //exit(0); } template<class Scalar> void ModelEvaluatorTPETRA<Scalar>::postprocess() { if(0 == post_proc.size() ) return; int numee = Error_est.size(); //ordering is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz const int dim = 3; std::vector<double> uu(numeqs_); std::vector<double> uuold(numeqs_); std::vector<double> uuoldold(numeqs_); std::vector<double> ug(dim*numee); auto uview = u_new_->get1dView(); auto uoldview = u_old_->get1dView(); auto uoldoldview = u_old_old_->get1dView(); for (int nn=0; nn < num_owned_nodes_; nn++) { //Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultHostExecutionSpace>(0,num_owned_nodes_),[=](const int& nn){ for( int k = 0; k < numeqs_; k++ ){ uu[k] = uview[numeqs_*nn+k]; uuold[k] = uoldview[numeqs_*nn+k]; uuoldold[k] = uoldoldview[numeqs_*nn+k]; } for( int k = 0; k < numee; k++ ){ ug[k*dim] = (*(Error_est[k].gradx_))[nn]; ug[k*dim+1] = (*(Error_est[k].grady_))[nn]; ug[k*dim+2] = (*(Error_est[k].gradz_))[nn]; } boost::ptr_vector<post_process>::iterator itp; for(itp = post_proc.begin();itp != post_proc.end();++itp){ itp->process(nn,&uu[0],&uuold[0],&uuoldold[0],&ug[0],time_,dt_,dtold_); } }//nn //); } template<class Scalar> void ModelEvaluatorTPETRA<Scalar>::temporalpostprocess(boost::ptr_vector<post_process> pp) { if(0 == pp.size() ) return; Teuchos::TimeMonitor ImportTimer(*ts_time_temperr); int numee = Error_est.size(); //ordering is dee0/dx,dee0/dy,dee0/dz,dee1/dx,dee1/dy,dee1/dz const int dim = 3; const int numeqs = numeqs_; //cuda 8 lambdas dont capture private data //lambda does not capture std::vector, we could use Kokkos::vector std::vector<double> uu(numeqs); std::vector<double> uuold(numeqs); std::vector<double> uuoldold(numeqs); std::vector<double> ug(numeqs); //right now for cuda, do this on cpu since the function pointer is buried in another class //and it takes very little percentage of time //another approach would be to use tpetra vectors here //we could openmp this easily, these can be extended to 1d kokkos views for gpu //ArrayRCP works on openmp Teuchos::ArrayRCP<const scalar_type> unewview = u_new_->get1dView(); Teuchos::ArrayRCP<const scalar_type> uoldview = u_old_->get1dView(); Teuchos::ArrayRCP<const scalar_type> predtempview = pred_temp_->get1dView(); for (int nn=0; nn < num_owned_nodes_; nn++) { //Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultHostExecutionSpace>(0,num_owned_nodes_),[=](const int& nn){ for( int k = 0; k < numeqs; k++ ){ uu[k] = unewview[numeqs*nn+k]; uuold[k] = uoldview[numeqs*nn+k]; //uuoldold[k] = (*u_old_old_)[numeqs_*nn+k]; uuoldold[k] = predtempview[numeqs*nn+k]; ug[k] = predtempview[numeqs*nn+k]; } //parallel_for / lambda does not like boost::ptr_vector boost::ptr_vector<post_process>::iterator itp; for(itp = pp.begin();itp != pp.end();++itp){ itp->process(nn,&uu[0],&uuold[0],&uuoldold[0],&ug[0],time_,dt_,dtold_); //std::cout<<nn<<" "<<mesh_->get_local_id((x_owned_map_->GID(nn))/numeqs_)<<" "<<xyz[0]<<std::endl; } }//nn //); } template<class Scalar> void ModelEvaluatorTPETRA<Scalar>::init_P_() { //this could be done with Tpetra::replaceDiagonalCrsMatrix( ::Tpetra::CrsMatrix< SC, LO, GO, NT > & matrix, // const ::Tpetra::Vector< SC, LO, GO, NT > & newDiag // ) P_->setAllToScalar((scalar_type)-1.0); Teuchos::RCP<vector_type > d = Teuchos::rcp(new vector_type(x_owned_map_)); d->putScalar((Scalar)27.); Tpetra::replaceDiagonalCrsMatrix(*P_,*d); //P_->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); P_->fillComplete(); } template<class Scalar> double ModelEvaluatorTPETRA<Scalar>::estimatetimestep() { auto comm_ = Teuchos::DefaultComm<int>::getComm(); double dtpred = 0.; //std::cout<<std::setprecision(std::numeric_limits<double>::digits10 + 1); Teuchos::ParameterList *atsList; atsList = &paramList.sublist (TusasatslistNameString, false ); const double atol = atsList->get<double>(TusasatsatolNameString); const double rtol = atsList->get<double>(TusasatsrtolNameString); const double sf = atsList->get<double>(TusasatssfNameString); const double rmax = atsList->get<double>(TusasatsrmaxNameString); const double rmin = atsList->get<double>(TusasatsrminNameString); const double eps = atsList->get<double>(TusasatsepsNameString); const double dtmax = atsList->get<double>(TusasatsmaxdtNameString); temporalpostprocess(temporal_est); boost::ptr_vector<post_process>::iterator itp; for(itp = temporal_est.begin();itp != temporal_est.end();++itp){ itp->scalar_reduction(); } //norm for rtol temporalpostprocess(temporal_norm); for(itp = temporal_norm.begin();itp != temporal_norm.end();++itp){ itp->scalar_reduction(); } temporalpostprocess(temporal_dyn); for(itp = temporal_dyn.begin();itp != temporal_dyn.end();++itp){ itp->scalar_reduction(); } std::vector<double> maxdt(numeqs_); std::vector<double> mindt(numeqs_); std::vector<double> newdt(numeqs_); std::vector<double> error(numeqs_,1.); std::vector<double> norm(numeqs_,0.); std::vector<double> dyn(numeqs_,0.); if( 0 == comm_->getRank()){ std::cout<<std::endl<<" Estimating timestep size:"<<std::endl; std::cout<<" using "<<atsList->get<std::string> (TusasatstypeNameString) <<" and theta = "<<t_theta_<<std::endl; std::cout<<" with atol = "<<atol <<"; rtol = "<<rtol <<"; sf = "<<sf<<"; rmax = "<<rmax<<"; rmin = "<<rmin<<"; current dt = "<<dt_<<"; dtmax = "<<dtmax<<std::endl; } double err_coef = 1.; if(atsList->get<std::string> (TusasatstypeNameString) == "second derivative") err_coef = 1.; if(atsList->get<std::string> (TusasatstypeNameString) == "predictor corrector") if(t_theta_ > .51){ err_coef = .5; } else{ err_coef = 1./3./(1.+dtold_/dt_); } for( int k = 0; k < numeqs_; k++ ){ error[k] = err_coef*(temporal_est[k].get_scalar_val()); norm[k] = temporal_norm[k].get_scalar_val(); dyn[k] = 1./temporal_dyn[k].get_scalar_val(); const double abserr = std::max(error[k],eps); const double tol = atol + rtol*norm[k]; double rr; if(t_theta_ > .51){ rr = std::sqrt(tol/abserr); } else{ rr = std::cbrt(tol/abserr); //rr = std::pow(tol/abserr, 1./3.); } const double h1 = sf*dt_*rr; maxdt[k] = std::max(h1,dt_*rmin); mindt[k] = std::min(h1,dt_*rmax); if( 0 == Comm->MyPID()){ std::cout<<std::endl<<" Variable: "<<(*varnames_)[k]<<std::endl<<std::scientific; //std::cout<<" tol = "<<tol<<std::endl; std::cout<<" error = "<<error[k]<<std::endl; std::cout<<" max dt = "<<dtmax<<std::endl; std::cout<<" max(error,eps) = "<<abserr<<std::endl; std::cout<<" (tol/err)^1/p = "<<rr<<std::endl; std::cout<<" h = sf*dt*(tol/err)^1/p = "<<h1<<std::endl; std::cout<<" max(h,dt*rmin) = "<<maxdt[k]<<std::endl; std::cout<<" min(h,dt*rmax) = "<<mindt[k]<<std::endl; std::cout<<" dynamic dt = "<<dyn[k]<<std::endl; std::cout<<std::endl; } if( h1 < dt_ ){ newdt[k] = maxdt[k]; }else{ newdt[k] = mindt[k]; } }//k dtpred = *min_element(newdt.begin(), newdt.end()); if( 0 == comm_->getRank()){ std::cout<<std::endl<<" Estimated timestep size : "<<dtpred<<std::endl; } dtpred = std::min(dtpred,dtmax); if( 0 == comm_->getRank()){ std::cout<<std::endl<<" min(dtpred,dtmax) : "<<dtpred<<std::endl<<std::endl<<std::defaultfloat; } return dtpred; } template<class Scalar> void ModelEvaluatorTPETRA<Scalar>::predictor() { //right now theta2=0 corresponds to FE, BE and TR //theta2=1 corresponds to AB predictor_step = true; auto comm_ = Teuchos::DefaultComm<int>::getComm(); if( 0 == comm_->getRank()){ std::cout<<std::endl<<std::endl<<std::endl<<" Predictor step started"<<std::endl; } //we might turn off the forcing term temporaily here const double t_theta_temp = t_theta_; t_theta2_ = 0.; if(t_theta_ > 0.45 && t_theta_ <.55) t_theta2_ = 1.;//ab predictor tr corrector //fe predictor be corrector t_theta_ = 0.; Teuchos::RCP< ::Thyra::VectorBase< double > > guess = Thyra::createVector(u_old_,x_space_); NOX::Thyra::Vector thyraguess(*guess); predictor_->reset(thyraguess); { Teuchos::TimeMonitor PredTimer(*ts_time_predsolve); NOX::StatusTest::StatusType solvStatus = predictor_->solve(); } const Thyra::VectorBase<double> * sol = &(dynamic_cast<const NOX::Thyra::Vector&>(predictor_->getSolutionGroup().getX() ).getThyraVector() ); Thyra::ConstDetachedSpmdVectorView<double> x_vec(sol->col(0)); Teuchos::ArrayRCP<const scalar_type> vals = x_vec.values(); Teuchos::ArrayRCP<scalar_type> predtempview = pred_temp_->get1dViewNonConst(); const int localLength = num_owned_nodes_; //for (int nn=0; nn < localLength; nn++) {//cn figure out a better way here... Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultHostExecutionSpace>(0,localLength),[=](const int& nn){ for( int k = 0; k < numeqs_; k++ ){ //predtempview[numeqs_*nn+k]=x_vec[numeqs_*nn+k]; predtempview[numeqs_*nn+k]=vals[numeqs_*nn+k]; } } );//parallel_for t_theta_ = t_theta_temp; t_theta2_ = 0.; //comm_->barrier(); if( 0 == comm_->getRank()){ std::cout<<std::endl<<" Predictor step ended"<<std::endl<<std::endl<<std::endl; } predictor_step = false; //exit(0); } template<class Scalar> void ModelEvaluatorTPETRA<Scalar>::initialsolve() { auto comm_ = Teuchos::DefaultComm<int>::getComm(); //right now, for TR it doesn't really matter in turns of performance if we set theta to 1 //here or leave it at .5 const double t_theta_temp = t_theta_; t_theta_ = 1.; t_theta2_ = 0.; if( 0 == comm_->getRank()) std::cout<<std::endl<<"Performing initial NOX solve"<<std::endl<<std::endl; Teuchos::RCP< ::Thyra::VectorBase< double > > guess = Thyra::createVector(u_old_,x_space_); NOX::Thyra::Vector thyraguess(*guess);//by sending the dereferenced pointer, we instigate a copy rather than a view solver_->reset(thyraguess); Teuchos::TimeMonitor NSolveTimer(*ts_time_nsolve); NOX::StatusTest::StatusType solvStatus = solver_->solve(); if( !(NOX::StatusTest::Converged == solvStatus)) { std::cout<<" NOX solver failed to converge. Status = "<<solvStatus<<std::endl<<std::endl; exit(0); } if( 0 == comm_->getRank()) std::cout<<std::endl<<"Initial NOX solve completed"<<std::endl<<std::endl; const Thyra::VectorBase<double> * sol = &(dynamic_cast<const NOX::Thyra::Vector&>( solver_->getSolutionGroup().getX() ).getThyraVector()); Thyra::ConstDetachedSpmdVectorView<double> x_vec(sol->col(0)); Teuchos::ArrayRCP<const scalar_type> vals = x_vec.values(); //now, //dudt(t=0) = (x_vec-u_old_)/dt_ // //so, also //dudt(t=0) = (u_old_ - u_old_old_)/dt_ //u_old_old_ = u_old_ - dt_*dudt(t=0) // = 2*u_old_ - x_vec { Teuchos::ArrayRCP<const scalar_type> uoldview = u_old_->get1dView(); Teuchos::ArrayRCP<scalar_type> uoldoldview = u_old_old_->get1dViewNonConst(); //for (int nn=0; nn < num_owned_nodes_; nn++) {//cn figure out a better way here... Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultHostExecutionSpace>(0,num_owned_nodes_),[=](const int& nn){ for( int k = 0; k < numeqs_; k++ ){ uoldoldview[numeqs_*nn+k] = 2.*uoldview[numeqs_*nn+k] - vals[numeqs_*nn+k]; } } ); } t_theta_ = t_theta_temp; } template<class Scalar> void ModelEvaluatorTPETRA<Scalar>::setadaptivetimestep() { auto comm_ = Teuchos::DefaultComm<int>::getComm(); bool dorestart = paramList.get<bool> (TusasrestartNameString); post_process::SCALAR_OP norm = post_process::NORMRMS; //cn this is not going to work with multiple k //what do we do with temporal_est[0].pos.... //is index_ correct here?? Teuchos::ParameterList *atsList; atsList = &paramList.sublist (TusasatslistNameString, false ); for( int k = 0; k < numeqs_; k++ ){ temporal_est.push_back(new post_process(Comm, mesh_, k, norm, dorestart, k, "temperror", 16)); //be with an error estimate based on second derivative if(atsList->get<std::string> (TusasatstypeNameString) == "second derivative") temporal_est[k].postprocfunc_ = &timeadapt::d2udt2_; //be with error estimate based on fe predictor: fe-be if(atsList->get<std::string> (TusasatstypeNameString) == "predictor corrector") temporal_est[k].postprocfunc_ = &timeadapt::predictor_fe_; //we will have tr with adams-bashforth predictor: ab-tr //would require a small first step to get ab going //or get u_n-1 via initial solve above with maybe a better update //see gresho for a wierd ab way for this--can use regular ab //and possibly tr with an explicit midpoint rule (huen) predictor: huen-tr //(we could use initial solve above //with better update to get //(up_n+1 - u_n-1)/(2 dt) = f(t_n) //with error = - (u_n+1 - up_n+1)/5 //see https://www.cs.princeton.edu/courses/archive/fall11/cos323/notes/cos323_f11_lecture17_ode2.pdf //we would utilize t_theta2_ similarly temporal_norm.push_back(new post_process(Comm, mesh_, k, norm, dorestart, k, "tempnorm", 16)); temporal_norm[k].postprocfunc_ = &timeadapt::normu_; temporal_dyn.push_back(new post_process(Comm, mesh_, k, post_process::NORMINF, dorestart, k, "tempdyn", 16)); temporal_dyn[k].postprocfunc_ = &timeadapt::dynamic_; } if( 0 == comm_->getRank()){ std::cout<<"setadaptivetimestep(): temporal_est.size() = "<<temporal_est.size()<<std::endl <<" temporal_norm.size() = "<<temporal_norm.size()<<std::endl; }//if } template<class Scalar> void ModelEvaluatorTPETRA<Scalar>::update_left_scaling() { //this is currently row scaling by inverse of solution at previous timestep const double small = 1e-8; Teuchos::RCP<vector_type> temp = Teuchos::rcp(new vector_type(*u_old_)); auto temp_view = temp->getLocalViewHost(Tpetra::Access::ReadWrite); auto temp_1d = Kokkos::subview (temp_view, Kokkos::ALL (), 0); const size_t localLength = num_owned_nodes_; //Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultHostExecutionSpace>(0,localLength),[=](const int& nn){ for(int nn = 0; nn < localLength; nn++){ for( int k = 0; k < numeqs_; k++ ){ if(abs(temp_1d[numeqs_*nn+k]) < small ) temp_1d[numeqs_*nn+k] = 1.; //std::cout<<numeqs_*nn+k<<" "<<temp_1d[numeqs_*nn+k]<<std::endl; } } Teuchos::RCP< ::Thyra::VectorBase< double > > r = Thyra::createVector(temp,x_space_); //Thyra::put_scalar(1.0,scaling_.ptr()); Thyra::reciprocal(*r,scaling_.ptr()); //scaling_->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); } template<class Scalar> void ModelEvaluatorTPETRA<Scalar>::print_norms() { auto comm_ = Teuchos::DefaultComm<int>::getComm(); int mypid = comm_->getRank(); const Thyra::VectorBase<double> * sol = &(dynamic_cast<const NOX::Thyra::Vector&>( solver_->getSolutionGroup().getF() ).getThyraVector() ); Thyra::ConstDetachedSpmdVectorView<double> x_vec(sol->col(0)); Teuchos::ArrayRCP<const scalar_type> vals = x_vec.values();//this probably needs to be a view std::vector<double> norms(numeqs_); Teuchos::RCP<vector_type > u = Teuchos::rcp(new vector_type(node_owned_map_)); const size_t localLength = node_owned_map_->getNodeNumElements(); //auto un_view = u->getLocalViewHost(Tpetra::Access::ReadWrite); auto un_view = u->getLocalView<Kokkos::DefaultExecutionSpace>(Tpetra::Access::ReadWrite); auto un_1d = Kokkos::subview (un_view, Kokkos::ALL (), 0); for( int k = 0; k < numeqs_; k++ ){ //for(int nn = 0; nn< localLength; nn++){ Kokkos::parallel_for(Kokkos::RangePolicy<Kokkos::DefaultExecutionSpace>(0,localLength),[=](const int& nn){ un_1d[nn] = vals[numeqs_*nn+k]; } );//parallel_for //}//k norms[k] = u->norm2(); } const double norm = solver_->getSolutionGroup().getNormF(); if( 0 == mypid ) std::cout<<" ||F|| = "<<std::scientific<<norm<<std::endl; for( int k = 0; k < numeqs_; k++ ){ if( 0 == mypid ) std::cout<<" ||F_"<<k<<"|| = "<<norms[k]<<std::endl<<std::defaultfloat; } } #endif
#pragma once #include <gflags/gflags.h> #include <Eigen/Dense> #include <algorithm> #include <random> #include <fstream> namespace ethdata { typedef struct Vertex_ { EIGEN_MAKE_ALIGNED_OPERATOR_NEW Vertex_(long int index_, double timestamp_, Eigen::Matrix4d pose_) : index(index_), timestamp(timestamp_), pose(pose_) { } long int index; double timestamp; Eigen::Matrix4d pose; } Vertex; class GroundTruth { public: GroundTruth(std::string path_to_csv) : number_of_elements_in_a_column_(18) { std::fstream filestream(path_to_csv); if (!filestream.is_open()) return; std::string buffer; while (getline(filestream, buffer)) { std::vector<std::string> record; std::istringstream streambuffer(buffer); std::string token; while (getline(streambuffer, token, ',')) { record.push_back(token); } if (record.size() == number_of_elements_in_a_column_) { try { std::uniform_real_distribution<double> unif(-0.5, 0.5); std::default_random_engine re; double sx = unif(re); double sy = unif(re); double sz = unif(re); Eigen::Matrix4d pose; pose << std::stod(record[2]), std::stod(record[3]), std::stod(record[4]), std::stod(record[5]) + sx, std::stod(record[6]), std::stod(record[7]), std::stod(record[8]), std::stod(record[9]) + sy, std::stod(record[10]), std::stod(record[11]), std::stod(record[12]), std::stod(record[13]) + sz, std::stod(record[14]), std::stod(record[15]), std::stod(record[16]), std::stod(record[17]); std::shared_ptr<Vertex> vertex = std::make_shared<Vertex>( std::stol(record[0]), std::stod(record[1]), pose); data_.push_back(vertex); } catch (const std::exception &e) { // std::cerr << e.what() << std::endl; // std::cerr << "skip this line" << std::endl; } } } } ~GroundTruth() {} std::vector<std::shared_ptr<Vertex>> data() { return data_; } private: size_t number_of_elements_in_a_column_; std::vector<std::shared_ptr<Vertex>> data_; }; class PointCloudCSV { public: PointCloudCSV(std::string path_to_csv) : number_of_elements_in_a_column_(7) { cloud_ = boost::make_shared<pcl::PointCloud<pcl::PointXYZ>>(); std::fstream filestream(path_to_csv); if (!filestream.is_open()) return; std::string buffer; while (getline(filestream, buffer)) { std::vector<std::string> record; std::istringstream streambuffer(buffer); std::string token; while (getline(streambuffer, token, ',')) { record.push_back(token); } if (record.size() == number_of_elements_in_a_column_) { try { pcl::PointXYZ point; point.x = std::stod(record[1]); point.y = std::stod(record[2]); point.z = std::stod(record[3]); cloud_->points.emplace_back(point); } catch (const std::exception &e) { // std::cerr << e.what() << std::endl; // std::cerr << "skip this line" << std::endl; } } } cloud_->width = cloud_->points.size(); cloud_->height = 0; cloud_->is_dense = false; } ~PointCloudCSV() {} pcl::PointCloud<pcl::PointXYZ>::Ptr cloud() { return cloud_; } private: size_t number_of_elements_in_a_column_; pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_; }; }
#ifndef __OCR_H__ #define __OCR_H__ #include "log.h" #include <vector> #include "net.h" #include "benchmark.h" #include <algorithm> #include <math.h> #include "opencv2/opencv.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "RRLib.h" #include "polygon.h" #include <fstream> #include <string> #include <iostream> #include "type.h" #include "ruler.h" using namespace std; using namespace ncnn; //class Point { //public: // Point(int x, int y) { // this->x = x; // this->y = y; // } // // int x; // int y; //}; struct Bbox { int x1; int y1; int x2; int y2; int x3; int y3; int x4; int y4; }; class OCR { public: OCR(); void detect(cv::Mat im_bgr, int long_size); private: ncnn::Net psenet, crnn_net, crnn_vertical_net, angle_net; ncnn::Mat img; int num_thread = 4; int shufflenetv2_target_w = 196; int shufflenetv2_target_h = 48; int crnn_h = 32; const float mean_vals_pse_angle[3] = {0.485 * 255, 0.456 * 255, 0.406 * 255}; const float norm_vals_pse_angle[3] = {1.0 / 0.229 / 255.0, 1.0 / 0.224 / 255.0, 1.0 / 0.225 / 255.0}; const float mean_vals_crnn[1] = {127.5}; const float norm_vals_crnn[1] = {1.0 / 127.5}; std::vector<std::string> alphabetChinese; }; cv::Mat resize_img(cv::Mat src, const int long_size); #endif
#include "stdafx.h" #include "TypeInQuestionView.h" #include "TypeInQuestionState.h" #include "TypeInQuestionViewController.h" #include "TypeInQuestion.h" using namespace qp; using namespace std; set<string> answers = { "First answer", "Second answer" }; struct TypeInQuestionViewControllerFixture { TypeInQuestionViewControllerFixture() :state(make_shared<CTypeInQuestionState>(make_shared<CTypeInQuestion>("Question description", answers, 10))) { } CTypeInQuestionStatePtr state; ostringstream ostrm; }; BOOST_FIXTURE_TEST_SUITE(TypeInQuestionViewTests, TypeInQuestionViewControllerFixture) BOOST_AUTO_TEST_CASE(ControllerCallsSetUserAnswer) { istringstream istrm("answer\n"); CTypeInQuestionViewPtr view = make_shared<CTypeInQuestionView>(state, ostrm, istrm); CTypeInQuestionViewController qvc(state, view); BOOST_CHECK(state->GetUserAnswer().empty()); BOOST_REQUIRE(view->HandleUserInput()); BOOST_CHECK_EQUAL(state->GetUserAnswer(), "answer"); BOOST_CHECK_EQUAL(ostrm.str(),"Enter an answer or type 'submit' or 'skip': " "Question description\n" "Your answer: 'answer'\n"); } BOOST_AUTO_TEST_CASE(SubmitAndReviewIncorrectAnswer) { istringstream istrm("answer\nsubmit\n"); CTypeInQuestionViewPtr view = make_shared<CTypeInQuestionView>(state, ostrm, istrm); CTypeInQuestionViewController qvc(state, view); BOOST_REQUIRE(view->HandleUserInput()); BOOST_REQUIRE(view->HandleUserInput()); BOOST_CHECK_EQUAL(ostrm.str(), "Enter an answer or type 'submit' or 'skip': " "Question description\n" "Your answer: 'answer'\n" "Enter an answer or type 'submit' or 'skip': " "Question description\n" "Your answer: 'answer'\n" "Right answer(s): 'First answer'\n" "'Second answer'\n" "Answer is not correct.\n"); } BOOST_AUTO_TEST_CASE(SubmitAndReviewCorrectAnswer) { istringstream istrm("First answer\nsubmit\n"); CTypeInQuestionViewPtr view = make_shared<CTypeInQuestionView>(state, ostrm, istrm); CTypeInQuestionViewController qvc(state, view); BOOST_REQUIRE(view->HandleUserInput()); BOOST_REQUIRE(view->HandleUserInput()); BOOST_CHECK_EQUAL(ostrm.str(), "Enter an answer or type 'submit' or 'skip': " "Question description\n" "Your answer: 'First answer'\n" "Enter an answer or type 'submit' or 'skip': " "Question description\n" "Your answer: 'First answer'\n" "Answer is correct. Score: 10\n"); } BOOST_AUTO_TEST_SUITE_END()
// Copyright (c) 2015 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <pika/init.hpp> #include <pika/modules/iterator_support.hpp> #include <pika/modules/timing.hpp> #include <pika/testing/performance.hpp> #include <chrono> #include <cstddef> #include <cstdint> #include <iostream> #include <iterator> #include <numeric> #include <tuple> #include <type_traits> #include <utility> #include <vector> /////////////////////////////////////////////////////////////////////////////// int test_count = 100; int partition_size = 10000; /////////////////////////////////////////////////////////////////////////////// namespace pika::experimental::detail { template <typename Iterator> PIKA_FORCEINLINE Iterator previous(Iterator it, std::false_type) { return --it; } template <typename Iterator> PIKA_FORCEINLINE Iterator previous(Iterator const& it, std::true_type) { return it - 1; } template <typename Iterator> PIKA_FORCEINLINE Iterator previous(Iterator const& it) { return previous(it, pika::traits::is_random_access_iterator<Iterator>()); } template <typename Iterator> PIKA_FORCEINLINE Iterator next(Iterator it, std::false_type) { return ++it; } template <typename Iterator> PIKA_FORCEINLINE Iterator next(Iterator const& it, std::true_type) { return it + 1; } template <typename Iterator> PIKA_FORCEINLINE Iterator next(Iterator const& it) { return next(it, pika::traits::is_random_access_iterator<Iterator>()); } } // namespace pika::experimental::detail /////////////////////////////////////////////////////////////////////////////// // Version of stencil3_iterator which handles boundary elements internally namespace pika::experimental { /////////////////////////////////////////////////////////////////////////// template <typename Iterator, typename IterBegin = Iterator, typename IterValueBegin = Iterator, typename IterEnd = IterBegin, typename IterValueEnd = IterValueBegin> class stencil3_iterator_full; namespace detail { /////////////////////////////////////////////////////////////////////// template <typename IteratorBase, typename IteratorValue> struct previous_transformer { previous_transformer() {} // at position 'begin' it will dereference 'value', otherwise 'it-1' previous_transformer(IteratorBase const& begin, IteratorValue const& value) : begin_(begin) , value_(value) { } template <typename Iterator> typename std::iterator_traits<Iterator>::reference operator()(Iterator const& it) const { if (it == begin_) return *value_; return *detail::previous(it); } private: IteratorBase begin_; IteratorValue value_; }; template <typename IteratorBase, typename IteratorValue> inline previous_transformer<IteratorBase, IteratorValue> make_previous_transformer(IteratorBase const& base, IteratorValue const& value) { return previous_transformer<IteratorBase, IteratorValue>(base, value); } /////////////////////////////////////////////////////////////////////// template <typename IteratorBase, typename IteratorValue> struct next_transformer { next_transformer() {} // at position 'end' it will dereference 'value', otherwise 'it+1' next_transformer(IteratorBase const& end, IteratorValue const& value) : end_(end) , value_(value) { } template <typename Iterator> typename std::iterator_traits<Iterator>::reference operator()(Iterator const& it) const { if (it == end_) return *value_; return *detail::next(it); } private: IteratorBase end_; IteratorValue value_; }; template <typename IteratorBase, typename IteratorValue> inline next_transformer<IteratorBase, IteratorValue> make_next_transformer(IteratorBase const& base, IteratorValue const& value) { return next_transformer<IteratorBase, IteratorValue>(base, value); } /////////////////////////////////////////////////////////////////////// template <typename Iterator, typename IterBegin, typename IterValueBegin, typename IterEnd, typename IterValueEnd> struct stencil3_iterator_base { using left_transformer = previous_transformer<IterBegin, IterValueBegin>; using right_transformer = next_transformer<IterEnd, IterValueEnd>; using left_iterator = util::transform_iterator<Iterator, left_transformer>; using right_iterator = util::transform_iterator<Iterator, right_transformer>; using type = util::detail::zip_iterator_base< std::tuple<left_iterator, Iterator, right_iterator>, stencil3_iterator_full<Iterator, IterBegin, IterValueBegin, IterEnd, IterValueEnd>>; static type create(Iterator const& it, IterBegin const& begin, IterValueBegin const& begin_val, IterEnd const& end, IterValueEnd const& end_val) { auto prev = make_previous_transformer(begin, begin_val); auto next = make_next_transformer(end, end_val); return type(std::make_tuple(util::make_transform_iterator(it, prev), it, util::make_transform_iterator(it, next))); } static type create(Iterator const& it) { return type(std::make_tuple(util::make_transform_iterator(it, left_transformer()), it, util::make_transform_iterator(it, right_transformer()))); } }; } // namespace detail /////////////////////////////////////////////////////////////////////////// template <typename Iterator, typename IterBegin, typename IterValueBegin, typename IterEnd, typename IterValueEnd> class stencil3_iterator_full : public detail::stencil3_iterator_base<Iterator, IterBegin, IterValueBegin, IterEnd, IterValueEnd>::type { private: using base_maker = detail::stencil3_iterator_base<Iterator, IterBegin, IterValueBegin, IterEnd, IterValueEnd>; using base_type = typename base_maker::type; public: stencil3_iterator_full() {} stencil3_iterator_full(Iterator const& it, IterBegin const& begin, IterValueBegin const& begin_val, IterEnd const& end, IterValueEnd const& end_val) : base_type(base_maker::create(it, begin, begin_val, end, end_val)) { } explicit stencil3_iterator_full(Iterator const& it) : base_type(base_maker::create(it)) { } private: friend class pika::util::iterator_core_access; bool equal(stencil3_iterator_full const& other) const { return std::get<1>(this->get_iterator_tuple()) == std::get<1>(other.get_iterator_tuple()); } }; template <typename Iterator, typename IterBegin, typename IterValueBegin, typename IterEnd, typename IterValueEnd> inline stencil3_iterator_full<Iterator, IterBegin, IterValueBegin, IterEnd, IterValueEnd> make_stencil3_full_iterator(Iterator const& it, IterBegin const& begin, IterValueBegin const& begin_val, IterEnd const& end, IterValueEnd const& end_val) { using result_type = stencil3_iterator_full<Iterator, IterBegin, IterValueBegin, IterEnd, IterValueEnd>; return result_type(it, begin, begin_val, end, end_val); } template <typename StencilIterator, typename Iterator> inline StencilIterator make_stencil3_full_iterator(Iterator const& it) { return StencilIterator(it); } template <typename Iterator, typename IterValue> inline std::pair<stencil3_iterator_full<Iterator, Iterator, IterValue, Iterator, IterValue>, stencil3_iterator_full<Iterator, Iterator, IterValue, Iterator, IterValue>> make_stencil3_full_range(Iterator const& begin, Iterator const& end, IterValue const& begin_val, IterValue const& end_val) { auto b = make_stencil3_full_iterator(begin, begin, begin_val, detail::previous(end), end_val); return std::make_pair(b, make_stencil3_full_iterator<decltype(b)>(end)); } } // namespace pika::experimental std::chrono::duration<double> bench_stencil3_iterator_full() { std::vector<int> values(partition_size); std::iota(std::begin(values), std::end(values), 0); auto start = std::chrono::high_resolution_clock::now(); auto r = pika::experimental::make_stencil3_full_range( values.begin(), values.end(), &values.back(), &values.front()); using reference = std::iterator_traits<decltype(r.first)>::reference; int result = 0; std::for_each(r.first, r.second, [&result](reference val) { using std::get; result += get<0>(val) + get<1>(val) + get<2>(val); }); return std::chrono::high_resolution_clock::now() - start; } /////////////////////////////////////////////////////////////////////////////// // compare with unchecked stencil3_iterator (version 1) namespace pika::experimental { template <typename Iterator> class stencil3_iterator_v1 : public util::detail::zip_iterator_base<std::tuple<Iterator, Iterator, Iterator>, stencil3_iterator_v1<Iterator>> { private: using base_type = util::detail::zip_iterator_base<std::tuple<Iterator, Iterator, Iterator>, stencil3_iterator_v1<Iterator>>; public: stencil3_iterator_v1() {} explicit stencil3_iterator_v1(Iterator const& it) : base_type(std::make_tuple(detail::previous(it), it, detail::next(it))) { } private: friend class pika::util::iterator_core_access; bool equal(stencil3_iterator_v1 const& other) const { return std::get<1>(this->get_iterator_tuple()) == std::get<1>(other.get_iterator_tuple()); } }; template <typename Iterator> inline stencil3_iterator_v1<Iterator> make_stencil3_iterator_v1(Iterator const& it) { return stencil3_iterator_v1<Iterator>(it); } template <typename Iterator> inline std::pair<stencil3_iterator_v1<Iterator>, stencil3_iterator_v1<Iterator>> make_stencil3_range_v1(Iterator const& begin, Iterator const& end) { return std::make_pair(make_stencil3_iterator_v1(begin), make_stencil3_iterator_v1(end)); } } // namespace pika::experimental std::chrono::duration<double> bench_stencil3_iterator_v1() { std::vector<int> values(partition_size); std::iota(std::begin(values), std::end(values), 0); auto start = std::chrono::high_resolution_clock::now(); auto r = pika::experimental::make_stencil3_range_v1(values.begin() + 1, values.end() - 1); using reference = std::iterator_traits<decltype(r.first)>::reference; // handle boundary elements explicitly int result = values.back() + values.front() + values[1]; std::for_each(r.first, r.second, [&result](reference val) { using std::get; result += get<0>(val) + get<1>(val) + get<2>(val); }); result += values[partition_size - 2] + values.back() + values.front(); PIKA_UNUSED(result); return std::chrono::high_resolution_clock::now() - start; } /////////////////////////////////////////////////////////////////////////////// // compare with unchecked stencil3_iterator (version 2) namespace pika::experimental { namespace detail { struct stencil_transformer_v2 { template <typename Iterator> struct result { using element_type = typename std::iterator_traits<Iterator>::reference; using type = std::tuple<element_type, element_type, element_type>; }; // it will dereference tuple(it-1, it, it+1) template <typename Iterator> typename result<Iterator>::type operator()(Iterator const& it) const { using type = typename result<Iterator>::type; return type(*detail::previous(it), *it, *detail::next(it)); } }; } // namespace detail /////////////////////////////////////////////////////////////////////////// template <typename Iterator, typename Transformer = detail::stencil_transformer_v2> class stencil3_iterator_v2 : public pika::util::transform_iterator<Iterator, Transformer> { private: using base_type = pika::util::transform_iterator<Iterator, Transformer>; public: stencil3_iterator_v2() {} explicit stencil3_iterator_v2(Iterator const& it) : base_type(it, Transformer()) { } stencil3_iterator_v2(Iterator const& it, Transformer const& t) : base_type(it, t) { } }; template <typename Iterator, typename Transformer> inline stencil3_iterator_v2<Iterator, Transformer> make_stencil3_iterator_v2(Iterator const& it, Transformer const& t) { return stencil3_iterator_v2<Iterator, Transformer>(it, t); } template <typename Iterator, typename Transformer> inline std::pair<stencil3_iterator_v2<Iterator, Transformer>, stencil3_iterator_v2<Iterator, Transformer>> make_stencil3_range_v2(Iterator const& begin, Iterator const& end, Transformer const& t) { return std::make_pair( make_stencil3_iterator_v2(begin, t), make_stencil3_iterator_v2(end, t)); } /////////////////////////////////////////////////////////////////////////// template <typename Iterator> inline stencil3_iterator_v2<Iterator> make_stencil3_iterator_v2(Iterator const& it) { return stencil3_iterator_v2<Iterator>(it); } template <typename Iterator> inline std::pair<stencil3_iterator_v2<Iterator>, stencil3_iterator_v2<Iterator>> make_stencil3_range_v2(Iterator const& begin, Iterator const& end) { return std::make_pair(make_stencil3_iterator_v2(begin), make_stencil3_iterator_v2(end)); } } // namespace pika::experimental std::chrono::duration<double> bench_stencil3_iterator_v2() { std::vector<int> values(partition_size); std::iota(std::begin(values), std::end(values), 0); auto start = std::chrono::high_resolution_clock::now(); auto r = pika::experimental::make_stencil3_range_v2(values.begin() + 1, values.end() - 1); using reference = std::iterator_traits<decltype(r.first)>::reference; // handle boundary elements explicitly int result = values.back() + values.front() + values[1]; std::for_each(r.first, r.second, [&result](reference val) { using std::get; result += get<0>(val) + get<1>(val) + get<2>(val); }); result += values[partition_size - 2] + values.back() + values.front(); PIKA_UNUSED(result); return std::chrono::high_resolution_clock::now() - start; } /////////////////////////////////////////////////////////////////////////////// std::chrono::duration<double> bench_stencil3_iterator_explicit() { std::vector<int> values(partition_size); std::iota(std::begin(values), std::end(values), 0); auto start = std::chrono::high_resolution_clock::now(); // handle all elements explicitly int result = values.back() + values.front() + values[1]; auto range = pika::detail::irange(1, partition_size - 1); std::for_each(std::begin(range), std::end(range), [&result, &values](std::size_t i) { result += values[i - 1] + values[i] + values[i + 1]; }); result += values[partition_size - 2] + values.back() + values.front(); PIKA_UNUSED(result); return std::chrono::high_resolution_clock::now() - start; } /////////////////////////////////////////////////////////////////////////////// int pika_main(pika::program_options::variables_map& vm) { // bool csvoutput = vm.count("csv_output") != 0; test_count = vm["test_count"].as<int>(); partition_size = vm["partition_size"].as<int>(); // verify that input is within domain of program if (test_count <= 0) { std::cout << "test_count cannot be zero or negative..." << std::endl; } else if (partition_size < 3) { std::cout << "partition_size cannot be smaller than 3..." << std::endl; } else { // first run full stencil3 tests { std::chrono::duration<double> t(0); for (int i = 0; i != test_count; ++i) t += bench_stencil3_iterator_full(); std::cout << "full: " << t.count() / test_count << std::endl; pika::util::print_cdash_timing("Stencil3Full", t.count() / test_count); } // now run explicit (no-check) stencil3 tests { std::chrono::duration<double> t(0); for (int i = 0; i != test_count; ++i) t += bench_stencil3_iterator_v1(); std::cout << "nocheck(v1): " << t.count() / test_count << std::endl; pika::util::print_cdash_timing("Stencil3NocheckV1", t.count() / test_count); } { std::chrono::duration<double> t(0); for (int i = 0; i != test_count; ++i) t += bench_stencil3_iterator_v2(); std::cout << "nocheck(v2): " << t.count() / test_count << std::endl; pika::util::print_cdash_timing("Stencil3NocheckV2", t.count() / test_count); } // now run explicit tests { std::chrono::duration<double> t(0); for (int i = 0; i != test_count; ++i) t += bench_stencil3_iterator_explicit(); std::cout << "explicit: " << t.count() / test_count << std::endl; pika::util::print_cdash_timing("Stencil3Explicit", t.count() / test_count); } } return pika::finalize(); } /////////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { // initialize program pika::program_options::options_description cmdline( "usage: " PIKA_APPLICATION_STRING " [options]"); // clang-format off cmdline.add_options() ("test_count", pika::program_options::value<int>()->default_value(100), "number of tests to be averaged (default: 100)") ("partition_size", pika::program_options::value<int>()->default_value(10000), "number of elements to iterate over (default: 10000)") ; // clang-format on pika::init_params init_args; init_args.desc_cmdline = cmdline; return pika::init(pika_main, argc, argv, init_args); }
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> #include <assert.h> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; char s[100111], WAS[333][100111], wasall[256]; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); // gets(s); /* char ch; int l = 0; while ((ch = getchar())) { if (feof(stdin)) break; if (ch >= '0' && ch <= '9') s[l++] = ch; } */ gets(s); int l = strlen(s); assert(l >= 1 && l <= 100000); WAS[0][0] = 1; int ans = 0; while (true) { char *was = WAS[ans], *wass = WAS[ans + 1]; if (was[l - 1]) break; for (int i = 0; i < l; ++i) if (was[i]) wasall[s[i]] = 1; for (int i = 0; i < l; ++i) if (was[i] || wasall[s[i]] || (i > 0 && was[i - 1]) || (i + 1 < l && was[i + 1])) wass[i] = 1; ++ans; } printf("%d\n", ans); return 0; }
#ifndef SPLAYTREE_H_ #define SPLAYTREE_H_ #include <iostream> template<typename T> class splaytree { struct node { T key; node* l = NULL; node* r = NULL; node() {} node(T key) :key(key) {} node(T key, node *l, node *r) :key(key), l(l), r(r) {} }; node* root = NULL; node* rroate(node* x) { node *y = x->l; x->l = y->r; y->r = x; return y; } node* lroate(node* x) { node* y = x->r; x->r = y->l; y->l = x; return y; } node *splay(T key, node *root) { if (!root) return NULL; node head, *l = &head, *r = &head; while (1) { if (key < root->key) { if (!root->l) break; if (key < root->l->key) { root = rroate(root); if (!root->l) break; } r = r->l = root; root = root->l; r->l = NULL; } else if (key > root->key) { if (!root->r) break; if (key > root->r->key) { root = lroate(root); if (!root->r) break; } l = l->r = root; root = root->r; l->r = NULL; } else break; } l->r = root->l; r->l = root->r; root->l = head.r; root->r = head.l; return root; } void print(node* root) {//preorder if (root) { if (!root->l && !root->r) return; std::cout << "key:" << root->key; if (root->l) std::cout << " l:" << root->l->key; if (root->r) std::cout << " r:" << root->r->key; std::cout << "\n"; print(root->l); print(root->r); } } public: void insert(T key) { if (!root) { root = new node(key); return; } root = splay(key, root); if (key < root->key) { node *p = new node(key, root->l, root); root->l = NULL; root = p; } else if (key > root->key) { node *p = new node(key, root, root->r); root->r = NULL; root = p; } return; } bool del(T key) { root = splay(key, root); if (!root || key != root->key) return 0;//¿ÕÊ÷»òûÕÒµ½ node *t = root; if (!root->l) { root = root->r; } else { root = splay(key, root->l); root->r = t->r; } delete t; return 1; } node* search(T key) { return root = splay(key, root); } void print() { print(root); } }; #endif SPLAYTREE_H_
/*************************************************************************** * * Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved * B142877 * **************************************************************************/ /** * @file datafile_lib.h * @author liuxufeng (liuxufeng@baidu.com) * @date 2017/05/31 13:09:41 * @version 1.0.0-alpha * @brief * 提供基于文件类的数据处理,例如svm格式转换,或者按列分析等 **/ #ifndef CPROCLIB_DATAFILE_LIB_H #define CPROCLIB_DATAFILE_LIB_H namespace datafile_lib { // translate matrix file to svm file int maxtrix2svm(std::string filename, std::string outfile, const bool header=False); int svm_scale(std::string svmfile, std::string outfile, std::string para_file){ throw "use libsvm's svm_scale"; } } #endif //CPROCLIB_DATAFILE_LIB_H
#include<bits/stdc++.h> #include <iostream> #include<fstream> #include <string> #include <limits> #include <vector> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; #define _USE_MATH_DEFINES #include <math.h> #include "cgal.h" #define MAX_REC_LEN 1024 /// edited /// #define readSize 101 typedef struct qEntry{ long long int pos; double prob; }qE; typedef struct information { double prob; long int pos; char contigField[15]; long int readLen; char* conName; } info; typedef struct buildString { long int pos; string cigar; string read; } bs; typedef struct readCigar { string cigar; string read; int contigNo; } CR; int startCentralTendency = 232000; int endCentralTendency = 233000; static int countInfoFile=0; void printGlobalMapData(); map<long int, vector<CR> > globalMap; map <int, vector<double> > mapOfProbListToPosition; /// edited /// int noContigs=0; int noReads=0; long int contigLength=0; int maxReadLength=0; long int totalContigLength=0; vector<char*> contigs; vector<char*> contigNames; vector<long int> contigLengths; FILE *contigFile; FILE *mapFile; FILE *summaryFile; FILE *outFile; ofstream infoFile; /// edited char *contigFileName; const char *mapFileName; static int iteration = 0; long int *insertCounts; int maxInsertSize=0; int MAX_INSERT_SIZE=100000; double insertSizeMean; double insertSizeVar; long int errorTypes[5][5]; long int baseCounts[5]; long int *errorPos; long int *inPos; long int *inLengths; long int *delPos; long int *delLengths; long int *readLengths; long int *effectiveLengths; double errorTypeProbs[5][5]; double baseErrorRates[5]; double *errorPosDist; double *inPosDist; double *inLengthDist; double *delPosDist; double *delLengthDist; double *insertLengthDist; double *noErrorProbs; int tmpCount=0; int toAlign; long int erroredReads=0; long int uniqueMappedReads=0; long int discardedReads=0; long int totalCount,unCount; char tempCigar[500], tempMD[500]; char noErrorCigar[500], noErrorMD[500]; ///edited void writeInfoToFile(vector<info> &multiMap, map<long int, string> &, map<long int, string> &); void writeBsToFile(vector<bs> &bsCollection, int count); void createBs(long int pos, char* readString, char* cigar, vector<bs> &B); void createInfo(double errorProb1, long int pos1, char* contigField1, char* readString1, vector<info> &M); void unixSort(); void calculateProbability(); void initInsertCounts(int max) { maxInsertSize=max; insertCounts=new long int[maxInsertSize]; for(int i=0; i<maxInsertSize; i++) { insertCounts[i]=1; } } void updateInsertCounts(int index) { if(index<=0) return; if(index<maxInsertSize) { insertCounts[index]++; } else { if(index>MAX_INSERT_SIZE) { discardedReads++; return; } int tempInsertSize=max(maxInsertSize*2,index); long int *tempCounts=new long int[maxInsertSize]; for(int i=0; i<maxInsertSize; i++) { tempCounts[i]=insertCounts[i]; } insertCounts=new long int[tempInsertSize]; for(int i=0; i<maxInsertSize; i++) { insertCounts[i]=tempCounts[i]; } for(int i=maxInsertSize; i<tempInsertSize; i++) { insertCounts[i]=1; } insertCounts[index]++; maxInsertSize=tempInsertSize; delete []tempCounts; } } void initErrorTypes(int readLength) { for(int i=0; i<5; i++) for(int j=0; j<5; j++) errorTypes[i][j]=1; for(int i=0; i<5; i++) baseCounts[i]=1; errorPos=new long int[readLength]; inPos=new long int[readLength]; inPos=new long int[readLength]; inPos=new long int[readLength]; inPos=new long int[readLength]; inLengths=new long int[readLength]; delPos=new long int[readLength]; delLengths=new long int[readLength]; readLengths=new long int[readLength]; for(int i=0; i<readLength; i++) { errorPos[i]=1; inPos[i]=1; inLengths[i]=1; delPos[i]=1; delLengths[i]=1; readLengths[i]=1; } } int getLength(char *read) { int i=0; while(read[i]) { if(read[i]=='A') baseCounts[0]++; else if(read[i]=='C') baseCounts[1]++; else if(read[i]=='G') baseCounts[2]++; else if(read[i]=='T') baseCounts[3]++; else baseCounts[4]++; i++; } return i; } void processErrorTypes(char *cigar, char *md, char *read, int strandNo) { int readLength=getLength(read); readLengths[readLength-1]++; if(strcmp(md,noErrorCigar)!=0) erroredReads++; else return; int mdLength=strlen(md)-5; int tempLength=0; char *temp; int index=0,totalLength=0; int curIndex=0; int *inserts=new int[readLength]; for(int i=0; i<readLength; i++) { inserts[i]=0; } int cigarLength=strlen(cigar); // char *tempCigar=new char[cigarLength]; char cigarChar; strcpy(tempCigar,cigar); temp=strtok(tempCigar,"IDMS^\t\n "); while(temp!=NULL) { tempLength=atoi(temp); totalLength+=strlen(temp); cigarChar=cigar[totalLength]; if(cigarChar=='M') { index+=tempLength; curIndex+=tempLength; } else if(cigarChar=='I' || cigarChar=='S') { if(strandNo==0) { inPos[index]++; inLengths[tempLength-1]++; } else { inPos[readLength-index-1]++; inLengths[tempLength-1]++; } inserts[curIndex]=tempLength; index+=tempLength; } else if(cigarChar=='D' ) { if(strandNo==0) { delPos[index]++; delLengths[tempLength-1]++; } else { delPos[readLength-index-1]++; delLengths[tempLength-1]++; } } totalLength++; temp=strtok(NULL,"IDMS^\t\n "); } strcpy(tempMD,md); strtok(tempMD,":"); strtok(NULL,":"); index=0,totalLength=0,tempLength=0; int f, t; while((temp=strtok(NULL,"ACGTN^\t\n "))!=NULL) { tempLength=strlen(temp); totalLength+=tempLength; if(totalLength<mdLength) { char from=md[5+totalLength]; if(from=='^') { totalLength++; index+=atoi(temp); for(int i=totalLength; i<mdLength; i++) { from=md[5+totalLength]; if(from=='A' || from=='C' || from=='G' || from=='T'|| from=='N') totalLength++; else break; } } else if(from=='A' || from=='C' || from=='G' || from=='T'|| from=='N') { totalLength++; index+=atoi(temp)+1; curIndex=0; for(int i=0; i<index; i++) { curIndex+=inserts[i]; } char to=read[index-1+curIndex]; if(strandNo==0) errorPos[index-1+curIndex]++; else errorPos[readLength-index-curIndex]++; switch(from) { case 'A': f=0; break; case 'C': f=1; break; case 'G': f=2; break; case 'T': f=3; break; default: f=4; } switch(to) { case 'A': t=0; break; case 'C': t=1; break; case 'G': t=2; break; case 'T': t=3; break; default: t=4; } if(f==t) { } else errorTypes[f][t]++; } else break; } } delete []inserts; } void computeProbabilites() { int errorCount=0; for(int i=0; i<5; i++) { errorCount=0; for(int j=0; j<5; j++) { errorCount+=errorTypes[i][j]; } for(int j=0; j<5; j++) { errorTypeProbs[i][j]=(double)errorTypes[i][j]/errorCount; } baseErrorRates[i]=errorCount/(double)baseCounts[i]; } double sum=0; for(int i=0; i<4; i++) sum+=baseErrorRates[i]; for(int i=0; i<4; i++) { baseErrorRates[i]=4*baseErrorRates[i]/sum;///??? } baseErrorRates[4]=1; for(int i=maxReadLength-1; i>0; i--) { readLengths[i-1]=readLengths[i]+readLengths[i-1]; } errorPosDist=new double[maxReadLength]; for(int i=0; i<maxReadLength; i++) { errorPosDist[i]=(double)errorPos[i]/readLengths[i]; } inPosDist=new double[maxReadLength]; for(int i=0; i<maxReadLength; i++) { inPosDist[i]=(double)inPos[i]/readLengths[i]; } inLengthDist=new double[maxReadLength]; int inCount=0; for(int i=0; i<maxReadLength; i++) { inCount+=inLengths[i]; } for(int i=0; i<maxReadLength; i++) { inLengthDist[i]=(double)inLengths[i]/inCount; } delPosDist=new double[maxReadLength]; for(int i=0; i<maxReadLength; i++) { delPosDist[i]=(double)delPos[i]/readLengths[i]; } delLengthDist=new double[maxReadLength]; int delCount=0; for(int i=0; i<maxReadLength; i++) { delCount+=delLengths[i]; } for(int i=0; i<maxReadLength; i++) { delLengthDist[i]=(double)delLengths[i]/delCount; } insertLengthDist=new double[maxInsertSize]; long int insCount=discardedReads; sum=0; for(int i=0; i<maxInsertSize; i++) { insCount+=insertCounts[i]; sum+=i*insertCounts[i]; } insertSizeMean=sum/insCount; sum=0; for(int i=0; i<maxInsertSize; i++) { insertLengthDist[i]=(double)insertCounts[i]/insCount; sum+=insertCounts[i]*(insertSizeMean-i)*(insertSizeMean-i); } insertSizeVar=sum/insCount; noErrorProbs=new double[maxReadLength]; double noErrorProb=1.0; for(int i=0; i<maxReadLength; i++) { noErrorProb*=(1-errorPosDist[i]-inPosDist[i]-delPosDist[i]); noErrorProbs[i]=noErrorProb; } effectiveLengths=new long int[maxInsertSize]; for(int i=0; i<maxInsertSize; i++) { effectiveLengths[i]=-1; } long int totalContigLength=0; for(int i=0; i<contigLengths.size(); i++) { totalContigLength+=contigLengths[i]; } effectiveLengths[0]=totalContigLength; } double dnorm(double x,double mean, double variance) { double val=1/sqrt(M_PI*2*variance); val*=exp(-((x-mean)*(x-mean))/(2*variance)); return val; } void processMapping(char *line) { char * temp; char *qname, *rname, *mapq, *contigField; int pos,flag; char * cigar, * readString; // * md, *nhstring; char md[500]; char nhstring[500]; int nh; int strandNo=0; char *temp1,*temp2,*temp3; qname=strtok(line,"\t"); temp=strtok(NULL,"\t"); flag=atoi(temp); strandNo=(flag&16)>>4; contigField =strtok(NULL, "\t"); temp=strtok(NULL,"\t"); pos=atoi(temp); cigar=strtok(NULL,"\t"); temp=strtok(NULL,"\t"); readString=strtok(NULL,"\t"); int insertSize=atoi(temp); while((temp=strtok(NULL,"\t\n"))!=NULL) { if(temp[0]=='M' && temp[1]=='D') { strcpy(md,temp); } else if(temp[0]=='I' && temp[1]=='H') { strcpy(nhstring,(temp+5)); nh=atoi(nhstring) ; } } if(nh==1 && md[5]!='^') { updateInsertCounts(insertSize); //cout << "Cigar " << cigar << " " << "MD" << md << " readString " << readString << " strandNO " << strandNo << endl; processErrorTypes(cigar,md,readString,strandNo); uniqueMappedReads++; } } long int getEffectiveLength(int insertSize) { if(insertSize<0) return effectiveLengths[0]; if(insertSize>=maxInsertSize) { long int effectiveLength=0; for(int i=0; i<contigLengths.size(); i++) { if(contigLengths[i]>=insertSize) effectiveLength+=(contigLengths[i]-insertSize+1); } return effectiveLength; } if(effectiveLengths[insertSize]==-1) { long int effectiveLength=0; for(int i=0; i<contigLengths.size(); i++) { if(contigLengths[i]>=insertSize) effectiveLength+=(contigLengths[i]-insertSize+1); } effectiveLengths[insertSize]=effectiveLength; } return effectiveLengths[insertSize]; } double computeErrorProb(char *cigar, char *md, char *read, int strandNo) { int readLength=strlen(read); //cout << "Entering error prob" << endl; double errorProb=noErrorProbs[readLength-1]; if(md[5]=='^') return errorProb; char tempMD[1000], tempCigar[1000]; int mdLength=strlen(md)-5; int tempLength=0; char *temp; int index=0,totalLength=0; int curIndex=0; int *inserts=new int[readLength]; for(int i=0; i<readLength; i++) { inserts[i]=0; } int cigarLength=strlen(cigar); char cigarChar; strcpy(tempCigar,cigar); temp=strtok(tempCigar,"IDM^\t\n "); //cout << "b4 while1 " << endl; while(temp!=NULL) { tempLength=atoi(temp); totalLength+=strlen(temp); cigarChar=cigar[totalLength]; if(cigarChar=='M') { index+=tempLength; curIndex+=tempLength; } else if(cigarChar=='I') { int i; if(strandNo==0) { //look up insert probs i=index; } else { i=readLength-index-1; } errorProb=errorProb*inPosDist[i]*inLengthDist[tempLength-1]/(1-errorPosDist[i]-inPosDist[i]-delPosDist[i]); inserts[curIndex]=tempLength; index+=tempLength; } else if(cigarChar=='D') { int i; if(strandNo==0) { i=index; // look up delete probs } else { i=readLength-index-1; } errorProb=errorProb*delPosDist[i]*delLengthDist[tempLength-1]/(1-errorPosDist[i]-inPosDist[i]-delPosDist[i]); } totalLength++; temp=strtok(NULL,"IDM^\t\n "); } //cout << "After while1" << endl; strcpy(tempMD,md); strtok(tempMD,":"); strtok(NULL,":"); index=0,totalLength=0,tempLength=0; int f, t; //cout << "B4 while2" << endl; while((temp=strtok(NULL,"ACGTN^\t\n "))!=NULL) { tempLength=strlen(temp); totalLength+=tempLength; if(totalLength<mdLength) { char from=md[5+totalLength]; if(from=='^') { totalLength++; index+=atoi(temp); for(int i=totalLength; i<mdLength; i++) { from=md[5+totalLength]; if(from=='A' || from=='C' || from=='G' || from=='T'|| from=='N') totalLength++; else break; } } else if(from=='A' || from=='C' || from=='G' || from=='T'|| from=='N') { totalLength++; index+=atoi(temp)+1; curIndex=0; //cout << "INdex:" << index << endl; for(int i=0; i<index; i++) { curIndex+=inserts[i]; } //cout << "Read:" << read << endl; //cout << index << ' ' << curIndex << endl; char to=read[index-1+curIndex]; int i; if(strandNo==0) i=index-1+curIndex; else i=readLength-index-curIndex; errorProb=errorProb*errorPosDist[i]/(1-errorPosDist[i]-inPosDist[i]-delPosDist[i]); switch(from) { case 'A': f=0; break; case 'C': f=1; break; case 'G': f=2; break; case 'T': f=3; break; default: f=4; } switch(to) { case 'A': t=0; break; case 'C': t=1; break; case 'G': t=2; break; case 'T': t=3; break; default: t=4; } if(f==t) { } else { //errorTypeProb errorProb*=baseErrorRates[f]*errorTypeProbs[f][t]; } } else break; } } //cout << "After while2" << endl; delete []inserts; return errorProb; } void printHelp() { cout<<"cgal v0.9.9-beta"<<endl; cout<<"----------------"<<endl; cout<<endl; cout<<"cgal - computes likelihood"<<endl; cout<<"Usage:"<<endl; cout<<"cgal [options] <contigfile>"<<endl; cout<<endl; cout<<"Required arguments:"<<endl; cout<<"<contigfile.sam>\t Assembly file in FASTA format"<<endl; cout<<endl; cout<<"Options:"<<endl; cout<<"-h [--help]\t\t Prints this message"<<endl; cout<<endl; cout<<"Output: "<<endl; cout<<"(In file out.txt) <numberContigs> <totalLikelihood> <mappedLikelihood> <unmappedLikelihood> <noReads> <noReadsUnmapped>"<<endl; cout<<"<numberContigs>\t\t Number of contigs"<<endl; cout<<"<totalLikelihood>\t Total log likelihood value"<<endl; cout<<"<mappedLikelihood>\t Likelihood value of reads mapped by the mapping tool"<<endl; cout<<"<unmappedLikelihood>\t Likelihood value corresponding to reads not mapped by alignment tool"<<endl; cout<<"<noReads>\t\t Total number of paired-end reads"<<endl; cout<<"<noReadsUnmapped>\t Number of reads not mapped by the alignment tool"<<endl; cout<<endl; exit(1); } void provideHelp (int argc, char *argv[]){ if(argc<2 || (strcmp(argv[1],"--help")==0 || strcmp(argv[1],"-h")==0)){ printHelp(); } } void createInfo(char *qName, double errorProb1, long int pos1, char* contigField1, char* readString1, vector<info> &M) { info temp1; temp1.prob = errorProb1; temp1.pos = pos1; strcpy(temp1.contigField, contigField1); temp1.readLen = strlen(readString1); temp1.conName = qName; M.push_back(temp1); } void createBs(long int pos, char* readString, char* cigar, vector<bs> &B) { bs bstemp1; bstemp1.pos = pos; bstemp1.read = readString; bstemp1.cigar = cigar; B.push_back(bstemp1); } void unixSort() { cout << "Sorting info1" << endl; system("sort -n -k1,1 -k2,2 info1.txt > infoOutput1.txt"); } void writeBsToFile(vector<bs> &bsCollection, int count) { if(count<10){ string s = "bsFolder2/bsOutput_"; string t = ".txt"; stringstream oss; oss<< s<<count<<t; cout<<oss.str()<<endl; //FILE *fp; //fp = fopen(oss.str().c_str(),"w"); ofstream bsFile(oss.str().c_str()); for(int i=0;i<bsCollection.size();i++) { bs b = bsCollection[i]; bsFile <<b.pos<<" "<< b.cigar<<" "<<b.read<<endl; //fprintf(fp,"%ld %s %s\n",b.pos,b.cigar,b.read); } //fclose(fp); bsFile.close(); } } void printGlobalMapData() { map<long int, vector<CR> >:: iterator it; ofstream gOut("globalOutput.txt"); for(it = globalMap.begin(); it!=globalMap.end(); it++) { vector<CR> tempCr = it->second; // cout << "itpos" << it->first << " " << tempCr.size() << endl; for(int i=0;i<tempCr.size();i++) { gOut<<it->first<<" "<<tempCr[i].contigNo<<" "<<tempCr[i].cigar<<" "<<tempCr[i].read<<endl; } } gOut.close(); system("sort -n -k1,1 -k2,2 globalOutput.txt > globalOutSort.txt"); } void writeInfoToFile(vector<info> &multiMap, map<long int, string> &cigar, map<long int, string> &read) { vector<double> cdf; vector<info> data(multiMap);// = getClonedMultiMap(multiMap); //cout<<data.size()<<" "<<multiMap.size()<<endl; double s=0,s1=0; for(int i=0; i<multiMap.size(); i++) { info temp = multiMap[i]; //fprintf(infoFile, "(%ld, %ld) --> %lf\n",temp.pos1,temp.pos2,temp.prob); s += temp.prob; } srand(time(NULL)); for(int i=0; i<multiMap.size(); i++) { info temp = multiMap[i]; //cout<<temp.prob<<endl; multiMap[i].prob = temp.prob/s; } double r = ((double) rand() / (RAND_MAX)); for(int i=0; i<multiMap.size(); i++) { info temp = multiMap[i]; s1 += temp.prob; info temp1 = data[i]; if(r<=s1) { iteration++; infoFile << temp1.contigField<< " " << temp1.pos << " " << temp1.prob << endl; CR ob; int number = atoi(temp1.contigField); ob.contigNo = temp1.pos; ob.cigar = cigar[temp1.pos]; ob.read = read[temp1.pos]; globalMap[number].push_back(ob); //cout<<iteration<<endl; break; } } /*for(int i=0;i<multiMap.size();i++){ info temp = multiMap[i]; //cout<<temp.prob<<endl; temp.prob = temp.prob/s; s1 += temp.prob; cdf.push_back(s1); } srand(time(NULL)); double r = ((double) rand() / (RAND_MAX)); for(int i=cdf.size()-1;i>=0;i--){ if(cdf[i]<r) { info temp = multiMap[i+1]; //cout<<temp.prob<<endl; fprintf(infoFile, "%s %s %ld %ld %e\n",temp.contigField1,temp.contigField2,temp.pos1,temp.pos2,temp.prob); break; } }*/ countInfoFile++; // cout<<"Write info to file"<<endl; } void checkCentralTendency(deque <qE> Q2, int position) { // cout << "Here in the function " << endl; vector <double> probList; for(int i=0;i<Q2.size();i++){ probList.push_back(Q2[i].prob); } mapOfProbListToPosition[position] = probList; } void writeFileForCentralTendencyCheck(){ // cout << "Here" << endl; ofstream fileWriter ("centralTendencyCheck.txt"); map<int , vector<double> >:: iterator it; for(it = mapOfProbListToPosition.begin(); it != mapOfProbListToPosition.end();it++ ){ vector <double> probList = it->second; int position = it->first; for(int i=0;i<probList.size();i++){ if(position >= startCentralTendency && position <= endCentralTendency){ fileWriter << position << probList[i] << endl; } } fileWriter << "~~~~~~~~~~~~~~~" << endl; } fileWriter.close(); }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<algorithm> #include<cmath> using namespace std; int main() { int T; scanf("%d",&T); while (T--) { double x,y,t,s; scanf("%lf%lf%lf%lf",&x,&y,&t,&s); if (x <= y) printf("%.3lf",t + s/x); else { double len = y*t,ans = 0; while (len <= s) { len } } } return 0; }
#include "MediaSegment.h" namespace hls { MediaSegment::MediaSegment() { } float MediaSegment::duration() const { return mDuration; } void MediaSegment::setDuration(float duration) { mDuration = duration; } QString MediaSegment::uri() const { return mUri; } void MediaSegment::setUri(const QString &uri) { mUri = uri; } } // namespace hls
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> #include <deque> #include <memory> const long long LINF = (5e18); const int INF = (1<<30); #define EPS 1e-6 const int MOD = 1000000007; using namespace std; class PathGame { public: int memo[1005][4][4]; // 1: up // 2: down // 3: none int getGrundy(int len, int l, int r) { if (memo[len][l][r] != -1) return memo[len][l][r]; if (len == 1 && l&r) return memo[len][l][r] = 1; if (len <= 1) return memo[len][l][r] = 0; set<int> s; if (l!=2) s.insert(getGrundy(len-1, 1, r)); if (l!=1) s.insert(getGrundy(len-1, 2, r)); if (r!=2) s.insert(getGrundy(len-1, l, 1)); if (r!=1) s.insert(getGrundy(len-1, l, 2)); for (int i=1; i<len-1; ++i) { s.insert(getGrundy(i, l, 1) ^ getGrundy(len-i-1, 1, r)); s.insert(getGrundy(i, l, 2) ^ getGrundy(len-i-1, 2, r)); } int res = 0; while (s.count(res)) ++res; return memo[len][l][r] = res; } string judge(vector <string> board) { board[0].push_back('*'); board[1].push_back('*'); memset(memo, -1, sizeof(memo)); int w = (int)board[0].size(); int len = 0; int leftState = 3; int grundy = 0; for (int i=0; i<w; ++i) { if (board[0][i] != '.' || board[1][i] != '.') { int rightState; if (board[0][i] == '#') rightState = 1; else if (board[1][i] == '#') rightState = 2; else rightState = 3; grundy ^= getGrundy(len, leftState, rightState); leftState = rightState; len = 0; } else { ++len; } } return grundy != 0 ? "Snuke" : "Sothe"; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"#.." ,"..."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Snuke"; verify_case(0, Arg1, judge(Arg0)); } void test_case_1() { string Arr0[] = {"#" ,"."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Sothe"; verify_case(1, Arg1, judge(Arg0)); } void test_case_2() { string Arr0[] = {"....." ,"..#.."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Sothe"; verify_case(2, Arg1, judge(Arg0)); } void test_case_3() { string Arr0[] = {".#..." ,"....."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Snuke"; verify_case(3, Arg1, judge(Arg0)); } void test_case_4() { string Arr0[] = {".....#..#........##......." ,"..........#..........#...."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Snuke"; verify_case(4, Arg1, judge(Arg0)); } void test_case_5() { string Arr0[] = {".." ,".."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Sothe"; verify_case(5, Arg1, judge(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { PathGame ___test; ___test.run_test(-1); } // END CUT HERE
// // GStateBGLayer.h // Core // // Created by Max Yoon on 11. 7. 30.. // Copyright 2011년 __MyCompanyName__. All rights reserved. // #ifndef Core_GStateBGLayer_h #define Core_GStateBGLayer_h class GStateBGLayer : public GLayer { public: static GStateBGLayer* CreateBackground(); public: bool InitBackground(); }; #endif
#ifndef _RESOURCES_MANAGER_H_ #define _RESOURCES_MANAGER_H_ #include <SFML/Graphics.hpp> #include <string> class ResourcesManager { public: ResourcesManager(); ~ResourcesManager(); sf::Texture * getTexture(const std::string &path); sf::Texture * addTexture(const std::string &path); void removeTexture(const std::string &path); sf::Font * getFont(const std::string &path); sf::Font * addFont(const std::string &path); void removeFont(const std::string &path); private: std::map<std::string, sf::Texture *> m_textures; std::map<std::string, sf::Font *> m_fonts; }; #endif // _RESOURCES_MANAGER_H_
#ifndef CELL_LIST_H #define CELL_LIST_H #include <cstdio> #include <vector> #include <forward_list> //class Node { //public: // Node() { next = NULL; } // double x; // double y; // int cell_idx; // Node * next; // // static int Lx; // static int Ly; // static int N; //}; template<class Node> class Cell { public: Cell() { head = NULL; } void cell_cell(); void cell_cell(Cell<Node>*); void cell_cell(Cell<Node>*, double, double); static void all_pairs(Cell<Node>*cell); static void link_nodes(Cell<Node> *cell, Node *node); static void refresh(Cell<Node> *cell, Node *node); static Cell<Node> *ini(Node *bird, double Lx, double Ly); Node* head; static int mx; static int my; static int mm; static double l0; }; template <class Node> int Cell<Node>::mx; template <class Node> int Cell<Node>::my; template <class Node> int Cell<Node>::mm; template <class Node> double Cell<Node>::l0; template <class Node> void Cell<Node>::cell_cell() { Node *node1 = head; Node *node2; while (node1->next) { node2 = node1->next; do { node1->interact(node2); node2 = node2->next; } while (node2); node1 = node1->next; } } template <class Node> void Cell<Node>::cell_cell(Cell<Node> *cell) { if (cell->head) { Node* node1 = head; Node* node2; do { node2 = cell->head; do { node1->interact(node2); node2 = node2->next; } while (node2); node1 = node1->next; } while (node1); } } template <class Node> void Cell<Node>::cell_cell(Cell<Node> *cell, double a, double b) { if (cell->head) { Node* node1 = head; Node* node2; do { node2 = cell->head; do { node1->interact(node2, a, b); node2 = node2->next; } while (node2); node1 = node1->next; } while (node1); } } template <class Node> void Cell<Node>::all_pairs(Cell<Node> * cell) { int i, j; Cell<Node>* p = cell; for (j = 0; j <= my - 2; j++) { if (p->head) { p->cell_cell(); p->cell_cell(p + 1); p->cell_cell(p + mx + mx - 1, -Node::Lx, 0); p->cell_cell(p + mx); p->cell_cell(p + mx + 1); } p++; for (i = 1; i <= mx - 2; i++) { if (p->head) { p->cell_cell(); p->cell_cell(p + 1); p->cell_cell(p + mx - 1); p->cell_cell(p + mx); p->cell_cell(p + mx + 1); } p++; } if (p->head) { p->cell_cell(); p->cell_cell(p - mx + 1, Node::Lx, 0); p->cell_cell(p + 1, Node::Lx, 0); p->cell_cell(p + mx); p->cell_cell(p + mx - 1); } p++; } if (p->head) { p->cell_cell(); p->cell_cell(p + 1); p->cell_cell(cell, 0, Node::Ly); p->cell_cell(cell + 1, 0, Node::Ly); p->cell_cell(cell + mx - 1, -Node::Lx, Node::Ly); } p++; for (i = 1; i <= mx - 2; i++) { if (p->head) { p->cell_cell(); p->cell_cell(p + 1); p->cell_cell(cell + i - 1, 0, Node::Ly); p->cell_cell(cell + i, 0, Node::Ly); p->cell_cell(cell + i + 1, 0, Node::Ly); } p++; } if (p->head) { p->cell_cell(); p->cell_cell(p - mx + 1, Node::Lx, 0); p->cell_cell(cell + mx - 2, 0, Node::Ly); p->cell_cell(cell + mx - 1, 0, Node::Ly); p->cell_cell(cell, Node::Lx, Node::Ly); } } template <class Node> void Cell<Node>::link_nodes(Cell<Node> * cell, Node* node) { for (int i = 0; i < Node::N; i++) { int col = int(node[i].x); if (col >= mx) col -= mx; else if (col < 0) col += mx; int row = int(node[i].y); if (row >= my) row -= my; else if (row < 0) row += my; int j = node[i].cell_idx = col + mx * row; node[i].next = cell[j].head; cell[j].head = &node[i]; } } template <class Node> void Cell<Node>::refresh(Cell<Node> * cell, Node* node) { for (int i = 0; i < mm; i++) { cell[i].head = NULL; } Cell::link_nodes(cell, node); } template <class Node> Cell<Node> * Cell<Node>::ini(Node *bird, double Lx, double Ly) { mx = int(Lx / l0); my = int(Ly / l0); mm = mx * my; Cell *cell = new Cell[mm]; for (int i = 0; i < mm; i++) { cell[i].head = nullptr; } link_nodes(cell, bird); return cell; } #endif
#include<iostream> #include<conio.h> int main() { int a, b, c; for(a=6;a>=1;a--) { for(b=1;b<a;b++) { std::cout << " "; } for (c=6;c>=a;c--) { std::cout << "*"; } std::cout<<std::endl; } getch(); }
#include <iostream> #include <node/node.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> namespace test { using v8::Array; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::NewStringType; using v8::Object; using v8::String; using v8::Value; int doNotCloseStreamsOnExit(int desc) { int flags = fcntl(desc, F_GETFD, 0); if (flags < 0) return flags; flags &= ~FD_CLOEXEC; //clear FD_CLOEXEC bit return fcntl(desc, F_SETFD, flags); } void Method(const FunctionCallbackInfo<Value> &args) { // const Local<Promise> defered = Promise::New(args.GetIsolate()).As<Promise>(); // Napi::Promise::Deferred defered = Napi::Promise::Deferred::New(args.GetIsolate()); Local<Array> arr = args[0].As<Array>(); const int leng = arr->Length(); char **argv = new char *[leng + 2]; // std::cout << arr->Length() << " Lenght " << std::endl; argv[0] = "heif-enc-node"; for (int i = 0; i < leng; i++) { Local<String> str = arr->Get(args.GetIsolate()->GetCurrentContext(), i).ToLocalChecked().As<String>(); argv[i + 1] = new char[str->Length()]; str->WriteUtf8(args.GetIsolate(), argv[i + 1]); } argv[leng + 1] = NULL; pid_t p = fork(); if (p) { int status = 0; wait(&status); args.GetReturnValue() .Set(arr->Get(args.GetIsolate()->GetCurrentContext(), 0).ToLocalChecked().As<String>()); } else { // fix stream flags doNotCloseStreamsOnExit(0); //stdin doNotCloseStreamsOnExit(1); //stdout doNotCloseStreamsOnExit(2); //stderr int res = execv("/usr/local/bin/heif-enc-node", argv); std::cout << res << std::endl; if (res < 0) { char *err_description = strerror(errno); std::cout << err_description << std::endl; } return; } } void Initialize(Local<Object> exports) { NODE_SET_METHOD(exports, "createHeic", Method); } NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) } // namespace test
#ifndef ELF_SECTION_H #define ELF_SECTION_H #include "defs.h" #include "elf_section_description.h" template<class IW> class ElfSection { public: ElfSection() = default; ElfSection(std::string name, std::string filename, u32 offset, u32 size); void create(std::string name, std::string filename, u32 offset, u32 size); void set_address_range(u32 base_addr, bool cacheable = true); std::string section_name(); u32 size_in_words(); u32 size_in_bytes(); u32* raw_data(); void resize_data(u32 sec_size); bool is_code(); void set_as_code(bool code); void set_description(elf::ElfSectionDescription<IW> &desc); elf::ElfSectionDescription<IW> & get_description(); u32 physical_address(); void get_address_range(IW &base_addr, IW &max_addr); protected: void set_address_range(IW base_addr, IW max_addr, bool cacheable); void init(); std::string elf_filename; u32 file_offset; u32 section_size; elf::ElfSectionDescription<IW> *p_description_{}; std::string section_name_; std::vector<u32> binary_image; bool initialised_{ false }; bool is_code_{ false }; u32 base_address_; u32 max_address_; bool cacheable_; }; template<class IW> ElfSection<IW>::ElfSection(std::string name_, std::string filename, u32 offset, u32 size) : elf_filename{ filename }, file_offset{ offset }, section_size{ size }, section_name_{ name_ } { init(); } template<class IW> void ElfSection<IW>::create(std::string name, std::string filename, u32 offset, u32 size) { elf_filename = filename; section_name_ = name; file_offset = offset; section_size = size; init(); } template<class IW> u32 ElfSection<IW>::size_in_words() { return section_size >> 2; } template<class IW> u32 ElfSection<IW>::size_in_bytes() { return section_size; } template<class IW> void ElfSection<IW>::resize_data(u32 sec_size) { section_size = sec_size; binary_image.resize(section_size); } template<class IW> u32* ElfSection<IW>::raw_data() { if (!section_size) return NULL; return &binary_image[0]; } template<class IW> std::string ElfSection<IW>::section_name() { return section_name_; } template<class IW> elf::ElfSectionDescription<IW> & ElfSection<IW>::get_description() { if (!p_description_) { static elf::ElfSectionDescription dummy; return dummy; } return *p_description_; } template<class IW> void ElfSection<IW>::set_description(elf::ElfSectionDescription<IW> &desc) { p_description_ = &desc; } template<class IW> void ElfSection<IW>::set_address_range(u32 base_addr, bool cacheable) { set_address_range(base_addr, base_addr + section_size - 1, cacheable); } template<class IW> u32 ElfSection<IW>::physical_address() { return base_address_; } template<class IW> void ElfSection<IW>::set_address_range(IW base_addr, IW max_addr, bool cacheable) { base_address_ = base_addr; max_address_ = max_addr; cacheable_ = cacheable; } template<class IW> void ElfSection<IW>::get_address_range(IW &base_addr, IW &max_addr) { base_addr = base_address_; max_addr = max_address_; } template<class IW> void ElfSection<IW>::init() { FILE * elf_file = NULL; initialised_ = false; elf_file = fopen(elf_filename.c_str(), "rb"); u32 word_size = section_size >> 2; base_address_ = 0; max_address_ = 0; cacheable_ = false; word_size++; binary_image.resize(word_size); if (!elf_file) return; fseek(elf_file, file_offset, SEEK_SET); size_t word_count = fread(&binary_image[0], sizeof(u32), word_size, elf_file); initialised_ = word_count == word_size; fclose(elf_file); } template<class IW> bool ElfSection<IW>::is_code() { return is_code_; } template<class IW> void ElfSection<IW>::set_as_code(bool code) { is_code_ = code; } #endif
#include<iostream> using namespace std; class Customer { private: char Customer_Name[20], Title[20], E_mail[30]; long int Customer_ID; long int Telephone_Number; char Address[50], NIC_NO[25]; public: void Add_New_Customer(long int id,char name[20],char title[20],char email[30],long int telephone,char address[50],char nic[25]) { Customer_ID=id; strcpy(Customer_Name,name); strcpy(Title,title); strcpy(E_mail,email); Telephone_Number=telephone; strcpy(Address,address); strcpy(NIC_NO,nic); } void Display_Customer_Record() {cout<<"customer id is "<<Customer_ID<<endl; cout<<"customer name is "<<Customer_Name<<endl; cout<<"Title is "<<Title<<endl; cout<<"Email is "<<E_mail<<endl; cout<<"Telephone number is "<<Telephone_Number<<endl; cout<<"Address is "<<Address<<endl; cout<<"Cnic number is"<<NIC_NO<<endl; } }; class Account { private: long int Account_ID; char Customer_ID[20], Account_Type[20]; double Balance; char Date_of_Creation[20]; public: void addnewaccount(long int accountid, char customerid[20],char accounttype[20],double bal,char date[20]) { Account_ID=accountid; strcpy(Customer_ID,customerid); strcpy(Account_Type,accounttype); Balance=bal; strcpy(Date_of_Creation,date); } void Display_Account_Details() {cout<<"customer id is "<<Customer_ID<<endl; cout<<"Account id is "<<Account_ID<<endl; cout<<"Account Type is "<<Account_Type<<endl; cout<<"Date of creation is "<<Date_of_Creation<<endl; cout<<"Total Balance is is "<< Balance<<endl; } }; class Transaction {private: long int Transaction_ID; char Account_ID[20], Transaction_Type[20]; double Amount_Transacted; public: void Make_New_Transaction(long int tans_id,char account_id[20],char transiction_type[20],double amount_transacted) { Transaction_ID=tans_id; strcpy( Account_ID,account_id); strcpy(Transaction_Type,transiction_type); Amount_Transacted=amount_transacted; } void Display_Transaction() { cout<<"Transaction id is "<<Transaction_ID<<endl; cout<<"Account id is"<<Account_ID<<endl; cout<<"Transaction Type is "<<Transaction_Type<<endl; cout<<"Amount Transacted is "<<Amount_Transacted<<endl; } };
//Программа lab7.exe обеспечивает преобразование файла ASCII в //Unicode с использованием асинхронного ввода - вывода с помощью про - //цедуры завершения.Многие переменные сделаны глобальными, для того //чтобы они были доступны для процедур завершения.Запуск программы //производится из командной строки в виде : lab7.exe filel file2. #include "pch.h" #include "EvryThng.h" #define MAX_OVRLP 4 #define REC_SIZE 64 #define UREC_SIZE 2 * REC_SIZE static VOID WINAPI ReadDone(DWORD, DWORD, LPOVERLAPPED); static VOID WINAPI WriteDone(DWORD, DWORD, LPOVERLAPPED); /* Первая структура перекрытия предназначена для чтения, а вторая для записи. Структуры и буфера выделяются для каждой незавершенной операции. */ OVERLAPPED OverLapIn[MAX_OVRLP], OverLapOut[MAX_OVRLP]; CHAR AsRec[MAX_OVRLP][REC_SIZE]; WCHAR UnRec[MAX_OVRLP][REC_SIZE]; HANDLE hInputFile, hOutputFile; LONGLONG nRecord, nDone; LARGE_INTEGER FileSize; LARGE_INTEGER CurPosIn, CurPosOut; DWORD ic; int _tmain(int argc, LPTSTR argv[]) { hInputFile = CreateFile(argv[1], GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); hOutputFile = CreateFile(argv[2], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_FLAG_OVERLAPPED, NULL); FileSize.LowPart = GetFileSize(hInputFile, (LPDWORD)FileSize.HighPart); nRecord = FileSize.QuadPart / REC_SIZE; printf("nR=%d\n", (int)nRecord); if ((FileSize.QuadPart % REC_SIZE) != 0) nRecord++; CurPosIn.QuadPart = 0; printf("nR2=%d\n", (int)nRecord); for (ic = 0; ic < MAX_OVRLP; ic++) { printf("ic=%d\n", (int)ic); OverLapIn[ic].hEvent = (HANDLE)ic; /* Перезагрузка события. */ OverLapOut[ic].hEvent = (HANDLE)ic; OverLapIn[ic].Offset = CurPosIn.LowPart; OverLapIn[ic].OffsetHigh = CurPosIn.HighPart; if (CurPosIn.QuadPart < FileSize.QuadPart) ReadFileEx(hInputFile, AsRec[ic], REC_SIZE, &OverLapIn[ic], ReadDone); CurPosIn.QuadPart += (LONGLONG)REC_SIZE; } /* Все операции чтения выполняются. Вводим состояние ожидания завершения и продолжаем, пока не будут обработаны все записи. */ nDone = 0; while (nDone < 2 * nRecord) SleepEx(INFINITE, TRUE); CloseHandle(hInputFile); CloseHandle(hOutputFile); _tprintf(_T("ASCII in Unicode is completed\n")); return 0; } static VOID WINAPI ReadDone(DWORD Code, DWORD nBytes, LPOVERLAPPED pOv) { /* Чтение завершено. Преобразуем данные и начинаем запись. */ DWORD i; nDone++; printf("nD1=%d\n", (int)nDone); /* Обработка записи и начало операции записи. */ ic = (DWORD)(pOv->hEvent); CurPosIn.LowPart = OverLapIn[ic].Offset; CurPosIn.HighPart = OverLapIn[ic].OffsetHigh; CurPosOut.QuadPart = (CurPosIn.QuadPart / REC_SIZE) * UREC_SIZE; OverLapOut[ic].Offset = CurPosOut.LowPart; OverLapOut[ic].OffsetHigh = CurPosOut.HighPart; /* Преобразование записи ASCII в Unicode. */ for (i = 0; i < nBytes; i++) UnRec[ic][i] = AsRec[ic][i]; WriteFileEx(hOutputFile, UnRec[ic], nBytes * 2, &OverLapOut[ic], WriteDone); /* Подготовка структуры перекрытия к следующему чтению. */ CurPosIn.QuadPart += REC_SIZE * (LONGLONG)(MAX_OVRLP); OverLapIn[ic].Offset = CurPosIn.LowPart; OverLapIn[ic].OffsetHigh = CurPosIn.HighPart; return; } static VOID WINAPI WriteDone(DWORD Code, DWORD nBytes,LPOVERLAPPED pOv){ /* Запись завершена. Начинаем следующее чтение. */ /*LARGE_INTEGER CurPosIn;*/ /*DWORD ic;*/ nDone++; printf("nD2=%d\n", (int)nDone); ic = (DWORD)(pOv->hEvent); CurPosIn.LowPart = OverLapIn[ic].Offset; CurPosIn.HighPart = OverLapIn[ic].OffsetHigh; if (CurPosIn.QuadPart < FileSize.QuadPart) { ReadFileEx(hInputFile, AsRec[ic], REC_SIZE, &OverLapIn[ic], ReadDone); } return; }
// Created on: 1996-09-17 // Created by: Odile Olivier // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StdSelect_ShapeTypeFilter_HeaderFile #define _StdSelect_ShapeTypeFilter_HeaderFile #include <TopAbs_ShapeEnum.hxx> #include <SelectMgr_Filter.hxx> class SelectMgr_EntityOwner; DEFINE_STANDARD_HANDLE(StdSelect_ShapeTypeFilter, SelectMgr_Filter) //! A filter framework which allows you to define a filter for a specific shape type. class StdSelect_ShapeTypeFilter : public SelectMgr_Filter { DEFINE_STANDARD_RTTIEXT(StdSelect_ShapeTypeFilter, SelectMgr_Filter) public: //! Constructs a filter object defined by the shape type aType. Standard_EXPORT StdSelect_ShapeTypeFilter(const TopAbs_ShapeEnum aType); //! Returns the type of shape selected by the filter. TopAbs_ShapeEnum Type() const {return myType;} Standard_EXPORT virtual Standard_Boolean IsOk (const Handle(SelectMgr_EntityOwner)& anobj) const Standard_OVERRIDE; Standard_EXPORT virtual Standard_Boolean ActsOn (const TopAbs_ShapeEnum aStandardMode) const Standard_OVERRIDE; private: TopAbs_ShapeEnum myType; }; #endif // _StdSelect_ShapeTypeFilter_HeaderFile
#include "Brick.h" /* Constructor for the brick. Initialize the width, height, the position, maximum number of hits and the color. */ Brick::Brick(std::string name, unsigned int width, unsigned int height, float x, float y, int numHits, glm::vec3 color) : CollidableSquare(name, width, height, x, y, color) { this->numHits = numHits; getRndPw = false; } /* Desructor for the brick */ Brick::~Brick() { } /* Scale the brick. Used in animation of destroing the brick. */ void Brick::ScaleOff(float stepTime) { this->ApplyTranformation(Transform2D::Scale(stepTime, stepTime)); } /* Update the state of the brick. If number of hits is less than 0, generate a random powerup and then destroy the brick. */ void Brick::Update(float gameTime) { if (this->numHits <= 0) { if (getRndPw) getRndPw = false; this->Destroy(gameTime); } } /* Hit the brick. Reduce the number of hits. */ void Brick::Hit() { this->numHits--; if (this->numHits == 0) { getRndPw = true; } } /* Getter for number of remaining hits */ int Brick::GetNumHits() { return this->numHits; } /* Getter for getRndPw; */ bool Brick::GenerateRndPw() { return this->getRndPw; } /* Destroy the brick. Apply the animation. */ void Brick::Destroy(float gameTime) { scaleOffSpeed -= scaleOffSpeed * gameTime; this->SetSize(this->GetSize() * glm::pow(scaleOffSpeed, gameTime)); ScaleOff(glm::pow(scaleOffSpeed, gameTime)); }
// // Created by 송지원 on 2020/06/25. // //200625 boj10828 문제 바킹독 님 버젼 //난 입력으로 들오오는 명령어를 위에 배열로 선언하고 그걸 활용하여 입력을 구분했는데 //그것보다는 아래 코드 내에서 직접 사용해서 구현 //#include <bits/stdc++.h> #include <iostream> #include <stack> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; stack<int> S; while (n--) { string c; cin >> c; if (c == "push") { int t; cin >> t; S.push(t); } else if (c == "pop") { if (S.empty()) { cout << "-1" << '\n'; } else { cout << S.top() << "\n"; S.pop(); } } else if (c == "size") { cout << S.size() << "\n"; } else if (c == "empty") { cout << (int)S.empty() << "\n"; } else { if (S.empty()) cout << "-1" << "\n"; else cout << S.top() << "\n"; } } }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; int f[210][210][210],sum[210][210][210],ans[210][3]; void dp(int n,int x,int y) { f[x][y][0] = 0; for (int i = 1;i <= n; i++) { f[x][y][i] = f[x][y][i-1] + 1; if (i >= x) f[x][y][i] = min(f[x][y][i-x]+1,f[x][y][i]); if (i >= y) f[x][y][i] = min(f[x][y][i-y]+1,f[x][y][i]); sum[x][y][i] = sum[x][y][i-1] + f[x][y][i]; } } int main() { int T,n = 200; for (int i = 2; i < n; i++) for (int j = i+1; j <= n; j++) dp(n,i,j); for (int k = 1;k <= n; k++) { int rec = n*(n-1)/2; ans[k][1] = 2;ans[k][2] = 3; for (int i = 2;i < k; i++) for (int j = i+1;j <= k; j++) { if (sum[i][j][k] < rec) { rec = sum[i][j][k]; ans[k][1] = i;ans[k][2] = j; } } } scanf("%d\n",&T); while (T--) { scanf("%d",&n); printf("1 %d %d\n",ans[n][1],ans[n][2]); } return 0; }
#include <Ogre.h> #include <OIS/OIS.h> #include "MenuState.h" #include "PlayState.h" #include "OverState.h" using namespace Ogre; OverState OverState::mOverState; void OverState::enter(void) { mContinue = true; mGameOverOverlay = OverlayManager::getSingleton().getByName("Overlay/GameOver"); mGameOverOverlay->show(); } void OverState::exit(void) { mGameOverOverlay->hide(); } void OverState::pause(void) { std::cout << "OverState pause\n"; } void OverState::resume(void) { std::cout << "OverState resume\n"; } bool OverState::frameStarted(GameManager* game, const FrameEvent& evt) { return true; } bool OverState::frameEnded(GameManager* game, const FrameEvent& evt) { return mContinue; } bool OverState::keyPressed(GameManager* game, const OIS::KeyEvent &e) { switch(e.key) { case OIS::KC_SPACE: game->changeState(MenuState::getInstance()); break; case OIS::KC_ESCAPE: game->changeState(MenuState::getInstance()); break; case OIS::KC_DOWN: break; case OIS::KC_UP: break; } return true; }
#include "stdafx.h" #include "JNIBridge.Core.h" #include "JNIBridge.Core.Utils.h" using namespace JNIBridge::Core::Utils; /// <summary> /// The g singleton /// </summary> JNIBridge::Core::Interop* g_Singleton; typedef jint(*ptrLoadJvm) (JavaVM** pvm, void** penv, void* args); #pragma region "Generic lambdas" auto dynamicallyLoadJvm = [&](JavaVM** pvm, void** penv, void* args, std::wstring selectedJvm) -> jint { auto retval = 0; ptrLoadJvm loadJvm; HINSTANCE hInstance; if ((hInstance = LoadLibrary(selectedJvm.c_str())) != nullptr) { if ((loadJvm = (ptrLoadJvm)GetProcAddress(hInstance, "JNI_CreateJavaVM")) != nullptr) { retval = loadJvm(pvm, penv, args); } FreeLibrary(hInstance); } // auto jvm = JNI_CreateJavaVM(&m_JavaVm, (void**)&env, &initArgs); return retval; }; /// <summary> /// The get jni versionfrom string /// </summary> auto getJniVersionfromString = [=](const std::wstring& versionAsString) -> int { auto retval = 0; auto selectedVersion = versionAsString.c_str(); if (wcscmp(selectedVersion, L"JNI_VERSION_1_1") == 0) retval = JNI_VERSION_1_1; else if (wcscmp(selectedVersion, L"JNI_VERSION_1_2") == 0) retval = JNI_VERSION_1_2; else if (wcscmp(selectedVersion, L"JNI_VERSION_1_4") == 0) retval = JNI_VERSION_1_4; else if (wcscmp(selectedVersion, L"JNI_VERSION_1_6") == 0) retval = JNI_VERSION_1_6; else if (wcscmp(selectedVersion, L"JNI_VERSION_1_8") == 0) retval = JNI_VERSION_1_8; return retval; }; /// <summary> /// The get safe array element count /// </summary> auto getSafeArrayElementCount = [&](SAFEARRAY& arr) -> long { long lowerBound, upperBound, retval; SafeArrayGetLBound(&arr, 1, &lowerBound); SafeArrayGetUBound(&arr, 1, &upperBound); retval = upperBound - lowerBound + 1; return retval; }; /// <summary> /// The get j value from argument type /// </summary> auto getJValueFromArgType = [&](BSTR& type, VARIANT& arg) -> jvalue { jvalue retval; if (wcscmp(type, L"single") == 0 || wcscmp(type, L"float") == 0) { retval.f = arg.fltVal; } else if (wcscmp(type, L"integer") == 0) { retval.i = arg.intVal; } else if (wcscmp(type, L"byte") == 0) { retval.b = arg.bVal; } else if (wcscmp(type, L"char") == 0) { retval.c = arg.cVal; } else if (wcscmp(type, L"short") == 0) { retval.s = arg.iVal; } else if (wcscmp(type, L"long") == 0) { retval.j = arg.lVal; } else if (wcscmp(type, L"double") == 0) { retval.d = arg.dblVal; } else if (wcscmp(type, L"bool") == 0) { retval.z = (jboolean)arg.boolVal; } else { // We'll default to "object" (void*) // [CONSIDER] Other reference data types (e.g.: string) [CONSIDER] retval.l = *(reinterpret_cast<jobject*>(arg.byref)); } return retval; }; /// <summary> /// The format exceptions as string /// </summary> auto formatExceptionsAsString = [=](const std::vector<std::string>& exceptions) -> std::string { auto count = 0; std::string retval; std::for_each(exceptions.begin(), exceptions.end(), [&](std::string ex) { char buffer[50] = { '\0' }; _itoa_s(++count, buffer, sizeof(char[50]), 10); auto exCount = std::string("Exception # ").append(buffer); retval += exCount + "\n" + ex + "[----------------------]"; }); return retval; }; #pragma endregion #pragma region "Interop class" /// <summary> /// Initializes a new instance of the <see cref="Interop"/> class. /// </summary> JNIBridge::Core::Interop::Interop() { } /// <summary> /// Finalizes an instance of the <see cref="Interop"/> class. /// </summary> JNIBridge::Core::Interop::~Interop() { if (m_JavaVm != nullptr) m_JavaVm->DestroyJavaVM(); } /// <summary> /// Runs the java env checks. /// </summary> void JNIBridge::Core::Interop::RunJavaEnvChecks() { // For JVM to load properly, it's required to have two SymLinks pointing to bin & lib folders respectively. if (!CheckRequiredJreSymLinks(true)) throw std::exception("SymLinks to JRE aren't available. Unable to continue."); if (!CheckForJavaEnvVariables()) throw std::exception("Make sure JAVA_HOME and JRE_HOME environment variables exist. Unable to continue."); } /// <summary> /// Checks for java env variables. /// </summary> /// <returns></returns> bool JNIBridge::Core::Interop::CheckForJavaEnvVariables() { auto count = 0; auto retval = false; std::map<std::wstring, std::wstring&> var{ {L"JAVA_HOME", m_javaHome},{ L"JRE_HOME", m_jreHome } }; for (std::map<std::wstring, std::wstring&>::iterator it = var.begin(); it != var.end(); ++it) { wchar_t buffer[MAX_PATH]; if (GetEnvironmentVariable((*it).first.c_str(), buffer, MAX_PATH) > 0) { (*it).second = std::wstring(buffer); count++; } } retval = var.size() == count; return retval; } /// <summary> /// Checks the required jre sym links. /// </summary> /// <param name="deleteAndCreateIfExist">if set to <c>true</c> [delete and create if exist].</param> /// <returns></returns> bool JNIBridge::Core::Interop::CheckRequiredJreSymLinks(bool deleteAndCreateIfExist) { auto retval = false; auto libSymLinkName = m_configReader.GetSetting(L"SymLinkLibName"); auto binSymLinkName = m_configReader.GetSetting(L"SymLinkBinName"); auto libSymLinkTarget = m_configReader.GetSetting(L"SymLinkLibTarget"); auto binSymLinkTarget = m_configReader.GetSetting(L"SymLinkBinTarget"); std::map<std::wstring, std::wstring> symLinks = { { libSymLinkName , libSymLinkTarget }, { binSymLinkName, binSymLinkTarget } }; // Let's first check if SymLinks exist, otherwise we'll create them (Lambda to re-use later on) auto checkFunc = [&](std::map<std::wstring, std::wstring> symLinks, bool deleteAndCreateIfExists)->bool { auto index = 0; auto exists = true; auto successCount = 0; for (auto &x : symLinks) { if (!deleteAndCreateIfExists) { if (!(GetFileAttributes(x.first.c_str()) & FILE_ATTRIBUTE_REPARSE_POINT)) { exists = false; break; } } else { if (GetFileAttributes(x.first.c_str()) & FILE_ATTRIBUTE_REPARSE_POINT) RemoveDirectory(x.first.c_str()); if (CreateSymbolicLink(x.first.c_str(), x.second.c_str(), SYMBOLIC_LINK_FLAG_DIRECTORY)) successCount++; } index++; } return deleteAndCreateIfExists ? successCount == symLinks.size() : exists; }; retval = checkFunc(symLinks, deleteAndCreateIfExist); return retval; } /// <summary> /// Initializes the JVM. /// </summary> /// <param name="configFile">The configuration file.</param> /// <returns></returns> bool JNIBridge::Core::Interop::InitializeJvm(const char* configFile) { JNIEnv* env; auto retval = false; JavaVMInitArgs initArgs; m_configReader.ReadConfig(configFile); unique_ptr<JavaVMOption[]> javaVmOption; auto selectedJvm = m_configReader.GetSetting(L"SelectedJvm"); auto formatJarPathFromVector = [&](std::vector<std::wstring> jars) -> std::wstring { std::wstring jarPath; std::for_each(jars.begin(), jars.end(), [&](std::wstring jar) { jarPath += jar + L"; "; }); jarPath = jarPath.substr(0, jarPath.length() - 2); return jarPath; }; RunJavaEnvChecks(); // Let's check environment variables and symlinks exist m_jarFiles = GetJarFiles(JavaHome_get().append(L"\\jre\\lib\\"), L"jar"); auto nEnvVarPos = m_configReader.GetSetting(L"jvmOptions").find(L"%java_home%"); auto originalOption = m_configReader.GetSetting(L"jvmOptions"); auto allJars = originalOption.replace(nEnvVarPos, wcslen(L"%java_home%"), formatJarPathFromVector(m_jarFiles)); auto version = getJniVersionfromString(m_configReader.GetSetting(L"jniVersion")); auto optionCount = Common::ConvertWstringToChar(m_configReader.GetSetting(L"jvmOptionCount")); auto nOptions = atoi(optionCount.c_str()); javaVmOption = make_unique<JavaVMOption[]>(nOptions); auto options = Common::ConvertWstringToChar(allJars); javaVmOption[0].optionString = const_cast<char*>(options.c_str()); javaVmOption[1].optionString = const_cast<char*>(Common::ConvertWstringToChar(m_configReader.GetSetting(L"jvmInitialHeapSize")).c_str()); // 1MB javaVmOption[2].optionString = const_cast<char*>(Common::ConvertWstringToChar(m_configReader.GetSetting(L"jvmMaximumHeapSize")).c_str());; // 1GB initArgs.version = (jint)version; initArgs.nOptions = nOptions; initArgs.options = javaVmOption.get(); initArgs.ignoreUnrecognized = JNI_TRUE; try { auto jvm = dynamicallyLoadJvm(&m_JavaVm, (void**)&env, &initArgs, selectedJvm); retval = jvm == JNI_OK; } catch (exception &ex) { auto p = ex.what(); } return retval; } /// <summary> /// Jnis the version get. /// </summary> /// <returns></returns> jint JNIBridge::Core::Interop::JniVersion_get() const { return m_configReader.Settings_get().size() > 0 ? (int)getJniVersionfromString(m_configReader.GetSetting(L"jniVersion")) : -1; } /// <summary> /// Javas the env get. /// </summary> /// <returns></returns> JNIEnv* JNIBridge::Core::Interop::JavaEnv_get() const { jint result; JNIEnv* retval = nullptr; if (m_JavaVm != nullptr) { // If current thread is detached from JVM, we'll attempt to re-attach it one more time if (result = m_JavaVm->GetEnv((void**)&retval, JniVersion_get()) == JNI_EDETACHED) { if (m_JavaVm->AttachCurrentThread((void**)&retval, nullptr) != JNI_OK) retval = nullptr; } } return retval; } /// <summary> /// Gets the jar files. /// </summary> /// <param name="directoryPath">The directory path.</param> /// <param name="extension">The extension.</param> /// <returns></returns> std::vector<std::wstring> JNIBridge::Core::Interop::GetJarFiles(std::wstring directoryPath, std::wstring extension) { std::vector<std::wstring> retval; auto getFileExt = [&](const std::wstring s) -> std::wstring { std::wstring retval; auto nPos = s.rfind('.', s.length()); if (nPos != std::wstring::npos) retval = s.substr(nPos + 1, s.length() - nPos); return retval; }; std::function<void(std::wstring)> fileEnum = [&](std::wstring path) -> void { WIN32_FIND_DATA fi; auto searchPattern = std::wstring(path.c_str()).append(L"*.*"); auto found = FindFirstFile(searchPattern.c_str(), &fi); while (FindNextFile(found, &fi) != 0) { if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (wcscmp(fi.cFileName, L".") == 0 || wcscmp(fi.cFileName, L"..") == 0) continue; else fileEnum(path + fi.cFileName + L"\\"); } else if (getFileExt(fi.cFileName) == extension) { retval.push_back(path + fi.cFileName); } } }; if (directoryPath.size() > 0 && extension.size() > 0) fileEnum(directoryPath); return retval; } /// <summary> /// Javas the vm get. /// </summary> /// <returns></returns> JavaVM* JNIBridge::Core::Interop::JavaVM_get() const { return m_JavaVm; } /// <summary> /// Configurations the get. /// </summary> /// <returns></returns> JNIBridge::Config::ConfigReader& JNIBridge::Core::Interop::Config_get() const { return m_configReader; } /// <summary> /// Loadeds the jars get. /// </summary> /// <returns></returns> std::vector<std::wstring>& JNIBridge::Core::Interop::LoadedJars_get() const { return m_jarFiles; } /// <summary> /// Javas the home get. /// </summary> /// <returns></returns> std::wstring JNIBridge::Core::Interop::JavaHome_get() const { return m_javaHome; } /// <summary> /// Javas the home get. /// </summary> /// <returns></returns> std::wstring JNIBridge::Core::Interop::JreHome_get() const { return m_jreHome; } /// <summary> /// Gets the jni expection details. /// </summary> /// <param name="e">The e.</param> /// <param name="env">The env.</param> /// <returns></returns> std::string JNIBridge::Core::Interop::GetJniExpectionDetails(const jthrowable& e, JNIEnv** env) { jobject res; jclass clazz; jmethodID method; std::string retval; if (env != nullptr) { clazz = (*env)->FindClass("com/simplicity/Inspector"); method = (*env)->GetStaticMethodID(clazz, "extractExceptionDetails", "(Ljava/lang/Object;)Ljava/lang/String;"); res = (*env)->CallStaticObjectMethod(clazz, method, e); const char* val = (*env)->GetStringUTFChars((jstring)res, nullptr); retval = std::string(val); // Release JNI resources (*env)->ReleaseStringUTFChars((jstring)res, val); (*env)->DeleteLocalRef(res); (*env)->DeleteLocalRef(clazz); } return retval; } /// <summary> /// Checks for exceptions in JVM. /// </summary> /// <param name="env">The env.</param> /// <param name="exceptionsThrown">The exceptions thrown.</param> void JNIBridge::Core::Interop::CheckForExceptionsInJvm(JNIEnv* env, std::vector<std::string>& exceptionsThrown) { jthrowable ex = nullptr; if (env->ExceptionCheck() && (ex = env->ExceptionOccurred()) != nullptr) { exceptionsThrown.push_back(JNIBridge::Core::Interop::GetJniExpectionDetails(ex, &env)); env->ExceptionClear(); env->DeleteLocalRef(ex); } } /// <summary> /// Prepares the arguments. /// </summary> /// <param name="params">The parameters.</param> /// <param name="paramType">Type of the parameter.</param> /// <param name="args">The arguments.</param> void JNIBridge::Core::Interop::PrepareArgs(SAFEARRAY& params, SAFEARRAY& paramType, std::vector<jvalue>& args) { BSTR *pArgTypes; VARIANT *pArgValues; if (SUCCEEDED(SafeArrayAccessData(&params, (void**)&pArgValues)) && SUCCEEDED(SafeArrayAccessData(&paramType, (void**)&pArgTypes))) { auto cArgElements = getSafeArrayElementCount(params); auto cTypeElements = getSafeArrayElementCount(paramType); // Element count must match for both safearrays (1-1 ratio) if (cArgElements == cTypeElements) { for (auto idx = 0; idx < cArgElements; ++idx) { auto argType = pArgTypes[idx]; auto argument = pArgValues[idx]; args.push_back(getJValueFromArgType(argType, argument)); } } } } #pragma endregion #pragma region "Exported functions" /// <summary> /// Loads the JVM and jar. /// </summary> /// <param name="configFile">The configuration file.</param> /// <returns></returns> JNIBRIDGE_API HRESULT LoadJVMAndJar(const char* configFile) { HRESULT retval; if (g_Singleton == nullptr) { g_Singleton = new JNIBridge::Core::Interop; retval = g_Singleton->InitializeJvm(configFile) ? S_OK : S_FALSE; } else retval = S_OK; return retval; } /// <summary> /// Shutdowns the JVM. /// </summary> /// <returns></returns> JNIBRIDGE_API void ShutdownJvm() { if (g_Singleton != nullptr) delete g_Singleton; } /// <summary> /// Forces the gc. /// </summary> /// <returns></returns> JNIBRIDGE_API void ForceGC() { JNIEnv* env; jclass clazz; jmethodID method; if (g_Singleton != nullptr && (env = g_Singleton->JavaEnv_get()) != nullptr) { clazz = env->FindClass("java/lang/System"); method = env->GetStaticMethodID(clazz, "gc", "()V"); env->CallStaticObjectMethod(clazz, method); env->DeleteLocalRef(clazz); } } /// <summary> /// Runs the method in jar. /// </summary> /// <param name="className">Name of the class.</param> /// <param name="methodName">Name of the method.</param> /// <param name="isStatic">The is static.</param> /// <param name="methodProto">The method proto.</param> /// <param name="params">The parameters.</param> /// <param name="paramType">Type of the parameter.</param> /// <param name="arrayLength">Length of the array.</param> /// <param name="returnValue">The return value.</param> /// <param name="exceptions">The exceptions.</param> /// <param name="returnType">Type of the return.</param> /// <returns></returns> JNIBRIDGE_API HRESULT RunMethodInJar(const char* className, const char* methodName, BOOL isStatic, const char* methodProto, SAFEARRAY params, SAFEARRAY paramType, int arrayLength, const void* returnValue, char* exceptions, char* returnType) { JNIEnv* env; jclass clazz; va_list parameters; jobject res, object; HRESULT retval = S_FALSE; std::vector<jvalue> args; jmethodID method, constructor; std::vector<std::string> exceptionsThrown; if (g_Singleton != nullptr && (env = g_Singleton->JavaEnv_get()) != nullptr && className != nullptr && strlen(className) > 0 && methodName != nullptr && strlen(methodName) && methodProto != nullptr && strlen(methodProto) > 0 && returnValue != nullptr) { try { clazz = env->FindClass(className); constructor = env->GetMethodID(clazz, "<init>", "()V"); object = env->NewObject(clazz, constructor); method = env->GetMethodID(clazz, methodName, methodProto); // Let's call right method based on parameter count if (arrayLength == 0) { res = env->CallObjectMethod(object, method); } else { JNIBridge::Core::Interop::PrepareArgs(params, paramType, args); res = env->CallObjectMethodA(object, method, &args[0]); } // Let's get exception details (if any) JNIBridge::Core::Interop::CheckForExceptionsInJvm(env, exceptionsThrown); // If exceptions were thrown, we'll copy string into exceptions (reference parameter) if (exceptionsThrown.size() > 0) { auto exceptionAsStr = formatExceptionsAsString(exceptionsThrown); strcpy_s(exceptions, sizeof(char[Max_BufferSizeForMessagesFromJni]), exceptionAsStr.c_str()); } retval = exceptionsThrown.size() == 0 ? S_OK : S_FALSE; // Return result to CLR via a callback if (strcmp(returnType, "single") == 0 || strcmp(returnType, "float") == 0) { ((ptrClrDelegateForFloat)returnValue)(*(reinterpret_cast<jfloat*>(&res))); } else if (strcmp(returnType, "integer") == 0) { ((ptrClrDelegateForInteger)returnValue)(*(reinterpret_cast<jint*>(&res))); } else if (strcmp(returnType, "byte") == 0) { ((ptrClrDelegateForByte)returnValue)(*(reinterpret_cast<jbyte*>(&res))); } else if (strcmp(returnType, "char") == 0) { ((ptrClrDelegateForChar)returnValue)(*(reinterpret_cast<jchar*>(&res))); } else if (strcmp(returnType, "short") == 0) { ((ptrClrDelegateForShort)returnValue)(*(reinterpret_cast<jshort*>(&res))); } else if (strcmp(returnType, "long") == 0) { ((ptrClrDelegateForLong)returnValue)(*(reinterpret_cast<jlong*>(&res))); } else if (strcmp(returnType, "double") == 0) { ((ptrClrDelegateForDouble)returnValue)(*(reinterpret_cast<jdouble*>(&res))); } else if (strcmp(returnType, "bool") == 0) { ((ptrClrDelegateForBoolean)returnValue)(*(reinterpret_cast<jboolean*>(&res))); } else { // We'll default to "object" (void*) // [CONSIDER] Other reference data types (e.g.: string) [CONSIDER] ((ptrClrDelegateForObject)returnValue)(*(reinterpret_cast<jobject*>(&res))); } // Release JNI Resources env->DeleteLocalRef(object); env->DeleteLocalRef(clazz); } catch (std::exception& e) { auto p = e.what(); } } return retval; } /// <summary> /// Serializes the methods in jar. /// </summary> /// <param name="jarFile">The jar file.</param> /// <param name="xmlPath">The XML path.</param> /// <param name="exceptions">The exceptions.</param> /// <returns></returns> JNIBRIDGE_API HRESULT SerializeMethodsInJar(const char* jarFile, const char* xmlPath, char* exceptions) { JNIEnv* env; jclass clazz; jstring jFile; jobject res, object; HRESULT retval = S_FALSE; jmethodID method, constructor; std::vector<std::string> exceptionsThrown; if (g_Singleton != nullptr && (env = g_Singleton->JavaEnv_get()) != nullptr && jarFile != nullptr && strlen(jarFile) > 0 && xmlPath != nullptr && strlen(xmlPath)) { try { // Create instance of Inspector and call getMethodsInClasses jFile = env->NewStringUTF(jarFile); clazz = env->FindClass("com/simplicity/Inspector"); constructor = env->GetMethodID(clazz, "<init>", "()V"); object = env->NewObject(clazz, constructor); method = env->GetMethodID(clazz, "getMethodsInClasses", "(Ljava/lang/String;)Ljava/util/Map;"); res = env->CallObjectMethod(object, method, jFile); JNIBridge::Core::Interop::CheckForExceptionsInJvm(env, exceptionsThrown); // Create instance of InspectorSerialized and serialize methods information jFile = env->NewStringUTF(xmlPath); clazz = env->FindClass("com/simplicity/InspectorSerializer"); constructor = env->GetMethodID(clazz, "<init>", "()V"); object = env->NewObject(clazz, constructor); method = env->GetMethodID(clazz, "serializeReflectedMethods", "(Ljava/util/Map;Ljava/lang/String;)Z"); retval = (jboolean)env->CallObjectMethod(object, method, res, jFile) == 1 ? S_OK : S_FALSE; JNIBridge::Core::Interop::CheckForExceptionsInJvm(env, exceptionsThrown); // If exceptions were thrown, we'll copy string into exceptions (reference parameter) if (exceptionsThrown.size() > 0) { auto exceptionAsStr = formatExceptionsAsString(exceptionsThrown); strcpy_s(exceptions, sizeof(char[Max_BufferSizeForMessagesFromJni]), exceptionAsStr.c_str()); } // Release JNI resources env->DeleteLocalRef(res); env->DeleteLocalRef(object); env->DeleteLocalRef(clazz); env->ReleaseStringUTFChars(jFile, nullptr); } catch (std::exception& e) { auto p = e.what(); } } return retval; } /// <summary> /// Adds the path. /// </summary> /// <param name="jarFile">The jar file.</param> /// <param name="result">The result.</param> /// <param name="exceptions">The exceptions.</param> /// <returns></returns> JNIBRIDGE_API HRESULT AddPath(const char* jarFile, char* result, char* exceptions) { JNIEnv* env; jobject res; jclass clazz; jstring jFile; jmethodID method; HRESULT retval = S_FALSE; std::vector<std::string> exceptionsThrown; if (g_Singleton != nullptr && (env = g_Singleton->JavaEnv_get()) != nullptr && jarFile != nullptr && strlen(jarFile) > 0) { try { jFile = env->NewStringUTF(jarFile); clazz = env->FindClass("com/simplicity/Inspector"); method = env->GetStaticMethodID(clazz, "addPath", "(Ljava/lang/String;)Ljava/lang/String;"); res = env->CallStaticObjectMethod(clazz, method, jFile); const char* val = env->GetStringUTFChars((jstring)res, nullptr); auto resLength = strlen(val); strcpy_s(result, sizeof(char[MAX_PATH]), val); JNIBridge::Core::Interop::CheckForExceptionsInJvm(env, exceptionsThrown); // If exceptions were thrown, we'll copy string into exceptions (reference parameter) if (exceptionsThrown.size() > 0) { auto exceptionAsStr = formatExceptionsAsString(exceptionsThrown); strcpy_s(exceptions, sizeof(char[Max_BufferSizeForMessagesFromJni]), exceptionAsStr.c_str()); } // Release JNI resources env->ReleaseStringUTFChars(jFile, val); env->DeleteLocalRef(res); env->DeleteLocalRef(clazz); env->DeleteLocalRef(jFile); retval = resLength > 0 ? S_OK : S_FALSE; } catch (std::exception& e) { auto p = e.what(); } } return retval; } #pragma endregion
#include <iostream> using namespace std; // Generic Programming - Ignore class Node { public: // Data int data; // Pointer to the next Node Node * next; // Construct that makes the ptr to NULL Node() { next = NULL; } }; class LinkedList { // Head + Circles inside linked with each other public: // Head -> Node type ptr Node * head; Node * tail; // Construct LinkedList() { head = NULL; tail = NULL; } // Circles inside linked with each other // Rules how circles will be linked // Insert void insert(int value) { // If 1st Node is added Node * temp = new Node; // Insert value in the node temp->data = value; // 1st Node only. if (head == NULL) { head = temp; } // Any other Node only. else { tail->next = temp; } tail = temp; } void insertAt(int n, int value) { // Reach the place before the pos // Create a node Node * temp1 = new Node; //set the data field temp1->data = value; //set the link or the next temp1->next = NULL; //condition if temp1 == head if (n == 1) { temp1->next = head; head = temp1; return; } Node * temp2 = head; for (int i = 0; i = n - 2; i++) { temp2 = temp2->next; } // Moving ptrs like magic ! if not head temp1->next = temp2->next; temp2->next = temp1; // Update the code for 1st position } void count() { Node *temp = head; int length = 0; while (temp != NULL) { length++; temp = temp->next; } cout << " The total number of nodes in this linkedlist is : " << length << endl; } // Deletion of last element void delet() { // store the tail in temp Node * temp = tail; // before tail has to point to null Node * current = head; while (current->next != tail) { current = current->next; } current->next = NULL; // update tail tail = current; // delete temp delete temp; } // Display void display() { Node * current = head; while (current != NULL) { cout << current->data << "->"; current = current->next; } cout << endl; } }; int main() { LinkedList l1; l1.insert(1); l1.insert(2); l1.insert(3); l1.display(); l1.delet(); l1.display(); l1.insertAt(1, 8); l1.display(); l1.count(); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2007-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef POSIX_OK_DNS # ifndef THREAD_SUPPORT #warning "You *really* want THREAD_SUPPORT with this host resolver !" /* If this implementation is used single-threaded, your application is severely * likely to stall for protracted periods from time to time. It has also never * been tested without THREAD_SUPPORT, although reasonable efforts have been * taken to ensure the design should still work in that case, albeit with * delays. * * It would be possible to implement a separate process serving instead of a * thread in support of this, if there's a serious need to do so. Contact the * module owner if you think you need that - but try using threads, first ! */ # endif // THREAD_SUPPORT #include "modules/hardcore/mh/messobj.h" // MessageObject #include "modules/hardcore/mh/mh.h" // MessageHandler (g_main_message_handler) #include "platforms/posix/posix_system_info.h" // for GetLocalHostName #include "platforms/posix/src/posix_async.h" // PendingDNSOp #include "platforms/posix/posix_native_util.h" // NativeString #include "platforms/posix/posix_logger.h" // PosixLogger #include "platforms/posix/net/posix_network_address.h" // PosixNetworkAddress, <netdb.h>, ipv[46]_addr #include "platforms/posix/posix_mutex.h" // PosixMutex #ifdef PREFS_HAVE_PREFER_IPV6 # include "modules/prefs/prefsmanager/collections/pc_network.h" # define PREFS_PREFER_IPV6 g_pcnet->GetIntegerPref(PrefsCollectionNetwork::PreferIPv6) #else # define PREFS_PREFER_IPV6 true #endif // PREFS_HAVE_PREFER_IPV6 #if defined(POSIX_DNS_USE_RES_INIT) || defined(POSIX_DNS_USE_RES_NINIT) # include <resolv.h> /** * This macro can be used to resolve a hostname with expression expr. If * the condition cond is true, ResolveInit() is called and we * try again to resolve a hostname with expression expr. * * @note The second call to resolve the hostname is only executed if * the specified condition is true and the PosixHostResolver::Worker * instance is still alive. When the PosixHostResolver::Worker has * been aborted by its boss, there is no need to continue the work. * * @param var a variable that receives the result of expr. * @param cond is a condition on which to call ResolveInit() and try to resolve * the hostname again. This condition should test if the first call to * resolve the hostname was not successful. * @param expr is the expression to resolve the hostname. */ # define ResolveMaybeInit(var, cond, expr) \ var = expr; \ if (cond && Live() && ResolveInit()) var = expr #else // !(POSIX_DNS_USE_RES_INIT or POSIX_DNS_USE_RES_NINIT) # define ResolveMaybeInit(var, cond, expr) var = expr #endif // POSIX_DNS_USE_RES_INIT or POSIX_DNS_USE_RES_NINIT #include <sys/socket.h> #include <netdb.h> #undef USING_HOSTENT #ifdef POSIX_DNS_IPNODE #define USING_HOSTENT #endif #ifdef POSIX_DNS_GETHOSTBYNAME #define USING_HOSTENT #endif // POSIX_DNS_GETHOSTBYNAME /** Implement OpHostResolver. * * This implementation can only Resolve() during the lifetime of g_opera. * * \msc * core,PosixHostResolver,Worker,Executor,PosixAsyncManager,process_queue; * core=>PosixHostResolver [label="creates"]; * core=>PosixHostResolver [label="1. Resolve()", url="\ref PosixHostResolver::Resolve"]; * PosixHostResolver=>Worker [label="2. creates"]; * PosixHostResolver=>Executor [label="3. creates"]; * Executor=>Executor [label="4. Enqueue()", url="\ref PosixAsyncManager::PendingOp::Enqueue()"]; * Executor=>PosixAsyncManager [label="4. Queue(this)", url="\ref PosixAsyncManager::Queue()"]; * PosixAsyncManager=>process_queue [label="5. starts thread"]; * core<<process_queue; * --- [label="on the started process_queue thread:"]; * process_queue:>PosixAsyncManager [label="6. Process()", url="\href PosixAsyncManager::Process()", linecolor="red"]; * PosixAsyncManager:>Executor [label="7. Run()", url="\href PosixAsyncManager::Executor::Run()", linecolor="red"]; * Executor:>Worker [label="8. Resolve()", url="\href PosixHostResolver::Worker::Resolve()", linecolour="red"]; * Executor<<Worker; * Executor->PosixHostResolver [label="9. MSG_POSIX_ASYNC_DONE"]; * Executor>>process_queue; * --- [label="on the core thread:"]; * core=>PosixHostResolver [label="10. HandleCallback()", url="\ref PosixHostResolver::HandleCallback()"]; * PosixHostResolver=>>core [label="11. OnHostResolved()", url="\ref OpHostResolverListener::OnHostResolved()"]; * core=>PosixHostResolver [label="GetAddressCount()", url="\ref PosixHostResolver::GetAddressCount()"]; * core=>PosixHostResolver [label="GetAddress()", url="\ref PosixHostResolver::GetAddress()"]; * core=>PosixHostResolver [label="destroy"]; * PosixHostResolver=>Executor [label="destroy"]; * PosixHostResolver=>Worker [label="destroy"]; * \endmsc * * -# core calls OpHostResolver::Resolve() to resolve the specified hostname. * -# PosixHostResolver::Resolve() creates an instance of * PosixHostResolver::Worker (#m_worker) and registers itself as the * MessageObject callback for the message MSG_POSIX_ASYNC_DONE with * the new worker instance as first argument. * -# PosixHostResolver::Resolve() creates an instance of * PosixHostResolver::Executor. The PosixHostResolver::Worker * instance is the executor's job and the PosixHostResolver is the * executor's boss. * -# The PosixHostResolver::Executor instance adds itself to the * queue of pending operations (instances of * PosixAsyncManager::PendingOp) by calling PendingOp::Enqueue(), * which calls PosixAsyncManager::Queue(). * -# PosixAsyncManager::Queue() may start a new \c process_queue * thread, which will handle one by one PendingOp instance which is * available in the PosixAsyncManager's queue. * -# The thread \c process_queue calls PosixAsyncManager::Process(). * -# PosixAsyncManager::Process() eventually handles the enqueued * PosixHostResolver::Executor by calling * PosixHostResolver::Executor::Run(). * -# PosixHostResolver::Executor::Run() calls * PosixHostResolver::Worker::Resolve() to perform the resolving job. * -# When the job is done, PosixHostResolver::Executor::Run() posts * the message MSG_POSIX_ASYNC_DONE to the PosixHostResolver instance. * -# PosixHostResolver::HandleCallback() handles the message * MSG_POSIX_ASYNC_DONE by calling ... * -# ... OpHostResolverListener::OnHostResolved(). Now core can call * GetAddressCount() and GetAddress() to retrieve the resolved addresses. */ class PosixHostResolver : public OpHostResolver, public PosixLogger, public MessageObject { /** Carriers for the results of a look-up; see m_answer4 and m_answer6. */ template<typename addr_t> class Answer { size_t m_count; addr_t m_addrs[1]; Answer() {} public: static Answer* Create(size_t count) { Answer *answer = reinterpret_cast<Answer*>(g_thread_tools->Allocate(sizeof(size_t) + sizeof(addr_t)*count)); if (answer) answer->m_count = count; return answer; } size_t Count() const { return m_count; } const addr_t &Get(int i) const { OP_ASSERT(i >= 0 && (size_t)i < m_count); return m_addrs[i]; } /** Overload operator delete. * * Answer objects are allocated on non-core thread, so must be deallocated * via g_thread_tools (which is responsible for ensuring it's done * thread-safely). */ void operator delete(void* p) { g_thread_tools->Free(p); } #ifdef USING_HOSTENT void Copy(char **data) { if (!m_addrs) return; for (size_t i = 0; i < m_count; i++) { OP_ASSERT(data[i]); m_addrs[i] = *reinterpret_cast<addr_t*>(data[i]); } OP_ASSERT(!data[m_count]); } #endif // USING_HOSTENT #ifdef POSIX_DNS_GETADDRINFO inline void Ingest(struct sockaddr *addr, socklen_t len, size_t i); inline void Digest(struct addrinfo *info, int family) { if (!m_addrs) return; size_t i = 0; while (info) { if (info->ai_family == family) { OP_ASSERT(info->ai_addr->sa_family == family); Ingest(info->ai_addr, info->ai_addrlen, i); i++; } info = info->ai_next; } OP_ASSERT(i == m_count); } #endif // POSIX_DNS_GETADDRINFO }; /** * The worker class does the actual job of resolving the hostname. * * The PosixHostResolver instance that created the worker is the * worker's boss (#m_boss) and the worker instance is stored as * #PosixHostResolver::m_worker. */ class Worker : public MessageObject #if defined(POSIX_DNS_LOCKING) || defined(POSIX_DNS_USE_RES_INIT) , public PosixAsyncManager::Resolver // provides Get*Mutex() #endif // POSIX_DNS_LOCKING or POSIX_DNS_USE_RES_INIT , public PosixLogger { // Being capable of resolving and remembering the answers: Answer<ipv4_addr> *m_answer4; #ifdef POSIX_SUPPORT_IPV6 Answer<ipv6_addr> *m_answer6; #endif #ifdef POSIX_SUPPORT_IPV6 static bool IsIPv6OK() { return g_opera && g_opera->posix_module.GetIPv6Support(); } static bool IsIPv6Usable() { return g_opera && g_opera->posix_module.GetIPv6Usable(); } #endif #ifdef USING_HOSTENT void Store4(struct hostent* data) { OP_ASSERT(!m_answer4); OP_ASSERT(data->h_addrtype == AF_INET); const size_t n = HostentCount(data); if (n) { m_answer4 = Answer<ipv4_addr>::Create(n); if (m_answer4) m_answer4->Copy(&(data->h_addr)); } } # ifdef POSIX_SUPPORT_IPV6 void Store6(struct hostent* data) { OP_ASSERT(!m_answer6); OP_ASSERT(data->h_addrtype == AF_INET6); const size_t n = IsIPv6OK() ? HostentCount(data) : 0; if (n) { m_answer6 = Answer<ipv6_addr>::Create(n); if (m_answer6) m_answer6->Copy(&(data->h_addr)); } } # endif // POSIX_SUPPORT_IPV6 #endif // USING_HOSTENT #if defined(POSIX_DNS_USE_RES_INIT) || defined(POSIX_DNS_USE_RES_NINIT) /** Returns true if res_init() / res_ninit() was successful. */ bool ResolveInit() { # ifdef POSIX_DNS_USE_RES_NINIT return 0 == res_ninit(&_res); # else // POSIX_DNS_USE_RES_INIT bool success = false; POSIX_MUTEX_LOCK(&(GetResInitMutex())); success = 0 == res_init(); POSIX_MUTEX_UNLOCK(&(GetResInitMutex())); return success; # endif // POSIX_DNS_USE_RES_NINIT } #endif // POSIX_DNS_USE_RES_INIT or POSIX_DNS_USE_RES_NINIT public: OpHostResolver::Error Resolve(); void DigestAddrs(struct addrinfo *const info, const char *name); UINT Count() { return (m_answer4 ? m_answer4->Count() : 0) #ifdef POSIX_SUPPORT_IPV6 + (m_answer6 ? m_answer6->Count() : 0) #endif ; } OP_STATUS Get(UINT index, #ifdef POSIX_SUPPORT_IPV6 bool prefer_v6, #endif PosixNetworkAddress *addr); private: // Being a worker object whose boss might vanish with no warning OP_STATUS SetAsCallback() { if (g_main_message_handler == 0) { PosixLogger::Log(PosixLogger::DNS, PosixLogger::TERSE, "No main message handler" " - can't register host resolver with it\n"); return OpStatus::ERR_NULL_POINTER; } return g_main_message_handler->SetCallBack(this, MSG_POSIX_ASYNC_DONE, (MH_PARAM_1)this); } const PosixNativeUtil::NativeString m_hostname; protected: PosixHostResolver *m_boss; public: virtual const char *SoughtName() const { return m_hostname.get(); } Worker(PosixHostResolver *boss, const uni_char *hostname) : PosixLogger(DNS) , m_answer4(0) #ifdef POSIX_SUPPORT_IPV6 , m_answer6(0) #endif , m_hostname(hostname) , m_boss(boss) {} OP_STATUS Ready() { return m_hostname.Ready(); } ~Worker() { if (g_main_message_handler) g_main_message_handler->UnsetCallBacks(this); OP_DELETE(m_answer4); #ifdef POSIX_SUPPORT_IPV6 OP_DELETE(m_answer6); #endif } /* MessageObject API: */ virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); OP_STATUS Abort() { OP_ASSERT(m_boss); if (g_main_message_handler && m_boss) g_main_message_handler->RemoveCallBacks(m_boss, (MH_PARAM_1) this); m_boss = 0; return SetAsCallback(); } bool Live() { return m_boss != 0; } } *m_worker; #ifdef SYNCHRONOUS_HOST_RESOLVING // <refugee> Class should be local to ResolveSync(), but gcc 2.95 can't cope. class LocalWorker : public Worker { public: LocalWorker(PosixHostResolver *boss, const uni_char *hostname) : Worker(boss, hostname) { m_boss->ClearWorker(); m_boss->m_worker = this; } ~LocalWorker() { OP_ASSERT(m_boss->m_worker == this); m_boss->m_worker = NULL; } }; friend class LocalWorker; // </refugee> #endif // SYNCHRONOUS_HOST_RESOLVING // <refugee> Class should be local to Resolve(), but gcc 2.95 can't cope. class Executor : public PosixAsyncManager::PendingDNSOp { Worker *m_job; public: Executor(Worker *job, OpHostResolver *boss) : PosixAsyncManager::PendingDNSOp(boss) , m_job(job) { Enqueue(); } virtual ~Executor() { OP_DELETE(m_job); } /** * Runs the resolving job by calling Worker::Resolve(). The result is * posted with the message MSG_POSIX_ASYNC_DONE to the core thread. * * @note This method is called on one of the PosixAsyncManager threads. */ virtual void Run() { Done(m_job->Resolve()); } // Don't actually lock here: Run() takes too long virtual bool TryLock() { if (m_job->Live()) return true; /* m_job->Live() returning false means that m_job->Abort() has been * called, i.e. the boss (PosixHostResolver) has no longer a * reference to the Worker instance m_job. So ensure that m_job * deletes itself on handling MSG_POSIX_ASYNC_DONE (the job is its * own message handler after calling Worker::Abort()): */ Done(OpHostResolver::NETWORK_NO_ERROR); return false; } private: void Done(OpHostResolver::Error result) { MH_PARAM_1 job = reinterpret_cast<MH_PARAM_1>(m_job); m_job = 0; PosixAsyncManager::PostSyncMessage(MSG_POSIX_ASYNC_DONE, job, (MH_PARAM_2) result); } }; // </refugee> // see OpHostResolver's enum Error for possible error values. OpHostResolverListener * const m_listener; /** * This attribute is true if the associated Worker instance m_worker has * finished its resolver process. HandleCallback() sets this attribute to * true on receiving the message MSG_POSIX_ASYNC_DONE. * * The attribute is initialized with false. On starting a new Resolve() * job, i.e. on creating a Worker instance and handing it to the resolver * thread, the attribute is set to false as well. * * This means that if the attribute is true, then the m_worker instance is * no longer referenced by any resolver thread and the instance can be * deleted safely. If the attribute is false, then the worker instance is * still used on some resolver thread and Worker::Abort() must be called * instead of deleting the instance. See ClearWorker(). */ bool m_done; /** * Deletes the Worker instance and sets m_worker to 0 and m_done to false. * If the Worker instance is still referenced by a resolver thread, then * Worker::Abort() is called instead of deleting the instance directly. * Worker::Abort() causes the Worker::HandleCallback() to delete itself * on receiving the MSG_POSIX_ASYNC_DONE. */ void ClearWorker() { if (m_done) { OP_DELETE(m_worker); m_worker = 0; m_done = false; } else if (m_worker) { /* Worker::HandleCallback() will delete itself on handling the * message MSG_POSIX_ASYNC_DONE: */ m_worker->Abort(); m_worker = 0; } } #ifdef POSIX_SUPPORT_IPV6 const bool m_prefer_ipv6; /* TODO: FIXME: conform to RFC 3484 ! * http://www.rfc-editor.org/rfc/rfc3484.txt */ #endif #ifdef USING_HOSTENT static size_t HostentCount(struct hostent *data) { # ifdef h_addr size_t n = 0; while (data->h_addr_list[n]) n++; return n; # else return data->h_addr ? 1 : 0; # endif } #endif // USING_HOSTENT friend class PosixHostResolver::Worker; #ifdef USING_HOSTENT static Error ByName2OpHost(int err, Error prior, const char *name) { // Where should OOM fit into this (if at all) ? switch (err) { case 0: // if (prior != NETWORK_NO_ERROR) return OpHostResolver::ERROR_HANDLED; return NETWORK_NO_ERROR; case NO_ADDRESS: if (prior != NETWORK_NO_ERROR) return HOST_ADDRESS_NOT_FOUND; break; case HOST_NOT_FOUND: if (prior != NETWORK_NO_ERROR && prior != HOST_ADDRESS_NOT_FOUND) return HOST_NOT_AVAILABLE; break; case TRY_AGAIN: if (prior != NETWORK_NO_ERROR && prior != HOST_ADDRESS_NOT_FOUND && prior != HOST_NOT_FOUND) return TIMED_OUT; break; case NO_RECOVERY: if (prior != NETWORK_NO_ERROR && prior != HOST_ADDRESS_NOT_FOUND && prior != HOST_NOT_FOUND) return NETWORK_ERROR; break; default: PosixLogger::Log(PosixLogger::DNS, TERSE, "Undocumented return (%d) from host lookup on (%s)\n", err, name); # if 0 if (prior != NETWORK_NO_ERROR && prior != NETWORK_ERROR && prior != HOST_ADDRESS_NOT_FOUND && prior != HOST_NOT_FOUND) return ERR_GENERIC; // what should we return in this case ? # endif } return prior; } #endif // USING_HOSTENT #ifdef POSIX_DNS_GETADDRINFO static Error GetAddr2OpHost(int err, const char *name) { switch (err) { case EAI_AGAIN: // temporary failure Log(DNS, NORMAL, "Temporary failure (%d) looking up %s\n", err, name); return TIMED_OUT; case EAI_MEMORY: // OOM Log(DNS, TERSE, "OOMed (%d) looking up %s\n", err, name); return OUT_OF_MEMORY; case EAI_NONAME: // no host with this name case EAI_FAIL: // non-recoverable error case EAI_SYSTEM: // system error #ifdef POSIX_HAS_EAI_OVERFLOW // The error code EAI_OVERFLOW indicates "An argument buffer // overflowed." EAI_OVERFLOW was created to provide a meaningful error // code for the getnameinfo() function, for the case where the buffers // provided by the caller were too small. The EAI_OVERFLOW error code // is not applicable to getaddrinfo(), which has no buffer arguments // to overflow. EAI_OVERFLOW was mistakenly added to the getaddrinfo() // page rather than the getnameinfo() page. The tweak // TWEAK_POSIX_HAS_EAI_OVERFLOW controls whether or not this symbol is // defined and if the code should check for it. case EAI_OVERFLOW: // argument buffer overflowed (?) #endif // POSIX_HAS_EAI_OVERFLOW Log(DNS, NORMAL, "Failed (%d) looking up %s\n", err, name); return NETWORK_ERROR; // None of these should be possible: case EAI_SERVICE: // unknown service name case EAI_SOCKTYPE: // unknown hints.ai_socktype case EAI_FAMILY: // unrecognised hints.ai_family case EAI_BADFLAGS: // bad hints.ai_flags Log(DNS, TERSE, "Internal error (%d) looking up %s\n", err, name); OP_ASSERT(!"How did that happen ?"); return NETWORK_ERROR; case 0: OP_ASSERT(!"Should have been handled by caller"); break; default: OP_ASSERT(!"Undocumented return from getaddrinfo()"); Log(DNS, TERSE, "Undocumented return, %d, from getaddrinfo(%s)", err, name); break; } return NETWORK_ERROR; // or what ? } void DigestAddrs(struct addrinfo *const info, const char *name); #endif // POSIX_DNS_GETADDRINFO public: PosixHostResolver() : PosixLogger(DNS), m_worker(0), m_listener(0), m_done(false) #ifdef POSIX_SUPPORT_IPV6 , m_prefer_ipv6(g_opera && g_opera->posix_module.GetIPv6Usable() && PREFS_PREFER_IPV6) #endif {} PosixHostResolver(OpHostResolverListener* listener) : PosixLogger(DNS), m_worker(0), m_listener(listener), m_done(false) #ifdef POSIX_SUPPORT_IPV6 , m_prefer_ipv6(g_opera && g_opera->posix_module.GetIPv6Usable() && PREFS_PREFER_IPV6) #endif {} virtual ~PosixHostResolver(); OP_STATUS SetAsCallback(Worker * job) { if (g_main_message_handler == 0) { Log(TERSE, "No main message handler" " - can't register host resolver with it\n"); return OpStatus::ERR_NULL_POINTER; } return g_main_message_handler->SetCallBack( this, MSG_POSIX_ASYNC_DONE, (MH_PARAM_1)job); } /** * @name Implementation of the MessageObject API: * @{ */ virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); /** @} */ /** * @name Implementation of the OpHostResolver API * @{ */ // Only required to handle one request at a time. virtual OP_STATUS Resolve(const uni_char* hostname); #ifdef SYNCHRONOUS_HOST_RESOLVING virtual OP_STATUS ResolveSync(const uni_char* hostname, OpSocketAddress* socket_address, Error* error); #endif // SYNCHRONOUS_HOST_RESOLVING // Always synchronous: virtual OP_STATUS GetLocalHostName(OpString* local_hostname, Error* error); // For listener->OnHostResolved(this) to call back to: virtual UINT GetAddressCount() { return m_worker ? m_worker->Count() : 0; } virtual OP_STATUS GetAddress(OpSocketAddress* socket_address, UINT index); /** @} */ }; #ifdef POSIX_DNS_GETADDRINFO template<> inline void PosixHostResolver::Answer<ipv4_addr>::Ingest(struct sockaddr *info, socklen_t len, size_t i) { OP_ASSERT(len == sizeof(struct sockaddr_in)); OP_ASSERT(i < m_count && m_addrs); m_addrs[i] = reinterpret_cast<struct sockaddr_in *>(info)->sin_addr; } # ifdef POSIX_SUPPORT_IPV6 template<> inline void PosixHostResolver::Answer<ipv6_addr>::Ingest(struct sockaddr *info, socklen_t len, size_t i) { OP_ASSERT(len == sizeof(struct sockaddr_in6)); OP_ASSERT(i < m_count && m_addrs); m_addrs[i] = reinterpret_cast<struct sockaddr_in6 *>(info)->sin6_addr; } # endif // POSIX_SUPPORT_IPV6 void PosixHostResolver::Worker::DigestAddrs(struct addrinfo *const info, const char *name) { int n4 = 0, n6 = 0; for (struct addrinfo *run = info; run; run = run->ai_next) if (run->ai_family == AF_INET) n4++; else { #ifdef POSIX_SUPPORT_IPV6 OP_ASSERT(run->ai_family == AF_INET6); #endif n6++; } OP_ASSERT(!m_answer4); if (n4) { m_answer4 = Answer<ipv4_addr>::Create(n4); if (m_answer4) m_answer4->Digest(info, AF_INET); Log(VERBOSE, "Found %d IPv4 address%s for %s\n", n4, n4 == 1 ? "" : "es", name); } #ifdef POSIX_SUPPORT_IPV6 OP_ASSERT(!m_answer6); #endif if (n6) { #ifdef POSIX_SUPPORT_IPV6 OP_ASSERT(IsIPv6OK()); m_answer6 = Answer<ipv6_addr>::Create(n6); if (m_answer6) m_answer6->Digest(info, AF_INET6); Log(VERBOSE, "Found %d IPv6 address%s for %s\n", n6, n6 == 1 ? "" : "es", name); #else OP_ASSERT(!"Got IPv6 addresses when asking only for IPv4"); Log(TERSE, "DNS supplied %d IPv6 address%s when asked only for IPv4, for %s\n", n6, n6 > 1 ? "es" : "", name); #endif } } #endif // POSIX_DNS_GETADDRINFO #ifdef POSIX_DNS_GETHOSTBYNAME # if defined(POSIX_GHBN2) || defined(POSIX_GHBN_2R6) || defined(POSIX_GHBN_2R7) #define USING_GHBN2 # endif /** Glue class to unify the many gethostbyname variants. */ class HostByName { #ifdef GHBN_BUFFER_SIZE char m_buffer[GHBN_BUFFER_SIZE]; // ARRAY OK 2010-08-12 markuso struct hostent m_hostent; #elif defined(POSIX_GHBN_R3) struct hostent_data m_buffer; struct hostent m_hostent; #endif const char *const m_name; int m_error; bool m_oom; public: HostByName(const char *name) : m_name(name), m_error(0), m_oom(false) {} #ifdef USING_GHBN2 struct hostent *Get(int type); #else struct hostent *Get(); #endif int Error(bool &oom) { if (m_oom) oom = true; return m_error; } }; # ifdef POSIX_GHBN_2R7 // linux inline struct hostent *HostByName::Get(int type) { struct hostent *res = 0; int err = gethostbyname2_r(m_name, type, &m_hostent, m_buffer, GHBN_BUFFER_SIZE, &res, &m_error); if (err == ENOMEM || err == ENOBUFS) m_oom = true; else if (res) m_error = 0; return res; } # elif defined(POSIX_GHBN_2R6) // QNX inline struct hostent *HostByName::Get(int type) { errno = 0; struct hostent *res = gethostbyname2_r(m_name, type, &m_hostent, m_buffer, GHBN_BUFFER_SIZE, &m_error); if (errno == ENOMEM || errno == ENOBUFS) m_oom = true; else if (res) m_error = 0; return res; } # elif defined(POSIX_GHBN_R5) // SunOS inline struct hostent *HostByName::Get() { errno = 0; struct hostent *res = gethostbyname_r(m_name, &m_hostent, m_buffer, GHBN_BUFFER_SIZE, &m_error); if (errno == ENOMEM || errno == ENOBUFS) m_oom = true; else if (res) m_error = 0; return res; } # elif defined(POSIX_GHBN_R3) // HP/UX inline struct hostent *HostByName::Get() { int err = gethostbyname_r(m_name, &m_hostent, &m_buffer); if (err == 0) { m_error = 0; return &m_hostent; } if (err == ENOMEM || err == ENOBUFS) m_oom = true; return 0; } # elif defined(POSIX_GHBN2) // not thread-safe inline struct hostent *HostByName::Get(int type) { errno = 0; h_errno = 0; struct hostent *res = gethostbyname2(m_name, type); m_error = res ? 0 : h_errno; if (errno == ENOMEM || errno == ENOBUFS) m_oom = true; return res; } # else // Strict POSIX, fully generic, but not thread-safe: inline struct hostent *HostByName::Get() { errno = 0; struct hostent *res = gethostbyname(m_name); m_error = res ? 0 : h_errno; if (errno == ENOMEM || errno == ENOBUFS) m_oom = true; return res; } # endif // gethosbyname variant selection #endif // POSIX_DNS_GETHOSTBYNAME /** Perform actual name resolution, if we can. * * This method gets called from the worker (possibly in another thread). It is * the heart of the selection between available resolvers; hence its heavy use * of \#if-ery. Where possible, variation should be mediated by tool classes * (c.f. HostByName) that isolate as much of the \#if-ery as possible, to limit * the amount of it needed here. */ OpHostResolver::Error PosixHostResolver::Worker::Resolve() { /* TODO: arrange to be able to do IPv4 and IPv6 lookups in parallel, in the * cases where the two have to be looked up separately anyway. */ OpHostResolver::Error result = OpHostResolver::DNS_NOT_FOUND; #undef ResolverImplemented #ifdef POSIX_DNS_IPNODE if (!Live()) return OpHostResolver::NETWORK_NO_ERROR; Log(VERBOSE, "Resolving getipnodebyname(%s, ...)\n", SoughtName()); int err = 0; hostent * ResolveMaybeInit(ans, !ans, getipnodebyname(SoughtName(), AF_INET, AI_ADDRCONFIG, &err)); if (ans) { POSIX_CLEANUP_PUSH(freehostent, ans); Store4(ans); POSIX_CLEANUP_POP(); freehostent(ans); } result = PosixHostResolver::ByName2OpHost(err, result, SoughtName()); OP_ASSERT(!ans == (result != OpHostResolver::NETWORK_NO_ERROR)); # ifdef POSIX_SUPPORT_IPV6 if (IsIPv6OK() && Live() && (!ans || IsIPv6Usable())) { Log(VERBOSE, "Checking getipnodebyname() for IPv6\n", SoughtName()); err = 0; ResolveMaybeInit(ans, !ans, getipnodebyname(SoughtName(), AF_INET6, AI_ADDRCONFIG, &err)); if (ans) { POSIX_CLEANUP_PUSH(freehostent, ans); Store6(ans); POSIX_CLEANUP_POP(); freehostent(ans); } result = PosixHostResolver::ByName2OpHost(err, result, SoughtName()); OP_ASSERT(result == OpHostResolver::NETWORK_NO_ERROR || !ans); } # endif // POSIX_SUPPORT_IPV6 #define ResolverImplemented #endif // POSIX_DNS_IPNODE #ifdef POSIX_DNS_GETADDRINFO if (!Live()) return OpHostResolver::NETWORK_NO_ERROR; // TODO: research why unix-net deprecated this struct addrinfo *info = 0; struct addrinfo hints; op_memset(&hints, 0, sizeof(hints)); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_ADDRCONFIG; hints.ai_family = # ifdef POSIX_SUPPORT_IPV6 // man 3posix getaddrinfo: AF_UNSPEC means we accept any address family: (IsIPv6OK()) ? AF_UNSPEC : # endif // POSIX_SUPPORT_IPV6 AF_INET; // FIXME: TODO: getaddrinfo calls malloc - and we're in a non-main thread ! // 0 as DNS service name; indicates generic service: int ResolveMaybeInit(err, err, getaddrinfo(SoughtName(), 0, &hints, &info)); if (err == 0) { POSIX_CLEANUP_PUSH((void (*)(void*))freeaddrinfo, info); DigestAddrs(info, SoughtName()); POSIX_CLEANUP_POP(); freeaddrinfo(info); result = OpHostResolver::NETWORK_NO_ERROR; } else { OP_ASSERT(!info); result = PosixHostResolver::GetAddr2OpHost(err, SoughtName()); } #define ResolverImplemented #endif // POSIX_DNS_GETADDRINFO #ifdef POSIX_DNS_GETHOSTBYNAME // Sub-divides into *many* factions; see also HostByName class above. if (!Live()) return OpHostResolver::NETWORK_NO_ERROR; HostByName query(SoughtName()); bool oom = false; { # ifdef POSIX_DNS_LOCKING // The cases whose variants aren't thread-safe. POSIX_MUTEX_LOCK(&GetDnsMutex()); # endif // POSIX_DNS_LOCKING # ifdef USING_GHBN2 struct hostent * ResolveMaybeInit(ans, !ans, query.Get(AF_INET)); result = PosixHostResolver::ByName2OpHost(query.Error(oom), result, SoughtName()); if (ans) Store4(ans); # ifdef POSIX_SUPPORT_IPV6 if (Live() && IsIPv6OK() && (!ans || IsIPv6Usable())) { ResolveMaybeInit(ans, !ans, query.Get(AF_INET6)); result = PosixHostResolver::ByName2OpHost(query.Error(oom), result, SoughtName()); if (ans) Store6(ans); } # endif // POSIX_SUPPORT_IPV6 # else // !USING_GHBN2 struct hostent * ResolveMaybeInit(ans, !ans, query.Get()); result = PosixHostResolver::ByName2OpHost(query.Error(oom), result, SoughtName()); if (ans) { if (ans->h_addrtype == AF_INET) Store4(ans); # ifdef POSIX_SUPPORT_IPV6 else if (IsIPv6OK() && ans->h_addrtype == AF_INET6) Store6(ans); # else // !POSIX_SUPPORT_IPV6 else Log(CHATTY, "Unsupported or unrecognized (%d) address type found for %s", ans->addrtype, SoughtName()); # endif // POSIX_SUPPORT_IPV6 } # endif // USING_GHBN2 # ifdef POSIX_DNS_LOCKING // The cases whose variants aren't thread-safe. POSIX_MUTEX_UNLOCK(&GetDnsMutex()); # endif // POSIX_DNS_LOCKING } #define ResolverImplemented #endif // POSIX_DNS_GETHOSTBYNAME #ifndef ResolverImplemented # error "You need to activate one of the supported ways to do DNS !" /* See: TWEAK_POSIX_DNS_GETADDRINFO, TWEAK_POSIX_DNS_GETHOSTBYNAME, * TWEAK_POSIX_DNS_IPNODE */ #endif #undef ResolverImplemented return result; } #undef ResolveMaybeInit /* Relatively easy stuff: */ PosixHostResolver::~PosixHostResolver() { if (g_main_message_handler) g_main_message_handler->UnsetCallBacks(this); if (m_worker) { PosixAsyncManager::PendingDNSOp *check = g_opera && g_posix_async ? g_posix_async->Find(this, TRUE) // That Out()ed it : 0; if (check) { /* check was a pending Executor instance and m_worker is its * m_job. This means that Executor::Run() was not yet called, * and thus Worker::Resolve() was not yet called and we can * safely delete the Executor, which deletes the worker: */ OP_ASSERT(!m_done); OP_DELETE(check); } else ClearWorker(); } else OP_ASSERT(!g_opera || !g_posix_async || !g_posix_async->Find(this, TRUE)); Log(CHATTY, "Host resolver destroyed (%p, %p)\n", this, m_listener); } OP_STATUS PosixHostResolver::GetLocalHostName(OpString* local_hostname, Error* error) { OP_STATUS ret = static_cast<PosixSystemInfo *>( g_op_system_info)->GetLocalHostName(*local_hostname); if (OpStatus::IsSuccess(ret) && local_hostname->IsEmpty()) ret = OpStatus::ERR; if (ret == OpStatus::ERR) *error = HOST_ADDRESS_NOT_FOUND; if (error) Log(TERSE, "Failed to determine local host name\n"); else Log(CHATTY, "Found local host name of length %d\n", local_hostname->Length()); return ret; } void PosixHostResolver::Worker::HandleCallback(OpMessage msg, MH_PARAM_1 one, MH_PARAM_2 two) { OP_ASSERT(msg == MSG_POSIX_ASYNC_DONE && one == (MH_PARAM_1)this); OP_ASSERT(!m_boss); OP_DELETE(this); } void PosixHostResolver::HandleCallback(OpMessage msg, MH_PARAM_1 one, MH_PARAM_2 two) { OP_ASSERT(msg == MSG_POSIX_ASYNC_DONE && one == (MH_PARAM_1)m_worker); m_done = true; // Async switch (Error error = (Error)two) { case NETWORK_NO_ERROR: Log(CHATTY, "DNS look-up succeeded for %s\n", m_worker->SoughtName()); m_listener->OnHostResolved(this); break; // case ERROR_HANDLED: // ? default: Log(NORMAL, "DNS look-up failed for %s\n", m_worker->SoughtName()); m_listener->OnHostResolverError(this, error); break; } // Warning: listener methods may have deleted this, so don't reference it ! } OP_STATUS PosixHostResolver::Resolve(const uni_char* hostname) { if (!(g_opera && g_posix_async && g_posix_async->IsActive())) { OP_ASSERT(!"Attempted DNS resolution outside life-time of g_opera"); return OpStatus::ERR; } if (g_posix_async->Find(this, FALSE)) { OP_ASSERT(!"Attempted Resolve while look-up pending"); return OpStatus::ERR; } ClearWorker(); Worker *job = OP_NEW(Worker, (this, hostname)); OP_STATUS err = OpStatus::ERR_NO_MEMORY; if (job) { OpStatus::Ignore(err); if (OpStatus::IsSuccess(err = job->Ready())) { if (OpStatus::IsSuccess(err = SetAsCallback(job))) { Executor * runner = OP_NEW(Executor, (job, this)); if (runner) { m_worker = job; Log(CHATTY, "Queued DNS look-up for %s\n", job->SoughtName()); return OpStatus::OK; } err = OpStatus::ERR_NO_MEMORY; g_main_message_handler->UnsetCallBacks(this); } } OP_DELETE(job); } Log(TERSE, "OOM: failed to queue DNS look-up\n"); return err; } #ifdef SYNCHRONOUS_HOST_RESOLVING OP_STATUS PosixHostResolver::ResolveSync(const uni_char* hostname, OpSocketAddress* socket_address, Error* error) { if (g_posix_async->Find(this, FALSE)) { OP_ASSERT(!"Attempted ResolveSync while look-up pending"); return OpStatus::ERR; } LocalWorker job(this, hostname); RETURN_IF_ERROR(job.Ready()); switch (*error = job.Resolve()) { // case ERROR_HANDLED: // ? case NETWORK_NO_ERROR: if (GetAddressCount()) { Log(CHATTY, "Successful synchronous DNS for %s\n", job.SoughtName()); return GetAddress(socket_address, 0); } Log(NORMAL, "DNS reports no match for %s\n", job.SoughtName()); *error = DNS_NOT_FOUND; break; default: Log(TERSE, "Failed (%d) synchronous DNS for %s\n", (int)*error, job.SoughtName()); break; } return OpStatus::ERR; } #endif // SYNCHRONOUS_HOST_RESOLVING OP_STATUS PosixHostResolver::Worker::Get(UINT index, #ifdef POSIX_SUPPORT_IPV6 bool prefer_v6, #endif PosixNetworkAddress *addr) { #ifndef POSIX_SUPPORT_IPV6 const size_t cut = 0; #else int cut = 0; int indsix = index; if (prefer_v6) cut = m_answer6 ? m_answer6->Count() : 0; else if (m_answer4) indsix -= m_answer4->Count(); OP_ASSERT(IsIPv6OK() || cut == 0); if (prefer_v6 == (indsix < cut)) { RETURN_IF_ERROR(addr->SetFromIPv(m_answer6->Get(indsix))); } else #endif // POSIX_SUPPORT_IPV6 { OP_ASSERT(m_answer4 && m_answer4->Count() > index - cut); RETURN_IF_ERROR(addr->SetFromIPv(m_answer4->Get(index - cut))); } return OpStatus::OK; } OP_STATUS PosixHostResolver::GetAddress(OpSocketAddress* socket_address, UINT index) { if (index >= GetAddressCount()) { OP_ASSERT(!"Requested socket address past end of range"); return OpStatus::ERR_OUT_OF_RANGE; } if (socket_address == 0) { OP_ASSERT(!"No socket address object provided."); return OpStatus::ERR_NULL_POINTER; } PosixNetworkAddress local; OP_ASSERT(m_worker); // else index >= GetAddressCount OP_STATUS stat = m_worker->Get(index, #ifdef POSIX_SUPPORT_IPV6 m_prefer_ipv6, #endif &local); return OpStatus::IsSuccess(stat) ? socket_address->Copy(&local) : stat; } /* Finally, the one thing visible outside this compilation unit: */ OP_STATUS OpHostResolver::Create(OpHostResolver** host_resolver, OpHostResolverListener* listener) { if (host_resolver == NULL) return OpStatus::ERR_NULL_POINTER; else *host_resolver = NULL; PosixHostResolver *local = OP_NEW(PosixHostResolver, (listener)); if (local == 0) { PosixHostResolver::Log(PosixLogger::DNS, PosixLogger::TERSE, "OOM: failed to create host resolver\n"); return OpStatus::ERR_NO_MEMORY; } local->Log(PosixLogger::CHATTY, "Created host resolver (%p, %p)\n", local, listener); *host_resolver = static_cast<OpHostResolver*>(local); return OpStatus::OK; } #endif // POSIX_OK_DNS