text
stringlengths
54
60.6k
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "executors.h" #include <daemon/cookie.h> #include <memcached/engine.h> #include <memcached/protocol_binary.h> void collections_set_manifest_executor(Cookie& cookie) { auto ret = cookie.swapAiostat(ENGINE_SUCCESS); if (ret == ENGINE_SUCCESS) { auto& connection = cookie.getConnection(); auto packet = cookie.getPacket(Cookie::PacketContent::Full); const auto* req = reinterpret_cast< const protocol_binary_collections_set_manifest*>(packet.data()); const uint32_t valuelen = ntohl(req->message.header.request.bodylen); cb::const_char_buffer jsonBuffer{ reinterpret_cast<const char*>(req->bytes + sizeof(req->bytes)), valuelen}; ret = ENGINE_ERROR_CODE( connection.getBucketEngine() ->collections .set_manifest(connection.getBucketEngine(), jsonBuffer) .code() .value()); } if (ret == ENGINE_SUCCESS) { cookie.sendResponse(cb::mcbp::Status::Success); } else { cookie.sendResponse(cb::engine_errc(ret)); } } <commit_msg>Refactor: Prepare collections_set_manifest_executor for Frame Extras<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "executors.h" #include <daemon/cookie.h> #include <memcached/engine.h> #include <memcached/protocol_binary.h> void collections_set_manifest_executor(Cookie& cookie) { auto ret = cookie.swapAiostat(ENGINE_SUCCESS); if (ret == ENGINE_SUCCESS) { auto& connection = cookie.getConnection(); auto& req = cookie.getRequest(Cookie::PacketContent::Full); auto val = req.getValue(); cb::const_char_buffer jsonBuffer{ reinterpret_cast<const char*>(val.data()), val.size()}; ret = ENGINE_ERROR_CODE( connection.getBucketEngine() ->collections .set_manifest(connection.getBucketEngine(), jsonBuffer) .code() .value()); } if (ret == ENGINE_SUCCESS) { cookie.sendResponse(cb::mcbp::Status::Success); } else { cookie.sendResponse(cb::engine_errc(ret)); } } <|endoftext|>
<commit_before>/*********************************************************************** qparms.cpp - Implements the SQLQuery class. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. MySQL++ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "qparms.h" #include "query.h" using namespace std; namespace mysqlpp { SQLString& SQLQueryParms::operator [](const char* str) { if (parent_) { return operator [](parent_->parsed_nums_[str]); } throw ObjectNotInitialized("SQLQueryParms object has no parent!"); } const SQLString& SQLQueryParms::operator[] (const char* str) const { if (parent_) { return operator [](parent_->parsed_nums_[str]); } throw ObjectNotInitialized("SQLQueryParms object has no parent!"); } SQLQueryParms SQLQueryParms::operator +(const SQLQueryParms& other) const { if (other.size() <= size()) { return *this; } SQLQueryParms New = *this; size_t i; for (i = size(); i < other.size(); i++) { New.push_back(other[i]); } return New; } } // end namespace mysqlpp <commit_msg>Comment fix<commit_after>/*********************************************************************** qparms.cpp - Implements the SQLQueryParms class. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004-2007 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. MySQL++ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "qparms.h" #include "query.h" using namespace std; namespace mysqlpp { SQLString& SQLQueryParms::operator [](const char* str) { if (parent_) { return operator [](parent_->parsed_nums_[str]); } throw ObjectNotInitialized("SQLQueryParms object has no parent!"); } const SQLString& SQLQueryParms::operator[] (const char* str) const { if (parent_) { return operator [](parent_->parsed_nums_[str]); } throw ObjectNotInitialized("SQLQueryParms object has no parent!"); } SQLQueryParms SQLQueryParms::operator +(const SQLQueryParms& other) const { if (other.size() <= size()) { return *this; } SQLQueryParms New = *this; size_t i; for (i = size(); i < other.size(); i++) { New.push_back(other[i]); } return New; } } // end namespace mysqlpp <|endoftext|>
<commit_before>/* * Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved. */ #include "db/util/DynamicObjectImpl.h" #include "db/util/DynamicObject.h" using namespace std; using namespace db::util; DynamicObjectImpl::DynamicObjectImpl() { mType = String; mString = strdup(""); } DynamicObjectImpl::~DynamicObjectImpl() { DynamicObjectImpl::freeData(); } void DynamicObjectImpl::freeData() { // clean up data based on type switch(mType) { case String: delete [] mString; mString = NULL; break; case Map: if(mMap != NULL) { // clean up member names for(ObjectMap::iterator i = mMap->begin(); i != mMap->end(); i++) { delete [] i->first; } delete mMap; mMap = NULL; } break; case Array: if(mArray != NULL) { delete mArray; mArray = NULL; } break; default: // nothing to cleanup break; } } void DynamicObjectImpl::setString(const char* value) { freeData(); mType = String; mString = strdup(value); } void DynamicObjectImpl::operator=(const char* value) { setString(value); } void DynamicObjectImpl::operator=(bool value) { freeData(); mType = Boolean; mBoolean = value; } void DynamicObjectImpl::operator=(int value) { freeData(); mType = Int32; mInt32 = value; } void DynamicObjectImpl::operator=(unsigned int value) { freeData(); mType = UInt32; mUInt32 = value; } void DynamicObjectImpl::operator=(long long value) { freeData(); mType = Int64; mInt64 = value; } void DynamicObjectImpl::operator=(unsigned long long value) { freeData(); mType = UInt64; mUInt64 = value; } void DynamicObjectImpl::operator=(double value) { freeData(); mType = Double; mDouble = value; } DynamicObject& DynamicObjectImpl::operator[](const std::string& name) { DynamicObject* rval = NULL; // change to map type if necessary setType(Map); ObjectMap::iterator i = mMap->find(name.c_str()); if(i == mMap->end()) { // create new map entry DynamicObject dyno; mMap->insert(std::make_pair(strdup(name.c_str()), dyno)); rval = &(*mMap)[name.c_str()]; } else { // get existing map entry rval = &i->second; } return *rval; } DynamicObject& DynamicObjectImpl::operator[](int index) { // change to array type if necessary setType(Array); if(index < 0) { index = mArray->size() + index; } // fill the object array as necessary if(index >= (int)mArray->size()) { int i = index - (int)mArray->size() + 1; for(; i > 0; i--) { DynamicObject dyno; mArray->push_back(dyno); } } return (*mArray)[index]; } void DynamicObjectImpl::setType(DynamicObjectType type) { if(getType() != type) { switch(type) { case String: getString(); break; case Boolean: getBoolean(); break; case Int32: getInt32(); break; case UInt32: getUInt32(); break; case Int64: getInt64(); break; case UInt64: getUInt64(); break; case Double: getDouble(); break; case Map: if(mType != Map) { freeData(); mType = Map; mMap = new ObjectMap(); } break; case Array: // change to array type if(mType != Array) { freeData(); mType = Array; mArray = new ObjectArray(); } break; } } } DynamicObjectType DynamicObjectImpl::getType() { return mType; } const char* DynamicObjectImpl::getString() { if(mType != String) { string str; toString(str); setString(str.c_str()); } return mString; } bool DynamicObjectImpl::getBoolean() { if(mType != Boolean) { // convert type as appropriate if(mType == String && mString != NULL) { *this = (strcmp(mString, "true") == 0); } else { switch(mType) { case Int32: *this = (mInt32 == 1); break; case UInt32: *this = (mUInt32 == 1); break; case Int64: *this = (mInt64 == 1); break; case UInt64: *this = (mUInt64 == 1); break; case Double: *this = (mDouble == 1); break; default: *this = false; break; } } } return mBoolean; } int DynamicObjectImpl::getInt32() { if(mType != Int32) { // convert type as appropriate if(mType == String && mString != NULL) { *this = (int)strtol(mString, NULL, 10); } else if(mType == Boolean) { *this = mBoolean ? (int)1 : (int)0; } else if(mType == UInt32) { *this = (int)mUInt64; } else if(mType == Int64) { *this = (int)mInt64; } else if(mType == UInt64) { *this = (int)mUInt64; } else if(mType == Double) { *this = (int)mDouble; } else { *this = (int)0; } } return mInt32; } unsigned int DynamicObjectImpl::getUInt32() { if(mType != UInt32) { // convert type as appropriate if(mType == String && mString != NULL) { *this = (unsigned int)strtoul(mString, NULL, 10); } else if(mType == Boolean) { *this = mBoolean ? (unsigned int)1 : (unsigned int)0; } else if(mType == Int32 && mInt32 > 0) { *this = (unsigned int)mInt32; } else if(mType == Int64 && mInt64 > 0) { *this = (unsigned int)mInt64; } else if(mType == UInt64) { *this = (unsigned int)mUInt64; } else if(mType == Double && mDouble > 0) { *this = (unsigned int)mDouble; } else { *this = (unsigned int)0; } } return mUInt32; } long long DynamicObjectImpl::getInt64() { if(mType != Int64) { // convert type as appropriate if(mType == String && mString != NULL) { *this = (long long)strtoll(mString, NULL, 10); } else if(mType == Boolean) { *this = mBoolean ? (long long)1 : (long long)0; } else if(mType == Int32) { *this = (long long)mInt32; } else if(mType == UInt32) { *this = (long long)mUInt32; } else if(mType == UInt64) { *this = (long long)mUInt64; } else if(mType == Double) { *this = (long long)mDouble; } else { *this = (long long)0; } } return mInt64; } unsigned long long DynamicObjectImpl::getUInt64() { if(mType != UInt64) { // convert type as appropriate if(mType == String && mString != NULL) { *this = (unsigned long long)strtoull(mString, NULL, 10); } else if(mType == Boolean) { *this = mBoolean ? (unsigned long long)1 : (unsigned long long)0; } else if(mType == Int32 && mInt32 > 0) { *this = (unsigned long long)mInt32; } else if(mType == UInt32) { *this = (unsigned long long)mUInt32; } else if(mType == Int64 && mInt64 > 0) { *this = (unsigned long long)mInt64; } else if(mType == Double && mDouble > 0) { *this = (unsigned long long)mDouble; } else { *this = (unsigned long long)0; } } return mUInt64; } double DynamicObjectImpl::getDouble() { if(mType != Double) { // convert type as appropriate if(mType == String && mString != NULL) { *this = (double)strtod(mString, NULL); } else if(mType == Boolean) { *this = mBoolean ? (double)1 : (double)0; } else if(mType == Int32) { *this = (double)mInt32; } else if(mType == UInt32) { *this = (double)mUInt32; } else if(mType == Int64) { *this = (double)mInt64; } else if(mType == UInt64) { *this = (double)mUInt64; } else { *this = (double)0; } } return mDouble; } bool DynamicObjectImpl::hasMember(const char* name) { bool rval = false; if(mType == Map) { ObjectMap::iterator i = mMap->find(name); rval = (i != mMap->end()); } return rval; } DynamicObject DynamicObjectImpl::removeMember(const char* name) { DynamicObject rval(NULL); if(mType == Map) { ObjectMap::iterator i = mMap->find(name); if(i != mMap->end()) { // remove key and entry delete [] i->first; rval = i->second; mMap->erase(i); } } return rval; } void DynamicObjectImpl::clear() { switch(mType) { case String: *this = ""; break; case Boolean: *this = false; break; case Int32: *this = (int)0;; break; case UInt32: *this = (unsigned int)0; break; case Int64: *this = (long long)0; break; case UInt64: *this = (unsigned long long)0; break; case Double: *this = (double)0.0; break; case Map: mMap->clear(); break; case Array: mArray->clear(); break; } } int DynamicObjectImpl::length() { int rval = 0; switch(mType) { case String: if(mString != NULL) { rval = strlen(getString()); } break; case Boolean: rval = 1; break; case Int32: case UInt32: rval = sizeof(unsigned int); break; case Int64: case UInt64: rval = sizeof(unsigned long long); break; case Double: rval = sizeof(double); break; case Map: rval = mMap->size(); break; case Array: rval = mArray->size(); break; } return rval; } string& DynamicObjectImpl::toString(string& str) const { if(mType != String) { // convert type as appropriate char temp[22]; switch(mType) { case Boolean: sprintf(temp, "%s", (mBoolean ? "true" : "false")); break; case Int32: sprintf(temp, "%i", mInt32); break; case UInt32: sprintf(temp, "%u", mUInt32); break; case Int64: sprintf(temp, "%lli", mInt64); break; case UInt64: sprintf(temp, "%llu", mUInt64); break; case Double: sprintf(temp, "%e", mDouble); break; default: /* Map, Array, ... */ temp[0] = 0; break; } str.assign(temp); } else { if(mString == NULL) { str.assign(""); } else { str.assign(mString); } } return str; } <commit_msg>Removed extra semi-colon.<commit_after>/* * Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved. */ #include "db/util/DynamicObjectImpl.h" #include "db/util/DynamicObject.h" using namespace std; using namespace db::util; DynamicObjectImpl::DynamicObjectImpl() { mType = String; mString = strdup(""); } DynamicObjectImpl::~DynamicObjectImpl() { DynamicObjectImpl::freeData(); } void DynamicObjectImpl::freeData() { // clean up data based on type switch(mType) { case String: delete [] mString; mString = NULL; break; case Map: if(mMap != NULL) { // clean up member names for(ObjectMap::iterator i = mMap->begin(); i != mMap->end(); i++) { delete [] i->first; } delete mMap; mMap = NULL; } break; case Array: if(mArray != NULL) { delete mArray; mArray = NULL; } break; default: // nothing to cleanup break; } } void DynamicObjectImpl::setString(const char* value) { freeData(); mType = String; mString = strdup(value); } void DynamicObjectImpl::operator=(const char* value) { setString(value); } void DynamicObjectImpl::operator=(bool value) { freeData(); mType = Boolean; mBoolean = value; } void DynamicObjectImpl::operator=(int value) { freeData(); mType = Int32; mInt32 = value; } void DynamicObjectImpl::operator=(unsigned int value) { freeData(); mType = UInt32; mUInt32 = value; } void DynamicObjectImpl::operator=(long long value) { freeData(); mType = Int64; mInt64 = value; } void DynamicObjectImpl::operator=(unsigned long long value) { freeData(); mType = UInt64; mUInt64 = value; } void DynamicObjectImpl::operator=(double value) { freeData(); mType = Double; mDouble = value; } DynamicObject& DynamicObjectImpl::operator[](const std::string& name) { DynamicObject* rval = NULL; // change to map type if necessary setType(Map); ObjectMap::iterator i = mMap->find(name.c_str()); if(i == mMap->end()) { // create new map entry DynamicObject dyno; mMap->insert(std::make_pair(strdup(name.c_str()), dyno)); rval = &(*mMap)[name.c_str()]; } else { // get existing map entry rval = &i->second; } return *rval; } DynamicObject& DynamicObjectImpl::operator[](int index) { // change to array type if necessary setType(Array); if(index < 0) { index = mArray->size() + index; } // fill the object array as necessary if(index >= (int)mArray->size()) { int i = index - (int)mArray->size() + 1; for(; i > 0; i--) { DynamicObject dyno; mArray->push_back(dyno); } } return (*mArray)[index]; } void DynamicObjectImpl::setType(DynamicObjectType type) { if(getType() != type) { switch(type) { case String: getString(); break; case Boolean: getBoolean(); break; case Int32: getInt32(); break; case UInt32: getUInt32(); break; case Int64: getInt64(); break; case UInt64: getUInt64(); break; case Double: getDouble(); break; case Map: if(mType != Map) { freeData(); mType = Map; mMap = new ObjectMap(); } break; case Array: // change to array type if(mType != Array) { freeData(); mType = Array; mArray = new ObjectArray(); } break; } } } DynamicObjectType DynamicObjectImpl::getType() { return mType; } const char* DynamicObjectImpl::getString() { if(mType != String) { string str; toString(str); setString(str.c_str()); } return mString; } bool DynamicObjectImpl::getBoolean() { if(mType != Boolean) { // convert type as appropriate if(mType == String && mString != NULL) { *this = (strcmp(mString, "true") == 0); } else { switch(mType) { case Int32: *this = (mInt32 == 1); break; case UInt32: *this = (mUInt32 == 1); break; case Int64: *this = (mInt64 == 1); break; case UInt64: *this = (mUInt64 == 1); break; case Double: *this = (mDouble == 1); break; default: *this = false; break; } } } return mBoolean; } int DynamicObjectImpl::getInt32() { if(mType != Int32) { // convert type as appropriate if(mType == String && mString != NULL) { *this = (int)strtol(mString, NULL, 10); } else if(mType == Boolean) { *this = mBoolean ? (int)1 : (int)0; } else if(mType == UInt32) { *this = (int)mUInt64; } else if(mType == Int64) { *this = (int)mInt64; } else if(mType == UInt64) { *this = (int)mUInt64; } else if(mType == Double) { *this = (int)mDouble; } else { *this = (int)0; } } return mInt32; } unsigned int DynamicObjectImpl::getUInt32() { if(mType != UInt32) { // convert type as appropriate if(mType == String && mString != NULL) { *this = (unsigned int)strtoul(mString, NULL, 10); } else if(mType == Boolean) { *this = mBoolean ? (unsigned int)1 : (unsigned int)0; } else if(mType == Int32 && mInt32 > 0) { *this = (unsigned int)mInt32; } else if(mType == Int64 && mInt64 > 0) { *this = (unsigned int)mInt64; } else if(mType == UInt64) { *this = (unsigned int)mUInt64; } else if(mType == Double && mDouble > 0) { *this = (unsigned int)mDouble; } else { *this = (unsigned int)0; } } return mUInt32; } long long DynamicObjectImpl::getInt64() { if(mType != Int64) { // convert type as appropriate if(mType == String && mString != NULL) { *this = (long long)strtoll(mString, NULL, 10); } else if(mType == Boolean) { *this = mBoolean ? (long long)1 : (long long)0; } else if(mType == Int32) { *this = (long long)mInt32; } else if(mType == UInt32) { *this = (long long)mUInt32; } else if(mType == UInt64) { *this = (long long)mUInt64; } else if(mType == Double) { *this = (long long)mDouble; } else { *this = (long long)0; } } return mInt64; } unsigned long long DynamicObjectImpl::getUInt64() { if(mType != UInt64) { // convert type as appropriate if(mType == String && mString != NULL) { *this = (unsigned long long)strtoull(mString, NULL, 10); } else if(mType == Boolean) { *this = mBoolean ? (unsigned long long)1 : (unsigned long long)0; } else if(mType == Int32 && mInt32 > 0) { *this = (unsigned long long)mInt32; } else if(mType == UInt32) { *this = (unsigned long long)mUInt32; } else if(mType == Int64 && mInt64 > 0) { *this = (unsigned long long)mInt64; } else if(mType == Double && mDouble > 0) { *this = (unsigned long long)mDouble; } else { *this = (unsigned long long)0; } } return mUInt64; } double DynamicObjectImpl::getDouble() { if(mType != Double) { // convert type as appropriate if(mType == String && mString != NULL) { *this = (double)strtod(mString, NULL); } else if(mType == Boolean) { *this = mBoolean ? (double)1 : (double)0; } else if(mType == Int32) { *this = (double)mInt32; } else if(mType == UInt32) { *this = (double)mUInt32; } else if(mType == Int64) { *this = (double)mInt64; } else if(mType == UInt64) { *this = (double)mUInt64; } else { *this = (double)0; } } return mDouble; } bool DynamicObjectImpl::hasMember(const char* name) { bool rval = false; if(mType == Map) { ObjectMap::iterator i = mMap->find(name); rval = (i != mMap->end()); } return rval; } DynamicObject DynamicObjectImpl::removeMember(const char* name) { DynamicObject rval(NULL); if(mType == Map) { ObjectMap::iterator i = mMap->find(name); if(i != mMap->end()) { // clean up key and remove map entry delete [] i->first; rval = i->second; mMap->erase(i); } } return rval; } void DynamicObjectImpl::clear() { switch(mType) { case String: *this = ""; break; case Boolean: *this = false; break; case Int32: *this = (int)0; break; case UInt32: *this = (unsigned int)0; break; case Int64: *this = (long long)0; break; case UInt64: *this = (unsigned long long)0; break; case Double: *this = (double)0.0; break; case Map: mMap->clear(); break; case Array: mArray->clear(); break; } } int DynamicObjectImpl::length() { int rval = 0; switch(mType) { case String: if(mString != NULL) { rval = strlen(getString()); } break; case Boolean: rval = 1; break; case Int32: case UInt32: rval = sizeof(unsigned int); break; case Int64: case UInt64: rval = sizeof(unsigned long long); break; case Double: rval = sizeof(double); break; case Map: rval = mMap->size(); break; case Array: rval = mArray->size(); break; } return rval; } string& DynamicObjectImpl::toString(string& str) const { if(mType != String) { // convert type as appropriate char temp[22]; switch(mType) { case Boolean: sprintf(temp, "%s", (mBoolean ? "true" : "false")); break; case Int32: sprintf(temp, "%i", mInt32); break; case UInt32: sprintf(temp, "%u", mUInt32); break; case Int64: sprintf(temp, "%lli", mInt64); break; case UInt64: sprintf(temp, "%llu", mUInt64); break; case Double: sprintf(temp, "%e", mDouble); break; default: /* Map, Array, ... */ temp[0] = 0; break; } str.assign(temp); } else { if(mString == NULL) { str.assign(""); } else { str.assign(mString); } } return str; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <Python.h> #include "bzfsAPI.h" #include "PyBZFlag.h" static char *ReadFile (const char *filename); static Python::BZFlag *module_bzflag; static PyObject *global_dict; static char *code_buffer; BZ_GET_PLUGIN_VERSION BZF_PLUGIN_CALL int bz_Load (const char *commandLine) { // I would use assert here, but "Assertion `3 == 2' failed" is really not a useful error at all if (BZ_API_VERSION != 2) { fprintf (stderr, "Python plugin currently wraps the version 2 API, but BZFS is exporting version %d. Please complain loudly\n", BZ_API_VERSION); abort (); } if (Python::BZFlag::References == 0) { Py_Initialize (); Py_SetProgramName ("BZFlag"); } module_bzflag = Python::BZFlag::GetInstance (); char *buffer = ReadFile (commandLine); code_buffer = buffer; PyCodeObject *code = (PyCodeObject *) Py_CompileString (buffer, commandLine, Py_file_input); if (PyErr_Occurred ()) { PyErr_Print (); return 1; } global_dict = PyDict_New (); PyDict_SetItemString (global_dict, "__builtins__", PyEval_GetBuiltins ()); PyDict_SetItemString (global_dict, "__name__", PyString_FromString ("__main__")); PyEval_EvalCode (code, global_dict, global_dict); if (PyErr_Occurred ()) { PyErr_Print (); return 1; } return 0; } BZF_PLUGIN_CALL int bz_Unload (void) { Python::BZFlag::DeRef (); if (Python::BZFlag::References == 0) { PyDict_Clear (global_dict); Py_DECREF (global_dict); Py_Finalize (); } delete [] code_buffer; return 0; } static char * ReadFile (const char *filename) { FILE *f = fopen (filename, "r"); unsigned int pos = ftell (f); fseek (f, 0, SEEK_END); unsigned int len = ftell (f); fseek (f, pos, SEEK_SET); char *buffer = new char[len + 1]; fread (buffer, 1, len, f); buffer[len] = '\0'; fclose (f); return buffer; } <commit_msg>add a bunch of import garbage to try to get this working<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <Python.h> #include "bzfsAPI.h" #include "PyBZFlag.h" static char *ReadFile (const char *filename); static Python::BZFlag *module_bzflag; static PyObject *global_dict; static char *code_buffer; BZ_GET_PLUGIN_VERSION static void AppendSysPath (char *directory) { PyObject *mod_sys, *dict, *path, *dir; PyErr_Clear (); dir = Py_BuildValue ("s", directory); mod_sys = PyImport_ImportModule ("sys"); dict = PyModule_GetDict (mod_sys); path = PyDict_GetItemString (dict, "path"); if (!PyList_Check (path)) return; PyList_Append (path, dir); if (PyErr_Occurred ()) Py_FatalError ("could not build sys.path"); Py_DECREF (mod_sys); } BZF_PLUGIN_CALL int bz_Load (const char *commandLine) { // I would use assert here, but "Assertion `3 == 2' failed" is really not a useful error at all if (BZ_API_VERSION != 2) { fprintf (stderr, "Python plugin currently wraps the version 2 API, but BZFS is exporting version %d. Please complain loudly\n", BZ_API_VERSION); abort (); } if (Python::BZFlag::References == 0) { Py_SetProgramName ("BZFlag"); Py_Initialize (); } module_bzflag = Python::BZFlag::GetInstance (); char *buffer = ReadFile (commandLine); code_buffer = buffer; PyErr_Clear (); PyCodeObject *code = (PyCodeObject *) Py_CompileString (buffer, commandLine, Py_file_input); if (PyErr_Occurred ()) { PyErr_Print (); return 1; } // set up the global dict global_dict = PyDict_New (); PyDict_SetItemString (global_dict, "__builtins__", PyEval_GetBuiltins ()); PyDict_SetItemString (global_dict, "__name__", PyString_FromString ("__main__")); // pull site-package dirs into sys.path PyObject *mod = PyImport_ImportModule ("site"); if (mod) { PyObject *item; int size = 0; PyObject *d = PyModule_GetDict (mod); PyObject *m = PyDict_GetItemString (d, "main"); if (m) { PyEval_CallObject (m, NULL); } PyObject *p = PyDict_GetItemString (d, "sitedirs"); if (p) { size = PyList_Size (p); for (int i = 0; i < size; i++) { item = PySequence_GetItem (p, i); if (item) AppendSysPath (PyString_AsString (item)); } } Py_DECREF (mod); } else { PyErr_Clear (); fprintf (stderr, "No installed Python found\n"); fprintf (stderr, "Only built-in modules are available. Some scripts may not run\n"); fprintf (stderr, "Continuing happily\n"); } // eek! totally unportable - append the script's directory to sys.path, // in case there are any local modules int len = strrchr (commandLine, '/') - commandLine; char *dir = new char[len + 1]; strncpy (dir, commandLine, len); dir[len] = '\0'; AppendSysPath (dir); free (dir); PyErr_Clear (); PyEval_EvalCode (code, global_dict, global_dict); if (PyErr_Occurred ()) { PyErr_Print (); return 1; } return 0; } BZF_PLUGIN_CALL int bz_Unload (void) { Python::BZFlag::DeRef (); if (Python::BZFlag::References == 0) { PyDict_Clear (global_dict); Py_DECREF (global_dict); Py_Finalize (); } delete [] code_buffer; return 0; } static char * ReadFile (const char *filename) { FILE *f = fopen (filename, "r"); unsigned int pos = ftell (f); fseek (f, 0, SEEK_END); unsigned int len = ftell (f); fseek (f, pos, SEEK_SET); char *buffer = new char[len + 1]; fread (buffer, 1, len, f); buffer[len] = '\0'; fclose (f); return buffer; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //----------------------------------------------------------------------------- // Class AliMUONResponseFactory // ----------------------------- // Factory for muon response // Class separated from AliMUONFactoryV4 //----------------------------------------------------------------------------- #include "AliMUONResponseFactory.h" #include "AliRun.h" #include "AliLog.h" #include "AliMpPlaneType.h" #include "AliMUON.h" #include "AliMUONConstants.h" #include "AliMUONChamber.h" #include "AliMUONResponseV0.h" #include "AliMUONResponseTrigger.h" #include "AliMUONResponseTriggerV1.h" /// \cond CLASSIMP ClassImp(AliMUONResponseFactory) /// \endcond //__________________________________________________________________________ AliMUONResponseFactory::AliMUONResponseFactory(const char* name, Bool_t isTailEffect) : TNamed(name, ""), fMUON(0), fResponse0(0), fIsTailEffect(isTailEffect) { /// Standard constructor AliDebug(1,Form("ctor this=%p",this)); } //__________________________________________________________________________ AliMUONResponseFactory::AliMUONResponseFactory() : TNamed(), fMUON(0), fResponse0(0), fIsTailEffect(kTRUE) { /// Default constructor AliDebug(1,Form("default (empty) ctor this=%p",this)); } //__________________________________________________________________________ AliMUONResponseFactory::~AliMUONResponseFactory() { /// Destructor AliDebug(1,Form("dtor this=%p",this)); delete fResponse0; } //__________________________________________________________________________ void AliMUONResponseFactory::BuildCommon() { /// Construct the default response. // Default response: 5 mm of gas fResponse0 = new AliMUONResponseV0; fResponse0->SetSqrtKx3AndDeriveKx2Kx4(0.7131); // sqrt(0.5085) fResponse0->SetSqrtKy3AndDeriveKy2Ky4(0.7642); // sqrt(0.5840) fResponse0->SetPitch(AliMUONConstants::Pitch()); // anode-cathode distance fResponse0->SetSigmaIntegration(10.); fResponse0->SetChargeSlope(10); fResponse0->SetChargeSpread(0.18, 0.18); fResponse0->SetMaxAdc(4096); fResponse0->SetSaturation(3000); fResponse0->SetZeroSuppression(6); fResponse0->SetTailEffect(fIsTailEffect); } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation1() { /// Configuration for Chamber TC1/2 (Station 1) ---------- // Response for 4 mm of gas (station 1) // automatic consistency with width of sensitive medium in CreateGeometry ???? AliMUONResponseV0 responseSt1; // Mathieson parameters from L.Kharmandarian's thesis, page 190 responseSt1.SetSqrtKx3AndDeriveKx2Kx4(0.7000); // sqrt(0.4900) responseSt1.SetSqrtKy3AndDeriveKy2Ky4(0.7550); // sqrt(0.5700) responseSt1.SetPitch(AliMUONConstants::PitchSt1()); // anode-cathode distance responseSt1.SetSigmaIntegration(10.); // ChargeSlope larger to compensate for the smaller anode-cathode distance // and keep the same most probable ADC channel for mip's responseSt1.SetChargeSlope(62.5); // assumed proportionality to anode-cathode distance for ChargeSpread responseSt1.SetChargeSpread(0.144, 0.144); responseSt1.SetMaxAdc(4096); responseSt1.SetSaturation(3000); responseSt1.SetZeroSuppression(6); responseSt1.SetTailEffect(fIsTailEffect); for (Int_t chamber = 0; chamber < 2; chamber++) { fMUON->SetResponseModel(chamber, responseSt1); // special response fMUON->Chamber(chamber).SetChargeCorrel(0.11); // 11% charge spread } } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation2() { /// Configuration for Chamber TC3/4 (Station 2) ----------- for (Int_t chamber = 2; chamber < 4; chamber++) { fMUON->SetResponseModel(chamber, *fResponse0); // normal response fMUON->Chamber(chamber).SetChargeCorrel(0.11); // 11% charge spread } } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation3() { /// Configuration for Chamber TC5/6 (Station 3) ---------- for (Int_t chamber = 4; chamber < 6; chamber++) { fMUON->SetResponseModel(chamber, *fResponse0); // normal response fMUON->Chamber(chamber).SetChargeCorrel(0.11); // 11% charge spread } } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation4() { /// Configuration for Chamber TC7/8 (Station 4) ---------- for (Int_t chamber = 6; chamber < 8; chamber++) { fMUON->SetResponseModel(chamber, *fResponse0); // normal response fMUON->Chamber(chamber).SetChargeCorrel(0.11); // 11% charge spread } } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation5() { /// Configuration for Chamber TC9/10 (Station 5) --------- for (Int_t chamber = 8; chamber < 10; chamber++) { fMUON->SetResponseModel(chamber, *fResponse0); // normal response fMUON->Chamber(chamber).SetChargeCorrel(0.11); // 11% charge spread } } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation6() { /// Configuration for Trigger Chambers (Station 6,7) --------- Bool_t resTrigV1 = fMUON->GetTriggerResponseV1(); for (Int_t chamber = 10; chamber < 14; chamber++) { AliMUONResponse* response; if (!resTrigV1) { response = new AliMUONResponseTrigger; } else { response = new AliMUONResponseTriggerV1; } fMUON->SetResponseModel(chamber,*response); fMUON->Chamber(chamber).SetChargeCorrel(0); // same charge on both cathodes delete response; } } //__________________________________________________________________________ void AliMUONResponseFactory::Build(AliMUON* where) { /// Construct MUON responses AliDebugStream(1) << "Tail effect: " << fIsTailEffect << endl; fMUON = where; // Set default parameters fMUON->SetIshunt(0); fMUON->SetMaxStepGas(0.1); fMUON->SetMaxStepAlu(0.1); // Build stations BuildCommon(); BuildStation1(); BuildStation2(); BuildStation3(); BuildStation4(); BuildStation5(); BuildStation6(); } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation(AliMUON* where, Int_t stationNumber) { /// Construct MUON responses for given station fMUON = where; if (!fResponse0) BuildCommon(); switch (stationNumber) { case 1: BuildStation1(); break; case 2: BuildStation2(); break; case 3: BuildStation3(); break; case 4: BuildStation4(); break; case 5: BuildStation5(); break; case 6: BuildStation6(); break; default: AliFatal("Wrong station number"); } } <commit_msg>Change charge slope parameter for St.1 to match simulation to real data (Sanjoy, Javier)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //----------------------------------------------------------------------------- // Class AliMUONResponseFactory // ----------------------------- // Factory for muon response // Class separated from AliMUONFactoryV4 //----------------------------------------------------------------------------- #include "AliMUONResponseFactory.h" #include "AliRun.h" #include "AliLog.h" #include "AliMpPlaneType.h" #include "AliMUON.h" #include "AliMUONConstants.h" #include "AliMUONChamber.h" #include "AliMUONResponseV0.h" #include "AliMUONResponseTrigger.h" #include "AliMUONResponseTriggerV1.h" /// \cond CLASSIMP ClassImp(AliMUONResponseFactory) /// \endcond //__________________________________________________________________________ AliMUONResponseFactory::AliMUONResponseFactory(const char* name, Bool_t isTailEffect) : TNamed(name, ""), fMUON(0), fResponse0(0), fIsTailEffect(isTailEffect) { /// Standard constructor AliDebug(1,Form("ctor this=%p",this)); } //__________________________________________________________________________ AliMUONResponseFactory::AliMUONResponseFactory() : TNamed(), fMUON(0), fResponse0(0), fIsTailEffect(kTRUE) { /// Default constructor AliDebug(1,Form("default (empty) ctor this=%p",this)); } //__________________________________________________________________________ AliMUONResponseFactory::~AliMUONResponseFactory() { /// Destructor AliDebug(1,Form("dtor this=%p",this)); delete fResponse0; } //__________________________________________________________________________ void AliMUONResponseFactory::BuildCommon() { /// Construct the default response. // Default response: 5 mm of gas fResponse0 = new AliMUONResponseV0; fResponse0->SetSqrtKx3AndDeriveKx2Kx4(0.7131); // sqrt(0.5085) fResponse0->SetSqrtKy3AndDeriveKy2Ky4(0.7642); // sqrt(0.5840) fResponse0->SetPitch(AliMUONConstants::Pitch()); // anode-cathode distance fResponse0->SetSigmaIntegration(10.); fResponse0->SetChargeSlope(10); fResponse0->SetChargeSpread(0.18, 0.18); fResponse0->SetMaxAdc(4096); fResponse0->SetSaturation(3000); fResponse0->SetZeroSuppression(6); fResponse0->SetTailEffect(fIsTailEffect); } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation1() { /// Configuration for Chamber TC1/2 (Station 1) ---------- // Response for 4 mm of gas (station 1) // automatic consistency with width of sensitive medium in CreateGeometry ???? AliMUONResponseV0 responseSt1; // Mathieson parameters from L.Kharmandarian's thesis, page 190 responseSt1.SetSqrtKx3AndDeriveKx2Kx4(0.7000); // sqrt(0.4900) responseSt1.SetSqrtKy3AndDeriveKy2Ky4(0.7550); // sqrt(0.5700) responseSt1.SetPitch(AliMUONConstants::PitchSt1()); // anode-cathode distance responseSt1.SetSigmaIntegration(10.); // ChargeSlope larger to compensate for the smaller anode-cathode distance // and keep the same most probable ADC channel for mip's responseSt1.SetChargeSlope(25); // SP & JC ajusted to match 2010 real data was 62.5 // assumed proportionality to anode-cathode distance for ChargeSpread responseSt1.SetChargeSpread(0.144, 0.144); responseSt1.SetMaxAdc(4096); responseSt1.SetSaturation(3000); responseSt1.SetZeroSuppression(6); responseSt1.SetTailEffect(fIsTailEffect); for (Int_t chamber = 0; chamber < 2; chamber++) { fMUON->SetResponseModel(chamber, responseSt1); // special response fMUON->Chamber(chamber).SetChargeCorrel(0.11); // 11% charge spread } } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation2() { /// Configuration for Chamber TC3/4 (Station 2) ----------- for (Int_t chamber = 2; chamber < 4; chamber++) { fMUON->SetResponseModel(chamber, *fResponse0); // normal response fMUON->Chamber(chamber).SetChargeCorrel(0.11); // 11% charge spread } } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation3() { /// Configuration for Chamber TC5/6 (Station 3) ---------- for (Int_t chamber = 4; chamber < 6; chamber++) { fMUON->SetResponseModel(chamber, *fResponse0); // normal response fMUON->Chamber(chamber).SetChargeCorrel(0.11); // 11% charge spread } } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation4() { /// Configuration for Chamber TC7/8 (Station 4) ---------- for (Int_t chamber = 6; chamber < 8; chamber++) { fMUON->SetResponseModel(chamber, *fResponse0); // normal response fMUON->Chamber(chamber).SetChargeCorrel(0.11); // 11% charge spread } } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation5() { /// Configuration for Chamber TC9/10 (Station 5) --------- for (Int_t chamber = 8; chamber < 10; chamber++) { fMUON->SetResponseModel(chamber, *fResponse0); // normal response fMUON->Chamber(chamber).SetChargeCorrel(0.11); // 11% charge spread } } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation6() { /// Configuration for Trigger Chambers (Station 6,7) --------- Bool_t resTrigV1 = fMUON->GetTriggerResponseV1(); for (Int_t chamber = 10; chamber < 14; chamber++) { AliMUONResponse* response; if (!resTrigV1) { response = new AliMUONResponseTrigger; } else { response = new AliMUONResponseTriggerV1; } fMUON->SetResponseModel(chamber,*response); fMUON->Chamber(chamber).SetChargeCorrel(0); // same charge on both cathodes delete response; } } //__________________________________________________________________________ void AliMUONResponseFactory::Build(AliMUON* where) { /// Construct MUON responses AliDebugStream(1) << "Tail effect: " << fIsTailEffect << endl; fMUON = where; // Set default parameters fMUON->SetIshunt(0); fMUON->SetMaxStepGas(0.1); fMUON->SetMaxStepAlu(0.1); // Build stations BuildCommon(); BuildStation1(); BuildStation2(); BuildStation3(); BuildStation4(); BuildStation5(); BuildStation6(); } //__________________________________________________________________________ void AliMUONResponseFactory::BuildStation(AliMUON* where, Int_t stationNumber) { /// Construct MUON responses for given station fMUON = where; if (!fResponse0) BuildCommon(); switch (stationNumber) { case 1: BuildStation1(); break; case 2: BuildStation2(); break; case 3: BuildStation3(); break; case 4: BuildStation4(); break; case 5: BuildStation5(); break; case 6: BuildStation6(); break; default: AliFatal("Wrong station number"); } } <|endoftext|>
<commit_before>/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <eosio/chain/block_header_state.hpp> #include <eosio/chain/block.hpp> #include <eosio/chain/transaction_metadata.hpp> #include <eosio/chain/action_receipt.hpp> namespace eosio { namespace chain { struct block_state : public block_header_state { block_state( const block_header_state& cur ):block_header_state(cur){} block_state( const block_header_state& prev, signed_block_ptr b ); block_state( const block_header_state& prev, block_timestamp_type when ); block_state() = default; /// weak_ptr prev_block_state.... signed_block_ptr block; bool validated = false; bool in_current_chain = false; /// this data is redundant with the data stored in block, but facilitates /// recapturing transactions when we pop a block vector<transaction_metadata_ptr> trxs; }; using block_state_ptr = std::shared_ptr<block_state>; } } /// namespace eosio::chain FC_REFLECT_DERIVED( eosio::chain::block_state, (eosio::chain::block_header_state), (block)(validated) ) <commit_msg>Fix reflect issue in block_state.hpp<commit_after>/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <eosio/chain/block_header_state.hpp> #include <eosio/chain/block.hpp> #include <eosio/chain/transaction_metadata.hpp> #include <eosio/chain/action_receipt.hpp> namespace eosio { namespace chain { struct block_state : public block_header_state { block_state( const block_header_state& cur ):block_header_state(cur){} block_state( const block_header_state& prev, signed_block_ptr b ); block_state( const block_header_state& prev, block_timestamp_type when ); block_state() = default; /// weak_ptr prev_block_state.... signed_block_ptr block; bool validated = false; bool in_current_chain = false; /// this data is redundant with the data stored in block, but facilitates /// recapturing transactions when we pop a block vector<transaction_metadata_ptr> trxs; }; using block_state_ptr = std::shared_ptr<block_state>; } } /// namespace eosio::chain FC_REFLECT_DERIVED( eosio::chain::block_state, (eosio::chain::block_header_state), (block)(validated)(in_current_chain) ) <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkDomainThreader.h" #include "itkThreadedIndexedContainerPartitioner.h" #include "itkCompensatedSummation.h" #include <iostream> #include <iomanip> /* * This test demonstrates to utility of the CompensatedSummation class * for summing the per-thread output of multi-threaded operation. This * reduces the variance in output when the same operation is * performed with different numbers of threads. The variance * is a result of different floating-point rounding that occurs when * different numbers of threads are used, mainly when the magnitudes of * the intermediate values calculated by each thread differ. */ class CompensatedSummationTest2Associate { public: typedef CompensatedSummationTest2Associate Self; // Nested class holds the domain threader class TestDomainThreader : public itk::DomainThreader< itk::ThreadedIndexedContainerPartitioner, Self > { public: typedef TestDomainThreader Self; typedef itk::DomainThreader< itk::ThreadedIndexedContainerPartitioner, Self > Superclass; typedef itk::SmartPointer< Self > Pointer; typedef itk::SmartPointer< const Self > ConstPointer; typedef Superclass::DomainPartitionerType DomainPartitionerType; typedef Superclass::DomainType DomainType; itkNewMacro( Self ); protected: TestDomainThreader() {}; private: virtual void BeforeThreadedExecution() { this->m_PerThreadCompensatedSum.resize( this->GetNumberOfThreadsUsed() ); for( itk::ThreadIdType i=0; i < this->GetNumberOfThreadsUsed(); i++ ) { this->m_PerThreadCompensatedSum[i].ResetToZero(); } } virtual void ThreadedExecution( const DomainType& subdomain, const itk::ThreadIdType threadId ) { if( threadId == 0 ) { std::cout << "This is the : " << this->m_Associate->m_ClassDescriptor << std::endl; } itk::CompensatedSummation<double> compensatedSum; for( DomainType::IndexValueType i=subdomain[0]; i <= subdomain[1]; i++ ) { double value = itk::NumericTraits<double>::One / (i+1); this->m_PerThreadCompensatedSum[threadId].AddElement( value ); } } virtual void AfterThreadedExecution() { this->m_Associate->m_UncompensatedSumOfThreads = itk::NumericTraits<double>::Zero; this->m_Associate->m_CompensatedSumOfThreads.ResetToZero(); for( itk::ThreadIdType i = 0; i < this->GetNumberOfThreadsUsed(); ++i ) { double sum = this->m_PerThreadCompensatedSum[i].GetSum(); this->m_Associate->m_CompensatedSumOfThreads.AddElement( sum ); this->m_Associate->m_UncompensatedSumOfThreads += sum; } } std::vector< itk::CompensatedSummation<double> > m_PerThreadCompensatedSum; TestDomainThreader( const Self & ); // purposely not implemented void operator=( const Self & ); // purposely not implemented }; // end TestDomainThreader class CompensatedSummationTest2Associate() { m_TestDomainThreader = TestDomainThreader::New(); m_ClassDescriptor = "enclosing class"; } double GetCompensatedSumOfThreads() { return this->m_CompensatedSumOfThreads.GetSum(); } double GetUncompensatedSumOfThreads() { return this->m_UncompensatedSumOfThreads; } TestDomainThreader * GetDomainThreader() { return m_TestDomainThreader.GetPointer(); } void Execute( const TestDomainThreader::DomainType & completeDomain ) { m_TestDomainThreader->Execute(this, completeDomain); } private: TestDomainThreader::Pointer m_TestDomainThreader; std::string m_ClassDescriptor; itk::CompensatedSummation<double> m_CompensatedSumOfThreads; double m_UncompensatedSumOfThreads; }; int itkCompensatedSummationTest2(int, char* []) { CompensatedSummationTest2Associate enclosingClass; CompensatedSummationTest2Associate::TestDomainThreader::Pointer domainThreader = enclosingClass.GetDomainThreader(); /* Check # of threads */ std::cout << "GetGlobalMaximumNumberOfThreads: " << domainThreader->GetMultiThreader()->GetGlobalMaximumNumberOfThreads() << std::endl; std::cout << "GetGlobalDefaultNumberOfThreads: " << domainThreader->GetMultiThreader()->GetGlobalDefaultNumberOfThreads() << std::endl; typedef CompensatedSummationTest2Associate::TestDomainThreader::DomainType DomainType; DomainType domain; itk::ThreadIdType maxNumberOfThreads = domainThreader->GetMultiThreader()->GetGlobalMaximumNumberOfThreads(); domain[0] = 0; domain[1] = maxNumberOfThreads * 10000; /* Test with single thread. We should get the same result. */ itk::ThreadIdType numberOfThreads = 1; domainThreader->SetMaximumNumberOfThreads( numberOfThreads ); std::cout << "Testing with " << numberOfThreads << " threads and domain " << domain << " ..." << std::endl; /* Execute */ enclosingClass.Execute( domain ); /* Did we use as many threads as requested? */ std::cout << "Requested numberOfThreads: " << numberOfThreads << std::endl << "actual: threader->GetNumberOfThreadsUsed(): " << domainThreader->GetNumberOfThreadsUsed() << "\n\n" << std::endl; /* Check results */ if( enclosingClass.GetCompensatedSumOfThreads() != enclosingClass.GetUncompensatedSumOfThreads() ) { std::cerr << std::setprecision(20) << "Error. Expected the sum to be the same for compensated and uncompensated." << " Instead, got " << enclosingClass.GetCompensatedSumOfThreads() << " and " << enclosingClass.GetUncompensatedSumOfThreads() << std::endl << "Difference: " << enclosingClass.GetCompensatedSumOfThreads() - enclosingClass.GetUncompensatedSumOfThreads() << std::endl; return EXIT_FAILURE; } /* Store result as reference */ double referenceSum = enclosingClass.GetCompensatedSumOfThreads(); /* Test with maximum threads. We need at least three threads to see a difference. */ if( domainThreader->GetMultiThreader()->GetGlobalMaximumNumberOfThreads() > 2 ) { domainThreader->SetMaximumNumberOfThreads( maxNumberOfThreads ); std::cout << "Testing with " << maxNumberOfThreads << " threads and domain " << domain << " ..." << std::endl; /* Execute */ enclosingClass.Execute( domain ); /* Check number of threads used */ if( domainThreader->GetNumberOfThreadsUsed() != maxNumberOfThreads ) { std::cerr << "Error: Expected to use " << maxNumberOfThreads << "threads, but used " << domainThreader->GetNumberOfThreadsUsed() << "." << std::endl; return EXIT_FAILURE; } std::cout << "# of digits precision in double: " << std::numeric_limits< double >::digits10 << std::endl; std::cout << std::setprecision(100) << "Reference: " << referenceSum << std::endl << "Compensated: " << enclosingClass.GetCompensatedSumOfThreads() << std::endl << "Uncompensated: " << enclosingClass.GetUncompensatedSumOfThreads() << std::endl << "Difference: " << enclosingClass.GetCompensatedSumOfThreads() - enclosingClass.GetUncompensatedSumOfThreads() << std::endl; /* Check that the compensated result is closer to reference than uncompensated */ if( vcl_fabs( referenceSum - enclosingClass.GetCompensatedSumOfThreads() ) >= vcl_fabs( referenceSum - enclosingClass.GetUncompensatedSumOfThreads() ) ) { std::cerr << "Error. Expected the compensated sum of threads to be closer " << "to reference than the uncompensated sum. " << std::endl; return EXIT_FAILURE; } } else { std::cout << "No multi-threading available, or too few threads available. " << std::endl; } return EXIT_SUCCESS; } <commit_msg>BUG: Fix itkCompensatedSummationTest2<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkDomainThreader.h" #include "itkThreadedIndexedContainerPartitioner.h" #include "itkCompensatedSummation.h" #include <iostream> #include <iomanip> /* * This test demonstrates the variance in output when the same operation is * performed with different numbers of threads, and the utility of the * CompensatedSummation class for summing the per-thread output of * multi-threaded operation to reduce the variance. The variance is a * result of different floating-point rounding that occurs when * different numbers of threads are used. */ class CompensatedSummationTest2Associate { public: typedef CompensatedSummationTest2Associate Self; // Nested class holds the domain threader class TestDomainThreader : public itk::DomainThreader< itk::ThreadedIndexedContainerPartitioner, Self > { public: typedef TestDomainThreader Self; typedef itk::DomainThreader< itk::ThreadedIndexedContainerPartitioner, Self > Superclass; typedef itk::SmartPointer< Self > Pointer; typedef itk::SmartPointer< const Self > ConstPointer; typedef Superclass::DomainPartitionerType DomainPartitionerType; typedef Superclass::DomainType DomainType; itkNewMacro( Self ); protected: TestDomainThreader() {}; private: virtual void BeforeThreadedExecution() { this->m_PerThreadCompensatedSum.resize( this->GetNumberOfThreadsUsed() ); for( itk::ThreadIdType i=0; i < this->GetNumberOfThreadsUsed(); i++ ) { this->m_PerThreadCompensatedSum[i].ResetToZero(); } } virtual void ThreadedExecution( const DomainType& subdomain, const itk::ThreadIdType threadId ) { itk::CompensatedSummation<double> compensatedSum; for( DomainType::IndexValueType i=subdomain[0]; i <= subdomain[1]; i++ ) { double value = itk::NumericTraits<double>::One / 7; this->m_PerThreadCompensatedSum[threadId].AddElement( value ); } } virtual void AfterThreadedExecution() { this->m_Associate->m_UncompensatedSumOfThreads = itk::NumericTraits<double>::Zero; this->m_Associate->m_CompensatedSumOfThreads.ResetToZero(); for( itk::ThreadIdType i = 0; i < this->GetNumberOfThreadsUsed(); ++i ) { double sum = this->m_PerThreadCompensatedSum[i].GetSum(); std::cout << i << ": " << sum << std::endl; this->m_Associate->m_CompensatedSumOfThreads.AddElement( sum ); this->m_Associate->m_UncompensatedSumOfThreads += sum; } } std::vector< itk::CompensatedSummation<double> > m_PerThreadCompensatedSum; TestDomainThreader( const Self & ); // purposely not implemented void operator=( const Self & ); // purposely not implemented }; // end TestDomainThreader class CompensatedSummationTest2Associate() { m_TestDomainThreader = TestDomainThreader::New(); m_ClassDescriptor = "enclosing class"; } double GetCompensatedSumOfThreads() { return this->m_CompensatedSumOfThreads.GetSum(); } double GetUncompensatedSumOfThreads() { return this->m_UncompensatedSumOfThreads; } TestDomainThreader * GetDomainThreader() { return m_TestDomainThreader.GetPointer(); } void Execute( const TestDomainThreader::DomainType & completeDomain ) { m_TestDomainThreader->Execute(this, completeDomain); } private: TestDomainThreader::Pointer m_TestDomainThreader; std::string m_ClassDescriptor; itk::CompensatedSummation<double> m_CompensatedSumOfThreads; double m_UncompensatedSumOfThreads; }; int itkCompensatedSummationTest2(int, char* []) { CompensatedSummationTest2Associate enclosingClass; CompensatedSummationTest2Associate::TestDomainThreader::Pointer domainThreader = enclosingClass.GetDomainThreader(); /* Check # of threads */ std::cout << "GetGlobalMaximumNumberOfThreads: " << domainThreader->GetMultiThreader()->GetGlobalMaximumNumberOfThreads() << std::endl; std::cout << "GetGlobalDefaultNumberOfThreads: " << domainThreader->GetMultiThreader()->GetGlobalDefaultNumberOfThreads() << std::endl; typedef CompensatedSummationTest2Associate::TestDomainThreader::DomainType DomainType; DomainType domain; itk::ThreadIdType maxNumberOfThreads = domainThreader->GetMultiThreader()->GetGlobalMaximumNumberOfThreads(); domain[0] = 0; domain[1] = maxNumberOfThreads * 10000; /* Test with single thread. We should get the same result. */ itk::ThreadIdType numberOfThreads = 1; domainThreader->SetMaximumNumberOfThreads( numberOfThreads ); std::cout << "Testing with " << numberOfThreads << " threads and domain " << domain << " ..." << std::endl; /* Execute */ enclosingClass.Execute( domain ); /* Did we use as many threads as requested? */ std::cout << "Requested numberOfThreads: " << numberOfThreads << std::endl << "actual: threader->GetNumberOfThreadsUsed(): " << domainThreader->GetNumberOfThreadsUsed() << "\n\n" << std::endl; /* Check results */ if( enclosingClass.GetCompensatedSumOfThreads() != enclosingClass.GetUncompensatedSumOfThreads() ) { std::cerr << std::setprecision(20) << "Error. Expected the sum to be the same for compensated and uncompensated." << " Instead, got " << enclosingClass.GetCompensatedSumOfThreads() << " and " << enclosingClass.GetUncompensatedSumOfThreads() << std::endl << "Difference: " << enclosingClass.GetCompensatedSumOfThreads() - enclosingClass.GetUncompensatedSumOfThreads() << std::endl; return EXIT_FAILURE; } /* Store result as reference */ double referenceSum = enclosingClass.GetCompensatedSumOfThreads(); /* Test with maximum threads. We need at least three threads to see a difference. */ if( domainThreader->GetMultiThreader()->GetGlobalMaximumNumberOfThreads() > 2 ) { domainThreader->SetMaximumNumberOfThreads( maxNumberOfThreads ); std::cout << "Testing with " << maxNumberOfThreads << " threads and domain " << domain << " ..." << std::endl; /* Execute */ enclosingClass.Execute( domain ); /* Check number of threads used */ if( domainThreader->GetNumberOfThreadsUsed() != maxNumberOfThreads ) { std::cerr << "Error: Expected to use " << maxNumberOfThreads << "threads, but used " << domainThreader->GetNumberOfThreadsUsed() << "." << std::endl; return EXIT_FAILURE; } std::cout << "# of digits precision in double: " << std::numeric_limits< double >::digits10 << std::endl; std::cout << std::setprecision(100) << "Reference: " << referenceSum << std::endl << "Compensated: " << enclosingClass.GetCompensatedSumOfThreads() << std::endl << "Uncompensated: " << enclosingClass.GetUncompensatedSumOfThreads() << std::endl << "Difference: " << enclosingClass.GetCompensatedSumOfThreads() - enclosingClass.GetUncompensatedSumOfThreads() << std::endl; /* Check that the compensated result is not further from reference than * uncompensated. * Generally we see the compensated sum closer, but on a few platforms the * sums are equal. This could be because of differences in compiler * optimizations that were not handled by the CompensatedSummation class * pragmas, or perhaps because of differences in math coprocessors, or * something else. It's not clear. */ if( vcl_fabs( referenceSum - enclosingClass.GetCompensatedSumOfThreads() ) > vcl_fabs( referenceSum - enclosingClass.GetUncompensatedSumOfThreads() ) ) { std::cerr << "Error. Expected the compensated sum of threads to be closer " << "to reference than the uncompensated sum, or the same value. " << std::endl; return EXIT_FAILURE; } } else { std::cout << "No multi-threading available, or too few threads available. " << std::endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//===- ICF.cpp ------------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Identical Code Folding is a feature to merge sections not by name (which // is regular comdat handling) but by contents. If two non-writable sections // have the same data, relocations, attributes, etc., then the two // are considered identical and merged by the linker. This optimization // makes outputs smaller. // // ICF is theoretically a problem of reducing graphs by merging as many // identical subgraphs as possible if we consider sections as vertices and // relocations as edges. It may sound simple, but it is a bit more // complicated than you might think. The order of processing sections // matters because merging two sections can make other sections, whose // relocations now point to the same section, mergeable. Graphs may contain // cycles. We need a sophisticated algorithm to do this properly and // efficiently. // // What we do in this file is this. We split sections into groups. Sections // in the same group are considered identical. // // We begin by optimistically putting all sections into a single equivalence // class. Then we apply a series of checks that split this initial // equivalence class into more and more refined equivalence classes based on // the properties by which a section can be distinguished. // // We begin by checking that the section contents and flags are the // same. This only needs to be done once since these properties don't depend // on the current equivalence class assignment. // // Then we split the equivalence classes based on checking that their // relocations are the same, where relocation targets are compared by their // equivalence class, not the concrete section. This may need to be done // multiple times because as the equivalence classes are refined, two // sections that had a relocation target in the same equivalence class may // now target different equivalence classes, and hence these two sections // must be put in different equivalence classes (whereas in the previous // iteration they were not since the relocation target was the same.) // // Our algorithm is smart enough to merge the following mutually-recursive // functions. // // void foo() { bar(); } // void bar() { foo(); } // // This algorithm is so-called "optimistic" algorithm described in // http://research.google.com/pubs/pub36912.html. (Note that what GNU // gold implemented is different from the optimistic algorithm.) // //===----------------------------------------------------------------------===// #include "ICF.h" #include "Config.h" #include "SymbolTable.h" #include "llvm/ADT/Hashing.h" #include "llvm/Object/ELF.h" #include "llvm/Support/ELF.h" #include <algorithm> using namespace lld; using namespace lld::elf; using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; namespace { template <class ELFT> class ICF { public: void run(); private: uint64_t NextId = 1; using Comparator = std::function<bool(const InputSection<ELFT> *, const InputSection<ELFT> *)>; void segregate(MutableArrayRef<InputSection<ELFT> *> Arr, Comparator Eq); void forEachGroup(std::vector<InputSection<ELFT> *> &V, std::function<void(MutableArrayRef<InputSection<ELFT> *>)> Fn); }; } // Returns a hash value for S. Note that the information about // relocation targets is not included in the hash value. template <class ELFT> static uint64_t getHash(InputSection<ELFT> *S) { return hash_combine(S->Flags, S->getSize(), S->NumRelocations); } // Returns true if section S is subject of ICF. template <class ELFT> static bool isEligible(InputSection<ELFT> *S) { // .init and .fini contains instructions that must be executed to // initialize and finalize the process. They cannot and should not // be merged. return S->Live && (S->Flags & SHF_ALLOC) && !(S->Flags & SHF_WRITE) && S->Name != ".init" && S->Name != ".fini"; } template <class ELFT> static std::vector<InputSection<ELFT> *> getSections() { std::vector<InputSection<ELFT> *> V; for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) if (auto *S = dyn_cast<InputSection<ELFT>>(Sec)) if (isEligible(S)) V.push_back(S); return V; } // Before calling this function, all sections in Arr must have the // same group ID. This function compare sections in Arr using Eq and // assign new group IDs for new groups. template <class ELFT> void ICF<ELFT>::segregate(MutableArrayRef<InputSection<ELFT> *> Arr, Comparator Eq) { // This loop rearranges Arr so that all sections that are equal in // terms of Eq are contiguous. The algorithm is quadratic in the // worst case, but that is not an issue in practice because the // number of distinct sections in Arr is usually very small. InputSection<ELFT> **I = Arr.begin(); for (;;) { InputSection<ELFT> *Head = *I; auto Bound = std::stable_partition( I + 1, Arr.end(), [&](InputSection<ELFT> *S) { return Eq(Head, S); }); if (Bound == Arr.end()) return; uint64_t Id = NextId++; for (; I != Bound; ++I) (*I)->GroupId = Id; } } // Call Fn for each section group having the same group ID. template <class ELFT> void ICF<ELFT>::forEachGroup( std::vector<InputSection<ELFT> *> &V, std::function<void(MutableArrayRef<InputSection<ELFT> *>)> Fn) { for (InputSection<ELFT> **I = V.data(), **E = I + V.size(); I != E;) { InputSection<ELFT> *Head = *I; auto Bound = std::find_if(I + 1, E, [&](InputSection<ELFT> *S) { return S->GroupId != Head->GroupId; }); Fn({I, Bound}); I = Bound; } } // Compare two lists of relocations. template <class ELFT, class RelTy> static bool relocationEq(ArrayRef<RelTy> RelsA, ArrayRef<RelTy> RelsB) { auto Eq = [](const RelTy &A, const RelTy &B) { return A.r_offset == B.r_offset && A.getType(Config->Mips64EL) == B.getType(Config->Mips64EL) && getAddend<ELFT>(A) == getAddend<ELFT>(B); }; return RelsA.size() == RelsB.size() && std::equal(RelsA.begin(), RelsA.end(), RelsB.begin(), Eq); } // Compare "non-moving" part of two InputSections, namely everything // except relocation targets. template <class ELFT> static bool equalsConstant(const InputSection<ELFT> *A, const InputSection<ELFT> *B) { if (A->NumRelocations != B->NumRelocations || A->Flags != B->Flags || A->getSize() != B->getSize() || A->Data != B->Data) return false; if (A->AreRelocsRela) return relocationEq<ELFT>(A->relas(), B->relas()); return relocationEq<ELFT>(A->rels(), B->rels()); } // Compare two lists of relocations. Returns true if all pairs of // relocations point to the same section in terms of ICF. template <class ELFT, class RelTy> static bool variableEq(const InputSection<ELFT> *A, ArrayRef<RelTy> RelsA, const InputSection<ELFT> *B, ArrayRef<RelTy> RelsB) { auto Eq = [&](const RelTy &RA, const RelTy &RB) { SymbolBody &SA = A->getFile()->getRelocTargetSym(RA); SymbolBody &SB = B->getFile()->getRelocTargetSym(RB); if (&SA == &SB) return true; // Or, the symbols should be pointing to the same section // in terms of the group ID. auto *DA = dyn_cast<DefinedRegular<ELFT>>(&SA); auto *DB = dyn_cast<DefinedRegular<ELFT>>(&SB); if (!DA || !DB) return false; if (DA->Value != DB->Value) return false; auto *X = dyn_cast<InputSection<ELFT>>(DA->Section); auto *Y = dyn_cast<InputSection<ELFT>>(DB->Section); return X && Y && X->GroupId && X->GroupId == Y->GroupId; }; return std::equal(RelsA.begin(), RelsA.end(), RelsB.begin(), Eq); } // Compare "moving" part of two InputSections, namely relocation targets. template <class ELFT> static bool equalsVariable(const InputSection<ELFT> *A, const InputSection<ELFT> *B) { if (A->AreRelocsRela) return variableEq(A, A->relas(), B, B->relas()); return variableEq(A, A->rels(), B, B->rels()); } // The main function of ICF. template <class ELFT> void ICF<ELFT>::run() { // Initially, we use hash values as section group IDs. Therefore, // if two sections have the same ID, they are likely (but not // guaranteed) to have the same static contents in terms of ICF. std::vector<InputSection<ELFT> *> Sections = getSections<ELFT>(); for (InputSection<ELFT> *S : Sections) // Set MSB on to avoid collisions with serial group IDs S->GroupId = getHash(S) | (uint64_t(1) << 63); // From now on, sections in Sections are ordered so that sections in // the same group are consecutive in the vector. std::stable_sort(Sections.begin(), Sections.end(), [](InputSection<ELFT> *A, InputSection<ELFT> *B) { if (A->GroupId != B->GroupId) return A->GroupId < B->GroupId; // Within a group, put the highest alignment // requirement first, so that's the one we'll keep. return B->Alignment < A->Alignment; }); // Compare static contents and assign unique IDs for each static content. forEachGroup(Sections, [&](MutableArrayRef<InputSection<ELFT> *> V) { segregate(V, equalsConstant<ELFT>); }); // Split groups by comparing relocations until we get a convergence. int Cnt = 1; for (;;) { ++Cnt; uint64_t Id = NextId; forEachGroup(Sections, [&](MutableArrayRef<InputSection<ELFT> *> V) { segregate(V, equalsVariable<ELFT>); }); if (Id == NextId) break; } log("ICF needed " + Twine(Cnt) + " iterations."); // Merge sections in the same group. forEachGroup(Sections, [](MutableArrayRef<InputSection<ELFT> *> V) { log("selected " + V[0]->Name); for (InputSection<ELFT> *S : V.slice(1)) { log(" removed " + S->Name); V[0]->replace(S); } }); } // ICF entry point function. template <class ELFT> void elf::doIcf() { ICF<ELFT>().run(); } template void elf::doIcf<ELF32LE>(); template void elf::doIcf<ELF32BE>(); template void elf::doIcf<ELF64LE>(); template void elf::doIcf<ELF64BE>(); <commit_msg>Change how we manage groups in ICF.<commit_after>//===- ICF.cpp ------------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Identical Code Folding is a feature to merge sections not by name (which // is regular comdat handling) but by contents. If two non-writable sections // have the same data, relocations, attributes, etc., then the two // are considered identical and merged by the linker. This optimization // makes outputs smaller. // // ICF is theoretically a problem of reducing graphs by merging as many // identical subgraphs as possible if we consider sections as vertices and // relocations as edges. It may sound simple, but it is a bit more // complicated than you might think. The order of processing sections // matters because merging two sections can make other sections, whose // relocations now point to the same section, mergeable. Graphs may contain // cycles. We need a sophisticated algorithm to do this properly and // efficiently. // // What we do in this file is this. We split sections into groups. Sections // in the same group are considered identical. // // We begin by optimistically putting all sections into a single equivalence // class. Then we apply a series of checks that split this initial // equivalence class into more and more refined equivalence classes based on // the properties by which a section can be distinguished. // // We begin by checking that the section contents and flags are the // same. This only needs to be done once since these properties don't depend // on the current equivalence class assignment. // // Then we split the equivalence classes based on checking that their // relocations are the same, where relocation targets are compared by their // equivalence class, not the concrete section. This may need to be done // multiple times because as the equivalence classes are refined, two // sections that had a relocation target in the same equivalence class may // now target different equivalence classes, and hence these two sections // must be put in different equivalence classes (whereas in the previous // iteration they were not since the relocation target was the same.) // // Our algorithm is smart enough to merge the following mutually-recursive // functions. // // void foo() { bar(); } // void bar() { foo(); } // // This algorithm is so-called "optimistic" algorithm described in // http://research.google.com/pubs/pub36912.html. (Note that what GNU // gold implemented is different from the optimistic algorithm.) // //===----------------------------------------------------------------------===// #include "ICF.h" #include "Config.h" #include "SymbolTable.h" #include "llvm/ADT/Hashing.h" #include "llvm/Object/ELF.h" #include "llvm/Support/ELF.h" #include <algorithm> using namespace lld; using namespace lld::elf; using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; namespace { struct Range { size_t Begin; size_t End; }; template <class ELFT> class ICF { public: void run(); private: void segregate(Range *R, bool Constant); template <class RelTy> bool constantEq(ArrayRef<RelTy> RelsA, ArrayRef<RelTy> RelsB); template <class RelTy> bool variableEq(const InputSection<ELFT> *A, ArrayRef<RelTy> RelsA, const InputSection<ELFT> *B, ArrayRef<RelTy> RelsB); bool equalsConstant(const InputSection<ELFT> *A, const InputSection<ELFT> *B); bool equalsVariable(const InputSection<ELFT> *A, const InputSection<ELFT> *B); std::vector<InputSection<ELFT> *> Sections; std::vector<Range> Ranges; // The main loop is repeated until we get a convergence. bool Repeat = false; // If Repeat is true, we need to repeat. int Cnt = 0; // Counter for the main loop. }; } // Returns a hash value for S. Note that the information about // relocation targets is not included in the hash value. template <class ELFT> static uint64_t getHash(InputSection<ELFT> *S) { return hash_combine(S->Flags, S->getSize(), S->NumRelocations); } // Returns true if section S is subject of ICF. template <class ELFT> static bool isEligible(InputSection<ELFT> *S) { // .init and .fini contains instructions that must be executed to // initialize and finalize the process. They cannot and should not // be merged. return S->Live && (S->Flags & SHF_ALLOC) && !(S->Flags & SHF_WRITE) && S->Name != ".init" && S->Name != ".fini"; } // Before calling this function, all sections in range R must have the // same group ID. template <class ELFT> void ICF<ELFT>::segregate(Range *R, bool Constant) { // This loop rearranges sections in range R so that all sections // that are equal in terms of equals{Constant,Variable} are contiguous // in Sections vector. // // The algorithm is quadratic in the worst case, but that is not an // issue in practice because the number of the distinct sections in // [R.Begin, R.End] is usually very small. while (R->End - R->Begin > 1) { // Divide range R into two. Let Mid be the start index of the // second group. auto Bound = std::stable_partition( Sections.begin() + R->Begin + 1, Sections.begin() + R->End, [&](InputSection<ELFT> *S) { if (Constant) return equalsConstant(Sections[R->Begin], S); return equalsVariable(Sections[R->Begin], S); }); size_t Mid = Bound - Sections.begin(); if (Mid == R->End) return; // Now we split [R.Begin, R.End) into [R.Begin, Mid) and [Mid, R.End). if (Mid - R->Begin > 1) Ranges.push_back({R->Begin, Mid}); R->Begin = Mid; // Update GroupIds for the new group members. We use the index of // the group first member as a group ID because that is unique. for (size_t I = Mid; I < R->End; ++I) Sections[I]->GroupId = Mid; // Since we have split a group, we need to repeat the main loop // later to obtain a convergence. Remember that. Repeat = true; } } // Compare two lists of relocations. template <class ELFT> template <class RelTy> bool ICF<ELFT>::constantEq(ArrayRef<RelTy> RelsA, ArrayRef<RelTy> RelsB) { auto Eq = [](const RelTy &A, const RelTy &B) { return A.r_offset == B.r_offset && A.getType(Config->Mips64EL) == B.getType(Config->Mips64EL) && getAddend<ELFT>(A) == getAddend<ELFT>(B); }; return RelsA.size() == RelsB.size() && std::equal(RelsA.begin(), RelsA.end(), RelsB.begin(), Eq); } // Compare "non-moving" part of two InputSections, namely everything // except relocation targets. template <class ELFT> bool ICF<ELFT>::equalsConstant(const InputSection<ELFT> *A, const InputSection<ELFT> *B) { if (A->NumRelocations != B->NumRelocations || A->Flags != B->Flags || A->getSize() != B->getSize() || A->Data != B->Data) return false; if (A->AreRelocsRela) return constantEq(A->relas(), B->relas()); return constantEq(A->rels(), B->rels()); } // Compare two lists of relocations. Returns true if all pairs of // relocations point to the same section in terms of ICF. template <class ELFT> template <class RelTy> bool ICF<ELFT>::variableEq(const InputSection<ELFT> *A, ArrayRef<RelTy> RelsA, const InputSection<ELFT> *B, ArrayRef<RelTy> RelsB) { auto Eq = [&](const RelTy &RA, const RelTy &RB) { SymbolBody &SA = A->getFile()->getRelocTargetSym(RA); SymbolBody &SB = B->getFile()->getRelocTargetSym(RB); if (&SA == &SB) return true; // Or, the symbols should be pointing to the same section // in terms of the group ID. auto *DA = dyn_cast<DefinedRegular<ELFT>>(&SA); auto *DB = dyn_cast<DefinedRegular<ELFT>>(&SB); if (!DA || !DB) return false; if (DA->Value != DB->Value) return false; auto *X = dyn_cast<InputSection<ELFT>>(DA->Section); auto *Y = dyn_cast<InputSection<ELFT>>(DB->Section); if (!X || !Y) return false; return X->GroupId != 0 && X->GroupId == Y->GroupId; }; return std::equal(RelsA.begin(), RelsA.end(), RelsB.begin(), Eq); } // Compare "moving" part of two InputSections, namely relocation targets. template <class ELFT> bool ICF<ELFT>::equalsVariable(const InputSection<ELFT> *A, const InputSection<ELFT> *B) { if (A->AreRelocsRela) return variableEq(A, A->relas(), B, B->relas()); return variableEq(A, A->rels(), B, B->rels()); } // The main function of ICF. template <class ELFT> void ICF<ELFT>::run() { // Collect sections to merge. for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) if (auto *S = dyn_cast<InputSection<ELFT>>(Sec)) if (isEligible(S)) Sections.push_back(S); // Initially, we use hash values as section group IDs. Therefore, // if two sections have the same ID, they are likely (but not // guaranteed) to have the same static contents in terms of ICF. for (InputSection<ELFT> *S : Sections) // Set MSB to 1 to avoid collisions with non-hash IDs. S->GroupId = getHash(S) | (uint64_t(1) << 63); // From now on, sections in Sections are ordered so that sections in // the same group are consecutive in the vector. std::stable_sort(Sections.begin(), Sections.end(), [](InputSection<ELFT> *A, InputSection<ELFT> *B) { if (A->GroupId != B->GroupId) return A->GroupId < B->GroupId; // Within a group, put the highest alignment // requirement first, so that's the one we'll keep. return B->Alignment < A->Alignment; }); // Split sections into groups by ID. And then we are going to // split groups into more and more smaller groups. // Note that we do not add single element groups because they // are already the smallest. Ranges.reserve(Sections.size()); for (size_t I = 0, E = Sections.size(); I < E - 1;) { // Let J be the first index whose element has a different ID. size_t J = I + 1; while (J < E && Sections[I]->GroupId == Sections[J]->GroupId) ++J; if (J - I > 1) Ranges.push_back({I, J}); I = J; } // Compare static contents and assign unique IDs for each static content. std::for_each(Ranges.begin(), Ranges.end(), [&](Range &R) { segregate(&R, true); }); ++Cnt; // Split groups by comparing relocations until convergence is obtained. do { Repeat = false; std::for_each(Ranges.begin(), Ranges.end(), [&](Range &R) { segregate(&R, false); }); ++Cnt; } while (Repeat); log("ICF needed " + Twine(Cnt) + " iterations"); // Merge sections in the same group. for (Range R : Ranges) { if (R.End - R.Begin == 1) continue; log("selected " + Sections[R.Begin]->Name); for (size_t I = R.Begin + 1; I < R.End; ++I) { log(" removed " + Sections[I]->Name); Sections[R.Begin]->replace(Sections[I]); } } } // ICF entry point function. template <class ELFT> void elf::doIcf() { ICF<ELFT>().run(); } template void elf::doIcf<ELF32LE>(); template void elf::doIcf<ELF32BE>(); template void elf::doIcf<ELF64LE>(); template void elf::doIcf<ELF64BE>(); <|endoftext|>
<commit_before>/* * main.cpp * * Copyright (C) 2015, Achim Lösch <achim.loesch@upb.de>, Ahmad El-Ali <aelali@mail.upb.de> * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. * * encoding: UTF-8 * tab size: 4 * * author: Ahmad El-Ali (aelali@mail.upb.de) * created: 10/5/16 * version: 0.3.0 - extend libmeasure and add application for online monitoring * 0.7.0 - modularized measurement struct * 0.7.4 - add query for currently active processes to libmeasure and system overview gui to msmonitor * 0.8.0 - client server implementation */ #include <cstdlib> #include <stdio.h> #include <iostream> #include <string> #include <signal.h> #include "CServer.hpp" static void termHandler(int s, siginfo_t* info, void* context); CServer srv = CServer(2901, 5); int main(int argc, char **argv) { int port = -1; if(argc > 1) { std::string s = argv[1]; if(s != "-d" && s != "-p") { std::cout<<"-d \t\tdebug information"<< std::endl; std::cout<<"-p [port]\tspecify server port"<< std::endl; return 1; } else if( s == "-d") { if(argc > 3) { s = argv[2]; if(s == "-p") { s = argv[3]; port = atoi(s.c_str()); } } } else if( s == "-p") { if(argc > 3) { s = argv[2]; port = atoi(s.c_str()); s = argv[3]; if( s != "-d") { std::cout.setstate(std::ios_base::failbit); } } else if(argc == 3) { s = argv[2]; port = atoi(s.c_str()); std::cout.setstate(std::ios_base::failbit); } } }else if (argc == 1) { std::cout.setstate(std::ios_base::failbit); } else return 1; if(port != -1) { srv.setPort(port); } std::cout << "initiating server..." << std::endl; struct sigaction act; memset (&act, '\0', sizeof(act)); act.sa_sigaction = &termHandler; act.sa_flags = SA_SIGINFO; if(sigaction(SIGINT, &act, NULL) < 0) { std::cout << "cannot catch SIGINT!" << std::endl; } if(sigaction(SIGUSR1, &act, NULL) < 0) { std::cout << "cannot catch SIGUSR1!" << std::endl; } if(sigaction(SIGUSR2, &act, NULL) < 0) { std::cout << "cannot catch SIGUSR2!" << std::endl; } srv.init(); srv.acceptLoop(); return 0; } void termHandler(int s, siginfo_t* info, void* context) { if(s == SIGINT) //closes client threads and joins them { std::cout << "interrupt triggered!" << std::endl; for(unsigned int i = 0; i < srv.mThreads.size(); i++){ int ret = pthread_cancel(srv.mThreads[i]); if(ret == 0){ ret = pthread_join(srv.mThreads[i], NULL); if( ret != 0){ std::cout << "error joining thread! Error: " << strerror(ret) << std::endl; } else{ std::cout << "client thread terminated!" << std::endl; } } } if(srv.mThreads.size() > 0){ srv.mThreads.clear(); srv.mDataVec.clear(); } std::cout << "terminating server..." << std::endl; exit(0); } else if(s == SIGUSR1) { std::cout << "Application started!" << std::endl; Application a; pid_t sender = info->si_pid; a.mPid = sender; srv.getCurrentTime(a.mTime); a.start = true; srv.mApplications.push_back(a); } else if(s == SIGUSR2) { std::cout << "Application finished!" << std::endl; Application a; pid_t sender = info->si_pid; a.mPid = sender; srv.getCurrentTime(a.mTime); a.start = false; srv.mApplications.push_back(a); } } <commit_msg>Change default port to 2900.<commit_after>/* * main.cpp * * Copyright (C) 2015, Achim Lösch <achim.loesch@upb.de>, Ahmad El-Ali <aelali@mail.upb.de> * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. * * encoding: UTF-8 * tab size: 4 * * author: Ahmad El-Ali (aelali@mail.upb.de) * created: 10/5/16 * version: 0.3.0 - extend libmeasure and add application for online monitoring * 0.7.0 - modularized measurement struct * 0.7.4 - add query for currently active processes to libmeasure and system overview gui to msmonitor * 0.8.0 - client server implementation */ #include <cstdlib> #include <stdio.h> #include <iostream> #include <string> #include <signal.h> #include "CServer.hpp" static void termHandler(int s, siginfo_t* info, void* context); CServer srv = CServer(2900, 5); int main(int argc, char **argv) { int port = -1; if(argc > 1) { std::string s = argv[1]; if(s != "-d" && s != "-p") { std::cout<<"-d \t\tdebug information"<< std::endl; std::cout<<"-p [port]\tspecify server port"<< std::endl; return 1; } else if( s == "-d") { if(argc > 3) { s = argv[2]; if(s == "-p") { s = argv[3]; port = atoi(s.c_str()); } } } else if( s == "-p") { if(argc > 3) { s = argv[2]; port = atoi(s.c_str()); s = argv[3]; if( s != "-d") { std::cout.setstate(std::ios_base::failbit); } } else if(argc == 3) { s = argv[2]; port = atoi(s.c_str()); std::cout.setstate(std::ios_base::failbit); } } }else if (argc == 1) { std::cout.setstate(std::ios_base::failbit); } else return 1; if(port != -1) { srv.setPort(port); } std::cout << "initiating server..." << std::endl; struct sigaction act; memset (&act, '\0', sizeof(act)); act.sa_sigaction = &termHandler; act.sa_flags = SA_SIGINFO; if(sigaction(SIGINT, &act, NULL) < 0) { std::cout << "cannot catch SIGINT!" << std::endl; } if(sigaction(SIGUSR1, &act, NULL) < 0) { std::cout << "cannot catch SIGUSR1!" << std::endl; } if(sigaction(SIGUSR2, &act, NULL) < 0) { std::cout << "cannot catch SIGUSR2!" << std::endl; } srv.init(); srv.acceptLoop(); return 0; } void termHandler(int s, siginfo_t* info, void* context) { if(s == SIGINT) //closes client threads and joins them { std::cout << "interrupt triggered!" << std::endl; for(unsigned int i = 0; i < srv.mThreads.size(); i++){ int ret = pthread_cancel(srv.mThreads[i]); if(ret == 0){ ret = pthread_join(srv.mThreads[i], NULL); if( ret != 0){ std::cout << "error joining thread! Error: " << strerror(ret) << std::endl; } else{ std::cout << "client thread terminated!" << std::endl; } } } if(srv.mThreads.size() > 0){ srv.mThreads.clear(); srv.mDataVec.clear(); } std::cout << "terminating server..." << std::endl; exit(0); } else if(s == SIGUSR1) { std::cout << "Application started!" << std::endl; Application a; pid_t sender = info->si_pid; a.mPid = sender; srv.getCurrentTime(a.mTime); a.start = true; srv.mApplications.push_back(a); } else if(s == SIGUSR2) { std::cout << "Application finished!" << std::endl; Application a; pid_t sender = info->si_pid; a.mPid = sender; srv.getCurrentTime(a.mTime); a.start = false; srv.mApplications.push_back(a); } } <|endoftext|>
<commit_before>// // Copyright 2012 Francisco Jerez // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #include "api/util.hpp" #include "core/program.hpp" using namespace clover; CLOVER_API cl_program clCreateProgramWithSource(cl_context d_ctx, cl_uint count, const char **strings, const size_t *lengths, cl_int *r_errcode) try { auto &ctx = obj(d_ctx); std::string source; if (!count || !strings || any_of(is_zero(), range(strings, count))) throw error(CL_INVALID_VALUE); // Concatenate all the provided fragments together for (unsigned i = 0; i < count; ++i) source += (lengths && lengths[i] ? std::string(strings[i], strings[i] + lengths[i]) : std::string(strings[i])); // ...and create a program object for them. ret_error(r_errcode, CL_SUCCESS); return new program(ctx, source); } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_program clCreateProgramWithBinary(cl_context d_ctx, cl_uint n, const cl_device_id *d_devs, const size_t *lengths, const unsigned char **binaries, cl_int *r_status, cl_int *r_errcode) try { auto &ctx = obj(d_ctx); auto devs = objs(d_devs, n); if (!lengths || !binaries) throw error(CL_INVALID_VALUE); if (any_of([&](const device &dev) { return !count(dev, ctx.devices()); }, devs)) throw error(CL_INVALID_DEVICE); // Deserialize the provided binaries, std::vector<std::pair<cl_int, module>> result = map( [](const unsigned char *p, size_t l) -> std::pair<cl_int, module> { if (!p || !l) return { CL_INVALID_VALUE, {} }; try { compat::istream::buffer_t bin(p, l); compat::istream s(bin); return { CL_SUCCESS, module::deserialize(s) }; } catch (compat::istream::error &e) { return { CL_INVALID_BINARY, {} }; } }, range(binaries, n), range(lengths, n)); // update the status array, if (r_status) copy(map(keys(), result), r_status); if (any_of(key_equals(CL_INVALID_VALUE), result)) throw error(CL_INVALID_VALUE); if (any_of(key_equals(CL_INVALID_BINARY), result)) throw error(CL_INVALID_BINARY); // initialize a program object with them. ret_error(r_errcode, CL_SUCCESS); return new program(ctx, devs, map(values(), result)); } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_program clCreateProgramWithBuiltInKernels(cl_context d_ctx, cl_uint n, const cl_device_id *d_devs, const char *kernel_names, cl_int *r_errcode) try { auto &ctx = obj(d_ctx); auto devs = objs(d_devs, n); if (any_of([&](const device &dev) { return !count(dev, ctx.devices()); }, devs)) throw error(CL_INVALID_DEVICE); // No currently supported built-in kernels. throw error(CL_INVALID_VALUE); } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_int clRetainProgram(cl_program d_prog) try { obj(d_prog).retain(); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clReleaseProgram(cl_program d_prog) try { if (obj(d_prog).release()) delete pobj(d_prog); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clBuildProgram(cl_program d_prog, cl_uint num_devs, const cl_device_id *d_devs, const char *p_opts, void (*pfn_notify)(cl_program, void *), void *user_data) { cl_int ret = clCompileProgram(d_prog, num_devs, d_devs, p_opts, 0, NULL, NULL, pfn_notify, user_data); return (ret == CL_COMPILE_PROGRAM_FAILURE ? CL_BUILD_PROGRAM_FAILURE : ret); } CLOVER_API cl_int clCompileProgram(cl_program d_prog, cl_uint num_devs, const cl_device_id *d_devs, const char *p_opts, cl_uint num_headers, const cl_program *d_header_progs, const char **header_names, void (*pfn_notify)(cl_program, void *), void *user_data) try { auto &prog = obj(d_prog); auto devs = (d_devs ? objs(d_devs, num_devs) : ref_vector<device>(prog.context().devices())); auto opts = (p_opts ? p_opts : ""); header_map headers; if (bool(num_devs) != bool(d_devs) || (!pfn_notify && user_data) || bool(num_headers) != bool(header_names)) throw error(CL_INVALID_VALUE); if (any_of([&](const device &dev) { return !count(dev, prog.context().devices()); }, devs)) throw error(CL_INVALID_DEVICE); if (prog.kernel_ref_count() || !prog.has_source) throw error(CL_INVALID_OPERATION); for_each([&](const char *name, const program &header) { if (!header.has_source) throw error(CL_INVALID_OPERATION); if (!any_of(key_equals(name), headers)) headers.push_back(compat::pair<compat::string, compat::string>( name, header.source())); }, range(header_names, num_headers), objs<allow_empty_tag>(d_header_progs, num_headers)); prog.build(devs, opts, headers); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clUnloadCompiler() { return CL_SUCCESS; } CLOVER_API cl_int clUnloadPlatformCompiler(cl_platform_id d_platform) { return CL_SUCCESS; } CLOVER_API cl_int clGetProgramInfo(cl_program d_prog, cl_program_info param, size_t size, void *r_buf, size_t *r_size) try { property_buffer buf { r_buf, size, r_size }; auto &prog = obj(d_prog); switch (param) { case CL_PROGRAM_REFERENCE_COUNT: buf.as_scalar<cl_uint>() = prog.ref_count(); break; case CL_PROGRAM_CONTEXT: buf.as_scalar<cl_context>() = desc(prog.context()); break; case CL_PROGRAM_NUM_DEVICES: buf.as_scalar<cl_uint>() = (prog.devices().size() ? prog.devices().size() : prog.context().devices().size()); break; case CL_PROGRAM_DEVICES: buf.as_vector<cl_device_id>() = (prog.devices().size() ? descs(prog.devices()) : descs(prog.context().devices())); break; case CL_PROGRAM_SOURCE: buf.as_string() = prog.source(); break; case CL_PROGRAM_BINARY_SIZES: buf.as_vector<size_t>() = map([&](const device &dev) { return prog.binary(dev).size(); }, prog.devices()); break; case CL_PROGRAM_BINARIES: buf.as_matrix<unsigned char>() = map([&](const device &dev) { compat::ostream::buffer_t bin; compat::ostream s(bin); prog.binary(dev).serialize(s); return bin; }, prog.devices()); break; case CL_PROGRAM_NUM_KERNELS: buf.as_scalar<cl_uint>() = prog.symbols().size(); break; case CL_PROGRAM_KERNEL_NAMES: buf.as_string() = fold([](const std::string &a, const module::symbol &s) { return ((a.empty() ? "" : a + ";") + std::string(s.name.begin(), s.name.size())); }, std::string(), prog.symbols()); break; default: throw error(CL_INVALID_VALUE); } return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clGetProgramBuildInfo(cl_program d_prog, cl_device_id d_dev, cl_program_build_info param, size_t size, void *r_buf, size_t *r_size) try { property_buffer buf { r_buf, size, r_size }; auto &prog = obj(d_prog); auto &dev = obj(d_dev); if (!count(dev, prog.context().devices())) return CL_INVALID_DEVICE; switch (param) { case CL_PROGRAM_BUILD_STATUS: buf.as_scalar<cl_build_status>() = prog.build_status(dev); break; case CL_PROGRAM_BUILD_OPTIONS: buf.as_string() = prog.build_opts(dev); break; case CL_PROGRAM_BUILD_LOG: buf.as_string() = prog.build_log(dev); break; default: throw error(CL_INVALID_VALUE); } return CL_SUCCESS; } catch (error &e) { return e.get(); } <commit_msg>clover: Factor input validation of clCompileProgram into a new function v2<commit_after>// // Copyright 2012 Francisco Jerez // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #include "api/util.hpp" #include "core/program.hpp" using namespace clover; namespace { void validate_build_program_common(const program &prog, cl_uint num_devs, const ref_vector<device> &devs, void (*pfn_notify)(cl_program, void *), void *user_data) { if ((!pfn_notify && user_data)) throw error(CL_INVALID_VALUE); if (prog.kernel_ref_count()) throw error(CL_INVALID_OPERATION); if (any_of([&](const device &dev) { return !count(dev, prog.context().devices()); }, devs)) throw error(CL_INVALID_DEVICE); } } CLOVER_API cl_program clCreateProgramWithSource(cl_context d_ctx, cl_uint count, const char **strings, const size_t *lengths, cl_int *r_errcode) try { auto &ctx = obj(d_ctx); std::string source; if (!count || !strings || any_of(is_zero(), range(strings, count))) throw error(CL_INVALID_VALUE); // Concatenate all the provided fragments together for (unsigned i = 0; i < count; ++i) source += (lengths && lengths[i] ? std::string(strings[i], strings[i] + lengths[i]) : std::string(strings[i])); // ...and create a program object for them. ret_error(r_errcode, CL_SUCCESS); return new program(ctx, source); } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_program clCreateProgramWithBinary(cl_context d_ctx, cl_uint n, const cl_device_id *d_devs, const size_t *lengths, const unsigned char **binaries, cl_int *r_status, cl_int *r_errcode) try { auto &ctx = obj(d_ctx); auto devs = objs(d_devs, n); if (!lengths || !binaries) throw error(CL_INVALID_VALUE); if (any_of([&](const device &dev) { return !count(dev, ctx.devices()); }, devs)) throw error(CL_INVALID_DEVICE); // Deserialize the provided binaries, std::vector<std::pair<cl_int, module>> result = map( [](const unsigned char *p, size_t l) -> std::pair<cl_int, module> { if (!p || !l) return { CL_INVALID_VALUE, {} }; try { compat::istream::buffer_t bin(p, l); compat::istream s(bin); return { CL_SUCCESS, module::deserialize(s) }; } catch (compat::istream::error &e) { return { CL_INVALID_BINARY, {} }; } }, range(binaries, n), range(lengths, n)); // update the status array, if (r_status) copy(map(keys(), result), r_status); if (any_of(key_equals(CL_INVALID_VALUE), result)) throw error(CL_INVALID_VALUE); if (any_of(key_equals(CL_INVALID_BINARY), result)) throw error(CL_INVALID_BINARY); // initialize a program object with them. ret_error(r_errcode, CL_SUCCESS); return new program(ctx, devs, map(values(), result)); } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_program clCreateProgramWithBuiltInKernels(cl_context d_ctx, cl_uint n, const cl_device_id *d_devs, const char *kernel_names, cl_int *r_errcode) try { auto &ctx = obj(d_ctx); auto devs = objs(d_devs, n); if (any_of([&](const device &dev) { return !count(dev, ctx.devices()); }, devs)) throw error(CL_INVALID_DEVICE); // No currently supported built-in kernels. throw error(CL_INVALID_VALUE); } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_int clRetainProgram(cl_program d_prog) try { obj(d_prog).retain(); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clReleaseProgram(cl_program d_prog) try { if (obj(d_prog).release()) delete pobj(d_prog); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clBuildProgram(cl_program d_prog, cl_uint num_devs, const cl_device_id *d_devs, const char *p_opts, void (*pfn_notify)(cl_program, void *), void *user_data) { cl_int ret = clCompileProgram(d_prog, num_devs, d_devs, p_opts, 0, NULL, NULL, pfn_notify, user_data); return (ret == CL_COMPILE_PROGRAM_FAILURE ? CL_BUILD_PROGRAM_FAILURE : ret); } CLOVER_API cl_int clCompileProgram(cl_program d_prog, cl_uint num_devs, const cl_device_id *d_devs, const char *p_opts, cl_uint num_headers, const cl_program *d_header_progs, const char **header_names, void (*pfn_notify)(cl_program, void *), void *user_data) try { auto &prog = obj(d_prog); auto devs = (d_devs ? objs(d_devs, num_devs) : ref_vector<device>(prog.context().devices())); auto opts = (p_opts ? p_opts : ""); header_map headers; validate_build_program_common(prog, num_devs, devs, pfn_notify, user_data); if (bool(num_headers) != bool(header_names)) throw error(CL_INVALID_VALUE); if (!prog.has_source) throw error(CL_INVALID_OPERATION); for_each([&](const char *name, const program &header) { if (!header.has_source) throw error(CL_INVALID_OPERATION); if (!any_of(key_equals(name), headers)) headers.push_back(compat::pair<compat::string, compat::string>( name, header.source())); }, range(header_names, num_headers), objs<allow_empty_tag>(d_header_progs, num_headers)); prog.build(devs, opts, headers); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clUnloadCompiler() { return CL_SUCCESS; } CLOVER_API cl_int clUnloadPlatformCompiler(cl_platform_id d_platform) { return CL_SUCCESS; } CLOVER_API cl_int clGetProgramInfo(cl_program d_prog, cl_program_info param, size_t size, void *r_buf, size_t *r_size) try { property_buffer buf { r_buf, size, r_size }; auto &prog = obj(d_prog); switch (param) { case CL_PROGRAM_REFERENCE_COUNT: buf.as_scalar<cl_uint>() = prog.ref_count(); break; case CL_PROGRAM_CONTEXT: buf.as_scalar<cl_context>() = desc(prog.context()); break; case CL_PROGRAM_NUM_DEVICES: buf.as_scalar<cl_uint>() = (prog.devices().size() ? prog.devices().size() : prog.context().devices().size()); break; case CL_PROGRAM_DEVICES: buf.as_vector<cl_device_id>() = (prog.devices().size() ? descs(prog.devices()) : descs(prog.context().devices())); break; case CL_PROGRAM_SOURCE: buf.as_string() = prog.source(); break; case CL_PROGRAM_BINARY_SIZES: buf.as_vector<size_t>() = map([&](const device &dev) { return prog.binary(dev).size(); }, prog.devices()); break; case CL_PROGRAM_BINARIES: buf.as_matrix<unsigned char>() = map([&](const device &dev) { compat::ostream::buffer_t bin; compat::ostream s(bin); prog.binary(dev).serialize(s); return bin; }, prog.devices()); break; case CL_PROGRAM_NUM_KERNELS: buf.as_scalar<cl_uint>() = prog.symbols().size(); break; case CL_PROGRAM_KERNEL_NAMES: buf.as_string() = fold([](const std::string &a, const module::symbol &s) { return ((a.empty() ? "" : a + ";") + std::string(s.name.begin(), s.name.size())); }, std::string(), prog.symbols()); break; default: throw error(CL_INVALID_VALUE); } return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clGetProgramBuildInfo(cl_program d_prog, cl_device_id d_dev, cl_program_build_info param, size_t size, void *r_buf, size_t *r_size) try { property_buffer buf { r_buf, size, r_size }; auto &prog = obj(d_prog); auto &dev = obj(d_dev); if (!count(dev, prog.context().devices())) return CL_INVALID_DEVICE; switch (param) { case CL_PROGRAM_BUILD_STATUS: buf.as_scalar<cl_build_status>() = prog.build_status(dev); break; case CL_PROGRAM_BUILD_OPTIONS: buf.as_string() = prog.build_opts(dev); break; case CL_PROGRAM_BUILD_LOG: buf.as_string() = prog.build_log(dev); break; default: throw error(CL_INVALID_VALUE); } return CL_SUCCESS; } catch (error &e) { return e.get(); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "CppUnitTest.h" #include "..\ProjectEuler\Problem2.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace ProjectEulerTests { TEST_CLASS(Problem2Tests) { public: TEST_METHOD(FibonacciSumEven_Input1_Returns0) { auto result = Problem2::FibonacciSumEven(1); Assert::AreEqual(0, result); } TEST_METHOD(FibonacciSumEven_Input2_Returns2) { auto result = Problem2::FibonacciSumEven(2); Assert::AreEqual(2, result); } TEST_METHOD(FibonacciSumEven_Input3_Returns2) { auto result = Problem2::FibonacciSumEven(3); Assert::AreEqual(2, result); } TEST_METHOD(FibonacciSumEven_Input5_Returns2) { auto result = Problem2::FibonacciSumEven(5); Assert::AreEqual(2, result); } TEST_METHOD(FibonacciSumEven_Input8_Returns10) { auto result = Problem2::FibonacciSumEven(8); Assert::AreEqual(10, result); } TEST_METHOD(Fibonacci_Input1_Returns1) { auto result = Problem2::Fibonacci(1); Assert::AreEqual(1, result); } TEST_METHOD(Fibonacci_Input2_Returns2) { auto result = Problem2::Fibonacci(2); Assert::AreEqual(2, result); } }; }<commit_msg>red-commit - Fibonacci_Input3_Returns3<commit_after>#include "stdafx.h" #include "CppUnitTest.h" #include "..\ProjectEuler\Problem2.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace ProjectEulerTests { TEST_CLASS(Problem2Tests) { public: TEST_METHOD(FibonacciSumEven_Input1_Returns0) { auto result = Problem2::FibonacciSumEven(1); Assert::AreEqual(0, result); } TEST_METHOD(FibonacciSumEven_Input2_Returns2) { auto result = Problem2::FibonacciSumEven(2); Assert::AreEqual(2, result); } TEST_METHOD(FibonacciSumEven_Input3_Returns2) { auto result = Problem2::FibonacciSumEven(3); Assert::AreEqual(2, result); } TEST_METHOD(FibonacciSumEven_Input5_Returns2) { auto result = Problem2::FibonacciSumEven(5); Assert::AreEqual(2, result); } TEST_METHOD(FibonacciSumEven_Input8_Returns10) { auto result = Problem2::FibonacciSumEven(8); Assert::AreEqual(10, result); } TEST_METHOD(Fibonacci_Input1_Returns1) { auto result = Problem2::Fibonacci(1); Assert::AreEqual(1, result); } TEST_METHOD(Fibonacci_Input2_Returns2) { auto result = Problem2::Fibonacci(2); Assert::AreEqual(2, result); } TEST_METHOD(Fibonacci_Input3_Returns3) { auto result = Problem2::Fibonacci(3); Assert::AreEqual(3, result); } }; }<|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/chrome_version_info.h" #include "base/base_paths.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/installer/util/google_update_settings.h" #include "chrome/installer/util/install_util.h" namespace chrome { // static std::string VersionInfo::GetVersionStringModifier() { #if defined(GOOGLE_CHROME_BUILD) base::FilePath module; string16 channel; if (PathService::Get(base::FILE_MODULE, &module)) { bool is_system_install = !InstallUtil::IsPerUserInstall(module.value().c_str()); GoogleUpdateSettings::GetChromeChannelAndModifiers(is_system_install, &channel); } return UTF16ToASCII(channel); #else return std::string(); #endif } // static VersionInfo::Channel VersionInfo::GetChannel() { #if defined(GOOGLE_CHROME_BUILD) std::wstring channel(L"unknown"); base::FilePath module; if (PathService::Get(base::FILE_MODULE, &module)) { bool is_system_install = !InstallUtil::IsPerUserInstall(module.value().c_str()); channel = GoogleUpdateSettings::GetChromeChannel(is_system_install); } if (channel.empty()) { return CHANNEL_STABLE; } else if (channel == L"beta") { return CHANNEL_BETA; } else if (channel == L"dev") { return CHANNEL_DEV; } else if (channel == L"canary") { return CHANNEL_CANARY; } #endif return CHANNEL_UNKNOWN; } } // namespace chrome <commit_msg>add 'Aura' to version if USE_AURA on windows<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/chrome_version_info.h" #include "base/base_paths.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/installer/util/google_update_settings.h" #include "chrome/installer/util/install_util.h" namespace chrome { // static std::string VersionInfo::GetVersionStringModifier() { #if defined(GOOGLE_CHROME_BUILD) base::FilePath module; string16 channel; if (PathService::Get(base::FILE_MODULE, &module)) { bool is_system_install = !InstallUtil::IsPerUserInstall(module.value().c_str()); GoogleUpdateSettings::GetChromeChannelAndModifiers(is_system_install, &channel); } #if defined(USE_AURA) channel += L" Aura"; #endif return UTF16ToASCII(channel); #else return std::string(); #endif } // static VersionInfo::Channel VersionInfo::GetChannel() { #if defined(GOOGLE_CHROME_BUILD) std::wstring channel(L"unknown"); base::FilePath module; if (PathService::Get(base::FILE_MODULE, &module)) { bool is_system_install = !InstallUtil::IsPerUserInstall(module.value().c_str()); channel = GoogleUpdateSettings::GetChromeChannel(is_system_install); } if (channel.empty()) { return CHANNEL_STABLE; } else if (channel == L"beta") { return CHANNEL_BETA; } else if (channel == L"dev") { return CHANNEL_DEV; } else if (channel == L"canary") { return CHANNEL_CANARY; } #endif return CHANNEL_UNKNOWN; } } // namespace chrome <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: IBM Corporation * * Copyright: 2008 by IBM Corporation * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /************************************************************************* * @file * Page master used bye XFMasterPage. * It is the real object to define header and footer of pages. ************************************************************************/ #include "xfpagemaster.hxx" #include "ixfstream.hxx" #include "ixfattrlist.hxx" #include "xfborders.hxx" #include "xfshadow.hxx" #include "xfcolumns.hxx" #include "xfheaderstyle.hxx" #include "xffooterstyle.hxx" #include "xfbgimage.hxx" XFPageMaster::XFPageMaster() { m_fPageWidth = 0; m_fPageHeight = 0; m_eUsage = enumXFPageUsageNone; m_eTextDir = enumXFTextDirNone; m_bPrintOrient = sal_True; m_pBorders = NULL; m_pShadow = NULL; m_pColumns = NULL; m_pBGImage = NULL; m_pHeaderStyle = NULL; m_pFooterStyle = NULL; m_eSepAlign = enumXFAlignNone; m_fSepWidth = 0; m_aSepColor = 0; m_fSepSpaceAbove = 0; m_fSepSpaceBelow = 0; m_nSepLengthPercent = 0; } XFPageMaster::~XFPageMaster() { if( m_pBorders ) delete m_pBorders; if( m_pShadow ) delete m_pShadow; if( m_pColumns ) delete m_pColumns; if( m_pHeaderStyle ) delete m_pHeaderStyle; if( m_pFooterStyle ) delete m_pFooterStyle; if( m_pBGImage ) delete m_pBGImage; } enumXFStyle XFPageMaster::GetStyleFamily() { return enumXFStylePageMaster; } void XFPageMaster::SetPageWidth(double width) { m_fPageWidth = width; } void XFPageMaster::SetPageHeight(double height) { m_fPageHeight = height; } void XFPageMaster::SetMargins(double left, double right,double top, double bottom) { if( left != -1 ) m_aMargin.SetLeft(left); if( right != -1 ) m_aMargin.SetRight(right); if( top != -1 ) m_aMargin.SetTop(top); if( bottom != -1 ) m_aMargin.SetBottom(bottom); } void XFPageMaster::SetBorders(XFBorders *pBorders) { if( m_pBorders && (pBorders != m_pBorders) ) delete m_pBorders; m_pBorders = pBorders; } void XFPageMaster::SetShadow(XFShadow *pShadow) { if( m_pShadow && (pShadow != m_pShadow) ) delete m_pShadow; m_pShadow = pShadow; } void XFPageMaster::SetBackColor(XFColor color) { m_aBackColor = color; } void XFPageMaster::SetBackImage(XFBGImage *image) { if( m_pBGImage ) delete m_pBGImage; m_pBGImage = image; } void XFPageMaster::SetColumns(XFColumns *pColumns) { if( m_pColumns && (pColumns != m_pColumns) ) delete m_pColumns; m_pColumns = pColumns; } void XFPageMaster::SetHeaderStyle(XFHeaderStyle *pHeaderStyle) { if( m_pHeaderStyle && (pHeaderStyle != m_pHeaderStyle) ) delete m_pHeaderStyle; m_pHeaderStyle = pHeaderStyle; } void XFPageMaster::SetFooterStyle(XFFooterStyle *pFooterStyle) { if( m_pFooterStyle && (pFooterStyle != m_pFooterStyle) ) delete m_pFooterStyle; m_pFooterStyle = pFooterStyle; } void XFPageMaster::SetFootNoteSeparator( enumXFAlignType align, double width, sal_Int32 lengthPercent, double spaceAbove, double spaceBelow, XFColor color ) { m_eSepAlign = align; m_fSepWidth = width; m_nSepLengthPercent = lengthPercent; m_fSepSpaceAbove = spaceAbove; m_fSepSpaceBelow = spaceBelow; m_aSepColor = color; } /** * <style:page-master style:name="pm1"> <style:properties fo:page-width="20.999cm" fo:page-height="29.699cm" style:num-format="1" style:print-orientation="portrait" fo:margin-top="1.249cm" fo:margin-bottom="1.249cm" fo:margin-left="3.175cm" fo:margin-right="3.175cm" style:writing-mode="lr-tb" style:layout-grid-color="#c0c0c0" style:layout-grid-lines="42" style:layout-grid-base-height="0.494cm" style:layout-grid-ruby-height="0.141cm" style:layout-grid-mode="none" style:layout-grid-ruby-below="false" style:layout-grid-print="false" style:layout-grid-display="false" style:footnote-max-height="0cm"> <style:footnote-sep style:width="0.018cm" style:distance-before-sep="0.101cm" style:distance-after-sep="0.101cm" style:adjustment="left" style:rel-width="25%" style:color="#000000"/> </style:properties> <style:header-style> <style:properties fo:min-height="1.291cm" fo:margin-bottom="0.792cm" style:dynamic-spacing="true"/> </style:header-style> <style:footer-style> <style:properties fo:min-height="1.291cm" fo:margin-top="0.792cm" style:dynamic-spacing="true"/> </style:footer-style> </style:page-master> */ void XFPageMaster::ToXml(IXFStream *pStream) { IXFAttrList *pAttrList = pStream->GetAttrList(); pAttrList->Clear(); pAttrList->AddAttribute(A2OUSTR("style:name"),GetStyleName()); if( m_eUsage != enumXFPageUsageNone ) pAttrList->AddAttribute(A2OUSTR("style:page-usage"), GetPageUsageName(m_eUsage)); pStream->StartElement( A2OUSTR("style:page-master") ); //style:properties pAttrList->Clear(); if( m_fPageWidth != 0 ) pAttrList->AddAttribute( A2OUSTR("fo:page-width"), DoubleToOUString(m_fPageWidth) + A2OUSTR("cm") ); if( m_fPageHeight != 0 ) pAttrList->AddAttribute( A2OUSTR("fo:page-height"), DoubleToOUString(m_fPageHeight) + A2OUSTR("cm") ); m_aMargin.ToXml(pStream); if( m_bPrintOrient ) pAttrList->AddAttribute( A2OUSTR("style:print-orientation"), A2OUSTR("portrait") ); else pAttrList->AddAttribute( A2OUSTR("style:print-orientation"), A2OUSTR("landscape") ); if( m_pBorders ) m_pBorders->ToXml(pStream); if( m_pShadow ) pAttrList->AddAttribute( A2OUSTR("style:shadow"), m_pShadow->ToString() ); if( m_aBackColor.IsValid() ) pAttrList->AddAttribute( A2OUSTR("fo:background-color"), m_aBackColor.ToString() ); //text directory if( m_eTextDir != enumXFTextDirNone ) pAttrList->AddAttribute( A2OUSTR("style:writing-mode"), GetTextDirName(m_eTextDir) ); pStream->StartElement( A2OUSTR("style:properties") ); if( m_pColumns ) m_pColumns->ToXml(pStream); if( m_pBGImage ) m_pBGImage->ToXml(pStream); if( m_eSepAlign || m_nSepLengthPercent>0 || m_fSepSpaceAbove>0 || m_fSepSpaceBelow>0 ) { pAttrList->Clear(); pAttrList->AddAttribute( A2OUSTR("style:width"), DoubleToOUString(m_fSepWidth) + A2OUSTR("cm") ); pAttrList->AddAttribute( A2OUSTR("style:distance-before-sep"), DoubleToOUString(m_fSepSpaceAbove) + A2OUSTR("cm") ); pAttrList->AddAttribute( A2OUSTR("style:distance-after-sep"), DoubleToOUString(m_fSepSpaceBelow) + A2OUSTR("cm") ); pAttrList->AddAttribute( A2OUSTR("style:color"), m_aSepColor.ToString() ); if( m_eSepAlign == enumXFAlignStart ) pAttrList->AddAttribute( A2OUSTR("style:adjustment"), A2OUSTR("left") ); else if( m_eSepAlign == enumXFAlignCenter ) pAttrList->AddAttribute( A2OUSTR("style:adjustment"), A2OUSTR("center") ); else if( m_eSepAlign == enumXFAlignEnd ) pAttrList->AddAttribute( A2OUSTR("style:adjustment"), A2OUSTR("right") ); pAttrList->AddAttribute( A2OUSTR("style:rel-width"), Int32ToOUString(m_nSepLengthPercent) + A2OUSTR("%") ); pStream->StartElement( A2OUSTR("style:footnote-sep") ); pStream->EndElement( A2OUSTR("style:footnote-sep") ); } pStream->EndElement( A2OUSTR("style:properties") ); //header style: if( m_pHeaderStyle ) m_pHeaderStyle->ToXml(pStream); //footer style: if( m_pFooterStyle ) m_pFooterStyle->ToXml(pStream); pStream->EndElement( A2OUSTR("style:page-master") ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Perform initalization in initialization list<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: IBM Corporation * * Copyright: 2008 by IBM Corporation * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /************************************************************************* * @file * Page master used bye XFMasterPage. * It is the real object to define header and footer of pages. ************************************************************************/ #include "xfpagemaster.hxx" #include "ixfstream.hxx" #include "ixfattrlist.hxx" #include "xfborders.hxx" #include "xfshadow.hxx" #include "xfcolumns.hxx" #include "xfheaderstyle.hxx" #include "xffooterstyle.hxx" #include "xfbgimage.hxx" XFPageMaster::XFPageMaster() : m_fPageWidth(0), m_fPageHeight(0), m_eUsage(enumXFPageUsageNone), m_eTextDir(enumXFTextDirNone), m_bPrintOrient(sal_True), m_pBorders(NULL), m_pShadow(NULL), m_pColumns(NULL), m_pBGImage(NULL), m_pHeaderStyle(NULL), m_pFooterStyle(NULL), m_eSepAlign(enumXFAlignNone), m_fSepWidth(0), m_aSepColor(0), m_fSepSpaceAbove(0), m_fSepSpaceBelow(0), m_nSepLengthPercent(0) { } XFPageMaster::~XFPageMaster() { if( m_pBorders ) delete m_pBorders; if( m_pShadow ) delete m_pShadow; if( m_pColumns ) delete m_pColumns; if( m_pHeaderStyle ) delete m_pHeaderStyle; if( m_pFooterStyle ) delete m_pFooterStyle; if( m_pBGImage ) delete m_pBGImage; } enumXFStyle XFPageMaster::GetStyleFamily() { return enumXFStylePageMaster; } void XFPageMaster::SetPageWidth(double width) { m_fPageWidth = width; } void XFPageMaster::SetPageHeight(double height) { m_fPageHeight = height; } void XFPageMaster::SetMargins(double left, double right,double top, double bottom) { if( left != -1 ) m_aMargin.SetLeft(left); if( right != -1 ) m_aMargin.SetRight(right); if( top != -1 ) m_aMargin.SetTop(top); if( bottom != -1 ) m_aMargin.SetBottom(bottom); } void XFPageMaster::SetBorders(XFBorders *pBorders) { if( m_pBorders && (pBorders != m_pBorders) ) delete m_pBorders; m_pBorders = pBorders; } void XFPageMaster::SetShadow(XFShadow *pShadow) { if( m_pShadow && (pShadow != m_pShadow) ) delete m_pShadow; m_pShadow = pShadow; } void XFPageMaster::SetBackColor(XFColor color) { m_aBackColor = color; } void XFPageMaster::SetBackImage(XFBGImage *image) { if( m_pBGImage ) delete m_pBGImage; m_pBGImage = image; } void XFPageMaster::SetColumns(XFColumns *pColumns) { if( m_pColumns && (pColumns != m_pColumns) ) delete m_pColumns; m_pColumns = pColumns; } void XFPageMaster::SetHeaderStyle(XFHeaderStyle *pHeaderStyle) { if( m_pHeaderStyle && (pHeaderStyle != m_pHeaderStyle) ) delete m_pHeaderStyle; m_pHeaderStyle = pHeaderStyle; } void XFPageMaster::SetFooterStyle(XFFooterStyle *pFooterStyle) { if( m_pFooterStyle && (pFooterStyle != m_pFooterStyle) ) delete m_pFooterStyle; m_pFooterStyle = pFooterStyle; } void XFPageMaster::SetFootNoteSeparator( enumXFAlignType align, double width, sal_Int32 lengthPercent, double spaceAbove, double spaceBelow, XFColor color ) { m_eSepAlign = align; m_fSepWidth = width; m_nSepLengthPercent = lengthPercent; m_fSepSpaceAbove = spaceAbove; m_fSepSpaceBelow = spaceBelow; m_aSepColor = color; } /** * <style:page-master style:name="pm1"> <style:properties fo:page-width="20.999cm" fo:page-height="29.699cm" style:num-format="1" style:print-orientation="portrait" fo:margin-top="1.249cm" fo:margin-bottom="1.249cm" fo:margin-left="3.175cm" fo:margin-right="3.175cm" style:writing-mode="lr-tb" style:layout-grid-color="#c0c0c0" style:layout-grid-lines="42" style:layout-grid-base-height="0.494cm" style:layout-grid-ruby-height="0.141cm" style:layout-grid-mode="none" style:layout-grid-ruby-below="false" style:layout-grid-print="false" style:layout-grid-display="false" style:footnote-max-height="0cm"> <style:footnote-sep style:width="0.018cm" style:distance-before-sep="0.101cm" style:distance-after-sep="0.101cm" style:adjustment="left" style:rel-width="25%" style:color="#000000"/> </style:properties> <style:header-style> <style:properties fo:min-height="1.291cm" fo:margin-bottom="0.792cm" style:dynamic-spacing="true"/> </style:header-style> <style:footer-style> <style:properties fo:min-height="1.291cm" fo:margin-top="0.792cm" style:dynamic-spacing="true"/> </style:footer-style> </style:page-master> */ void XFPageMaster::ToXml(IXFStream *pStream) { IXFAttrList *pAttrList = pStream->GetAttrList(); pAttrList->Clear(); pAttrList->AddAttribute(A2OUSTR("style:name"),GetStyleName()); if( m_eUsage != enumXFPageUsageNone ) pAttrList->AddAttribute(A2OUSTR("style:page-usage"), GetPageUsageName(m_eUsage)); pStream->StartElement( A2OUSTR("style:page-master") ); //style:properties pAttrList->Clear(); if( m_fPageWidth != 0 ) pAttrList->AddAttribute( A2OUSTR("fo:page-width"), DoubleToOUString(m_fPageWidth) + A2OUSTR("cm") ); if( m_fPageHeight != 0 ) pAttrList->AddAttribute( A2OUSTR("fo:page-height"), DoubleToOUString(m_fPageHeight) + A2OUSTR("cm") ); m_aMargin.ToXml(pStream); if( m_bPrintOrient ) pAttrList->AddAttribute( A2OUSTR("style:print-orientation"), A2OUSTR("portrait") ); else pAttrList->AddAttribute( A2OUSTR("style:print-orientation"), A2OUSTR("landscape") ); if( m_pBorders ) m_pBorders->ToXml(pStream); if( m_pShadow ) pAttrList->AddAttribute( A2OUSTR("style:shadow"), m_pShadow->ToString() ); if( m_aBackColor.IsValid() ) pAttrList->AddAttribute( A2OUSTR("fo:background-color"), m_aBackColor.ToString() ); //text directory if( m_eTextDir != enumXFTextDirNone ) pAttrList->AddAttribute( A2OUSTR("style:writing-mode"), GetTextDirName(m_eTextDir) ); pStream->StartElement( A2OUSTR("style:properties") ); if( m_pColumns ) m_pColumns->ToXml(pStream); if( m_pBGImage ) m_pBGImage->ToXml(pStream); if( m_eSepAlign || m_nSepLengthPercent>0 || m_fSepSpaceAbove>0 || m_fSepSpaceBelow>0 ) { pAttrList->Clear(); pAttrList->AddAttribute( A2OUSTR("style:width"), DoubleToOUString(m_fSepWidth) + A2OUSTR("cm") ); pAttrList->AddAttribute( A2OUSTR("style:distance-before-sep"), DoubleToOUString(m_fSepSpaceAbove) + A2OUSTR("cm") ); pAttrList->AddAttribute( A2OUSTR("style:distance-after-sep"), DoubleToOUString(m_fSepSpaceBelow) + A2OUSTR("cm") ); pAttrList->AddAttribute( A2OUSTR("style:color"), m_aSepColor.ToString() ); if( m_eSepAlign == enumXFAlignStart ) pAttrList->AddAttribute( A2OUSTR("style:adjustment"), A2OUSTR("left") ); else if( m_eSepAlign == enumXFAlignCenter ) pAttrList->AddAttribute( A2OUSTR("style:adjustment"), A2OUSTR("center") ); else if( m_eSepAlign == enumXFAlignEnd ) pAttrList->AddAttribute( A2OUSTR("style:adjustment"), A2OUSTR("right") ); pAttrList->AddAttribute( A2OUSTR("style:rel-width"), Int32ToOUString(m_nSepLengthPercent) + A2OUSTR("%") ); pStream->StartElement( A2OUSTR("style:footnote-sep") ); pStream->EndElement( A2OUSTR("style:footnote-sep") ); } pStream->EndElement( A2OUSTR("style:properties") ); //header style: if( m_pHeaderStyle ) m_pHeaderStyle->ToXml(pStream); //footer style: if( m_pFooterStyle ) m_pFooterStyle->ToXml(pStream); pStream->EndElement( A2OUSTR("style:page-master") ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/notification_provider.h" #include "base/string_util.h" #include "base/task.h" #include "chrome/common/render_messages.h" #include "chrome/common/url_constants.h" #include "chrome/renderer/render_thread.h" #include "chrome/renderer/render_view.h" #include "third_party/WebKit/WebKit/chromium/public/WebDocument.h" #include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/WebKit/chromium/public/WebNotificationPermissionCallback.h" #include "third_party/WebKit/WebKit/chromium/public/WebURL.h" using WebKit::WebDocument; using WebKit::WebNotification; using WebKit::WebNotificationPresenter; using WebKit::WebNotificationPermissionCallback; using WebKit::WebSecurityOrigin; using WebKit::WebString; using WebKit::WebURL; NotificationProvider::NotificationProvider(RenderView* view) : view_(view) { } bool NotificationProvider::show(const WebNotification& notification) { int notification_id = manager_.RegisterNotification(notification); if (notification.isHTML()) return ShowHTML(notification, notification_id); else return ShowText(notification, notification_id); } void NotificationProvider::cancel(const WebNotification& notification) { int id; bool id_found = manager_.GetId(notification, id); // Won't be found if the notification has already been closed by the user. if (id_found) Send(new ViewHostMsg_CancelDesktopNotification(view_->routing_id(), id)); } void NotificationProvider::objectDestroyed( const WebNotification& notification) { int id; bool id_found = manager_.GetId(notification, id); // Won't be found if the notification has already been closed by the user. if (id_found) manager_.UnregisterNotification(id); } WebNotificationPresenter::Permission NotificationProvider::checkPermission( const WebURL& url) { int permission; Send(new ViewHostMsg_CheckNotificationPermission( view_->routing_id(), url, &permission)); return static_cast<WebNotificationPresenter::Permission>(permission); } void NotificationProvider::requestPermission( const WebSecurityOrigin& origin, WebNotificationPermissionCallback* callback) { // We only request permission in response to a user gesture. if (!view_->webview()->mainFrame()->isProcessingUserGesture()) return; int id = manager_.RegisterPermissionRequest(callback); Send(new ViewHostMsg_RequestNotificationPermission(view_->routing_id(), GURL(origin.toString()), id)); } bool NotificationProvider::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(NotificationProvider, message) IPC_MESSAGE_HANDLER(ViewMsg_PostDisplayToNotificationObject, OnDisplay); IPC_MESSAGE_HANDLER(ViewMsg_PostErrorToNotificationObject, OnError); IPC_MESSAGE_HANDLER(ViewMsg_PostCloseToNotificationObject, OnClose); IPC_MESSAGE_HANDLER(ViewMsg_PermissionRequestDone, OnPermissionRequestComplete); IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void NotificationProvider::OnNavigate() { manager_.Clear(); } bool NotificationProvider::ShowHTML(const WebNotification& notification, int id) { // Disallow HTML notifications from non-HTTP schemes. GURL url = notification.url(); if (!url.SchemeIs(chrome::kHttpScheme) && !url.SchemeIs(chrome::kHttpsScheme) && !url.SchemeIs(chrome::kExtensionScheme)) return false; DCHECK(notification.isHTML()); return Send(new ViewHostMsg_ShowDesktopNotification(view_->routing_id(), GURL(view_->webview()->mainFrame()->url()).GetOrigin(), notification.url(), id)); } bool NotificationProvider::ShowText(const WebNotification& notification, int id) { DCHECK(!notification.isHTML()); return Send(new ViewHostMsg_ShowDesktopNotificationText(view_->routing_id(), GURL(view_->webview()->mainFrame()->url()).GetOrigin(), notification.iconURL(), notification.title(), notification.body(), id)); } void NotificationProvider::OnDisplay(int id) { WebNotification notification; bool found = manager_.GetNotification(id, &notification); // |found| may be false if the WebNotification went out of scope in // the page before it was actually displayed to the user. if (found) notification.dispatchDisplayEvent(); } void NotificationProvider::OnError(int id, const WebString& message) { WebNotification notification; bool found = manager_.GetNotification(id, &notification); // |found| may be false if the WebNotification went out of scope in // the page before the error occurred. if (found) notification.dispatchErrorEvent(message); } void NotificationProvider::OnClose(int id, bool by_user) { WebNotification notification; bool found = manager_.GetNotification(id, &notification); // |found| may be false if the WebNotification went out of scope in // the page before the associated toast was closed by the user. if (found) { notification.dispatchCloseEvent(by_user); manager_.UnregisterNotification(id); } } void NotificationProvider::OnPermissionRequestComplete(int id) { WebNotificationPermissionCallback* callback = manager_.GetCallback(id); DCHECK(callback); callback->permissionRequestComplete(); manager_.OnPermissionRequestComplete(id); } bool NotificationProvider::Send(IPC::Message* message) { return RenderThread::current()->Send(message); } <commit_msg>Allow creating HTML notifications with the data: scheme. I've confirmed this doesn't open up the same extra privileges as javascript: scheme, which is still disallowed.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/notification_provider.h" #include "base/string_util.h" #include "base/task.h" #include "chrome/common/render_messages.h" #include "chrome/common/url_constants.h" #include "chrome/renderer/render_thread.h" #include "chrome/renderer/render_view.h" #include "third_party/WebKit/WebKit/chromium/public/WebDocument.h" #include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/WebKit/chromium/public/WebNotificationPermissionCallback.h" #include "third_party/WebKit/WebKit/chromium/public/WebURL.h" using WebKit::WebDocument; using WebKit::WebNotification; using WebKit::WebNotificationPresenter; using WebKit::WebNotificationPermissionCallback; using WebKit::WebSecurityOrigin; using WebKit::WebString; using WebKit::WebURL; NotificationProvider::NotificationProvider(RenderView* view) : view_(view) { } bool NotificationProvider::show(const WebNotification& notification) { int notification_id = manager_.RegisterNotification(notification); if (notification.isHTML()) return ShowHTML(notification, notification_id); else return ShowText(notification, notification_id); } void NotificationProvider::cancel(const WebNotification& notification) { int id; bool id_found = manager_.GetId(notification, id); // Won't be found if the notification has already been closed by the user. if (id_found) Send(new ViewHostMsg_CancelDesktopNotification(view_->routing_id(), id)); } void NotificationProvider::objectDestroyed( const WebNotification& notification) { int id; bool id_found = manager_.GetId(notification, id); // Won't be found if the notification has already been closed by the user. if (id_found) manager_.UnregisterNotification(id); } WebNotificationPresenter::Permission NotificationProvider::checkPermission( const WebURL& url) { int permission; Send(new ViewHostMsg_CheckNotificationPermission( view_->routing_id(), url, &permission)); return static_cast<WebNotificationPresenter::Permission>(permission); } void NotificationProvider::requestPermission( const WebSecurityOrigin& origin, WebNotificationPermissionCallback* callback) { // We only request permission in response to a user gesture. if (!view_->webview()->mainFrame()->isProcessingUserGesture()) return; int id = manager_.RegisterPermissionRequest(callback); Send(new ViewHostMsg_RequestNotificationPermission(view_->routing_id(), GURL(origin.toString()), id)); } bool NotificationProvider::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(NotificationProvider, message) IPC_MESSAGE_HANDLER(ViewMsg_PostDisplayToNotificationObject, OnDisplay); IPC_MESSAGE_HANDLER(ViewMsg_PostErrorToNotificationObject, OnError); IPC_MESSAGE_HANDLER(ViewMsg_PostCloseToNotificationObject, OnClose); IPC_MESSAGE_HANDLER(ViewMsg_PermissionRequestDone, OnPermissionRequestComplete); IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void NotificationProvider::OnNavigate() { manager_.Clear(); } bool NotificationProvider::ShowHTML(const WebNotification& notification, int id) { // Disallow HTML notifications from unwanted schemes. javascript: // in particular allows unwanted cross-domain access. GURL url = notification.url(); if (!url.SchemeIs(chrome::kHttpScheme) && !url.SchemeIs(chrome::kHttpsScheme) && !url.SchemeIs(chrome::kExtensionScheme) && !url.SchemeIs(chrome::kDataScheme)) return false; DCHECK(notification.isHTML()); return Send(new ViewHostMsg_ShowDesktopNotification(view_->routing_id(), GURL(view_->webview()->mainFrame()->url()).GetOrigin(), notification.url(), id)); } bool NotificationProvider::ShowText(const WebNotification& notification, int id) { DCHECK(!notification.isHTML()); return Send(new ViewHostMsg_ShowDesktopNotificationText(view_->routing_id(), GURL(view_->webview()->mainFrame()->url()).GetOrigin(), notification.iconURL(), notification.title(), notification.body(), id)); } void NotificationProvider::OnDisplay(int id) { WebNotification notification; bool found = manager_.GetNotification(id, &notification); // |found| may be false if the WebNotification went out of scope in // the page before it was actually displayed to the user. if (found) notification.dispatchDisplayEvent(); } void NotificationProvider::OnError(int id, const WebString& message) { WebNotification notification; bool found = manager_.GetNotification(id, &notification); // |found| may be false if the WebNotification went out of scope in // the page before the error occurred. if (found) notification.dispatchErrorEvent(message); } void NotificationProvider::OnClose(int id, bool by_user) { WebNotification notification; bool found = manager_.GetNotification(id, &notification); // |found| may be false if the WebNotification went out of scope in // the page before the associated toast was closed by the user. if (found) { notification.dispatchCloseEvent(by_user); manager_.UnregisterNotification(id); } } void NotificationProvider::OnPermissionRequestComplete(int id) { WebNotificationPermissionCallback* callback = manager_.GetCallback(id); DCHECK(callback); callback->permissionRequestComplete(); manager_.OnPermissionRequestComplete(id); } bool NotificationProvider::Send(IPC::Message* message) { return RenderThread::current()->Send(message); } <|endoftext|>
<commit_before>// Copyright 2020-present MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <bsoncxx/builder/basic/document.hpp> #include <bsoncxx/builder/basic/kvp.hpp> #include <bsoncxx/json.hpp> #include <mongocxx/client.hpp> #include <mongocxx/client_session.hpp> #include <mongocxx/collection.hpp> #include <mongocxx/exception/exception.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/options/insert.hpp> #include <mongocxx/options/transaction.hpp> #include <mongocxx/read_concern.hpp> #include <mongocxx/read_preference.hpp> #include <mongocxx/uri.hpp> #include <mongocxx/write_concern.hpp> using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; using namespace mongocxx; // // This example shows how to use the client_session::with_transaction helper to // conveniently run a custom callback inside of a transaction. // int main() { // Start Transactions withTxn API Example 1 // The mongocxx::instance constructor and destructor initialize and shut down the driver, // respectively. Therefore, a mongocxx::instance must be created before using the driver and // must remain alive for as long as the driver is in use. mongocxx::instance inst{}; // For a replica set, include the replica set name and a seedlist of the members in the URI // string; e.g. // uriString = // 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl' // For a sharded cluster, connect to the mongos instances; e.g. // uriString = 'mongodb://mongos0.example.com:27017,mongos1.example.com:27017/' mongocxx::client client{mongocxx::uri{"mongodb://localhost/?replicaSet=replset"}}; write_concern wc_majority{}; wc_majority.acknowledge_level(write_concern::level::k_majority); read_concern rc_local{}; rc_local.acknowledge_level(read_concern::level::k_local); read_preference rp_primary{}; rp_primary.mode(read_preference::read_mode::k_primary); // Prereq: Create collections. CRUD operations in transactions must be on existing collections. auto foo = client["mydb1"]["foo"]; auto bar = client["mydb2"]["bar"]; try { options::insert opts; opts.write_concern(wc_majority); foo.insert_one(make_document(kvp("abc", 0)), opts); bar.insert_one(make_document(kvp("xyz", 0)), opts); } catch (const mongocxx::exception& e) { std::cout << "An exception occurred while inserting: " << e.what() << std::endl; return EXIT_FAILURE; } // Step 1: Define the callback that specifies the sequence of operations to perform inside the // transactions. client_session::with_transaction_cb callback = [&](client_session* session) { // Important:: You must pass the session to the operations. foo.insert_one(*session, make_document(kvp("abc", 1))); bar.insert_one(*session, make_document(kvp("xyz", 999))); }; // Step 2: Start a client session auto session = client.start_session(); // Step 3: Use with_transaction to start a transaction, execute the callback, // and commit (or abort on error). try { options::transaction opts; opts.write_concern(wc_majority); opts.read_concern(rc_local); opts.read_preference(rp_primary); session.with_transaction(callback, opts); } catch (const mongocxx::exception& e) { std::cout << "An exception occurred: " << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; // End Transactions withTxn API Example 1 } <commit_msg>CXX-1967 update comment<commit_after>// Copyright 2020-present MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <bsoncxx/builder/basic/document.hpp> #include <bsoncxx/builder/basic/kvp.hpp> #include <bsoncxx/json.hpp> #include <mongocxx/client.hpp> #include <mongocxx/client_session.hpp> #include <mongocxx/collection.hpp> #include <mongocxx/exception/exception.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/options/insert.hpp> #include <mongocxx/options/transaction.hpp> #include <mongocxx/read_concern.hpp> #include <mongocxx/read_preference.hpp> #include <mongocxx/uri.hpp> #include <mongocxx/write_concern.hpp> using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; using namespace mongocxx; // // This example shows how to use the client_session::with_transaction helper to // conveniently run a custom callback inside of a transaction. // int main() { // Start Transactions withTxn API Example 1 // The mongocxx::instance constructor and destructor initialize and shut down the driver, // respectively. Therefore, a mongocxx::instance must be created before using the driver and // must remain alive for as long as the driver is in use. mongocxx::instance inst{}; // For a replica set, include the replica set name and a seedlist of the members in the URI // string; e.g. // uriString = // 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl' // For a sharded cluster, connect to the mongos instances; e.g. // uriString = 'mongodb://mongos0.example.com:27017,mongos1.example.com:27017/' mongocxx::client client{mongocxx::uri{"mongodb://localhost/?replicaSet=replset"}}; write_concern wc_majority{}; wc_majority.acknowledge_level(write_concern::level::k_majority); read_concern rc_local{}; rc_local.acknowledge_level(read_concern::level::k_local); read_preference rp_primary{}; rp_primary.mode(read_preference::read_mode::k_primary); // Prereq: Create collections. auto foo = client["mydb1"]["foo"]; auto bar = client["mydb2"]["bar"]; try { options::insert opts; opts.write_concern(wc_majority); foo.insert_one(make_document(kvp("abc", 0)), opts); bar.insert_one(make_document(kvp("xyz", 0)), opts); } catch (const mongocxx::exception& e) { std::cout << "An exception occurred while inserting: " << e.what() << std::endl; return EXIT_FAILURE; } // Step 1: Define the callback that specifies the sequence of operations to perform inside the // transactions. client_session::with_transaction_cb callback = [&](client_session* session) { // Important:: You must pass the session to the operations. foo.insert_one(*session, make_document(kvp("abc", 1))); bar.insert_one(*session, make_document(kvp("xyz", 999))); }; // Step 2: Start a client session auto session = client.start_session(); // Step 3: Use with_transaction to start a transaction, execute the callback, // and commit (or abort on error). try { options::transaction opts; opts.write_concern(wc_majority); opts.read_concern(rc_local); opts.read_preference(rp_primary); session.with_transaction(callback, opts); } catch (const mongocxx::exception& e) { std::cout << "An exception occurred: " << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; // End Transactions withTxn API Example 1 } <|endoftext|>
<commit_before>#include <osg/Geode> #include <osg/ShapeDrawable> #include <osg/Material> #include <osg/Texture2D> #include <osg/MatrixTransform> #include <osg/PositionAttitudeTransform> #include <osg/BlendFunc> #include <osg/ClearNode> #include <osg/Projection> #include <osgUtil/Tesselator> #include <osgUtil/TransformCallback> #include <osgUtil/CullVisitor> #include <osgGA/TrackballManipulator> #include <osgProducer/Viewer> #include <osgDB/ReadFile> #include <osgSim/ScalarsToColors> #include <osgSim/ColorRange> #include <osgSim/ScalarBar> #include <sstream> #include <math.h> using namespace osgSim; using osgSim::ScalarBar; osg::Node* createScalarBar() { #if 1 //ScalarsToColors* stc = new ScalarsToColors(0.0f,1.0f); //ScalarBar* sb = new ScalarBar(2,3,stc,"STC_ScalarBar"); // Create a custom color set std::vector<osg::Vec4> cs; cs.push_back(osg::Vec4(1.0f,0.0f,0.0f,1.0f)); // R cs.push_back(osg::Vec4(0.0f,1.0f,0.0f,1.0f)); // G cs.push_back(osg::Vec4(1.0f,1.0f,0.0f,1.0f)); // G cs.push_back(osg::Vec4(0.0f,0.0f,1.0f,1.0f)); // B cs.push_back(osg::Vec4(0.0f,1.0f,1.0f,1.0f)); // R // Create a custom scalar printer struct MyScalarPrinter: public ScalarBar::ScalarPrinter { std::string printScalar(float scalar) { std::cout<<"In MyScalarPrinter::printScalar"<<std::endl; if(scalar==0.0f) return ScalarBar::ScalarPrinter::printScalar(scalar)+" Bottom"; else if(scalar==0.5f) return ScalarBar::ScalarPrinter::printScalar(scalar)+" Middle"; else if(scalar==1.0f) return ScalarBar::ScalarPrinter::printScalar(scalar)+" Top"; else return ScalarBar::ScalarPrinter::printScalar(scalar); } }; ColorRange* cr = new ColorRange(0.0f,1.0f,cs); ScalarBar* sb = new ScalarBar(20, 11, cr, "ScalarBar", ScalarBar::VERTICAL, 0.1f, new MyScalarPrinter); sb->setScalarPrinter(new MyScalarPrinter); return sb; #else ScalarBar *sb = new ScalarBar; ScalarBar::TextProperties tp; tp._fontFile = "fonts/times.ttf"; sb->setTextProperties(tp); return sb; #endif } osg::Node * createScalarBar_HUD() { osgSim::ScalarBar * geode = new osgSim::ScalarBar; osgSim::ScalarBar::TextProperties tp; tp._fontFile = "fonts/times.ttf"; geode->setTextProperties(tp); osg::StateSet * stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF); stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); stateset->setRenderBinDetails(11, "RenderBin"); osg::MatrixTransform * modelview = new osg::MatrixTransform; modelview->setReferenceFrame(osg::Transform::ABSOLUTE_RF); osg::Matrixd matrix(osg::Matrixd::scale(1000,1000,1000) * osg::Matrixd::translate(120,10,0)); // I've played with these values a lot and it seems to work, but I have no idea why modelview->setMatrix(matrix); modelview->addChild(geode); osg::Projection * projection = new osg::Projection; projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024)); // or whatever the OSG window res is projection->addChild(modelview); return projection; //make sure you delete the return sb line } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates both text, animation and billboard via custom transform to create the OpenSceneGraph logo.."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); arguments.getApplicationUsage()->addCommandLineOption("ps","Render the Professional Services logo"); // construct the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } osg::Group* group = new osg::Group; group->addChild(createScalarBar()); group->addChild(createScalarBar_HUD()); // add model to viewer. viewer.setSceneData( group ); // create the windows and run the threads. viewer.realize(); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } // wait for all cull and draw threads to complete before exit. viewer.sync(); return 0; } <commit_msg>Attempted fix for VS6.0 compile problems<commit_after>#include <osg/Geode> #include <osg/ShapeDrawable> #include <osg/Material> #include <osg/Texture2D> #include <osg/MatrixTransform> #include <osg/PositionAttitudeTransform> #include <osg/BlendFunc> #include <osg/ClearNode> #include <osg/Projection> #include <osgUtil/Tesselator> #include <osgUtil/TransformCallback> #include <osgUtil/CullVisitor> #include <osgGA/TrackballManipulator> #include <osgProducer/Viewer> #include <osgDB/ReadFile> #include <osgSim/ScalarsToColors> #include <osgSim/ColorRange> #include <osgSim/ScalarBar> #include <sstream> #include <math.h> using namespace osgSim; using osgSim::ScalarBar; #if defined(_MSC_VER) // not have to have this pathway for just VS6.0 as its unable to handle the full // ScalarBar::ScalarPrinter::printScalar scoping. // Create a custom scalar printer struct MyScalarPrinter: public ScalarBar::ScalarPrinter { std::string printScalar(float scalar) { std::cout<<"In MyScalarPrinter::printScalar"<<std::endl; if(scalar==0.0f) return ScalarPrinter::printScalar(scalar)+" Bottom"; else if(scalar==0.5f) return ScalarPrinter::printScalar(scalar)+" Middle"; else if(scalar==1.0f) return ScalarPrinter::printScalar(scalar)+" Top"; else return ScalarPrinter::printScalar(scalar); } }; #else // Create a custom scalar printer struct MyScalarPrinter: public ScalarBar::ScalarPrinter { std::string printScalar(float scalar) { std::cout<<"In MyScalarPrinter::printScalar"<<std::endl; if(scalar==0.0f) return ScalarBar::ScalarPrinter::printScalar(scalar)+" Bottom"; else if(scalar==0.5f) return ScalarBar::ScalarPrinter::printScalar(scalar)+" Middle"; else if(scalar==1.0f) return ScalarBar::ScalarPrinter::printScalar(scalar)+" Top"; else return ScalarBar::ScalarPrinter::printScalar(scalar); } }; #endif osg::Node* createScalarBar() { #if 1 //ScalarsToColors* stc = new ScalarsToColors(0.0f,1.0f); //ScalarBar* sb = new ScalarBar(2,3,stc,"STC_ScalarBar"); // Create a custom color set std::vector<osg::Vec4> cs; cs.push_back(osg::Vec4(1.0f,0.0f,0.0f,1.0f)); // R cs.push_back(osg::Vec4(0.0f,1.0f,0.0f,1.0f)); // G cs.push_back(osg::Vec4(1.0f,1.0f,0.0f,1.0f)); // G cs.push_back(osg::Vec4(0.0f,0.0f,1.0f,1.0f)); // B cs.push_back(osg::Vec4(0.0f,1.0f,1.0f,1.0f)); // R ColorRange* cr = new ColorRange(0.0f,1.0f,cs); ScalarBar* sb = new ScalarBar(20, 11, cr, "ScalarBar", ScalarBar::VERTICAL, 0.1f, new MyScalarPrinter); sb->setScalarPrinter(new MyScalarPrinter); return sb; #else ScalarBar *sb = new ScalarBar; ScalarBar::TextProperties tp; tp._fontFile = "fonts/times.ttf"; sb->setTextProperties(tp); return sb; #endif } osg::Node * createScalarBar_HUD() { osgSim::ScalarBar * geode = new osgSim::ScalarBar; osgSim::ScalarBar::TextProperties tp; tp._fontFile = "fonts/times.ttf"; geode->setTextProperties(tp); osg::StateSet * stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF); stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); stateset->setRenderBinDetails(11, "RenderBin"); osg::MatrixTransform * modelview = new osg::MatrixTransform; modelview->setReferenceFrame(osg::Transform::ABSOLUTE_RF); osg::Matrixd matrix(osg::Matrixd::scale(1000,1000,1000) * osg::Matrixd::translate(120,10,0)); // I've played with these values a lot and it seems to work, but I have no idea why modelview->setMatrix(matrix); modelview->addChild(geode); osg::Projection * projection = new osg::Projection; projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024)); // or whatever the OSG window res is projection->addChild(modelview); return projection; //make sure you delete the return sb line } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates both text, animation and billboard via custom transform to create the OpenSceneGraph logo.."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); arguments.getApplicationUsage()->addCommandLineOption("ps","Render the Professional Services logo"); // construct the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } osg::Group* group = new osg::Group; group->addChild(createScalarBar()); group->addChild(createScalarBar_HUD()); // add model to viewer. viewer.setSceneData( group ); // create the windows and run the threads. viewer.realize(); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } // wait for all cull and draw threads to complete before exit. viewer.sync(); return 0; } <|endoftext|>
<commit_before>#include <coffee/core/CApplication> #include <coffee/core/CProfiling> #include <coffee/core/CFiles> #include <coffee/core/CInput> #include <coffee/CImage> #include <coffee/sdl2/CSDL2System> #include <coffee/sdl2/CSDL2Dialog> #include <coffee/sdl2/CSDL2SpriteWindow> using namespace Coffee; using namespace Display; using BasicWindow = SDL2WindowHost; using Sprites = SDL2SpriteRenderer; const constexpr szptr num_points = 10; CPointF sprite_pos[num_points] = {}; CSizeF sprite_scale = {1,1}; CSize window_size = {}; #ifndef COFFEE_USE_RTTI SDL2WindowHost* window_host; #endif bool exit_flag = false; void WindowResize_1(void*, const CDEvent& e, c_cptr d) { if(e.type == CDEvent::Resize) { auto ev = (CDResizeEvent const*)d; window_size = *ev; } } void TouchInput_1(void*, const CIEvent& e, c_cptr d) { if(e.type == CIEvent::MultiTouch) { const CIMTouchMotionEvent& tch = *(const CIMTouchMotionEvent*)d; if(tch.fingers==2) { scalar v = tch.dist; v /= Int16_Max; v += 1.f; CSizeF s = {v,v}; sprite_scale.w *= s.w; sprite_scale.h *= s.h; } } else if(e.type == CIEvent::TouchMotion) { const CITouchMotionEvent& tch = *(const CITouchMotionEvent*)d; if(tch.finger>num_points) return; if(!tch.hover) { sprite_pos[tch.finger] = tch.origin; sprite_pos[tch.finger].x *= window_size.w; sprite_pos[tch.finger].y *= window_size.h; sprite_pos[tch.finger].x -= 64; sprite_pos[tch.finger].y -= 64; } }else if(e.type == CIEvent::MouseMove) { const CIMouseMoveEvent& mbn = *(const CIMouseMoveEvent*)d; if(mbn.btn!=0) { sprite_pos[0] = mbn.origin; sprite_pos[0].x -= 64; sprite_pos[0].y -= 64; } }else if(e.type == CIEvent::TouchTap) { const CITouchTapEvent& tch = *(const CITouchTapEvent*)d; if(tch.finger>num_points) return; if(tch.pressed) { sprite_pos[tch.finger] = tch.pos; sprite_pos[tch.finger].x *= window_size.w; sprite_pos[tch.finger].y *= window_size.h; sprite_pos[tch.finger].x -= 64; sprite_pos[tch.finger].y -= 64; } }else if(e.type == CIEvent::MouseButton) { const CIMouseButtonEvent& mbn = *(const CIMouseButtonEvent*)d; if(mbn.mod&CIMouseButtonEvent::Pressed) { sprite_pos[0] = mbn.pos; sprite_pos[0].x -= 64; sprite_pos[0].y -= 64; } } } void ExitHandler_1(void* ptr, const CIEvent& e, c_cptr d) { #ifdef COFFEE_USE_RTTI SDL2WindowHost* host = dynamic_cast<SDL2WindowHost*>((SDL2EventHandler*)ptr); #else SDL2WindowHost* host = window_host; #endif if(e.type == CIEvent::QuitSign) { host->closeWindow(); }else if(e.type==CIEvent::Keyboard) { CIKeyEvent const* kev = (CIKeyEvent const*)d; if(kev->key==CK_Escape) host->closeWindow(); } } int32 coffee_main(int32 argc, cstring_w* argv) { SubsystemWrapper<SDL2::SDL2> sys1; C_UNUSED(sys1); /* Set file prefix, basically a cwd but only for resources */ CResources::FileResourcePrefix("sample_data/ctest_hud/"); /* Create a window host for the renderer */ BasicWindow test; auto visual = GetDefaultVisual(); #ifndef COFFEE_USE_RTTI window_host = &test; #endif CString err; if(!test.init(visual,&err)) { cDebug("Initialization error: {0}",err); return 1; } Profiler::Profile("Window init"); /* Create a sprite renderer context */ Sprites rend(&test); if(!rend.init(&err)) { cDebug("Initialization error: {0}",err); return 1; } /* Create a renderer handle */ Sprites::Renderer r = rend.createRenderer(); Profiler::Profile("Context handle"); /* Create a texture */ Sprites::Texture t; rend.createTexture(r,1,&t,PixelFormat::RGBA8UI,ResourceAccess::Streaming,CSize(128,128)); Profiler::Profile("Texture creation"); { /* Map a texture into memory */ CResources::Resource texfile("particle_sprite.png",false, ResourceAccess::SpecifyStorage| ResourceAccess::AssetFile| ResourceAccess::ReadOnly); cDebug("Opening texture: {0}",texfile.resource()); CResources::FileMap(texfile); cDebug("Pointer to texture: {0}",(const byte_t*)texfile.data); /* Decode file to RGBA data */ CStbImageLib::CStbImage img; CStbImageLib::LoadData(&img,&texfile); /* Copy texture into texture memory */ { CRGBA* data = (CRGBA*)rend.mapTexture(t); MemCpy(data,img.data,img.size.area()*img.bpp); rend.unmapTexture(t); } /* Clean up */ CStbImageLib::ImageFree(&img); CResources::FileUnmap(texfile); } Profiler::Profile("Texture load"); /* Create a sprite from the texture */ CRect src(0,0,128,128); Sprites::Sprite sprite; rend.createSprite(t,src,&sprite); /* Show the window */ test.showWindow(); CRGBA clearCol = CRGBA(255,0,0); /* Set clear color for buffer */ rend.setClearColor(r,clearCol); Profiler::Profile("Renderer state"); /* Start rendering! */ SDL2Dialog::InformationMessage("Leaving?","Hello there! Did you press the wrong button?"); test.installEventHandler({TouchInput_1}); test.installEventHandler({ExitHandler_1}); test.installEventHandler({WindowResize_1}); while(!test.closeFlag()) { rend.setClearColor(r,clearCol); rend.clearBuffer(r); for(szptr i=0;i<num_points;i++) rend.drawSprite(r,sprite_pos[i],sprite_scale,sprite); clearCol.r = (Time::CurrentTimestamp()*1000)%255; rend.swapBuffers(r); test.pollEvents(); } rend.destroyTexture(1,&t); rend.destroyRenderer(r); test.hideWindow(); rend.spritesTerminate(); test.cleanup(); return 0; } COFFEE_APPLICATION_MAIN(coffee_main) <commit_msg> - Fix crash in SDLSpriteTest<commit_after>#include <coffee/core/CApplication> #include <coffee/core/CProfiling> #include <coffee/core/CFiles> #include <coffee/core/CInput> #include <coffee/CImage> #include <coffee/sdl2/CSDL2System> #include <coffee/sdl2/CSDL2Dialog> #include <coffee/sdl2/CSDL2SpriteWindow> using namespace Coffee; using namespace Display; using BasicWindow = SDL2WindowHost; using Sprites = SDL2SpriteRenderer; const constexpr szptr num_points = 10; CPointF sprite_pos[num_points] = {}; CSizeF sprite_scale = {1,1}; CSize window_size = {}; bool exit_flag = false; void WindowResize_1(void*, const CDEvent& e, c_cptr d) { if(e.type == CDEvent::Resize) { auto ev = (CDResizeEvent const*)d; window_size = *ev; } } void TouchInput_1(void*, const CIEvent& e, c_cptr d) { if(e.type == CIEvent::MultiTouch) { const CIMTouchMotionEvent& tch = *(const CIMTouchMotionEvent*)d; if(tch.fingers==2) { scalar v = tch.dist; v /= Int16_Max; v += 1.f; CSizeF s = {v,v}; sprite_scale.w *= s.w; sprite_scale.h *= s.h; } } else if(e.type == CIEvent::TouchMotion) { const CITouchMotionEvent& tch = *(const CITouchMotionEvent*)d; if(tch.finger>num_points) return; if(!tch.hover) { sprite_pos[tch.finger] = tch.origin; sprite_pos[tch.finger].x *= window_size.w; sprite_pos[tch.finger].y *= window_size.h; sprite_pos[tch.finger].x -= 64; sprite_pos[tch.finger].y -= 64; } }else if(e.type == CIEvent::MouseMove) { const CIMouseMoveEvent& mbn = *(const CIMouseMoveEvent*)d; if(mbn.btn!=0) { sprite_pos[0] = mbn.origin; sprite_pos[0].x -= 64; sprite_pos[0].y -= 64; } }else if(e.type == CIEvent::TouchTap) { const CITouchTapEvent& tch = *(const CITouchTapEvent*)d; if(tch.finger>num_points) return; if(tch.pressed) { sprite_pos[tch.finger] = tch.pos; sprite_pos[tch.finger].x *= window_size.w; sprite_pos[tch.finger].y *= window_size.h; sprite_pos[tch.finger].x -= 64; sprite_pos[tch.finger].y -= 64; } }else if(e.type == CIEvent::MouseButton) { const CIMouseButtonEvent& mbn = *(const CIMouseButtonEvent*)d; if(mbn.mod&CIMouseButtonEvent::Pressed) { sprite_pos[0] = mbn.pos; sprite_pos[0].x -= 64; sprite_pos[0].y -= 64; } } } void ExitHandler_1(void* ptr, const CIEvent& e, c_cptr d) { SDL2WindowHost* host = (SDL2WindowHost*)ptr; if(e.type == CIEvent::QuitSign) { host->closeWindow(); }else if(e.type==CIEvent::Keyboard) { CIKeyEvent const* kev = (CIKeyEvent const*)d; if(kev->key==CK_Escape) host->closeWindow(); } } int32 coffee_main(int32 argc, cstring_w* argv) { SubsystemWrapper<SDL2::SDL2> sys1; C_UNUSED(sys1); /* Set file prefix, basically a cwd but only for resources */ CResources::FileResourcePrefix("sample_data/ctest_hud/"); /* Create a window host for the renderer */ BasicWindow test; auto visual = GetDefaultVisual(); CString err; if(!test.init(visual,&err)) { cDebug("Initialization error: {0}",err); return 1; } Profiler::Profile("Window init"); /* Create a sprite renderer context */ Sprites rend(&test); if(!rend.init(&err)) { cDebug("Initialization error: {0}",err); return 1; } /* Create a renderer handle */ Sprites::Renderer r = rend.createRenderer(); Profiler::Profile("Context handle"); /* Create a texture */ Sprites::Texture t; rend.createTexture(r,1,&t,PixelFormat::RGBA8UI,ResourceAccess::Streaming,CSize(128,128)); Profiler::Profile("Texture creation"); { /* Map a texture into memory */ CResources::Resource texfile("particle_sprite.png",false, ResourceAccess::SpecifyStorage| ResourceAccess::AssetFile| ResourceAccess::ReadOnly); cDebug("Opening texture: {0}",texfile.resource()); CResources::FileMap(texfile); cDebug("Pointer to texture: {0}",(const byte_t*)texfile.data); /* Decode file to RGBA data */ CStbImageLib::CStbImage img; CStbImageLib::LoadData(&img,&texfile); /* Copy texture into texture memory */ { CRGBA* data = (CRGBA*)rend.mapTexture(t); MemCpy(data,img.data,img.size.area()*img.bpp); rend.unmapTexture(t); } /* Clean up */ CStbImageLib::ImageFree(&img); CResources::FileUnmap(texfile); } Profiler::Profile("Texture load"); /* Create a sprite from the texture */ CRect src(0,0,128,128); Sprites::Sprite sprite; rend.createSprite(t,src,&sprite); /* Show the window */ test.showWindow(); CRGBA clearCol = CRGBA(255,0,0); /* Set clear color for buffer */ rend.setClearColor(r,clearCol); Profiler::Profile("Renderer state"); /* Start rendering! */ SDL2Dialog::InformationMessage("Leaving?","Hello there! Did you press the wrong button?"); test.installEventHandler({TouchInput_1,nullptr,&test}); test.installEventHandler({ExitHandler_1,nullptr,&test}); test.installEventHandler({WindowResize_1,nullptr,&test}); while(!test.closeFlag()) { rend.setClearColor(r,clearCol); rend.clearBuffer(r); for(szptr i=0;i<num_points;i++) rend.drawSprite(r,sprite_pos[i],sprite_scale,sprite); clearCol.r = (Time::CurrentTimestamp()*1000)%255; rend.swapBuffers(r); test.pollEvents(); } rend.destroyTexture(1,&t); rend.destroyRenderer(r); test.hideWindow(); rend.spritesTerminate(); test.cleanup(); return 0; } COFFEE_APPLICATION_MAIN(coffee_main) <|endoftext|>
<commit_before>/* * ADXL345.cpp * * Created on: May 10, 2013 * Author: Ryler Hockenbury * * Library for ADXL345 3-channel accelerometer sensor * NOTE: Sensor is packaged with ITG3200 and HMC5883L * */ #include "ADXL345.h" #include "../Quad_Defines/globals.h" ADXL345::ADXL345() { devAddr = ADXL345_ADDR; accelStatus = OFF; offset[X] = 0.0; offset[Y] = 0.0; offset[Z] = 0.0; data[X] = 0; data[Y] = 0; data[Z] = 0; } /* * Initialize responsive sensor to default configuration * Sample rate = 100 Hz * Range = +/- 8g * Enable measurements */ bool ADXL345::init() { // sensors needs to be alive to init if(test()) { accelStatus = ON; setSampleRate(ADXL345_RATE_100); setFormat(ADXL345_RANGE_8G); setPowerMode(ON); return true; } else { accelStatus = OFF; Serial.println("WARNING: accelerometer not responding to init"); return false; } } /* * Test sensor connection by checking device id register value */ bool ADXL345::test() { return (getID() == ADXL345_DEVID); } /* * Return sensor device identifier */ uint8_t ADXL345::getID() { I2Cdev::readByte(devAddr, ADXL345_WHOAMI_REGADDR, buffer); return buffer[0]; } /* * Set the sample output rate */ void ADXL345::setSampleRate(uint8_t rate) { I2Cdev::writeBits(devAddr, ADXL345_SMPLRT_REGADDR, ADXL345_BWRATE_BIT, ADXL345_BWRATE_LENGTH, rate); } /* * Set the range, and enable full resolution */ void ADXL345::setFormat(uint8_t range) { I2Cdev::writeBits(devAddr, ADXL345_DATAFORMAT_REGADDR, ADXL345_RANGE_BIT, ADXL345_RANGE_LENGTH, range); I2Cdev::writeBit(devAddr, ADXL345_DATAFORMAT_REGADDR, ADXL345_FULLRES_BIT, ON); } /* * Set the measurement mode (on or off) */ void ADXL345::setPowerMode(bool mode) { I2Cdev::writeBit(devAddr, ADXL345_PWRMODE_REGADDR, ADXL345_MEASURE_BIT, mode); } /* * Set the offset values (zero voltage values) * WARNING: the platform should be leveled first * using body mounted bubble level * Read 10 samples from sensor and average * Place offsets in offset registers */ void ADXL345::setOffset() { if(accelStatus == ON) { int32_t sumX = 0; int32_t sumY = 0; int32_t sumZ = 0; for(uint8_t i = 0; i < 10; i++) { getRawData(); // read raw data sumX = sumX + (int32_t) data[X]; sumY = sumY + (int32_t) data[Y]; sumZ = sumZ + (int32_t) data[Z]; // delay long enough for another sample to be available // @ 100 Hz -> 0.01 seconds delay(10); } offset[X] = (float) sumX / 10.0; offset[Y] = (float) sumY / 10.0; offset[Z] = (float) sumZ / 10.0 - (float) 256; vehicleStatus = vehicleStatus | ACCEL_READY; } else { Serial.println("WARNING: accel is not online -> cannot be zeroed"); } } /* * Read raw data */ void ADXL345::getRawData() { I2Cdev::readBytes(devAddr, ADXL345_XDATA0_REGADDR, 6, buffer); data[X] = (((int16_t)buffer[1]) << 8) | buffer[0]; data[Y] = (((int16_t)buffer[3]) << 8) | buffer[2]; data[Z] = (((int16_t)buffer[5]) << 8) | buffer[4]; } /* * Return accelerations in g's */ void ADXL345::getValue(float *value) { getRawData(); // TODO - calibration work value[X] = -((float)data[X] - offset[X]) / (float) ADXL345_8GSENSITIVITY; value[Y] = ((float)data[Y] - offset[Y]) / (float) ADXL345_8GSENSITIVITY; value[Z] = ((float)data[Z] - offset[Z]) / (float) 263; //Serial.print(value[X]); //Serial.print(", "); //Serial.print(value[Y]); //Serial.print(", "); //Serial.print(value[Z]); //Serial.print("\n"); } <commit_msg>Reformatted accelerometer code<commit_after>/* * ADXL345.cpp * * Created on: May 10, 2013 * Author: Ryler Hockenbury * * Library for ADXL345 3-channel accelerometer sensor * NOTE: Sensor is packaged with ITG3200 and HMC5883L * */ #include "ADXL345.h" #include "../Quad_Defines/globals.h" ADXL345::ADXL345() { devAddr = ADXL345_ADDR; accelStatus = OFF; offset[X] = 0.0; offset[Y] = 0.0; offset[Z] = 0.0; data[X] = 0; data[Y] = 0; data[Z] = 0; } /* * Initialize responsive sensor to default configuration * Sample rate = 100 Hz * Range = +/- 8g * Enable measurements */ bool ADXL345::init() { if(test()) { accelStatus = ON; setSampleRate(ADXL345_RATE_100); setFormat(ADXL345_RANGE_8G); setPowerMode(ON); return true; } else { accelStatus = OFF; Serial.println("WARNING: accelerometer not responding"); return false; } } /* * Test sensor connection by checking device id register value */ bool ADXL345::test() { return (getID() == ADXL345_DEVID); } /* * Return sensor device identifier */ uint8_t ADXL345::getID() { I2Cdev::readByte(devAddr, ADXL345_WHOAMI_REGADDR, buffer); return buffer[0]; } /* * Set the sample output rate */ void ADXL345::setSampleRate(uint8_t rate) { I2Cdev::writeBits(devAddr, ADXL345_SMPLRT_REGADDR, ADXL345_BWRATE_BIT, ADXL345_BWRATE_LENGTH, rate); } /* * Set the range, and enable full resolution */ void ADXL345::setFormat(uint8_t range) { I2Cdev::writeBits(devAddr, ADXL345_DATAFORMAT_REGADDR, ADXL345_RANGE_BIT, ADXL345_RANGE_LENGTH, range); I2Cdev::writeBit(devAddr, ADXL345_DATAFORMAT_REGADDR, ADXL345_FULLRES_BIT, ON); } /* * Set the measurement mode (on or off) */ void ADXL345::setPowerMode(bool mode) { I2Cdev::writeBit(devAddr, ADXL345_PWRMODE_REGADDR, ADXL345_MEASURE_BIT, mode); } /* * Set the offset values (zero voltage values) * WARNING: the platform should be leveled first * using body mounted bubble level * Read 10 samples from sensor and average * Place offsets in offset registers */ void ADXL345::setOffset() { if(accelStatus == ON) { int32_t sumX = 0; int32_t sumY = 0; int32_t sumZ = 0; for(uint8_t i = 0; i < 10; i++) { getRawData(); // read raw data sumX = sumX + (int32_t) data[X]; sumY = sumY + (int32_t) data[Y]; sumZ = sumZ + (int32_t) data[Z]; // delay long enough for another sample to be available // @ 100 Hz -> 0.01 seconds delay(10); } offset[X] = (float) sumX / 10.0; offset[Y] = (float) sumY / 10.0; offset[Z] = (float) sumZ / 10.0 - (float) 256; vehicleStatus = vehicleStatus | ACCEL_READY; } else { Serial.println("WARNING: accel is not online -> cannot be zeroed"); } } /* * Read raw data */ void ADXL345::getRawData() { I2Cdev::readBytes(devAddr, ADXL345_XDATA0_REGADDR, 6, buffer); data[X] = (((int16_t)buffer[1]) << 8) | buffer[0]; data[Y] = (((int16_t)buffer[3]) << 8) | buffer[2]; data[Z] = (((int16_t)buffer[5]) << 8) | buffer[4]; } /* * Return accelerations in g's */ void ADXL345::getValue(float *value) { getRawData(); // TODO - calibration work value[X] = -((float)data[X] - offset[X]) / (float) ADXL345_8GSENSITIVITY; value[Y] = ((float)data[Y] - offset[Y]) / (float) ADXL345_8GSENSITIVITY; value[Z] = ((float)data[Z] - offset[Z]) / (float) 263; //Serial.print(value[X]); //Serial.print(", "); //Serial.print(value[Y]); //Serial.print(", "); //Serial.print(value[Z]); //Serial.print("\n"); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qbs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "moduleproperties.h" #include <buildgraph/artifact.h> #include <language/language.h> #include <language/propertymapinternal.h> #include <language/scriptengine.h> #include <logging/translator.h> #include <tools/error.h> #include <QtScript/qscriptengine.h> namespace qbs { namespace Internal { static QString ptrKey() { return QLatin1String("__internalPtr"); } static QString typeKey() { return QLatin1String("__type"); } static QString productType() { return QLatin1String("product"); } static QString artifactType() { return QLatin1String("artifact"); } void ModuleProperties::init(QScriptValue productObject, const ResolvedProductConstPtr &product) { init(productObject, product.data(), productType()); } void ModuleProperties::init(QScriptValue artifactObject, const Artifact *artifact) { init(artifactObject, artifact, artifactType()); } void ModuleProperties::init(QScriptValue objectWithProperties, const void *ptr, const QString &type) { QScriptEngine * const engine = objectWithProperties.engine(); objectWithProperties.setProperty(QLatin1String("moduleProperty"), engine->newFunction(ModuleProperties::js_moduleProperty, 2)); objectWithProperties.setProperty(ptrKey(), engine->toScriptValue(quintptr(ptr))); objectWithProperties.setProperty(typeKey(), type); } QScriptValue ModuleProperties::js_moduleProperty(QScriptContext *context, QScriptEngine *engine) { try { return moduleProperty(context, engine); } catch (const ErrorInfo &e) { return context->throwError(e.toString()); } } QScriptValue ModuleProperties::moduleProperty(QScriptContext *context, QScriptEngine *engine) { if (Q_UNLIKELY(context->argumentCount() < 2)) { return context->throwError(QScriptContext::SyntaxError, Tr::tr("Function moduleProperty() expects 2 arguments")); } const QScriptValue objectWithProperties = context->thisObject(); const QScriptValue typeScriptValue = objectWithProperties.property(typeKey()); if (Q_UNLIKELY(!typeScriptValue.isString())) { return context->throwError(QScriptContext::TypeError, QLatin1String("Internal error: __type not set up")); } const QScriptValue ptrScriptValue = objectWithProperties.property(ptrKey()); if (Q_UNLIKELY(!ptrScriptValue.isNumber())) { return context->throwError(QScriptContext::TypeError, QLatin1String("Internal error: __internalPtr not set up")); } const void *ptr = reinterpret_cast<const void *>(qscriptvalue_cast<quintptr>(ptrScriptValue)); PropertyMapConstPtr properties; const Artifact *artifact = 0; if (typeScriptValue.toString() == productType()) { properties = static_cast<const ResolvedProduct *>(ptr)->moduleProperties; } else if (typeScriptValue.toString() == artifactType()) { artifact = static_cast<const Artifact *>(ptr); properties = artifact->properties; } else { return context->throwError(QScriptContext::TypeError, QLatin1String("Internal error: invalid type")); } ScriptEngine * const qbsEngine = static_cast<ScriptEngine *>(engine); const QString moduleName = context->argument(0).toString(); const QString propertyName = context->argument(1).toString(); QVariant value; if (qbsEngine->isPropertyCacheEnabled()) value = qbsEngine->retrieveFromPropertyCache(moduleName, propertyName, properties); if (!value.isValid()) { value = properties->moduleProperty(moduleName, propertyName); const Property p(moduleName, propertyName, value); if (artifact) qbsEngine->addPropertyRequestedFromArtifact(artifact, p); else qbsEngine->addPropertyRequestedInScript(p); // Cache the variant value. We must not cache the QScriptValue here, because it's a // reference and the user might change the actual object. if (qbsEngine->isPropertyCacheEnabled()) qbsEngine->addToPropertyCache(moduleName, propertyName, properties, value); } return engine->toScriptValue(value); } } // namespace Internal } // namespace qbs <commit_msg>JS API: expose the properties of an artifact's product<commit_after>/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qbs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "moduleproperties.h" #include <buildgraph/artifact.h> #include <language/language.h> #include <language/propertymapinternal.h> #include <language/scriptengine.h> #include <logging/translator.h> #include <tools/error.h> #include <QtScript/qscriptengine.h> namespace qbs { namespace Internal { static QString ptrKey() { return QLatin1String("__internalPtr"); } static QString typeKey() { return QLatin1String("__type"); } static QString productType() { return QLatin1String("product"); } static QString artifactType() { return QLatin1String("artifact"); } void ModuleProperties::init(QScriptValue productObject, const ResolvedProductConstPtr &product) { init(productObject, product.data(), productType()); } void ModuleProperties::init(QScriptValue artifactObject, const Artifact *artifact) { init(artifactObject, artifact, artifactType()); } void ModuleProperties::init(QScriptValue objectWithProperties, const void *ptr, const QString &type) { QScriptEngine * const engine = objectWithProperties.engine(); objectWithProperties.setProperty(QLatin1String("moduleProperty"), engine->newFunction(ModuleProperties::js_moduleProperty, 2)); objectWithProperties.setProperty(ptrKey(), engine->toScriptValue(quintptr(ptr))); objectWithProperties.setProperty(typeKey(), type); if (type == artifactType()) { const auto product = static_cast<const Artifact *>(ptr)->product; const QVariantMap productProperties { {QStringLiteral("buildDirectory"), product->buildDirectory()}, {QStringLiteral("destinationDirectory"), product->destinationDirectory}, {QStringLiteral("name"), product->name}, {QStringLiteral("sourceDirectory"), product->sourceDirectory}, {QStringLiteral("targetName"), product->targetName}, {QStringLiteral("type"), product->fileTags.toStringList()} }; objectWithProperties.setProperty(QStringLiteral("product"), engine->toScriptValue(productProperties)); } } QScriptValue ModuleProperties::js_moduleProperty(QScriptContext *context, QScriptEngine *engine) { try { return moduleProperty(context, engine); } catch (const ErrorInfo &e) { return context->throwError(e.toString()); } } QScriptValue ModuleProperties::moduleProperty(QScriptContext *context, QScriptEngine *engine) { if (Q_UNLIKELY(context->argumentCount() < 2)) { return context->throwError(QScriptContext::SyntaxError, Tr::tr("Function moduleProperty() expects 2 arguments")); } const QScriptValue objectWithProperties = context->thisObject(); const QScriptValue typeScriptValue = objectWithProperties.property(typeKey()); if (Q_UNLIKELY(!typeScriptValue.isString())) { return context->throwError(QScriptContext::TypeError, QLatin1String("Internal error: __type not set up")); } const QScriptValue ptrScriptValue = objectWithProperties.property(ptrKey()); if (Q_UNLIKELY(!ptrScriptValue.isNumber())) { return context->throwError(QScriptContext::TypeError, QLatin1String("Internal error: __internalPtr not set up")); } const void *ptr = reinterpret_cast<const void *>(qscriptvalue_cast<quintptr>(ptrScriptValue)); PropertyMapConstPtr properties; const Artifact *artifact = 0; if (typeScriptValue.toString() == productType()) { properties = static_cast<const ResolvedProduct *>(ptr)->moduleProperties; } else if (typeScriptValue.toString() == artifactType()) { artifact = static_cast<const Artifact *>(ptr); properties = artifact->properties; } else { return context->throwError(QScriptContext::TypeError, QLatin1String("Internal error: invalid type")); } ScriptEngine * const qbsEngine = static_cast<ScriptEngine *>(engine); const QString moduleName = context->argument(0).toString(); const QString propertyName = context->argument(1).toString(); QVariant value; if (qbsEngine->isPropertyCacheEnabled()) value = qbsEngine->retrieveFromPropertyCache(moduleName, propertyName, properties); if (!value.isValid()) { value = properties->moduleProperty(moduleName, propertyName); const Property p(moduleName, propertyName, value); if (artifact) qbsEngine->addPropertyRequestedFromArtifact(artifact, p); else qbsEngine->addPropertyRequestedInScript(p); // Cache the variant value. We must not cache the QScriptValue here, because it's a // reference and the user might change the actual object. if (qbsEngine->isPropertyCacheEnabled()) qbsEngine->addToPropertyCache(moduleName, propertyName, properties, value); } return engine->toScriptValue(value); } } // namespace Internal } // namespace qbs <|endoftext|>
<commit_before>/* * main.cpp * * Created on: 2014-05-05 * Author: mathieu */ #include <QtNetwork/QNetworkInterface> #include <QtCore/QCoreApplication> #include "TcpClient.h" void showUsage() { printf("tcpClient [hostname] port\n"); exit(-1); } int main(int argc, char * argv[]) { if(argc < 2 || argc > 3) { showUsage(); } QString ipAddress; quint16 port = 0; if(argc == 2) { port = std::atoi(argv[1]); } else if(argc == 3) { ipAddress = argv[1]; port = std::atoi(argv[2]); } if(ipAddress.isEmpty()) { // find out which IP to connect to QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses(); // use the first non-localhost IPv4 address for (int i = 0; i < ipAddressesList.size(); ++i) { if (ipAddressesList.at(i) != QHostAddress::LocalHost && ipAddressesList.at(i).toIPv4Address()) { ipAddress = ipAddressesList.at(i).toString(); break; } } // if we did not find one, use IPv4 localhost if (ipAddress.isEmpty()) { ipAddress = QHostAddress(QHostAddress::LocalHost).toString(); } } QCoreApplication app(argc, argv); printf("Connecting to \"%s:%d\"...\n", ipAddress.toStdString().c_str(), port); TcpClient client(ipAddress, port); if(client.waitForConnected()) { printf("Connecting to \"%s:%d\"... connected!\n", ipAddress.toStdString().c_str(), port); app.exec(); } else { printf("Connecting to \"%s:%d\"... connection failed!\n", ipAddress.toStdString().c_str(), port); } return 0; } <commit_msg>fixed compilation error on Mac OS X Maverick (std::atoi -> atoi)<commit_after>/* * main.cpp * * Created on: 2014-05-05 * Author: mathieu */ #include <QtNetwork/QNetworkInterface> #include <QtCore/QCoreApplication> #include "TcpClient.h" void showUsage() { printf("tcpClient [hostname] port\n"); exit(-1); } int main(int argc, char * argv[]) { if(argc < 2 || argc > 3) { showUsage(); } QString ipAddress; quint16 port = 0; if(argc == 2) { port = atoi(argv[1]); } else if(argc == 3) { ipAddress = argv[1]; port = atoi(argv[2]); } if(ipAddress.isEmpty()) { // find out which IP to connect to QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses(); // use the first non-localhost IPv4 address for (int i = 0; i < ipAddressesList.size(); ++i) { if (ipAddressesList.at(i) != QHostAddress::LocalHost && ipAddressesList.at(i).toIPv4Address()) { ipAddress = ipAddressesList.at(i).toString(); break; } } // if we did not find one, use IPv4 localhost if (ipAddress.isEmpty()) { ipAddress = QHostAddress(QHostAddress::LocalHost).toString(); } } QCoreApplication app(argc, argv); printf("Connecting to \"%s:%d\"...\n", ipAddress.toStdString().c_str(), port); TcpClient client(ipAddress, port); if(client.waitForConnected()) { printf("Connecting to \"%s:%d\"... connected!\n", ipAddress.toStdString().c_str(), port); app.exec(); } else { printf("Connecting to \"%s:%d\"... connection failed!\n", ipAddress.toStdString().c_str(), port); } return 0; } <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2019-2019 ARM Limited * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MBED_CONF_RTOS_PRESENT) #error [NOT_SUPPORTED] stack size unification test cases require a RTOS to run. #else #include "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #ifdef TARGET_RENESAS #error [NOT_SUPPORTED] Cortex-A target not supported for this test #else using namespace utest::v1; extern osThreadAttr_t _main_thread_attr; extern uint32_t mbed_stack_isr_size; /* Exception for Nordic boards - BLE requires 2KB ISR stack. */ #if defined(TARGET_NRF5x) #define EXPECTED_ISR_STACK_SIZE (2048) #else #define EXPECTED_ISR_STACK_SIZE (1024) #endif #if defined(TARGET_NUCLEO_F070RB) || defined(TARGET_NANO100) || defined(TARGET_STM32F072RB) || defined(TARGET_TMPM46B) || defined(TARGET_TMPM066) #define EXPECTED_MAIN_THREAD_STACK_SIZE (3072) #else #define EXPECTED_MAIN_THREAD_STACK_SIZE (4096) #endif #define EXPECTED_USER_THREAD_DEFAULT_STACK_SIZE (4096) /* Test sizes of ISR stack, main thread stack, default user thread stack. * * On some platforms with lower RAM size (e.g. NUCLEO_F070RB - 16 KB RAM) it is impossible * to create thread with default stack size to check its size, that is why we will * check only macro which specifies default user thread stack. * */ void stack_size_unification_test() { TEST_ASSERT_EQUAL(EXPECTED_ISR_STACK_SIZE, mbed_stack_isr_size); TEST_ASSERT_EQUAL(EXPECTED_MAIN_THREAD_STACK_SIZE, _main_thread_attr.stack_size); TEST_ASSERT_EQUAL(EXPECTED_USER_THREAD_DEFAULT_STACK_SIZE, OS_STACK_SIZE); } utest::v1::status_t test_setup(const size_t number_of_cases) { GREENTEA_SETUP(10, "default_auto"); return verbose_test_setup_handler(number_of_cases); } Case cases[] = { Case("Stack size unification test", stack_size_unification_test) }; Specification specification(test_setup, cases); int main() { return !Harness::run(specification); } #endif // TARGET_RENESAS #endif // !defined(MBED_CONF_RTOS_PRESENT) <commit_msg>NANO130: Fix mbed_hal-stack_size_unification failure<commit_after>/* mbed Microcontroller Library * Copyright (c) 2019-2019 ARM Limited * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MBED_CONF_RTOS_PRESENT) #error [NOT_SUPPORTED] stack size unification test cases require a RTOS to run. #else #include "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #ifdef TARGET_RENESAS #error [NOT_SUPPORTED] Cortex-A target not supported for this test #else using namespace utest::v1; extern osThreadAttr_t _main_thread_attr; extern uint32_t mbed_stack_isr_size; /* Exception for Nordic boards - BLE requires 2KB ISR stack. */ #if defined(TARGET_NRF5x) #define EXPECTED_ISR_STACK_SIZE (2048) #else #define EXPECTED_ISR_STACK_SIZE (1024) #endif #if defined(TARGET_NUCLEO_F070RB) || defined(TARGET_STM32F072RB) || defined(TARGET_TMPM46B) || defined(TARGET_TMPM066) #define EXPECTED_MAIN_THREAD_STACK_SIZE (3072) #else #define EXPECTED_MAIN_THREAD_STACK_SIZE (4096) #endif #define EXPECTED_USER_THREAD_DEFAULT_STACK_SIZE (4096) /* Test sizes of ISR stack, main thread stack, default user thread stack. * * On some platforms with lower RAM size (e.g. NUCLEO_F070RB - 16 KB RAM) it is impossible * to create thread with default stack size to check its size, that is why we will * check only macro which specifies default user thread stack. * */ void stack_size_unification_test() { TEST_ASSERT_EQUAL(EXPECTED_ISR_STACK_SIZE, mbed_stack_isr_size); TEST_ASSERT_EQUAL(EXPECTED_MAIN_THREAD_STACK_SIZE, _main_thread_attr.stack_size); TEST_ASSERT_EQUAL(EXPECTED_USER_THREAD_DEFAULT_STACK_SIZE, OS_STACK_SIZE); } utest::v1::status_t test_setup(const size_t number_of_cases) { GREENTEA_SETUP(10, "default_auto"); return verbose_test_setup_handler(number_of_cases); } Case cases[] = { Case("Stack size unification test", stack_size_unification_test) }; Specification specification(test_setup, cases); int main() { return !Harness::run(specification); } #endif // TARGET_RENESAS #endif // !defined(MBED_CONF_RTOS_PRESENT) <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: atktextattributes.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: ihi $ $Date: 2006-08-04 13:11:54 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __ATK_ATKTEXTATTRIBUTES_HXX__ #define __ATK_ATKTEXTATTRIBUTES_HXX__ #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #include <atk/atk.h> AtkAttributeSet* attribute_set_new_from_property_values( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& rAttributeList ); bool attribute_set_map_to_property_values( AtkAttributeSet* attribute_set, com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& rValueList ); #endif <commit_msg>INTEGRATION: CWS atkbridge5 (1.3.176); FILE MERGED 2007/01/18 12:32:54 obr 1.3.176.1: #i71385# rework of text attribute code, added language and scale<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: atktextattributes.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2007-01-29 14:23:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __ATK_ATKTEXTATTRIBUTES_HXX__ #define __ATK_ATKTEXTATTRIBUTES_HXX__ #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #include <atk/atk.h> AtkAttributeSet* attribute_set_new_from_property_values( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& rAttributeList, bool run_attributes_only, AtkText *text); bool attribute_set_map_to_property_values( AtkAttributeSet* attribute_set, com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& rValueList ); #endif <|endoftext|>
<commit_before>// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com //---------------------------------------------------------------------------------- #include "stdafx.h" namespace WISP_FILE { //---------------------------------------------------------------------------------- string g_WispMappedFileError = ""; //---------------------------------------------------------------------------------- CMappedFile::CMappedFile() : WISP_DATASTREAM::CDataReader() { } //---------------------------------------------------------------------------------- CMappedFile::~CMappedFile() { Unload(); } //---------------------------------------------------------------------------------- bool CMappedFile::Load() { WISPFUN_DEBUG("c7_f1"); bool result = false; m_Size = GetFileSize(m_File, NULL); if (m_Size > 0) { m_Map = CreateFileMapping(m_File, NULL, 2, 0, NULL, NULL); if (m_Map != NULL) { m_Start = (puchar)MapViewOfFile(m_Map, FILE_MAP_READ, 0, 0, m_Size); result = (m_Start != NULL); if (!result) { CloseHandle(m_Map); CloseHandle(m_File); m_Map = NULL; m_File = INVALID_HANDLE_VALUE; } else SetData(m_Start, m_Size); } else { CloseHandle(m_File); m_File = INVALID_HANDLE_VALUE; } } else { CloseHandle(m_File); m_File = INVALID_HANDLE_VALUE; } return result; } //---------------------------------------------------------------------------------- bool CMappedFile::Load(const string &path) { WISPFUN_DEBUG("c7_f2"); LOG("Mmaping %s\n", path); bool result = false; if (PathFileExistsA(path.c_str())) { Unload(); m_File = CreateFileA(path.c_str(), GENERIC_READ, 1, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (m_File != INVALID_HANDLE_VALUE) result = Load(); else LOG("INVALID_HANDLE_VALUE for CreateFileA %s\n", path); } else LOG("File not found %s\n", path); if (!result) { DWORD errorCode = GetLastError(); LOG("Failed to memory map, error code: %i\n", errorCode); g_WispMappedFileError = path; } return result; } //---------------------------------------------------------------------------------- bool CMappedFile::Load(const wstring &path) { WISPFUN_DEBUG("c7_f3"); bool result = false; if (PathFileExistsW(path.c_str())) { Unload(); m_File = CreateFileW(path.c_str(), GENERIC_READ, 1, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (m_File != INVALID_HANDLE_VALUE) result = Load(); } if (!result) g_WispMappedFileError = ToString(path); return result; } //---------------------------------------------------------------------------------- void CMappedFile::Unload() { WISPFUN_DEBUG("c7_f4"); if (m_Start != NULL) UnmapViewOfFile(m_Start); if (m_Map != NULL) { CloseHandle(m_Map); m_Map = 0; } if (m_File != INVALID_HANDLE_VALUE) { CloseHandle(m_File); m_File = INVALID_HANDLE_VALUE; } SetData(NULL, 0); } //---------------------------------------------------------------------------------- }; //namespace //---------------------------------------------------------------------------------- <commit_msg>path to c-string<commit_after>// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com //---------------------------------------------------------------------------------- #include "stdafx.h" namespace WISP_FILE { //---------------------------------------------------------------------------------- string g_WispMappedFileError = ""; //---------------------------------------------------------------------------------- CMappedFile::CMappedFile() : WISP_DATASTREAM::CDataReader() { } //---------------------------------------------------------------------------------- CMappedFile::~CMappedFile() { Unload(); } //---------------------------------------------------------------------------------- bool CMappedFile::Load() { WISPFUN_DEBUG("c7_f1"); bool result = false; m_Size = GetFileSize(m_File, NULL); if (m_Size > 0) { m_Map = CreateFileMapping(m_File, NULL, 2, 0, NULL, NULL); if (m_Map != NULL) { m_Start = (puchar)MapViewOfFile(m_Map, FILE_MAP_READ, 0, 0, m_Size); result = (m_Start != NULL); if (!result) { CloseHandle(m_Map); CloseHandle(m_File); m_Map = NULL; m_File = INVALID_HANDLE_VALUE; } else SetData(m_Start, m_Size); } else { CloseHandle(m_File); m_File = INVALID_HANDLE_VALUE; } } else { CloseHandle(m_File); m_File = INVALID_HANDLE_VALUE; } return result; } //---------------------------------------------------------------------------------- bool CMappedFile::Load(const string &path) { WISPFUN_DEBUG("c7_f2"); LOG("Mmaping %s\n", path.c_str()); bool result = false; if (PathFileExistsA(path.c_str())) { Unload(); m_File = CreateFileA(path.c_str(), GENERIC_READ, 1, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (m_File != INVALID_HANDLE_VALUE) result = Load(); else LOG("INVALID_HANDLE_VALUE for CreateFileA %s\n", path.c_str()); } else LOG("File not found %s\n", path.c_str()); if (!result) { DWORD errorCode = GetLastError(); LOG("Failed to memory map, error code: %i\n", errorCode); g_WispMappedFileError = path; } return result; } //---------------------------------------------------------------------------------- bool CMappedFile::Load(const wstring &path) { WISPFUN_DEBUG("c7_f3"); bool result = false; if (PathFileExistsW(path.c_str())) { Unload(); m_File = CreateFileW(path.c_str(), GENERIC_READ, 1, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (m_File != INVALID_HANDLE_VALUE) result = Load(); } if (!result) g_WispMappedFileError = ToString(path); return result; } //---------------------------------------------------------------------------------- void CMappedFile::Unload() { WISPFUN_DEBUG("c7_f4"); if (m_Start != NULL) UnmapViewOfFile(m_Start); if (m_Map != NULL) { CloseHandle(m_Map); m_Map = 0; } if (m_File != INVALID_HANDLE_VALUE) { CloseHandle(m_File); m_File = INVALID_HANDLE_VALUE; } SetData(NULL, 0); } //---------------------------------------------------------------------------------- }; //namespace //---------------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* ************************************************************************ * Copyright 2016 Advanced Micro Devices, Inc. * * ************************************************************************ */ #include <sys/time.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <vector> #include "rocblas.hpp" #include "utility.h" #include "cblas_interface.h" #include "norm.h" #include "unit.h" #include "flops.h" #include <typeinfo> using namespace std; /* ============================================================================================ */ template<typename T> rocblas_status testing_gemm(Arguments argus) { rocblas_int M = argus.M; rocblas_int N = argus.N; rocblas_int K = argus.K; rocblas_int lda = argus.lda; rocblas_int ldb = argus.ldb; rocblas_int ldc = argus.ldc; rocblas_operation transA = char2rocblas_operation(argus.transA_option); rocblas_operation transB = char2rocblas_operation(argus.transB_option); rocblas_int A_size, B_size, C_size, A_row, A_col, B_row, B_col; T alpha = argus.alpha; T beta = argus.beta; double gpu_time_used, cpu_time_used; double rocblas_gflops, cblas_gflops; T rocblas_error = 0.0; rocblas_handle handle; rocblas_status status = rocblas_status_success; rocblas_create_handle(&handle); if(transA == rocblas_operation_none){ A_row = M; A_col = K; } else{ A_row = K; A_col = M; } if(transB == rocblas_operation_none){ B_row = K; B_col = N; } else{ B_row = N; B_col = K; } A_size = lda * A_col; B_size = ldb * B_col; C_size = ldc * N; //check here to prevent undefined memory allocation error if( M < 0 || N < 0 || K < 0 || lda < 0 || ldb < 0 || ldc < 0 ){ return rocblas_status_invalid_size; } //Naming: dX is in GPU (device) memory. hK is in CPU (host) memory, plz follow this practice vector<T> hA(A_size); vector<T> hB(B_size); vector<T> hC(C_size); vector<T> hC_copy(C_size); T *dA, *dB, *dC; //allocate memory on device CHECK_HIP_ERROR(hipMalloc(&dA, A_size * sizeof(T))); CHECK_HIP_ERROR(hipMalloc(&dB, B_size * sizeof(T))); CHECK_HIP_ERROR(hipMalloc(&dC, C_size * sizeof(T))); //Initial Data on CPU srand(1); rocblas_init<T>(hA, A_row, A_col, lda); rocblas_init<T>(hB, B_row, B_col, ldb); rocblas_init<T>(hC, M, N, ldc); //copy vector is easy in STL; hz = hx: save a copy in hC_copy which will be output of CPU BLAS hC_copy = hC; //copy data from CPU to device, does not work for lda != A_row CHECK_HIP_ERROR(hipMemcpy(dA, hA.data(), sizeof(T)*lda*A_col, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dB, hB.data(), sizeof(T)*ldb*B_col, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dC, hC.data(), sizeof(T)*ldc*N, hipMemcpyHostToDevice)); /* ===================================================================== ROCBLAS =================================================================== */ if(argus.timing){ gpu_time_used = get_time_us();// in microseconds } //library interface status = rocblas_gemm<T>(handle, transA, transB, M, N, K, &alpha, dA, lda, dB, ldb, &beta, dC, ldc); // sleep(1); if(argus.timing){ gpu_time_used = get_time_us() - gpu_time_used; rocblas_gflops = gemm_gflop_count<T> (M, N, K) / gpu_time_used * 1e6; } //copy output from device to CPU CHECK_HIP_ERROR(hipMemcpy(hC.data(), dC, sizeof(T)*ldc*N, hipMemcpyDeviceToHost)); if(argus.unit_check || argus.norm_check){ /* ===================================================================== CPU BLAS =================================================================== */ if(argus.timing){ cpu_time_used = get_time_us(); } cblas_gemm<T>( transA, transB, M, N, K, alpha, hA.data(), lda, hB.data(), ldb, beta, hC_copy.data(), ldc); if(argus.timing){ cpu_time_used = get_time_us() - cpu_time_used; cblas_gflops = gemm_gflop_count<T>(M, N, K) / cpu_time_used * 1e6; } for(int i=0;i<min(N, 4);i++) for(int j=0;j<min(M,4);j++) { printf("matrix C col %d, row %d, CPU result=%f, GPU result=%f\n", i, j, hC_copy[j+i*ldc], hC[j+i*ldc]); } //enable unit check, notice unit check is not invasive, but norm check is, // unit check and norm check can not be interchanged their order if(argus.unit_check){ unit_check_general<T>(M, N, ldc, hC_copy.data(), hC.data()); } //if enable norm check, norm check is invasive //any typeinfo(T) will not work here, because template deduction is matched in compilation time if(argus.norm_check){ rocblas_error = norm_check_general<T>('F', M, N, ldc, hC_copy.data(), hC.data()); } }// end of if unit/norm check if(argus.timing){ //only norm_check return an norm error, unit check won't return anything, cout << "Shape, M, N, K, lda, ldb, ldc, rocblas-Gflops (us) "; if(argus.norm_check){ cout << "CPU-Gflops(us), norm-error" ; } cout << endl; cout << argus.transA_option << argus.transB_option << ',' << M <<','<< N <<',' << K <<',' << lda <<','<< ldb <<',' << ldc <<',' << rocblas_gflops << "(" << gpu_time_used << "),"; if(argus.norm_check){ cout << cblas_gflops << "(" << cpu_time_used << "),"; cout << rocblas_error; } cout << endl; } CHECK_HIP_ERROR(hipFree(dA)); CHECK_HIP_ERROR(hipFree(dB)); CHECK_HIP_ERROR(hipFree(dC)); rocblas_destroy_handle(handle); return status; } /* ============================================================================================ */ /*! \brief Bencharking GEMM, allocate a large matrix once. subsequent steps get a sub-matrix. The memory allocation/deallocation overhead is amortized Intended for long time running */ template<typename T> rocblas_status range_testing_gemm(Arguments argus) { rocblas_int start = argus.start; rocblas_int step = argus.step; rocblas_int end = argus.end; rocblas_operation transA = char2rocblas_operation(argus.transA_option); rocblas_operation transB = char2rocblas_operation(argus.transB_option); rocblas_int A_size, B_size, C_size; T alpha = argus.alpha; T beta = argus.beta; double rocblas_gflops, cblas_gflops; double gpu_time_used, cpu_time_used; T rocblas_error = 0.0; rocblas_handle handle; rocblas_status status = rocblas_status_success; //argument sanity check, quick return if input parameters are invalid before allocating invalid memory if( start < 0 || end < 0 || step < 0 || end < start ){ cout << "Invalid matrix dimension input, will return" << endl; return rocblas_status_invalid_size; } A_size = B_size = C_size = end * end; //Naming: dX is in GPU (device) memory. hK is in CPU (host) memory, plz follow this practice vector<T> hA(A_size); vector<T> hB(B_size); vector<T> hC(C_size); vector<T> hC_copy(C_size); T *dA, *dB, *dC; rocblas_create_handle(&handle); //allocate memory on device CHECK_HIP_ERROR(hipMalloc(&dA, A_size * sizeof(T))); CHECK_HIP_ERROR(hipMalloc(&dB, B_size * sizeof(T))); CHECK_HIP_ERROR(hipMalloc(&dC, C_size * sizeof(T))); //rocblas_malloc_device(&dx, sizeX * sizeof(T)); //Initial Data on CPU srand(1); rocblas_init<T>(hA, end, end, end); rocblas_init<T>(hB, end, end, end); rocblas_init<T>(hC, end, end, end); //copy vector is easy in STL; hz = hx: save a copy in hC_copy which will be output of CPU BLAS hC_copy = hC; //copy data from CPU to device CHECK_HIP_ERROR(hipMemcpy(dA, hA.data(), sizeof(T)*end*end, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dB, hB.data(), sizeof(T)*end*end, hipMemcpyHostToDevice)); char precision = type2char<T>(); // like turn float-> 's' string filename = string("benchmark_") + precision + string("gemm_") + argus.transA_option + argus.transB_option + string("_") + to_string(start) + "to" + to_string(end) + "_step" + to_string(step) + ".csv"; ofstream myfile; myfile.open(filename); if (myfile.is_open()){ myfile << "M, N, K, lda, ldb, ldc, rocblas-Gflops (us) "; if(argus.norm_check){ myfile << "CPU-Gflops(us), norm-error" ; } myfile << endl; } for(rocblas_int size = start; size <= end; size += step){ cout << "Benchmarking M:" << (int)size << ", N:"<< (int) size <<", K:" << (int)size << endl ; //make sure CPU and GPU routines see the same input hC = hC_copy; CHECK_HIP_ERROR(hipMemcpy(dC, hC.data(), sizeof(T)*size*size, hipMemcpyHostToDevice)); /* ===================================================================== ROCBLAS =================================================================== */ gpu_time_used = get_time_us();// in microseconds rocblas_gflops = gemm_gflop_count<T> (size, size, size) / gpu_time_used * 1e6 ; //library interface status = rocblas_gemm<T>(handle, transA, transB, size, size, size, &alpha, dA, size, dB, size, &beta, dC, size); gpu_time_used = get_time_us() - gpu_time_used; //copy output from device to CPU hipMemcpy(hC.data(), dC, sizeof(T)*size*size, hipMemcpyDeviceToHost); if(argus.norm_check){ /* ===================================================================== CPU BLAS =================================================================== */ cpu_time_used = get_time_us(); cblas_gemm<T>( transA, transB, size, size, size, alpha, hA.data(), size, hB.data(), size, beta, hC_copy.data(), size); cpu_time_used = get_time_us() - cpu_time_used; cblas_gflops = gemm_gflop_count<T> (size, size, size) / cpu_time_used * 1e6 ; //if enable norm check, norm check is invasive //any typeinfo(T) will not work here, because template deduction is matched in compilation time if(argus.norm_check) { rocblas_error = norm_check_general<T>('F', size, size, size, hC_copy.data(), hC.data()); } }// end of if unit/norm check if (myfile.is_open()){ //only norm_check return an norm error, unit check won't return anything, only return the real part, imag part does not make sense myfile << size <<','<< size <<',' << size <<',' << size <<','<< size <<',' << size <<',' << rocblas_gflops << "(" << gpu_time_used << "),"; if(argus.norm_check){ myfile << cblas_gflops << "(" << cpu_time_used << "),"; //cout << rocblas_error; } myfile << endl; } }// end of loop if (myfile.is_open()) myfile.close(); CHECK_HIP_ERROR(hipFree(dA)); CHECK_HIP_ERROR(hipFree(dB)); CHECK_HIP_ERROR(hipFree(dC)); rocblas_destroy_handle(handle); return status; } template<typename T> rocblas_status benchmark_gemm(Arguments argus) { //if negative, fall back to specific matrix size testing //otherwise, range testing. only norm check is enabled in range_test if(argus.start < 0 || argus.end < 0 || argus.step < 0){ cout << "Specific matrix size testing: output will be displayed on terminal" << endl; cout << endl; return testing_gemm<T>(argus); } else{ argus.timing = 1; //timing is enabled cout << "Range matrix size testing: output will be benchmark_xgemm_(transpose)_(begin)to(end)_(step).csv ..." << endl; cout << endl; //cout << "==================================================================" << endl; return range_testing_gemm<T>(argus); } } <commit_msg>protect cblas call when status == success<commit_after>/* ************************************************************************ * Copyright 2016 Advanced Micro Devices, Inc. * * ************************************************************************ */ #include <sys/time.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <vector> #include "rocblas.hpp" #include "utility.h" #include "cblas_interface.h" #include "norm.h" #include "unit.h" #include "flops.h" #include <typeinfo> using namespace std; /* ============================================================================================ */ template<typename T> rocblas_status testing_gemm(Arguments argus) { rocblas_int M = argus.M; rocblas_int N = argus.N; rocblas_int K = argus.K; rocblas_int lda = argus.lda; rocblas_int ldb = argus.ldb; rocblas_int ldc = argus.ldc; rocblas_operation transA = char2rocblas_operation(argus.transA_option); rocblas_operation transB = char2rocblas_operation(argus.transB_option); rocblas_int A_size, B_size, C_size, A_row, A_col, B_row, B_col; T alpha = argus.alpha; T beta = argus.beta; double gpu_time_used, cpu_time_used; double rocblas_gflops, cblas_gflops; T rocblas_error = 0.0; rocblas_handle handle; rocblas_status status = rocblas_status_success; rocblas_create_handle(&handle); if(transA == rocblas_operation_none){ A_row = M; A_col = K; } else{ A_row = K; A_col = M; } if(transB == rocblas_operation_none){ B_row = K; B_col = N; } else{ B_row = N; B_col = K; } A_size = lda * A_col; B_size = ldb * B_col; C_size = ldc * N; //check here to prevent undefined memory allocation error if( M < 0 || N < 0 || K < 0 || lda < 0 || ldb < 0 || ldc < 0 ){ return rocblas_status_invalid_size; } //Naming: dX is in GPU (device) memory. hK is in CPU (host) memory, plz follow this practice vector<T> hA(A_size); vector<T> hB(B_size); vector<T> hC(C_size); vector<T> hC_copy(C_size); T *dA, *dB, *dC; //allocate memory on device CHECK_HIP_ERROR(hipMalloc(&dA, A_size * sizeof(T))); CHECK_HIP_ERROR(hipMalloc(&dB, B_size * sizeof(T))); CHECK_HIP_ERROR(hipMalloc(&dC, C_size * sizeof(T))); //Initial Data on CPU srand(1); rocblas_init<T>(hA, A_row, A_col, lda); rocblas_init<T>(hB, B_row, B_col, ldb); rocblas_init<T>(hC, M, N, ldc); //copy vector is easy in STL; hz = hx: save a copy in hC_copy which will be output of CPU BLAS hC_copy = hC; //copy data from CPU to device, does not work for lda != A_row CHECK_HIP_ERROR(hipMemcpy(dA, hA.data(), sizeof(T)*lda*A_col, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dB, hB.data(), sizeof(T)*ldb*B_col, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dC, hC.data(), sizeof(T)*ldc*N, hipMemcpyHostToDevice)); /* ===================================================================== ROCBLAS =================================================================== */ if(argus.timing){ gpu_time_used = get_time_us();// in microseconds } //library interface status = rocblas_gemm<T>(handle, transA, transB, M, N, K, &alpha, dA, lda, dB, ldb, &beta, dC, ldc); // sleep(1); if(argus.timing){ gpu_time_used = get_time_us() - gpu_time_used; rocblas_gflops = gemm_gflop_count<T> (M, N, K) / gpu_time_used * 1e6; } //copy output from device to CPU CHECK_HIP_ERROR(hipMemcpy(hC.data(), dC, sizeof(T)*ldc*N, hipMemcpyDeviceToHost)); if(argus.unit_check || argus.norm_check){ /* ===================================================================== CPU BLAS =================================================================== */ if(argus.timing){ cpu_time_used = get_time_us(); } if(status == rocblas_status_success) { cblas_gemm<T>( transA, transB, M, N, K, alpha, hA.data(), lda, hB.data(), ldb, beta, hC_copy.data(), ldc); } if(argus.timing){ cpu_time_used = get_time_us() - cpu_time_used; cblas_gflops = gemm_gflop_count<T>(M, N, K) / cpu_time_used * 1e6; } for(int i=0;i<min(N, 4);i++) for(int j=0;j<min(M,4);j++) { printf("matrix C col %d, row %d, CPU result=%f, GPU result=%f\n", i, j, hC_copy[j+i*ldc], hC[j+i*ldc]); } //enable unit check, notice unit check is not invasive, but norm check is, // unit check and norm check can not be interchanged their order if(argus.unit_check){ unit_check_general<T>(M, N, ldc, hC_copy.data(), hC.data()); } //if enable norm check, norm check is invasive //any typeinfo(T) will not work here, because template deduction is matched in compilation time if(argus.norm_check){ rocblas_error = norm_check_general<T>('F', M, N, ldc, hC_copy.data(), hC.data()); } }// end of if unit/norm check if(argus.timing){ //only norm_check return an norm error, unit check won't return anything, cout << "Shape, M, N, K, lda, ldb, ldc, rocblas-Gflops (us) "; if(argus.norm_check){ cout << "CPU-Gflops(us), norm-error" ; } cout << endl; cout << argus.transA_option << argus.transB_option << ',' << M <<','<< N <<',' << K <<',' << lda <<','<< ldb <<',' << ldc <<',' << rocblas_gflops << "(" << gpu_time_used << "),"; if(argus.norm_check){ cout << cblas_gflops << "(" << cpu_time_used << "),"; cout << rocblas_error; } cout << endl; } CHECK_HIP_ERROR(hipFree(dA)); CHECK_HIP_ERROR(hipFree(dB)); CHECK_HIP_ERROR(hipFree(dC)); rocblas_destroy_handle(handle); return status; } /* ============================================================================================ */ /*! \brief Bencharking GEMM, allocate a large matrix once. subsequent steps get a sub-matrix. The memory allocation/deallocation overhead is amortized Intended for long time running */ template<typename T> rocblas_status range_testing_gemm(Arguments argus) { rocblas_int start = argus.start; rocblas_int step = argus.step; rocblas_int end = argus.end; rocblas_operation transA = char2rocblas_operation(argus.transA_option); rocblas_operation transB = char2rocblas_operation(argus.transB_option); rocblas_int A_size, B_size, C_size; T alpha = argus.alpha; T beta = argus.beta; double rocblas_gflops, cblas_gflops; double gpu_time_used, cpu_time_used; T rocblas_error = 0.0; rocblas_handle handle; rocblas_status status = rocblas_status_success; //argument sanity check, quick return if input parameters are invalid before allocating invalid memory if( start < 0 || end < 0 || step < 0 || end < start ){ cout << "Invalid matrix dimension input, will return" << endl; return rocblas_status_invalid_size; } A_size = B_size = C_size = end * end; //Naming: dX is in GPU (device) memory. hK is in CPU (host) memory, plz follow this practice vector<T> hA(A_size); vector<T> hB(B_size); vector<T> hC(C_size); vector<T> hC_copy(C_size); T *dA, *dB, *dC; rocblas_create_handle(&handle); //allocate memory on device CHECK_HIP_ERROR(hipMalloc(&dA, A_size * sizeof(T))); CHECK_HIP_ERROR(hipMalloc(&dB, B_size * sizeof(T))); CHECK_HIP_ERROR(hipMalloc(&dC, C_size * sizeof(T))); //rocblas_malloc_device(&dx, sizeX * sizeof(T)); //Initial Data on CPU srand(1); rocblas_init<T>(hA, end, end, end); rocblas_init<T>(hB, end, end, end); rocblas_init<T>(hC, end, end, end); //copy vector is easy in STL; hz = hx: save a copy in hC_copy which will be output of CPU BLAS hC_copy = hC; //copy data from CPU to device CHECK_HIP_ERROR(hipMemcpy(dA, hA.data(), sizeof(T)*end*end, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dB, hB.data(), sizeof(T)*end*end, hipMemcpyHostToDevice)); char precision = type2char<T>(); // like turn float-> 's' string filename = string("benchmark_") + precision + string("gemm_") + argus.transA_option + argus.transB_option + string("_") + to_string(start) + "to" + to_string(end) + "_step" + to_string(step) + ".csv"; ofstream myfile; myfile.open(filename); if (myfile.is_open()){ myfile << "M, N, K, lda, ldb, ldc, rocblas-Gflops (us) "; if(argus.norm_check){ myfile << "CPU-Gflops(us), norm-error" ; } myfile << endl; } for(rocblas_int size = start; size <= end; size += step){ cout << "Benchmarking M:" << (int)size << ", N:"<< (int) size <<", K:" << (int)size << endl ; //make sure CPU and GPU routines see the same input hC = hC_copy; CHECK_HIP_ERROR(hipMemcpy(dC, hC.data(), sizeof(T)*size*size, hipMemcpyHostToDevice)); /* ===================================================================== ROCBLAS =================================================================== */ gpu_time_used = get_time_us();// in microseconds rocblas_gflops = gemm_gflop_count<T> (size, size, size) / gpu_time_used * 1e6 ; //library interface status = rocblas_gemm<T>(handle, transA, transB, size, size, size, &alpha, dA, size, dB, size, &beta, dC, size); gpu_time_used = get_time_us() - gpu_time_used; //copy output from device to CPU hipMemcpy(hC.data(), dC, sizeof(T)*size*size, hipMemcpyDeviceToHost); if(argus.norm_check){ /* ===================================================================== CPU BLAS =================================================================== */ cpu_time_used = get_time_us(); cblas_gemm<T>( transA, transB, size, size, size, alpha, hA.data(), size, hB.data(), size, beta, hC_copy.data(), size); cpu_time_used = get_time_us() - cpu_time_used; cblas_gflops = gemm_gflop_count<T> (size, size, size) / cpu_time_used * 1e6 ; //if enable norm check, norm check is invasive //any typeinfo(T) will not work here, because template deduction is matched in compilation time if(argus.norm_check) { rocblas_error = norm_check_general<T>('F', size, size, size, hC_copy.data(), hC.data()); } }// end of if unit/norm check if (myfile.is_open()){ //only norm_check return an norm error, unit check won't return anything, only return the real part, imag part does not make sense myfile << size <<','<< size <<',' << size <<',' << size <<','<< size <<',' << size <<',' << rocblas_gflops << "(" << gpu_time_used << "),"; if(argus.norm_check){ myfile << cblas_gflops << "(" << cpu_time_used << "),"; //cout << rocblas_error; } myfile << endl; } }// end of loop if (myfile.is_open()) myfile.close(); CHECK_HIP_ERROR(hipFree(dA)); CHECK_HIP_ERROR(hipFree(dB)); CHECK_HIP_ERROR(hipFree(dC)); rocblas_destroy_handle(handle); return status; } template<typename T> rocblas_status benchmark_gemm(Arguments argus) { //if negative, fall back to specific matrix size testing //otherwise, range testing. only norm check is enabled in range_test if(argus.start < 0 || argus.end < 0 || argus.step < 0){ cout << "Specific matrix size testing: output will be displayed on terminal" << endl; cout << endl; return testing_gemm<T>(argus); } else{ argus.timing = 1; //timing is enabled cout << "Range matrix size testing: output will be benchmark_xgemm_(transpose)_(begin)to(end)_(step).csv ..." << endl; cout << endl; //cout << "==================================================================" << endl; return range_testing_gemm<T>(argus); } } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "CommandDescriptor.h" #include "OOModel/src/expressions/ReferenceExpression.h" #include "OOModel/src/expressions/EmptyExpression.h" #include "OOModel/src/expressions/UnfinishedOperator.h" #include "OOModel/src/expressions/CommaExpression.h" namespace OOInteraction { QMap<QString, CommandExpression*> CommandDescriptor::commands; bool CommandDescriptor::registerCommand(CommandExpression* command) { if (commands.contains(command->name())) return false; else commands.insert(command->name(), command); return true; } void CommandDescriptor::unregisterCommand(CommandExpression* command) { if (command) commands.remove(command->name()); } CommandDescriptor::CommandDescriptor(const QString& name, const QString& signature, int precedence, Associativity associativity) : OOOperatorDescriptor(name, signature, precedence, associativity) {} CommandDescriptor::~CommandDescriptor() { for(auto c : commands.values()) SAFE_DELETE(c); } OOModel::Expression* CommandDescriptor::create(const QList<OOModel::Expression*>& operands) { auto ref = dynamic_cast<OOModel::ReferenceExpression*>( operands.first()); Q_ASSERT(ref); QString name = ref->name(); SAFE_DELETE(ref); // Unpack second argument if any QList<OOModel::Expression*> arguments; if (operands.size() > 1) { if (auto comma = dynamic_cast<OOModel::CommaExpression*>(operands.last())) { for(auto arg : comma->allSubOperands(true)) arguments.append(arg); SAFE_DELETE(comma); } else if (!dynamic_cast<OOModel::EmptyExpression*>(operands.last()) ) arguments.append(operands.last()); } auto it = commands.find(name); OOModel::Expression* e = nullptr; if (it != commands.end()) e = (*it)->create(arguments); if (e) return e; else return createUnfinished(name, arguments); } OOModel::UnfinishedOperator* CommandDescriptor::createUnfinished(const QString& name, const QList<OOModel::Expression*>& arguments) { auto unf = new OOModel::UnfinishedOperator(); unf->delimiters()->append(new Model::Text("\\")); unf->operands()->append(new OOModel::ReferenceExpression(name)); if (!arguments.isEmpty()) { unf->delimiters()->append(new Model::Text("(")); for(int i = 0; i< arguments.size(); ++i) { if (i > 0) unf->delimiters()->append(new Model::Text(",")); unf->operands()->append(arguments[i]); } unf->delimiters()->append(new Model::Text(")")); } else unf->delimiters()->append(new Model::Text(QString())); // append an empty postfix if there are no arguments return unf; } } /* namespace OOInteraction */ <commit_msg>Fix a double delete bug and a related memory leak<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "CommandDescriptor.h" #include "OOModel/src/expressions/ReferenceExpression.h" #include "OOModel/src/expressions/EmptyExpression.h" #include "OOModel/src/expressions/UnfinishedOperator.h" #include "OOModel/src/expressions/CommaExpression.h" namespace OOInteraction { QMap<QString, CommandExpression*> CommandDescriptor::commands; bool CommandDescriptor::registerCommand(CommandExpression* command) { if (commands.contains(command->name())) return false; else commands.insert(command->name(), command); return true; } void CommandDescriptor::unregisterCommand(CommandExpression* command) { if (command) commands.remove(command->name()); SAFE_DELETE(command); } CommandDescriptor::CommandDescriptor(const QString& name, const QString& signature, int precedence, Associativity associativity) : OOOperatorDescriptor(name, signature, precedence, associativity) {} CommandDescriptor::~CommandDescriptor() { qDeleteAll(commands); commands.clear(); } OOModel::Expression* CommandDescriptor::create(const QList<OOModel::Expression*>& operands) { auto ref = dynamic_cast<OOModel::ReferenceExpression*>( operands.first()); Q_ASSERT(ref); QString name = ref->name(); SAFE_DELETE(ref); // Unpack second argument if any QList<OOModel::Expression*> arguments; if (operands.size() > 1) { if (auto comma = dynamic_cast<OOModel::CommaExpression*>(operands.last())) { for(auto arg : comma->allSubOperands(true)) arguments.append(arg); SAFE_DELETE(comma); } else if (!dynamic_cast<OOModel::EmptyExpression*>(operands.last()) ) arguments.append(operands.last()); } auto it = commands.find(name); OOModel::Expression* e = nullptr; if (it != commands.end()) e = (*it)->create(arguments); if (e) return e; else return createUnfinished(name, arguments); } OOModel::UnfinishedOperator* CommandDescriptor::createUnfinished(const QString& name, const QList<OOModel::Expression*>& arguments) { auto unf = new OOModel::UnfinishedOperator(); unf->delimiters()->append(new Model::Text("\\")); unf->operands()->append(new OOModel::ReferenceExpression(name)); if (!arguments.isEmpty()) { unf->delimiters()->append(new Model::Text("(")); for(int i = 0; i< arguments.size(); ++i) { if (i > 0) unf->delimiters()->append(new Model::Text(",")); unf->operands()->append(arguments[i]); } unf->delimiters()->append(new Model::Text(")")); } else unf->delimiters()->append(new Model::Text(QString())); // append an empty postfix if there are no arguments return unf; } } /* namespace OOInteraction */ <|endoftext|>
<commit_before>/* Copyright (c) 2017-2018 Andrew Depke */ #include "LinuxStackTrace.h" #include "../../Math/MathCore.h" #include <cxxabi.h> #include <execinfo.h> #include <dlfcn.h> #include <stdlib.h> // Darwin Doesn't Have free() By Default, Include it Here namespace Red { bool CaptureStackTrace(int MaxDepth, std::vector<StackFrame>* Output) { if (!Output || MaxDepth <= 0) { return false; } size_t Frames = 0; void* RawStackTrace[128]; Frames = backtrace(RawStackTrace, Min(MaxDepth, 128)); if (Frames <= 0) { return false; } char** StackTrace = backtrace_symbols(RawStackTrace, Frames); for (size_t Iter = 0; Iter < Frames; ++Iter) { std::string FrameString = StackTrace[Iter]; StackFrame Frame; char FrameAddressBuffer[64]; snprintf(FrameAddressBuffer, sizeof(FrameAddressBuffer), "0x%016llX", (unsigned long long int)RawStackTrace[Iter]); // Assume 64 Bit Addresses. Frame.Address = FrameAddressBuffer; // Note: Module Name Can Also Be Obtained From dladdr() size_t ModuleNameEnd = FrameString.find('('); Frame.Module = FrameString.substr(0, ModuleNameEnd); // Isolate the Module Name in the Case of "./<ModuleName>" if (sizeof(Frame.Module) / sizeof(Frame.Module[0]) > 2) { if (Frame.Module[0] == '.' && Frame.Module[1] == '/') { Frame.Module = Frame.Module.substr(2); } } Dl_info Info; if (dladdr(RawStackTrace[Iter], &Info) && Info.dli_sname) { int OperationStatus; char* DemangledName = abi::__cxa_demangle(Info.dli_sname, nullptr, 0, &OperationStatus); if (OperationStatus == 0 && DemangledName) { Frame.Function = DemangledName; free(DemangledName); } else { Frame.Function == Info.dli_sname; } } Output->push_back(Frame); } if (StackTrace) { free(StackTrace); } return true; } } // namespace Red <commit_msg>Fixed Assignment Typo<commit_after>/* Copyright (c) 2017-2018 Andrew Depke */ #include "LinuxStackTrace.h" #include "../../Math/MathCore.h" #include <cxxabi.h> #include <execinfo.h> #include <dlfcn.h> #include <stdlib.h> // Darwin Doesn't Have free() By Default, Include it Here namespace Red { bool CaptureStackTrace(int MaxDepth, std::vector<StackFrame>* Output) { if (!Output || MaxDepth <= 0) { return false; } size_t Frames = 0; void* RawStackTrace[128]; Frames = backtrace(RawStackTrace, Min(MaxDepth, 128)); if (Frames <= 0) { return false; } char** StackTrace = backtrace_symbols(RawStackTrace, Frames); for (size_t Iter = 0; Iter < Frames; ++Iter) { std::string FrameString = StackTrace[Iter]; StackFrame Frame; char FrameAddressBuffer[64]; snprintf(FrameAddressBuffer, sizeof(FrameAddressBuffer), "0x%016llX", (unsigned long long int)RawStackTrace[Iter]); // Assume 64 Bit Addresses. Frame.Address = FrameAddressBuffer; // Note: Module Name Can Also Be Obtained From dladdr() size_t ModuleNameEnd = FrameString.find('('); Frame.Module = FrameString.substr(0, ModuleNameEnd); // Isolate the Module Name in the Case of "./<ModuleName>" if (sizeof(Frame.Module) / sizeof(Frame.Module[0]) > 2) { if (Frame.Module[0] == '.' && Frame.Module[1] == '/') { Frame.Module = Frame.Module.substr(2); } } Dl_info Info; if (dladdr(RawStackTrace[Iter], &Info) && Info.dli_sname) { int OperationStatus; char* DemangledName = abi::__cxa_demangle(Info.dli_sname, nullptr, 0, &OperationStatus); if (OperationStatus == 0 && DemangledName) { Frame.Function = DemangledName; free(DemangledName); } else { Frame.Function = Info.dli_sname; } } Output->push_back(Frame); } if (StackTrace) { free(StackTrace); } return true; } } // namespace Red <|endoftext|>
<commit_before>#ifndef VEXCL_BACKEND_OPENCL_DEVICE_VECTOR_HPP #define VEXCL_BACKEND_OPENCL_DEVICE_VECTOR_HPP /* The MIT License Copyright (c) 2012-2018 Denis Demidov <dennis.demidov@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file vexcl/backend/opencl/device_vector.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief OpenCL device vector. */ #include <vexcl/backend/opencl/defines.hpp> #include <CL/cl.hpp> namespace vex { namespace backend { namespace opencl { typedef cl_mem_flags mem_flags; static const mem_flags MEM_READ_ONLY = CL_MEM_READ_ONLY; static const mem_flags MEM_WRITE_ONLY = CL_MEM_WRITE_ONLY; static const mem_flags MEM_READ_WRITE = CL_MEM_READ_WRITE; template <typename T> class device_vector { public: typedef T value_type; typedef cl_mem raw_type; device_vector() {} device_vector(const cl::CommandQueue &q, size_t n, const T *host = 0, mem_flags flags = MEM_READ_WRITE) { if (host && !(flags & CL_MEM_USE_HOST_PTR)) flags |= CL_MEM_COPY_HOST_PTR; if (n) buffer = cl::Buffer(q.getInfo<CL_QUEUE_CONTEXT>(), flags, n * sizeof(T), static_cast<void*>(const_cast<T*>(host))); } device_vector(cl::Buffer buffer) : buffer( std::move(buffer) ) {} template <typename U> device_vector<U> reinterpret() const { return device_vector<U>(buffer); } void write(const cl::CommandQueue &q, size_t offset, size_t size, const T *host, bool blocking = false) const { if (size) q.enqueueWriteBuffer( buffer, blocking ? CL_TRUE : CL_FALSE, sizeof(T) * offset, sizeof(T) * size, host ); } void read(const cl::CommandQueue &q, size_t offset, size_t size, T *host, bool blocking = false) const { if (size) q.enqueueReadBuffer( buffer, blocking ? CL_TRUE : CL_FALSE, sizeof(T) * offset, sizeof(T) * size, host ); } size_t size() const { return buffer.getInfo<CL_MEM_SIZE>() / sizeof(T); } struct buffer_unmapper { const cl::CommandQueue &queue; const cl::Buffer &buffer; buffer_unmapper(const cl::CommandQueue &q, const cl::Buffer &b) : queue(q), buffer(b) {} void operator()(T* ptr) const { queue.enqueueUnmapMemObject(buffer, ptr); } }; typedef std::unique_ptr<T[], buffer_unmapper> mapped_array; mapped_array map(const cl::CommandQueue &q) { return mapped_array( static_cast<T*>( q.enqueueMapBuffer( buffer, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, size() * sizeof(T) ) ), buffer_unmapper(q, buffer) ); } mapped_array map(const cl::CommandQueue &q) const { return mapped_array( static_cast<T*>( q.enqueueMapBuffer( buffer, CL_TRUE, CL_MAP_READ, 0, size() * sizeof(T) ) ), buffer_unmapper(q, buffer) ); } cl_mem raw() const { return buffer(); } cl::Buffer raw_buffer() const { return buffer; } private: cl::Buffer buffer; }; } // namespace opencl } // namespace backend } // namespace vex #endif <commit_msg>Fix device_vector::size() for an empty vector<commit_after>#ifndef VEXCL_BACKEND_OPENCL_DEVICE_VECTOR_HPP #define VEXCL_BACKEND_OPENCL_DEVICE_VECTOR_HPP /* The MIT License Copyright (c) 2012-2018 Denis Demidov <dennis.demidov@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file vexcl/backend/opencl/device_vector.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief OpenCL device vector. */ #include <vexcl/backend/opencl/defines.hpp> #include <CL/cl.hpp> namespace vex { namespace backend { namespace opencl { typedef cl_mem_flags mem_flags; static const mem_flags MEM_READ_ONLY = CL_MEM_READ_ONLY; static const mem_flags MEM_WRITE_ONLY = CL_MEM_WRITE_ONLY; static const mem_flags MEM_READ_WRITE = CL_MEM_READ_WRITE; template <typename T> class device_vector { public: typedef T value_type; typedef cl_mem raw_type; device_vector() {} device_vector(const cl::CommandQueue &q, size_t n, const T *host = 0, mem_flags flags = MEM_READ_WRITE) { if (host && !(flags & CL_MEM_USE_HOST_PTR)) flags |= CL_MEM_COPY_HOST_PTR; if (n) buffer = cl::Buffer(q.getInfo<CL_QUEUE_CONTEXT>(), flags, n * sizeof(T), static_cast<void*>(const_cast<T*>(host))); } device_vector(cl::Buffer buffer) : buffer( std::move(buffer) ) {} template <typename U> device_vector<U> reinterpret() const { return device_vector<U>(buffer); } void write(const cl::CommandQueue &q, size_t offset, size_t size, const T *host, bool blocking = false) const { if (size) q.enqueueWriteBuffer( buffer, blocking ? CL_TRUE : CL_FALSE, sizeof(T) * offset, sizeof(T) * size, host ); } void read(const cl::CommandQueue &q, size_t offset, size_t size, T *host, bool blocking = false) const { if (size) q.enqueueReadBuffer( buffer, blocking ? CL_TRUE : CL_FALSE, sizeof(T) * offset, sizeof(T) * size, host ); } size_t size() const { if (buffer()) return buffer.getInfo<CL_MEM_SIZE>() / sizeof(T); return 0; } struct buffer_unmapper { const cl::CommandQueue &queue; const cl::Buffer &buffer; buffer_unmapper(const cl::CommandQueue &q, const cl::Buffer &b) : queue(q), buffer(b) {} void operator()(T* ptr) const { queue.enqueueUnmapMemObject(buffer, ptr); } }; typedef std::unique_ptr<T[], buffer_unmapper> mapped_array; mapped_array map(const cl::CommandQueue &q) { return mapped_array( static_cast<T*>( q.enqueueMapBuffer( buffer, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, size() * sizeof(T) ) ), buffer_unmapper(q, buffer) ); } mapped_array map(const cl::CommandQueue &q) const { return mapped_array( static_cast<T*>( q.enqueueMapBuffer( buffer, CL_TRUE, CL_MAP_READ, 0, size() * sizeof(T) ) ), buffer_unmapper(q, buffer) ); } cl_mem raw() const { return buffer(); } cl::Buffer raw_buffer() const { return buffer; } private: cl::Buffer buffer; }; } // namespace opencl } // namespace backend } // namespace vex #endif <|endoftext|>
<commit_before>AliAnalysisTaskESDfilter *AddTaskESDFilter(Bool_t useKineFilter=kTRUE) { // Creates a filter task and adds it to the analysis manager. // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskESDFilter", "No analysis manager to connect to."); return NULL; } // This task requires an ESD input handler and an AOD output handler. // Check this using the analysis manager. //=============================================================================== TString type = mgr->GetInputEventHandler()->GetDataType(); if (!type.Contains("ESD")) { ::Error("AddTaskESDFilter", "ESD filtering task needs the manager to have an ESD input handler."); return NULL; } // Check if AOD output handler exist. AliAODHandler *aod_h = (AliAODHandler*)mgr->GetOutputEventHandler(); if (!aod_h) { ::Error("AddTaskESDFilter", "ESD filtering task needs the manager to have an AOD output handler."); return NULL; } // Check if MC handler is connected in case kine filter requested AliMCEventHandler *mcH = (AliMCEventHandler*)mgr->GetMCtruthEventHandler(); if (!mcH && useKineFilter) { ::Error("AddTaskESDFilter", "No MC handler connected while kine filtering requested"); return NULL; } // Filtering of MC particles (decays conversions etc) // this task is also needed to set the MCEventHandler // to the AODHandler, this will not be needed when // AODHandler goes to ANALYSISalice AliAnalysisTaskMCParticleFilter *kinefilter = 0; if (useKineFilter) { kinefilter = new AliAnalysisTaskMCParticleFilter("Particle Kine Filter"); mgr->AddTask(kinefilter); } // Create the task, add it to the manager and configure it. //=========================================================================== // Barrel tracks filter AliAnalysisTaskESDfilter *esdfilter = new AliAnalysisTaskESDfilter("ESD Filter"); mgr->AddTask(esdfilter); // Muons AliAnalysisTaskESDMuonFilter *esdmuonfilter = new AliAnalysisTaskESDMuonFilter("ESD Muon Filter"); mgr->AddTask(esdmuonfilter); // Cuts on primary tracks AliESDtrackCuts* esdTrackCutsL = new AliESDtrackCuts("Standard Track Cuts", "ESD Track Cuts"); esdTrackCutsL->SetMinNClustersTPC(50); esdTrackCutsL->SetMaxChi2PerClusterTPC(3.5); esdTrackCutsL->SetRequireTPCRefit(kTRUE); esdTrackCutsL->SetMaxDCAToVertexXY(2.4); esdTrackCutsL->SetMaxDCAToVertexZ(3.2); esdTrackCutsL->SetDCAToVertex2D(kTRUE); esdTrackCutsL->SetRequireSigmaToVertex(kFALSE); esdTrackCutsL->SetAcceptKinkDaughters(kFALSE); // ITS stand-alone tracks AliESDtrackCuts* esdTrackCutsITSsa = new AliESDtrackCuts("ITS stand-alone Track Cuts", "ESD Track Cuts"); esdTrackCutsITSsa->SetRequireITSStandAlone(kTRUE); // Pixel OR necessary for the electrons AliESDtrackCuts *itsStrong = new AliESDtrackCuts("ITSorSPD", "pixel requirement for ITS"); itsStrong->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny); // PID for the electrons AliESDpidCuts *electronID = new AliESDpidCuts("Electrons", "Electron PID cuts"); electronID->SetTPCnSigmaCut(AliPID::kElectron, 3.); // Compose the filter AliAnalysisFilter* trackFilter = new AliAnalysisFilter("trackFilter"); // 1 trackFilter->AddCuts(esdTrackCutsL); // 2 trackFilter->AddCuts(esdTrackCutsITSsa); // 4 trackFilter->AddCuts(itsStrong); itsStrong->SetFilterMask(1); // AND with Standard track cuts // 8 trackFilter->AddCuts(electronID); electronID->SetFilterMask(4); // AND with Pixel Cuts // Filter with cuts on V0s AliESDv0Cuts* esdV0Cuts = new AliESDv0Cuts("Standard V0 Cuts pp", "ESD V0 Cuts"); esdV0Cuts->SetMinRadius(0.2); esdV0Cuts->SetMaxRadius(100); esdV0Cuts->SetMinDcaPosToVertex(0.05); esdV0Cuts->SetMinDcaNegToVertex(0.05); esdV0Cuts->SetMaxDcaV0Daughters(0.5); esdV0Cuts->SetMinCosinePointingAngle(0.99); AliAnalysisFilter* v0Filter = new AliAnalysisFilter("v0Filter"); v0Filter->AddCuts(esdV0Cuts); esdfilter->SetTrackFilter(trackFilter); esdfilter->SetV0Filter(v0Filter); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== mgr->ConnectInput (esdfilter, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (esdfilter, 0, mgr->GetCommonOutputContainer()); mgr->ConnectInput (esdmuonfilter, 0, mgr->GetCommonInputContainer()); if (useKineFilter) { mgr->ConnectInput (kinefilter, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (kinefilter, 0, mgr->GetCommonOutputContainer()); AliAnalysisDataContainer *coutputEx = mgr->CreateContainer("cFilterList", TList::Class(), AliAnalysisManager::kOutputContainer,"pyxsec_hists.root"); mgr->ConnectOutput (kinefilter, 1,coutputEx); } return esdfilter; } <commit_msg>Better cuts for V0 (Ana Marin)<commit_after>AliAnalysisTaskESDfilter *AddTaskESDFilter(Bool_t useKineFilter=kTRUE) { // Creates a filter task and adds it to the analysis manager. // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskESDFilter", "No analysis manager to connect to."); return NULL; } // This task requires an ESD input handler and an AOD output handler. // Check this using the analysis manager. //=============================================================================== TString type = mgr->GetInputEventHandler()->GetDataType(); if (!type.Contains("ESD")) { ::Error("AddTaskESDFilter", "ESD filtering task needs the manager to have an ESD input handler."); return NULL; } // Check if AOD output handler exist. AliAODHandler *aod_h = (AliAODHandler*)mgr->GetOutputEventHandler(); if (!aod_h) { ::Error("AddTaskESDFilter", "ESD filtering task needs the manager to have an AOD output handler."); return NULL; } // Check if MC handler is connected in case kine filter requested AliMCEventHandler *mcH = (AliMCEventHandler*)mgr->GetMCtruthEventHandler(); if (!mcH && useKineFilter) { ::Error("AddTaskESDFilter", "No MC handler connected while kine filtering requested"); return NULL; } // Filtering of MC particles (decays conversions etc) // this task is also needed to set the MCEventHandler // to the AODHandler, this will not be needed when // AODHandler goes to ANALYSISalice AliAnalysisTaskMCParticleFilter *kinefilter = 0; if (useKineFilter) { kinefilter = new AliAnalysisTaskMCParticleFilter("Particle Kine Filter"); mgr->AddTask(kinefilter); } // Create the task, add it to the manager and configure it. //=========================================================================== // Barrel tracks filter AliAnalysisTaskESDfilter *esdfilter = new AliAnalysisTaskESDfilter("ESD Filter"); mgr->AddTask(esdfilter); // Muons AliAnalysisTaskESDMuonFilter *esdmuonfilter = new AliAnalysisTaskESDMuonFilter("ESD Muon Filter"); mgr->AddTask(esdmuonfilter); // Cuts on primary tracks AliESDtrackCuts* esdTrackCutsL = new AliESDtrackCuts("Standard Track Cuts", "ESD Track Cuts"); esdTrackCutsL->SetMinNClustersTPC(50); esdTrackCutsL->SetMaxChi2PerClusterTPC(3.5); esdTrackCutsL->SetRequireTPCRefit(kTRUE); esdTrackCutsL->SetMaxDCAToVertexXY(2.4); esdTrackCutsL->SetMaxDCAToVertexZ(3.2); esdTrackCutsL->SetDCAToVertex2D(kTRUE); esdTrackCutsL->SetRequireSigmaToVertex(kFALSE); esdTrackCutsL->SetAcceptKinkDaughters(kFALSE); // ITS stand-alone tracks AliESDtrackCuts* esdTrackCutsITSsa = new AliESDtrackCuts("ITS stand-alone Track Cuts", "ESD Track Cuts"); esdTrackCutsITSsa->SetRequireITSStandAlone(kTRUE); // Pixel OR necessary for the electrons AliESDtrackCuts *itsStrong = new AliESDtrackCuts("ITSorSPD", "pixel requirement for ITS"); itsStrong->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny); // PID for the electrons AliESDpidCuts *electronID = new AliESDpidCuts("Electrons", "Electron PID cuts"); electronID->SetTPCnSigmaCut(AliPID::kElectron, 3.); // Compose the filter AliAnalysisFilter* trackFilter = new AliAnalysisFilter("trackFilter"); // 1 trackFilter->AddCuts(esdTrackCutsL); // 2 trackFilter->AddCuts(esdTrackCutsITSsa); // 4 trackFilter->AddCuts(itsStrong); itsStrong->SetFilterMask(1); // AND with Standard track cuts // 8 trackFilter->AddCuts(electronID); electronID->SetFilterMask(4); // AND with Pixel Cuts // Filter with cuts on V0s AliESDv0Cuts* esdV0Cuts = new AliESDv0Cuts("Standard V0 Cuts pp", "ESD V0 Cuts"); esdV0Cuts->SetMinRadius(0.2); esdV0Cuts->SetMaxRadius(200); esdV0Cuts->SetMinDcaPosToVertex(0.05); esdV0Cuts->SetMinDcaNegToVertex(0.05); esdV0Cuts->SetMaxDcaV0Daughters(1.5); esdV0Cuts->SetMinCosinePointingAngle(0.99); AliAnalysisFilter* v0Filter = new AliAnalysisFilter("v0Filter"); v0Filter->AddCuts(esdV0Cuts); esdfilter->SetTrackFilter(trackFilter); esdfilter->SetV0Filter(v0Filter); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== mgr->ConnectInput (esdfilter, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (esdfilter, 0, mgr->GetCommonOutputContainer()); mgr->ConnectInput (esdmuonfilter, 0, mgr->GetCommonInputContainer()); if (useKineFilter) { mgr->ConnectInput (kinefilter, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (kinefilter, 0, mgr->GetCommonOutputContainer()); AliAnalysisDataContainer *coutputEx = mgr->CreateContainer("cFilterList", TList::Class(), AliAnalysisManager::kOutputContainer,"pyxsec_hists.root"); mgr->ConnectOutput (kinefilter, 1,coutputEx); } return esdfilter; } <|endoftext|>
<commit_before>#include <TitleScene.hpp> #include <Scenes.hpp> using namespace uth; uth::Layer& TitleScene::getLayer(LayerId id) { return *m_layers[id]; } TitleScene::TitleScene() { uthEngine.GetWindow().GetCamera().SetSize(1280, 720); m_BGM = uthRS.LoadSound("Audio/Music/menu_theme.wav"); m_BGM->Play(); auto& window = uthEngine.GetWindow(); Creditsu = false; getLayer(LayerId::TitleBackground); getLayer(LayerId::Buttons); for (auto& e : m_layers) { AddChild(e.second = new Layer()); } auto TitleBgTex = uthRS.LoadTexture("Title/menu_bg.png"); TitleBgTex->SetSmooth(true); getLayer(LayerId::TitleBackground).AddChild(m_TitleBG = new GameObject()); m_TitleBG->AddComponent(new Sprite(TitleBgTex,"TitleBG")); m_TitleBG->transform.SetOrigin(uth::Origin::TopLeft); m_TitleBG->transform.SetPosition(window.GetCamera().GetPosition().x - window.GetCamera().GetSize().x / 2, window.GetCamera().GetPosition().y - window.GetCamera().GetSize().y / 2); //play-button uth::Texture* PlayTex = uthRS.LoadTexture("Title/Play.png"); PlayTex->SetSmooth(true); getLayer(LayerId::Buttons).AddChild(m_PlayB = new GameObject()); m_PlayB->AddComponent(new AnimatedSprite(PlayTex,2,2,1,0)); m_PlayB->transform.SetOrigin(uth::Origin::TopLeft); m_PlayB->transform.SetPosition(window.GetCamera().GetPosition().x - window.GetCamera().GetSize().x / 2 + 150, window.GetCamera().GetPosition().y - window.GetCamera().GetSize().y / 2 + 400); button = new Button(m_PlayB); //credits getLayer(LayerId::Buttons).AddChild(m_CreditsB = new GameObject()); uth::Texture* CredTex = uthRS.LoadTexture("Title/credits.png"); CredTex->SetSmooth(true); m_CreditsB->AddComponent(new AnimatedSprite(CredTex, 2, 2, 1, 0)); m_CreditsB->transform.SetOrigin(uth::Origin::TopLeft); m_CreditsB->transform.SetPosition(window.GetCamera().GetPosition().x - window.GetCamera().GetSize().x / 2 + 175, window.GetCamera().GetPosition().y - window.GetCamera().GetSize().y / 2 + 550); button2 = new Button(m_CreditsB); //options (ball) getLayer(LayerId::Buttons).AddChild(m_OptionsB = new GameObject()); uth::Texture* OptionsTex = uthRS.LoadTexture("Title/options.png"); OptionsTex->SetSmooth(true); m_OptionsB->AddComponent(new AnimatedSprite(OptionsTex, 2, 2, 1, 0)); m_OptionsB->transform.SetOrigin(uth::Origin::TopLeft); m_OptionsB->transform.SetPosition(window.GetCamera().GetPosition().x - window.GetCamera().GetSize().x / 2 + 630, window.GetCamera().GetPosition().y - window.GetCamera().GetSize().y / 2 + 600); button3 = new Button(m_OptionsB); getLayer(LayerId::Buttons).AddChild(m_CBG = new GameObject()); uth::Texture* CBGTex = uthRS.LoadTexture("UI/pause_BG.png"); CBGTex->SetSmooth(true); m_CBG->AddComponent(new Sprite(CBGTex, "CBG")); m_CBG->transform.SetOrigin(uth::Origin::TopLeft); m_CBG->transform.SetPosition(uthEngine.GetWindow().GetCamera().GetPosition().x - uthEngine.GetWindow().GetCamera().GetSize().x / 2 + 780, uthEngine.GetWindow().GetCamera().GetPosition().y - uthEngine.GetWindow().GetCamera().GetSize().y / 2 + 50); m_CBG->SetActive(false); getLayer(LayerId::Buttons).AddChild(m_EscB = new GameObject()); uth::Texture* EscTex = uthRS.LoadTexture("UI/esc.png"); OptionsTex->SetSmooth(true); m_EscB->AddComponent(new AnimatedSprite(EscTex, 2, 2, 1, 0)); m_EscB->transform.SetOrigin(uth::Origin::TopLeft); m_EscB->transform.SetPosition(uthEngine.GetWindow().GetCamera().GetPosition().x - uthEngine.GetWindow().GetCamera().GetSize().x / 2 + 1150, uthEngine.GetWindow().GetCamera().GetPosition().y - uthEngine.GetWindow().GetCamera().GetSize().y / 2 + 75); button4 = new Button(m_EscB); m_EscB->SetActive(false); } TitleScene::~TitleScene() {} void TitleScene::Update(float dt) { if (!Creditsu) { button->update(dt); button2->update(dt); button3->update(dt); m_CBG->SetActive(false); m_EscB->SetActive(false); if (button->IsPressedS() ) { uthSceneM.GoToScene(GAME); m_BGM->Stop(); } if (button2->IsPressedS() ) { Creditsu = true; } } else { m_CBG->SetActive(true); m_EscB->SetActive(true); button4->update(dt); if (button4->IsPressedS()) { Creditsu = false; } } } bool TitleScene::Init() { return true; } bool TitleScene::DeInit() { m_BGM = nullptr; return true; } <commit_msg>title BGM loops<commit_after>#include <TitleScene.hpp> #include <Scenes.hpp> using namespace uth; uth::Layer& TitleScene::getLayer(LayerId id) { return *m_layers[id]; } TitleScene::TitleScene() { uthEngine.GetWindow().GetCamera().SetSize(1280, 720); m_BGM = uthRS.LoadSound("Audio/Music/menu_theme.wav"); m_BGM->Play(); m_BGM->Loop(true); auto& window = uthEngine.GetWindow(); Creditsu = false; getLayer(LayerId::TitleBackground); getLayer(LayerId::Buttons); for (auto& e : m_layers) { AddChild(e.second = new Layer()); } auto TitleBgTex = uthRS.LoadTexture("Title/menu_bg.png"); TitleBgTex->SetSmooth(true); getLayer(LayerId::TitleBackground).AddChild(m_TitleBG = new GameObject()); m_TitleBG->AddComponent(new Sprite(TitleBgTex,"TitleBG")); m_TitleBG->transform.SetOrigin(uth::Origin::TopLeft); m_TitleBG->transform.SetPosition(window.GetCamera().GetPosition().x - window.GetCamera().GetSize().x / 2, window.GetCamera().GetPosition().y - window.GetCamera().GetSize().y / 2); //play-button uth::Texture* PlayTex = uthRS.LoadTexture("Title/Play.png"); PlayTex->SetSmooth(true); getLayer(LayerId::Buttons).AddChild(m_PlayB = new GameObject()); m_PlayB->AddComponent(new AnimatedSprite(PlayTex,2,2,1,0)); m_PlayB->transform.SetOrigin(uth::Origin::TopLeft); m_PlayB->transform.SetPosition(window.GetCamera().GetPosition().x - window.GetCamera().GetSize().x / 2 + 150, window.GetCamera().GetPosition().y - window.GetCamera().GetSize().y / 2 + 400); button = new Button(m_PlayB); //credits getLayer(LayerId::Buttons).AddChild(m_CreditsB = new GameObject()); uth::Texture* CredTex = uthRS.LoadTexture("Title/credits.png"); CredTex->SetSmooth(true); m_CreditsB->AddComponent(new AnimatedSprite(CredTex, 2, 2, 1, 0)); m_CreditsB->transform.SetOrigin(uth::Origin::TopLeft); m_CreditsB->transform.SetPosition(window.GetCamera().GetPosition().x - window.GetCamera().GetSize().x / 2 + 175, window.GetCamera().GetPosition().y - window.GetCamera().GetSize().y / 2 + 550); button2 = new Button(m_CreditsB); //options (ball) getLayer(LayerId::Buttons).AddChild(m_OptionsB = new GameObject()); uth::Texture* OptionsTex = uthRS.LoadTexture("Title/options.png"); OptionsTex->SetSmooth(true); m_OptionsB->AddComponent(new AnimatedSprite(OptionsTex, 2, 2, 1, 0)); m_OptionsB->transform.SetOrigin(uth::Origin::TopLeft); m_OptionsB->transform.SetPosition(window.GetCamera().GetPosition().x - window.GetCamera().GetSize().x / 2 + 630, window.GetCamera().GetPosition().y - window.GetCamera().GetSize().y / 2 + 600); button3 = new Button(m_OptionsB); getLayer(LayerId::Buttons).AddChild(m_CBG = new GameObject()); uth::Texture* CBGTex = uthRS.LoadTexture("UI/pause_BG.png"); CBGTex->SetSmooth(true); m_CBG->AddComponent(new Sprite(CBGTex, "CBG")); m_CBG->transform.SetOrigin(uth::Origin::TopLeft); m_CBG->transform.SetPosition(uthEngine.GetWindow().GetCamera().GetPosition().x - uthEngine.GetWindow().GetCamera().GetSize().x / 2 + 780, uthEngine.GetWindow().GetCamera().GetPosition().y - uthEngine.GetWindow().GetCamera().GetSize().y / 2 + 50); m_CBG->SetActive(false); getLayer(LayerId::Buttons).AddChild(m_EscB = new GameObject()); uth::Texture* EscTex = uthRS.LoadTexture("UI/esc.png"); OptionsTex->SetSmooth(true); m_EscB->AddComponent(new AnimatedSprite(EscTex, 2, 2, 1, 0)); m_EscB->transform.SetOrigin(uth::Origin::TopLeft); m_EscB->transform.SetPosition(uthEngine.GetWindow().GetCamera().GetPosition().x - uthEngine.GetWindow().GetCamera().GetSize().x / 2 + 1150, uthEngine.GetWindow().GetCamera().GetPosition().y - uthEngine.GetWindow().GetCamera().GetSize().y / 2 + 75); button4 = new Button(m_EscB); m_EscB->SetActive(false); } TitleScene::~TitleScene() {} void TitleScene::Update(float dt) { if (!Creditsu) { button->update(dt); button2->update(dt); button3->update(dt); m_CBG->SetActive(false); m_EscB->SetActive(false); if (button->IsPressedS() ) { uthSceneM.GoToScene(GAME); m_BGM->Stop(); } if (button2->IsPressedS() ) { Creditsu = true; } } else { m_CBG->SetActive(true); m_EscB->SetActive(true); button4->update(dt); if (button4->IsPressedS()) { Creditsu = false; } } } bool TitleScene::Init() { return true; } bool TitleScene::DeInit() { m_BGM = nullptr; return true; } <|endoftext|>
<commit_before>/*////////////////////////////////////////////////////////////////// //// SKIRT -- an advanced radiative transfer code //// //// © Astronomical Observatory, Ghent University //// ///////////////////////////////////////////////////////////////// */ #include <cmath> #include "PerspectiveInstrument.hpp" #include "FatalError.hpp" #include "FilePaths.hpp" #include "FITSInOut.hpp" #include "LockFree.hpp" #include "Log.hpp" #include "PhotonPackage.hpp" #include "Units.hpp" #include "WavelengthGrid.hpp" using namespace std; //////////////////////////////////////////////////////////////////// namespace { double norm (double x, double y, double z) { return sqrt(x*x + y*y + z*z); } } //////////////////////////////////////////////////////////////////// PerspectiveInstrument::PerspectiveInstrument() : _Nx(0), _Ny(0), _Sx(0), _Vx(0), _Vy(0), _Vz(0), _Cx(0), _Cy(0), _Cz(0), _Ux(0), _Uy(0), _Uz(0), _Fe(0) { } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setupSelfBefore() { Instrument::setupSelfBefore(); // verify attribute values if (_Nx <= 0 || _Ny <= 0) throw FATALERROR("Number of pixels was not set"); if (_Sx <= 0) throw FATALERROR("Viewport width was not set"); if (_Ux == 0 && _Uy == 0 && _Uz == 0) throw FATALERROR("Upwards direction was not set"); if (_Fe <= 0) throw FATALERROR("Focal length was not set"); // unit vector in direction from crosshair position to viewport origin double G = norm(_Vx - _Cx, _Vy - _Cy, _Vz - _Cz); if (G < 1e-20) throw FATALERROR("Crosshair is too close to viewport origin"); double a = (_Vx - _Cx) / G; double b = (_Vy - _Cy) / G; double c = (_Vz - _Cz) / G; // pixel width and height (assuming square pixels) _s = _Sx/_Nx; // eye position _Ex = _Vx + _Fe * a; _Ey = _Vy + _Fe * b; _Ez = _Vz + _Fe * c; // the perspective transformation // from world to eye coordinates _transform.translate(-_Ex, -_Ey, -_Ez); double v = sqrt(b*b+c*c); if (v > 0.3) { _transform.rotateX(c/v, -b/v); _transform.rotateY(v, -a); double k = (b*b+c*c)*_Ux - a*b*_Uy - a*c*_Uz; double l = c*_Uy - b*_Uz; double u = sqrt(k*k+l*l); _transform.rotateZ(l/u, -k/u); } else { v = sqrt(a*a+c*c); _transform.rotateY(c/v, -a/v); _transform.rotateX(v, -b); double k = c*_Ux - a*_Uz; double l = (a*a+c*c)*_Uy - a*b*_Ux - b*c*_Uz; double u = sqrt(k*k+l*l); _transform.rotateZ(l/u, -k/u); } _transform.scale(1., 1., -1.); // from eye to viewport coordinates _transform.perspectiveZ(_Fe); // from viewport to pixel coordinates _transform.scale(1./_s, 1./_s, 1.); _transform.translate(_Nx/2., _Ny/2., 0); // the data cube int Nlambda = find<WavelengthGrid>()->Nlambda(); _ftotv.resize(Nlambda*_Nx*_Ny); } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setPixelsX(int value) { _Nx = value; } //////////////////////////////////////////////////////////////////// int PerspectiveInstrument::pixelsX() const { return _Nx; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setPixelsY(int value) { _Ny = value; } //////////////////////////////////////////////////////////////////// int PerspectiveInstrument::pixelsY() const { return _Ny; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setWidth(double value) { _Sx = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::width() const { return _Sx; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setViewX(double value) { _Vx = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::viewX() const { return _Vx; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setViewY(double value) { _Vy = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::viewY() const { return _Vy; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setViewZ(double value) { _Vz = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::viewZ() const { return _Vz; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setCrossX(double value) { _Cx = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::crossX() const { return _Cx; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setCrossY(double value) { _Cy = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::crossY() const { return _Cy; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setCrossZ(double value) { _Cz = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::crossZ() const { return _Cz; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setUpX(double value) { _Ux = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::upX() const { return _Ux; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setUpY(double value) { _Uy = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::upY() const { return _Uy; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setUpZ(double value) { _Uz = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::upZ() const { return _Uz; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setFocal(double value) { _Fe = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::focal() const { return _Fe; } //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// Direction PerspectiveInstrument::bfkobs(const Position& bfr) const { // distance from launch to eye double Px, Py, Pz; bfr.cartesian(Px, Py, Pz); double D = norm(_Ex - Px, _Ey - Py, _Ez - Pz); // if the distance is very small, return something silly - the photon package is behind the viewport anyway if (D < 1e-20) return Direction(); // otherwise return a unit vector in the direction from launch to eye return Direction((_Ex - Px)/D, (_Ey - Py)/D, (_Ez - Pz)/D); } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::detect(PhotonPackage* pp) { // get the position double x, y, z; pp->position().cartesian(x,y,z); // transform from world to pixel coordinates double xp, yp, zp, wp; _transform.transform(x, y, z, 1., xp, yp, zp, wp); int i = xp/wp; int j = yp/wp; // ignore photon packages arriving outside the viewport, originating from behind the viewport, // or originating from very close to the viewport if (i>=0 && i<_Nx && j>=0 && j<_Ny && zp > _s/10.) { double d = zp; // determine the photon package's luminosity, attenuated for the absorption along its path to the instrument double taupath = opticalDepth(pp,d); double L = pp->luminosity() * exp(-taupath); // adjust the luminosity for the distance from the launch position to the instrument double r = _s / (2.*d); double rar = r / atan(r); L *= rar*rar; // add the adjusted luminosity to the appropriate pixel in the data cube int ell = pp->ell(); int m = i + _Nx*j + _Nx*_Ny*ell; LockFree::add(_ftotv[m], L); } } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::write() { Units* units = find<Units>(); WavelengthGrid* lambdagrid = find<WavelengthGrid>(); int Nlambda = find<WavelengthGrid>()->Nlambda(); // multiply each sample by lambda/dlamdba and by the constant factor 1/(4 pi s^2) // to obtain the surface brightness and convert to output units (such as W/m2/arcsec2) double front = 1. / (4.*M_PI*_s*_s); for (int ell=0; ell<Nlambda; ell++) { double lambda = lambdagrid->lambda(ell); double dlambda = lambdagrid->dlambda(ell); for (int i=0; i<_Nx; i++) { for (int j=0; j<_Ny; j++) { int m = i + _Nx*j + _Nx*_Ny*ell; _ftotv[m] = units->osurfacebrightness(lambda, _ftotv[m]*front/dlambda); } } } // write a FITS file containing the data cube QString filename = find<FilePaths>()->output(_instrumentname + "_total.fits"); find<Log>()->info("Writing total flux to FITS file " + filename + "..."); FITSInOut::write(filename, _ftotv, _Nx, _Ny, Nlambda, units->olength(_s), units->olength(_s), units->usurfacebrightness(), units->ulength()); } //////////////////////////////////////////////////////////////////// <commit_msg>Fixed a bug where a PerspectiveInstrument could not be used when running with MPI<commit_after>/*////////////////////////////////////////////////////////////////// //// SKIRT -- an advanced radiative transfer code //// //// © Astronomical Observatory, Ghent University //// ///////////////////////////////////////////////////////////////// */ #include <cmath> #include "PerspectiveInstrument.hpp" #include "FatalError.hpp" #include "FilePaths.hpp" #include "FITSInOut.hpp" #include "LockFree.hpp" #include "Log.hpp" #include "PeerToPeerCommunicator.hpp" #include "PhotonPackage.hpp" #include "Units.hpp" #include "WavelengthGrid.hpp" using namespace std; //////////////////////////////////////////////////////////////////// namespace { double norm (double x, double y, double z) { return sqrt(x*x + y*y + z*z); } } //////////////////////////////////////////////////////////////////// PerspectiveInstrument::PerspectiveInstrument() : _Nx(0), _Ny(0), _Sx(0), _Vx(0), _Vy(0), _Vz(0), _Cx(0), _Cy(0), _Cz(0), _Ux(0), _Uy(0), _Uz(0), _Fe(0) { } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setupSelfBefore() { Instrument::setupSelfBefore(); // verify attribute values if (_Nx <= 0 || _Ny <= 0) throw FATALERROR("Number of pixels was not set"); if (_Sx <= 0) throw FATALERROR("Viewport width was not set"); if (_Ux == 0 && _Uy == 0 && _Uz == 0) throw FATALERROR("Upwards direction was not set"); if (_Fe <= 0) throw FATALERROR("Focal length was not set"); // unit vector in direction from crosshair position to viewport origin double G = norm(_Vx - _Cx, _Vy - _Cy, _Vz - _Cz); if (G < 1e-20) throw FATALERROR("Crosshair is too close to viewport origin"); double a = (_Vx - _Cx) / G; double b = (_Vy - _Cy) / G; double c = (_Vz - _Cz) / G; // pixel width and height (assuming square pixels) _s = _Sx/_Nx; // eye position _Ex = _Vx + _Fe * a; _Ey = _Vy + _Fe * b; _Ez = _Vz + _Fe * c; // the perspective transformation // from world to eye coordinates _transform.translate(-_Ex, -_Ey, -_Ez); double v = sqrt(b*b+c*c); if (v > 0.3) { _transform.rotateX(c/v, -b/v); _transform.rotateY(v, -a); double k = (b*b+c*c)*_Ux - a*b*_Uy - a*c*_Uz; double l = c*_Uy - b*_Uz; double u = sqrt(k*k+l*l); _transform.rotateZ(l/u, -k/u); } else { v = sqrt(a*a+c*c); _transform.rotateY(c/v, -a/v); _transform.rotateX(v, -b); double k = c*_Ux - a*_Uz; double l = (a*a+c*c)*_Uy - a*b*_Ux - b*c*_Uz; double u = sqrt(k*k+l*l); _transform.rotateZ(l/u, -k/u); } _transform.scale(1., 1., -1.); // from eye to viewport coordinates _transform.perspectiveZ(_Fe); // from viewport to pixel coordinates _transform.scale(1./_s, 1./_s, 1.); _transform.translate(_Nx/2., _Ny/2., 0); // the data cube int Nlambda = find<WavelengthGrid>()->Nlambda(); _ftotv.resize(Nlambda*_Nx*_Ny); } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setPixelsX(int value) { _Nx = value; } //////////////////////////////////////////////////////////////////// int PerspectiveInstrument::pixelsX() const { return _Nx; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setPixelsY(int value) { _Ny = value; } //////////////////////////////////////////////////////////////////// int PerspectiveInstrument::pixelsY() const { return _Ny; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setWidth(double value) { _Sx = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::width() const { return _Sx; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setViewX(double value) { _Vx = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::viewX() const { return _Vx; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setViewY(double value) { _Vy = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::viewY() const { return _Vy; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setViewZ(double value) { _Vz = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::viewZ() const { return _Vz; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setCrossX(double value) { _Cx = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::crossX() const { return _Cx; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setCrossY(double value) { _Cy = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::crossY() const { return _Cy; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setCrossZ(double value) { _Cz = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::crossZ() const { return _Cz; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setUpX(double value) { _Ux = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::upX() const { return _Ux; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setUpY(double value) { _Uy = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::upY() const { return _Uy; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setUpZ(double value) { _Uz = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::upZ() const { return _Uz; } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::setFocal(double value) { _Fe = value; } //////////////////////////////////////////////////////////////////// double PerspectiveInstrument::focal() const { return _Fe; } //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// Direction PerspectiveInstrument::bfkobs(const Position& bfr) const { // distance from launch to eye double Px, Py, Pz; bfr.cartesian(Px, Py, Pz); double D = norm(_Ex - Px, _Ey - Py, _Ez - Pz); // if the distance is very small, return something silly - the photon package is behind the viewport anyway if (D < 1e-20) return Direction(); // otherwise return a unit vector in the direction from launch to eye return Direction((_Ex - Px)/D, (_Ey - Py)/D, (_Ez - Pz)/D); } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::detect(PhotonPackage* pp) { // get the position double x, y, z; pp->position().cartesian(x,y,z); // transform from world to pixel coordinates double xp, yp, zp, wp; _transform.transform(x, y, z, 1., xp, yp, zp, wp); int i = xp/wp; int j = yp/wp; // ignore photon packages arriving outside the viewport, originating from behind the viewport, // or originating from very close to the viewport if (i>=0 && i<_Nx && j>=0 && j<_Ny && zp > _s/10.) { double d = zp; // determine the photon package's luminosity, attenuated for the absorption along its path to the instrument double taupath = opticalDepth(pp,d); double L = pp->luminosity() * exp(-taupath); // adjust the luminosity for the distance from the launch position to the instrument double r = _s / (2.*d); double rar = r / atan(r); L *= rar*rar; // add the adjusted luminosity to the appropriate pixel in the data cube int ell = pp->ell(); int m = i + _Nx*j + _Nx*_Ny*ell; LockFree::add(_ftotv[m], L); } } //////////////////////////////////////////////////////////////////// void PerspectiveInstrument::write() { Units* units = find<Units>(); WavelengthGrid* lambdagrid = find<WavelengthGrid>(); int Nlambda = find<WavelengthGrid>()->Nlambda(); // Put the data cube in a list of f-array pointers, as the sumResults function requires QList< Array* > farrays; farrays << &_ftotv; // Sum the flux arrays element-wise across the different processes sumResults(farrays); // From here on, only the root process should continue PeerToPeerCommunicator* comm = find<PeerToPeerCommunicator>(); if (comm->rank()) return; // multiply each sample by lambda/dlamdba and by the constant factor 1/(4 pi s^2) // to obtain the surface brightness and convert to output units (such as W/m2/arcsec2) double front = 1. / (4.*M_PI*_s*_s); for (int ell=0; ell<Nlambda; ell++) { double lambda = lambdagrid->lambda(ell); double dlambda = lambdagrid->dlambda(ell); for (int i=0; i<_Nx; i++) { for (int j=0; j<_Ny; j++) { int m = i + _Nx*j + _Nx*_Ny*ell; _ftotv[m] = units->osurfacebrightness(lambda, _ftotv[m]*front/dlambda); } } } // write a FITS file containing the data cube QString filename = find<FilePaths>()->output(_instrumentname + "_total.fits"); find<Log>()->info("Writing total flux to FITS file " + filename + "..."); FITSInOut::write(filename, _ftotv, _Nx, _Ny, Nlambda, units->olength(_s), units->olength(_s), units->usurfacebrightness(), units->ulength()); } //////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2008-2013 Imperial College London * Copyright 2008-2013 Daniel Rueckert, Julia Schnabel * Copyright 2013-2015 Andreas Schuh * * 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 "mirtk/Common.h" #include "mirtk/Options.h" #include "mirtk/IOConfig.h" #include "mirtk/BaseImage.h" using namespace mirtk; // ============================================================================= // Help // ============================================================================= // ----------------------------------------------------------------------------- void PrintHelp(const char *name) { cout << "\n"; cout << "Usage: " << name << " <input>... <output> [options]\n"; cout << " " << name << " <input>... -output <output> [options]\n"; cout << " " << name << " [options]\n"; cout << "\n"; cout << "Description:\n"; cout << " Concatenate two or more either 2D images to form a 3D volume,\n"; cout << " or 3D volumes to form a 3D+t temporal sequence. All input images\n"; cout << " must have the same image attributes, except in either the third (2D)\n"; cout << " or the third and fourth (3D) image dimension.\n"; cout << "\n"; cout << "Optional arguments:\n"; cout << " -output <output> Output image file. Last positional argument if option missing.\n"; cout << " -image <input> Add one input image. Option can be given multiple times.\n"; cout << " -images <input>... Add one or more input images. Option can be given multiple times.\n"; cout << " -sort [on|off] Automatically determine correct order of input images\n"; cout << " based on the distance along the third or fourth image axis.\n"; cout << " -nosort Disable sorting of input images, same as :option:`-sort` off. (default)\n"; cout << " -start <float> Position of first slice/frame of output volume/sequence.\n"; cout << " -spacing <float> Slice/Temporal spacing of output volume/sequence.\n"; PrintStandardOptions(cout); cout << "\n"; } // ============================================================================= // Auxiliaries // ============================================================================= // ----------------------------------------------------------------------------- bool CheckOrientation(const ImageAttributes &a, const ImageAttributes &b) { if ((a._xaxis[0] * b._xaxis[0] + a._xaxis[1] * b._xaxis[1] + a._xaxis[2] * b._xaxis[2] - 1.0) > .001) return false; if ((a._yaxis[0] * b._yaxis[0] + a._yaxis[1] * b._yaxis[1] + a._yaxis[2] * b._yaxis[2] - 1.0) > .001) return false; if ((a._zaxis[0] * b._zaxis[0] + a._zaxis[1] * b._zaxis[1] + a._zaxis[2] * b._zaxis[2] - 1.0) > .001) return false; return true; } // ============================================================================= // Main // ============================================================================= // ----------------------------------------------------------------------------- int main(int argc, char *argv[]) { // Parse arguments REQUIRES_POSARGS(0); Array<const char *> input_names; for (int i = 1; i <= NUM_POSARGS; ++i) { input_names.push_back(POSARG(i)); } const char *output_name = nullptr; bool sort_input = false; double spacing = numeric_limits<double>::quiet_NaN(); double start = numeric_limits<double>::quiet_NaN(); for (ALL_OPTIONS) { if (OPTION("-image")) input_names.push_back(ARGUMENT); else if (OPTION("-images")) { do { input_names.push_back(ARGUMENT); } while (HAS_ARGUMENT); } else if (OPTION("-output")) { output_name = ARGUMENT; } else if (OPTION("-sort")) { if (HAS_ARGUMENT) PARSE_ARGUMENT(sort_input); else sort_input = true; } else if (OPTION("-nosort")) sort_input = false; else if (OPTION("-spacing")) PARSE_ARGUMENT(spacing); else if (OPTION("-start")) PARSE_ARGUMENT(start); else HANDLE_COMMON_OR_UNKNOWN_OPTION(); } if (!output_name) { if (input_names.empty()) { FatalError("No input images and -output file specified!"); } output_name = input_names.back(); input_names.pop_back(); } const int n = static_cast<int>(input_names.size()); if (n < 2) FatalError("Not enough input images given!"); InitializeIOLibrary(); // Get attributes of first input image UniquePtr<BaseImage> ref(BaseImage::New(input_names[0])); if (ref->T() > 1) { FatalError("Input images must be either 2D (nz == 1) or 3D (nz == 1 and nt == 1)!"); } const bool twod = (ref->Z() == 1); // Sort input images // // Note: Images are not first read all at once into memory to // not be limited by the amount of memory we have available. // We better read in the images twice from disk if necessary. Array<int> pos(n); for (int i = 0; i < n; ++i) pos[i] = i; if (sort_input) { if (verbose) cout << "Sorting input images...", cout.flush(); // Compute distance to axis origin Point p; Array<double> origin(n); if (twod) { p = ref->GetOrigin(); ref->WorldToImage(p); origin[0] = p._z; } else { origin[0] = ref->GetTOrigin(); } for (int i = 1; i < n; ++i) { UniquePtr<BaseImage> image(BaseImage::New(input_names[i])); p = image->GetOrigin(); if (twod) { Point p = image->GetOrigin(); ref->WorldToImage(p); origin[i] = p._z; } else { origin[i] = image->GetTOrigin(); } } // Determine order of images sorted by ascending distance value sort(pos.begin(), pos.end(), SortIndicesOfArray<double>(origin)); if (pos[0] != 0) ref.reset(BaseImage::New(input_names[pos[0]])); if (verbose) cout << " done\n"; } // Create output image if (verbose) { cout << "Making "; if (twod) cout << "volume"; else cout << "sequence"; cout << " from " << n << " input images..."; } ImageAttributes out_attr = ref->Attributes(); if (twod) out_attr._z = n; // spacing and origin set later below else out_attr._t = n; UniquePtr<BaseImage> output(BaseImage::New(ref->GetDataType())); output->Initialize(out_attr); // Concatenate images double avg_spacing = .0; double min_zorigin = numeric_limits<double>::max(); if (twod) { for (int j = 0; j < out_attr._y; ++j) for (int i = 0; i < out_attr._x; ++i) { output->PutAsDouble(i, j, 0, 0, ref->GetAsDouble(i, j)); } for (int k = 1; k < n; ++k) { UniquePtr<BaseImage> image(BaseImage::New(input_names[pos[k]])); if (image->Z() != 1 || image->T() != 1) { if (verbose) cout << " failed" << endl; FatalError("Input image " << k+1 << " is not 2D!"); } if (image->X() != ref->X() || image->Y() != ref->Y()) { if (verbose) cout << " failed" << endl; FatalError("Input image " << k+1 << " has differing number of voxels!"); } if (!fequal(image->GetXSize(), ref->GetXSize()) || !fequal(image->GetYSize(), ref->GetYSize())) { if (verbose) cout << " failed" << endl; FatalError("Input image " << k+1 << " has differing voxel size!"); } if (!fequal(image->GetTSize(), ref->GetTSize())) { Warning("Input image " << k+1 << " has differing temporal spacing."); } if (!CheckOrientation(image->Attributes(), ref->Attributes())) { if (verbose) cout << " failed" << endl; FatalError("Input image " << k+1 << " has different orientation!"); } for (int j = 0; j < out_attr._y; ++j) for (int i = 0; i < out_attr._x; ++i) { output->PutAsDouble(i, j, k, 0, image->GetAsDouble(i, j)); } min_zorigin = min(min_zorigin, image->GetOrigin()._z); avg_spacing += image->GetZSize(); } } else { for (int k = 0; k < out_attr._z; ++k) for (int j = 0; j < out_attr._y; ++j) for (int i = 0; i < out_attr._x; ++i) { output->PutAsDouble(i, j, k, 0, ref->GetAsDouble(i, j, k)); } for (int l = 1; l < n; ++l) { UniquePtr<BaseImage> image(BaseImage::New(input_names[pos[l]])); if (image->T() != 1) { if (verbose) cout << " failed" << endl; FatalError("Input image " << l+1 << " is not 3D!"); } if (image->X() != ref->X() || image->Y() != ref->Y() || image->Z() != ref->Z()) { if (verbose) cout << " failed" << endl; FatalError("Input image " << l+1 << " has differing number of voxels!"); } if (!fequal(image->GetXSize(), ref->GetXSize()) || !fequal(image->GetYSize(), ref->GetYSize()) || !fequal(image->GetZSize(), ref->GetZSize())) { if (verbose) cout << " failed" << endl; FatalError("Input image " << l+1 << " has differing voxel size!"); } if (!CheckOrientation(image->Attributes(), ref->Attributes())) { if (verbose) cout << " failed" << endl; FatalError("Input image " << l+1 << " has different orientation!"); } for (int k = 0; k < out_attr._z; ++k) for (int j = 0; j < out_attr._y; ++j) for (int i = 0; i < out_attr._x; ++i) { output->PutAsDouble(i, j, k, l, image->GetAsDouble(i, j, k)); } avg_spacing += image->GetZSize(); } } // Set output spacing to average of input images by default if (IsNaN(spacing)) spacing = avg_spacing; if (twod) { if (spacing < .0) { // must be positive out_attr._zaxis[0] *= -1.0; out_attr._zaxis[1] *= -1.0; out_attr._zaxis[2] *= -1.0; spacing *= -1.0; } double dx, dy, dz; output->GetPixelSize(dx, dy, dz); output->PutPixelSize(dx, dy, spacing); } else { output->PutTSize(spacing); // can be negative } // Set output origin if (twod) { if (IsNaN(start)) start = min_zorigin; Point origin = output->GetOrigin(); origin._z = start; // Move to center of image stack, i.e. translate along z axis double s = .5 * (output->Z() * output->GetZSize()); origin._x += s * output->Attributes()._zaxis[0]; origin._y += s * output->Attributes()._zaxis[1]; origin._z += s * output->Attributes()._zaxis[2]; output->PutOrigin(origin); } else { if (!IsNaN(start)) out_attr._torigin = start; // else torigin is time of first (sorted) input volume } if (verbose) cout << " done" << endl; // Write output image if (verbose) cout << "Writing concatenated images to " << output_name << "..."; output->Write(output_name); if (verbose) cout << " done" << endl; return 0; } <commit_msg>fix: Use new IncreasingOrder helper in combine-images [Applications]<commit_after>/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2008-2013 Imperial College London * Copyright 2008-2013 Daniel Rueckert, Julia Schnabel * Copyright 2013-2015 Andreas Schuh * * 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 "mirtk/Common.h" #include "mirtk/Options.h" #include "mirtk/IOConfig.h" #include "mirtk/BaseImage.h" using namespace mirtk; // ============================================================================= // Help // ============================================================================= // ----------------------------------------------------------------------------- void PrintHelp(const char *name) { cout << "\n"; cout << "Usage: " << name << " <input>... <output> [options]\n"; cout << " " << name << " <input>... -output <output> [options]\n"; cout << " " << name << " [options]\n"; cout << "\n"; cout << "Description:\n"; cout << " Concatenate two or more either 2D images to form a 3D volume,\n"; cout << " or 3D volumes to form a 3D+t temporal sequence. All input images\n"; cout << " must have the same image attributes, except in either the third (2D)\n"; cout << " or the third and fourth (3D) image dimension.\n"; cout << "\n"; cout << "Optional arguments:\n"; cout << " -output <output> Output image file. Last positional argument if option missing.\n"; cout << " -image <input> Add one input image. Option can be given multiple times.\n"; cout << " -images <input>... Add one or more input images. Option can be given multiple times.\n"; cout << " -sort [on|off] Automatically determine correct order of input images\n"; cout << " based on the distance along the third or fourth image axis.\n"; cout << " -nosort Disable sorting of input images, same as :option:`-sort` off. (default)\n"; cout << " -start <float> Position of first slice/frame of output volume/sequence.\n"; cout << " -spacing <float> Slice/Temporal spacing of output volume/sequence.\n"; PrintStandardOptions(cout); cout << "\n"; } // ============================================================================= // Auxiliaries // ============================================================================= // ----------------------------------------------------------------------------- bool CheckOrientation(const ImageAttributes &a, const ImageAttributes &b) { if ((a._xaxis[0] * b._xaxis[0] + a._xaxis[1] * b._xaxis[1] + a._xaxis[2] * b._xaxis[2] - 1.0) > .001) return false; if ((a._yaxis[0] * b._yaxis[0] + a._yaxis[1] * b._yaxis[1] + a._yaxis[2] * b._yaxis[2] - 1.0) > .001) return false; if ((a._zaxis[0] * b._zaxis[0] + a._zaxis[1] * b._zaxis[1] + a._zaxis[2] * b._zaxis[2] - 1.0) > .001) return false; return true; } // ============================================================================= // Main // ============================================================================= // ----------------------------------------------------------------------------- int main(int argc, char *argv[]) { // Parse arguments REQUIRES_POSARGS(0); Array<const char *> input_names; for (int i = 1; i <= NUM_POSARGS; ++i) { input_names.push_back(POSARG(i)); } const char *output_name = nullptr; bool sort_input = false; double spacing = numeric_limits<double>::quiet_NaN(); double start = numeric_limits<double>::quiet_NaN(); for (ALL_OPTIONS) { if (OPTION("-image")) input_names.push_back(ARGUMENT); else if (OPTION("-images")) { do { input_names.push_back(ARGUMENT); } while (HAS_ARGUMENT); } else if (OPTION("-output")) { output_name = ARGUMENT; } else if (OPTION("-sort")) { if (HAS_ARGUMENT) PARSE_ARGUMENT(sort_input); else sort_input = true; } else if (OPTION("-nosort")) sort_input = false; else if (OPTION("-spacing")) PARSE_ARGUMENT(spacing); else if (OPTION("-start")) PARSE_ARGUMENT(start); else HANDLE_COMMON_OR_UNKNOWN_OPTION(); } if (!output_name) { if (input_names.empty()) { FatalError("No input images and -output file specified!"); } output_name = input_names.back(); input_names.pop_back(); } const int n = static_cast<int>(input_names.size()); if (n < 2) FatalError("Not enough input images given!"); InitializeIOLibrary(); // Get attributes of first input image UniquePtr<BaseImage> ref(BaseImage::New(input_names[0])); if (ref->T() > 1) { FatalError("Input images must be either 2D (nz == 1) or 3D (nz == 1 and nt == 1)!"); } const bool twod = (ref->Z() == 1); // Sort input images // // Note: Images are not first read all at once into memory to // not be limited by the amount of memory we have available. // We better read in the images twice from disk if necessary. Array<int> pos(n); for (int i = 0; i < n; ++i) pos[i] = i; if (sort_input) { if (verbose) cout << "Sorting input images...", cout.flush(); // Compute distance to axis origin Point p; Array<double> origin(n); if (twod) { p = ref->GetOrigin(); ref->WorldToImage(p); origin[0] = p._z; } else { origin[0] = ref->GetTOrigin(); } for (int i = 1; i < n; ++i) { UniquePtr<BaseImage> image(BaseImage::New(input_names[i])); p = image->GetOrigin(); if (twod) { Point p = image->GetOrigin(); ref->WorldToImage(p); origin[i] = p._z; } else { origin[i] = image->GetTOrigin(); } } // Determine order of images sorted by ascending distance value pos = IncreasingOrder(origin); if (pos[0] != 0) ref.reset(BaseImage::New(input_names[pos[0]])); if (verbose) cout << " done\n"; } // Create output image if (verbose) { cout << "Making "; if (twod) cout << "volume"; else cout << "sequence"; cout << " from " << n << " input images..."; } ImageAttributes out_attr = ref->Attributes(); if (twod) out_attr._z = n; // spacing and origin set later below else out_attr._t = n; UniquePtr<BaseImage> output(BaseImage::New(ref->GetDataType())); output->Initialize(out_attr); // Concatenate images double avg_spacing = .0; double min_zorigin = numeric_limits<double>::max(); if (twod) { for (int j = 0; j < out_attr._y; ++j) for (int i = 0; i < out_attr._x; ++i) { output->PutAsDouble(i, j, 0, 0, ref->GetAsDouble(i, j)); } for (int k = 1; k < n; ++k) { UniquePtr<BaseImage> image(BaseImage::New(input_names[pos[k]])); if (image->Z() != 1 || image->T() != 1) { if (verbose) cout << " failed" << endl; FatalError("Input image " << k+1 << " is not 2D!"); } if (image->X() != ref->X() || image->Y() != ref->Y()) { if (verbose) cout << " failed" << endl; FatalError("Input image " << k+1 << " has differing number of voxels!"); } if (!fequal(image->GetXSize(), ref->GetXSize()) || !fequal(image->GetYSize(), ref->GetYSize())) { if (verbose) cout << " failed" << endl; FatalError("Input image " << k+1 << " has differing voxel size!"); } if (!fequal(image->GetTSize(), ref->GetTSize())) { Warning("Input image " << k+1 << " has differing temporal spacing."); } if (!CheckOrientation(image->Attributes(), ref->Attributes())) { if (verbose) cout << " failed" << endl; FatalError("Input image " << k+1 << " has different orientation!"); } for (int j = 0; j < out_attr._y; ++j) for (int i = 0; i < out_attr._x; ++i) { output->PutAsDouble(i, j, k, 0, image->GetAsDouble(i, j)); } min_zorigin = min(min_zorigin, image->GetOrigin()._z); avg_spacing += image->GetZSize(); } } else { for (int k = 0; k < out_attr._z; ++k) for (int j = 0; j < out_attr._y; ++j) for (int i = 0; i < out_attr._x; ++i) { output->PutAsDouble(i, j, k, 0, ref->GetAsDouble(i, j, k)); } for (int l = 1; l < n; ++l) { UniquePtr<BaseImage> image(BaseImage::New(input_names[pos[l]])); if (image->T() != 1) { if (verbose) cout << " failed" << endl; FatalError("Input image " << l+1 << " is not 3D!"); } if (image->X() != ref->X() || image->Y() != ref->Y() || image->Z() != ref->Z()) { if (verbose) cout << " failed" << endl; FatalError("Input image " << l+1 << " has differing number of voxels!"); } if (!fequal(image->GetXSize(), ref->GetXSize()) || !fequal(image->GetYSize(), ref->GetYSize()) || !fequal(image->GetZSize(), ref->GetZSize())) { if (verbose) cout << " failed" << endl; FatalError("Input image " << l+1 << " has differing voxel size!"); } if (!CheckOrientation(image->Attributes(), ref->Attributes())) { if (verbose) cout << " failed" << endl; FatalError("Input image " << l+1 << " has different orientation!"); } for (int k = 0; k < out_attr._z; ++k) for (int j = 0; j < out_attr._y; ++j) for (int i = 0; i < out_attr._x; ++i) { output->PutAsDouble(i, j, k, l, image->GetAsDouble(i, j, k)); } avg_spacing += image->GetZSize(); } } // Set output spacing to average of input images by default if (IsNaN(spacing)) spacing = avg_spacing; if (twod) { if (spacing < .0) { // must be positive out_attr._zaxis[0] *= -1.0; out_attr._zaxis[1] *= -1.0; out_attr._zaxis[2] *= -1.0; spacing *= -1.0; } double dx, dy, dz; output->GetPixelSize(dx, dy, dz); output->PutPixelSize(dx, dy, spacing); } else { output->PutTSize(spacing); // can be negative } // Set output origin if (twod) { if (IsNaN(start)) start = min_zorigin; Point origin = output->GetOrigin(); origin._z = start; // Move to center of image stack, i.e. translate along z axis double s = .5 * (output->Z() * output->GetZSize()); origin._x += s * output->Attributes()._zaxis[0]; origin._y += s * output->Attributes()._zaxis[1]; origin._z += s * output->Attributes()._zaxis[2]; output->PutOrigin(origin); } else { if (!IsNaN(start)) out_attr._torigin = start; // else torigin is time of first (sorted) input volume } if (verbose) cout << " done" << endl; // Write output image if (verbose) cout << "Writing concatenated images to " << output_name << "..."; output->Write(output_name); if (verbose) cout << " done" << endl; return 0; } <|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iree/compiler/Dialect/HAL/Target/VMLA/VMLATarget.h" #include "flatbuffers/flatbuffers.h" #include "iree/compiler/Dialect/Flow/IR/FlowOps.h" #include "iree/compiler/Dialect/HAL/Target/TargetRegistry.h" #include "iree/compiler/Dialect/VM/Conversion/ConversionTarget.h" #include "iree/compiler/Dialect/VM/IR/VMDialect.h" #include "iree/compiler/Dialect/VM/Target/Bytecode/BytecodeModuleTarget.h" #include "iree/compiler/Dialect/VM/Transforms/Passes.h" #include "iree/compiler/Dialect/VMLA/IR/VMLADialect.h" #include "iree/compiler/Dialect/VMLA/Transforms/Passes.h" #include "iree/schemas/vmla_executable_def_generated.h" #include "llvm/ADT/ScopeExit.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/raw_ostream.h" #include "mlir/IR/Builders.h" #include "mlir/IR/Module.h" #include "mlir/IR/OperationSupport.h" #include "mlir/Pass/PassManager.h" #include "mlir/Support/LogicalResult.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace HAL { namespace { bool AreInterfacesEquivalent(IREE::HAL::InterfaceOp lhs, IREE::HAL::InterfaceOp rhs) { auto lhsBindings = lhs.getBlock().getOps<IREE::HAL::InterfaceBindingOp>(); auto rhsBindings = rhs.getBlock().getOps<IREE::HAL::InterfaceBindingOp>(); auto lhsIt = lhsBindings.begin(), lhsEnd = lhsBindings.end(); auto rhsIt = rhsBindings.begin(), rhsEnd = rhsBindings.end(); for (; lhsIt != lhsEnd && rhsIt != rhsEnd; ++lhsIt, ++rhsIt) { // Assume bindings are in order, check equivalence of each pairing. if (!OperationEquivalence::isEquivalentTo(*lhsIt, *rhsIt)) return false; } if (lhsIt != lhsEnd || rhsIt != rhsEnd) { // Not finished iterating through one, number of interface bindings differ. return false; } return true; } } // namespace VMLATargetOptions getVMLATargetOptionsFromFlags() { VMLATargetOptions targetOptions; // TODO(benvanik): flags. return targetOptions; } class VMLATargetBackend final : public TargetBackend { public: VMLATargetBackend(VMLATargetOptions options) : options_(std::move(options)) {} std::string name() const override { return "vmla"; } std::string filter_pattern() const override { return "vmla"; } void getDependentDialects(DialectRegistry &registry) const override { registry.insert<VM::VMDialect, VMLA::VMLADialect>(); } void buildTranslationPassPipeline(IREE::HAL::ExecutableTargetOp targetOp, OpPassManager &passManager) override { IREE::VMLA::buildVMLATransformPassPipeline(passManager); // TODO(#614): remove this when the std->vm conversion isn't looking for // iree.module.export. passManager.addPass(IREE::VM::createMarkPublicSymbolsExportedPass()); IREE::VM::buildVMTransformPassPipeline( passManager, IREE::VM::getTargetOptionsFromFlags()); } LogicalResult linkExecutables(mlir::ModuleOp moduleOp) override { // --- Linking overview --- // // We start with a `module` containing multiple `hal.executable`s, each with // potentially multiple `hal.executable.target`s. We want to move all // compatible VMLA functions into a new "linked" executable, de-duping // symbols, and updating references as we go. // // Sample IR after: // hal.executable @linked_vmla { // hal.interface @legacy_io_0 { ... } // hal.interface @legacy_io_1 { ... } // hal.executable.target @vmla, filter="vmla" { // hal.executable.entry_point @main_dispatch_0 attributes { ... } // hal.executable.entry_point @main_dispatch_1 attributes { ... } // hal.executable.entry_point @main_dispatch_2 attributes { ... } // module { // vm.module @module { // vm.func @main_0(...) { ... } // vm.func @main_1(...) { ... } // vm.func @main_2(...) { ... } // } // } // } // } // hal.executable @main_dispatch_0 { // hal.interface @legacy_io { ... } // hal.executable.target @other, filter="other" { // hal.executable.entry_point @main_dispatch_0 attributes { ... } // module { ... } // } // } OpBuilder builder = OpBuilder::atBlockBegin(moduleOp.getBody()); auto executableOps = moduleOp.getOps<IREE::HAL::ExecutableOp>(); // Create our new "linked" hal.executable. auto linkedExecutableOp = builder.create<IREE::HAL::ExecutableOp>( moduleOp.getLoc(), "linked_vmla"); SymbolTable::setSymbolVisibility(linkedExecutableOp, SymbolTable::Visibility::Private); // Add our VMLA hal.executable.target with an empty module. builder.setInsertionPointToStart(linkedExecutableOp.getBody()); auto linkedTargetOp = builder.create<IREE::HAL::ExecutableTargetOp>( moduleOp.getLoc(), name(), filter_pattern()); builder.setInsertionPoint(&linkedTargetOp.getBlock().back()); auto linkedModuleOp = builder.create<ModuleOp>(moduleOp.getLoc()); // Add an empty vm.module to that module. builder.setInsertionPointToStart(linkedModuleOp.getBody()); auto linkedVmModuleOp = builder.create<IREE::VM::ModuleOp>(moduleOp.getLoc(), "linked_module"); int executablesLinked = 0; llvm::SmallVector<IREE::HAL::InterfaceOp, 4> interfaceOps; int nextEntryPointOrdinal = 0; for (auto executableOp : executableOps) { auto targetOps = llvm::to_vector<4>( executableOp.getOps<IREE::HAL::ExecutableTargetOp>()); for (auto targetOp : targetOps) { // Only process targets matching our pattern. if (!matchPattern(targetOp.target_backend_filter(), filter_pattern())) { continue; } IREE::HAL::InterfaceOp interfaceOpForExecutable; for (auto interfaceOp : interfaceOps) { if (AreInterfacesEquivalent(interfaceOp, executableOp.getFirstInterfaceOp())) { interfaceOpForExecutable = interfaceOp; } } if (!interfaceOpForExecutable) { builder.setInsertionPoint(linkedTargetOp); interfaceOpForExecutable = dyn_cast<IREE::HAL::InterfaceOp>( builder.clone(*executableOp.getFirstInterfaceOp())); interfaceOpForExecutable.setName( llvm::formatv("legacy_io_{0}", interfaceOps.size()).str()); interfaceOps.push_back(interfaceOpForExecutable); } // Clone entry point ops, remapping ordinals and updating symbol refs. builder.setInsertionPoint(linkedModuleOp); for (auto entryPointOp : targetOp.getOps<IREE::HAL::ExecutableEntryPointOp>()) { auto newEntryPointOp = builder.create<IREE::HAL::ExecutableEntryPointOp>( entryPointOp.getLoc(), entryPointOp.sym_nameAttr(), builder.getI32IntegerAttr(nextEntryPointOrdinal++), builder.getSymbolRefAttr(interfaceOpForExecutable.getName()), entryPointOp.signatureAttr()); // Update references to @executable::@target::@entry symbols. // SymbolTable::replaceAllSymbolUses only looks at root symbols, // which we can't blindly replace (other targets will map to other // linked executables). auto executableUses = SymbolTable::getSymbolUses(executableOp, moduleOp); if (!executableUses.hasValue()) continue; for (auto executableUse : executableUses.getValue()) { auto executableUser = executableUse.getUser(); // Only process symbols for this @target::@entry. auto nestedRefs = executableUse.getSymbolRef().getNestedReferences(); if (nestedRefs.size() != 2 || nestedRefs[0].getValue() != targetOp.sym_name() || nestedRefs[1].getValue() != entryPointOp.sym_name()) { continue; } if (auto dispatchOp = dyn_cast<IREE::HAL::CommandBufferDispatchSymbolOp>( executableUser)) { // New nested reference to the linked exe/target/entry. StringRef newExecutableOpSymName = linkedExecutableOp .getAttrOfType<StringAttr>( SymbolTable::getSymbolAttrName()) .getValue(); auto newSymbolRefAttr = builder.getSymbolRefAttr( newExecutableOpSymName, {builder.getSymbolRefAttr(linkedTargetOp), builder.getSymbolRefAttr(newEntryPointOp)}); dispatchOp.setAttr("entry_point", newSymbolRefAttr); } } } // Clone vm.module ops, including their contents. auto vmModuleOps = targetOp.getInnerModule().getOps<IREE::VM::ModuleOp>(); if (vmModuleOps.empty()) { return targetOp.getInnerModule().emitError() << "target's outer module does not contain a vm.module op"; } auto vmModuleOp = *vmModuleOps.begin(); builder.setInsertionPoint(&linkedVmModuleOp.getBlock().back()); // Use a SymbolTable to guard against inserting duplicate symbols. SymbolTable symbolTable(linkedVmModuleOp.getOperation()); for (auto &op : vmModuleOp.getBody()->getOperations()) { if (auto terminatorOp = dyn_cast<IREE::VM::ModuleTerminatorOp>(op)) { continue; } if (op.hasTrait<SymbolOpInterface::Trait>() && symbolTable.lookup(dyn_cast<SymbolOpInterface>(op).getName())) { continue; } builder.clone(op); } // Now that we're done cloning its ops, delete the original target op. targetOp.erase(); executablesLinked++; } } if (executablesLinked == 0) { linkedExecutableOp.erase(); } return success(); } LogicalResult serializeExecutable(IREE::HAL::ExecutableTargetOp targetOp, OpBuilder &executableBuilder) override { // Serialize the VM module to bytes. std::string byteStreamValue; llvm::raw_string_ostream byte_stream(byteStreamValue); IREE::VM::BytecodeTargetOptions bytecodeOptions; if (failed(translateModuleToBytecode(targetOp.getInnerModule(), bytecodeOptions, byte_stream))) { return targetOp.emitError() << "failed to serialize converted VM module"; } // Pack the executable definition and get the bytes with the proper header. // The header is used to verify the contents at runtime. ::flatbuffers::FlatBufferBuilder fbb; iree::VMLAExecutableDefT vmlaExecutableDef; vmlaExecutableDef.bytecode_module.resize(byteStreamValue.size()); std::memcpy(vmlaExecutableDef.bytecode_module.data(), byteStreamValue.data(), byteStreamValue.size()); auto executableOffset = iree::VMLAExecutableDef::Pack(fbb, &vmlaExecutableDef); iree::FinishVMLAExecutableDefBuffer(fbb, executableOffset); std::vector<uint8_t> bytes; bytes.resize(fbb.GetSize()); std::memcpy(bytes.data(), fbb.GetBufferPointer(), bytes.size()); // Add the binary data to the target executable. executableBuilder.create<IREE::HAL::ExecutableBinaryOp>( targetOp.getLoc(), static_cast<uint32_t>(IREE::HAL::ExecutableFormat::VMLA), std::move(bytes)); return success(); } std::array<Value, 3> calculateDispatchWorkgroupCount( Location loc, IREE::HAL::ExecutableOp executableOp, IREE::HAL::ExecutableEntryPointOp entryPointOp, Value workload, OpBuilder &builder) override { // For now we are not tiling and just dispatch everything as 1,1,1. auto constantOne = builder.createOrFold<mlir::ConstantIndexOp>(loc, 1); return {constantOne, constantOne, constantOne}; } private: VMLATargetOptions options_; }; void registerVMLATargetBackends( std::function<VMLATargetOptions()> queryOptions) { getVMLATargetOptionsFromFlags(); static TargetBackendRegistration registration("vmla", [=]() { return std::make_unique<VMLATargetBackend>(queryOptions()); }); } } // namespace HAL } // namespace IREE } // namespace iree_compiler } // namespace mlir <commit_msg>Reworks VMLA executable linking to optimize symbol walks. (#3470)<commit_after>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iree/compiler/Dialect/HAL/Target/VMLA/VMLATarget.h" #include "flatbuffers/flatbuffers.h" #include "iree/compiler/Dialect/Flow/IR/FlowOps.h" #include "iree/compiler/Dialect/HAL/Target/TargetRegistry.h" #include "iree/compiler/Dialect/VM/Conversion/ConversionTarget.h" #include "iree/compiler/Dialect/VM/IR/VMDialect.h" #include "iree/compiler/Dialect/VM/Target/Bytecode/BytecodeModuleTarget.h" #include "iree/compiler/Dialect/VM/Transforms/Passes.h" #include "iree/compiler/Dialect/VMLA/IR/VMLADialect.h" #include "iree/compiler/Dialect/VMLA/Transforms/Passes.h" #include "iree/schemas/vmla_executable_def_generated.h" #include "llvm/ADT/ScopeExit.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/raw_ostream.h" #include "mlir/IR/Builders.h" #include "mlir/IR/Module.h" #include "mlir/IR/OperationSupport.h" #include "mlir/Pass/PassManager.h" #include "mlir/Support/LogicalResult.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace HAL { namespace { bool areInterfacesEquivalent(IREE::HAL::InterfaceOp lhs, IREE::HAL::InterfaceOp rhs) { auto lhsBindings = lhs.getBlock().getOps<IREE::HAL::InterfaceBindingOp>(); auto rhsBindings = rhs.getBlock().getOps<IREE::HAL::InterfaceBindingOp>(); auto lhsIt = lhsBindings.begin(), lhsEnd = lhsBindings.end(); auto rhsIt = rhsBindings.begin(), rhsEnd = rhsBindings.end(); for (; lhsIt != lhsEnd && rhsIt != rhsEnd; ++lhsIt, ++rhsIt) { // Assume bindings are in order, check equivalence of each pairing. if (!OperationEquivalence::isEquivalentTo(*lhsIt, *rhsIt)) return false; } if (lhsIt != lhsEnd || rhsIt != rhsEnd) { // Not finished iterating through one, number of interface bindings differ. return false; } return true; } } // namespace VMLATargetOptions getVMLATargetOptionsFromFlags() { VMLATargetOptions targetOptions; // TODO(benvanik): flags. return targetOptions; } class VMLATargetBackend final : public TargetBackend { public: VMLATargetBackend(VMLATargetOptions options) : options_(std::move(options)) {} std::string name() const override { return "vmla"; } std::string filter_pattern() const override { return "vmla"; } void getDependentDialects(DialectRegistry &registry) const override { registry.insert<VM::VMDialect, VMLA::VMLADialect>(); } void buildTranslationPassPipeline(IREE::HAL::ExecutableTargetOp targetOp, OpPassManager &passManager) override { IREE::VMLA::buildVMLATransformPassPipeline(passManager); // TODO(#614): remove this when the std->vm conversion isn't looking for // iree.module.export. passManager.addPass(IREE::VM::createMarkPublicSymbolsExportedPass()); IREE::VM::buildVMTransformPassPipeline( passManager, IREE::VM::getTargetOptionsFromFlags()); } LogicalResult linkExecutables(mlir::ModuleOp moduleOp) override { // --- Linking overview --- // // We start with a `module` containing multiple `hal.executable`s, each with // potentially multiple `hal.executable.target`s. We want to move all // compatible VMLA functions into a new "linked" executable, de-duping // symbols, and updating references as we go. // // Sample IR after: // hal.executable @linked_vmla { // hal.interface @legacy_io_0 { ... } // hal.interface @legacy_io_1 { ... } // hal.executable.target @vmla, filter="vmla" { // hal.executable.entry_point @main_dispatch_0 attributes { ... } // hal.executable.entry_point @main_dispatch_1 attributes { ... } // hal.executable.entry_point @main_dispatch_2 attributes { ... } // module { // vm.module @module { // vm.func @main_0(...) { ... } // vm.func @main_1(...) { ... } // vm.func @main_2(...) { ... } // } // } // } // } // hal.executable @main_dispatch_0 { // hal.interface @legacy_io { ... } // hal.executable.target @other, filter="other" { // hal.executable.entry_point @main_dispatch_0 attributes { ... } // module { ... } // } // } OpBuilder builder = OpBuilder::atBlockBegin(moduleOp.getBody()); auto executableOps = llvm::to_vector<8>(moduleOp.getOps<IREE::HAL::ExecutableOp>()); // Create our new "linked" hal.executable. auto linkedExecutableOp = builder.create<IREE::HAL::ExecutableOp>( moduleOp.getLoc(), "linked_vmla"); SymbolTable::setSymbolVisibility(linkedExecutableOp, SymbolTable::Visibility::Private); // Add our VMLA hal.executable.target with an empty module. builder.setInsertionPointToStart(linkedExecutableOp.getBody()); auto linkedTargetOp = builder.create<IREE::HAL::ExecutableTargetOp>( moduleOp.getLoc(), name(), filter_pattern()); builder.setInsertionPoint(&linkedTargetOp.getBlock().back()); auto linkedModuleOp = builder.create<ModuleOp>(moduleOp.getLoc()); // Add an empty vm.module to that module. builder.setInsertionPointToStart(linkedModuleOp.getBody()); auto linkedVmModuleOp = builder.create<IREE::VM::ModuleOp>(moduleOp.getLoc(), "linked_module"); llvm::SmallVector<IREE::HAL::InterfaceOp, 4> interfaceOps; int nextEntryPointOrdinal = 0; DenseMap<StringRef, Operation *> symbolMap; DenseMap<Attribute, Attribute> entryPointRefReplacements; auto linkedExecutableBuilder = OpBuilder::atBlockBegin(linkedExecutableOp.getBody()); auto linkedTargetBuilder = OpBuilder::atBlockBegin(linkedTargetOp.getBody()); for (auto executableOp : executableOps) { auto targetOps = llvm::to_vector<4>( executableOp.getOps<IREE::HAL::ExecutableTargetOp>()); for (auto targetOp : targetOps) { // Only process targets matching our pattern. if (!matchPattern(targetOp.target_backend_filter(), filter_pattern())) { continue; } IREE::HAL::InterfaceOp interfaceOpForExecutable; for (auto interfaceOp : interfaceOps) { if (areInterfacesEquivalent(interfaceOp, executableOp.getFirstInterfaceOp())) { interfaceOpForExecutable = interfaceOp; break; } } if (!interfaceOpForExecutable) { interfaceOpForExecutable = dyn_cast<IREE::HAL::InterfaceOp>(linkedExecutableBuilder.clone( *executableOp.getFirstInterfaceOp())); interfaceOpForExecutable.setName( llvm::formatv("legacy_io_{0}", interfaceOps.size()).str()); interfaceOps.push_back(interfaceOpForExecutable); } // Clone entry point ops and queue remapping ordinals and updating // symbol refs. for (auto entryPointOp : targetOp.getOps<IREE::HAL::ExecutableEntryPointOp>()) { auto newEntryPointOp = linkedTargetBuilder.create<IREE::HAL::ExecutableEntryPointOp>( entryPointOp.getLoc(), entryPointOp.sym_nameAttr(), builder.getI32IntegerAttr(nextEntryPointOrdinal++), builder.getSymbolRefAttr(interfaceOpForExecutable.getName()), entryPointOp.signatureAttr()); // Add to replacement table for fixing up dispatch calls referencing // this entry point. auto oldSymbolRefAttr = builder.getSymbolRefAttr( executableOp.getName(), {builder.getSymbolRefAttr(targetOp), builder.getSymbolRefAttr(entryPointOp)}); auto newSymbolRefAttr = builder.getSymbolRefAttr( linkedExecutableOp.getName(), {builder.getSymbolRefAttr(linkedTargetOp), builder.getSymbolRefAttr(newEntryPointOp)}); entryPointRefReplacements[oldSymbolRefAttr] = newSymbolRefAttr; } // Merge the existing vm.module op into the new linked vm.module op. auto vmModuleOps = targetOp.getInnerModule().getOps<IREE::VM::ModuleOp>(); if (vmModuleOps.empty()) { return targetOp.getInnerModule().emitError() << "target's outer module does not contain a vm.module op"; } mergeModuleInto(*vmModuleOps.begin(), linkedVmModuleOp, symbolMap); targetOp.erase(); } if (executableOp.getOps<IREE::HAL::ExecutableTargetOp>().empty()) { executableOp.erase(); } } // Update references to @executable::@target::@entry symbols. replaceEntryPointUses(moduleOp, entryPointRefReplacements); // Remove if we didn't add anything. if (linkedTargetOp.getOps<IREE::HAL::ExecutableEntryPointOp>().empty()) { linkedTargetOp.erase(); linkedExecutableOp.erase(); } return success(); } // Destructively merges |sourceModuleOp| into |targetModuleOp|. // |targetSymbolTable| is updated with the new symbols. void mergeModuleInto(IREE::VM::ModuleOp sourceModuleOp, IREE::VM::ModuleOp targetModuleOp, DenseMap<StringRef, Operation *> &targetSymbolMap) { auto allOps = llvm::to_vector<8>(llvm::map_range( sourceModuleOp.getBlock(), [&](Operation &op) { return &op; })); for (auto &op : allOps) { if (op->isKnownTerminator()) continue; if (auto symbolInterface = dyn_cast<SymbolOpInterface>(op)) { if (targetSymbolMap.count(symbolInterface.getName())) { // TODO(scotttodd): compare ops to ensure we aren't copying different // things with the same name. continue; } targetSymbolMap[symbolInterface.getName()] = op; } op->moveBefore(&targetModuleOp.getBlock().back()); } // Now that we're done cloning its ops, delete the original target op. sourceModuleOp.erase(); } // Replaces each usage of an entry point with its original symbol name with a // new symbol name. void replaceEntryPointUses( mlir::ModuleOp moduleOp, const DenseMap<Attribute, Attribute> &replacements) { for (auto funcOp : moduleOp.getOps<mlir::FuncOp>()) { funcOp.walk([&](IREE::HAL::CommandBufferDispatchSymbolOp dispatchOp) { auto it = replacements.find(dispatchOp.entry_point()); if (it != replacements.end()) { dispatchOp.entry_pointAttr(it->second.cast<SymbolRefAttr>()); } }); } } LogicalResult serializeExecutable(IREE::HAL::ExecutableTargetOp targetOp, OpBuilder &executableBuilder) override { // Serialize the VM module to bytes. std::string byteStreamValue; llvm::raw_string_ostream byte_stream(byteStreamValue); IREE::VM::BytecodeTargetOptions bytecodeOptions; if (failed(translateModuleToBytecode(targetOp.getInnerModule(), bytecodeOptions, byte_stream))) { return targetOp.emitError() << "failed to serialize converted VM module"; } // Pack the executable definition and get the bytes with the proper header. // The header is used to verify the contents at runtime. ::flatbuffers::FlatBufferBuilder fbb; iree::VMLAExecutableDefT vmlaExecutableDef; vmlaExecutableDef.bytecode_module.resize(byteStreamValue.size()); std::memcpy(vmlaExecutableDef.bytecode_module.data(), byteStreamValue.data(), byteStreamValue.size()); auto executableOffset = iree::VMLAExecutableDef::Pack(fbb, &vmlaExecutableDef); iree::FinishVMLAExecutableDefBuffer(fbb, executableOffset); std::vector<uint8_t> bytes; bytes.resize(fbb.GetSize()); std::memcpy(bytes.data(), fbb.GetBufferPointer(), bytes.size()); // Add the binary data to the target executable. executableBuilder.create<IREE::HAL::ExecutableBinaryOp>( targetOp.getLoc(), static_cast<uint32_t>(IREE::HAL::ExecutableFormat::VMLA), std::move(bytes)); return success(); } std::array<Value, 3> calculateDispatchWorkgroupCount( Location loc, IREE::HAL::ExecutableOp executableOp, IREE::HAL::ExecutableEntryPointOp entryPointOp, Value workload, OpBuilder &builder) override { // For now we are not tiling and just dispatch everything as 1,1,1. auto constantOne = builder.createOrFold<mlir::ConstantIndexOp>(loc, 1); return {constantOne, constantOne, constantOne}; } private: VMLATargetOptions options_; }; void registerVMLATargetBackends( std::function<VMLATargetOptions()> queryOptions) { getVMLATargetOptionsFromFlags(); static TargetBackendRegistration registration("vmla", [=]() { return std::make_unique<VMLATargetBackend>(queryOptions()); }); } } // namespace HAL } // namespace IREE } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before>// glut108.cpp : Defines the entry point for the console application. // #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; } <commit_msg>program 8 - depth cube<commit_after>// glut108.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "../glut/glut.h" float z_pos = -10.0f; float rot = 0.0f; void resize(int width, int height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0, (float)width / (float)height, 1.0, 300.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void myTimeOut(int id) { // called if timer event // ...advance the state of animation incrementally... rot += 10; glutPostRedisplay(); // request redisplay glutTimerFunc(100, myTimeOut, 0); // request next timer event } void myKeyboard(unsigned char key, int x, int y) { if ((key == '<') || (key == ',')) z_pos -= 0.1f; if ((key == '>') || (key == '.')) z_pos += 0.1f; } void mydisplay(void) { //glClear(GL_COLOR_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef(0.0, 0.0f, z_pos); glRotatef(rot, 0, 1, 0); glBegin(GL_QUADS); // Front Face, red glColor3f(1.0, 0.0, 0.0); glVertex3f(-1.0f, -1.0f, 1.0f); glVertex3f(1.0f, -1.0f, 1.0f); glVertex3f(1.0f, 1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Back Face, green glColor3f(0.0, 1.0, 0.0); glVertex3f(1.0f, -1.0f, -1.0f); glVertex3f(1.0f, 1.0f, -1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glVertex3f(-1.0f, -1.0f, -1.0f); // Top Face, blue glColor3f(0.0, 0.0, 1.0); glVertex3f(-1.0f, 1.0f, -1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glVertex3f(1.0f, 1.0f, 1.0f); glVertex3f(1.0f, 1.0f, -1.0f); // Bottom Face, yellow glColor3f(1.0, 1.0, 0.0); glVertex3f(-1.0f, -1.0f, -1.0f); glVertex3f(1.0f, -1.0f, -1.0f); glVertex3f(1.0f, -1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Right face, cyan glColor3f(0.0, 1.0, 1.0); glVertex3f(1.0f, -1.0f, -1.0f); glVertex3f(1.0f, 1.0f, -1.0f); glVertex3f(1.0f, 1.0f, 1.0f); glVertex3f(1.0f, -1.0f, 1.0f); // Left Face, magenta glColor3f(1.0, 0.0, 1.0); glVertex3f(-1.0f, -1.0f, -1.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glEnd(); glFlush(); glutSwapBuffers(); } void init() { glEnable(GL_DEPTH_TEST); glClearColor(0.0, 0.0, 0.0, 1.0); // A Background Clear Color glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45, (GLdouble)500.0 / (GLdouble)500.0, 0, 100); glMatrixMode(GL_MODELVIEW); return; } int _tmain(int argc, _TCHAR* argv[]) { glutInit(&argc, (char**)argv); //glutInitDisplayMode( GLUT_DOUBLE /*| GLUT_DEPTH*/ ); glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(500, 500); glutInitWindowPosition(0, 0); glutCreateWindow("simple"); // callbacks glutDisplayFunc(mydisplay); glutKeyboardFunc(myKeyboard); glutTimerFunc(100, myTimeOut, 0); glutReshapeFunc(resize); init(); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2016 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Contains Template Metaprogramming (TMP) utilities for SFINAE. * * Clang compiler tries to do smart error reporting based on enable-if. For * this reason, all the aliases are defined in terms of enable-if and not by * composition. Nevertheless, even with that, error reporting fails short when * enable_if is not used directly. Therefore, it is advised to use the macros * instead of the aliases. */ #ifndef CPP_UTILS_TMP_SFINAE_HPP #define CPP_UTILS_TMP_SFINAE_HPP namespace cpp { /*! * \brief Helper to use a enable-if-not (disable-if) * * This can be used to improve readibility of the code * * \tparam B The boolean disabler * \tparam T The type in case of success */ template<bool B, typename T = void> using disable_if = std::enable_if<!B, T>; /*! * \brief Helper to use a enable-if-not (disable-if), this helper is directly * the type of the disabler. * * This can be used to improve readibility of the code * * \tparam B The boolean disabler * \tparam T The type in case of success */ template<bool B, typename T = void> using disable_if_t = typename std::enable_if<!B, T>::type; namespace detail { //Note: Unfortunately, CLang is bugged (Bug 11723), therefore, it is not //possible to use universal enable_if/disable_if directly, it is necessary to //use the dummy :( FU Clang! enum class enabler_t { DUMMY }; constexpr const enabler_t dummy = enabler_t::DUMMY; } //end of detail //Note: For error reporting reasons, it is not a good idea to define these next //utilities using each other (for instance enable_if_c using enable_if_u) //CLang tries to report errors of disabling for SFINAE but does a very poor job //handling enable_if_t, therefore std::enable_if is used directly //Even with this, the error reporting using these alias declarations is pretty //bad, this is the reason, the macros have been written :( /*! * \brief Universal enable_if helper, the success-type is a dummy type. * \tparam B The boolean enabler */ template<bool B> using enable_if_u = typename std::enable_if<B, detail::enabler_t>::type; /*! * \brief Universal disable_if helper, the success-type is a dummy type. * \tparam B The boolean disabler */ template<bool B> using disable_if_u = typename std::enable_if<not_u<B>::value, detail::enabler_t>::type; /*! * \brief Universal enable_if helper from traits, the success-type is a dummy type. * \tparam C The traits to extract the value from. */ template<typename C> using enable_if_c = typename std::enable_if<C::value, detail::enabler_t>::type; /*! * \brief Universal disable_if helper from traits, the success-type is a dummy type. * \tparam C The traits to extract the value from. */ template<typename C> using disable_if_c = typename std::enable_if<not_c<C>::value, detail::enabler_t>::type; /*! * \brief Universal enable_if helper for several boolean values (AND), the success-type is a dummy type. * \tparam B The boolean values for enabler */ template<bool... B> using enable_if_all_u = typename std::enable_if<and_u<B...>::value, detail::enabler_t>::type; /*! * \brief Universal disable_if helper for several boolean values (AND), the success-type is a dummy type. * \tparam B The boolean values for disabler */ template<bool... B> using disable_if_all_u = typename std::enable_if<not_c<and_u<B...>>::value, detail::enabler_t>::type; /*! * \brief Universal enable_if helper for several traits (AND), the success-type is a dummy type. * \tparam C The traits for enabler */ template<typename... C> using enable_if_all_c = typename std::enable_if<and_c<C...>::value, detail::enabler_t>::type; /*! * \brief Universal disable_if helper for several traits (AND), the success-type is a dummy type. * \tparam C The traits for disabler */ template<typename... C> using disable_if_all_c = typename std::enable_if<not_c<and_c<C...>>::value, detail::enabler_t>::type; /*! * \brief Universal enable_if helper for several boolean values (OR), the success-type is a dummy type. * \tparam B The boolean values for enabler */ template<bool... B> using enable_if_one_u = typename std::enable_if<or_u<B...>::value, detail::enabler_t>::type; /*! * \brief Universal disable_if helper for several boolean values (OR), the success-type is a dummy type. * \tparam B The boolean values for disabler */ template<bool... B> using disable_if_one_u = typename std::enable_if<not_c<or_u<B...>>::value, detail::enabler_t>::type; /*! * \brief Universal enable_if helper for several traits (OR), the success-type is a dummy type. * \tparam C The traits for enabler */ template<typename... C> using enable_if_one_c = typename std::enable_if<or_c<C...>::value, detail::enabler_t>::type; /*! * \brief Universal disable_if helper for several traits (OR), the success-type is a dummy type. * \tparam C The traits for disabler */ template<typename... C> using disable_if_one_c = typename std::enable_if<not_c<or_c<C...>>::value, detail::enabler_t>::type; //For the same reasons, the macros are defined using std::enable_if and not the //simpler versions //Note: We don't surround args by parenths, since this would result in being evaluated as the comma operator #define cpp_enable_if(...) typename std::enable_if<cpp::and_u<__VA_ARGS__>::value, cpp::detail::enabler_t>::type = cpp::detail::dummy #define cpp_disable_if(...) typename std::enable_if<cpp::not_c<cpp::and_u<__VA_ARGS__>>::value, cpp::detail::enabler_t>::type= cpp::detail::dummy #define cpp_enable_if_fwd(...) typename std::enable_if<cpp::and_u<__VA_ARGS__>::value, cpp::detail::enabler_t>::type #define cpp_disable_if_fwd(...) typename std::enable_if<cpp::not_c<cpp::and_u<__VA_ARGS__>>::value, cpp::detail::enabler_t>::type #define cpp_enable_if_or(...) typename std::enable_if<cpp::or_u<__VA_ARGS__>::value, cpp::detail::enabler_t>::type = cpp::detail::dummy #define cpp_disable_if_or(...) typename std::enable_if<cpp::not_c<cpp::or_u<__VA_ARGS__>>::value, cpp::detail::enabler_t>::type= cpp::detail::dummy #define cpp_enable_if_or_fwd(...) typename std::enable_if<cpp::or_u<__VA_ARGS__>::value, cpp::detail::enabler_t>::type #define cpp_disable_if_or_fwd(...) typename std::enable_if<cpp::not_c<cpp::or_u<__VA_ARGS__>>::value, cpp::detail::enabler_t>::type #define cpp_enable_if_cst(...) bool CPP_CST_ENABLE = true, typename std::enable_if<(__VA_ARGS__) && CPP_CST_ENABLE, cpp::detail::enabler_t>::type = cpp::detail::dummy #define cpp_disable_if_cst(...) bool CPP_CST_ENABLE = true, typename std::enable_if<!((__VA_ARGS__) && CPP_CST_ENABLE), cpp::detail::enabler_t>::type = cpp::detail::dummy } //end of namespace cpp #endif //CPP_UTILS_TMP_HPP <commit_msg>Workaround for sonar-cxx<commit_after>//======================================================================= // Copyright (c) 2013-2016 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Contains Template Metaprogramming (TMP) utilities for SFINAE. * * Clang compiler tries to do smart error reporting based on enable-if. For * this reason, all the aliases are defined in terms of enable-if and not by * composition. Nevertheless, even with that, error reporting fails short when * enable_if is not used directly. Therefore, it is advised to use the macros * instead of the aliases. */ #ifndef CPP_UTILS_TMP_SFINAE_HPP #define CPP_UTILS_TMP_SFINAE_HPP namespace cpp { /*! * \brief Helper to use a enable-if-not (disable-if) * * This can be used to improve readibility of the code * * \tparam B The boolean disabler * \tparam T The type in case of success */ template<bool B, typename T = void> using disable_if = std::enable_if<!B, T>; /*! * \brief Helper to use a enable-if-not (disable-if), this helper is directly * the type of the disabler. * * This can be used to improve readibility of the code * * \tparam B The boolean disabler * \tparam T The type in case of success */ template<bool B, typename T = void> using disable_if_t = typename std::enable_if<!B, T>::type; namespace detail { //Note: Unfortunately, CLang is bugged (Bug 11723), therefore, it is not //possible to use universal enable_if/disable_if directly, it is necessary to //use the dummy :( FU Clang! enum class enabler_t { DUMMY }; constexpr const enabler_t dummy = enabler_t::DUMMY; } //end of detail //Note: For error reporting reasons, it is not a good idea to define these next //utilities using each other (for instance enable_if_c using enable_if_u) //CLang tries to report errors of disabling for SFINAE but does a very poor job //handling enable_if_t, therefore std::enable_if is used directly //Even with this, the error reporting using these alias declarations is pretty //bad, this is the reason, the macros have been written :( /*! * \brief Universal enable_if helper, the success-type is a dummy type. * \tparam B The boolean enabler */ template<bool B> using enable_if_u = typename std::enable_if<B, detail::enabler_t>::type; /*! * \brief Universal disable_if helper, the success-type is a dummy type. * \tparam B The boolean disabler */ template<bool B> using disable_if_u = typename std::enable_if<not_u<B>::value, detail::enabler_t>::type; /*! * \brief Universal enable_if helper from traits, the success-type is a dummy type. * \tparam C The traits to extract the value from. */ template<typename C> using enable_if_c = typename std::enable_if<C::value, detail::enabler_t>::type; /*! * \brief Universal disable_if helper from traits, the success-type is a dummy type. * \tparam C The traits to extract the value from. */ template<typename C> using disable_if_c = typename std::enable_if<not_c<C>::value, detail::enabler_t>::type; /*! * \brief Universal enable_if helper for several boolean values (AND), the success-type is a dummy type. * \tparam B The boolean values for enabler */ template<bool... B> using enable_if_all_u = typename std::enable_if<and_u<B...>::value, detail::enabler_t>::type; /*! * \brief Universal disable_if helper for several boolean values (AND), the success-type is a dummy type. * \tparam B The boolean values for disabler */ template<bool... B> using disable_if_all_u = typename std::enable_if<not_c<and_u<B...>>::value, detail::enabler_t>::type; /*! * \brief Universal enable_if helper for several traits (AND), the success-type is a dummy type. * \tparam C The traits for enabler */ template<typename... C> using enable_if_all_c = typename std::enable_if<and_c<C...>::value, detail::enabler_t>::type; /*! * \brief Universal disable_if helper for several traits (AND), the success-type is a dummy type. * \tparam C The traits for disabler */ template<typename... C> using disable_if_all_c = typename std::enable_if<not_c<and_c<C...>>::value, detail::enabler_t>::type; /*! * \brief Universal enable_if helper for several boolean values (OR), the success-type is a dummy type. * \tparam B The boolean values for enabler */ template<bool... B> using enable_if_one_u = typename std::enable_if<or_u<B...>::value, detail::enabler_t>::type; /*! * \brief Universal disable_if helper for several boolean values (OR), the success-type is a dummy type. * \tparam B The boolean values for disabler */ template<bool... B> using disable_if_one_u = typename std::enable_if<not_c<or_u<B...>>::value, detail::enabler_t>::type; /*! * \brief Universal enable_if helper for several traits (OR), the success-type is a dummy type. * \tparam C The traits for enabler */ template<typename... C> using enable_if_one_c = typename std::enable_if<or_c<C...>::value, detail::enabler_t>::type; /*! * \brief Universal disable_if helper for several traits (OR), the success-type is a dummy type. * \tparam C The traits for disabler */ template<typename... C> using disable_if_one_c = typename std::enable_if<not_c<or_c<C...>>::value, detail::enabler_t>::type; //For the same reasons, the macros are defined using std::enable_if and not the //simpler versions //Note: We don't surround args by parenths, since this would result in being evaluated as the comma operator #ifndef SONAR_ANALYSIS #define cpp_enable_if(...) typename std::enable_if<cpp::and_u<__VA_ARGS__>::value, cpp::detail::enabler_t>::type = cpp::detail::dummy #define cpp_disable_if(...) typename std::enable_if<cpp::not_c<cpp::and_u<__VA_ARGS__>>::value, cpp::detail::enabler_t>::type= cpp::detail::dummy #define cpp_enable_if_fwd(...) typename std::enable_if<cpp::and_u<__VA_ARGS__>::value, cpp::detail::enabler_t>::type #define cpp_disable_if_fwd(...) typename std::enable_if<cpp::not_c<cpp::and_u<__VA_ARGS__>>::value, cpp::detail::enabler_t>::type #define cpp_enable_if_or(...) typename std::enable_if<cpp::or_u<__VA_ARGS__>::value, cpp::detail::enabler_t>::type = cpp::detail::dummy #define cpp_disable_if_or(...) typename std::enable_if<cpp::not_c<cpp::or_u<__VA_ARGS__>>::value, cpp::detail::enabler_t>::type= cpp::detail::dummy #define cpp_enable_if_or_fwd(...) typename std::enable_if<cpp::or_u<__VA_ARGS__>::value, cpp::detail::enabler_t>::type #define cpp_disable_if_or_fwd(...) typename std::enable_if<cpp::not_c<cpp::or_u<__VA_ARGS__>>::value, cpp::detail::enabler_t>::type #define cpp_enable_if_cst(...) bool CPP_CST_ENABLE = true, typename std::enable_if<(__VA_ARGS__) && CPP_CST_ENABLE, cpp::detail::enabler_t>::type = cpp::detail::dummy #define cpp_disable_if_cst(...) bool CPP_CST_ENABLE = true, typename std::enable_if<!((__VA_ARGS__) && CPP_CST_ENABLE), cpp::detail::enabler_t>::type = cpp::detail::dummy #else //sonar-cxx does a very poor job of handling the macros directly. Therefore we simply use std::enable_if_t to avoid false positives by the hundreds //These versions cannot be used in the general case for debugging reasons (see explanations above) #define cpp_enable_if(...) std::enable_if_t<cpp::and_u<__VA_ARGS__>::value, cpp::detail::enabler_t> = cpp::detail::dummy #define cpp_disable_if(...) std::enable_if_t<cpp::not_c<cpp::and_u<__VA_ARGS__>>::value, cpp::detail::enabler_t> = cpp::detail::dummy #define cpp_enable_if_fwd(...) std::enable_if_t<cpp::and_u<__VA_ARGS__>::value, cpp::detail::enabler_t> #define cpp_disable_if_fwd(...) std::enable_if_t<cpp::not_c<cpp::and_u<__VA_ARGS__>>::value, cpp::detail::enabler_t> #define cpp_enable_if_or(...) std::enable_if_t<cpp::or_u<__VA_ARGS__>::value, cpp::detail::enabler_t> = cpp::detail::dummy #define cpp_disable_if_or(...) std::enable_if_t<cpp::not_c<cpp::or_u<__VA_ARGS__>>::value, cpp::detail::enabler_t> = cpp::detail::dummy #define cpp_enable_if_or_fwd(...) std::enable_if_t<cpp::or_u<__VA_ARGS__>::value, cpp::detail::enabler_t> #define cpp_disable_if_or_fwd(...) std::enable_if_t<cpp::not_c<cpp::or_u<__VA_ARGS__>>::value, cpp::detail::enabler_t> #define cpp_enable_if_cst(...) bool CPP_CST_ENABLE = true, std::enable_if_t<(__VA_ARGS__) && CPP_CST_ENABLE, cpp::detail::enabler_t> = cpp::detail::dummy #define cpp_disable_if_cst(...) bool CPP_CST_ENABLE = true, std::enable_if_t<!((__VA_ARGS__) && CPP_CST_ENABLE), cpp::detail::enabler_t> = cpp::detail::dummy #endif } //end of namespace cpp #endif //CPP_UTILS_TMP_HPP <|endoftext|>
<commit_before>/* * Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved. */ #include "db/rt/DynamicObjectImpl.h" #include "db/rt/DynamicObject.h" using namespace std; using namespace db::rt; DynamicObjectImpl::DynamicObjectImpl() { mType = String; mString = NULL; mStringValue = NULL; } DynamicObjectImpl::~DynamicObjectImpl() { DynamicObjectImpl::freeData(); // free cached string value if(mStringValue != NULL) { free(mStringValue); } } void DynamicObjectImpl::freeMapKeys() { // clean up member names for(ObjectMap::iterator i = mMap->begin(); i != mMap->end(); i++) { free((char*)i->first); } } void DynamicObjectImpl::freeData() { // clean up data based on type switch(mType) { case String: if(mString != NULL) { free(mString); mString = NULL; } break; case Map: if(mMap != NULL) { freeMapKeys(); delete mMap; mMap = NULL; } break; case Array: if(mArray != NULL) { delete mArray; mArray = NULL; } break; default: // nothing to cleanup break; } } void DynamicObjectImpl::setString(const char* value) { freeData(); mType = String; mString = strdup(value); } void DynamicObjectImpl::operator=(const char* value) { setString(value); } void DynamicObjectImpl::operator=(bool value) { freeData(); mType = Boolean; mBoolean = value; } void DynamicObjectImpl::operator=(int value) { freeData(); mType = Int32; mInt32 = value; } void DynamicObjectImpl::operator=(unsigned int value) { freeData(); mType = UInt32; mUInt32 = value; } void DynamicObjectImpl::operator=(long long value) { freeData(); mType = Int64; mInt64 = value; } void DynamicObjectImpl::operator=(unsigned long long value) { freeData(); mType = UInt64; mUInt64 = value; } void DynamicObjectImpl::operator=(double value) { freeData(); mType = Double; mDouble = value; } DynamicObject& DynamicObjectImpl::operator[](const char* name) { DynamicObject* rval = NULL; // change to map type if necessary setType(Map); ObjectMap::iterator i = mMap->find(name); if(i == mMap->end()) { // create new map entry DynamicObject dyno; mMap->insert(std::make_pair(strdup(name), dyno)); rval = &(*mMap)[name]; } else { // get existing map entry rval = &i->second; } return *rval; } DynamicObject& DynamicObjectImpl::operator[](int index) { // change to array type if necessary setType(Array); if(index < 0) { index = mArray->size() + index; } // fill the object array as necessary if(index >= (int)mArray->size()) { int i = index - (int)mArray->size() + 1; for(; i > 0; i--) { DynamicObject dyno; mArray->push_back(dyno); } } return (*mArray)[index]; } DynamicObject& DynamicObjectImpl::append() { return (*this)[length()]; } void DynamicObjectImpl::setType(DynamicObjectType type) { if(mType != type) { switch(type) { case String: *this = getString(); break; case Boolean: *this = getBoolean(); break; case Int32: *this = getInt32(); break; case UInt32: *this = getUInt32(); break; case Int64: *this = getInt64(); break; case UInt64: *this = getUInt64(); break; case Double: *this = getDouble(); break; case Map: { freeData(); mType = Map; mMap = new ObjectMap(); } break; case Array: { freeData(); mType = Array; mArray = new ObjectArray(); } break; } } } DynamicObjectType DynamicObjectImpl::getType() { return mType; } const char* DynamicObjectImpl::getString() { const char* rval; if(mType == String) { if(mString != NULL) { // use existing string rval = mString; } else { // only duplicate blank string upon request rval = mString = strdup(""); } } else { // convert type as appropriate switch(mType) { case Boolean: mStringValue = (char*)realloc(mStringValue, 6); snprintf(mStringValue, 6, "%s", (mBoolean ? "true" : "false")); break; case Int32: mStringValue = (char*)realloc(mStringValue, 12); snprintf(mStringValue, 12, "%i", mInt32); break; case UInt32: mStringValue = (char*)realloc(mStringValue, 11); snprintf(mStringValue, 11, "%u", mUInt32); break; case Int64: mStringValue = (char*)realloc(mStringValue, 22); snprintf(mStringValue, 22, "%lli", mInt64); break; case UInt64: mStringValue = (char*)realloc(mStringValue, 21); snprintf(mStringValue, 21, "%llu", mUInt64); break; case Double: // use default precision of 6 // X.000000e+00 = 11 places to right of decimal mStringValue = (char*)realloc(mStringValue, 50); snprintf(mStringValue, 50, "%e", mDouble); break; default: /* Map, Array, ... */ { if(mStringValue == NULL) { // duplicate blank string mStringValue = strdup(""); } else { // set null-terminator to first character mStringValue[0] = 0; } } break; } // return generated value rval = mStringValue; } return rval; } bool DynamicObjectImpl::getBoolean() { bool rval; switch(mType) { case Boolean: rval = mBoolean; break; case String: rval = (mString == NULL) ? false : (strcmp(mString, "true") == 0); break; case Int32: rval = (mInt32 == 1); break; case UInt32: rval = (mUInt32 == 1); break; case Int64: rval = (mInt64 == 1); break; case UInt64: rval = (mUInt64 == 1); break; case Double: rval = (mDouble == 1); break; default: rval = false; break; } return rval; } int DynamicObjectImpl::getInt32() { int rval; switch(mType) { case Int32: rval = mInt32; break; case String: rval = (mString == NULL) ? 0 : strtol(mString, NULL, 10); break; case Boolean: rval = mBoolean ? 1 : 0; break; case UInt32: rval = (int)mUInt32; break; case Int64: rval = (int)mInt64; break; case UInt64: rval = (int)mUInt64; break; case Double: rval = (int)mDouble; break; default: rval = 0; break; } return rval; } unsigned int DynamicObjectImpl::getUInt32() { unsigned int rval; switch(mType) { case UInt32: rval = mUInt32; break; case String: rval = (mString == NULL) ? 0 : strtoul(mString, NULL, 10); break; case Boolean: rval = mBoolean ? 1 : 0; break; case Int32: rval = (mInt32 < 0) ? 0 : mInt32; break; case Int64: rval = (mInt64 < 0) ? 0 : (unsigned int)mInt64; break; case UInt64: rval = (unsigned int)mUInt64; break; case Double: rval = (unsigned int)mDouble; break; default: rval = 0; break; } return rval; } long long DynamicObjectImpl::getInt64() { long long rval; switch(mType) { case Int64: rval = mInt64; break; case String: rval = (mString == NULL) ? 0 : strtoll(mString, NULL, 10); break; case Boolean: rval = mBoolean ? 1 : 0; break; case Int32: rval = mInt32; break; case UInt32: rval = mUInt32; break; case UInt64: rval = (long long)mUInt64; break; case Double: rval = (long long)mDouble; break; default: rval = 0; break; } return rval; } unsigned long long DynamicObjectImpl::getUInt64() { unsigned long long rval; switch(mType) { case UInt64: rval = mUInt64; break; case String: rval = (mString == NULL) ? 0 : strtoull(mString, NULL, 10); break; case Boolean: rval = mBoolean ? 1 : 0; break; case Int32: rval = (mInt32 < 0) ? 0 : mInt32; break; case UInt32: rval = mUInt32; break; case Int64: rval = (mInt64 < 0) ? 0 : mInt64; break; case Double: rval = (unsigned long long)mDouble; break; default: rval = 0; break; } return rval; } double DynamicObjectImpl::getDouble() { double rval; switch(mType) { case Double: rval = mDouble; break; case String: rval = (mString == NULL) ? 0 : strtod(mString, NULL); break; case Boolean: rval = mBoolean ? 1 : 0; break; case Int32: rval = mInt32; break; case UInt32: rval = mUInt32; break; case Int64: rval = mInt64; break; case UInt64: rval = mUInt64; break; default: rval = 0; break; } return rval; } bool DynamicObjectImpl::hasMember(const char* name) { bool rval = false; if(mType == Map) { ObjectMap::iterator i = mMap->find(name); rval = (i != mMap->end()); } return rval; } DynamicObject DynamicObjectImpl::removeMember(const char* name) { DynamicObject rval(NULL); if(mType == Map) { ObjectMap::iterator i = mMap->find(name); if(i != mMap->end()) { // clean up key and remove map entry free((char*)i->first); rval = i->second; mMap->erase(i); } } return rval; } void DynamicObjectImpl::clear() { switch(mType) { case String: *this = ""; break; case Boolean: *this = false; break; case Int32: *this = (int)0; break; case UInt32: *this = (unsigned int)0; break; case Int64: *this = (long long)0; break; case UInt64: *this = (unsigned long long)0; break; case Double: *this = (double)0.0; break; case Map: freeMapKeys(); mMap->clear(); break; case Array: mArray->clear(); break; } } int DynamicObjectImpl::length() { int rval = 0; switch(mType) { case String: if(mString != NULL) { rval = strlen(getString()); } break; case Boolean: rval = 1; break; case Int32: case UInt32: rval = sizeof(unsigned int); break; case Int64: case UInt64: rval = sizeof(unsigned long long); break; case Double: rval = sizeof(double); break; case Map: rval = mMap->size(); break; case Array: rval = mArray->size(); break; } return rval; } <commit_msg>Made sure to convert type to array when using append().<commit_after>/* * Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved. */ #include "db/rt/DynamicObjectImpl.h" #include "db/rt/DynamicObject.h" using namespace std; using namespace db::rt; DynamicObjectImpl::DynamicObjectImpl() { mType = String; mString = NULL; mStringValue = NULL; } DynamicObjectImpl::~DynamicObjectImpl() { DynamicObjectImpl::freeData(); // free cached string value if(mStringValue != NULL) { free(mStringValue); } } void DynamicObjectImpl::freeMapKeys() { // clean up member names for(ObjectMap::iterator i = mMap->begin(); i != mMap->end(); i++) { free((char*)i->first); } } void DynamicObjectImpl::freeData() { // clean up data based on type switch(mType) { case String: if(mString != NULL) { free(mString); mString = NULL; } break; case Map: if(mMap != NULL) { freeMapKeys(); delete mMap; mMap = NULL; } break; case Array: if(mArray != NULL) { delete mArray; mArray = NULL; } break; default: // nothing to cleanup break; } } void DynamicObjectImpl::setString(const char* value) { freeData(); mType = String; mString = strdup(value); } void DynamicObjectImpl::operator=(const char* value) { setString(value); } void DynamicObjectImpl::operator=(bool value) { freeData(); mType = Boolean; mBoolean = value; } void DynamicObjectImpl::operator=(int value) { freeData(); mType = Int32; mInt32 = value; } void DynamicObjectImpl::operator=(unsigned int value) { freeData(); mType = UInt32; mUInt32 = value; } void DynamicObjectImpl::operator=(long long value) { freeData(); mType = Int64; mInt64 = value; } void DynamicObjectImpl::operator=(unsigned long long value) { freeData(); mType = UInt64; mUInt64 = value; } void DynamicObjectImpl::operator=(double value) { freeData(); mType = Double; mDouble = value; } DynamicObject& DynamicObjectImpl::operator[](const char* name) { DynamicObject* rval = NULL; // change to map type if necessary setType(Map); ObjectMap::iterator i = mMap->find(name); if(i == mMap->end()) { // create new map entry DynamicObject dyno; mMap->insert(std::make_pair(strdup(name), dyno)); rval = &(*mMap)[name]; } else { // get existing map entry rval = &i->second; } return *rval; } DynamicObject& DynamicObjectImpl::operator[](int index) { // change to array type if necessary setType(Array); if(index < 0) { index = mArray->size() + index; } // fill the object array as necessary if(index >= (int)mArray->size()) { int i = index - (int)mArray->size() + 1; for(; i > 0; i--) { DynamicObject dyno; mArray->push_back(dyno); } } return (*mArray)[index]; } DynamicObject& DynamicObjectImpl::append() { setType(Array); return (*this)[length()]; } void DynamicObjectImpl::setType(DynamicObjectType type) { if(mType != type) { switch(type) { case String: *this = getString(); break; case Boolean: *this = getBoolean(); break; case Int32: *this = getInt32(); break; case UInt32: *this = getUInt32(); break; case Int64: *this = getInt64(); break; case UInt64: *this = getUInt64(); break; case Double: *this = getDouble(); break; case Map: { freeData(); mType = Map; mMap = new ObjectMap(); } break; case Array: { freeData(); mType = Array; mArray = new ObjectArray(); } break; } } } DynamicObjectType DynamicObjectImpl::getType() { return mType; } const char* DynamicObjectImpl::getString() { const char* rval; if(mType == String) { if(mString != NULL) { // use existing string rval = mString; } else { // only duplicate blank string upon request rval = mString = strdup(""); } } else { // convert type as appropriate switch(mType) { case Boolean: mStringValue = (char*)realloc(mStringValue, 6); snprintf(mStringValue, 6, "%s", (mBoolean ? "true" : "false")); break; case Int32: mStringValue = (char*)realloc(mStringValue, 12); snprintf(mStringValue, 12, "%i", mInt32); break; case UInt32: mStringValue = (char*)realloc(mStringValue, 11); snprintf(mStringValue, 11, "%u", mUInt32); break; case Int64: mStringValue = (char*)realloc(mStringValue, 22); snprintf(mStringValue, 22, "%lli", mInt64); break; case UInt64: mStringValue = (char*)realloc(mStringValue, 21); snprintf(mStringValue, 21, "%llu", mUInt64); break; case Double: // use default precision of 6 // X.000000e+00 = 11 places to right of decimal mStringValue = (char*)realloc(mStringValue, 50); snprintf(mStringValue, 50, "%e", mDouble); break; default: /* Map, Array, ... */ { if(mStringValue == NULL) { // duplicate blank string mStringValue = strdup(""); } else { // set null-terminator to first character mStringValue[0] = 0; } } break; } // return generated value rval = mStringValue; } return rval; } bool DynamicObjectImpl::getBoolean() { bool rval; switch(mType) { case Boolean: rval = mBoolean; break; case String: rval = (mString == NULL) ? false : (strcmp(mString, "true") == 0); break; case Int32: rval = (mInt32 == 1); break; case UInt32: rval = (mUInt32 == 1); break; case Int64: rval = (mInt64 == 1); break; case UInt64: rval = (mUInt64 == 1); break; case Double: rval = (mDouble == 1); break; default: rval = false; break; } return rval; } int DynamicObjectImpl::getInt32() { int rval; switch(mType) { case Int32: rval = mInt32; break; case String: rval = (mString == NULL) ? 0 : strtol(mString, NULL, 10); break; case Boolean: rval = mBoolean ? 1 : 0; break; case UInt32: rval = (int)mUInt32; break; case Int64: rval = (int)mInt64; break; case UInt64: rval = (int)mUInt64; break; case Double: rval = (int)mDouble; break; default: rval = 0; break; } return rval; } unsigned int DynamicObjectImpl::getUInt32() { unsigned int rval; switch(mType) { case UInt32: rval = mUInt32; break; case String: rval = (mString == NULL) ? 0 : strtoul(mString, NULL, 10); break; case Boolean: rval = mBoolean ? 1 : 0; break; case Int32: rval = (mInt32 < 0) ? 0 : mInt32; break; case Int64: rval = (mInt64 < 0) ? 0 : (unsigned int)mInt64; break; case UInt64: rval = (unsigned int)mUInt64; break; case Double: rval = (unsigned int)mDouble; break; default: rval = 0; break; } return rval; } long long DynamicObjectImpl::getInt64() { long long rval; switch(mType) { case Int64: rval = mInt64; break; case String: rval = (mString == NULL) ? 0 : strtoll(mString, NULL, 10); break; case Boolean: rval = mBoolean ? 1 : 0; break; case Int32: rval = mInt32; break; case UInt32: rval = mUInt32; break; case UInt64: rval = (long long)mUInt64; break; case Double: rval = (long long)mDouble; break; default: rval = 0; break; } return rval; } unsigned long long DynamicObjectImpl::getUInt64() { unsigned long long rval; switch(mType) { case UInt64: rval = mUInt64; break; case String: rval = (mString == NULL) ? 0 : strtoull(mString, NULL, 10); break; case Boolean: rval = mBoolean ? 1 : 0; break; case Int32: rval = (mInt32 < 0) ? 0 : mInt32; break; case UInt32: rval = mUInt32; break; case Int64: rval = (mInt64 < 0) ? 0 : mInt64; break; case Double: rval = (unsigned long long)mDouble; break; default: rval = 0; break; } return rval; } double DynamicObjectImpl::getDouble() { double rval; switch(mType) { case Double: rval = mDouble; break; case String: rval = (mString == NULL) ? 0 : strtod(mString, NULL); break; case Boolean: rval = mBoolean ? 1 : 0; break; case Int32: rval = mInt32; break; case UInt32: rval = mUInt32; break; case Int64: rval = mInt64; break; case UInt64: rval = mUInt64; break; default: rval = 0; break; } return rval; } bool DynamicObjectImpl::hasMember(const char* name) { bool rval = false; if(mType == Map) { ObjectMap::iterator i = mMap->find(name); rval = (i != mMap->end()); } return rval; } DynamicObject DynamicObjectImpl::removeMember(const char* name) { DynamicObject rval(NULL); if(mType == Map) { ObjectMap::iterator i = mMap->find(name); if(i != mMap->end()) { // clean up key and remove map entry free((char*)i->first); rval = i->second; mMap->erase(i); } } return rval; } void DynamicObjectImpl::clear() { switch(mType) { case String: *this = ""; break; case Boolean: *this = false; break; case Int32: *this = (int)0; break; case UInt32: *this = (unsigned int)0; break; case Int64: *this = (long long)0; break; case UInt64: *this = (unsigned long long)0; break; case Double: *this = (double)0.0; break; case Map: freeMapKeys(); mMap->clear(); break; case Array: mArray->clear(); break; } } int DynamicObjectImpl::length() { int rval = 0; switch(mType) { case String: if(mString != NULL) { rval = strlen(getString()); } break; case Boolean: rval = 1; break; case Int32: case UInt32: rval = sizeof(unsigned int); break; case Int64: case UInt64: rval = sizeof(unsigned long long); break; case Double: rval = sizeof(double); break; case Map: rval = mMap->size(); break; case Array: rval = mArray->size(); break; } return rval; } <|endoftext|>
<commit_before>/** * << detailed description >> * * @file SingleCPUTestParticleData.cpp * @brief << brief description >> * @author clonker * @date 07.06.16 */ #include <gtest/gtest.h> #include <readdy/common/make_unique.h> #include <readdy/kernel/singlecpu/model/SingleCPUParticleData.h> #include <boost/log/trivial.hpp> using namespace readdy::kernel::singlecpu::model; TEST(ParticleData, initialization) { // everything should be deactivated auto data = std::make_unique<SingleCPUParticleData>(10); for (size_t i = 0; i < 10; i++) { EXPECT_TRUE(data->isDeactivated(i)); } } TEST(ParticleData, additionOfParticles) { // initial capacity of 3 auto data = std::make_unique<SingleCPUParticleData>(3); EXPECT_TRUE(data->getNDeactivated() == 3); data->addParticle({1, 1, 1, 5}); EXPECT_TRUE(data->getNDeactivated() == 2); data->addParticle({2, 2, 2, 6}); EXPECT_TRUE(data->getNDeactivated() == 1); data->addParticle({3, 3, 3, 7}); EXPECT_TRUE(data->getNDeactivated() == 0); data->addParticle({4, 4, 4, 8}); EXPECT_TRUE(data->getNDeactivated() == 0); int i = 0; for (auto &&it = data->begin_positions(); it != data->end_positions(); ++it) { i++; EXPECT_TRUE(*it == readdy::model::Vec3(i, i, i)); } i = 5; for (auto &&it = data->begin_types(); it != data->end_types(); ++it) { EXPECT_TRUE((*it) == i); i++; } } TEST(ParticleData, removalOfParticles) { auto data = std::make_unique<SingleCPUParticleData>(5); EXPECT_TRUE(data->getNDeactivated()== 5); for (auto &&i = 0; i < 100; i++) { data->addParticle({(double) i, (double) i, (double) i, 5}); } EXPECT_TRUE(data->size() == 100); EXPECT_TRUE(data->getNDeactivated() == 0); int i = 0; for (auto &&it = data->begin_positions(); it != data->end_positions(); ++it) { EXPECT_TRUE(*it == readdy::model::Vec3(i, i, i)); i++; } data->removeParticle(2); EXPECT_TRUE(data->size() == 99); EXPECT_TRUE(data->getNDeactivated() == 1); //EXPECT_TRUE(*data->getDeactivatedParticles()->begin() == 2); // we expect an offset by 1 for every particle that comes after the 3rd EXPECT_TRUE(*(data->begin_positions() + 10) == readdy::model::Vec3(10, 10, 10)); EXPECT_TRUE(*(data->begin_positions() + 1) == readdy::model::Vec3(1, 1, 1)); EXPECT_TRUE(*(data->begin_positions() + 2) == readdy::model::Vec3(99, 99, 99)); // take up the space again data->addParticle({.5, .5, .5, 1}); EXPECT_TRUE(data->size() == 100); EXPECT_TRUE(data->getNDeactivated() == 0); EXPECT_TRUE(*(data->end_positions()) == readdy::model::Vec3(.5, .5, .5)); } TEST(ParticleData, empty) { auto data = std::make_unique<SingleCPUParticleData>(3); EXPECT_TRUE(data->empty()); data->addParticle({4, 4, 4, 4}); EXPECT_FALSE(data->empty()); }<commit_msg>[singlecpu/particledata iterator] fixed test<commit_after>/** * << detailed description >> * * @file SingleCPUTestParticleData.cpp * @brief << brief description >> * @author clonker * @date 07.06.16 */ #include <gtest/gtest.h> #include <readdy/common/make_unique.h> #include <readdy/kernel/singlecpu/model/SingleCPUParticleData.h> #include <boost/log/trivial.hpp> using namespace readdy::kernel::singlecpu::model; TEST(ParticleData, initialization) { // everything should be deactivated auto data = std::make_unique<SingleCPUParticleData>(10); for (size_t i = 0; i < 10; i++) { EXPECT_TRUE(data->isDeactivated(i)); } } TEST(ParticleData, additionOfParticles) { // initial capacity of 3 auto data = std::make_unique<SingleCPUParticleData>(3); EXPECT_TRUE(data->getNDeactivated() == 3); data->addParticle({1, 1, 1, 5}); EXPECT_TRUE(data->getNDeactivated() == 2); data->addParticle({2, 2, 2, 6}); EXPECT_TRUE(data->getNDeactivated() == 1); data->addParticle({3, 3, 3, 7}); EXPECT_TRUE(data->getNDeactivated() == 0); data->addParticle({4, 4, 4, 8}); EXPECT_TRUE(data->getNDeactivated() == 0); int i = 0; for (auto &&it = data->begin_positions(); it != data->end_positions(); ++it) { i++; EXPECT_TRUE(*it == readdy::model::Vec3(i, i, i)); } i = 5; for (auto &&it = data->begin_types(); it != data->end_types(); ++it) { EXPECT_TRUE((*it) == i); i++; } } TEST(ParticleData, removalOfParticles) { unsigned int n_particles = 15; auto data = std::make_unique<SingleCPUParticleData>(5); EXPECT_TRUE(data->getNDeactivated()== 5); for (auto &&i = 0; i < n_particles; i++) { data->addParticle({(double) i, (double) i, (double) i, 5}); } EXPECT_TRUE(data->size() == n_particles); EXPECT_TRUE(data->getNDeactivated() == 0); int i = 0; for (auto &&it = data->begin_positions(); it != data->end_positions(); ++it) { EXPECT_TRUE(*it == readdy::model::Vec3(i, i, i)); i++; } data->removeParticle(2); EXPECT_TRUE(data->size() == n_particles-1); EXPECT_TRUE(data->getNDeactivated() == 1); //EXPECT_TRUE(*data->getDeactivatedParticles()->begin() == 2); // we expect an offset by 1 for every particle that comes after the 3rd EXPECT_TRUE(*(data->begin_positions() + 10) == readdy::model::Vec3(10, 10, 10)); EXPECT_TRUE(*(data->begin_positions() + 1) == readdy::model::Vec3(1, 1, 1)); EXPECT_TRUE(*(data->begin_positions() + 2) == readdy::model::Vec3(n_particles-1, n_particles-1, n_particles-1)); // take up the space again data->addParticle({.5, .5, .5, 1}); EXPECT_TRUE(data->size() == n_particles); EXPECT_TRUE(data->getNDeactivated() == 0); EXPECT_TRUE(*(data->end_positions() - 1) == readdy::model::Vec3(.5, .5, .5)); } TEST(ParticleData, empty) { auto data = std::make_unique<SingleCPUParticleData>(3); EXPECT_TRUE(data->empty()); data->addParticle({4, 4, 4, 4}); EXPECT_FALSE(data->empty()); }<|endoftext|>
<commit_before>/// \file stream.cpp /// Utilities for handling streams. #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <semaphore.h> #include "json.h" #include "stream.h" #include "procs.h" #include "config.h" #include "socket.h" #include "defines.h" #include "shared_memory.h" #include "dtsc.h" std::string Util::getTmpFolder() { std::string dir; char * tmp_char = 0; if (!tmp_char) { tmp_char = getenv("TMP"); } if (!tmp_char) { tmp_char = getenv("TEMP"); } if (!tmp_char) { tmp_char = getenv("TMPDIR"); } if (tmp_char) { dir = tmp_char; dir += "/mist"; } else { #if defined(_WIN32) || defined(_CYGWIN_) dir = "C:/tmp/mist"; #else dir = "/tmp/mist"; #endif } if (access(dir.c_str(), 0) != 0) { mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); //attempt to create mist folder - ignore failures } return dir + "/"; } /// Filters the streamname, removing invalid characters and converting all /// letters to lowercase. If a '?' character is found, everything following /// that character is deleted. The original string is modified. If a '+' or space /// exists, then only the part before that is sanitized. void Util::sanitizeName(std::string & streamname) { //strip anything that isn't numbers, digits or underscores size_t index = streamname.find_first_of("+ "); if(index != std::string::npos){ std::string preplus = streamname.substr(0,index); sanitizeName(preplus); std::string postplus = streamname.substr(index+1); if (postplus.find('?') != std::string::npos){ postplus = postplus.substr(0, (postplus.find('?'))); } streamname = preplus+"+"+postplus; return; } for (std::string::iterator i = streamname.end() - 1; i >= streamname.begin(); --i) { if (*i == '?') { streamname.erase(i, streamname.end()); break; } if ( !isalpha( *i) && !isdigit( *i) && *i != '_' && *i != '.'){ streamname.erase(i); } else { *i = tolower(*i); } } } JSON::Value Util::getStreamConfig(std::string streamname){ JSON::Value result; if (streamname.size() > 100){ FAIL_MSG("Stream opening denied: %s is longer than 100 characters (%lu).", streamname.c_str(), streamname.size()); return result; } IPC::sharedPage mistConfOut(SHM_CONF, DEFAULT_CONF_PAGE_SIZE, false, false); IPC::semaphore configLock(SEM_CONF, O_CREAT | O_RDWR, ACCESSPERMS, 1); configLock.wait(); DTSC::Scan config = DTSC::Scan(mistConfOut.mapped, mistConfOut.len); sanitizeName(streamname); std::string smp = streamname.substr(0, streamname.find_first_of("+ ")); //check if smp (everything before + or space) exists DTSC::Scan stream_cfg = config.getMember("streams").getMember(smp); if (!stream_cfg){ DEBUG_MSG(DLVL_MEDIUM, "Stream %s not configured", streamname.c_str()); }else{ result = stream_cfg.asJSON(); } configLock.post();//unlock the config semaphore return result; } /// Checks if the given streamname has an active input serving it. Returns true if this is the case. /// Assumes the streamname has already been through sanitizeName()! bool Util::streamAlive(std::string & streamname){ char semName[NAME_BUFFER_SIZE]; snprintf(semName, NAME_BUFFER_SIZE, SEM_INPUT, streamname.c_str()); IPC::semaphore playerLock(semName, O_RDWR, ACCESSPERMS, 1, true); if (!playerLock){return false;} if (!playerLock.tryWait()) { playerLock.close(); return true; }else{ playerLock.post(); playerLock.close(); return false; } } /// Assures the input for the given stream name is active. /// Does stream name sanitation first, followed by a stream name length check (<= 100 chars). /// Then, checks if an input is already active by running streamAlive(). If yes, return true. /// If no, loads up the server configuration and attempts to start the given stream according to current configuration. /// At this point, fails and aborts if MistController isn't running. bool Util::startInput(std::string streamname, std::string filename, bool forkFirst, bool isProvider) { sanitizeName(streamname); if (streamname.size() > 100){ FAIL_MSG("Stream opening denied: %s is longer than 100 characters (%lu).", streamname.c_str(), streamname.size()); return false; } //Check if the stream is already active. //If yes, don't activate again to prevent duplicate inputs. //It's still possible a duplicate starts anyway, this is caught in the inputs initializer. //Note: this uses the _whole_ stream name, including + (if any). //This means "test+a" and "test+b" have separate locks and do not interact with each other. if (streamAlive(streamname)){ DEBUG_MSG(DLVL_MEDIUM, "Stream %s already active; continuing", streamname.c_str()); return true; } //Attempt to load up configuration and find this stream IPC::sharedPage mistConfOut(SHM_CONF, DEFAULT_CONF_PAGE_SIZE); IPC::semaphore configLock(SEM_CONF, O_CREAT | O_RDWR, ACCESSPERMS, 1); //Lock the config to prevent race conditions and corruption issues while reading configLock.wait(); DTSC::Scan config = DTSC::Scan(mistConfOut.mapped, mistConfOut.len); //Abort if no config available if (!config){ FAIL_MSG("Configuration not available, aborting! Is MistController running?"); configLock.post();//unlock the config semaphore return false; } //Find stream base name std::string smp = streamname.substr(0, streamname.find_first_of("+ ")); //check if base name (everything before + or space) exists DTSC::Scan stream_cfg = config.getMember("streams").getMember(smp); if (!stream_cfg){ DEBUG_MSG(DLVL_HIGH, "Stream %s not configured - attempting to ignore", streamname.c_str()); } //Only use configured source if not manually overridden. Abort if no config is available. if (!filename.size()){ if (!stream_cfg){ DEBUG_MSG(DLVL_MEDIUM, "Stream %s not configured, no source manually given, cannot start", streamname.c_str()); configLock.post();//unlock the config semaphore return false; } filename = stream_cfg.getMember("source").asString(); } //check in curConf for capabilities-inputs-<naam>-priority/source_match std::string player_bin; bool selected = false; long long int curPrio = -1; DTSC::Scan inputs = config.getMember("capabilities").getMember("inputs"); DTSC::Scan input; unsigned int input_size = inputs.getSize(); bool noProviderNoPick = false; for (unsigned int i = 0; i < input_size; ++i){ DTSC::Scan tmp_input = inputs.getIndice(i); //if match voor current stream && priority is hoger dan wat we al hebben if (tmp_input.getMember("source_match") && curPrio < tmp_input.getMember("priority").asInt()){ if (tmp_input.getMember("source_match").getSize()){ for(unsigned int j = 0; j < tmp_input.getMember("source_match").getSize(); ++j){ std::string source = tmp_input.getMember("source_match").getIndice(j).asString(); std::string front = source.substr(0,source.find('*')); std::string back = source.substr(source.find('*')+1); MEDIUM_MSG("Checking input %s: %s (%s)", inputs.getIndiceName(i).c_str(), tmp_input.getMember("name").asString().c_str(), source.c_str()); if (filename.substr(0,front.size()) == front && filename.substr(filename.size()-back.size()) == back){ if (tmp_input.getMember("non-provider") && !isProvider){ noProviderNoPick = true; continue; } player_bin = Util::getMyPath() + "MistIn" + tmp_input.getMember("name").asString(); curPrio = tmp_input.getMember("priority").asInt(); selected = true; input = tmp_input; } } }else{ std::string source = tmp_input.getMember("source_match").asString(); std::string front = source.substr(0,source.find('*')); std::string back = source.substr(source.find('*')+1); MEDIUM_MSG("Checking input %s: %s (%s)", inputs.getIndiceName(i).c_str(), tmp_input.getMember("name").asString().c_str(), source.c_str()); if (filename.substr(0,front.size()) == front && filename.substr(filename.size()-back.size()) == back){ if (tmp_input.getMember("non-provider") && !isProvider){ noProviderNoPick = true; continue; } player_bin = Util::getMyPath() + "MistIn" + tmp_input.getMember("name").asString(); curPrio = tmp_input.getMember("priority").asInt(); selected = true; input = tmp_input; } } } } if (!selected){ configLock.post();//unlock the config semaphore if (noProviderNoPick){ INFO_MSG("Not a media provider for stream %s: %s", streamname.c_str(), filename.c_str()); }else{ FAIL_MSG("No compatible input found for stream %s: %s", streamname.c_str(), filename.c_str()); } return false; } //copy the necessary arguments to separate storage so we can unlock the config semaphore safely std::map<std::string, std::string> str_args; //check required parameters DTSC::Scan required = input.getMember("required"); unsigned int req_size = required.getSize(); for (unsigned int i = 0; i < req_size; ++i){ std::string opt = required.getIndiceName(i); if (!stream_cfg.getMember(opt)){ configLock.post();//unlock the config semaphore FAIL_MSG("Required parameter %s for stream %s missing", opt.c_str(), streamname.c_str()); return false; } str_args[required.getIndice(i).getMember("option").asString()] = stream_cfg.getMember(opt).asString(); } //check optional parameters DTSC::Scan optional = input.getMember("optional"); unsigned int opt_size = optional.getSize(); for (unsigned int i = 0; i < opt_size; ++i){ std::string opt = optional.getIndiceName(i); VERYHIGH_MSG("Checking optional %u: %s", i, opt.c_str()); if (stream_cfg.getMember(opt)){ str_args[optional.getIndice(i).getMember("option").asString()] = stream_cfg.getMember(opt).asString(); } } //finally, unlock the config semaphore configLock.post(); INFO_MSG("Starting %s -s %s %s", player_bin.c_str(), streamname.c_str(), filename.c_str()); char * argv[30] = {(char *)player_bin.c_str(), (char *)"-s", (char *)streamname.c_str(), (char *)filename.c_str()}; int argNum = 3; std::string debugLvl; if (Util::Config::printDebugLevel != DEBUG && !str_args.count("--debug")){ debugLvl = JSON::Value((long long)Util::Config::printDebugLevel).asString(); argv[++argNum] = (char *)"--debug"; argv[++argNum] = (char *)debugLvl.c_str(); } for (std::map<std::string, std::string>::iterator it = str_args.begin(); it != str_args.end(); ++it){ argv[++argNum] = (char *)it->first.c_str(); argv[++argNum] = (char *)it->second.c_str(); INFO_MSG(" Option %s = %s", it->first.c_str(), it->second.c_str()); } argv[++argNum] = (char *)0; int pid = 0; if (forkFirst){ DEBUG_MSG(DLVL_DONTEVEN, "Forking"); pid = fork(); if (pid == -1) { FAIL_MSG("Forking process for stream %s failed: %s", streamname.c_str(), strerror(errno)); return false; } if (pid && filename.substr(0, 21) == "push://INTERNAL_ONLY:"){ Util::Procs::setHandler(); Util::Procs::remember(pid); } }else{ DEBUG_MSG(DLVL_DONTEVEN, "Not forking"); } if (pid == 0){ Socket::Connection io(0, 1); io.close(); DEBUG_MSG(DLVL_DONTEVEN, "execvp"); execvp(argv[0], argv); FAIL_MSG("Starting process %s for stream %s failed: %s", argv[0], streamname.c_str(), strerror(errno)); _exit(42); } unsigned int waiting = 0; while (!streamAlive(streamname) && ++waiting < 40){ Util::wait(250); } return streamAlive(streamname); } uint8_t Util::getStreamStatus(const std::string & streamname){ char pageName[NAME_BUFFER_SIZE]; snprintf(pageName, NAME_BUFFER_SIZE, SHM_STREAM_STATE, streamname.c_str()); IPC::sharedPage streamStatus(pageName, 1, false, false); if (!streamStatus){return STRMSTAT_OFF;} return streamStatus.mapped[0]; } <commit_msg>Fixed stream connect during shutdown<commit_after>/// \file stream.cpp /// Utilities for handling streams. #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <semaphore.h> #include "json.h" #include "stream.h" #include "procs.h" #include "config.h" #include "socket.h" #include "defines.h" #include "shared_memory.h" #include "dtsc.h" std::string Util::getTmpFolder() { std::string dir; char * tmp_char = 0; if (!tmp_char) { tmp_char = getenv("TMP"); } if (!tmp_char) { tmp_char = getenv("TEMP"); } if (!tmp_char) { tmp_char = getenv("TMPDIR"); } if (tmp_char) { dir = tmp_char; dir += "/mist"; } else { #if defined(_WIN32) || defined(_CYGWIN_) dir = "C:/tmp/mist"; #else dir = "/tmp/mist"; #endif } if (access(dir.c_str(), 0) != 0) { mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); //attempt to create mist folder - ignore failures } return dir + "/"; } /// Filters the streamname, removing invalid characters and converting all /// letters to lowercase. If a '?' character is found, everything following /// that character is deleted. The original string is modified. If a '+' or space /// exists, then only the part before that is sanitized. void Util::sanitizeName(std::string & streamname) { //strip anything that isn't numbers, digits or underscores size_t index = streamname.find_first_of("+ "); if(index != std::string::npos){ std::string preplus = streamname.substr(0,index); sanitizeName(preplus); std::string postplus = streamname.substr(index+1); if (postplus.find('?') != std::string::npos){ postplus = postplus.substr(0, (postplus.find('?'))); } streamname = preplus+"+"+postplus; return; } for (std::string::iterator i = streamname.end() - 1; i >= streamname.begin(); --i) { if (*i == '?') { streamname.erase(i, streamname.end()); break; } if ( !isalpha( *i) && !isdigit( *i) && *i != '_' && *i != '.'){ streamname.erase(i); } else { *i = tolower(*i); } } } JSON::Value Util::getStreamConfig(std::string streamname){ JSON::Value result; if (streamname.size() > 100){ FAIL_MSG("Stream opening denied: %s is longer than 100 characters (%lu).", streamname.c_str(), streamname.size()); return result; } IPC::sharedPage mistConfOut(SHM_CONF, DEFAULT_CONF_PAGE_SIZE, false, false); IPC::semaphore configLock(SEM_CONF, O_CREAT | O_RDWR, ACCESSPERMS, 1); configLock.wait(); DTSC::Scan config = DTSC::Scan(mistConfOut.mapped, mistConfOut.len); sanitizeName(streamname); std::string smp = streamname.substr(0, streamname.find_first_of("+ ")); //check if smp (everything before + or space) exists DTSC::Scan stream_cfg = config.getMember("streams").getMember(smp); if (!stream_cfg){ DEBUG_MSG(DLVL_MEDIUM, "Stream %s not configured", streamname.c_str()); }else{ result = stream_cfg.asJSON(); } configLock.post();//unlock the config semaphore return result; } /// Checks if the given streamname has an active input serving it. Returns true if this is the case. /// Assumes the streamname has already been through sanitizeName()! bool Util::streamAlive(std::string & streamname){ char semName[NAME_BUFFER_SIZE]; snprintf(semName, NAME_BUFFER_SIZE, SEM_INPUT, streamname.c_str()); IPC::semaphore playerLock(semName, O_RDWR, ACCESSPERMS, 1, true); if (!playerLock){return false;} if (!playerLock.tryWait()) { playerLock.close(); return true; }else{ playerLock.post(); playerLock.close(); return false; } } /// Assures the input for the given stream name is active. /// Does stream name sanitation first, followed by a stream name length check (<= 100 chars). /// Then, checks if an input is already active by running streamAlive(). If yes, return true. /// If no, loads up the server configuration and attempts to start the given stream according to current configuration. /// At this point, fails and aborts if MistController isn't running. bool Util::startInput(std::string streamname, std::string filename, bool forkFirst, bool isProvider) { sanitizeName(streamname); if (streamname.size() > 100){ FAIL_MSG("Stream opening denied: %s is longer than 100 characters (%lu).", streamname.c_str(), streamname.size()); return false; } //Check if the stream is already active. //If yes, don't activate again to prevent duplicate inputs. //It's still possible a duplicate starts anyway, this is caught in the inputs initializer. //Note: this uses the _whole_ stream name, including + (if any). //This means "test+a" and "test+b" have separate locks and do not interact with each other. if (streamAlive(streamname)){ uint8_t streamStat = getStreamStatus(streamname); while (streamStat == STRMSTAT_SHUTDOWN){ Util::sleep(250); streamStat = getStreamStatus(streamname); } if (streamStat != STRMSTAT_OFF){ DEBUG_MSG(DLVL_MEDIUM, "Stream %s already active; continuing", streamname.c_str()); return true; } } //Attempt to load up configuration and find this stream IPC::sharedPage mistConfOut(SHM_CONF, DEFAULT_CONF_PAGE_SIZE); IPC::semaphore configLock(SEM_CONF, O_CREAT | O_RDWR, ACCESSPERMS, 1); //Lock the config to prevent race conditions and corruption issues while reading configLock.wait(); DTSC::Scan config = DTSC::Scan(mistConfOut.mapped, mistConfOut.len); //Abort if no config available if (!config){ FAIL_MSG("Configuration not available, aborting! Is MistController running?"); configLock.post();//unlock the config semaphore return false; } //Find stream base name std::string smp = streamname.substr(0, streamname.find_first_of("+ ")); //check if base name (everything before + or space) exists DTSC::Scan stream_cfg = config.getMember("streams").getMember(smp); if (!stream_cfg){ DEBUG_MSG(DLVL_HIGH, "Stream %s not configured - attempting to ignore", streamname.c_str()); } //Only use configured source if not manually overridden. Abort if no config is available. if (!filename.size()){ if (!stream_cfg){ DEBUG_MSG(DLVL_MEDIUM, "Stream %s not configured, no source manually given, cannot start", streamname.c_str()); configLock.post();//unlock the config semaphore return false; } filename = stream_cfg.getMember("source").asString(); } //check in curConf for capabilities-inputs-<naam>-priority/source_match std::string player_bin; bool selected = false; long long int curPrio = -1; DTSC::Scan inputs = config.getMember("capabilities").getMember("inputs"); DTSC::Scan input; unsigned int input_size = inputs.getSize(); bool noProviderNoPick = false; for (unsigned int i = 0; i < input_size; ++i){ DTSC::Scan tmp_input = inputs.getIndice(i); //if match voor current stream && priority is hoger dan wat we al hebben if (tmp_input.getMember("source_match") && curPrio < tmp_input.getMember("priority").asInt()){ if (tmp_input.getMember("source_match").getSize()){ for(unsigned int j = 0; j < tmp_input.getMember("source_match").getSize(); ++j){ std::string source = tmp_input.getMember("source_match").getIndice(j).asString(); std::string front = source.substr(0,source.find('*')); std::string back = source.substr(source.find('*')+1); MEDIUM_MSG("Checking input %s: %s (%s)", inputs.getIndiceName(i).c_str(), tmp_input.getMember("name").asString().c_str(), source.c_str()); if (filename.substr(0,front.size()) == front && filename.substr(filename.size()-back.size()) == back){ if (tmp_input.getMember("non-provider") && !isProvider){ noProviderNoPick = true; continue; } player_bin = Util::getMyPath() + "MistIn" + tmp_input.getMember("name").asString(); curPrio = tmp_input.getMember("priority").asInt(); selected = true; input = tmp_input; } } }else{ std::string source = tmp_input.getMember("source_match").asString(); std::string front = source.substr(0,source.find('*')); std::string back = source.substr(source.find('*')+1); MEDIUM_MSG("Checking input %s: %s (%s)", inputs.getIndiceName(i).c_str(), tmp_input.getMember("name").asString().c_str(), source.c_str()); if (filename.substr(0,front.size()) == front && filename.substr(filename.size()-back.size()) == back){ if (tmp_input.getMember("non-provider") && !isProvider){ noProviderNoPick = true; continue; } player_bin = Util::getMyPath() + "MistIn" + tmp_input.getMember("name").asString(); curPrio = tmp_input.getMember("priority").asInt(); selected = true; input = tmp_input; } } } } if (!selected){ configLock.post();//unlock the config semaphore if (noProviderNoPick){ INFO_MSG("Not a media provider for stream %s: %s", streamname.c_str(), filename.c_str()); }else{ FAIL_MSG("No compatible input found for stream %s: %s", streamname.c_str(), filename.c_str()); } return false; } //copy the necessary arguments to separate storage so we can unlock the config semaphore safely std::map<std::string, std::string> str_args; //check required parameters DTSC::Scan required = input.getMember("required"); unsigned int req_size = required.getSize(); for (unsigned int i = 0; i < req_size; ++i){ std::string opt = required.getIndiceName(i); if (!stream_cfg.getMember(opt)){ configLock.post();//unlock the config semaphore FAIL_MSG("Required parameter %s for stream %s missing", opt.c_str(), streamname.c_str()); return false; } str_args[required.getIndice(i).getMember("option").asString()] = stream_cfg.getMember(opt).asString(); } //check optional parameters DTSC::Scan optional = input.getMember("optional"); unsigned int opt_size = optional.getSize(); for (unsigned int i = 0; i < opt_size; ++i){ std::string opt = optional.getIndiceName(i); VERYHIGH_MSG("Checking optional %u: %s", i, opt.c_str()); if (stream_cfg.getMember(opt)){ str_args[optional.getIndice(i).getMember("option").asString()] = stream_cfg.getMember(opt).asString(); } } //finally, unlock the config semaphore configLock.post(); INFO_MSG("Starting %s -s %s %s", player_bin.c_str(), streamname.c_str(), filename.c_str()); char * argv[30] = {(char *)player_bin.c_str(), (char *)"-s", (char *)streamname.c_str(), (char *)filename.c_str()}; int argNum = 3; std::string debugLvl; if (Util::Config::printDebugLevel != DEBUG && !str_args.count("--debug")){ debugLvl = JSON::Value((long long)Util::Config::printDebugLevel).asString(); argv[++argNum] = (char *)"--debug"; argv[++argNum] = (char *)debugLvl.c_str(); } for (std::map<std::string, std::string>::iterator it = str_args.begin(); it != str_args.end(); ++it){ argv[++argNum] = (char *)it->first.c_str(); argv[++argNum] = (char *)it->second.c_str(); INFO_MSG(" Option %s = %s", it->first.c_str(), it->second.c_str()); } argv[++argNum] = (char *)0; int pid = 0; if (forkFirst){ DEBUG_MSG(DLVL_DONTEVEN, "Forking"); pid = fork(); if (pid == -1) { FAIL_MSG("Forking process for stream %s failed: %s", streamname.c_str(), strerror(errno)); return false; } if (pid && filename.substr(0, 21) == "push://INTERNAL_ONLY:"){ Util::Procs::setHandler(); Util::Procs::remember(pid); } }else{ DEBUG_MSG(DLVL_DONTEVEN, "Not forking"); } if (pid == 0){ Socket::Connection io(0, 1); io.close(); DEBUG_MSG(DLVL_DONTEVEN, "execvp"); execvp(argv[0], argv); FAIL_MSG("Starting process %s for stream %s failed: %s", argv[0], streamname.c_str(), strerror(errno)); _exit(42); } unsigned int waiting = 0; while (!streamAlive(streamname) && ++waiting < 40){ Util::wait(250); } return streamAlive(streamname); } uint8_t Util::getStreamStatus(const std::string & streamname){ char pageName[NAME_BUFFER_SIZE]; snprintf(pageName, NAME_BUFFER_SIZE, SHM_STREAM_STATE, streamname.c_str()); IPC::sharedPage streamStatus(pageName, 1, false, false); if (!streamStatus){return STRMSTAT_OFF;} return streamStatus.mapped[0]; } <|endoftext|>
<commit_before>#ifndef VARIADIC_HPP #define VARIADIC_HPP #include <type_traits> /// Cobalt template library namespace ctl { template<typename T, typename ... Args> struct is_any_of; template<typename T, typename U, typename ... Args> struct is_any_of<T, U, Args...> { static const bool value = std::is_same<T, U>::value || is_any_of<T, Args...>::value; }; template<typename T, typename U> struct is_any_of<T, U> { static const bool value = std::is_same<T, U>::value; }; struct separator {}; template<typename ... Args> struct head_t; template<typename T, typename ... Args> struct head_t<T, Args...> { using type = T; }; template<typename ... Args> using head = typename head_t<Args...>::type; template<typename ... Args> struct tail_t; template<typename T> struct tail_t<T> { using type = T; }; template<typename T, typename ... Args> struct tail_t<T, Args...> { using type = typename tail_t<Args...>::type; }; template<typename ... Args> using tail = typename tail_t<Args...>::type; template<typename ... Args> struct type_list; template<typename ... Args> struct type_list_popf_t; template<typename T, typename ... Args> struct type_list_popf_t<T, Args...> { using type = type_list<Args...>; }; template<typename ... Args> struct type_list_popb_t; template<typename T> struct type_list_popb_t<T> { using type = T; }; template<typename T, typename ... Args> struct type_list_popb_t<T, Args...> { using type = typename type_list_popb_t<Args...>::type; }; template<> struct type_list<> { template<typename V> using push_front_t = type_list<V>; template<typename V> using push_back_t = type_list<V>; template<typename V> push_front_t<V> push_front() { return push_front_t<V>(); } template<typename V> push_back_t<V> push_back() { return push_back_t<V>(); } }; template<typename T> struct type_list<T> { template<typename V> using push_front_t = type_list<V, T>; template<typename V> using push_back_t = type_list<T, V>; using pop_front_t = type_list<>; using pop_back_t = type_list<>; using front_t = T; using back_t = T; template<typename V> push_front_t<V> push_front() { return push_front_t<V>(); } template<typename V> push_back_t<V> push_back() { return push_back_t<V>(); } pop_front_t pop_front() { return pop_front_t(); } pop_back_t pop_back() { return pop_back_t(); } }; template<typename ... Args> struct type_list { template<typename V> using push_front_t = type_list<V, Args...>; template<typename V> using push_back_t = type_list<Args..., V>; using pop_front_t = typename type_list_popf_t<Args...>::type; using pop_back_t = typename type_list_popb_t<Args...>::type; using front_t = head<Args...>; using back_t = tail<Args...>; template<typename V> push_front_t<V> push_front() { return push_front_t<V>(); } template<typename V> push_back_t<V> push_back() { return push_back_t<V>(); } pop_front_t pop_front() { return pop_front_t(); } pop_back_t pop_back() { return pop_back_t(); } }; template<std::size_t N, typename T, typename ... Args> struct type_list_element__t { using type = typename type_list_element__t<N-1, Args...>::type; }; template<typename T, typename ... Args> struct type_list_element__t<0, T, Args...> { using type = T; }; template<std::size_t N, typename T> struct type_list_element_t; template<std::size_t N, typename ... Args> struct type_list_element_t<N, type_list<Args...>> { using type = typename type_list_element__t<N, Args...>::type; }; template<std::size_t N, typename T> using type_list_element = typename type_list_element_t<N, T>::type; template<typename T> struct type_list_size; template<typename ... Args> struct type_list_size<type_list<Args...>> { static const std::size_t value = sizeof...(Args); }; template<typename Pack1, typename Pack2> struct are_convertible; template<typename T1, typename T2,typename ... Args1, typename ... Args2> struct are_convertible<type_list<T1, Args1...>, type_list<T2, Args2...>> { static const bool value = std::is_convertible<T1,T2>::value && are_convertible<type_list<Args1...>, type_list<Args2...>>::value; }; template<> struct are_convertible<type_list<>, type_list<>> { static const bool value = true; }; template<typename T> struct type_holder { using type = T; }; template<typename T> struct type_holder_get_type; template<typename T> struct type_holder_get_type<type_holder<T>> { using type = T; }; template<typename T> struct function_arguments_t; template<typename R, typename T, typename ... Args> struct function_arguments_t<R (T::*)(Args...)> { using type = type_list<Args...>; }; template<typename R, typename T, typename ... Args> struct function_arguments_t<R (T::*)(Args...) const> { using type = type_list<Args...>; }; template<typename T> using function_arguments = typename function_arguments_t<T>::type; template<typename T> using functor_arguments = function_arguments<decltype(&T::operator())>; template<typename T> struct function_argument_t; template<typename R, typename T, typename Arg> struct function_argument_t<R (T::*)(Arg)> { using type = Arg; }; template<typename R, typename T, typename Arg> struct function_argument_t<R (T::*)(Arg) const> { using type = Arg; }; template<typename T> using function_argument = typename function_argument_t<T>::type; template<typename T> using functor_argument = function_argument<decltype(&T::operator())>; template<typename T> struct argument_count { static const std::size_t value = argument_count<decltype(&T::operator())>::value; }; template<typename R, typename T, typename ... Args> struct argument_count<R (T::*)(Args...)> { static const std::size_t value = sizeof...(Args); }; template<typename R, typename T, typename ... Args> struct argument_count<R (T::*)(Args...) const> { static const std::size_t value = sizeof...(Args); }; template<typename T> struct return_type; template<typename R, typename ... Args> struct return_type<R(Args...)> { using type = R; }; template<typename R, typename ... Args> struct return_type<R(*)(Args...)> { using type = R; }; template<typename R, typename T, typename ... Args> struct return_type<R(T::*)(Args...)> { using type = R; }; template<typename R, typename T, typename ... Args> struct return_type<R(T::*)(Args...) const> { using type = R; }; auto no_op = [](){}; template<typename T1, typename T2> struct has_left_shift { template <typename U> static std::true_type dummy(typename std::decay< decltype(std::declval<T1&>() << std::declval<const U&>())>::type*); template <typename U> static std::false_type dummy(...); static const bool value = decltype(dummy<T2>(0))::value; }; template<typename T1, typename T2> struct has_right_shift { template <typename U> static std::true_type dummy(typename std::decay< decltype(std::declval<T1&>() << std::declval<const U&>())>::type*); template <typename U> static std::false_type dummy(...); static const bool value = decltype(dummy<T2>(0))::value; }; /// Class holding a sequence of integer values. template<std::size_t ...> struct seq_t {}; namespace impl { template<std::size_t N, std::size_t D, std::size_t ... S> struct gen_seq_ : public gen_seq_<N+1, D, S..., N> {}; template<std::size_t D, std::size_t ... S> struct gen_seq_<D, D, S...> { using type = seq_t<S..., D>; }; } /// Generate a sequence of integer from 0 to D (exclusive). template<std::size_t D> using gen_seq = typename impl::gen_seq_<0, D-1>::type; } #endif <commit_msg>Added result_of_functor and tuple_to_args.<commit_after>#ifndef VARIADIC_HPP #define VARIADIC_HPP #include <type_traits> #include <tuple> /// Cobalt template library namespace ctl { template<typename T, typename ... Args> struct is_any_of; template<typename T, typename U, typename ... Args> struct is_any_of<T, U, Args...> { static const bool value = std::is_same<T, U>::value || is_any_of<T, Args...>::value; }; template<typename T, typename U> struct is_any_of<T, U> { static const bool value = std::is_same<T, U>::value; }; struct separator {}; template<typename ... Args> struct head_t; template<typename T, typename ... Args> struct head_t<T, Args...> { using type = T; }; template<typename ... Args> using head = typename head_t<Args...>::type; template<typename ... Args> struct tail_t; template<typename T> struct tail_t<T> { using type = T; }; template<typename T, typename ... Args> struct tail_t<T, Args...> { using type = typename tail_t<Args...>::type; }; template<typename ... Args> using tail = typename tail_t<Args...>::type; template<typename ... Args> struct type_list; template<typename ... Args> struct type_list_popf_t; template<typename T, typename ... Args> struct type_list_popf_t<T, Args...> { using type = type_list<Args...>; }; template<typename ... Args> struct type_list_popb_t; template<typename T> struct type_list_popb_t<T> { using type = T; }; template<typename T, typename ... Args> struct type_list_popb_t<T, Args...> { using type = typename type_list_popb_t<Args...>::type; }; template<> struct type_list<> { template<typename V> using push_front_t = type_list<V>; template<typename V> using push_back_t = type_list<V>; template<typename V> push_front_t<V> push_front() { return push_front_t<V>(); } template<typename V> push_back_t<V> push_back() { return push_back_t<V>(); } }; template<typename T> struct type_list<T> { template<typename V> using push_front_t = type_list<V, T>; template<typename V> using push_back_t = type_list<T, V>; using pop_front_t = type_list<>; using pop_back_t = type_list<>; using front_t = T; using back_t = T; template<typename V> push_front_t<V> push_front() { return push_front_t<V>(); } template<typename V> push_back_t<V> push_back() { return push_back_t<V>(); } pop_front_t pop_front() { return pop_front_t(); } pop_back_t pop_back() { return pop_back_t(); } }; template<typename ... Args> struct type_list { template<typename V> using push_front_t = type_list<V, Args...>; template<typename V> using push_back_t = type_list<Args..., V>; using pop_front_t = typename type_list_popf_t<Args...>::type; using pop_back_t = typename type_list_popb_t<Args...>::type; using front_t = head<Args...>; using back_t = tail<Args...>; template<typename V> push_front_t<V> push_front() { return push_front_t<V>(); } template<typename V> push_back_t<V> push_back() { return push_back_t<V>(); } pop_front_t pop_front() { return pop_front_t(); } pop_back_t pop_back() { return pop_back_t(); } }; template<std::size_t N, typename T, typename ... Args> struct type_list_element__t { using type = typename type_list_element__t<N-1, Args...>::type; }; template<typename T, typename ... Args> struct type_list_element__t<0, T, Args...> { using type = T; }; template<std::size_t N, typename T> struct type_list_element_t; template<std::size_t N, typename ... Args> struct type_list_element_t<N, type_list<Args...>> { using type = typename type_list_element__t<N, Args...>::type; }; template<std::size_t N, typename T> using type_list_element = typename type_list_element_t<N, T>::type; template<typename T> struct type_list_size; template<typename ... Args> struct type_list_size<type_list<Args...>> { static const std::size_t value = sizeof...(Args); }; template<typename Pack1, typename Pack2> struct are_convertible; template<typename T1, typename T2,typename ... Args1, typename ... Args2> struct are_convertible<type_list<T1, Args1...>, type_list<T2, Args2...>> { static const bool value = std::is_convertible<T1,T2>::value && are_convertible<type_list<Args1...>, type_list<Args2...>>::value; }; template<> struct are_convertible<type_list<>, type_list<>> { static const bool value = true; }; template<typename T> struct type_holder { using type = T; }; template<typename T> struct type_holder_get_type; template<typename T> struct type_holder_get_type<type_holder<T>> { using type = T; }; template<typename T> struct function_arguments_t; template<typename R, typename T, typename ... Args> struct function_arguments_t<R (T::*)(Args...)> { using type = type_list<Args...>; }; template<typename R, typename T, typename ... Args> struct function_arguments_t<R (T::*)(Args...) const> { using type = type_list<Args...>; }; template<typename T> using function_arguments = typename function_arguments_t<T>::type; template<typename T> using functor_arguments = function_arguments<decltype(&T::operator())>; template<typename T> struct function_argument_t; template<typename R, typename T, typename Arg> struct function_argument_t<R (T::*)(Arg)> { using type = Arg; }; template<typename R, typename T, typename Arg> struct function_argument_t<R (T::*)(Arg) const> { using type = Arg; }; template<typename T> using function_argument = typename function_argument_t<T>::type; template<typename T> using functor_argument = function_argument<decltype(&T::operator())>; template<typename T> struct argument_count { static const std::size_t value = argument_count<decltype(&T::operator())>::value; }; template<typename R, typename T, typename ... Args> struct argument_count<R (T::*)(Args...)> { static const std::size_t value = sizeof...(Args); }; template<typename R, typename T, typename ... Args> struct argument_count<R (T::*)(Args...) const> { static const std::size_t value = sizeof...(Args); }; template<typename T> struct return_type; template<typename R, typename ... Args> struct return_type<R(Args...)> { using type = R; }; template<typename R, typename ... Args> struct return_type<R(*)(Args...)> { using type = R; }; template<typename R, typename T, typename ... Args> struct return_type<R(T::*)(Args...)> { using type = R; }; template<typename R, typename T, typename ... Args> struct return_type<R(T::*)(Args...) const> { using type = R; }; auto no_op = [](){}; template<typename T1, typename T2> struct has_left_shift { template <typename U> static std::true_type dummy(typename std::decay< decltype(std::declval<T1&>() << std::declval<const U&>())>::type*); template <typename U> static std::false_type dummy(...); static const bool value = decltype(dummy<T2>(0))::value; }; template<typename T1, typename T2> struct has_right_shift { template <typename U> static std::true_type dummy(typename std::decay< decltype(std::declval<T1&>() << std::declval<const U&>())>::type*); template <typename U> static std::false_type dummy(...); static const bool value = decltype(dummy<T2>(0))::value; }; /// Class holding a sequence of integer values. template<std::size_t ...> struct seq_t {}; namespace impl { template<std::size_t N, std::size_t D, std::size_t ... S> struct gen_seq_ : public gen_seq_<N+1, D, S..., N> {}; template<std::size_t D, std::size_t ... S> struct gen_seq_<D, D, S...> { using type = seq_t<S..., D>; }; } /// Generate a sequence of integer from 0 to D (exclusive). template<std::size_t D> using gen_seq = typename impl::gen_seq_<0, D-1>::type; /// Get the return type of a functor given the parameter types template<typename F, typename ... Args> struct result_of_functor { using type = decltype(std::declval<F>()(std::declval<Args>()...)); }; namespace impl { template<typename F, typename T> struct t2a_return_; template<typename F, typename ... Args> struct t2a_return_<F, std::tuple<Args...>> { using type = typename result_of_functor<F, Args...>::type; }; template<typename F> struct t2a_return_<F, std::tuple<>> { using type = void; }; template<typename F, typename T> using t2a_return = typename t2a_return_< typename std::decay<F>::type, typename std::decay<T>::type >::type; template<typename F, typename T, std::size_t ... I> t2a_return<F,T> tuple_to_args_(F&& func, T&& tup, seq_t<I...>) { return func(std::get<I>(std::forward<T>(tup))...); } template<typename F, typename T, std::size_t N> impl::t2a_return<F,T> tuple_to_args_(F&& func, T&& tup, std::integral_constant<std::size_t,N>) { return impl::tuple_to_args_( std::forward<F>(func), std::forward<T>(tup), gen_seq<N>{} ); } template<typename F, typename T> impl::t2a_return<F,T> tuple_to_args_(F&& func, T&& tup, std::integral_constant<std::size_t,0>) {} } /// Unfold a tuple and use the result as function parameters template<typename F, typename T> impl::t2a_return<F,T> tuple_to_args(F&& func, T&& tup) { using tuple_type = typename std::decay<T>::type; return impl::tuple_to_args_( std::forward<F>(func), std::forward<T>(tup), std::integral_constant<std::size_t, std::tuple_size<tuple_type>::value>{} ); } } #endif <|endoftext|>
<commit_before>#include <stdio.h> //׼ͷļ #include <stdlib.h> //׼ͷļ #define LIST_INIT_SIZE 100 //̬ʵֵԱijʼС #define LISTINCREMENT 10 //ÿζ̬ӵĴС #define OVERFLOW -1 //Խ #define FALSE 0 //ʧ #define OK 1 //ɹ //̬ʵֵԱݽṹ typedef struct{ int *elem; //ÿԱӦĶ̬׵ַַ int length; //Աǰij int listsize; //ԱĴС }SqList; //ʼһյԱ int InitList_Sq(SqList &L){ //̬ L.elem=(int*)malloc(LIST_INIT_SIZE*sizeof(int)); if (!L.elem) return OVERFLOW; //ʧ L.length=0; //ձijΪ0 L.listsize=LIST_INIT_SIZE; //ʼ洢 return OK; //سʼɹ }//InitList_Sq 㷨 2.3 //˳Lеiλ֮ǰµԪe int ListInsert_Sq(SqList &L,int i, int e){ //жiֵǷϷ 1<=i<=L.length+1 if (i<1||i>L.length+1) return OVERFLOW; //ǰ洢ռӷ if (L.length>=L.listsize){ int * newbase=(int *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(int)); if (!newbase) return OVERFLOW; //ʧ L.elem=newbase; //µĵַ L.listsize+=LISTINCREMENT; //ԱĴС } int *q=&(L.elem[i-1]); //Ҫλ for (int *p=&(L.elem[L.length-1]); p>=q; p--){ *(p+1)=*p; //λüԪغһλ } *q=e; //e ++L.length; //+1 return OK; } //ԱLɾiԪأeֵ int ListDelete_Sq(SqList &L,int i,int &e){ if (i<1||i>L.length) return OVERFLOW; // iȡֵΧΪ 1<=i<=L.length int *p=&(L.elem[i-1]); //pΪɾԪ e=*p; //eرɾԪ int *q=&(L.elem[L.length-1]); //βԪ // int *q=L.elem+L.length for (++p; p<=q; ++p){ *(p-1)=*p; //iԪԺԪͳͳǰƶһ ܹƶ n-i } --L.length; //-1 return OK; } int LocateElem(SqList &L,int e,int &i){ for (int j=0; j<L.length; ++j){ if (e==L.elem[j]){ i=j+1; return OK; } } return FALSE; } //ԪرȽϺ int compare(int p,int e){ return p==e; } //Compare //Աвe compareԪصλ δҵ򷵻0 int LocateElem_Sq(SqList &L,int e,int (* compare)(int,int)){ int i=1; //һԪصλ int *p=L.elem; //һԪصָ while (i<=L.length&&!(*compare)(*p++,e)) ++i; //ɨԱ һ ܺã if (i<=L.length) return i; //ڷ λ else return FALSE; //ڷʧ } //LocateElem_Sq int main(){ //һ ʵֵԱ SqList L; //ʼԱ InitList_Sq(L); //Բ20 for (int i=0; i<20; i++){ ListInsert_Sq(L,i+1,i); printf("%d %d \n",L.elem[i],L.length); } // ԱɾһԪ λ1 int e; ListDelete_Sq(L,1,e); //ɾԪ printf("%d\n",e); //ӦɾԱ for (int i=0; i<L.length; i++){ printf("%d %d\n",L.elem[i],i+1); } //Աв eԪ int i=LocateElem_Sq(L,12,compare); //ҽ printf("%d\n",i); } <commit_msg>delete-locate-elem-my-thought<commit_after>#include <stdio.h> //׼ͷļ #include <stdlib.h> //׼ͷļ #define LIST_INIT_SIZE 100 //̬ʵֵԱijʼС #define LISTINCREMENT 10 //ÿζ̬ӵĴС #define OVERFLOW -1 //Խ #define FALSE 0 //ʧ #define OK 1 //ɹ //̬ʵֵԱݽṹ typedef struct{ int *elem; //ÿԱӦĶ̬׵ַַ int length; //Աǰij int listsize; //ԱĴС }SqList; //ʼһյԱ int InitList_Sq(SqList &L){ //̬ L.elem=(int*)malloc(LIST_INIT_SIZE*sizeof(int)); if (!L.elem) return OVERFLOW; //ʧ L.length=0; //ձijΪ0 L.listsize=LIST_INIT_SIZE; //ʼ洢 return OK; //سʼɹ }//InitList_Sq 㷨 2.3 //˳Lеiλ֮ǰµԪe int ListInsert_Sq(SqList &L,int i, int e){ //жiֵǷϷ 1<=i<=L.length+1 if (i<1||i>L.length+1) return OVERFLOW; //ǰ洢ռӷ if (L.length>=L.listsize){ int * newbase=(int *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(int)); if (!newbase) return OVERFLOW; //ʧ L.elem=newbase; //µĵַ L.listsize+=LISTINCREMENT; //ԱĴС } int *q=&(L.elem[i-1]); //Ҫλ for (int *p=&(L.elem[L.length-1]); p>=q; p--){ *(p+1)=*p; //λüԪغһλ } *q=e; //e ++L.length; //+1 return OK; } //ԱLɾiԪأeֵ int ListDelete_Sq(SqList &L,int i,int &e){ if (i<1||i>L.length) return OVERFLOW; // iȡֵΧΪ 1<=i<=L.length int *p=&(L.elem[i-1]); //pΪɾԪ e=*p; //eرɾԪ int *q=&(L.elem[L.length-1]); //βԪ // int *q=L.elem+L.length for (++p; p<=q; ++p){ *(p-1)=*p; //iԪԺԪͳͳǰƶһ ܹƶ n-i } --L.length; //-1 return OK; } //ԪرȽϺ int compare(int p,int e){ return p==e; } //Compare //Աвe compareԪصλ δҵ򷵻0 int LocateElem_Sq(SqList &L,int e,int (* compare)(int,int)){ int i=1; //һԪصλ int *p=L.elem; //һԪصָ while (i<=L.length&&!(*compare)(*p++,e)) ++i; //ɨԱ һ ܺã if (i<=L.length) return i; //ڷ λ else return FALSE; //ڷʧ } //LocateElem_Sq int main(){ //һ ʵֵԱ SqList L; //ʼԱ InitList_Sq(L); //Բ20 for (int i=0; i<20; i++){ ListInsert_Sq(L,i+1,i); printf("%d %d \n",L.elem[i],L.length); } // ԱɾһԪ λ1 int e; ListDelete_Sq(L,1,e); //ɾԪ printf("%d\n",e); //ӦɾԱ for (int i=0; i<L.length; i++){ printf("%d %d\n",L.elem[i],i+1); } //Աв eԪ int i=LocateElem_Sq(L,12,compare); //ҽ printf("%d\n",i); } <|endoftext|>
<commit_before>//===-- LanaiMCCodeEmitter.cpp - Convert Lanai code to machine code -------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the LanaiMCCodeEmitter class. // //===----------------------------------------------------------------------===// #include "Lanai.h" #include "MCTargetDesc/LanaiBaseInfo.h" #include "MCTargetDesc/LanaiFixupKinds.h" #include "MCTargetDesc/LanaiMCExpr.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/MC/MCCodeEmitter.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCFixup.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/Support/Casting.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstdint> #define DEBUG_TYPE "mccodeemitter" STATISTIC(MCNumEmitted, "Number of MC instructions emitted"); namespace llvm { namespace { class LanaiMCCodeEmitter : public MCCodeEmitter { public: LanaiMCCodeEmitter(const MCInstrInfo &MCII, MCContext &C) {} LanaiMCCodeEmitter(const LanaiMCCodeEmitter &) = delete; void operator=(const LanaiMCCodeEmitter &) = delete; ~LanaiMCCodeEmitter() override = default; // The functions below are called by TableGen generated functions for getting // the binary encoding of instructions/opereands. // getBinaryCodeForInstr - TableGen'erated function for getting the // binary encoding for an instruction. uint64_t getBinaryCodeForInstr(const MCInst &Inst, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const; // getMachineOpValue - Return binary encoding of operand. If the machine // operand requires relocation, record the relocation and return zero. unsigned getMachineOpValue(const MCInst &Inst, const MCOperand &MCOp, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const; unsigned getRiMemoryOpValue(const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const; unsigned getRrMemoryOpValue(const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const; unsigned getSplsOpValue(const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const; unsigned getBranchTargetOpValue(const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const; void encodeInstruction(const MCInst &Inst, raw_ostream &Ostream, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const override; unsigned adjustPqBitsRmAndRrm(const MCInst &Inst, unsigned Value, const MCSubtargetInfo &STI) const; unsigned adjustPqBitsSpls(const MCInst &Inst, unsigned Value, const MCSubtargetInfo &STI) const; }; } // end anonymous namespace static Lanai::Fixups FixupKind(const MCExpr *Expr) { if (isa<MCSymbolRefExpr>(Expr)) return Lanai::FIXUP_LANAI_21; if (const LanaiMCExpr *McExpr = dyn_cast<LanaiMCExpr>(Expr)) { LanaiMCExpr::VariantKind ExprKind = McExpr->getKind(); switch (ExprKind) { case LanaiMCExpr::VK_Lanai_None: return Lanai::FIXUP_LANAI_21; case LanaiMCExpr::VK_Lanai_ABS_HI: return Lanai::FIXUP_LANAI_HI16; case LanaiMCExpr::VK_Lanai_ABS_LO: return Lanai::FIXUP_LANAI_LO16; } } return Lanai::Fixups(0); } // getMachineOpValue - Return binary encoding of operand. If the machine // operand requires relocation, record the relocation and return zero. unsigned LanaiMCCodeEmitter::getMachineOpValue( const MCInst &Inst, const MCOperand &MCOp, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const { if (MCOp.isReg()) return getLanaiRegisterNumbering(MCOp.getReg()); if (MCOp.isImm()) return static_cast<unsigned>(MCOp.getImm()); // MCOp must be an expression assert(MCOp.isExpr()); const MCExpr *Expr = MCOp.getExpr(); // Extract the symbolic reference side of a binary expression. if (Expr->getKind() == MCExpr::Binary) { const MCBinaryExpr *BinaryExpr = static_cast<const MCBinaryExpr *>(Expr); Expr = BinaryExpr->getLHS(); } assert(isa<LanaiMCExpr>(Expr) || Expr->getKind() == MCExpr::SymbolRef); // Push fixup (all info is contained within) Fixups.push_back( MCFixup::create(0, MCOp.getExpr(), MCFixupKind(FixupKind(Expr)))); return 0; } // Helper function to adjust P and Q bits on load and store instructions. static unsigned adjustPqBits(const MCInst &Inst, unsigned Value, unsigned PBitShift, unsigned QBitShift) { const MCOperand AluOp = Inst.getOperand(3); unsigned AluCode = AluOp.getImm(); // Set the P bit to one iff the immediate is nonzero and not a post-op // instruction. const MCOperand Op2 = Inst.getOperand(2); Value &= ~(1 << PBitShift); if (!LPAC::isPostOp(AluCode) && ((Op2.isImm() && Op2.getImm() != 0) || (Op2.isReg() && Op2.getReg() != Lanai::R0) || (Op2.isExpr()))) Value |= (1 << PBitShift); // Set the Q bit to one iff it is a post- or pre-op instruction. assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg() && "Expected register operand."); Value &= ~(1 << QBitShift); if (LPAC::modifiesOp(AluCode) && ((Op2.isImm() && Op2.getImm() != 0) || (Op2.isReg() && Op2.getReg() != Lanai::R0))) Value |= (1 << QBitShift); return Value; } unsigned LanaiMCCodeEmitter::adjustPqBitsRmAndRrm(const MCInst &Inst, unsigned Value, const MCSubtargetInfo &STI) const { return adjustPqBits(Inst, Value, 17, 16); } unsigned LanaiMCCodeEmitter::adjustPqBitsSpls(const MCInst &Inst, unsigned Value, const MCSubtargetInfo &STI) const { return adjustPqBits(Inst, Value, 11, 10); } void LanaiMCCodeEmitter::encodeInstruction( const MCInst &Inst, raw_ostream &Ostream, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const { // Get instruction encoding and emit it unsigned Value = getBinaryCodeForInstr(Inst, Fixups, SubtargetInfo); ++MCNumEmitted; // Keep track of the number of emitted insns. // Emit bytes in big-endian for (int i = (4 - 1) * 8; i >= 0; i -= 8) Ostream << static_cast<char>((Value >> i) & 0xff); } // Encode Lanai Memory Operand unsigned LanaiMCCodeEmitter::getRiMemoryOpValue( const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const { unsigned Encoding; const MCOperand Op1 = Inst.getOperand(OpNo + 0); const MCOperand Op2 = Inst.getOperand(OpNo + 1); const MCOperand AluOp = Inst.getOperand(OpNo + 2); assert(Op1.isReg() && "First operand is not register."); assert((Op2.isImm() || Op2.isExpr()) && "Second operand is neither an immediate nor an expression."); assert((LPAC::getAluOp(AluOp.getImm()) == LPAC::ADD) && "Register immediate only supports addition operator"); Encoding = (getLanaiRegisterNumbering(Op1.getReg()) << 18); if (Op2.isImm()) { assert(isInt<16>(Op2.getImm()) && "Constant value truncated (limited to 16-bit)"); Encoding |= (Op2.getImm() & 0xffff); if (Op2.getImm() != 0) { if (LPAC::isPreOp(AluOp.getImm())) Encoding |= (0x3 << 16); if (LPAC::isPostOp(AluOp.getImm())) Encoding |= (0x1 << 16); } } else getMachineOpValue(Inst, Op2, Fixups, SubtargetInfo); return Encoding; } unsigned LanaiMCCodeEmitter::getRrMemoryOpValue( const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const { unsigned Encoding; const MCOperand Op1 = Inst.getOperand(OpNo + 0); const MCOperand Op2 = Inst.getOperand(OpNo + 1); const MCOperand AluMCOp = Inst.getOperand(OpNo + 2); assert(Op1.isReg() && "First operand is not register."); Encoding = (getLanaiRegisterNumbering(Op1.getReg()) << 15); assert(Op2.isReg() && "Second operand is not register."); Encoding |= (getLanaiRegisterNumbering(Op2.getReg()) << 10); assert(AluMCOp.isImm() && "Third operator is not immediate."); // Set BBB unsigned AluOp = AluMCOp.getImm(); Encoding |= LPAC::encodeLanaiAluCode(AluOp) << 5; // Set P and Q if (LPAC::isPreOp(AluOp)) Encoding |= (0x3 << 8); if (LPAC::isPostOp(AluOp)) Encoding |= (0x1 << 8); // Set JJJJ switch (LPAC::getAluOp(AluOp)) { case LPAC::SHL: case LPAC::SRL: Encoding |= 0x10; break; case LPAC::SRA: Encoding |= 0x18; break; default: break; } return Encoding; } unsigned LanaiMCCodeEmitter::getSplsOpValue(const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const { unsigned Encoding; const MCOperand Op1 = Inst.getOperand(OpNo + 0); const MCOperand Op2 = Inst.getOperand(OpNo + 1); const MCOperand AluOp = Inst.getOperand(OpNo + 2); assert(Op1.isReg() && "First operand is not register."); assert((Op2.isImm() || Op2.isExpr()) && "Second operand is neither an immediate nor an expression."); assert((LPAC::getAluOp(AluOp.getImm()) == LPAC::ADD) && "Register immediate only supports addition operator"); Encoding = (getLanaiRegisterNumbering(Op1.getReg()) << 12); if (Op2.isImm()) { assert(isInt<10>(Op2.getImm()) && "Constant value truncated (limited to 10-bit)"); Encoding |= (Op2.getImm() & 0x3ff); if (Op2.getImm() != 0) { if (LPAC::isPreOp(AluOp.getImm())) Encoding |= (0x3 << 10); if (LPAC::isPostOp(AluOp.getImm())) Encoding |= (0x1 << 10); } } else getMachineOpValue(Inst, Op2, Fixups, SubtargetInfo); return Encoding; } unsigned LanaiMCCodeEmitter::getBranchTargetOpValue( const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const { const MCOperand &MCOp = Inst.getOperand(OpNo); if (MCOp.isReg() || MCOp.isImm()) return getMachineOpValue(Inst, MCOp, Fixups, SubtargetInfo); Fixups.push_back(MCFixup::create( 0, MCOp.getExpr(), static_cast<MCFixupKind>(Lanai::FIXUP_LANAI_25))); return 0; } #include "LanaiGenMCCodeEmitter.inc" } // end namespace llvm llvm::MCCodeEmitter * llvm::createLanaiMCCodeEmitter(const MCInstrInfo &InstrInfo, const MCRegisterInfo & /*MRI*/, MCContext &context) { return new LanaiMCCodeEmitter(InstrInfo, context); } <commit_msg>Include what you use in LanaiMCCodeEmitter.cpp<commit_after>//===-- LanaiMCCodeEmitter.cpp - Convert Lanai code to machine code -------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the LanaiMCCodeEmitter class. // //===----------------------------------------------------------------------===// #include "LanaiAluCode.h" #include "MCTargetDesc/LanaiBaseInfo.h" #include "MCTargetDesc/LanaiFixupKinds.h" #include "MCTargetDesc/LanaiMCExpr.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/MC/MCCodeEmitter.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCFixup.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/Support/Casting.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstdint> #define DEBUG_TYPE "mccodeemitter" STATISTIC(MCNumEmitted, "Number of MC instructions emitted"); namespace llvm { namespace { class LanaiMCCodeEmitter : public MCCodeEmitter { public: LanaiMCCodeEmitter(const MCInstrInfo &MCII, MCContext &C) {} LanaiMCCodeEmitter(const LanaiMCCodeEmitter &) = delete; void operator=(const LanaiMCCodeEmitter &) = delete; ~LanaiMCCodeEmitter() override = default; // The functions below are called by TableGen generated functions for getting // the binary encoding of instructions/opereands. // getBinaryCodeForInstr - TableGen'erated function for getting the // binary encoding for an instruction. uint64_t getBinaryCodeForInstr(const MCInst &Inst, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const; // getMachineOpValue - Return binary encoding of operand. If the machine // operand requires relocation, record the relocation and return zero. unsigned getMachineOpValue(const MCInst &Inst, const MCOperand &MCOp, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const; unsigned getRiMemoryOpValue(const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const; unsigned getRrMemoryOpValue(const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const; unsigned getSplsOpValue(const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const; unsigned getBranchTargetOpValue(const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const; void encodeInstruction(const MCInst &Inst, raw_ostream &Ostream, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const override; unsigned adjustPqBitsRmAndRrm(const MCInst &Inst, unsigned Value, const MCSubtargetInfo &STI) const; unsigned adjustPqBitsSpls(const MCInst &Inst, unsigned Value, const MCSubtargetInfo &STI) const; }; } // end anonymous namespace static Lanai::Fixups FixupKind(const MCExpr *Expr) { if (isa<MCSymbolRefExpr>(Expr)) return Lanai::FIXUP_LANAI_21; if (const LanaiMCExpr *McExpr = dyn_cast<LanaiMCExpr>(Expr)) { LanaiMCExpr::VariantKind ExprKind = McExpr->getKind(); switch (ExprKind) { case LanaiMCExpr::VK_Lanai_None: return Lanai::FIXUP_LANAI_21; case LanaiMCExpr::VK_Lanai_ABS_HI: return Lanai::FIXUP_LANAI_HI16; case LanaiMCExpr::VK_Lanai_ABS_LO: return Lanai::FIXUP_LANAI_LO16; } } return Lanai::Fixups(0); } // getMachineOpValue - Return binary encoding of operand. If the machine // operand requires relocation, record the relocation and return zero. unsigned LanaiMCCodeEmitter::getMachineOpValue( const MCInst &Inst, const MCOperand &MCOp, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const { if (MCOp.isReg()) return getLanaiRegisterNumbering(MCOp.getReg()); if (MCOp.isImm()) return static_cast<unsigned>(MCOp.getImm()); // MCOp must be an expression assert(MCOp.isExpr()); const MCExpr *Expr = MCOp.getExpr(); // Extract the symbolic reference side of a binary expression. if (Expr->getKind() == MCExpr::Binary) { const MCBinaryExpr *BinaryExpr = static_cast<const MCBinaryExpr *>(Expr); Expr = BinaryExpr->getLHS(); } assert(isa<LanaiMCExpr>(Expr) || Expr->getKind() == MCExpr::SymbolRef); // Push fixup (all info is contained within) Fixups.push_back( MCFixup::create(0, MCOp.getExpr(), MCFixupKind(FixupKind(Expr)))); return 0; } // Helper function to adjust P and Q bits on load and store instructions. static unsigned adjustPqBits(const MCInst &Inst, unsigned Value, unsigned PBitShift, unsigned QBitShift) { const MCOperand AluOp = Inst.getOperand(3); unsigned AluCode = AluOp.getImm(); // Set the P bit to one iff the immediate is nonzero and not a post-op // instruction. const MCOperand Op2 = Inst.getOperand(2); Value &= ~(1 << PBitShift); if (!LPAC::isPostOp(AluCode) && ((Op2.isImm() && Op2.getImm() != 0) || (Op2.isReg() && Op2.getReg() != Lanai::R0) || (Op2.isExpr()))) Value |= (1 << PBitShift); // Set the Q bit to one iff it is a post- or pre-op instruction. assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg() && "Expected register operand."); Value &= ~(1 << QBitShift); if (LPAC::modifiesOp(AluCode) && ((Op2.isImm() && Op2.getImm() != 0) || (Op2.isReg() && Op2.getReg() != Lanai::R0))) Value |= (1 << QBitShift); return Value; } unsigned LanaiMCCodeEmitter::adjustPqBitsRmAndRrm(const MCInst &Inst, unsigned Value, const MCSubtargetInfo &STI) const { return adjustPqBits(Inst, Value, 17, 16); } unsigned LanaiMCCodeEmitter::adjustPqBitsSpls(const MCInst &Inst, unsigned Value, const MCSubtargetInfo &STI) const { return adjustPqBits(Inst, Value, 11, 10); } void LanaiMCCodeEmitter::encodeInstruction( const MCInst &Inst, raw_ostream &Ostream, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const { // Get instruction encoding and emit it unsigned Value = getBinaryCodeForInstr(Inst, Fixups, SubtargetInfo); ++MCNumEmitted; // Keep track of the number of emitted insns. // Emit bytes in big-endian for (int i = (4 - 1) * 8; i >= 0; i -= 8) Ostream << static_cast<char>((Value >> i) & 0xff); } // Encode Lanai Memory Operand unsigned LanaiMCCodeEmitter::getRiMemoryOpValue( const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const { unsigned Encoding; const MCOperand Op1 = Inst.getOperand(OpNo + 0); const MCOperand Op2 = Inst.getOperand(OpNo + 1); const MCOperand AluOp = Inst.getOperand(OpNo + 2); assert(Op1.isReg() && "First operand is not register."); assert((Op2.isImm() || Op2.isExpr()) && "Second operand is neither an immediate nor an expression."); assert((LPAC::getAluOp(AluOp.getImm()) == LPAC::ADD) && "Register immediate only supports addition operator"); Encoding = (getLanaiRegisterNumbering(Op1.getReg()) << 18); if (Op2.isImm()) { assert(isInt<16>(Op2.getImm()) && "Constant value truncated (limited to 16-bit)"); Encoding |= (Op2.getImm() & 0xffff); if (Op2.getImm() != 0) { if (LPAC::isPreOp(AluOp.getImm())) Encoding |= (0x3 << 16); if (LPAC::isPostOp(AluOp.getImm())) Encoding |= (0x1 << 16); } } else getMachineOpValue(Inst, Op2, Fixups, SubtargetInfo); return Encoding; } unsigned LanaiMCCodeEmitter::getRrMemoryOpValue( const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const { unsigned Encoding; const MCOperand Op1 = Inst.getOperand(OpNo + 0); const MCOperand Op2 = Inst.getOperand(OpNo + 1); const MCOperand AluMCOp = Inst.getOperand(OpNo + 2); assert(Op1.isReg() && "First operand is not register."); Encoding = (getLanaiRegisterNumbering(Op1.getReg()) << 15); assert(Op2.isReg() && "Second operand is not register."); Encoding |= (getLanaiRegisterNumbering(Op2.getReg()) << 10); assert(AluMCOp.isImm() && "Third operator is not immediate."); // Set BBB unsigned AluOp = AluMCOp.getImm(); Encoding |= LPAC::encodeLanaiAluCode(AluOp) << 5; // Set P and Q if (LPAC::isPreOp(AluOp)) Encoding |= (0x3 << 8); if (LPAC::isPostOp(AluOp)) Encoding |= (0x1 << 8); // Set JJJJ switch (LPAC::getAluOp(AluOp)) { case LPAC::SHL: case LPAC::SRL: Encoding |= 0x10; break; case LPAC::SRA: Encoding |= 0x18; break; default: break; } return Encoding; } unsigned LanaiMCCodeEmitter::getSplsOpValue(const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const { unsigned Encoding; const MCOperand Op1 = Inst.getOperand(OpNo + 0); const MCOperand Op2 = Inst.getOperand(OpNo + 1); const MCOperand AluOp = Inst.getOperand(OpNo + 2); assert(Op1.isReg() && "First operand is not register."); assert((Op2.isImm() || Op2.isExpr()) && "Second operand is neither an immediate nor an expression."); assert((LPAC::getAluOp(AluOp.getImm()) == LPAC::ADD) && "Register immediate only supports addition operator"); Encoding = (getLanaiRegisterNumbering(Op1.getReg()) << 12); if (Op2.isImm()) { assert(isInt<10>(Op2.getImm()) && "Constant value truncated (limited to 10-bit)"); Encoding |= (Op2.getImm() & 0x3ff); if (Op2.getImm() != 0) { if (LPAC::isPreOp(AluOp.getImm())) Encoding |= (0x3 << 10); if (LPAC::isPostOp(AluOp.getImm())) Encoding |= (0x1 << 10); } } else getMachineOpValue(Inst, Op2, Fixups, SubtargetInfo); return Encoding; } unsigned LanaiMCCodeEmitter::getBranchTargetOpValue( const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &SubtargetInfo) const { const MCOperand &MCOp = Inst.getOperand(OpNo); if (MCOp.isReg() || MCOp.isImm()) return getMachineOpValue(Inst, MCOp, Fixups, SubtargetInfo); Fixups.push_back(MCFixup::create( 0, MCOp.getExpr(), static_cast<MCFixupKind>(Lanai::FIXUP_LANAI_25))); return 0; } #include "LanaiGenMCCodeEmitter.inc" } // end namespace llvm llvm::MCCodeEmitter * llvm::createLanaiMCCodeEmitter(const MCInstrInfo &InstrInfo, const MCRegisterInfo & /*MRI*/, MCContext &context) { return new LanaiMCCodeEmitter(InstrInfo, context); } <|endoftext|>
<commit_before>// Copyright 2017-2020 The Verible Authors. // // 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 "common/util/forward.h" #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" namespace verible { namespace { class TestClassA {}; class TestClassB { public: TestClassB() = default; explicit TestClassB(const TestClassA&) {} }; TEST(ForwardReferenceElseConstructTest, ForwardReference) { TestClassA a; const auto& ref = ForwardReferenceElseConstruct<TestClassA>()(a); EXPECT_EQ(&ref, &a); // same object forwarded } TEST(ForwardReferenceElseConstructTest, ForwardReferenceConst) { const TestClassA a; const auto& ref = ForwardReferenceElseConstruct<TestClassA>()(a); EXPECT_EQ(&ref, &a); // same object forwarded } TEST(ForwardReferenceElseConstructTest, Construct) { const TestClassA a; const auto& ref = ForwardReferenceElseConstruct<TestClassB>()(a); static_assert(!std::is_same<decltype(ref), TestClassA>::value); } TEST(ForwardReferenceElseConstructTest, ForwardStringView) { const absl::string_view a("hello"); const auto& ref = ForwardReferenceElseConstruct<absl::string_view>()(a); EXPECT_EQ(&ref, &a); // same object forwarded } TEST(ForwardReferenceElseConstructTest, ConstructString) { const absl::string_view a("hello"); const auto& ref = ForwardReferenceElseConstruct<std::string>()(a); static_assert(!std::is_same<decltype(ref), absl::string_view>::value); } TEST(ForwardReferenceElseConstructTest, ForwardString) { const std::string a("hello"); const auto& ref = ForwardReferenceElseConstruct<std::string>()(a); EXPECT_EQ(&ref, &a); // same object forwarded } TEST(ForwardReferenceElseConstructTest, ConstructStringView) { const std::string a("hello"); const auto& ref = ForwardReferenceElseConstruct<absl::string_view>()(a); static_assert(!std::is_same<decltype(ref), std::string>::value); } } // namespace } // namespace verible <commit_msg>Use C++11 compatible version of static_assert; before C++17 the second message parameter to static_assert was not optional.<commit_after>// Copyright 2017-2020 The Verible Authors. // // 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 "common/util/forward.h" #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" namespace verible { namespace { class TestClassA {}; class TestClassB { public: TestClassB() = default; explicit TestClassB(const TestClassA&) {} }; TEST(ForwardReferenceElseConstructTest, ForwardReference) { TestClassA a; const auto& ref = ForwardReferenceElseConstruct<TestClassA>()(a); EXPECT_EQ(&ref, &a); // same object forwarded } TEST(ForwardReferenceElseConstructTest, ForwardReferenceConst) { const TestClassA a; const auto& ref = ForwardReferenceElseConstruct<TestClassA>()(a); EXPECT_EQ(&ref, &a); // same object forwarded } TEST(ForwardReferenceElseConstructTest, Construct) { const TestClassA a; const auto& ref = ForwardReferenceElseConstruct<TestClassB>()(a); static_assert(!std::is_same<decltype(ref), TestClassA>::value, "!std::is_same<decltype(ref), TestClassA>::value"); } TEST(ForwardReferenceElseConstructTest, ForwardStringView) { const absl::string_view a("hello"); const auto& ref = ForwardReferenceElseConstruct<absl::string_view>()(a); EXPECT_EQ(&ref, &a); // same object forwarded } TEST(ForwardReferenceElseConstructTest, ConstructString) { const absl::string_view a("hello"); const auto& ref = ForwardReferenceElseConstruct<std::string>()(a); static_assert(!std::is_same<decltype(ref), absl::string_view>::value, "!std::is_same<decltype(ref), absl::string_view>::value"); } TEST(ForwardReferenceElseConstructTest, ForwardString) { const std::string a("hello"); const auto& ref = ForwardReferenceElseConstruct<std::string>()(a); EXPECT_EQ(&ref, &a); // same object forwarded } TEST(ForwardReferenceElseConstructTest, ConstructStringView) { const std::string a("hello"); const auto& ref = ForwardReferenceElseConstruct<absl::string_view>()(a); static_assert(!std::is_same<decltype(ref), std::string>::value, "!std::is_same<decltype(ref), std::string>::value"); } } // namespace } // namespace verible <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2018 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Kaveh Vahedipour //////////////////////////////////////////////////////////////////////////////// #include "AgentCallback.h" #include "Agency/Agent.h" #include "ApplicationFeatures/ApplicationServer.h" #include "Logger/LogMacros.h" #include "Network/Methods.h" using namespace arangodb::application_features; using namespace arangodb::consensus; using namespace arangodb::velocypack; AgentCallback::AgentCallback() : _server(nullptr), _agent(nullptr), _last(0), _toLog(0), _startTime(0.0) {} AgentCallback::AgentCallback(Agent* agent, std::string const& slaveID, index_t last, size_t toLog) : _server(&agent->server()), _agent(agent), _last(last), _slaveID(slaveID), _toLog(toLog), _startTime(TRI_microtime()) {} void AgentCallback::shutdown() { _agent = nullptr; } bool AgentCallback::operator()(network::Response const & r) { if (r.ok()) { if (_agent) { auto body = r.slice(); bool success = false; term_t otherTerm = 0; try { success = body.get("success").isTrue(); otherTerm = body.get("term").getNumber<term_t>(); } catch (std::exception const& e) { LOG_TOPIC("1b7bb", WARN, Logger::AGENCY) << "Bad callback message received: " << e.what(); _agent->reportFailed(_slaveID, _toLog); } if (otherTerm > _agent->term()) { _agent->resign(otherTerm); } else if (!success) { LOG_TOPIC("7cbce", DEBUG, Logger::CLUSTER) << "Got negative answer from follower, will retry later."; // This reportFailed will reset _confirmed in Agent fot this follower _agent->reportFailed(_slaveID, _toLog, true); } else { Slice senderTimeStamp = body.get("senderTimeStamp"); if (senderTimeStamp.isInteger()) { try { int64_t sts = senderTimeStamp.getNumber<int64_t>(); int64_t now = std::llround(steadyClockToDouble() * 1000); if (now - sts > 1000) { // a second round trip time! LOG_TOPIC("c2aac", DEBUG, Logger::AGENCY) << "Round trip for appendEntriesRPC took " << now - sts << " milliseconds, which is way too high!"; } } catch (...) { LOG_TOPIC("b1549", WARN, Logger::AGENCY) << "Exception when looking at senderTimeStamp in " "appendEntriesRPC" " answer."; } } LOG_TOPIC("0bfa4", DEBUG, Logger::AGENCY) << "AgentCallback: " << body.toJson(); _agent->reportIn(_slaveID, _last, _toLog); } } LOG_TOPIC("8b0d8", DEBUG, Logger::AGENCY) << "Got good callback from AppendEntriesRPC: " << "comm_status(" << fuerte::to_string(r.error) << "), last(" << _last << "), follower(" << _slaveID << "), time(" << TRI_microtime() - _startTime << ")"; } else { if (_server == nullptr || (!_server->isStopping() && (_agent == nullptr || !_agent->isStopping()))) { // Do not warn if we are already shutting down: LOG_TOPIC("2c712", WARN, Logger::AGENCY) << "Got bad callback from AppendEntriesRPC: " << "comm_status(" << fuerte::to_string(r.error) << "), last(" << _last << "), follower(" << _slaveID << "), time(" << TRI_microtime() - _startTime << ")"; } if (_agent != nullptr) { _agent->reportFailed(_slaveID, _toLog); } } return true; } <commit_msg>Fix Windows compile error from network namespace. (#10133)<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2018 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Kaveh Vahedipour //////////////////////////////////////////////////////////////////////////////// #include "AgentCallback.h" #include "Agency/Agent.h" #include "ApplicationFeatures/ApplicationServer.h" #include "Logger/LogMacros.h" #include "Network/Methods.h" using namespace arangodb::application_features; using namespace arangodb::consensus; using namespace arangodb::velocypack; AgentCallback::AgentCallback() : _server(nullptr), _agent(nullptr), _last(0), _toLog(0), _startTime(0.0) {} AgentCallback::AgentCallback(Agent* agent, std::string const& slaveID, index_t last, size_t toLog) : _server(&agent->server()), _agent(agent), _last(last), _slaveID(slaveID), _toLog(toLog), _startTime(TRI_microtime()) {} void AgentCallback::shutdown() { _agent = nullptr; } bool AgentCallback::operator()(arangodb::network::Response const& r) { if (r.ok()) { if (_agent) { auto body = r.slice(); bool success = false; term_t otherTerm = 0; try { success = body.get("success").isTrue(); otherTerm = body.get("term").getNumber<term_t>(); } catch (std::exception const& e) { LOG_TOPIC("1b7bb", WARN, Logger::AGENCY) << "Bad callback message received: " << e.what(); _agent->reportFailed(_slaveID, _toLog); } if (otherTerm > _agent->term()) { _agent->resign(otherTerm); } else if (!success) { LOG_TOPIC("7cbce", DEBUG, Logger::CLUSTER) << "Got negative answer from follower, will retry later."; // This reportFailed will reset _confirmed in Agent fot this follower _agent->reportFailed(_slaveID, _toLog, true); } else { Slice senderTimeStamp = body.get("senderTimeStamp"); if (senderTimeStamp.isInteger()) { try { int64_t sts = senderTimeStamp.getNumber<int64_t>(); int64_t now = std::llround(steadyClockToDouble() * 1000); if (now - sts > 1000) { // a second round trip time! LOG_TOPIC("c2aac", DEBUG, Logger::AGENCY) << "Round trip for appendEntriesRPC took " << now - sts << " milliseconds, which is way too high!"; } } catch (...) { LOG_TOPIC("b1549", WARN, Logger::AGENCY) << "Exception when looking at senderTimeStamp in " "appendEntriesRPC" " answer."; } } LOG_TOPIC("0bfa4", DEBUG, Logger::AGENCY) << "AgentCallback: " << body.toJson(); _agent->reportIn(_slaveID, _last, _toLog); } } LOG_TOPIC("8b0d8", DEBUG, Logger::AGENCY) << "Got good callback from AppendEntriesRPC: " << "comm_status(" << fuerte::to_string(r.error) << "), last(" << _last << "), follower(" << _slaveID << "), time(" << TRI_microtime() - _startTime << ")"; } else { if (_server == nullptr || (!_server->isStopping() && (_agent == nullptr || !_agent->isStopping()))) { // Do not warn if we are already shutting down: LOG_TOPIC("2c712", WARN, Logger::AGENCY) << "Got bad callback from AppendEntriesRPC: " << "comm_status(" << fuerte::to_string(r.error) << "), last(" << _last << "), follower(" << _slaveID << "), time(" << TRI_microtime() - _startTime << ")"; } if (_agent != nullptr) { _agent->reportFailed(_slaveID, _toLog); } } return true; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief MRuby shell /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include <mruby.h> #include <mruby/proc.h> #include <mruby/data.h> #include <mruby/variable.h> #include <mruby/compile.h> #include <stdio.h> #include <fstream> #include "BasicsC/common.h" #include "ArangoShell/ArangoClient.h" #include "Basics/FileUtils.h" #include "Basics/ProgramOptions.h" #include "Basics/ProgramOptionsDescription.h" #include "Basics/StringUtils.h" #include "BasicsC/csv.h" #include "BasicsC/files.h" #include "BasicsC/init.h" #include "BasicsC/logging.h" #include "BasicsC/shell-colors.h" #include "BasicsC/tri-strings.h" #include "BasicsC/terminal-utils.h" #include "Logger/Logger.h" #include "MRClient/MRubyClientConnection.h" #include "MRuby/MRLineEditor.h" #include "MRuby/MRLoader.h" #include "MRuby/mr-utils.h" #include "Rest/Endpoint.h" #include "Rest/InitialiseRest.h" #include "SimpleHttpClient/SimpleHttpClient.h" #include "SimpleHttpClient/SimpleHttpResult.h" using namespace std; using namespace triagens::basics; using namespace triagens::rest; using namespace triagens::httpclient; using namespace triagens::arango; using namespace triagens::mrclient; #include "mr/common/bootstrap/mr-error.h" // ----------------------------------------------------------------------------- // --SECTION-- private variables // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup MRShell /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief base class for clients //////////////////////////////////////////////////////////////////////////////// ArangoClient BaseClient; //////////////////////////////////////////////////////////////////////////////// /// @brief the initial default connection //////////////////////////////////////////////////////////////////////////////// MRubyClientConnection* ClientConnection = 0; //////////////////////////////////////////////////////////////////////////////// /// @brief startup MR files //////////////////////////////////////////////////////////////////////////////// static MRLoader StartupLoader; //////////////////////////////////////////////////////////////////////////////// /// @brief path for Ruby modules files //////////////////////////////////////////////////////////////////////////////// static string StartupModules = ""; //////////////////////////////////////////////////////////////////////////////// /// @brief path for Ruby bootstrap files //////////////////////////////////////////////////////////////////////////////// static string StartupPath = ""; //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- ruby functions // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup MRShell /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief ClientConnection method "httpGet" //////////////////////////////////////////////////////////////////////////////// static mrb_value ClientConnection_httpGet (mrb_state* mrb, mrb_value self) { char* url; /* int res; */ size_t l; struct RData* rdata; MRubyClientConnection* connection; /* res = */ mrb_get_args(mrb, "s", &url, &l); if (url == 0) { return self; } // looking at "mruby.h" I assume that is the way to unwrap the pointer rdata = (struct RData*) mrb_object(self); connection = (MRubyClientConnection*) rdata->data; if (connection == NULL) { printf("unknown connection (TODO raise error)\n"); return self; } // check header fields map<string, string> headerFields; // and execute return connection->getData(url, headerFields); } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- private functions // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup MRShell /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief return a new client connection instance //////////////////////////////////////////////////////////////////////////////// static MRubyClientConnection* createConnection (mrb_state* mrb) { return new MRubyClientConnection(mrb, BaseClient.endpointServer(), BaseClient.username(), BaseClient.password(), BaseClient.requestTimeout(), BaseClient.connectTimeout(), ArangoClient::DEFAULT_RETRIES, false); } //////////////////////////////////////////////////////////////////////////////// /// @brief parses the program options //////////////////////////////////////////////////////////////////////////////// static void ParseProgramOptions (int argc, char* argv[]) { ProgramOptionsDescription description("STANDARD options"); ProgramOptionsDescription ruby("RUBY options"); ruby ("ruby.directory", &StartupPath, "startup paths containing the Ruby files; multiple directories can be separated by cola") ("ruby.modules-path", &StartupModules, "one or more directories separated by cola") ; description (ruby, false) ; // fill in used options BaseClient.setupGeneral(description); BaseClient.setupServer(description); // and parse the command line and config file ProgramOptions options; BaseClient.parse(options, description, argc, argv, "arangoirb.conf"); // check module path if (StartupModules.empty()) { LOGGER_FATAL_AND_EXIT("module path not known, please use '--ruby.modules-path'"); } } //////////////////////////////////////////////////////////////////////////////// /// @brief set-up the connection functions //////////////////////////////////////////////////////////////////////////////// static void MR_ArangoConnection_Free (mrb_state* mrb, void* p) { printf("free of ArangoCollection called\n"); } static const struct mrb_data_type MR_ArangoConnection_Type = { "ArangoConnection", MR_ArangoConnection_Free }; static void InitMRClientConnection (mrb_state* mrb, MRubyClientConnection* connection) { struct RClass *rcl; // ............................................................................. // arango client connection // ............................................................................. rcl = mrb_define_class(mrb, "ArangoConnection", mrb->object_class); mrb_define_method(mrb, rcl, "get", ClientConnection_httpGet, ARGS_REQ(1)); // create the connection variable mrb_value arango = mrb_obj_value(Data_Wrap_Struct(mrb, rcl, &MR_ArangoConnection_Type, (void*) connection)); mrb_gv_set(mrb, mrb_intern(mrb, "$arango"), arango); } //////////////////////////////////////////////////////////////////////////////// /// @brief executes the shell //////////////////////////////////////////////////////////////////////////////// static void RunShell (mrb_state* mrb) { MRLineEditor console(mrb, ".arangoirb.history"); console.open(false /*! NoAutoComplete*/); while (true) { char* input = console.prompt("arangoirb> "); if (input == 0) { break; } if (*input == '\0') { TRI_FreeString(TRI_CORE_MEM_ZONE, input); continue; } console.addHistory(input); struct mrb_parser_state* p = mrb_parse_nstring(mrb, input, strlen(input), NULL); TRI_FreeString(TRI_CORE_MEM_ZONE, input); if (p == 0 || p->tree == 0 || 0 < p->nerr) { cout << "UPPS!\n"; continue; } int n = mrb_generate_code(mrb, p); if (n < 0) { cout << "UPPS: " << n << " returned by mrb_generate_code\n"; continue; } mrb_value result = mrb_run(mrb, mrb_proc_new(mrb, mrb->irep[n]), mrb_top_self(mrb)); if (mrb->exc) { cout << "Caught exception:\n"; mrb_p(mrb, mrb_obj_value(mrb->exc)); mrb->exc = 0; } else if (! mrb_nil_p(result)) { mrb_p(mrb, result); } } console.close(); cout << endl; BaseClient.printByeBye(); } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- public functions // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup MRShell /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief main //////////////////////////////////////////////////////////////////////////////// int main (int argc, char* argv[]) { TRIAGENS_C_INITIALISE(argc, argv); TRIAGENS_REST_INITIALISE(argc, argv); TRI_InitialiseLogging(false); int ret = EXIT_SUCCESS; BaseClient.setEndpointString(Endpoint::getDefaultEndpoint()); // ............................................................................. // parse the program options // ............................................................................. ParseProgramOptions(argc, argv); // ............................................................................. // set-up MRuby objects // ............................................................................. // create a new ruby shell mrb_state* mrb = MR_OpenShell(); TRI_InitMRUtils(mrb); // ............................................................................. // set-up client connection // ............................................................................. // check if we want to connect to a server bool useServer = (BaseClient.endpointString() != "none"); if (useServer) { BaseClient.createEndpoint(); if (BaseClient.endpointServer() == 0) { LOGGER_FATAL_AND_EXIT("invalid value for --server.endpoint ('" << BaseClient.endpointString() << "')"); } ClientConnection = createConnection(mrb); InitMRClientConnection(mrb, ClientConnection); } // ............................................................................. // banner // ............................................................................. // http://www.network-science.de/ascii/ Font: ogre if (! BaseClient.quiet()) { char const* g = TRI_SHELL_COLOR_GREEN; char const* r = TRI_SHELL_COLOR_RED; char const* z = TRI_SHELL_COLOR_RESET; if (! BaseClient.colors()) { g = ""; r = ""; z = ""; } printf("%s %s _ _ %s\n", g, r, z); printf("%s __ _ _ __ __ _ _ __ __ _ ___ %s(_)_ __| |__ %s\n", g, r, z); printf("%s / _` | '__/ _` | '_ \\ / _` |/ _ \\%s| | '__| '_ \\ %s\n", g, r, z); printf("%s| (_| | | | (_| | | | | (_| | (_) %s| | | | |_) |%s\n", g, r, z); printf("%s \\__,_|_| \\__,_|_| |_|\\__, |\\___/%s|_|_| |_.__/ %s\n", g, r, z); printf("%s |___/ %s %s\n", g, r, z); cout << endl << "Welcome to arangosh " << TRI_VERSION_FULL << ". Copyright (c) 2012 triAGENS GmbH" << endl; #ifdef TRI_V8_VERSION cout << "Using MRUBY " << TRI_MRUBY_VERSION << " engine. Copyright (c) 2012 mruby developers." << endl; #endif #ifdef TRI_READLINE_VERSION cout << "Using READLINE " << TRI_READLINE_VERSION << endl; #endif cout << endl; BaseClient.printWelcomeInfo(); if (useServer) { if (ClientConnection->isConnected()) { if (! BaseClient.quiet()) { cout << "Connected to ArangoDB '" << BaseClient.endpointServer()->getSpecification() << "' Version " << ClientConnection->getVersion() << endl; } } else { cerr << "Could not connect to endpoint '" << BaseClient.endpointString() << "'" << endl; cerr << "Error message '" << ClientConnection->getErrorMessage() << "'" << endl; } } } // ............................................................................. // read files // ............................................................................. // load java script from js/bootstrap/*.h files if (StartupPath.empty()) { StartupLoader.defineScript("common/bootstrap/error.rb", MR_common_bootstrap_error); } else { LOGGER_DEBUG("using Ruby startup files at '" << StartupPath << "'"); StartupLoader.setDirectory(StartupPath); } // load all init files char const* files[] = { "common/bootstrap/error.rb" }; for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) { bool ok = StartupLoader.loadScript(mrb, files[i]); if (ok) { LOGGER_TRACE("loaded ruby file '" << files[i] << "'"); } else { LOGGER_FATAL_AND_EXIT("cannot load ruby file '" << files[i] << "'"); } } // ............................................................................. // run normal shell // ............................................................................. RunShell(mrb); TRIAGENS_REST_SHUTDOWN; return ret; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <commit_msg>fixed typo in ifdef<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief MRuby shell /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include <mruby.h> #include <mruby/proc.h> #include <mruby/data.h> #include <mruby/variable.h> #include <mruby/compile.h> #include <stdio.h> #include <fstream> #include "BasicsC/common.h" #include "ArangoShell/ArangoClient.h" #include "Basics/FileUtils.h" #include "Basics/ProgramOptions.h" #include "Basics/ProgramOptionsDescription.h" #include "Basics/StringUtils.h" #include "BasicsC/csv.h" #include "BasicsC/files.h" #include "BasicsC/init.h" #include "BasicsC/logging.h" #include "BasicsC/shell-colors.h" #include "BasicsC/tri-strings.h" #include "BasicsC/terminal-utils.h" #include "Logger/Logger.h" #include "MRClient/MRubyClientConnection.h" #include "MRuby/MRLineEditor.h" #include "MRuby/MRLoader.h" #include "MRuby/mr-utils.h" #include "Rest/Endpoint.h" #include "Rest/InitialiseRest.h" #include "SimpleHttpClient/SimpleHttpClient.h" #include "SimpleHttpClient/SimpleHttpResult.h" using namespace std; using namespace triagens::basics; using namespace triagens::rest; using namespace triagens::httpclient; using namespace triagens::arango; using namespace triagens::mrclient; #include "mr/common/bootstrap/mr-error.h" // ----------------------------------------------------------------------------- // --SECTION-- private variables // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup MRShell /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief base class for clients //////////////////////////////////////////////////////////////////////////////// ArangoClient BaseClient; //////////////////////////////////////////////////////////////////////////////// /// @brief the initial default connection //////////////////////////////////////////////////////////////////////////////// MRubyClientConnection* ClientConnection = 0; //////////////////////////////////////////////////////////////////////////////// /// @brief startup MR files //////////////////////////////////////////////////////////////////////////////// static MRLoader StartupLoader; //////////////////////////////////////////////////////////////////////////////// /// @brief path for Ruby modules files //////////////////////////////////////////////////////////////////////////////// static string StartupModules = ""; //////////////////////////////////////////////////////////////////////////////// /// @brief path for Ruby bootstrap files //////////////////////////////////////////////////////////////////////////////// static string StartupPath = ""; //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- ruby functions // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup MRShell /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief ClientConnection method "httpGet" //////////////////////////////////////////////////////////////////////////////// static mrb_value ClientConnection_httpGet (mrb_state* mrb, mrb_value self) { char* url; /* int res; */ size_t l; struct RData* rdata; MRubyClientConnection* connection; /* res = */ mrb_get_args(mrb, "s", &url, &l); if (url == 0) { return self; } // looking at "mruby.h" I assume that is the way to unwrap the pointer rdata = (struct RData*) mrb_object(self); connection = (MRubyClientConnection*) rdata->data; if (connection == NULL) { printf("unknown connection (TODO raise error)\n"); return self; } // check header fields map<string, string> headerFields; // and execute return connection->getData(url, headerFields); } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- private functions // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup MRShell /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief return a new client connection instance //////////////////////////////////////////////////////////////////////////////// static MRubyClientConnection* createConnection (mrb_state* mrb) { return new MRubyClientConnection(mrb, BaseClient.endpointServer(), BaseClient.username(), BaseClient.password(), BaseClient.requestTimeout(), BaseClient.connectTimeout(), ArangoClient::DEFAULT_RETRIES, false); } //////////////////////////////////////////////////////////////////////////////// /// @brief parses the program options //////////////////////////////////////////////////////////////////////////////// static void ParseProgramOptions (int argc, char* argv[]) { ProgramOptionsDescription description("STANDARD options"); ProgramOptionsDescription ruby("RUBY options"); ruby ("ruby.directory", &StartupPath, "startup paths containing the Ruby files; multiple directories can be separated by cola") ("ruby.modules-path", &StartupModules, "one or more directories separated by cola") ; description (ruby, false) ; // fill in used options BaseClient.setupGeneral(description); BaseClient.setupServer(description); // and parse the command line and config file ProgramOptions options; BaseClient.parse(options, description, argc, argv, "arangoirb.conf"); // check module path if (StartupModules.empty()) { LOGGER_FATAL_AND_EXIT("module path not known, please use '--ruby.modules-path'"); } } //////////////////////////////////////////////////////////////////////////////// /// @brief set-up the connection functions //////////////////////////////////////////////////////////////////////////////// static void MR_ArangoConnection_Free (mrb_state* mrb, void* p) { printf("free of ArangoCollection called\n"); } static const struct mrb_data_type MR_ArangoConnection_Type = { "ArangoConnection", MR_ArangoConnection_Free }; static void InitMRClientConnection (mrb_state* mrb, MRubyClientConnection* connection) { struct RClass *rcl; // ............................................................................. // arango client connection // ............................................................................. rcl = mrb_define_class(mrb, "ArangoConnection", mrb->object_class); mrb_define_method(mrb, rcl, "get", ClientConnection_httpGet, ARGS_REQ(1)); // create the connection variable mrb_value arango = mrb_obj_value(Data_Wrap_Struct(mrb, rcl, &MR_ArangoConnection_Type, (void*) connection)); mrb_gv_set(mrb, mrb_intern(mrb, "$arango"), arango); } //////////////////////////////////////////////////////////////////////////////// /// @brief executes the shell //////////////////////////////////////////////////////////////////////////////// static void RunShell (mrb_state* mrb) { MRLineEditor console(mrb, ".arangoirb.history"); console.open(false /*! NoAutoComplete*/); while (true) { char* input = console.prompt("arangoirb> "); if (input == 0) { break; } if (*input == '\0') { TRI_FreeString(TRI_CORE_MEM_ZONE, input); continue; } console.addHistory(input); struct mrb_parser_state* p = mrb_parse_nstring(mrb, input, strlen(input), NULL); TRI_FreeString(TRI_CORE_MEM_ZONE, input); if (p == 0 || p->tree == 0 || 0 < p->nerr) { cout << "UPPS!\n"; continue; } int n = mrb_generate_code(mrb, p); if (n < 0) { cout << "UPPS: " << n << " returned by mrb_generate_code\n"; continue; } mrb_value result = mrb_run(mrb, mrb_proc_new(mrb, mrb->irep[n]), mrb_top_self(mrb)); if (mrb->exc) { cout << "Caught exception:\n"; mrb_p(mrb, mrb_obj_value(mrb->exc)); mrb->exc = 0; } else if (! mrb_nil_p(result)) { mrb_p(mrb, result); } } console.close(); cout << endl; BaseClient.printByeBye(); } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- public functions // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup MRShell /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief main //////////////////////////////////////////////////////////////////////////////// int main (int argc, char* argv[]) { TRIAGENS_C_INITIALISE(argc, argv); TRIAGENS_REST_INITIALISE(argc, argv); TRI_InitialiseLogging(false); int ret = EXIT_SUCCESS; BaseClient.setEndpointString(Endpoint::getDefaultEndpoint()); // ............................................................................. // parse the program options // ............................................................................. ParseProgramOptions(argc, argv); // ............................................................................. // set-up MRuby objects // ............................................................................. // create a new ruby shell mrb_state* mrb = MR_OpenShell(); TRI_InitMRUtils(mrb); // ............................................................................. // set-up client connection // ............................................................................. // check if we want to connect to a server bool useServer = (BaseClient.endpointString() != "none"); if (useServer) { BaseClient.createEndpoint(); if (BaseClient.endpointServer() == 0) { LOGGER_FATAL_AND_EXIT("invalid value for --server.endpoint ('" << BaseClient.endpointString() << "')"); } ClientConnection = createConnection(mrb); InitMRClientConnection(mrb, ClientConnection); } // ............................................................................. // banner // ............................................................................. // http://www.network-science.de/ascii/ Font: ogre if (! BaseClient.quiet()) { char const* g = TRI_SHELL_COLOR_GREEN; char const* r = TRI_SHELL_COLOR_RED; char const* z = TRI_SHELL_COLOR_RESET; if (! BaseClient.colors()) { g = ""; r = ""; z = ""; } printf("%s %s _ _ %s\n", g, r, z); printf("%s __ _ _ __ __ _ _ __ __ _ ___ %s(_)_ __| |__ %s\n", g, r, z); printf("%s / _` | '__/ _` | '_ \\ / _` |/ _ \\%s| | '__| '_ \\ %s\n", g, r, z); printf("%s| (_| | | | (_| | | | | (_| | (_) %s| | | | |_) |%s\n", g, r, z); printf("%s \\__,_|_| \\__,_|_| |_|\\__, |\\___/%s|_|_| |_.__/ %s\n", g, r, z); printf("%s |___/ %s %s\n", g, r, z); cout << endl << "Welcome to arangosh " << TRI_VERSION_FULL << ". Copyright (c) 2012 triAGENS GmbH" << endl; #ifdef TRI_MRUBY_VERSION cout << "Using MRUBY " << TRI_MRUBY_VERSION << " engine. Copyright (c) 2012 mruby developers." << endl; #endif #ifdef TRI_READLINE_VERSION cout << "Using READLINE " << TRI_READLINE_VERSION << endl; #endif cout << endl; BaseClient.printWelcomeInfo(); if (useServer) { if (ClientConnection->isConnected()) { if (! BaseClient.quiet()) { cout << "Connected to ArangoDB '" << BaseClient.endpointServer()->getSpecification() << "' Version " << ClientConnection->getVersion() << endl; } } else { cerr << "Could not connect to endpoint '" << BaseClient.endpointString() << "'" << endl; cerr << "Error message '" << ClientConnection->getErrorMessage() << "'" << endl; } } } // ............................................................................. // read files // ............................................................................. // load java script from js/bootstrap/*.h files if (StartupPath.empty()) { StartupLoader.defineScript("common/bootstrap/error.rb", MR_common_bootstrap_error); } else { LOGGER_DEBUG("using Ruby startup files at '" << StartupPath << "'"); StartupLoader.setDirectory(StartupPath); } // load all init files char const* files[] = { "common/bootstrap/error.rb" }; for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) { bool ok = StartupLoader.loadScript(mrb, files[i]); if (ok) { LOGGER_TRACE("loaded ruby file '" << files[i] << "'"); } else { LOGGER_FATAL_AND_EXIT("cannot load ruby file '" << files[i] << "'"); } } // ............................................................................. // run normal shell // ............................................................................. RunShell(mrb); TRIAGENS_REST_SHUTDOWN; return ret; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <|endoftext|>
<commit_before>#include "util/file_piece.hh" #include "util/exception.hh" #include <string> #include <limits> #include <assert.h> #include <cstdlib> #include <ctype.h> #include <err.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #ifdef HAVE_ZLIB #include <zlib.h> #endif namespace util { EndOfFileException::EndOfFileException() throw() { *this << "End of file"; } EndOfFileException::~EndOfFileException() throw() {} ParseNumberException::ParseNumberException(StringPiece value) throw() { *this << "Could not parse \"" << value << "\" into a float"; } GZException::GZException(void *file) { #ifdef HAVE_ZLIB int num; *this << gzerror(file, &num) << " from zlib"; #endif // HAVE_ZLIB } int OpenReadOrThrow(const char *name) { int ret = open(name, O_RDONLY); if (ret == -1) UTIL_THROW(ErrnoException, "in open (" << name << ") for reading"); return ret; } off_t SizeFile(int fd) { struct stat sb; if (fstat(fd, &sb) == -1 || (!sb.st_size && !S_ISREG(sb.st_mode))) return kBadSize; return sb.st_size; } FilePiece::FilePiece(const char *name, std::ostream *show_progress, off_t min_buffer) throw (GZException) : file_(OpenReadOrThrow(name)), total_size_(SizeFile(file_.get())), page_(sysconf(_SC_PAGE_SIZE)), progress_(total_size_ == kBadSize ? NULL : show_progress, std::string("Reading ") + name, total_size_) { Initialize(name, show_progress, min_buffer); } FilePiece::FilePiece(int fd, const char *name, std::ostream *show_progress, off_t min_buffer) throw (GZException) : file_(fd), total_size_(SizeFile(file_.get())), page_(sysconf(_SC_PAGE_SIZE)), progress_(total_size_ == kBadSize ? NULL : show_progress, std::string("Reading ") + name, total_size_) { Initialize(name, show_progress, min_buffer); } FilePiece::~FilePiece() { #ifdef HAVE_ZLIB if (gz_file_) { // zlib took ownership file_.release(); int ret; if (Z_OK != (ret = gzclose(gz_file_))) { errx(1, "could not close file %s using zlib", file_name_.c_str()); abort(); } } #endif } void FilePiece::Initialize(const char *name, std::ostream *show_progress, off_t min_buffer) throw (GZException) { #ifdef HAVE_ZLIB gz_file_ = NULL; #endif file_name_ = name; default_map_size_ = page_ * std::max<off_t>((min_buffer / page_ + 1), 2); position_ = NULL; position_end_ = NULL; mapped_offset_ = 0; at_end_ = false; if (total_size_ == kBadSize) { // So the assertion passes. fallback_to_read_ = false; if (show_progress) *show_progress << "File " << name << " isn't normal. Using slower read() instead of mmap(). No progress bar." << std::endl; TransitionToRead(); } else { fallback_to_read_ = false; } Shift(); // gzip detect. if ((position_end_ - position_) > 2 && *position_ == 0x1f && static_cast<unsigned char>(*(position_ + 1)) == 0x8b) { #ifndef HAVE_ZLIB UTIL_THROW(GZException, "Looks like a gzip file but support was not compiled in."); #endif if (!fallback_to_read_) { at_end_ = false; TransitionToRead(); } } } float FilePiece::ReadFloat() throw(GZException, EndOfFileException, ParseNumberException) { SkipSpaces(); while (last_space_ < position_) { if (at_end_) { // Hallucinate a null off the end of the file. std::string buffer(position_, position_end_); char *end; float ret = strtof(buffer.c_str(), &end); if (buffer.c_str() == end) throw ParseNumberException(buffer); position_ += end - buffer.c_str(); return ret; } Shift(); } char *end; float ret = strtof(position_, &end); if (end == position_) throw ParseNumberException(ReadDelimited()); position_ = end; return ret; } void FilePiece::SkipSpaces() throw (GZException, EndOfFileException) { for (; ; ++position_) { if (position_ == position_end_) Shift(); if (!isspace(*position_)) return; } } const char *FilePiece::FindDelimiterOrEOF() throw (GZException, EndOfFileException) { for (const char *i = position_; i <= last_space_; ++i) { if (isspace(*i)) return i; } while (!at_end_) { size_t skip = position_end_ - position_; Shift(); for (const char *i = position_ + skip; i <= last_space_; ++i) { if (isspace(*i)) return i; } } return position_end_; } StringPiece FilePiece::ReadLine(char delim) throw (GZException, EndOfFileException) { const char *start = position_; do { for (const char *i = start; i < position_end_; ++i) { if (*i == delim) { StringPiece ret(position_, i - position_); position_ = i + 1; return ret; } } size_t skip = position_end_ - position_; Shift(); start = position_ + skip; } while (!at_end_); StringPiece ret(position_, position_end_ - position_); position_ = position_end_; return position_; } void FilePiece::Shift() throw(GZException, EndOfFileException) { if (at_end_) { progress_.Finished(); throw EndOfFileException(); } off_t desired_begin = position_ - data_.begin() + mapped_offset_; if (!fallback_to_read_) MMapShift(desired_begin); // Notice an mmap failure might set the fallback. if (fallback_to_read_) ReadShift(); for (last_space_ = position_end_ - 1; last_space_ >= position_; --last_space_) { if (isspace(*last_space_)) break; } } void FilePiece::MMapShift(off_t desired_begin) throw() { // Use mmap. off_t ignore = desired_begin % page_; // Duplicate request for Shift means give more data. if (position_ == data_.begin() + ignore) { default_map_size_ *= 2; } // Local version so that in case of failure it doesn't overwrite the class variable. off_t mapped_offset = desired_begin - ignore; off_t mapped_size; if (default_map_size_ >= static_cast<size_t>(total_size_ - mapped_offset)) { at_end_ = true; mapped_size = total_size_ - mapped_offset; } else { mapped_size = default_map_size_; } // Forcibly clear the existing mmap first. data_.reset(); data_.reset(mmap(NULL, mapped_size, PROT_READ, MAP_PRIVATE, *file_, mapped_offset), mapped_size, scoped_memory::MMAP_ALLOCATED); if (data_.get() == MAP_FAILED) { if (desired_begin) { if (((off_t)-1) == lseek(*file_, desired_begin, SEEK_SET)) UTIL_THROW(ErrnoException, "mmap failed even though it worked before. lseek failed too, so using read isn't an option either."); } // The mmap was scheduled to end the file, but now we're going to read it. at_end_ = false; TransitionToRead(); return; } mapped_offset_ = mapped_offset; position_ = data_.begin() + ignore; position_end_ = data_.begin() + mapped_size; progress_.Set(desired_begin); } void FilePiece::TransitionToRead() throw (GZException) { assert(!fallback_to_read_); fallback_to_read_ = true; data_.reset(); data_.reset(malloc(default_map_size_), default_map_size_, scoped_memory::MALLOC_ALLOCATED); if (!data_.get()) UTIL_THROW(ErrnoException, "malloc failed for " << default_map_size_); position_ = data_.begin(); position_end_ = position_; #ifdef HAVE_ZLIB assert(!gz_file_); gz_file_ = gzdopen(file_.get(), "r"); if (!gz_file_) { UTIL_THROW(GZException, "zlib failed to open " << file_name_); } #endif } void FilePiece::ReadShift() throw(GZException, EndOfFileException) { assert(fallback_to_read_); // Bytes [data_.begin(), position_) have been consumed. // Bytes [position_, position_end_) have been read into the buffer. // Start at the beginning of the buffer if there's nothing useful in it. if (position_ == position_end_) { mapped_offset_ += (position_end_ - data_.begin()); position_ = data_.begin(); position_end_ = position_; } std::size_t already_read = position_end_ - data_.begin(); if (already_read == default_map_size_) { if (position_ == data_.begin()) { // Buffer too small. std::size_t valid_length = position_end_ - position_; default_map_size_ *= 2; data_.call_realloc(default_map_size_); if (!data_.get()) UTIL_THROW(ErrnoException, "realloc failed for " << default_map_size_); position_ = data_.begin(); position_end_ = position_ + valid_length; } else { size_t moving = position_end_ - position_; memmove(data_.get(), position_, moving); position_ = data_.begin(); position_end_ = position_ + moving; already_read = moving; } } ssize_t read_return; #ifdef HAVE_ZLIB read_return = gzread(gz_file_, static_cast<char*>(data_.get()) + already_read, default_map_size_ - already_read); if (read_return == -1) throw GZException(gz_file_); if (total_size_ != kBadSize) { // Just get the position, don't actually seek. Apparently this is how you do it. . . off_t ret = lseek(file_.get(), 0, SEEK_CUR); if (ret != -1) progress_.Set(ret); } #else read_return = read(file_.get(), static_cast<char*>(data_.get()) + already_read, default_map_size_ - already_read); if (read_return == -1) UTIL_THROW(ErrnoException, "read failed"); progress_.Set(mapped_offset_); #endif if (read_return == 0) { at_end_ = true; } position_end_ += read_return; } } // namespace util <commit_msg>Fix return value of FilePiece::ReadLine at end of file. Did not impact existing kenlm (since they don't read to the end of file) but will impact future versions. <commit_after>#include "util/file_piece.hh" #include "util/exception.hh" #include <string> #include <limits> #include <assert.h> #include <ctype.h> #include <err.h> #include <fcntl.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #ifdef HAVE_ZLIB #include <zlib.h> #endif namespace util { EndOfFileException::EndOfFileException() throw() { *this << "End of file"; } EndOfFileException::~EndOfFileException() throw() {} ParseNumberException::ParseNumberException(StringPiece value) throw() { *this << "Could not parse \"" << value << "\" into a float"; } GZException::GZException(void *file) { #ifdef HAVE_ZLIB int num; *this << gzerror(file, &num) << " from zlib"; #endif // HAVE_ZLIB } int OpenReadOrThrow(const char *name) { int ret = open(name, O_RDONLY); if (ret == -1) UTIL_THROW(ErrnoException, "in open (" << name << ") for reading"); return ret; } off_t SizeFile(int fd) { struct stat sb; if (fstat(fd, &sb) == -1 || (!sb.st_size && !S_ISREG(sb.st_mode))) return kBadSize; return sb.st_size; } FilePiece::FilePiece(const char *name, std::ostream *show_progress, off_t min_buffer) throw (GZException) : file_(OpenReadOrThrow(name)), total_size_(SizeFile(file_.get())), page_(sysconf(_SC_PAGE_SIZE)), progress_(total_size_ == kBadSize ? NULL : show_progress, std::string("Reading ") + name, total_size_) { Initialize(name, show_progress, min_buffer); } FilePiece::FilePiece(int fd, const char *name, std::ostream *show_progress, off_t min_buffer) throw (GZException) : file_(fd), total_size_(SizeFile(file_.get())), page_(sysconf(_SC_PAGE_SIZE)), progress_(total_size_ == kBadSize ? NULL : show_progress, std::string("Reading ") + name, total_size_) { Initialize(name, show_progress, min_buffer); } FilePiece::~FilePiece() { #ifdef HAVE_ZLIB if (gz_file_) { // zlib took ownership file_.release(); int ret; if (Z_OK != (ret = gzclose(gz_file_))) { errx(1, "could not close file %s using zlib", file_name_.c_str()); abort(); } } #endif } void FilePiece::Initialize(const char *name, std::ostream *show_progress, off_t min_buffer) throw (GZException) { #ifdef HAVE_ZLIB gz_file_ = NULL; #endif file_name_ = name; default_map_size_ = page_ * std::max<off_t>((min_buffer / page_ + 1), 2); position_ = NULL; position_end_ = NULL; mapped_offset_ = 0; at_end_ = false; if (total_size_ == kBadSize) { // So the assertion passes. fallback_to_read_ = false; if (show_progress) *show_progress << "File " << name << " isn't normal. Using slower read() instead of mmap(). No progress bar." << std::endl; TransitionToRead(); } else { fallback_to_read_ = false; } Shift(); // gzip detect. if ((position_end_ - position_) > 2 && *position_ == 0x1f && static_cast<unsigned char>(*(position_ + 1)) == 0x8b) { #ifndef HAVE_ZLIB UTIL_THROW(GZException, "Looks like a gzip file but support was not compiled in."); #endif if (!fallback_to_read_) { at_end_ = false; TransitionToRead(); } } } float FilePiece::ReadFloat() throw(GZException, EndOfFileException, ParseNumberException) { SkipSpaces(); while (last_space_ < position_) { if (at_end_) { // Hallucinate a null off the end of the file. std::string buffer(position_, position_end_); char *end; float ret = strtof(buffer.c_str(), &end); if (buffer.c_str() == end) throw ParseNumberException(buffer); position_ += end - buffer.c_str(); return ret; } Shift(); } char *end; float ret = strtof(position_, &end); if (end == position_) throw ParseNumberException(ReadDelimited()); position_ = end; return ret; } void FilePiece::SkipSpaces() throw (GZException, EndOfFileException) { for (; ; ++position_) { if (position_ == position_end_) Shift(); if (!isspace(*position_)) return; } } const char *FilePiece::FindDelimiterOrEOF() throw (GZException, EndOfFileException) { for (const char *i = position_; i <= last_space_; ++i) { if (isspace(*i)) return i; } while (!at_end_) { size_t skip = position_end_ - position_; Shift(); for (const char *i = position_ + skip; i <= last_space_; ++i) { if (isspace(*i)) return i; } } return position_end_; } StringPiece FilePiece::ReadLine(char delim) throw (GZException, EndOfFileException) { const char *start = position_; do { for (const char *i = start; i < position_end_; ++i) { if (*i == delim) { StringPiece ret(position_, i - position_); position_ = i + 1; return ret; } } size_t skip = position_end_ - position_; Shift(); start = position_ + skip; } while (!at_end_); StringPiece ret(position_, position_end_ - position_); position_ = position_end_; return ret; } void FilePiece::Shift() throw(GZException, EndOfFileException) { if (at_end_) { progress_.Finished(); throw EndOfFileException(); } off_t desired_begin = position_ - data_.begin() + mapped_offset_; if (!fallback_to_read_) MMapShift(desired_begin); // Notice an mmap failure might set the fallback. if (fallback_to_read_) ReadShift(); for (last_space_ = position_end_ - 1; last_space_ >= position_; --last_space_) { if (isspace(*last_space_)) break; } } void FilePiece::MMapShift(off_t desired_begin) throw() { // Use mmap. off_t ignore = desired_begin % page_; // Duplicate request for Shift means give more data. if (position_ == data_.begin() + ignore) { default_map_size_ *= 2; } // Local version so that in case of failure it doesn't overwrite the class variable. off_t mapped_offset = desired_begin - ignore; off_t mapped_size; if (default_map_size_ >= static_cast<size_t>(total_size_ - mapped_offset)) { at_end_ = true; mapped_size = total_size_ - mapped_offset; } else { mapped_size = default_map_size_; } // Forcibly clear the existing mmap first. data_.reset(); data_.reset(mmap(NULL, mapped_size, PROT_READ, MAP_PRIVATE, *file_, mapped_offset), mapped_size, scoped_memory::MMAP_ALLOCATED); if (data_.get() == MAP_FAILED) { if (desired_begin) { if (((off_t)-1) == lseek(*file_, desired_begin, SEEK_SET)) UTIL_THROW(ErrnoException, "mmap failed even though it worked before. lseek failed too, so using read isn't an option either."); } // The mmap was scheduled to end the file, but now we're going to read it. at_end_ = false; TransitionToRead(); return; } mapped_offset_ = mapped_offset; position_ = data_.begin() + ignore; position_end_ = data_.begin() + mapped_size; progress_.Set(desired_begin); } void FilePiece::TransitionToRead() throw (GZException) { assert(!fallback_to_read_); fallback_to_read_ = true; data_.reset(); data_.reset(malloc(default_map_size_), default_map_size_, scoped_memory::MALLOC_ALLOCATED); if (!data_.get()) UTIL_THROW(ErrnoException, "malloc failed for " << default_map_size_); position_ = data_.begin(); position_end_ = position_; #ifdef HAVE_ZLIB assert(!gz_file_); gz_file_ = gzdopen(file_.get(), "r"); if (!gz_file_) { UTIL_THROW(GZException, "zlib failed to open " << file_name_); } #endif } void FilePiece::ReadShift() throw(GZException, EndOfFileException) { assert(fallback_to_read_); // Bytes [data_.begin(), position_) have been consumed. // Bytes [position_, position_end_) have been read into the buffer. // Start at the beginning of the buffer if there's nothing useful in it. if (position_ == position_end_) { mapped_offset_ += (position_end_ - data_.begin()); position_ = data_.begin(); position_end_ = position_; } std::size_t already_read = position_end_ - data_.begin(); if (already_read == default_map_size_) { if (position_ == data_.begin()) { // Buffer too small. std::size_t valid_length = position_end_ - position_; default_map_size_ *= 2; data_.call_realloc(default_map_size_); if (!data_.get()) UTIL_THROW(ErrnoException, "realloc failed for " << default_map_size_); position_ = data_.begin(); position_end_ = position_ + valid_length; } else { size_t moving = position_end_ - position_; memmove(data_.get(), position_, moving); position_ = data_.begin(); position_end_ = position_ + moving; already_read = moving; } } ssize_t read_return; #ifdef HAVE_ZLIB read_return = gzread(gz_file_, static_cast<char*>(data_.get()) + already_read, default_map_size_ - already_read); if (read_return == -1) throw GZException(gz_file_); if (total_size_ != kBadSize) { // Just get the position, don't actually seek. Apparently this is how you do it. . . off_t ret = lseek(file_.get(), 0, SEEK_CUR); if (ret != -1) progress_.Set(ret); } #else read_return = read(file_.get(), static_cast<char*>(data_.get()) + already_read, default_map_size_ - already_read); if (read_return == -1) UTIL_THROW(ErrnoException, "read failed"); progress_.Set(mapped_offset_); #endif if (read_return == 0) { at_end_ = true; } position_end_ += read_return; } } // namespace util <|endoftext|>
<commit_before>#include "TCanvas.h" #include "TClassTable.h" #include "TFile.h" #include "TH1.h" #include "TKey.h" #include "TChain.h" #include "TSystem.h" #include "iostream.h" #include "dt_DrawTest.C" Bool_t gInteractiveTest = kTRUE; Bool_t gQuietLevel = 0; //_______________________________________________________________ Int_t HistCompare(TH1 *ref, TH1 *comp) { // Compare histograms h1 and h2 // Check number of entries, mean and rms // if means differ by more than 1/1000 of the range return -1 // if rms differs in percent by more than 1/1000 return -2 // Otherwise return difference of number of entries Int_t n1 = (Int_t)ref->GetEntries(); Double_t mean1 = ref->GetMean(); Double_t rms1 = ref->GetRMS(); Int_t n2 = (Int_t)comp->GetEntries(); Double_t mean2 = comp->GetMean(); Double_t rms2 = comp->GetRMS(); Int_t factor = 1; if (n2==2*n1) { // we have a chain. factor = 2; } Float_t xrange = ref->GetXaxis()->GetXmax() - ref->GetXaxis()->GetXmin(); if (TMath::Abs((mean1-mean2)/xrange) > 0.001*xrange) return -1; if (rms1 && TMath::Abs((rms1-rms2)/rms1) > 0.001) return -2; return n1*factor-n2; } Int_t Compare(TDirectory* from) { TFile * reffile = new TFile("dt_reference.root"); TIter next(reffile->GetListOfKeys()); TH1 *ref, *draw; const char* name; Int_t comp; Int_t fail = 0; TKey* key; while ((key=(TKey*)next())) { if (strcmp(key->GetClassName(),"TH1F") && strcmp(key->GetClassName(),"TH2F") ) continue; //may be a TList of TStreamerInfo ref = (TH1*)reffile->Get(key->GetName()); name = ref->GetName(); if (strncmp(name,"ref",3)) continue; name += 3; draw = (TH1*)from->Get(name); if (!draw) { if (!gSkipped.FindObject(name)) { cerr << "Miss: " << name << endl; fail++; } continue; } comp = HistCompare(ref,draw); if (comp!=0) { cerr << "Fail: " << name << ":" << comp << endl; fail++; if (gInteractiveTest) { TCanvas * canv = new TCanvas(); canv->Divide(2,1); canv->cd(1); ref->Draw(); canv->cd(2); draw->Draw(); return 1; } } else { if (gQuietLevel<1) cerr << "Succ: " << name << ":" << comp << endl; } } return fail; } void SetVerboseLevel(Int_t verboseLevel) { switch (verboseLevel) { case 0: gInteractiveTest = kFALSE; gQuietLevel = 2; break; case 1: gInteractiveTest = kFALSE; gQuietLevel = 1; break; case 2: gInteractiveTest = kFALSE; gQuietLevel = 0; break; case 3: gInteractiveTest = kTRUE; gQuietLevel = 0; break; } } void dt_RunDrawTest(const char* from, Int_t mode = 0, Int_t verboseLevel = 0) { // This launch a test a TTree::Draw. // The mode currently available are: // 0: Do not load the shared library // 1: Load the shared library before opening the file // 2: Load the shared library after opening the file // 3: Simple TChain test with shared library // 4: Simple Friend test with shared library // The verboseLeve currently available: // 0: As silent as possible, only report errors and overall speed results. // 1: Output 0 + label for the start of each phase // 2: Output 1 + more details on the different phase being done // 3: Output 2 + stop at the first and draw a canvas showing the differences SetVerboseLevel(verboseLevel); if (mode == 1) { if (!TClassTable::GetDict("Event")) { gSystem->Load("libEvent"); } gHasLibrary = kTRUE; } TFile *hfile = 0; TTree *tree; if (mode <3) { hfile = new TFile(from); tree = (TTree*)hfile->Get("T"); } if (mode >= 2 && mode <= 4) { if (!TClassTable::GetDict("Event")) { gSystem->Load("libEvent"); } else { cerr << "Since libEvent.so has already been loaded, mode 2 can not be tested!"; cerr << endl; } gHasLibrary = kTRUE; } if (mode == 3) { // Test Chains. TChain * chain = new TChain("T"); chain->Add(from); chain->Add(from); tree = chain; } if (mode == 4) { // Test friends. tree = new TTree("T","Base of friendship"); tree->AddFriend("T",from); } if (gQuietLevel<2) cout << "Generating histograms from TTree::Draw" << endl; TDirectory* where = GenerateDrawHist(tree); if (gQuietLevel<2) cout << "Comparing histograms" << endl; if (Compare(where)>0) { cout << "DrawTest: Comparison failed" << endl; return; } DrawMarks(); cout << "DrawTest: Comparison was successfull" << endl; if (hfile) delete hfile; else delete tree; gROOT->GetList()->Delete(); } <commit_msg>Initialize local variable tree to 0 to avoid a compiler warning.<commit_after>#include "TCanvas.h" #include "TClassTable.h" #include "TFile.h" #include "TH1.h" #include "TKey.h" #include "TChain.h" #include "TSystem.h" #include "iostream.h" #include "dt_DrawTest.C" Bool_t gInteractiveTest = kTRUE; Bool_t gQuietLevel = 0; //_______________________________________________________________ Int_t HistCompare(TH1 *ref, TH1 *comp) { // Compare histograms h1 and h2 // Check number of entries, mean and rms // if means differ by more than 1/1000 of the range return -1 // if rms differs in percent by more than 1/1000 return -2 // Otherwise return difference of number of entries Int_t n1 = (Int_t)ref->GetEntries(); Double_t mean1 = ref->GetMean(); Double_t rms1 = ref->GetRMS(); Int_t n2 = (Int_t)comp->GetEntries(); Double_t mean2 = comp->GetMean(); Double_t rms2 = comp->GetRMS(); Int_t factor = 1; if (n2==2*n1) { // we have a chain. factor = 2; } Float_t xrange = ref->GetXaxis()->GetXmax() - ref->GetXaxis()->GetXmin(); if (TMath::Abs((mean1-mean2)/xrange) > 0.001*xrange) return -1; if (rms1 && TMath::Abs((rms1-rms2)/rms1) > 0.001) return -2; return n1*factor-n2; } Int_t Compare(TDirectory* from) { TFile * reffile = new TFile("dt_reference.root"); TIter next(reffile->GetListOfKeys()); TH1 *ref, *draw; const char* name; Int_t comp; Int_t fail = 0; TKey* key; while ((key=(TKey*)next())) { if (strcmp(key->GetClassName(),"TH1F") && strcmp(key->GetClassName(),"TH2F") ) continue; //may be a TList of TStreamerInfo ref = (TH1*)reffile->Get(key->GetName()); name = ref->GetName(); if (strncmp(name,"ref",3)) continue; name += 3; draw = (TH1*)from->Get(name); if (!draw) { if (!gSkipped.FindObject(name)) { cerr << "Miss: " << name << endl; fail++; } continue; } comp = HistCompare(ref,draw); if (comp!=0) { cerr << "Fail: " << name << ":" << comp << endl; fail++; if (gInteractiveTest) { TCanvas * canv = new TCanvas(); canv->Divide(2,1); canv->cd(1); ref->Draw(); canv->cd(2); draw->Draw(); return 1; } } else { if (gQuietLevel<1) cerr << "Succ: " << name << ":" << comp << endl; } } return fail; } void SetVerboseLevel(Int_t verboseLevel) { switch (verboseLevel) { case 0: gInteractiveTest = kFALSE; gQuietLevel = 2; break; case 1: gInteractiveTest = kFALSE; gQuietLevel = 1; break; case 2: gInteractiveTest = kFALSE; gQuietLevel = 0; break; case 3: gInteractiveTest = kTRUE; gQuietLevel = 0; break; } } void dt_RunDrawTest(const char* from, Int_t mode = 0, Int_t verboseLevel = 0) { // This launch a test a TTree::Draw. // The mode currently available are: // 0: Do not load the shared library // 1: Load the shared library before opening the file // 2: Load the shared library after opening the file // 3: Simple TChain test with shared library // 4: Simple Friend test with shared library // The verboseLeve currently available: // 0: As silent as possible, only report errors and overall speed results. // 1: Output 0 + label for the start of each phase // 2: Output 1 + more details on the different phase being done // 3: Output 2 + stop at the first and draw a canvas showing the differences SetVerboseLevel(verboseLevel); if (mode == 1) { if (!TClassTable::GetDict("Event")) { gSystem->Load("libEvent"); } gHasLibrary = kTRUE; } TFile *hfile = 0; TTree *tree = 0; if (mode <3) { hfile = new TFile(from); tree = (TTree*)hfile->Get("T"); } if (mode >= 2 && mode <= 4) { if (!TClassTable::GetDict("Event")) { gSystem->Load("libEvent"); } else { cerr << "Since libEvent.so has already been loaded, mode 2 can not be tested!"; cerr << endl; } gHasLibrary = kTRUE; } if (mode == 3) { // Test Chains. TChain * chain = new TChain("T"); chain->Add(from); chain->Add(from); tree = chain; } if (mode == 4) { // Test friends. tree = new TTree("T","Base of friendship"); tree->AddFriend("T",from); } if (gQuietLevel<2) cout << "Generating histograms from TTree::Draw" << endl; TDirectory* where = GenerateDrawHist(tree); if (gQuietLevel<2) cout << "Comparing histograms" << endl; if (Compare(where)>0) { cout << "DrawTest: Comparison failed" << endl; return; } DrawMarks(); cout << "DrawTest: Comparison was successfull" << endl; if (hfile) delete hfile; else delete tree; gROOT->GetList()->Delete(); } <|endoftext|>
<commit_before> // Qt includes #include <QDebug> #include <QLayout> #include <QTableView> #include <QStandardItemModel> #include <QHeaderView> // Visomics includes #include "voExtendedTableView.h" #include "voDataObject.h" #include "vtkExtendedTable.h" #include "voUtils.h" // VTK includes #include <vtkDoubleArray.h> #include <vtkStringArray.h> #include <vtkTable.h> // -------------------------------------------------------------------------- class voExtendedTableViewPrivate { public: voExtendedTableViewPrivate(); QTableView* TableView; QStandardItemModel Model; }; // -------------------------------------------------------------------------- // voExtendedTableViewPrivate methods // -------------------------------------------------------------------------- voExtendedTableViewPrivate::voExtendedTableViewPrivate() { this->TableView = 0; } // -------------------------------------------------------------------------- // voExtendedTableView methods // -------------------------------------------------------------------------- voExtendedTableView::voExtendedTableView(QWidget* newParent): Superclass(newParent), d_ptr(new voExtendedTableViewPrivate) { } // -------------------------------------------------------------------------- voExtendedTableView::~voExtendedTableView() { } // -------------------------------------------------------------------------- void voExtendedTableView::setupUi(QLayout *layout) { Q_D(voExtendedTableView); d->TableView = new QTableView(); d->TableView->setModel(&d->Model); layout->addWidget(d->TableView); } // -------------------------------------------------------------------------- void voExtendedTableView::setDataObject(voDataObject *dataObject) { Q_D(voExtendedTableView); if (!dataObject) { qCritical() << "voExtendedTableView - Failed to setDataObject - dataObject is NULL"; return; } vtkExtendedTable * extendedTable = vtkExtendedTable::SafeDownCast(dataObject->data()); if (!extendedTable) { qCritical() << "voExtendedTableView - Failed to setDataObject - vtkExtendedTable data is expected !"; return; } int modelRowCount = extendedTable->GetTotalNumberOfRows(); if (extendedTable->HasColumnMetaData()) { modelRowCount--; } d->Model.setRowCount(modelRowCount); int modelColumnCount = extendedTable->GetTotalNumberOfColumns(); if (extendedTable->HasRowMetaData()) { modelColumnCount--; } d->Model.setColumnCount(modelColumnCount); QColor headerBackgroundColor = QPalette().color(QPalette::Window); // Set column meta data for (vtkIdType tableRowItr = 0; tableRowItr < extendedTable->GetNumberOfColumnMetaDataTypes(); ++tableRowItr) { vtkStringArray * metadata = extendedTable->GetColumnMetaDataAsString(tableRowItr); Q_ASSERT(metadata); for(vtkIdType tableColItr = 0; tableColItr < metadata->GetNumberOfValues(); ++tableColItr) { int modelRowItr = tableRowItr; if (tableRowItr > extendedTable->GetColumnMetaDataTypeOfInterest()) { modelRowItr--; } int modelColItr = tableColItr; if (extendedTable->HasRowMetaData()) { modelColItr += extendedTable->GetNumberOfRowMetaDataTypes() - 1; } QString value = QString(metadata->GetValue(tableColItr)); if(tableRowItr == extendedTable->GetColumnMetaDataTypeOfInterest()) { value.prepend(QString("%1: ").arg(voUtils::counterIntToAlpha(tableColItr))); d->Model.setHeaderData(modelColItr, Qt::Horizontal, value); } else { QStandardItem * currentItem = new QStandardItem(value); d->Model.setItem(modelRowItr, modelColItr, currentItem); currentItem->setData(headerBackgroundColor, Qt::BackgroundRole); currentItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); } } } // Set row meta data for(vtkIdType tableColItr = 0; tableColItr < extendedTable->GetNumberOfRowMetaDataTypes(); ++tableColItr) { vtkStringArray * metadata = extendedTable->GetRowMetaDataAsString(tableColItr); Q_ASSERT(metadata); for (vtkIdType tableRowItr = 0; tableRowItr < metadata->GetNumberOfValues(); ++tableRowItr) { int modelColItr = tableColItr; if (tableColItr > extendedTable->GetRowMetaDataTypeOfInterest()) { modelColItr--; } int modelRowItr = tableRowItr; if (extendedTable->HasColumnMetaData()) { modelRowItr += extendedTable->GetNumberOfColumnMetaDataTypes() - 1; } QString value = QString(metadata->GetValue(tableRowItr)); if(tableColItr == extendedTable->GetRowMetaDataTypeOfInterest()) { value.prepend(QString("%1: ").arg(1 + tableRowItr)); d->Model.setHeaderData(modelRowItr, Qt::Vertical, value); } else { QStandardItem * currentItem = new QStandardItem(value); d->Model.setItem(modelRowItr, modelColItr, currentItem); currentItem->setData(headerBackgroundColor, Qt::BackgroundRole); currentItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); } } } // Set Data vtkTable * data = extendedTable->GetData(); if (data) { for (int cid = 0; cid < data->GetNumberOfColumns(); ++cid) { vtkDoubleArray * dataColumn = vtkDoubleArray::SafeDownCast(data->GetColumn(cid)); Q_ASSERT(dataColumn); for (int rid = 0; rid < dataColumn->GetNumberOfTuples(); ++rid) { int modelColumnId = cid; if (extendedTable->HasRowMetaData()) { modelColumnId += extendedTable->GetNumberOfRowMetaDataTypes() - 1; } int modelRowId = rid; if (extendedTable->HasColumnMetaData()) { modelRowId += extendedTable->GetNumberOfColumnMetaDataTypes() - 1; } double value = dataColumn->GetValue(rid); QStandardItem * currentItem = new QStandardItem(QString::number(value)); d->Model.setItem(modelRowId, modelColumnId, currentItem); currentItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); } } } // Set column metadata labels for (int modelRowId = 0; modelRowId < extendedTable->GetColumnMetaDataLabels()->GetNumberOfValues() - 1; ++modelRowId) { int tableRowId = modelRowId; if (tableRowId >= extendedTable->GetColumnMetaDataTypeOfInterest()) { tableRowId++; } QString value = QString(extendedTable->GetColumnMetaDataLabels()->GetValue(tableRowId)); d->Model.setHeaderData(modelRowId, Qt::Vertical, value); } // Set row metadata labels for (int modelColumnId = 0; modelColumnId < extendedTable->GetRowMetaDataLabels()->GetNumberOfValues() - 1; ++modelColumnId) { int tableColumnId = modelColumnId; if (tableColumnId >= extendedTable->GetRowMetaDataTypeOfInterest()) { tableColumnId++; } QString value = QString(extendedTable->GetRowMetaDataLabels()->GetValue(tableColumnId)); d->Model.setHeaderData(modelColumnId, Qt::Horizontal, value); } // Expand column widths to fit long labels or data d->TableView->horizontalHeader()->setMinimumSectionSize(100); d->TableView->resizeColumnsToContents(); } <commit_msg>Add ordinal labeling to metadata labels<commit_after> // Qt includes #include <QDebug> #include <QLayout> #include <QTableView> #include <QStandardItemModel> #include <QHeaderView> // Visomics includes #include "voExtendedTableView.h" #include "voDataObject.h" #include "vtkExtendedTable.h" #include "voUtils.h" // VTK includes #include <vtkDoubleArray.h> #include <vtkStringArray.h> #include <vtkTable.h> // -------------------------------------------------------------------------- class voExtendedTableViewPrivate { public: voExtendedTableViewPrivate(); QTableView* TableView; QStandardItemModel Model; }; // -------------------------------------------------------------------------- // voExtendedTableViewPrivate methods // -------------------------------------------------------------------------- voExtendedTableViewPrivate::voExtendedTableViewPrivate() { this->TableView = 0; } // -------------------------------------------------------------------------- // voExtendedTableView methods // -------------------------------------------------------------------------- voExtendedTableView::voExtendedTableView(QWidget* newParent): Superclass(newParent), d_ptr(new voExtendedTableViewPrivate) { } // -------------------------------------------------------------------------- voExtendedTableView::~voExtendedTableView() { } // -------------------------------------------------------------------------- void voExtendedTableView::setupUi(QLayout *layout) { Q_D(voExtendedTableView); d->TableView = new QTableView(); d->TableView->setModel(&d->Model); layout->addWidget(d->TableView); } // -------------------------------------------------------------------------- void voExtendedTableView::setDataObject(voDataObject *dataObject) { Q_D(voExtendedTableView); if (!dataObject) { qCritical() << "voExtendedTableView - Failed to setDataObject - dataObject is NULL"; return; } vtkExtendedTable * extendedTable = vtkExtendedTable::SafeDownCast(dataObject->data()); if (!extendedTable) { qCritical() << "voExtendedTableView - Failed to setDataObject - vtkExtendedTable data is expected !"; return; } int modelRowCount = extendedTable->GetTotalNumberOfRows(); if (extendedTable->HasColumnMetaData()) { modelRowCount--; } d->Model.setRowCount(modelRowCount); int modelColumnCount = extendedTable->GetTotalNumberOfColumns(); if (extendedTable->HasRowMetaData()) { modelColumnCount--; } d->Model.setColumnCount(modelColumnCount); QColor headerBackgroundColor = QPalette().color(QPalette::Window); // Set column meta data for (vtkIdType tableRowItr = 0; tableRowItr < extendedTable->GetNumberOfColumnMetaDataTypes(); ++tableRowItr) { vtkStringArray * metadata = extendedTable->GetColumnMetaDataAsString(tableRowItr); Q_ASSERT(metadata); for(vtkIdType tableColItr = 0; tableColItr < metadata->GetNumberOfValues(); ++tableColItr) { int modelRowItr = tableRowItr; if (tableRowItr > extendedTable->GetColumnMetaDataTypeOfInterest()) { modelRowItr--; } int modelColItr = tableColItr; if (extendedTable->HasRowMetaData()) { modelColItr += extendedTable->GetNumberOfRowMetaDataTypes() - 1; } QString value = QString(metadata->GetValue(tableColItr)); if(tableRowItr == extendedTable->GetColumnMetaDataTypeOfInterest()) { value.prepend(QString("%1: ").arg(voUtils::counterIntToAlpha(tableColItr))); d->Model.setHeaderData(modelColItr, Qt::Horizontal, value); } else { QStandardItem * currentItem = new QStandardItem(value); d->Model.setItem(modelRowItr, modelColItr, currentItem); currentItem->setData(headerBackgroundColor, Qt::BackgroundRole); currentItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); } } } // Set row meta data for(vtkIdType tableColItr = 0; tableColItr < extendedTable->GetNumberOfRowMetaDataTypes(); ++tableColItr) { vtkStringArray * metadata = extendedTable->GetRowMetaDataAsString(tableColItr); Q_ASSERT(metadata); for (vtkIdType tableRowItr = 0; tableRowItr < metadata->GetNumberOfValues(); ++tableRowItr) { int modelColItr = tableColItr; if (tableColItr > extendedTable->GetRowMetaDataTypeOfInterest()) { modelColItr--; } int modelRowItr = tableRowItr; if (extendedTable->HasColumnMetaData()) { modelRowItr += extendedTable->GetNumberOfColumnMetaDataTypes() - 1; } QString value = QString(metadata->GetValue(tableRowItr)); if(tableColItr == extendedTable->GetRowMetaDataTypeOfInterest()) { value.prepend(QString("%1: ").arg(1 + tableRowItr)); d->Model.setHeaderData(modelRowItr, Qt::Vertical, value); } else { QStandardItem * currentItem = new QStandardItem(value); d->Model.setItem(modelRowItr, modelColItr, currentItem); currentItem->setData(headerBackgroundColor, Qt::BackgroundRole); currentItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); } } } // Set Data vtkTable * data = extendedTable->GetData(); if (data) { for (int cid = 0; cid < data->GetNumberOfColumns(); ++cid) { vtkDoubleArray * dataColumn = vtkDoubleArray::SafeDownCast(data->GetColumn(cid)); Q_ASSERT(dataColumn); for (int rid = 0; rid < dataColumn->GetNumberOfTuples(); ++rid) { int modelColumnId = cid; if (extendedTable->HasRowMetaData()) { modelColumnId += extendedTable->GetNumberOfRowMetaDataTypes() - 1; } int modelRowId = rid; if (extendedTable->HasColumnMetaData()) { modelRowId += extendedTable->GetNumberOfColumnMetaDataTypes() - 1; } double value = dataColumn->GetValue(rid); QStandardItem * currentItem = new QStandardItem(QString::number(value)); d->Model.setItem(modelRowId, modelColumnId, currentItem); currentItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); } } } // Set column metadata labels for (int modelRowId = 0; modelRowId < extendedTable->GetColumnMetaDataLabels()->GetNumberOfValues() - 1; ++modelRowId) { int tableRowId = modelRowId; if (tableRowId >= extendedTable->GetColumnMetaDataTypeOfInterest()) { tableRowId++; } QString value = QString(extendedTable->GetColumnMetaDataLabels()->GetValue(tableRowId)); value.prepend(QString("%1: ").arg(voUtils::counterIntToAlpha(modelRowId))); d->Model.setHeaderData(modelRowId, Qt::Vertical, value); } // Set row metadata labels for (int modelColumnId = 0; modelColumnId < extendedTable->GetRowMetaDataLabels()->GetNumberOfValues() - 1; ++modelColumnId) { int tableColumnId = modelColumnId; if (tableColumnId >= extendedTable->GetRowMetaDataTypeOfInterest()) { tableColumnId++; } QString value = QString(extendedTable->GetRowMetaDataLabels()->GetValue(tableColumnId)); value.prepend(QString("%1: ").arg(1 + modelColumnId)); d->Model.setHeaderData(modelColumnId, Qt::Horizontal, value); } // Expand column widths to fit long labels or data d->TableView->horizontalHeader()->setMinimumSectionSize(100); d->TableView->resizeColumnsToContents(); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "settingsdialog.h" #include <QMessageBox> #include <QFileDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::showAlert(const QString &title, const QString &text) { QMessageBox messageBox; messageBox.information(0, title, text); } void MainWindow::on_pushButton_clicked() { //Start button this->showAlert("Alert", "Start"); } void MainWindow::on_pushButton_4_clicked() { //Stop button this->showAlert("Alert", "Stop"); } void MainWindow::on_pushButton_2_clicked() { //Pause button this->showAlert("Alert", "Pause"); } void MainWindow::on_pushButton_3_clicked() { //Resume button this->showAlert("Alert", "Resume"); } void MainWindow::on_actionSave_Settings_2_triggered() { // Save settings QString path = QFileDialog::getSaveFileName(this, tr("Save Settings"), tr("."), tr("Text Files (*.txt)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionLoad_Settings_2_triggered() { QString path = QFileDialog::getOpenFileName(this, tr("Open Settings File"), ".", tr("Text Files (*.txt)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionSave_Graph_triggered() { QString path = QFileDialog::getSaveFileName(this, tr("Save Graph"), tr("."), tr("Text Files (*.txt)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionZachary_format_triggered() { // Load Zachary Format QString path = QFileDialog::getOpenFileName(this, tr("Open Zachary Karate Club Graph"), ".", tr("All Files (*)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionMovielens_format_triggered() { // Load Movielens Format QString path = QFileDialog::getOpenFileName(this, tr("Open Movielens Graph"), ".", tr("All Files (*)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionSave_Population_triggered() { // Save population QString path = QFileDialog::getSaveFileName(this, tr("Save Population"), tr("."), tr("Text Files (*.txt)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionLoad_Population_triggered() { // Load population QString path = QFileDialog::getOpenFileName(this, tr("Load Population"), ".", tr("Text Files (*.txt)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionAbout_2_triggered() { QString info = "Clustring of Social Network Graphs using Genetic Algotithms\n\n\ This project was developped for the 2015 Software Engineering Lab course in Jacobs University Bremen.\ \n\nAuthors: Denis Rochau, Dinesh Kannan, Annu Thapa,\ Valentin Vasiliu, Radu Homorozan, Kiril Kafadarov"; QMessageBox::about(this, "About this project", info); } void MainWindow::on_actionEdit_Settings_triggered() { SettingsDialog dialog(this); dialog.exec(); } <commit_msg>Get my name correct!<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "settingsdialog.h" #include <QMessageBox> #include <QFileDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::showAlert(const QString &title, const QString &text) { QMessageBox messageBox; messageBox.information(0, title, text); } void MainWindow::on_pushButton_clicked() { //Start button this->showAlert("Alert", "Start"); } void MainWindow::on_pushButton_4_clicked() { //Stop button this->showAlert("Alert", "Stop"); } void MainWindow::on_pushButton_2_clicked() { //Pause button this->showAlert("Alert", "Pause"); } void MainWindow::on_pushButton_3_clicked() { //Resume button this->showAlert("Alert", "Resume"); } void MainWindow::on_actionSave_Settings_2_triggered() { // Save settings QString path = QFileDialog::getSaveFileName(this, tr("Save Settings"), tr("."), tr("Text Files (*.txt)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionLoad_Settings_2_triggered() { QString path = QFileDialog::getOpenFileName(this, tr("Open Settings File"), ".", tr("Text Files (*.txt)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionSave_Graph_triggered() { QString path = QFileDialog::getSaveFileName(this, tr("Save Graph"), tr("."), tr("Text Files (*.txt)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionZachary_format_triggered() { // Load Zachary Format QString path = QFileDialog::getOpenFileName(this, tr("Open Zachary Karate Club Graph"), ".", tr("All Files (*)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionMovielens_format_triggered() { // Load Movielens Format QString path = QFileDialog::getOpenFileName(this, tr("Open Movielens Graph"), ".", tr("All Files (*)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionSave_Population_triggered() { // Save population QString path = QFileDialog::getSaveFileName(this, tr("Save Population"), tr("."), tr("Text Files (*.txt)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionLoad_Population_triggered() { // Load population QString path = QFileDialog::getOpenFileName(this, tr("Load Population"), ".", tr("Text Files (*.txt)")); if (!path.isNull() && !path.isEmpty()) { this->showAlert("Alert", "Path is " + path); } } void MainWindow::on_actionAbout_2_triggered() { QString info = "Clustring of Social Network Graphs using Genetic Algotithms\n\n\ This project was developped for the 2015 Software Engineering Lab course in Jacobs University Bremen.\ \n\nAuthors: Denis Rochau, Dinesh Acharya, Annu Thapa,\ Valentin Vasiliu, Radu Homorozan, Kiril Kafadarov"; QMessageBox::about(this, "About this project", info); } void MainWindow::on_actionEdit_Settings_triggered() { SettingsDialog dialog(this); dialog.exec(); } <|endoftext|>
<commit_before>/* * RBGolfBall.cpp * golf * * Created by Robert Rose on 9/9/08. * Copyright 2008 Bork 3D LLC. All rights reserved. * */ #include "RBGolfBall.h" #include "RudeDebug.h" #include "RudeGL.h" #include "RudePhysicsSphere.h" #include "RudePhysics.h" #include "RudeMesh.h" #include <btBulletDynamicsCommon.h> const float kBallRadius = 0.15f; const float kBallMass = 0.1f; const float kSpinForceDelay = 0.75f; const float kSpinForceStopTime = 1.75f; const float kWindDelay = 1.0f; RBGolfBall::RBGolfBall() : m_linearContactDamping(0.0f) , m_angularContactDamping(0.0f) , m_movementThreshold(0.0f) , m_curLinearDamping(0.0f) , m_curAngularDamping(0.0f) , m_inContact(false) , m_stop(false) , m_stopped(false) , m_ballScale(kBallRadius) , m_curMaterial(kTee) , m_spinForce(0,0,0) , m_spinForceTimer(0.0f) , m_wind(0,0,0) , m_windTimer(0.0f) { } void RBGolfBall::Load(const char *name) { LoadMesh(name); LoadPhysicsSphere(kBallRadius, kBallMass); //RudeMesh *mesh = GetMesh(); //mesh->SetScale(btVector3(kBallRadius, 0.2, 0.2)); RudePhysicsSphere *obj = (RudePhysicsSphere *) GetPhysicsObject(); btRigidBody *rb = obj->GetRigidBody(); rb->setFriction(1.0f); rb->setRestitution(0.78f); rb->setCcdMotionThreshold(kBallRadius * 0.5f); rb->setCcdSweptSphereRadius(kBallRadius * 0.5f); } void RBGolfBall::NextFrame(float delta) { if(m_stopped) return; RudePhysicsSphere *obj = (RudePhysicsSphere *) GetPhysicsObject(); btRigidBody *rb = obj->GetRigidBody(); // apply force from spin if(m_applySpinForce) { m_spinForceTimer += delta; if(m_spinForceTimer < kSpinForceStopTime) { float gradient = m_spinForceTimer / kSpinForceDelay; if(gradient > 1.0f) gradient = 1.0f; btVector3 linvel = rb->getLinearVelocity(); linvel += m_spinForce * delta * gradient; rb->setLinearVelocity(linvel); } } // apply wind if(m_inContact == 0) { m_windTimer += delta; float gradient = m_windTimer / kWindDelay; if(gradient > 1.0f) gradient = 1.0f; btVector3 linvel = rb->getLinearVelocity(); linvel += m_wind * delta * gradient; rb->setLinearVelocity(linvel); } else m_windTimer = 0.0f; if(m_inContact > 0) { if(m_applySpinForce) { if(m_spinForceTimer > 0.1f) m_applySpinForce = false; } m_curLinearDamping += m_linearContactDamping * delta; m_curAngularDamping += m_angularContactDamping * delta; rb->setDamping(m_curLinearDamping, m_curAngularDamping); m_inContact--; } else { m_curLinearDamping = 0.0f; m_curAngularDamping = 0.0f; m_angularContactDamping = 0.0f; m_linearContactDamping = 0.0f; rb->setDamping(0.0f, 0.0f); } if(m_stop) { GetPhysicsObject()->GetRigidBody()->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT); m_stopped = true; } //if(!rb->isActive()) // ball has reached a stop state // printf("INACTIVE\n"); //printf("l = %f, a = %f\n", m_curLinearDamping, m_curAngularDamping); } void RBGolfBall::Render() { btVector3 eye = RGL.GetEye(); btTransform trans; GetPhysicsObject()->GetRigidBody()->getMotionState()->getWorldTransform(trans); //trans = GetPhysicsObject()->GetRigidBody()->getWorldTransform(); btVector3 ballpos = trans.getOrigin(); float scalefactor = 1.0f; float eyedist = (eye - ballpos).length(); scalefactor += eyedist / 75.0f; m_ballScale = kBallRadius * scalefactor; GetPhysicsObject()->Render(); glScalef(m_ballScale, m_ballScale, m_ballScale); GetMesh()->Render(); } void RBGolfBall::Render(btVector3 pos, btVector3 rot) { glMatrixMode(GL_MODELVIEW); btMatrix3x3 rotmat; if(rot.length() > 0.1f) { btQuaternion q(rot.normalize(), rot.length()); rotmat.setRotation(q); } else rotmat.setIdentity(); btTransform trans(rotmat, pos); btScalar m[16]; trans.getOpenGLMatrix(m); glLoadMatrixf(m); glScalef(kBallRadius, kBallRadius, kBallRadius); GetMesh()->Render(); } btVector3 RBGolfBall::GetPosition() { btTransform trans; GetPhysicsObject()->GetRigidBody()->getMotionState()->getWorldTransform(trans); return trans.getOrigin(); } btVector3 RBGolfBall::GetAngularVelocity() { return GetPhysicsObject()->GetRigidBody()->getAngularVelocity(); } btVector3 RBGolfBall::GetLinearVelocity() { return GetPhysicsObject()->GetRigidBody()->getLinearVelocity(); } void RBGolfBall::SetPosition(const btVector3 &p) { btTransform trans; trans.setIdentity(); trans.setOrigin(p); GetPhysicsObject()->GetRigidBody()->setWorldTransform(trans); GetPhysicsObject()->GetRigidBody()->activate(true); } void RBGolfBall::HitBall(const btVector3 &linvel, const btVector3 &spinForce) { m_spinForce = spinForce; m_applySpinForce = true; m_spinForceTimer = 0.0f; m_windTimer = 0.0f; m_stop = false; m_stopped = false; GetPhysicsObject()->GetRigidBody()->setCollisionFlags(0); GetPhysicsObject()->GetRigidBody()->setLinearVelocity(linvel); GetPhysicsObject()->GetRigidBody()->setAngularVelocity(btVector3(0,0,0)); GetPhysicsObject()->GetRigidBody()->clearForces(); //GetPhysicsObject()->GetRigidBody()->applyForce(p, btVector3(0,0,0)); GetPhysicsObject()->GetRigidBody()->activate(true); m_inContact = 0; } void RBGolfBall::StickAtPosition(const btVector3 &p) { m_stopped = true; btVector3 p0 = p + btVector3(0,1000,0); btVector3 p1 = p + btVector3(0,-1000,0); btDiscreteDynamicsWorld *world = RudePhysics::GetInstance()->GetWorld(); btCollisionWorld::ClosestRayResultCallback cb(p0, p1); world->rayTest(p0, p1, cb); RUDE_ASSERT(cb.hasHit(), "Could not stick ball at position"); btTransform trans; trans.setIdentity(); trans.setOrigin(cb.m_hitPointWorld + btVector3(0, 0.5f + kBallRadius,0)); GetPhysicsObject()->GetRigidBody()->getMotionState()->setWorldTransform(trans); GetPhysicsObject()->GetRigidBody()->setWorldTransform(trans); GetPhysicsObject()->GetRigidBody()->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT); } <commit_msg>another fix for the ball stick problem<commit_after>/* * RBGolfBall.cpp * golf * * Created by Robert Rose on 9/9/08. * Copyright 2008 Bork 3D LLC. All rights reserved. * */ #include "RBGolfBall.h" #include "RudeDebug.h" #include "RudeGL.h" #include "RudePhysicsSphere.h" #include "RudePhysics.h" #include "RudeMesh.h" #include <btBulletDynamicsCommon.h> const float kBallRadius = 0.15f; const float kBallMass = 0.1f; const float kSpinForceDelay = 0.75f; const float kSpinForceStopTime = 1.75f; const float kWindDelay = 1.0f; RBGolfBall::RBGolfBall() : m_linearContactDamping(0.0f) , m_angularContactDamping(0.0f) , m_movementThreshold(0.0f) , m_curLinearDamping(0.0f) , m_curAngularDamping(0.0f) , m_inContact(false) , m_stop(false) , m_stopped(false) , m_ballScale(kBallRadius) , m_curMaterial(kTee) , m_spinForce(0,0,0) , m_spinForceTimer(0.0f) , m_wind(0,0,0) , m_windTimer(0.0f) { } void RBGolfBall::Load(const char *name) { LoadMesh(name); LoadPhysicsSphere(kBallRadius, kBallMass); //RudeMesh *mesh = GetMesh(); //mesh->SetScale(btVector3(kBallRadius, 0.2, 0.2)); RudePhysicsSphere *obj = (RudePhysicsSphere *) GetPhysicsObject(); btRigidBody *rb = obj->GetRigidBody(); rb->setFriction(1.0f); rb->setRestitution(0.78f); rb->setCcdMotionThreshold(kBallRadius * 0.5f); rb->setCcdSweptSphereRadius(kBallRadius * 0.5f); } void RBGolfBall::NextFrame(float delta) { if(m_stopped) return; RudePhysicsSphere *obj = (RudePhysicsSphere *) GetPhysicsObject(); btRigidBody *rb = obj->GetRigidBody(); // apply force from spin if(m_applySpinForce) { m_spinForceTimer += delta; if(m_spinForceTimer < kSpinForceStopTime) { float gradient = m_spinForceTimer / kSpinForceDelay; if(gradient > 1.0f) gradient = 1.0f; btVector3 linvel = rb->getLinearVelocity(); linvel += m_spinForce * delta * gradient; rb->setLinearVelocity(linvel); } } // apply wind if(m_inContact == 0) { m_windTimer += delta; float gradient = m_windTimer / kWindDelay; if(gradient > 1.0f) gradient = 1.0f; btVector3 linvel = rb->getLinearVelocity(); linvel += m_wind * delta * gradient; rb->setLinearVelocity(linvel); } else m_windTimer = 0.0f; if(m_inContact > 0) { if(m_applySpinForce) { if(m_spinForceTimer > 0.1f) m_applySpinForce = false; } m_curLinearDamping += m_linearContactDamping * delta; m_curAngularDamping += m_angularContactDamping * delta; rb->setDamping(m_curLinearDamping, m_curAngularDamping); m_inContact--; } else { m_curLinearDamping = 0.0f; m_curAngularDamping = 0.0f; m_angularContactDamping = 0.0f; m_linearContactDamping = 0.0f; rb->setDamping(0.0f, 0.0f); } if(m_stop) { GetPhysicsObject()->GetRigidBody()->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT); m_stopped = true; } //if(!rb->isActive()) // ball has reached a stop state // printf("INACTIVE\n"); //printf("l = %f, a = %f\n", m_curLinearDamping, m_curAngularDamping); } void RBGolfBall::Render() { btVector3 eye = RGL.GetEye(); btTransform trans; GetPhysicsObject()->GetRigidBody()->getMotionState()->getWorldTransform(trans); //trans = GetPhysicsObject()->GetRigidBody()->getWorldTransform(); btVector3 ballpos = trans.getOrigin(); float scalefactor = 1.0f; float eyedist = (eye - ballpos).length(); scalefactor += eyedist / 75.0f; m_ballScale = kBallRadius * scalefactor; GetPhysicsObject()->Render(); glScalef(m_ballScale, m_ballScale, m_ballScale); GetMesh()->Render(); } void RBGolfBall::Render(btVector3 pos, btVector3 rot) { glMatrixMode(GL_MODELVIEW); btMatrix3x3 rotmat; if(rot.length() > 0.1f) { btQuaternion q(rot.normalize(), rot.length()); rotmat.setRotation(q); } else rotmat.setIdentity(); btTransform trans(rotmat, pos); btScalar m[16]; trans.getOpenGLMatrix(m); glLoadMatrixf(m); glScalef(kBallRadius, kBallRadius, kBallRadius); GetMesh()->Render(); } btVector3 RBGolfBall::GetPosition() { btTransform trans; GetPhysicsObject()->GetRigidBody()->getMotionState()->getWorldTransform(trans); return trans.getOrigin(); } btVector3 RBGolfBall::GetAngularVelocity() { return GetPhysicsObject()->GetRigidBody()->getAngularVelocity(); } btVector3 RBGolfBall::GetLinearVelocity() { return GetPhysicsObject()->GetRigidBody()->getLinearVelocity(); } void RBGolfBall::SetPosition(const btVector3 &p) { btTransform trans; trans.setIdentity(); trans.setOrigin(p); GetPhysicsObject()->GetRigidBody()->setWorldTransform(trans); GetPhysicsObject()->GetRigidBody()->activate(true); } void RBGolfBall::HitBall(const btVector3 &linvel, const btVector3 &spinForce) { m_spinForce = spinForce; m_applySpinForce = true; m_spinForceTimer = 0.0f; m_windTimer = 0.0f; m_stop = false; m_stopped = false; GetPhysicsObject()->GetRigidBody()->setCollisionFlags(0); GetPhysicsObject()->GetRigidBody()->setLinearVelocity(linvel); GetPhysicsObject()->GetRigidBody()->setAngularVelocity(btVector3(0,0,0)); GetPhysicsObject()->GetRigidBody()->clearForces(); //GetPhysicsObject()->GetRigidBody()->applyForce(p, btVector3(0,0,0)); GetPhysicsObject()->GetRigidBody()->activate(true); m_inContact = 0; } void RBGolfBall::StickAtPosition(const btVector3 &p) { m_stopped = true; btVector3 p0 = p + btVector3(0,10,0); btVector3 p1 = p + btVector3(0,-1000,0); btDiscreteDynamicsWorld *world = RudePhysics::GetInstance()->GetWorld(); btCollisionWorld::ClosestRayResultCallback cb(p0, p1); world->rayTest(p0, p1, cb); RUDE_ASSERT(cb.hasHit(), "Could not stick ball at position"); RUDE_REPORT("Sticking ball at %f %f %f\n", cb.m_hitPointWorld.x(), cb.m_hitPointWorld.y(), cb.m_hitPointWorld.z()); btTransform trans; trans.setIdentity(); trans.setOrigin(cb.m_hitPointWorld + btVector3(0, 0.5f + kBallRadius,0)); GetPhysicsObject()->GetRigidBody()->getMotionState()->setWorldTransform(trans); GetPhysicsObject()->GetRigidBody()->setWorldTransform(trans); GetPhysicsObject()->GetRigidBody()->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT); } <|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // clang-format off // NOLINTNEXTLINE // RUN: true // test-vector-transfers-jit // -runtime-support=$(dirname %s)/runtime-support.so | IreeFileCheck %s // clang-format on #include "experimental/ModelBuilder/MemRefUtils.h" #include "experimental/ModelBuilder/ModelBuilder.h" #include "experimental/ModelBuilder/ModelRunner.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/InitLLVM.h" using namespace mlir; // NOLINT using namespace mlir::edsc; // NOLINT using namespace mlir::edsc::intrinsics; // NOLINT static llvm::cl::opt<std::string> runtimeSupport( "runtime-support", llvm::cl::desc("Runtime support library filename"), llvm::cl::value_desc("filename"), llvm::cl::init("-")); void TestVectorTransfers(ArrayRef<int64_t> szA, ArrayRef<int64_t> szB, ArrayRef<int64_t> szVec, ArrayRef<int64_t> shA, ArrayRef<int64_t> shBWr, ArrayRef<int64_t> shBRd) { assert(szA.size() == shA.size()); assert(szB.size() == shBWr.size()); assert(szB.size() == shBRd.size()); assert(szVec.size() <= shA.size()); assert(szVec.size() <= shBWr.size()); assert(szVec.size() <= shBRd.size()); ModelBuilder mb; // Build a func "vector_transfers". constexpr StringLiteral funcName = "vector_transfers"; auto func = mb.makeFunction(funcName, {}, {}, MLIRFuncOpConfig().setEmitCInterface(true)); OpBuilder b(&func.getBody()); ScopedContext scope(b, func.getLoc()); SmallVector<Value, 4> indicesA; indicesA.reserve(szA.size()); for (auto s : shA) indicesA.push_back(std_constant_index(s)); SmallVector<Value, 4> indicesBWr; indicesBWr.reserve(szB.size()); for (auto s : shBWr) indicesBWr.push_back(std_constant_index(s)); SmallVector<Value, 4> indicesBRd; indicesBRd.reserve(indicesBRd.size()); for (auto s : shBRd) indicesBRd.push_back(std_constant_index(s)); // clang-format off MLIRContext *ctx = mb.getContext(); Value flt_0 = mb.constant_f32(0.0f); Value flt_1 = mb.constant_f32(1.0f); Value flt_42 = mb.constant_f32(42.0f); Value A = std_alloc(mb.getMemRefType(szA, mb.f32)); Value B = std_alloc(mb.getMemRefType(szB, mb.f32)); linalg_fill(A, flt_0); linalg_fill(B, flt_1); Value vFullA = vector_transfer_read( mb.getVectorType(szA, mb.f32), A, SmallVector<Value, 4>(szA.size(), std_constant_index(0)), AffineMap::getMinorIdentityMap(szA.size(), szA.size(), ctx), flt_42, ArrayAttr()); Value vA = vector_transfer_read( mb.getVectorType(szVec, mb.f32), A, indicesA, AffineMap::getMinorIdentityMap(szA.size(), szVec.size(), ctx), flt_42, ArrayAttr()); auto mapB = AffineMap::getMinorIdentityMap(szB.size(), szVec.size(), ctx); vector_transfer_write(vA, B, indicesBWr, mapB); Value flt_13 = std_constant_float(APFloat(13.0f), mb.f32); Value vFullB = vector_transfer_read( mb.getVectorType(szB, mb.f32), B, SmallVector<Value, 4>(szB.size(), std_constant_index(0)), AffineMap::getMinorIdentityMap(szB.size(), szB.size(), ctx), flt_13, ArrayAttr()); Value vB = vector_transfer_read( mb.getVectorType(szVec, mb.f32), B, indicesBRd, AffineMap::getMinorIdentityMap(szB.size(), szVec.size(), ctx), flt_13, ArrayAttr()); (vector_print(vFullA)); (vector_print(vA)); (vector_print(vFullB)); (vector_print(vB)); (std_dealloc(A)); (std_dealloc(B)); std_ret(); // clang-format on // Compile the function, pass in runtime support library // to the execution engine for vector.print. ModelRunner runner(mb.getModuleRef()); runner.compile(CompilationOptions(), runtimeSupport); // Call the funcOp. auto err = runner.invoke(funcName); if (err) llvm_unreachable("Error running function."); } int main(int argc, char **argv) { ModelBuilder::registerAllDialects(); llvm::InitLLVM y(argc, argv); llvm::cl::ParseCommandLineOptions(argc, argv, "TestVectorTransfers\n"); // A[5] // CHECK: ( 0, 0, 0, 0, 0 ) // Load v4 from A[5]@{3:7} with 42 padding // CHECK: ( 0, 0, 42, 42 ) // Store v4 into B[6]@{1:5} // CHECK: ( 1, 0, 0, 42, 42, 1 ) // Load v4 from B[6]@{4:8} with 13 padding // CHECK: ( 42, 1, 13, 13 ) TestVectorTransfers( /*szA=*/{5}, /*szB=*/{6}, /*szVec=*/{4}, /*shA=*/{3}, /*shBWr=*/{1}, /*shBRd=*/{4}); // A[5] // CHECK: ( 0, 0, 0, 0, 0 ) // Load v4 from A[5]@{3:7} with 42 padding // CHECK: ( 0, 0, 42, 42 ) // Store v4 into B[7]@{4:8} don't write out of bounds // CHECK: ( 1, 1, 1, 1, 0, 0, 42 ) // Load v4 from B[7]@{5:9} with 13 padding // CHECK: ( 0, 42, 13, 13 ) TestVectorTransfers( /*szA=*/{5}, /*szB=*/{7}, /*szVec=*/{4}, /*shA=*/{3}, /*shBWr=*/{4}, /*shBRd=*/{5}); // A[2][5] // CHECK: ( ( 0, 0, 0, 0, 0 ), ( 0, 0, 0, 0, 0 ), ( 0, 0, 0, 0, 0 ), // CHECK-SAME: ( 0, 0, 0, 0, 0 ) ) // Load v4 from A[4][5]@{3:3}{3:7} with 42 padding // CHECK: ( 0, 0, 42, 42 ) // Store v4 into B[6]@{1:5} // CHECK: ( 1, 0, 0, 42, 42, 1 ) // Load v4 from B[6]@{3:7} with 13 padding // CHECK: ( 42, 42, 1, 13 ) TestVectorTransfers( /*szA=*/{4, 5}, /*szB=*/{6}, /*szVec=*/{4}, /*shA=*/{3, 3}, /*shBWr=*/{1}, /*shBRd=*/{3}); // A[3][4] // CHECK: ( ( 0, 0, 0, 0 ), ( 0, 0, 0, 0 ), ( 0, 0, 0, 0 ) ) // Load v2x3 from A[3][4]@{2:4}{3:6} with 42 padding // CHECK: ( ( 0, 42, 42 ), ( 42, 42, 42 ) ) // Store v2x3 into B[4][5]@{1:3}{3:6} // CHECK: ( ( 1, 1, 1, 1, 1 ), ( 1, 1, 1, 0, 42 ), // CHECK-SAME: ( 1, 1, 1, 42, 42 ), ( 1, 1, 1, 1, 1 ) ) // Load v2x3 from B[4][5]@{0:2}{3:6} with 13 padding // CHECK: ( ( 1, 1, 13 ), ( 0, 42, 13 ) ) TestVectorTransfers( /*szA=*/{3, 4}, /*szB=*/{4, 5}, /*szVec=*/{2, 3}, /*shA=*/{2, 3}, /*shBWr=*/{1, 3}, /*shBRd=*/{0, 3}); } <commit_msg>[ModelBuilder] Re-enable transfer JIT test<commit_after>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // clang-format off // NOLINTNEXTLINE // RUN: test-vector-transfers-jit -runtime-support=$(dirname %s)/runtime-support.so | IreeFileCheck %s // clang-format on #include "experimental/ModelBuilder/MemRefUtils.h" #include "experimental/ModelBuilder/ModelBuilder.h" #include "experimental/ModelBuilder/ModelRunner.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/InitLLVM.h" using namespace mlir; // NOLINT using namespace mlir::edsc; // NOLINT using namespace mlir::edsc::intrinsics; // NOLINT static llvm::cl::opt<std::string> runtimeSupport( "runtime-support", llvm::cl::desc("Runtime support library filename"), llvm::cl::value_desc("filename"), llvm::cl::init("-")); void TestVectorTransfers(ArrayRef<int64_t> szA, ArrayRef<int64_t> szB, ArrayRef<int64_t> szVec, ArrayRef<int64_t> shA, ArrayRef<int64_t> shBWr, ArrayRef<int64_t> shBRd) { assert(szA.size() == shA.size()); assert(szB.size() == shBWr.size()); assert(szB.size() == shBRd.size()); assert(szVec.size() <= shA.size()); assert(szVec.size() <= shBWr.size()); assert(szVec.size() <= shBRd.size()); ModelBuilder mb; // Build a func "vector_transfers". constexpr StringLiteral funcName = "vector_transfers"; auto func = mb.makeFunction(funcName, {}, {}, MLIRFuncOpConfig().setEmitCInterface(true)); OpBuilder b(&func.getBody()); ScopedContext scope(b, func.getLoc()); SmallVector<Value, 4> indicesA; indicesA.reserve(szA.size()); for (auto s : shA) indicesA.push_back(std_constant_index(s)); SmallVector<Value, 4> indicesBWr; indicesBWr.reserve(szB.size()); for (auto s : shBWr) indicesBWr.push_back(std_constant_index(s)); SmallVector<Value, 4> indicesBRd; indicesBRd.reserve(indicesBRd.size()); for (auto s : shBRd) indicesBRd.push_back(std_constant_index(s)); // clang-format off MLIRContext *ctx = mb.getContext(); Value flt_0 = mb.constant_f32(0.0f); Value flt_1 = mb.constant_f32(1.0f); Value flt_42 = mb.constant_f32(42.0f); Value A = std_alloc(mb.getMemRefType(szA, mb.f32)); Value B = std_alloc(mb.getMemRefType(szB, mb.f32)); linalg_fill(A, flt_0); linalg_fill(B, flt_1); Value vFullA = vector_transfer_read( mb.getVectorType(szA, mb.f32), A, SmallVector<Value, 4>(szA.size(), std_constant_index(0)), AffineMap::getMinorIdentityMap(szA.size(), szA.size(), ctx), flt_42, ArrayAttr()); Value vA = vector_transfer_read( mb.getVectorType(szVec, mb.f32), A, indicesA, AffineMap::getMinorIdentityMap(szA.size(), szVec.size(), ctx), flt_42, ArrayAttr()); auto mapB = AffineMap::getMinorIdentityMap(szB.size(), szVec.size(), ctx); vector_transfer_write(vA, B, indicesBWr, mapB); Value flt_13 = std_constant_float(APFloat(13.0f), mb.f32); Value vFullB = vector_transfer_read( mb.getVectorType(szB, mb.f32), B, SmallVector<Value, 4>(szB.size(), std_constant_index(0)), AffineMap::getMinorIdentityMap(szB.size(), szB.size(), ctx), flt_13, ArrayAttr()); Value vB = vector_transfer_read( mb.getVectorType(szVec, mb.f32), B, indicesBRd, AffineMap::getMinorIdentityMap(szB.size(), szVec.size(), ctx), flt_13, ArrayAttr()); (vector_print(vFullA)); (vector_print(vA)); (vector_print(vFullB)); (vector_print(vB)); (std_dealloc(A)); (std_dealloc(B)); std_ret(); // clang-format on // Compile the function, pass in runtime support library // to the execution engine for vector.print. ModelRunner runner(mb.getModuleRef()); runner.compile(CompilationOptions(), runtimeSupport); // Call the funcOp. auto err = runner.invoke(funcName); if (err) llvm_unreachable("Error running function."); } int main(int argc, char **argv) { ModelBuilder::registerAllDialects(); llvm::InitLLVM y(argc, argv); llvm::cl::ParseCommandLineOptions(argc, argv, "TestVectorTransfers\n"); // A[5] // CHECK: ( 0, 0, 0, 0, 0 ) // Load v4 from A[5]@{3:7} with 42 padding // CHECK: ( 0, 0, 42, 42 ) // Store v4 into B[6]@{1:5} // CHECK: ( 1, 0, 0, 42, 42, 1 ) // Load v4 from B[6]@{4:8} with 13 padding // CHECK: ( 42, 1, 13, 13 ) TestVectorTransfers( /*szA=*/{5}, /*szB=*/{6}, /*szVec=*/{4}, /*shA=*/{3}, /*shBWr=*/{1}, /*shBRd=*/{4}); // A[5] // CHECK: ( 0, 0, 0, 0, 0 ) // Load v4 from A[5]@{3:7} with 42 padding // CHECK: ( 0, 0, 42, 42 ) // Store v4 into B[7]@{4:8} don't write out of bounds // CHECK: ( 1, 1, 1, 1, 0, 0, 42 ) // Load v4 from B[7]@{5:9} with 13 padding // CHECK: ( 0, 42, 13, 13 ) TestVectorTransfers( /*szA=*/{5}, /*szB=*/{7}, /*szVec=*/{4}, /*shA=*/{3}, /*shBWr=*/{4}, /*shBRd=*/{5}); // A[2][5] // CHECK: ( ( 0, 0, 0, 0, 0 ), ( 0, 0, 0, 0, 0 ), ( 0, 0, 0, 0, 0 ), // CHECK-SAME: ( 0, 0, 0, 0, 0 ) ) // Load v4 from A[4][5]@{3:3}{3:7} with 42 padding // CHECK: ( 0, 0, 42, 42 ) // Store v4 into B[6]@{1:5} // CHECK: ( 1, 0, 0, 42, 42, 1 ) // Load v4 from B[6]@{3:7} with 13 padding // CHECK: ( 42, 42, 1, 13 ) TestVectorTransfers( /*szA=*/{4, 5}, /*szB=*/{6}, /*szVec=*/{4}, /*shA=*/{3, 3}, /*shBWr=*/{1}, /*shBRd=*/{3}); // A[3][4] // CHECK: ( ( 0, 0, 0, 0 ), ( 0, 0, 0, 0 ), ( 0, 0, 0, 0 ) ) // Load v2x3 from A[3][4]@{2:4}{3:6} with 42 padding // CHECK: ( ( 0, 42, 42 ), ( 42, 42, 42 ) ) // Store v2x3 into B[4][5]@{1:3}{3:6} // CHECK: ( ( 1, 1, 1, 1, 1 ), ( 1, 1, 1, 0, 42 ), // CHECK-SAME: ( 1, 1, 1, 42, 42 ), ( 1, 1, 1, 1, 1 ) ) // Load v2x3 from B[4][5]@{0:2}{3:6} with 13 padding // CHECK: ( ( 1, 1, 13 ), ( 0, 42, 13 ) ) TestVectorTransfers( /*szA=*/{3, 4}, /*szB=*/{4, 5}, /*szVec=*/{2, 3}, /*shA=*/{2, 3}, /*shBWr=*/{1, 3}, /*shBRd=*/{0, 3}); } <|endoftext|>
<commit_before>/*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ========================================================================== SeqCons -- Read alignment via realignment or MSA. ========================================================================== Author: Tobias Rausch <rausch@embl.de> ========================================================================== */ #include <seqan/basic.h> #include <seqan/consensus.h> #include <seqan/modifier.h> #include <seqan/misc/misc_cmdparser.h> #include <iostream> #include <fstream> using namespace seqan; void _addVersion(CommandLineParser & parser) { ::std::string rev = "$Revision: 4663 $"; addVersionLine(parser, "Version 0.22 (06. August 2009) Revision: " + rev.substr(11, 4) + ""); } void setUpCommandLineParser(CommandLineParser & parser) { _addVersion(parser); addTitleLine(parser, "***************************************"); addTitleLine(parser, "* Multi-read alignment - SeqCons *"); addTitleLine(parser, "* (c) Copyright 2009 by Tobias Rausch *"); addTitleLine(parser, "***************************************"); addUsageLine(parser, "-r <FASTA file with reads> [Options]"); addUsageLine(parser, "-a <AMOS message file> [Options]"); addUsageLine(parser, "-s <SAM file> [-c <FASTA contigs file>] [Options]"); addSection(parser, "Main Options:"); addOption(parser, addArgumentText(CommandLineOption("r", "reads", "file with reads", OptionType::String), "<FASTA reads file>")); addOption(parser, addArgumentText(CommandLineOption("a", "afg", "message file", OptionType::String), "<AMOS afg file>")); addOption(parser, addArgumentText(CommandLineOption("s", "sam", "SAM file", OptionType::String), "<SAM file>")); addOption(parser, addArgumentText(CommandLineOption("c", "contigs", "FASTA file with contigs, ignored if not SAM input", OptionType::String), "<FASTA contigs file>")); addOption(parser, addArgumentText(CommandLineOption("o", "outfile", "output filename", (int)OptionType::String, "align.txt"), "<Filename>")); addOption(parser, addArgumentText(CommandLineOption("f", "format", "output format", (int)OptionType::String, "afg"), "[seqan | afg | sam]")); addOption(parser, addArgumentText(CommandLineOption("m", "method", "alignment method", (int)OptionType::String, "realign"), "[realign | msa]")); addOption(parser, addArgumentText(CommandLineOption("b", "bandwidth", "bandwidth", (int)OptionType::Int, 8), "<Int>")); addOption(parser, CommandLineOption("n", "noalign", "no align, only convert input", OptionType::Boolean)); addSection(parser, "MSA Method Options:"); addOption(parser, addArgumentText(CommandLineOption("ma", "matchlength", "min. overlap length", (int)OptionType::Int, 15), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("qu", "quality", "min. overlap precent identity", (int)OptionType::Int, 80), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("ov", "overlaps", "min. number of overlaps per read", (int)OptionType::Int, 3), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("wi", "window", "window size", (int)OptionType::Int, 0), "<Int>")); addHelpLine(parser, "/*If this parameter is > 0 then all"); addHelpLine(parser, " overlaps within a given window"); addHelpLine(parser, " are computed.*/"); addSection(parser, "ReAlign Method Options:"); addOption(parser, CommandLineOption("in", "include", "include contig sequence", OptionType::Boolean)); addOption(parser, addArgumentText(CommandLineOption("rm", "rmethod", "realign method", (int)OptionType::String, "gotoh"), "[nw | gotoh]")); } int parseCommandLine(ConsensusOptions & consOpt, CommandLineParser & parser, int argc, const char * argv[]) { if (argc == 1) { shortHelp(parser, std::cerr); // print short help and exit return 1; } if (!parse(parser, argc, argv, ::std::cerr)) return 1; if (isSetLong(parser, "help") || isSetLong(parser, "version")) return 0; // print help or version and exit // Main options getOptionValueLong(parser, "reads", consOpt.readsfile); getOptionValueLong(parser, "afg", consOpt.afgfile); getOptionValueLong(parser, "sam", consOpt.samfile); getOptionValueLong(parser, "contigs", consOpt.contigsfile); getOptionValueLong(parser, "outfile", consOpt.outfile); if (empty(consOpt.samfile) && !empty(consOpt.contigsfile)) std::cerr << "WARNING: Contigs specified by input is not FASTA, ignoring --contigs parameters." << std::endl; String<char> optionVal; getOptionValueLong(parser, "format", optionVal); if (optionVal == "seqan") consOpt.output = 0; else if (optionVal == "afg") consOpt.output = 1; else if (optionVal == "frg") consOpt.output = 2; else if (optionVal == "cgb") consOpt.output = 3; else if (optionVal == "sam") consOpt.output = 4; getOptionValueLong(parser, "method", optionVal); if (optionVal == "realign") consOpt.method = 0; else if (optionVal == "msa") consOpt.method = 1; getOptionValueLong(parser, "bandwidth", consOpt.bandwidth); #ifdef CELERA_OFFSET if (!isSetLong(parser, "bandwidth")) consOpt.bandwidth = 15; #endif getOptionValueLong(parser, "noalign", consOpt.noalign); // MSA options getOptionValueLong(parser, "matchlength", consOpt.matchlength); getOptionValueLong(parser, "quality", consOpt.quality); getOptionValueLong(parser, "overlaps", consOpt.overlaps); #ifdef CELERA_OFFSET if (!isSetLong(parser, "overlaps")) consOpt.overlaps = 5; #endif getOptionValueLong(parser, "window", consOpt.window); // ReAlign options getOptionValueLong(parser, "include", consOpt.include); getOptionValueLong(parser, "rmethod", optionVal); if (optionVal == "nw") consOpt.rmethod = 0; else if (optionVal == "gotoh") consOpt.rmethod = 1; return 0; } // Load the reads and layout positions template <typename TFragmentStore, typename TSize> int loadFiles(TFragmentStore & fragStore, TSize & numberOfContigs, ConsensusOptions const & consOpt) { std::cerr << "Reading input..." << std::endl; if (!empty(consOpt.readsfile)) { // Load simple read file std::fstream strmReads(consOpt.readsfile.c_str(), std::fstream::in | std::fstream::binary); bool moveToFront = false; if (consOpt.noalign) moveToFront = true; bool success = _convertSimpleReadFile(strmReads, fragStore, consOpt.readsfile, moveToFront); if (!success) return 1; numberOfContigs = 1; } else if (!empty(consOpt.afgfile)) { // Load Amos message file std::fstream strmReads(consOpt.afgfile.c_str(), std::fstream::in | std::fstream::binary); read(strmReads, fragStore, Amos()); numberOfContigs = length(fragStore.contigStore); } else if (!empty(consOpt.samfile)) { // Possibly load contigs into fragment store. if (!empty(consOpt.contigsfile)) { if (!loadContigs(fragStore, consOpt.contigsfile.c_str())) { std::cerr << "Could not load contigs file " << consOpt.contigsfile.c_str() << std::endl; return 1; } } // Load SAM message file std::fstream strmReads(consOpt.samfile.c_str(), std::fstream::in | std::fstream::binary); read(strmReads, fragStore, SAM()); numberOfContigs = length(fragStore.contigStore); } else { return 1; } return 0; } // Write resulting alignment. template <typename TFragmentStore> int writeOutput(TFragmentStore /*const*/ & fragStore, ConsensusOptions const & consOpt) { std::cerr << "Writing output..." << std::endl; if (consOpt.output == 0) { // Write old SeqAn multi-read alignment format FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); write(strmWrite, fragStore, FastaReadFormat()); fclose(strmWrite); } else if (consOpt.output == 1) { // Write Amos FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); write(strmWrite, fragStore, Amos()); fclose(strmWrite); } else if (consOpt.output == 2) { FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); _writeCeleraFrg(strmWrite, fragStore); fclose(strmWrite); } else if (consOpt.output == 3) { FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); _writeCeleraCgb(strmWrite, fragStore); fclose(strmWrite); } return 0; } int main(int argc, const char *argv[]) { // Command line parsing CommandLineParser parser; setUpCommandLineParser(parser); // Get all command line options ConsensusOptions consOpt; int ret = parseCommandLine(consOpt, parser, argc, argv); if (ret != 0) return ret; // Create a new fragment store typedef FragmentStore<> TFragmentStore; typedef Size<TFragmentStore>::Type TSize; TFragmentStore fragStore; // Load the reads and layout positions TSize numberOfContigs = 0; ret = loadFiles(fragStore, numberOfContigs, consOpt); if (ret != 0) { shortHelp(parser, std::cerr); return ret; } // Multi-realignment desired or just conversion of the input if (!consOpt.noalign) { // Iterate over all contigs if (consOpt.method == 0) std::cerr << "Performing realignment..." << std::endl; else std::cerr << "Performing consensus alignment..." << std::endl; for (TSize currentContig = 0; currentContig < numberOfContigs; ++currentContig) { std::cerr << "contig " << (currentContig + 1) << "/" << numberOfContigs << std::endl; if (consOpt.method == 0) { Score<int, WeightedConsensusScore<Score<int, FractionalScore>, Score<int, ConsensusScore> > > combinedScore; reAlign(fragStore, combinedScore, currentContig, consOpt.rmethod, consOpt.bandwidth, consOpt.include); } else { std::cerr << "Performing consensus alignment..." << std::endl; // Import all reads of the given contig typedef TFragmentStore::TReadSeq TReadSeq; StringSet<TReadSeq, Owner<> > readSet; String<Pair<TSize, TSize> > begEndPos; _loadContigReads(readSet, begEndPos, fragStore, currentContig); if (!length(readSet)) continue; // Align the reads typedef StringSet<TReadSeq, Dependent<> > TStringSet; typedef Graph<Alignment<TStringSet, void, WithoutEdgeId> > TAlignGraph; TAlignGraph gOut(readSet); consensusAlignment(gOut, begEndPos, consOpt); // Update the contig in the fragment store if (!empty(gOut)) updateContig(fragStore, gOut, currentContig); clear(gOut); //// Debug code for CA //mtRandInit(); //String<char> fileTmp1 = "tmp1"; //String<char> fileTmp2 = "tmp2"; //for(int i = 0; i<10; ++i) { // int file = (mtRand() % 20) + 65; // appendValue(fileTmp1, char(file)); // appendValue(fileTmp2, char(file)); //} //std::fstream strm3; //strm3.open(toCString(fileTmp2), std::ios_base::out | std::ios_base::trunc); //for(int i = 0;i<(int) length(origStrSet); ++i) { // std::stringstream name; // name << value(begEndPos, i).i1 << "," << value(begEndPos, i).i2; // String<char> myTitle = name.str(); // write(strm3, origStrSet[i], myTitle, Fasta()); // if (value(begEndPos, i).i1 > value(begEndPos, i).i2) reverseComplementInPlace(origStrSet[i]); //} //strm3.close(); } } // end loop over all contigs } // Write result. ret = writeOutput(fragStore, consOpt); return ret; } <commit_msg>Writing out consensus sequence in FASTA for SAM output.<commit_after>/*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ========================================================================== SeqCons -- Read alignment via realignment or MSA. ========================================================================== Author: Tobias Rausch <rausch@embl.de> ========================================================================== */ #include <seqan/basic.h> #include <seqan/consensus.h> #include <seqan/modifier.h> #include <seqan/misc/misc_cmdparser.h> #include <iostream> #include <fstream> using namespace seqan; void _addVersion(CommandLineParser & parser) { ::std::string rev = "$Revision: 4663 $"; addVersionLine(parser, "Version 0.22 (06. August 2009) Revision: " + rev.substr(11, 4) + ""); } void setUpCommandLineParser(CommandLineParser & parser) { _addVersion(parser); addTitleLine(parser, "***************************************"); addTitleLine(parser, "* Multi-read alignment - SeqCons *"); addTitleLine(parser, "* (c) Copyright 2009 by Tobias Rausch *"); addTitleLine(parser, "***************************************"); addUsageLine(parser, "-r <FASTA file with reads> [Options]"); addUsageLine(parser, "-a <AMOS message file> [Options]"); addUsageLine(parser, "-s <SAM file> [-c <FASTA contigs file>] [Options]"); addSection(parser, "Main Options:"); addOption(parser, addArgumentText(CommandLineOption("r", "reads", "file with reads", OptionType::String), "<FASTA reads file>")); addOption(parser, addArgumentText(CommandLineOption("a", "afg", "message file", OptionType::String), "<AMOS afg file>")); addOption(parser, addArgumentText(CommandLineOption("s", "sam", "SAM file", OptionType::String), "<SAM file>")); addOption(parser, addArgumentText(CommandLineOption("c", "contigs", "FASTA file with contigs, ignored if not SAM input", OptionType::String), "<FASTA contigs file>")); addOption(parser, addArgumentText(CommandLineOption("o", "outfile", "output filename", (int)OptionType::String, "align.txt"), "<Filename>")); addOption(parser, addArgumentText(CommandLineOption("f", "format", "output format", (int)OptionType::String, "afg"), "[seqan | afg | sam]")); addOption(parser, addArgumentText(CommandLineOption("m", "method", "alignment method", (int)OptionType::String, "realign"), "[realign | msa]")); addOption(parser, addArgumentText(CommandLineOption("b", "bandwidth", "bandwidth", (int)OptionType::Int, 8), "<Int>")); addOption(parser, CommandLineOption("n", "noalign", "no align, only convert input", OptionType::Boolean)); addSection(parser, "MSA Method Options:"); addOption(parser, addArgumentText(CommandLineOption("ma", "matchlength", "min. overlap length", (int)OptionType::Int, 15), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("qu", "quality", "min. overlap precent identity", (int)OptionType::Int, 80), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("ov", "overlaps", "min. number of overlaps per read", (int)OptionType::Int, 3), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("wi", "window", "window size", (int)OptionType::Int, 0), "<Int>")); addHelpLine(parser, "/*If this parameter is > 0 then all"); addHelpLine(parser, " overlaps within a given window"); addHelpLine(parser, " are computed.*/"); addSection(parser, "ReAlign Method Options:"); addOption(parser, CommandLineOption("in", "include", "include contig sequence", OptionType::Boolean)); addOption(parser, addArgumentText(CommandLineOption("rm", "rmethod", "realign method", (int)OptionType::String, "gotoh"), "[nw | gotoh]")); } int parseCommandLine(ConsensusOptions & consOpt, CommandLineParser & parser, int argc, const char * argv[]) { if (argc == 1) { shortHelp(parser, std::cerr); // print short help and exit return 1; } if (!parse(parser, argc, argv, ::std::cerr)) return 1; if (isSetLong(parser, "help") || isSetLong(parser, "version")) return 0; // print help or version and exit // Main options getOptionValueLong(parser, "reads", consOpt.readsfile); getOptionValueLong(parser, "afg", consOpt.afgfile); getOptionValueLong(parser, "sam", consOpt.samfile); getOptionValueLong(parser, "contigs", consOpt.contigsfile); getOptionValueLong(parser, "outfile", consOpt.outfile); if (empty(consOpt.samfile) && !empty(consOpt.contigsfile)) std::cerr << "WARNING: Contigs specified by input is not FASTA, ignoring --contigs parameters." << std::endl; String<char> optionVal; getOptionValueLong(parser, "format", optionVal); if (optionVal == "seqan") consOpt.output = 0; else if (optionVal == "afg") consOpt.output = 1; else if (optionVal == "frg") consOpt.output = 2; else if (optionVal == "cgb") consOpt.output = 3; else if (optionVal == "sam") consOpt.output = 4; getOptionValueLong(parser, "method", optionVal); if (optionVal == "realign") consOpt.method = 0; else if (optionVal == "msa") consOpt.method = 1; getOptionValueLong(parser, "bandwidth", consOpt.bandwidth); #ifdef CELERA_OFFSET if (!isSetLong(parser, "bandwidth")) consOpt.bandwidth = 15; #endif getOptionValueLong(parser, "noalign", consOpt.noalign); // MSA options getOptionValueLong(parser, "matchlength", consOpt.matchlength); getOptionValueLong(parser, "quality", consOpt.quality); getOptionValueLong(parser, "overlaps", consOpt.overlaps); #ifdef CELERA_OFFSET if (!isSetLong(parser, "overlaps")) consOpt.overlaps = 5; #endif getOptionValueLong(parser, "window", consOpt.window); // ReAlign options getOptionValueLong(parser, "include", consOpt.include); getOptionValueLong(parser, "rmethod", optionVal); if (optionVal == "nw") consOpt.rmethod = 0; else if (optionVal == "gotoh") consOpt.rmethod = 1; return 0; } // Load the reads and layout positions template <typename TFragmentStore, typename TSize> int loadFiles(TFragmentStore & fragStore, TSize & numberOfContigs, ConsensusOptions const & consOpt) { std::cerr << "Reading input..." << std::endl; if (!empty(consOpt.readsfile)) { // Load simple read file std::fstream strmReads(consOpt.readsfile.c_str(), std::fstream::in | std::fstream::binary); bool moveToFront = false; if (consOpt.noalign) moveToFront = true; bool success = _convertSimpleReadFile(strmReads, fragStore, consOpt.readsfile, moveToFront); if (!success) return 1; numberOfContigs = 1; } else if (!empty(consOpt.afgfile)) { // Load Amos message file std::fstream strmReads(consOpt.afgfile.c_str(), std::fstream::in | std::fstream::binary); read(strmReads, fragStore, Amos()); numberOfContigs = length(fragStore.contigStore); } else if (!empty(consOpt.samfile)) { // Possibly load contigs into fragment store. if (!empty(consOpt.contigsfile)) { if (!loadContigs(fragStore, consOpt.contigsfile.c_str())) { std::cerr << "Could not load contigs file " << consOpt.contigsfile.c_str() << std::endl; return 1; } } // Load SAM message file std::fstream strmReads(consOpt.samfile.c_str(), std::fstream::in | std::fstream::binary); read(strmReads, fragStore, SAM()); numberOfContigs = length(fragStore.contigStore); } else { return 1; } return 0; } // Write resulting alignment. template <typename TFragmentStore> int writeOutput(TFragmentStore /*const*/ & fragStore, ConsensusOptions const & consOpt) { std::cerr << "Writing output..." << std::endl; if (consOpt.output == 0) { // Write old SeqAn multi-read alignment format FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); write(strmWrite, fragStore, FastaReadFormat()); fclose(strmWrite); } else if (consOpt.output == 1) { // Write Amos FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); write(strmWrite, fragStore, Amos()); fclose(strmWrite); } else if (consOpt.output == 2) { FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); _writeCeleraFrg(strmWrite, fragStore); fclose(strmWrite); } else if (consOpt.output == 3) { FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); _writeCeleraCgb(strmWrite, fragStore); fclose(strmWrite); } else if (consOpt.output == 4) { // Write out resulting MSA in a SAM file. FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); write(strmWrite, fragStore, SAM()); fclose(strmWrite); // Write out resulting consensus sequence. char buffer[10*1024]; buffer[0] = '\0'; strcat(buffer, consOpt.outfile.c_str()); strcat(buffer, ".consensus.fasta"); strmWrite = fopen(buffer, "w"); writeContigs(strmWrite, fragStore, Fasta()); fclose(strmWrite); } return 0; } int main(int argc, const char *argv[]) { // Command line parsing CommandLineParser parser; setUpCommandLineParser(parser); // Get all command line options ConsensusOptions consOpt; int ret = parseCommandLine(consOpt, parser, argc, argv); if (ret != 0) return ret; // Create a new fragment store typedef FragmentStore<> TFragmentStore; typedef Size<TFragmentStore>::Type TSize; TFragmentStore fragStore; // Load the reads and layout positions TSize numberOfContigs = 0; ret = loadFiles(fragStore, numberOfContigs, consOpt); if (ret != 0) { shortHelp(parser, std::cerr); return ret; } // Multi-realignment desired or just conversion of the input if (!consOpt.noalign) { // Iterate over all contigs if (consOpt.method == 0) std::cerr << "Performing realignment..." << std::endl; else std::cerr << "Performing consensus alignment..." << std::endl; for (TSize currentContig = 0; currentContig < numberOfContigs; ++currentContig) { std::cerr << "contig " << (currentContig + 1) << "/" << numberOfContigs << std::endl; if (consOpt.method == 0) { Score<int, WeightedConsensusScore<Score<int, FractionalScore>, Score<int, ConsensusScore> > > combinedScore; reAlign(fragStore, combinedScore, currentContig, consOpt.rmethod, consOpt.bandwidth, consOpt.include); } else { std::cerr << "Performing consensus alignment..." << std::endl; // Import all reads of the given contig typedef TFragmentStore::TReadSeq TReadSeq; StringSet<TReadSeq, Owner<> > readSet; String<Pair<TSize, TSize> > begEndPos; _loadContigReads(readSet, begEndPos, fragStore, currentContig); if (!length(readSet)) continue; // Align the reads typedef StringSet<TReadSeq, Dependent<> > TStringSet; typedef Graph<Alignment<TStringSet, void, WithoutEdgeId> > TAlignGraph; TAlignGraph gOut(readSet); consensusAlignment(gOut, begEndPos, consOpt); // Update the contig in the fragment store if (!empty(gOut)) updateContig(fragStore, gOut, currentContig); clear(gOut); //// Debug code for CA //mtRandInit(); //String<char> fileTmp1 = "tmp1"; //String<char> fileTmp2 = "tmp2"; //for(int i = 0; i<10; ++i) { // int file = (mtRand() % 20) + 65; // appendValue(fileTmp1, char(file)); // appendValue(fileTmp2, char(file)); //} //std::fstream strm3; //strm3.open(toCString(fileTmp2), std::ios_base::out | std::ios_base::trunc); //for(int i = 0;i<(int) length(origStrSet); ++i) { // std::stringstream name; // name << value(begEndPos, i).i1 << "," << value(begEndPos, i).i2; // String<char> myTitle = name.str(); // write(strm3, origStrSet[i], myTitle, Fasta()); // if (value(begEndPos, i).i1 > value(begEndPos, i).i2) reverseComplementInPlace(origStrSet[i]); //} //strm3.close(); } } // end loop over all contigs } // Write result. ret = writeOutput(fragStore, consOpt); return ret; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <stdlib.h> #include <openssl/rand.h> #include "Crypto.h" #include "Identity.h" #include "common/key.hpp" // XXX: make this faster static bool check_keys(const std::string & prefix, i2p::data::PrivateKeys & key) { return key.GetPublic()->GetIdentHash().ToBase32().substr(0, prefix.length()) == prefix; } // XXX: make this faster static void mutate_keys(uint8_t * buf, i2p::data::PrivateKeys & key) { uint8_t * ptr = key.GetPadding(); // TODO: do not hard code for ed25519 RAND_bytes(ptr, 96); key.RecalculateIdentHash(buf); } int main (int argc, char * argv[]) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " filename prefix" << std::endl; return -1; } uint8_t buf[1024] = {0}; std::string prefix(argv[2]); i2p::crypto::InitCrypto (false); // default to ed 25519 keys i2p::data::SigningKeyType type = i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519; auto keys = i2p::data::PrivateKeys::CreateRandomKeys (type); // TODO: multi threading while(!check_keys(prefix, keys)) mutate_keys(buf, keys); std::ofstream f (argv[1], std::ofstream::binary | std::ofstream::out); if (f) { size_t len = keys.GetFullLen (); uint8_t * buf = new uint8_t[len]; len = keys.ToBuffer (buf, len); f.write ((char *)buf, len); delete[] buf; std::cout << "Destination " << keys.GetPublic ()->GetIdentHash ().ToBase32 () << " created" << std::endl; } else std::cout << "Can't create file " << argv[1] << std::endl; i2p::crypto::TerminateCrypto (); return 0; } <commit_msg>Multithread<commit_after>#include <iostream> #include <fstream> #include <stdlib.h> #include <openssl/rand.h> #include "Crypto.h" #include "Identity.h" #include "common/key.hpp" #include <thread> #include <unistd.h> #include <vector> #include <mutex> static std::mutex thread_mutex; static i2p::data::SigningKeyType type; static i2p::data::PrivateKeys keys; static bool finded=false; static size_t padding_size; static uint8_t * KeyBuf; static uint8_t * PaddingBuf; static unsigned long long hash; #define CPU_ONLY #ifdef CPU_ONLY // XXX: make this faster static inline bool NotThat(const char * a, const char *b){ while(*b) if(*a++!=*b++) return true; return false; } inline void twist_cpu(uint8_t * buf,size_t * l0){ //TODO: NORMAL IMPLEMENTATION RAND_bytes(buf,padding_size); } // XXX: make this faster static inline void mutate_keys_cpu( uint8_t * buf, uint8_t * padding, size_t * l0) { twist_cpu(padding,l0); thread_mutex.lock(); keys.RecalculateIdentHash(buf); thread_mutex.unlock(); } void thread_find(const char * prefix){ while(NotThat(keys.GetPublic()->GetIdentHash().ToBase32().c_str(),prefix) and !finded) { size_t l0 = 0; mutate_keys_cpu(KeyBuf,PaddingBuf, (size_t*)&l0); hash++; } } #endif int main (int argc, char * argv[]) { if (argc < 2) { std::cout << "Usage: keygen filename generatestring <signature type>" << std::endl; return 0; } i2p::crypto::InitCrypto (false); type = i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519; if (argc > 3) type = NameToSigType(std::string(argv[3])); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// keys = i2p::data::PrivateKeys::CreateRandomKeys (type); switch(type){ case i2p::data::SIGNING_KEY_TYPE_DSA_SHA1: case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA512_P521: case i2p::data::SIGNING_KEY_TYPE_RSA_SHA256_2048: case i2p::data::SIGNING_KEY_TYPE_RSA_SHA384_3072: case i2p::data::SIGNING_KEY_TYPE_RSA_SHA512_4096: case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_TC26_A_512_GOSTR3411_512: case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_TC26_A_512_GOSTR3411_512_TEST: std::cout << "Sorry, i don't can generate adress for this signature type" << std::endl; return 0; break; } switch(type){ case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256: padding_size=64; break; case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA384_P384: padding_size=32; break; case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA512_P521: padding_size=4; break; case i2p::data::SIGNING_KEY_TYPE_RSA_SHA256_2048: padding_size=128; break; case i2p::data::SIGNING_KEY_TYPE_RSA_SHA384_3072: padding_size=256; break; case i2p::data::SIGNING_KEY_TYPE_RSA_SHA512_4096: padding_size=384; break; case i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519: padding_size=96; break; case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_CRYPTO_PRO_A_GOSTR3411_256: case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_CRYPTO_PRO_A_GOSTR3411_256_TEST: padding_size=64; break; } // TODO: multi threading KeyBuf = new uint8_t[keys.GetFullLen()]; PaddingBuf = keys.GetPadding(); unsigned int count_cpu = sysconf(_SC_NPROCESSORS_ONLN); std::vector<std::thread> threads(count_cpu); std::cout << "Start vanity generator in " << count_cpu << " threads" << std::endl; for ( unsigned int j = count_cpu;j--;){ threads[j] = std::thread(thread_find,argv[2]); sched_param sch; int policy; pthread_getschedparam(threads[j].native_handle(), &policy, &sch); sch.sched_priority = 10; if (pthread_setschedparam(threads[j].native_handle(), SCHED_FIFO, &sch)) { std::cout << "Failed to setschedparam" << std::endl; return 1; } } for(unsigned int j = 0; j < count_cpu;j++) threads[j].join(); std::cout << "Hashes: " << hash << std::endl; std::ofstream f (argv[1], std::ofstream::binary | std::ofstream::out); if (f) { size_t len = keys.GetFullLen (); len = keys.ToBuffer (KeyBuf, len); f.write ((char *)KeyBuf, len); delete [] KeyBuf; std::cout << "Destination " << keys.GetPublic ()->GetIdentHash ().ToBase32 () << " created" << std::endl; } else std::cout << "Can't create file " << argv[1] << std::endl; i2p::crypto::TerminateCrypto (); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <folly/synchronization/Rcu.h> #include <thread> #include <vector> #include <glog/logging.h> #include <folly/Benchmark.h> #include <folly/Random.h> #include <folly/portability/GFlags.h> #include <folly/portability/GTest.h> using namespace folly; DEFINE_int64(iters, 100000, "Number of iterations"); DEFINE_uint64(threads, 32, "Number of threads"); TEST(RcuTest, Basic) { auto foo = new int(2); rcu_retire(foo); } class des { bool* d_; public: des(bool* d) : d_(d) {} ~des() { *d_ = true; } }; TEST(RcuTest, Guard) { bool del = false; auto foo = new des(&del); { rcu_reader g; } rcu_retire(foo); rcu_synchronize(); EXPECT_TRUE(del); } TEST(RcuTest, SlowReader) { std::thread t; { rcu_reader g; t = std::thread([&]() { rcu_synchronize(); }); usleep(100); // Wait for synchronize to start } t.join(); } rcu_reader tryretire(des* obj) { rcu_reader g; rcu_retire(obj); return g; } TEST(RcuTest, CopyGuard) { bool del = false; auto foo = new des(&del); { auto res = tryretire(foo); EXPECT_FALSE(del); } rcu_barrier(); EXPECT_TRUE(del); } static void delete_or_retire_oldint(int* oldint) { if (folly::Random::rand32() % 2 == 0) { rcu_retire<int>(oldint, [](int* obj) { *obj = folly::Random::rand32(); delete obj; }); } else { rcu_synchronize(); *oldint = folly::Random::rand32(); delete oldint; } } TEST(RcuTest, Stress) { std::vector<std::thread> readers; constexpr uint32_t sz = 1000; std::atomic<int*> ints[sz]; for (uint32_t i = 0; i < sz; i++) { ints[i].store(new int(0)); } for (unsigned th = 0; th < FLAGS_threads; th++) { readers.push_back(std::thread([&]() { for (int i = 0; i < FLAGS_iters / 100; i++) { rcu_reader g; int sum = 0; int* ptrs[sz]; for (uint32_t j = 0; j < sz; j++) { ptrs[j] = ints[j].load(std::memory_order_acquire); } for (uint32_t j = 0; j < sz; j++) { sum += *ptrs[j]; } EXPECT_EQ(sum, 0); } })); } std::atomic<bool> done{false}; std::vector<std::thread> updaters; for (unsigned th = 0; th < FLAGS_threads; th++) { updaters.push_back(std::thread([&]() { while (!done.load()) { auto newint = new int(0); auto oldint = ints[folly::Random::rand32() % sz].exchange(newint); delete_or_retire_oldint(oldint); } })); } for (auto& t : readers) { t.join(); } done = true; for (auto& t : updaters) { t.join(); } // Cleanup for asan rcu_synchronize(); for (uint32_t i = 0; i < sz; i++) { delete ints[i].exchange(nullptr); } } TEST(RcuTest, Synchronize) { std::vector<std::thread> threads; for (unsigned th = 0; th < FLAGS_threads; th++) { threads.push_back(std::thread([&]() { for (int i = 0; i < 10; i++) { rcu_synchronize(); } })); } for (auto& t : threads) { t.join(); } } TEST(RcuTest, NewDomainTest) { struct UniqueTag; rcu_domain<UniqueTag> newdomain(nullptr); rcu_synchronize(newdomain); } TEST(RcuTest, NewDomainGuardTest) { struct UniqueTag; rcu_domain<UniqueTag> newdomain(nullptr); bool del = false; auto foo = new des(&del); { rcu_reader_domain<UniqueTag> g(newdomain); } rcu_retire(foo, {}, newdomain); rcu_synchronize(newdomain); EXPECT_TRUE(del); } TEST(RcuTest, MovableReader) { { rcu_reader g; rcu_reader f(std::move(g)); } rcu_synchronize(); { rcu_reader g(std::defer_lock); rcu_reader f; g = std::move(f); } rcu_synchronize(); } TEST(RcuTest, SynchronizeInCall) { rcu_default_domain().call([]() { rcu_synchronize(); }); rcu_synchronize(); } TEST(RcuTest, MoveReaderBetweenThreads) { rcu_reader g; std::thread t([f = std::move(g)] {}); t.join(); rcu_synchronize(); } TEST(RcuTest, ForkTest) { rcu_token<RcuTag> epoch; std::thread t([&]() { epoch = rcu_default_domain().lock_shared(); }); t.join(); auto pid = fork(); if (pid) { // parent rcu_default_domain().unlock_shared(std::move(epoch)); rcu_synchronize(); int status = -1; auto pid2 = waitpid(pid, &status, 0); EXPECT_EQ(status, 0); EXPECT_EQ(pid, pid2); } else { // child rcu_synchronize(); exit(0); // Do not print gtest results } } TEST(RcuTest, ThreadLocalList) { struct TTag; folly::detail::ThreadCachedLists<TTag> lists; std::vector<std::thread> threads{FLAGS_threads}; std::atomic<unsigned long> done{FLAGS_threads}; for (auto& tr : threads) { tr = std::thread([&]() { for (int i = 0; i < FLAGS_iters; i++) { auto node = new folly::detail::ThreadCachedListsBase::Node; lists.push(node); } --done; }); } while (done.load() > 0) { folly::detail::ThreadCachedLists<TTag>::ListHead list{}; lists.collect(list); list.forEach([](folly::detail::ThreadCachedLists<TTag>::Node* node) { delete node; }); } for (auto& thread : threads) { thread.join(); } // Run cleanup pass one more time to make ASAN happy folly::detail::ThreadCachedLists<TTag>::ListHead list{}; lists.collect(list); list.forEach( [](folly::detail::ThreadCachedLists<TTag>::Node* node) { delete node; }); } TEST(RcuTest, ThreadDeath) { bool del = false; std::thread t([&] { auto foo = new des(&del); rcu_retire(foo); }); t.join(); rcu_synchronize(); EXPECT_TRUE(del); } TEST(RcuTest, RcuObjBase) { bool retired = false; struct base_test : rcu_obj_base<base_test> { bool* ret_; base_test(bool* ret) : ret_(ret) {} ~base_test() { (*ret_) = true; } }; auto foo = new base_test(&retired); foo->retire(); rcu_synchronize(); EXPECT_TRUE(retired); } TEST(RcuTest, Tsan) { int data = 0; std::thread t1([&] { auto epoch = rcu_default_domain().lock_shared(); data = 1; rcu_default_domain().unlock_shared(std::move(epoch)); // Delay before exiting so the thread is still alive for TSAN detection. std::this_thread::sleep_for(std::chrono::milliseconds(200)); }); std::thread t2([&] { std::this_thread::sleep_for(std::chrono::milliseconds(100)); // This should establish a happens-before relationship between the earlier // write (data = 1) and this write below (data = 2). rcu_default_domain().synchronize(); data = 2; }); t1.join(); t2.join(); EXPECT_EQ(data, 2); } TEST(RcuTest, DeeplyNestedReaders) { std::vector<std::thread> readers; std::atomic<int*> int_ptr = std::atomic<int*>(nullptr); int_ptr.store(new int(0)); for (unsigned th = 0; th < 32; th++) { readers.push_back(std::thread([&]() { std::vector<rcu_reader> domain_readers; for (unsigned i = 0; i < 8192; i++) { domain_readers.emplace_back(); EXPECT_EQ(*(int_ptr.load(std::memory_order_acquire)), 0); } })); } std::atomic<bool> done{false}; auto updater = std::thread([&]() { while (!done.load()) { auto newint = new int(0); auto oldint = int_ptr.exchange(newint, std::memory_order_acq_rel); delete_or_retire_oldint(oldint); } }); for (auto& t : readers) { t.join(); } done = true; updater.join(); // Clean up to avoid ASAN complaining about a leak. rcu_synchronize(); delete int_ptr.exchange(nullptr, std::memory_order_acquire); } <commit_msg>folly: Use explicit memory orders in rcu_test<commit_after>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <folly/synchronization/Rcu.h> #include <atomic> #include <thread> #include <vector> #include <glog/logging.h> #include <folly/Benchmark.h> #include <folly/Random.h> #include <folly/portability/GFlags.h> #include <folly/portability/GTest.h> using namespace folly; DEFINE_int64(iters, 100000, "Number of iterations"); DEFINE_uint64(threads, 32, "Number of threads"); TEST(RcuTest, Basic) { auto foo = new int(2); rcu_retire(foo); } class des { bool* d_; public: des(bool* d) : d_(d) {} ~des() { *d_ = true; } }; TEST(RcuTest, Guard) { bool del = false; auto foo = new des(&del); { rcu_reader g; } rcu_retire(foo); rcu_synchronize(); EXPECT_TRUE(del); } TEST(RcuTest, SlowReader) { std::thread t; { rcu_reader g; t = std::thread([&]() { rcu_synchronize(); }); usleep(100); // Wait for synchronize to start } t.join(); } rcu_reader tryretire(des* obj) { rcu_reader g; rcu_retire(obj); return g; } TEST(RcuTest, CopyGuard) { bool del = false; auto foo = new des(&del); { auto res = tryretire(foo); EXPECT_FALSE(del); } rcu_barrier(); EXPECT_TRUE(del); } static void delete_or_retire_oldint(int* oldint) { if (folly::Random::rand32() % 2 == 0) { rcu_retire<int>(oldint, [](int* obj) { *obj = folly::Random::rand32(); delete obj; }); } else { rcu_synchronize(); *oldint = folly::Random::rand32(); delete oldint; } } TEST(RcuTest, Stress) { std::vector<std::thread> readers; constexpr uint32_t sz = 1000; std::atomic<int*> ints[sz]; for (uint32_t i = 0; i < sz; i++) { ints[i].store(new int(0), std::memory_order_release); } for (unsigned th = 0; th < FLAGS_threads; th++) { readers.push_back(std::thread([&]() { for (int i = 0; i < FLAGS_iters / 100; i++) { rcu_reader g; int sum = 0; int* ptrs[sz]; for (uint32_t j = 0; j < sz; j++) { ptrs[j] = ints[j].load(std::memory_order_acquire); } for (uint32_t j = 0; j < sz; j++) { sum += *ptrs[j]; } EXPECT_EQ(sum, 0); } })); } std::atomic<bool> done{false}; std::vector<std::thread> updaters; for (unsigned th = 0; th < FLAGS_threads; th++) { updaters.push_back(std::thread([&]() { while (!done.load(std::memory_order_acquire)) { auto newint = new int(0); auto oldint = ints[folly::Random::rand32() % sz].exchange( newint, std::memory_order_acq_rel); delete_or_retire_oldint(oldint); } })); } for (auto& t : readers) { t.join(); } done.store(true, std::memory_order_release); for (auto& t : updaters) { t.join(); } // Cleanup for asan rcu_synchronize(); for (uint32_t i = 0; i < sz; i++) { delete ints[i].exchange(nullptr, std::memory_order_acq_rel); } } TEST(RcuTest, Synchronize) { std::vector<std::thread> threads; for (unsigned th = 0; th < FLAGS_threads; th++) { threads.push_back(std::thread([&]() { for (int i = 0; i < 10; i++) { rcu_synchronize(); } })); } for (auto& t : threads) { t.join(); } } TEST(RcuTest, NewDomainTest) { struct UniqueTag; rcu_domain<UniqueTag> newdomain(nullptr); rcu_synchronize(newdomain); } TEST(RcuTest, NewDomainGuardTest) { struct UniqueTag; rcu_domain<UniqueTag> newdomain(nullptr); bool del = false; auto foo = new des(&del); { rcu_reader_domain<UniqueTag> g(newdomain); } rcu_retire(foo, {}, newdomain); rcu_synchronize(newdomain); EXPECT_TRUE(del); } TEST(RcuTest, MovableReader) { { rcu_reader g; rcu_reader f(std::move(g)); } rcu_synchronize(); { rcu_reader g(std::defer_lock); rcu_reader f; g = std::move(f); } rcu_synchronize(); } TEST(RcuTest, SynchronizeInCall) { rcu_default_domain().call([]() { rcu_synchronize(); }); rcu_synchronize(); } TEST(RcuTest, MoveReaderBetweenThreads) { rcu_reader g; std::thread t([f = std::move(g)] {}); t.join(); rcu_synchronize(); } TEST(RcuTest, ForkTest) { rcu_token<RcuTag> epoch; std::thread t([&]() { epoch = rcu_default_domain().lock_shared(); }); t.join(); auto pid = fork(); if (pid) { // parent rcu_default_domain().unlock_shared(std::move(epoch)); rcu_synchronize(); int status = -1; auto pid2 = waitpid(pid, &status, 0); EXPECT_EQ(status, 0); EXPECT_EQ(pid, pid2); } else { // child rcu_synchronize(); exit(0); // Do not print gtest results } } TEST(RcuTest, ThreadLocalList) { struct TTag; folly::detail::ThreadCachedLists<TTag> lists; std::vector<std::thread> threads{FLAGS_threads}; std::atomic<unsigned long> done{FLAGS_threads}; for (auto& tr : threads) { tr = std::thread([&]() { for (int i = 0; i < FLAGS_iters; i++) { auto node = new folly::detail::ThreadCachedListsBase::Node; lists.push(node); } --done; }); } while (done.load(std::memory_order_acquire) > 0) { folly::detail::ThreadCachedLists<TTag>::ListHead list{}; lists.collect(list); list.forEach([](folly::detail::ThreadCachedLists<TTag>::Node* node) { delete node; }); } for (auto& thread : threads) { thread.join(); } // Run cleanup pass one more time to make ASAN happy folly::detail::ThreadCachedLists<TTag>::ListHead list{}; lists.collect(list); list.forEach( [](folly::detail::ThreadCachedLists<TTag>::Node* node) { delete node; }); } TEST(RcuTest, ThreadDeath) { bool del = false; std::thread t([&] { auto foo = new des(&del); rcu_retire(foo); }); t.join(); rcu_synchronize(); EXPECT_TRUE(del); } TEST(RcuTest, RcuObjBase) { bool retired = false; struct base_test : rcu_obj_base<base_test> { bool* ret_; base_test(bool* ret) : ret_(ret) {} ~base_test() { (*ret_) = true; } }; auto foo = new base_test(&retired); foo->retire(); rcu_synchronize(); EXPECT_TRUE(retired); } TEST(RcuTest, Tsan) { int data = 0; std::thread t1([&] { auto epoch = rcu_default_domain().lock_shared(); data = 1; rcu_default_domain().unlock_shared(std::move(epoch)); // Delay before exiting so the thread is still alive for TSAN detection. std::this_thread::sleep_for(std::chrono::milliseconds(200)); }); std::thread t2([&] { std::this_thread::sleep_for(std::chrono::milliseconds(100)); // This should establish a happens-before relationship between the earlier // write (data = 1) and this write below (data = 2). rcu_default_domain().synchronize(); data = 2; }); t1.join(); t2.join(); EXPECT_EQ(data, 2); } TEST(RcuTest, DeeplyNestedReaders) { std::vector<std::thread> readers; std::atomic<int*> int_ptr = std::atomic<int*>(nullptr); int_ptr.store(new int(0), std::memory_order_release); for (unsigned th = 0; th < 32; th++) { readers.push_back(std::thread([&]() { std::vector<rcu_reader> domain_readers; for (unsigned i = 0; i < 8192; i++) { domain_readers.emplace_back(); EXPECT_EQ(*(int_ptr.load(std::memory_order_acquire)), 0); } })); } std::atomic<bool> done{false}; auto updater = std::thread([&]() { while (!done.load(std::memory_order_acquire)) { auto newint = new int(0); auto oldint = int_ptr.exchange(newint, std::memory_order_acq_rel); delete_or_retire_oldint(oldint); } }); for (auto& t : readers) { t.join(); } done.store(true, std::memory_order_release); updater.join(); // Clean up to avoid ASAN complaining about a leak. rcu_synchronize(); delete int_ptr.exchange(nullptr, std::memory_order_acq_rel); } <|endoftext|>
<commit_before>/* * Binary Search * * O(lgn) * */ class Solution { public: int findPeakElement(vector<int>& nums) { int l = 0, r = nums.size()-1; while(l < r) { int mid = l + (r-l) / 2; if(nums[mid] > nums[mid+1]) { r = mid; } else { l = mid+1; } } return r; } };<commit_msg>Update 162.cpp<commit_after>/* * Binary Search * O(lgn) * */ class Solution { public: int findPeakElement(vector<int>& nums) { int l = 0, r = nums.size()-1; while(l < r) { int mid = l + (r-l) / 2; if(nums[mid] > nums[mid+1]) { r = mid; } else { l = mid+1; } } return r; } }; // Conclusion: // How to choose between mid and mid+1(or mid-1) ? // <|endoftext|>
<commit_before>/* * (C) 2009 Jack Lloyd * * Distributed under the terms of the Botan license */ /** Generate a 1024 bit DSA key and put it into a file. The public key format is that specified by X.509, while the private key format is PKCS #8. The domain parameters are the ones specified as the Java default DSA parameters. There is nothing special about these, it's just the only 1024-bit DSA parameter set that's included in Botan at the time of this writing. The application always reads/writes all of the domain parameters to/from the file, so a new set could be used without any problems. We could generate a new set for each key, or read a set of DSA params from a file and use those, but they mostly seem like needless complications. */ #include <iostream> #include <fstream> #include <string> #include <botan/botan.h> #include <botan/dsa.h> #include <botan/rng.h> using namespace Botan; #include <memory> int main(int argc, char* argv[]) { if(argc != 1 && argc != 2) { std::cout << "Usage: " << argv[0] << " [passphrase]" << std::endl; return 1; } Botan::LibraryInitializer init; std::ofstream priv("dsapriv.pem"); std::ofstream pub("dsapub.pem"); if(!priv || !pub) { std::cout << "Couldn't write output files" << std::endl; return 1; } try { AutoSeeded_RNG rng; DL_Group group(rng, DL_Group::DSA_Kosherizer, 2048, 256); DSA_PrivateKey key(rng, group); pub << X509::PEM_encode(key); if(argc == 1) priv << PKCS8::PEM_encode(key); else priv << PKCS8::PEM_encode(key, rng, argv[1]); } catch(std::exception& e) { std::cout << "Exception caught: " << e.what() << std::endl; } return 0; } <commit_msg>Remove incorrect comment<commit_after>/* * (C) 2009 Jack Lloyd * * Distributed under the terms of the Botan license * * Generate a 1024 bit DSA key and put it into a file. The public key * format is that specified by X.509, while the private key format is * PKCS #8. */ #include <iostream> #include <fstream> #include <string> #include <botan/botan.h> #include <botan/dsa.h> #include <botan/rng.h> using namespace Botan; #include <memory> int main(int argc, char* argv[]) { if(argc != 1 && argc != 2) { std::cout << "Usage: " << argv[0] << " [passphrase]" << std::endl; return 1; } Botan::LibraryInitializer init; std::ofstream priv("dsapriv.pem"); std::ofstream pub("dsapub.pem"); if(!priv || !pub) { std::cout << "Couldn't write output files" << std::endl; return 1; } try { AutoSeeded_RNG rng; DL_Group group(rng, DL_Group::DSA_Kosherizer, 2048, 256); DSA_PrivateKey key(rng, group); pub << X509::PEM_encode(key); if(argc == 1) priv << PKCS8::PEM_encode(key); else priv << PKCS8::PEM_encode(key, rng, argv[1]); } catch(std::exception& e) { std::cout << "Exception caught: " << e.what() << std::endl; } return 0; } <|endoftext|>
<commit_before>#include <oms/OssimTools.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimGrect.h> #include <ossim/util/ossimUtilityRegistry.h> #include <ossim/util/ossimViewshedUtil.h> #include <ossim/util/ossimHlzUtil.h> #include <cstdlib> using namespace oms; using namespace std; OssimTools::OssimTools(string name) : m_chipProcUtil(0) { if ((name.compare("hlz") == 0) || (name.compare("viewshed") == 0)) m_chipProcUtil = (ossimChipProcUtil*) ossimUtilityRegistry::instance()->createUtility(name); else cerr<<"OssimTools() Bad opeation requested: <"<<name<<">. Ignoring."<<endl; } OssimTools::~OssimTools() { delete m_chipProcUtil; } bool OssimTools::initialize(map<string, string> params) { if (m_chipProcUtil == 0) return false; try { ossimKeywordlist kwl (params); m_chipProcUtil->initialize(kwl); } catch (...) { cerr<<"Caught exception in OssimTools::initialize(). Operation aborted."<<endl; return false; } return true; } bool OssimTools::getChip(char* data, map<string,string> hints) { int status = OSSIM_STATUS_UNKNOWN; if ((m_chipProcUtil == 0) || (data == 0)) return OSSIM_NULL; // Expect only geographic bounding rect in hints. double min_lat=ossim::nan(), max_lat=ossim::nan(), min_lon=ossim::nan(), max_lon=ossim::nan(); map<string,string>::iterator value; value = hints.find("min_lat"); if (value != hints.end()) min_lat = atof(value->second.c_str()); value = hints.find("max_lat"); if (value != hints.end()) max_lat = atof(value->second.c_str()); value = hints.find("min_lon"); if (value != hints.end()) min_lon = atof(value->second.c_str()); value = hints.find("max_lon"); if (value != hints.end()) max_lon = atof(value->second.c_str()); ossimGrect bbox (max_lat, min_lon, min_lat, max_lat); if (bbox.hasNans()) return OSSIM_NULL; // Need the ossimImageData buffer returned from native call as a char buffer: try { ossimRefPtr<ossimImageData> chip = m_chipProcUtil->getChip(bbox); if ( chip.valid() ) { status = chip->getDataObjectStatus(); ossimIrect rect = chip->getImageRectangle(); if ( !rect.hasNans() && (status != (int) OSSIM_NULL)) chip->unloadTile( (void*)data, rect, OSSIM_BIP ); } } catch ( ... ) { cerr<<"Caught exception in OssimTools::getChip(). Operation aborted."<<endl; } return status; } <commit_msg>Intermediate<commit_after>#include <oms/OssimTools.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimGrect.h> #include <ossim/util/ossimUtilityRegistry.h> #include <ossim/util/ossimViewshedUtil.h> #include <ossim/util/ossimHlzUtil.h> #include <cstdlib> using namespace oms; using namespace std; OssimTools::OssimTools(string name) : m_chipProcUtil(0) { m_chipProcUtil = (ossimChipProcUtil*) ossimUtilityRegistry::instance()->createUtility(name); if (m_chipProcUtil == 0) cerr<<"OssimTools() Bad opeation requested: <"<<name<<">. Ignoring."<<endl; } OssimTools::~OssimTools() { delete m_chipProcUtil; } bool OssimTools::initialize(map<string, string> params) { if (m_chipProcUtil == 0) return false; try { ossimKeywordlist kwl (params); m_chipProcUtil->initialize(kwl); } catch (...) { cerr<<"Caught exception in OssimTools::initialize(). Operation aborted."<<endl; return false; } return true; } bool OssimTools::getChip(char* data, map<string,string> hints) { int status = OSSIM_STATUS_UNKNOWN; if ((m_chipProcUtil == 0) || (data == 0)) return OSSIM_NULL; // Expect only geographic bounding rect in hints. double min_lat=ossim::nan(), max_lat=ossim::nan(), min_lon=ossim::nan(), max_lon=ossim::nan(); map<string,string>::iterator value; value = hints.find("min_lat"); if (value != hints.end()) min_lat = atof(value->second.c_str()); value = hints.find("max_lat"); if (value != hints.end()) max_lat = atof(value->second.c_str()); value = hints.find("min_lon"); if (value != hints.end()) min_lon = atof(value->second.c_str()); value = hints.find("max_lon"); if (value != hints.end()) max_lon = atof(value->second.c_str()); ossimGrect bbox (max_lat, min_lon, min_lat, max_lat); // Need the ossimImageData buffer returned from native call as a char buffer: try { ossimRefPtr<ossimImageData> chip = m_chipProcUtil->getChip(bbox); if ( chip.valid() ) { status = chip->getDataObjectStatus(); ossimIrect rect = chip->getImageRectangle(); if ( !rect.hasNans() && (status != (int) OSSIM_NULL)) chip->unloadTile( (void*)data, rect, OSSIM_BIP ); } } catch ( ... ) { cerr<<"Caught exception in OssimTools::getChip(). Operation aborted."<<endl; } return status; } <|endoftext|>
<commit_before>#include <oms/OssimTools.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimGrect.h> #include <ossim/base/ossimException.h> #include <ossim/projection/ossimMapProjection.h> #include <ossim/util/ossimHlzTool.h> #include <ossim/util/ossimToolRegistry.h> #include <ossim/util/ossimViewshedTool.h> #include <cstdlib> using namespace oms; using namespace std; bool OssimTools::m_locked = false; OssimTools::OssimTools(string name) : m_utility(0) { m_utility = ossimToolRegistry::instance()->createUtility(name); if (m_utility == 0) cerr<<"OssimTools() Bad opeation requested: <"<<name<<">. Ignoring."<<endl; } OssimTools::~OssimTools() { delete m_utility; } bool OssimTools::initialize(const map<string, string>& params) { if (m_utility == 0) return false; // Accept map from service and translate to KWL expected by native code: ossimKeywordlist kwl; try { if (!m_locked) { m_locked = true; ossimKeywordlist kwl (params); cout<<"\nOssimTools::initialize() -- KWL:\n"<<kwl<<endl;//TODO:remove debug m_utility->initialize(kwl); m_locked = false; } } catch (ossimException& e) { cerr<<"Caught OSSIM exception in OssimTools::initialize():\n"<<e.what()<<endl; return false; } catch (...) { cerr<<"Caught unknown exception in OssimTools::initialize()."<<endl; return false; } return true; } bool OssimTools::execute(char* outstreambuf) { if (m_utility == 0) return false; ostringstream outputStream; m_utility->setOutputStream(&outputStream); bool status = m_utility->execute(); // Copy the output stream to string array: size_t bufsize = outputStream.width(); outstreambuf = new char[bufsize+1]; memcpy(outstreambuf, outputStream.str().c_str(), bufsize); return status; } bool OssimTools::getChip(ossim_int8* data, const map<string,string>& hints) { if ((m_utility == 0) || !m_utility->isChipProcessor() || (data == 0)) return false; ossimChipProcTool* chipper = (ossimChipProcTool*) m_utility; // Expect only geographic bounding rect in hints. double min_x, max_x, min_y, max_y; int width=0, height=0; map<string,string>::const_iterator value; do { value = hints.find("min_x"); if (value == hints.end()) break; min_x = atof(value->second.c_str()); value = hints.find("max_x"); if (value == hints.end()) break; max_x = atof(value->second.c_str()); value = hints.find("min_y"); if (value == hints.end()) break; min_y = atof(value->second.c_str()); value = hints.find("max_y"); if (value == hints.end()) break; max_y = atof(value->second.c_str()); value = hints.find("width"); if (value == hints.end()) break; width = atoi(value->second.c_str()); value = hints.find("height"); if (value == hints.end()) break; height = atoi(value->second.c_str()); } while (0); if (width == 0) { cerr<<"OssimTools ["<<__LINE__<<"] -- Bad parse of hints map."<<endl; return false; } ossimDrect map_bbox (min_x, max_y, max_x, min_y); double gsd_x = fabs(max_x - min_x)/(double) (width-1); double gsd_y = fabs(max_y - min_y)/(double) (height-1); ossimDpt gsd (gsd_x, gsd_y); // Need the ossimImageData buffer returned from native call as a char buffer: cerr<<"\nOssimTools:"<<__LINE__<<endl;//TODO:remove debug cerr<<"\nOssimTools: map_bbox"<<map_bbox<<endl;//TODO:remove debug cerr<<"\nOssimTools: gsd"<<gsd<<endl;//TODO:remove debug try { ossimRefPtr<ossimImageData> chip = chipper->getChip(map_bbox, gsd); cerr<<"\nOssimTools:"<<__LINE__<<endl;//TODO:remove debug if ( chip.valid() ) { cerr<<"\nOssimTools:"<<__LINE__<<endl;//TODO:remove debug ossimDataObjectStatus status = chip->getDataObjectStatus(); ossimIrect rect = chip->getImageRectangle(); if ( !rect.hasNans() && (status != (int) OSSIM_NULL)) { cerr<<"\nOssimTools:"<<__LINE__<<endl;//TODO:remove debug //chip->computeAlphaChannel(); cerr<<"\nOssimTools:"<<__LINE__<<endl;//TODO:remove debug chip->unloadTile((void*)data, rect, OSSIM_BIP); cerr<<"\nOssimTools:"<<__LINE__<<endl;//TODO:remove debug chip->write("/tmp/getChip.ras");//TODO:remove debug } else throw ossimException("Bad chip returned from native getChip call."); } else throw ossimException("Null chip returned from native getChip call."); } catch (ossimException& e) { cerr<<"Caught OSSIM exception in OssimTools::getChip():\n"<<e.what()<<endl; return false; } catch ( ... ) { cerr<<"Caught exception in OssimTools::getChip(). Operation aborted."<<endl; return false; } return true; } <commit_msg>Fixed remaining references to "Utility" and renamed to "Tool"<commit_after>#include <oms/OssimTools.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimGrect.h> #include <ossim/base/ossimException.h> #include <ossim/projection/ossimMapProjection.h> #include <ossim/util/ossimHlzTool.h> #include <ossim/util/ossimToolRegistry.h> #include <ossim/util/ossimViewshedTool.h> #include <cstdlib> using namespace oms; using namespace std; bool OssimTools::m_locked = false; OssimTools::OssimTools(string name) : m_utility(0) { m_utility = ossimToolRegistry::instance()->createTool(name); if (m_utility == 0) cerr<<"OssimTools() Bad opeation requested: <"<<name<<">. Ignoring."<<endl; } OssimTools::~OssimTools() { delete m_utility; } bool OssimTools::initialize(const map<string, string>& params) { if (m_utility == 0) return false; // Accept map from service and translate to KWL expected by native code: ossimKeywordlist kwl; try { if (!m_locked) { m_locked = true; ossimKeywordlist kwl (params); cout<<"\nOssimTools::initialize() -- KWL:\n"<<kwl<<endl;//TODO:remove debug m_utility->initialize(kwl); m_locked = false; } } catch (ossimException& e) { cerr<<"Caught OSSIM exception in OssimTools::initialize():\n"<<e.what()<<endl; return false; } catch (...) { cerr<<"Caught unknown exception in OssimTools::initialize()."<<endl; return false; } return true; } bool OssimTools::execute(char* outstreambuf) { if (m_utility == 0) return false; ostringstream outputStream; m_utility->setOutputStream(&outputStream); bool status = m_utility->execute(); // Copy the output stream to string array: size_t bufsize = outputStream.width(); outstreambuf = new char[bufsize+1]; memcpy(outstreambuf, outputStream.str().c_str(), bufsize); return status; } bool OssimTools::getChip(ossim_int8* data, const map<string,string>& hints) { if ((m_utility == 0) || !m_utility->isChipProcessor() || (data == 0)) return false; ossimChipProcTool* chipper = (ossimChipProcTool*) m_utility; // Expect only geographic bounding rect in hints. double min_x, max_x, min_y, max_y; int width=0, height=0; map<string,string>::const_iterator value; do { value = hints.find("min_x"); if (value == hints.end()) break; min_x = atof(value->second.c_str()); value = hints.find("max_x"); if (value == hints.end()) break; max_x = atof(value->second.c_str()); value = hints.find("min_y"); if (value == hints.end()) break; min_y = atof(value->second.c_str()); value = hints.find("max_y"); if (value == hints.end()) break; max_y = atof(value->second.c_str()); value = hints.find("width"); if (value == hints.end()) break; width = atoi(value->second.c_str()); value = hints.find("height"); if (value == hints.end()) break; height = atoi(value->second.c_str()); } while (0); if (width == 0) { cerr<<"OssimTools ["<<__LINE__<<"] -- Bad parse of hints map."<<endl; return false; } ossimDrect map_bbox (min_x, max_y, max_x, min_y); double gsd_x = fabs(max_x - min_x)/(double) (width-1); double gsd_y = fabs(max_y - min_y)/(double) (height-1); ossimDpt gsd (gsd_x, gsd_y); // Need the ossimImageData buffer returned from native call as a char buffer: cerr<<"\nOssimTools:"<<__LINE__<<endl;//TODO:remove debug cerr<<"\nOssimTools: map_bbox"<<map_bbox<<endl;//TODO:remove debug cerr<<"\nOssimTools: gsd"<<gsd<<endl;//TODO:remove debug try { ossimRefPtr<ossimImageData> chip = chipper->getChip(map_bbox, gsd); cerr<<"\nOssimTools:"<<__LINE__<<endl;//TODO:remove debug if ( chip.valid() ) { cerr<<"\nOssimTools:"<<__LINE__<<endl;//TODO:remove debug ossimDataObjectStatus status = chip->getDataObjectStatus(); ossimIrect rect = chip->getImageRectangle(); if ( !rect.hasNans() && (status != (int) OSSIM_NULL)) { cerr<<"\nOssimTools:"<<__LINE__<<endl;//TODO:remove debug //chip->computeAlphaChannel(); cerr<<"\nOssimTools:"<<__LINE__<<endl;//TODO:remove debug chip->unloadTile((void*)data, rect, OSSIM_BIP); cerr<<"\nOssimTools:"<<__LINE__<<endl;//TODO:remove debug chip->write("/tmp/getChip.ras");//TODO:remove debug } else throw ossimException("Bad chip returned from native getChip call."); } else throw ossimException("Null chip returned from native getChip call."); } catch (ossimException& e) { cerr<<"Caught OSSIM exception in OssimTools::getChip():\n"<<e.what()<<endl; return false; } catch ( ... ) { cerr<<"Caught exception in OssimTools::getChip(). Operation aborted."<<endl; return false; } return true; } <|endoftext|>
<commit_before>/** * @file /cost_map_core/include/cost_map_core/operators/inflation.hpp */ /***************************************************************************** ** Ifdefs *****************************************************************************/ #ifndef cost_map_core_INFLATION_HPP_ #define cost_map_core_INFLATION_HPP_ /***************************************************************************** ** Includes *****************************************************************************/ #include "../CostMap.hpp" #include <queue> /***************************************************************************** ** Namespaces *****************************************************************************/ namespace cost_map { /***************************************************************************** ** Inflation Function *****************************************************************************/ /** * @brief Function which can compute costs for the inflation layer. * * Inherit from this to generate your own inflation * functions. */ class InflationComputer { public: InflationComputer() {}; virtual ~InflationComputer() {}; /** @brief Given a distance, compute a cost. * * @param distance The distance from an obstacle in cells * @return A cost value for the distance **/ virtual unsigned char operator()(const float &distance) const = 0; }; /** * @brief Function which can compute costs for the inflation layer. * * This class provides a default inflation function which works like the * ROS inflation layer. Inherit from this to generate your own inflation * functions. */ class ROSInflationComputer : public InflationComputer { public: ROSInflationComputer(const float& inscribed_radius, const float& weight); virtual ~ROSInflationComputer() {}; /** @brief Given a distance, compute a cost. * * @param distance The metric distance from an obstacle (distance = cell_distance*resolution) * @return A cost value for the distance **/ virtual unsigned char operator()(const float &distance) const; private: float inscribed_radius_, weight_; }; /***************************************************************************** ** Inflation *****************************************************************************/ class Inflate { public: /** * @brief Inflate... * * @param layer_source * @param layer_destination * @param inflation_radius * @param inscribed_radius * @param cost_map * @throw std::out_of_range if no map layer with name `layer` is present. */ void operator()(const std::string layer_source, const std::string layer_destination, const float& inflation_radius, const InflationComputer& inflation_computer, CostMap& cost_map ); private: struct CellData { /** * @brief Constructor for CellData objects * @param d The distance to the nearest obstacle, used for ordering in the priority queue * @param x The x coordinate of the cell in the cost map * @param y The y coordinate of the cell in the cost map * @param sx The x coordinate of the closest obstacle cell in the costmap * @param sy The y coordinate of the closest obstacle cell in the costmap * @return */ CellData(double d, unsigned int x, unsigned int y, unsigned int sx, unsigned int sy) : distance_(d), x_(x), y_(y), src_x_(sx), src_y_(sy) { } /** * @brief Provide an ordering between CellData objects in the priority queue * @return We want the lowest distance to have the highest priority... so this returns true if a has higher priority than b */ friend bool operator<(const CellData &a, const CellData &b) { return a.distance_ > b.distance_; } double distance_; unsigned int x_, y_; unsigned int src_x_, src_y_; }; /** * @brief Given an index of a cell in the costmap, place it into a priority queue for obstacle inflation * @param data_destination the costs (will be read and superimposed on this) * @param mx The x coordinate of the cell (can be computed from the index, but saves time to store it) * @param my The y coordinate of the cell (can be computed from the index, but saves time to store it) * @param src_x The x index of the obstacle point inflation started at * @param src_y The y index of the obstacle point inflation started at */ void enqueue(const cost_map::Matrix& data_source, cost_map::Matrix& data_destination, unsigned int mx, unsigned int my, unsigned int src_x, unsigned int src_y ); /** * @brief Lookup pre-computed distances * @param mx The x coordinate of the current cell * @param my The y coordinate of the current cell * @param src_x The x coordinate of the source cell * @param src_y The y coordinate of the source cell * @return */ double distanceLookup(int mx, int my, int src_x, int src_y); /** * @brief Lookup pre-computed costs * @param mx The x coordinate of the current cell * @param my The y coordinate of the current cell * @param src_x The x coordinate of the source cell * @param src_y The y coordinate of the source cell * @return */ unsigned char costLookup(int mx, int my, int src_x, int src_y); void computeCaches(const float& resolution, const InflationComputer& compute_cost); Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic> seen_; Eigen::MatrixXf cached_distances_; cost_map::Matrix cached_costs_; std::priority_queue<CellData> inflation_queue_; unsigned int cell_inflation_radius_; /// size of the inflation radius in cells }; /***************************************************************************** ** Deflation *****************************************************************************/ /** * Use to strip the inflation layer from a cost map. */ class Deflate { public: Deflate(const bool& do_not_strip_inscribed_region=false); /** * @brief Deflate... * * @param layer_source * @param layer_destination * @param cost_map * @throw std::out_of_range if no map layer with name `layer` is present. */ void operator()(const std::string layer_source, const std::string layer_destination, CostMap& cost_map ); private: bool do_not_strip_inscribed_region; }; /***************************************************************************** ** Trailers *****************************************************************************/ } // namespace cost_map_core #endif /* cost_map_core_INFLATION_HPP_ */ <commit_msg>[cost_map_core] initialises cell_inflation_radius<commit_after>/** * @file /cost_map_core/include/cost_map_core/operators/inflation.hpp */ /***************************************************************************** ** Ifdefs *****************************************************************************/ #ifndef cost_map_core_INFLATION_HPP_ #define cost_map_core_INFLATION_HPP_ /***************************************************************************** ** Includes *****************************************************************************/ #include "../CostMap.hpp" #include <limits> #include <queue> /***************************************************************************** ** Namespaces *****************************************************************************/ namespace cost_map { /***************************************************************************** ** Inflation Function *****************************************************************************/ /** * @brief Function which can compute costs for the inflation layer. * * Inherit from this to generate your own inflation * functions. */ class InflationComputer { public: InflationComputer() {}; virtual ~InflationComputer() {}; /** @brief Given a distance, compute a cost. * * @param distance The distance from an obstacle in cells * @return A cost value for the distance **/ virtual unsigned char operator()(const float &distance) const = 0; }; /** * @brief Function which can compute costs for the inflation layer. * * This class provides a default inflation function which works like the * ROS inflation layer. Inherit from this to generate your own inflation * functions. */ class ROSInflationComputer : public InflationComputer { public: ROSInflationComputer(const float& inscribed_radius, const float& weight); virtual ~ROSInflationComputer() {}; /** @brief Given a distance, compute a cost. * * @param distance The metric distance from an obstacle (distance = cell_distance*resolution) * @return A cost value for the distance **/ virtual unsigned char operator()(const float &distance) const; private: float inscribed_radius_, weight_; }; /***************************************************************************** ** Inflation *****************************************************************************/ class Inflate { public: Inflate() : cell_inflation_radius_(std::numeric_limits<unsigned int>::max()) { }; /** * @brief Inflate... * * @param layer_source * @param layer_destination * @param inflation_radius * @param inscribed_radius * @param cost_map * @throw std::out_of_range if no map layer with name `layer` is present. */ void operator()(const std::string layer_source, const std::string layer_destination, const float& inflation_radius, const InflationComputer& inflation_computer, CostMap& cost_map ); private: struct CellData { /** * @brief Constructor for CellData objects * @param d The distance to the nearest obstacle, used for ordering in the priority queue * @param x The x coordinate of the cell in the cost map * @param y The y coordinate of the cell in the cost map * @param sx The x coordinate of the closest obstacle cell in the costmap * @param sy The y coordinate of the closest obstacle cell in the costmap * @return */ CellData(double d, unsigned int x, unsigned int y, unsigned int sx, unsigned int sy) : distance_(d), x_(x), y_(y), src_x_(sx), src_y_(sy) { } /** * @brief Provide an ordering between CellData objects in the priority queue * @return We want the lowest distance to have the highest priority... so this returns true if a has higher priority than b */ friend bool operator<(const CellData &a, const CellData &b) { return a.distance_ > b.distance_; } double distance_; unsigned int x_, y_; unsigned int src_x_, src_y_; }; /** * @brief Given an index of a cell in the costmap, place it into a priority queue for obstacle inflation * @param data_destination the costs (will be read and superimposed on this) * @param mx The x coordinate of the cell (can be computed from the index, but saves time to store it) * @param my The y coordinate of the cell (can be computed from the index, but saves time to store it) * @param src_x The x index of the obstacle point inflation started at * @param src_y The y index of the obstacle point inflation started at */ void enqueue(const cost_map::Matrix& data_source, cost_map::Matrix& data_destination, unsigned int mx, unsigned int my, unsigned int src_x, unsigned int src_y ); /** * @brief Lookup pre-computed distances * @param mx The x coordinate of the current cell * @param my The y coordinate of the current cell * @param src_x The x coordinate of the source cell * @param src_y The y coordinate of the source cell * @return */ double distanceLookup(int mx, int my, int src_x, int src_y); /** * @brief Lookup pre-computed costs * @param mx The x coordinate of the current cell * @param my The y coordinate of the current cell * @param src_x The x coordinate of the source cell * @param src_y The y coordinate of the source cell * @return */ unsigned char costLookup(int mx, int my, int src_x, int src_y); void computeCaches(const float& resolution, const InflationComputer& compute_cost); Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic> seen_; Eigen::MatrixXf cached_distances_; cost_map::Matrix cached_costs_; std::priority_queue<CellData> inflation_queue_; unsigned int cell_inflation_radius_; /// size of the inflation radius in cells }; /***************************************************************************** ** Deflation *****************************************************************************/ /** * Use to strip the inflation layer from a cost map. */ class Deflate { public: Deflate(const bool& do_not_strip_inscribed_region=false); /** * @brief Deflate... * * @param layer_source * @param layer_destination * @param cost_map * @throw std::out_of_range if no map layer with name `layer` is present. */ void operator()(const std::string layer_source, const std::string layer_destination, CostMap& cost_map ); private: bool do_not_strip_inscribed_region; }; /***************************************************************************** ** Trailers *****************************************************************************/ } // namespace cost_map_core #endif /* cost_map_core_INFLATION_HPP_ */ <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // 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) //======================================================================= /* * This file contains the OS specific layer */ #include "acpica.hpp" #include "kalloc.hpp" #include "console.hpp" #include "scheduler.hpp" #include "virtual_allocator.hpp" #include "paging.hpp" extern "C" { void* AcpiOsAllocate(ACPI_SIZE size){ return kalloc::k_malloc(size); } void AcpiOsFree(void* p){ kalloc::k_free(p); } void AcpiOsPrintf(const char* format, ...){ va_list va; va_start(va, format); printf(format, va); va_end(va); } void AcpiOsVprintf(const char* format, va_list va){ printf(format, va); } ACPI_THREAD_ID AcpiOsGetThreadId(void){ return scheduler::get_pid(); } ACPI_PHYSICAL_ADDRESS AcpiOsGetRootPointer(){ ACPI_PHYSICAL_ADDRESS root_pointer; root_pointer = 0; AcpiFindRootPointer(&root_pointer); return root_pointer; } void* AcpiOsMapMemory(ACPI_PHYSICAL_ADDRESS phys, ACPI_SIZE length){ size_t pages = (length + paging::PAGE_SIZE - 1) & ~(paging::PAGE_SIZE - 1); auto virt = virtual_allocator::allocate(pages); auto phys_aligned = phys - (phys & ~(paging::PAGE_SIZE - 1)); paging::map_pages(virt, phys_aligned, pages); return reinterpret_cast<void*>(virt + (phys & ~(paging::PAGE_SIZE - 1))); } void AcpiOsUnmapMemory(void* virt_aligned_raw, ACPI_SIZE length){ size_t pages = (length + paging::PAGE_SIZE - 1) & ~(paging::PAGE_SIZE - 1); auto virt_aligned = reinterpret_cast<size_t>(virt_aligned_raw); auto virt = virt_aligned - (virt_aligned & ~(paging::PAGE_SIZE - 1)); paging::unmap_pages(virt, pages); virtual_allocator::free(virt, pages); } } //end of extern "C" <commit_msg>Add comments<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // 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) //======================================================================= /* * This file contains the OS specific layer */ #include "acpica.hpp" #include "kalloc.hpp" #include "console.hpp" #include "scheduler.hpp" #include "virtual_allocator.hpp" #include "paging.hpp" extern "C" { // Dynamic allocation void* AcpiOsAllocate(ACPI_SIZE size){ return kalloc::k_malloc(size); } void AcpiOsFree(void* p){ kalloc::k_free(p); } // terminal void AcpiOsPrintf(const char* format, ...){ va_list va; va_start(va, format); printf(format, va); va_end(va); } void AcpiOsVprintf(const char* format, va_list va){ printf(format, va); } // Scheduling ACPI_THREAD_ID AcpiOsGetThreadId(void){ return scheduler::get_pid(); } // ACPI ACPI_PHYSICAL_ADDRESS AcpiOsGetRootPointer(){ ACPI_PHYSICAL_ADDRESS root_pointer; root_pointer = 0; AcpiFindRootPointer(&root_pointer); return root_pointer; } // Paging void* AcpiOsMapMemory(ACPI_PHYSICAL_ADDRESS phys, ACPI_SIZE length){ size_t pages = (length + paging::PAGE_SIZE - 1) & ~(paging::PAGE_SIZE - 1); auto virt = virtual_allocator::allocate(pages); auto phys_aligned = phys - (phys & ~(paging::PAGE_SIZE - 1)); paging::map_pages(virt, phys_aligned, pages); return reinterpret_cast<void*>(virt + (phys & ~(paging::PAGE_SIZE - 1))); } void AcpiOsUnmapMemory(void* virt_aligned_raw, ACPI_SIZE length){ size_t pages = (length + paging::PAGE_SIZE - 1) & ~(paging::PAGE_SIZE - 1); auto virt_aligned = reinterpret_cast<size_t>(virt_aligned_raw); auto virt = virt_aligned - (virt_aligned & ~(paging::PAGE_SIZE - 1)); paging::unmap_pages(virt, pages); virtual_allocator::free(virt, pages); } } //end of extern "C" <|endoftext|>
<commit_before>/* * File: catmem.cpp * Copyright (C) 2009 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "tr/cat/catmem.h" #include "tr/cat/catmem.h" #include <stack> CatalogMemoryContext *CATALOG_TEMPORARY_CONTEXT = NULL; CatalogMemoryContext *CATALOG_COMMON_CONTEXT = NULL; void * local_space_base = NULL; void * catalog_space_base = NULL; void * default_context_space = NULL; static std::stack<void *> contextstack; void setDefaultSpace(void * space) { contextstack.push(default_context_space); default_context_space = space; }; void * popDefaultSpace() { default_context_space = contextstack.top(); contextstack.pop(); }; /* As soon as persistent context is the same as temporary */ #ifdef CATMEM_TRACE unsigned allocated_objects = 0; unsigned deallocated_objects = 0; #endif #ifdef CATMEM_DEBUG void *cat_malloc_context_debug(CatalogMemoryContext *context, size_t size, const char *file, unsigned line) { void *res; if (!size) return NULL; res = cat_malloc_context_(context, (context) ? size : size + 4); if (context == NULL) { *(uint32_t *)res = 0xDEADBEAF; res = (char *)res + 4; } TRACE_CAT_ALLOC(res, file, line); return res; } void cat_free_debug(void *p, const char *file, unsigned line) { TRACE_CAT_FREE(p, file, line); p = (char *)p - 4; U_ASSERT(*((uint32_t *)p) == 0xDEADBEAF || *((uint32_t *)p) == CONTEXT_MAGIC); *((uint32_t *)p) = 0; cat_free_(p); } #endif /* CATMEM_DEBUG */ void *cat_malloc_context_(CatalogMemoryContext *context, size_t size) { void *mem; if (size == 0) return NULL; if (context) mem = context->cust_malloc(size); else mem = malloc(size); if (!mem) throw std::bad_alloc(); return mem; } void *cat_malloc(void * parent, size_t size) { CatalogMemoryContext *parent_context = CatalogMemoryContext::find_context_for_addr(parent); return cat_malloc_context(parent_context, size); } void *cat_malloc_safe(void * parent, size_t size) { CatalogMemoryContext *parent_context = CatalogMemoryContext::find_context_for_addr_safe(parent); return cat_malloc_context(parent_context, size); } void cat_free_(void *p) { /* we don't want to call free for context address since we do bulk free there */ if (CatalogMemoryContext::find_context_for_addr(p)) return; free(p); } void *FastPointerArray::search_for_chunk_addr(uint32_t cust_chunk_size, void *addr) { FastPointerArrayChunk *i = chunks; unsigned c = lastPtr; while (i != NULL) { for (unsigned j = 0; j < c; j++) { uintptr_t chunk_start = (uintptr_t)i->data[j]; uintptr_t chunk_boundary = chunk_start + cust_chunk_size; if ((uintptr_t)addr >= chunk_start && (uintptr_t)addr < chunk_boundary) return i->data[j]; } c = FPA_SIZE; i = i->next; } return NULL; } void *FastPointerArray::get_elem(uint32_t ind) { unsigned i, j; FastPointerArrayChunk *chunk = chunks; i = chunk_num - ind / FPA_SIZE - 1; j = ind % FPA_SIZE; U_ASSERT(i <= chunk_num); while (i--) chunk = chunk->next; return chunk->data[j]; } int CatalogMemoryContext::allocate_chunk() { chunk_head *header; if (chunk_num == UINT32_MAX - 1) return -1; curr_chunk_addr = malloc(chunk_size); if (!curr_chunk_addr) return -1; header = (chunk_head *)curr_chunk_addr; header->context = this; header->chunk_num = chunk_num++; header->magic = CONTEXT_MAGIC; chunks.add(curr_chunk_addr); curr_chunk_offset = sizeof(struct chunk_head); return 0; } void *CatalogMemoryContext::cust_malloc(size_t size) { char *res = NULL; alloc_head *header; if (size == 0) return NULL; size += sizeof(struct alloc_head); if (size > chunk_size) return NULL; if (chunk_num == 0 && allocate_chunk() != 0) /* first allocation */ return NULL; if (curr_chunk_offset + size > chunk_size && allocate_chunk() != 0) return NULL; res = (char *)curr_chunk_addr + curr_chunk_offset; header = (alloc_head *)res; header->chunk_addr = (chunk_head *)curr_chunk_addr; #ifdef CATMEM_DEBUG header->magic = CONTEXT_MAGIC; #endif res += sizeof(struct alloc_head); curr_chunk_offset += size; return res; } CatalogMemoryContext *CatalogMemoryContext::find_context_for_addr_safe(void *addr) { if (CATALOG_TEMPORARY_CONTEXT && CATALOG_TEMPORARY_CONTEXT->is_addr_in_context(addr)) return CATALOG_TEMPORARY_CONTEXT; else if (CATALOG_COMMON_CONTEXT && CATALOG_COMMON_CONTEXT->is_addr_in_context(addr)) return CATALOG_COMMON_CONTEXT; /* CATALOG_PERSISTENT_CONTEXT is commented out since for now it equals CATALOG_TEMPORARY_CONTEXT (AK) else if (CATALOG_PERSISTENT_CONTEXT && CATALOG_PERSISTENT_CONTEXT->is_addr_in_context(addr)) return CATALOG_PERSISTENT_CONTEXT; */ return NULL; } char * cat_strcpy(void * parent, const char * src) { if (src == NULL) { return NULL; } int n = strlen(src) + 1; char * dest = (char *) cat_malloc(parent, n); return strncpy(dest, src, n); } <commit_msg>CL compilation error<commit_after>/* * File: catmem.cpp * Copyright (C) 2009 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "tr/cat/catmem.h" #include "tr/cat/catmem.h" #include <stack> CatalogMemoryContext *CATALOG_TEMPORARY_CONTEXT = NULL; CatalogMemoryContext *CATALOG_COMMON_CONTEXT = NULL; void * local_space_base = NULL; void * catalog_space_base = NULL; void * default_context_space = NULL; static std::stack<void *> contextstack; void setDefaultSpace(void * space) { contextstack.push(default_context_space); default_context_space = space; }; void * popDefaultSpace() { default_context_space = contextstack.top(); contextstack.pop(); return default_context_space; }; /* As soon as persistent context is the same as temporary */ #ifdef CATMEM_TRACE unsigned allocated_objects = 0; unsigned deallocated_objects = 0; #endif #ifdef CATMEM_DEBUG void *cat_malloc_context_debug(CatalogMemoryContext *context, size_t size, const char *file, unsigned line) { void *res; if (!size) return NULL; res = cat_malloc_context_(context, (context) ? size : size + 4); if (context == NULL) { *(uint32_t *)res = 0xDEADBEAF; res = (char *)res + 4; } TRACE_CAT_ALLOC(res, file, line); return res; } void cat_free_debug(void *p, const char *file, unsigned line) { TRACE_CAT_FREE(p, file, line); p = (char *)p - 4; U_ASSERT(*((uint32_t *)p) == 0xDEADBEAF || *((uint32_t *)p) == CONTEXT_MAGIC); *((uint32_t *)p) = 0; cat_free_(p); } #endif /* CATMEM_DEBUG */ void *cat_malloc_context_(CatalogMemoryContext *context, size_t size) { void *mem; if (size == 0) return NULL; if (context) mem = context->cust_malloc(size); else mem = malloc(size); if (!mem) throw std::bad_alloc(); return mem; } void *cat_malloc(void * parent, size_t size) { CatalogMemoryContext *parent_context = CatalogMemoryContext::find_context_for_addr(parent); return cat_malloc_context(parent_context, size); } void *cat_malloc_safe(void * parent, size_t size) { CatalogMemoryContext *parent_context = CatalogMemoryContext::find_context_for_addr_safe(parent); return cat_malloc_context(parent_context, size); } void cat_free_(void *p) { /* we don't want to call free for context address since we do bulk free there */ if (CatalogMemoryContext::find_context_for_addr(p)) return; free(p); } void *FastPointerArray::search_for_chunk_addr(uint32_t cust_chunk_size, void *addr) { FastPointerArrayChunk *i = chunks; unsigned c = lastPtr; while (i != NULL) { for (unsigned j = 0; j < c; j++) { uintptr_t chunk_start = (uintptr_t)i->data[j]; uintptr_t chunk_boundary = chunk_start + cust_chunk_size; if ((uintptr_t)addr >= chunk_start && (uintptr_t)addr < chunk_boundary) return i->data[j]; } c = FPA_SIZE; i = i->next; } return NULL; } void *FastPointerArray::get_elem(uint32_t ind) { unsigned i, j; FastPointerArrayChunk *chunk = chunks; i = chunk_num - ind / FPA_SIZE - 1; j = ind % FPA_SIZE; U_ASSERT(i <= chunk_num); while (i--) chunk = chunk->next; return chunk->data[j]; } int CatalogMemoryContext::allocate_chunk() { chunk_head *header; if (chunk_num == UINT32_MAX - 1) return -1; curr_chunk_addr = malloc(chunk_size); if (!curr_chunk_addr) return -1; header = (chunk_head *)curr_chunk_addr; header->context = this; header->chunk_num = chunk_num++; header->magic = CONTEXT_MAGIC; chunks.add(curr_chunk_addr); curr_chunk_offset = sizeof(struct chunk_head); return 0; } void *CatalogMemoryContext::cust_malloc(size_t size) { char *res = NULL; alloc_head *header; if (size == 0) return NULL; size += sizeof(struct alloc_head); if (size > chunk_size) return NULL; if (chunk_num == 0 && allocate_chunk() != 0) /* first allocation */ return NULL; if (curr_chunk_offset + size > chunk_size && allocate_chunk() != 0) return NULL; res = (char *)curr_chunk_addr + curr_chunk_offset; header = (alloc_head *)res; header->chunk_addr = (chunk_head *)curr_chunk_addr; #ifdef CATMEM_DEBUG header->magic = CONTEXT_MAGIC; #endif res += sizeof(struct alloc_head); curr_chunk_offset += size; return res; } CatalogMemoryContext *CatalogMemoryContext::find_context_for_addr_safe(void *addr) { if (CATALOG_TEMPORARY_CONTEXT && CATALOG_TEMPORARY_CONTEXT->is_addr_in_context(addr)) return CATALOG_TEMPORARY_CONTEXT; else if (CATALOG_COMMON_CONTEXT && CATALOG_COMMON_CONTEXT->is_addr_in_context(addr)) return CATALOG_COMMON_CONTEXT; /* CATALOG_PERSISTENT_CONTEXT is commented out since for now it equals CATALOG_TEMPORARY_CONTEXT (AK) else if (CATALOG_PERSISTENT_CONTEXT && CATALOG_PERSISTENT_CONTEXT->is_addr_in_context(addr)) return CATALOG_PERSISTENT_CONTEXT; */ return NULL; } char * cat_strcpy(void * parent, const char * src) { if (src == NULL) { return NULL; } int n = strlen(src) + 1; char * dest = (char *) cat_malloc(parent, n); return strncpy(dest, src, n); } <|endoftext|>
<commit_before> #include "../../Flare.h" #include "FlareShipStatus.h" #include "../../Player/FlareMenuManager.h" #define LOCTEXT_NAMESPACE "FlareShipStatus" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareShipStatus::Construct(const FArguments& InArgs) { TargetShip = InArgs._Ship; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); ChildSlot .VAlign(VAlign_Fill) .HAlign(HAlign_Fill) .Padding(FMargin(8, 8, 32, 8)) [ SNew(SHorizontalBox) // Power icon + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("Propulsion")) .ColorAndOpacity(this, &SFlareShipStatus::GetIconColor, EFlareSubsystem::SYS_Propulsion) ] // RCS icon + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("RCS")) .ColorAndOpacity(this, &SFlareShipStatus::GetIconColor, EFlareSubsystem::SYS_RCS) ] // Weapon icon + SHorizontalBox::Slot() .AutoWidth() [ SAssignNew(WeaponIndicator, SImage) .Image(FFlareStyleSet::GetIcon("Shell")) .ColorAndOpacity(this, &SFlareShipStatus::GetIconColor, EFlareSubsystem::SYS_Weapon) ] // Health + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(60) .VAlign(VAlign_Center) [ SNew(SProgressBar) .Percent(this, &SFlareShipStatus::GetGlobalHealth) .Style(&Theme.ProgressBarStyle) ] ] ]; SetVisibility(EVisibility::Hidden); } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareShipStatus::SetTargetShip(UFlareSimulatedSpacecraft* Target) { TargetShip = Target; if (TargetShip) { SetVisibility(EVisibility::Visible); if (TargetShip->IsMilitary()) { WeaponIndicator->SetVisibility(EVisibility::Visible); } else { WeaponIndicator->SetVisibility(EVisibility::Hidden); } } else { SetVisibility(EVisibility::Hidden); } } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ void SFlareShipStatus::OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent) { SWidget::OnMouseEnter(MyGeometry, MouseEvent); AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager && TargetShip) { FText Info; UFlareSimulatedSpacecraftDamageSystem* DamageSystem = TargetShip->GetDamageSystem(); if (DamageSystem->IsStranded()) { Info = FText::Format(LOCTEXT("ShipStrandedFormat", "{0}This ship is stranded and can't exit the sector !\n"), Info); } if (DamageSystem->IsUncontrollable()) { Info = FText::Format(LOCTEXT("ShipUncontrollableFormat", "{0}This ship is uncontrollable and can't move in the local space !\n"), Info); } if (TargetShip->IsMilitary() && DamageSystem->IsDisarmed()) { Info = FText::Format(LOCTEXT("ShipDisarmedFormat", "{0}This ship is disarmed and unable to fight back !\n"), Info); } for (int32 Index = EFlareSubsystem::SYS_None + 1; Index <= EFlareSubsystem::SYS_Weapon; Index++) { if (Index == EFlareSubsystem::SYS_Weapon && !TargetShip->IsMilitary()) { continue; } Info = FText::Format(LOCTEXT("HealthInfoFormat", "{0}\n{1} : {2}%"), Info, UFlareSimulatedSpacecraftDamageSystem::GetSubsystemName((EFlareSubsystem::Type)Index), FText::AsNumber(FMath::RoundToInt(100 * DamageSystem->GetSubsystemHealth((EFlareSubsystem::Type)Index, false))) ); } MenuManager->ShowTooltip(this, LOCTEXT("Status", "SHIP STATUS"), Info); } } void SFlareShipStatus::OnMouseLeave(const FPointerEvent& MouseEvent) { SWidget::OnMouseLeave(MouseEvent); AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager) { MenuManager->HideTooltip(this); } } TOptional<float> SFlareShipStatus::GetGlobalHealth() const { if (TargetShip) { return TargetShip->GetDamageSystem()->GetGlobalHealth(); } else { return 0; } } FSlateColor SFlareShipStatus::GetIconColor(EFlareSubsystem::Type Type) const { FLinearColor Result = FLinearColor::Black; Result.A = 0.0f; // Ignore stations if (TargetShip && !TargetShip->IsStation()) { bool IsIncapacitated = false; UFlareSimulatedSpacecraftDamageSystem* DamageSystem = TargetShip->GetDamageSystem(); // Only those are used (see above) switch (Type) { case EFlareSubsystem::SYS_Propulsion: IsIncapacitated = DamageSystem->IsStranded(); break; case EFlareSubsystem::SYS_RCS: IsIncapacitated = DamageSystem->IsUncontrollable(); break; case EFlareSubsystem::SYS_Weapon: IsIncapacitated = DamageSystem->IsDisarmed(); break; default: break; } // Show in red when disabled if (IsIncapacitated) { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); Result = Theme.DamageColor; Result.A = 1.0f; } } return Result; } #undef LOCTEXT_NAMESPACE <commit_msg>Make the healh progress bar fill the whole space<commit_after> #include "../../Flare.h" #include "FlareShipStatus.h" #include "../../Player/FlareMenuManager.h" #define LOCTEXT_NAMESPACE "FlareShipStatus" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareShipStatus::Construct(const FArguments& InArgs) { TargetShip = InArgs._Ship; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); ChildSlot .VAlign(VAlign_Fill) .HAlign(HAlign_Fill) .Padding(FMargin(8, 8, 32, 8)) [ SNew(SHorizontalBox) // Power icon + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("Propulsion")) .ColorAndOpacity(this, &SFlareShipStatus::GetIconColor, EFlareSubsystem::SYS_Propulsion) ] // RCS icon + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("RCS")) .ColorAndOpacity(this, &SFlareShipStatus::GetIconColor, EFlareSubsystem::SYS_RCS) ] // Weapon icon + SHorizontalBox::Slot() .AutoWidth() [ SAssignNew(WeaponIndicator, SImage) .Image(FFlareStyleSet::GetIcon("Shell")) .ColorAndOpacity(this, &SFlareShipStatus::GetIconColor, EFlareSubsystem::SYS_Weapon) ] // Health + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(60) .VAlign(VAlign_Center) [ SNew(SProgressBar) .Percent(this, &SFlareShipStatus::GetGlobalHealth) .BorderPadding( FVector2D(0,0)) .Style(&Theme.ProgressBarStyle) ] ] ]; SetVisibility(EVisibility::Hidden); } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareShipStatus::SetTargetShip(UFlareSimulatedSpacecraft* Target) { TargetShip = Target; if (TargetShip) { SetVisibility(EVisibility::Visible); if (TargetShip->IsMilitary()) { WeaponIndicator->SetVisibility(EVisibility::Visible); } else { WeaponIndicator->SetVisibility(EVisibility::Hidden); } } else { SetVisibility(EVisibility::Hidden); } } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ void SFlareShipStatus::OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent) { SWidget::OnMouseEnter(MyGeometry, MouseEvent); AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager && TargetShip) { FText Info; UFlareSimulatedSpacecraftDamageSystem* DamageSystem = TargetShip->GetDamageSystem(); if (DamageSystem->IsStranded()) { Info = FText::Format(LOCTEXT("ShipStrandedFormat", "{0}This ship is stranded and can't exit the sector !\n"), Info); } if (DamageSystem->IsUncontrollable()) { Info = FText::Format(LOCTEXT("ShipUncontrollableFormat", "{0}This ship is uncontrollable and can't move in the local space !\n"), Info); } if (TargetShip->IsMilitary() && DamageSystem->IsDisarmed()) { Info = FText::Format(LOCTEXT("ShipDisarmedFormat", "{0}This ship is disarmed and unable to fight back !\n"), Info); } for (int32 Index = EFlareSubsystem::SYS_None + 1; Index <= EFlareSubsystem::SYS_Weapon; Index++) { if (Index == EFlareSubsystem::SYS_Weapon && !TargetShip->IsMilitary()) { continue; } Info = FText::Format(LOCTEXT("HealthInfoFormat", "{0}\n{1} : {2}%"), Info, UFlareSimulatedSpacecraftDamageSystem::GetSubsystemName((EFlareSubsystem::Type)Index), FText::AsNumber(FMath::RoundToInt(100 * DamageSystem->GetSubsystemHealth((EFlareSubsystem::Type)Index, false))) ); } MenuManager->ShowTooltip(this, LOCTEXT("Status", "SHIP STATUS"), Info); } } void SFlareShipStatus::OnMouseLeave(const FPointerEvent& MouseEvent) { SWidget::OnMouseLeave(MouseEvent); AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager) { MenuManager->HideTooltip(this); } } TOptional<float> SFlareShipStatus::GetGlobalHealth() const { if (TargetShip) { return TargetShip->GetDamageSystem()->GetGlobalHealth(); } else { return 0; } } FSlateColor SFlareShipStatus::GetIconColor(EFlareSubsystem::Type Type) const { FLinearColor Result = FLinearColor::Black; Result.A = 0.0f; // Ignore stations if (TargetShip && !TargetShip->IsStation()) { bool IsIncapacitated = false; UFlareSimulatedSpacecraftDamageSystem* DamageSystem = TargetShip->GetDamageSystem(); // Only those are used (see above) switch (Type) { case EFlareSubsystem::SYS_Propulsion: IsIncapacitated = DamageSystem->IsStranded(); break; case EFlareSubsystem::SYS_RCS: IsIncapacitated = DamageSystem->IsUncontrollable(); break; case EFlareSubsystem::SYS_Weapon: IsIncapacitated = DamageSystem->IsDisarmed(); break; default: break; } // Show in red when disabled if (IsIncapacitated) { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); Result = Theme.DamageColor; Result.A = 1.0f; } } return Result; } #undef LOCTEXT_NAMESPACE <|endoftext|>
<commit_before>/* Copyright (c) 2007 Volker Krause <vkrause@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "messageactions.h" #include "globalsettings.h" #include "kmfolder.h" #include "kmmessage.h" #include "kmreaderwin.h" #include <kaction.h> #include <kactioncollection.h> #include <kdebug.h> #include <klocale.h> #include <qwidget.h> using namespace KMail; MessageActions::MessageActions( KActionCollection *ac, QWidget * parent ) : QObject( parent ), mParent( parent ), mActionCollection( ac ), mCurrentMessage( 0 ), mMessageView( 0 ) { mReplyActionMenu = new KActionMenu( i18n("Message->","&Reply"), "mail_reply", mActionCollection, "message_reply_menu" ); connect( mReplyActionMenu, SIGNAL(activated()), this, SLOT(slotReplyToMsg()) ); mReplyAction = new KAction( i18n("&Reply..."), "mail_reply", Key_R, this, SLOT(slotReplyToMsg()), mActionCollection, "reply" ); mReplyActionMenu->insert( mReplyAction ); mReplyAuthorAction = new KAction( i18n("Reply to A&uthor..."), "mail_reply", SHIFT+Key_A, this, SLOT(slotReplyAuthorToMsg()), mActionCollection, "reply_author" ); mReplyActionMenu->insert( mReplyAuthorAction ); mReplyAllAction = new KAction( i18n("Reply to &All..."), "mail_replyall", Key_A, this, SLOT(slotReplyAllToMsg()), mActionCollection, "reply_all" ); mReplyActionMenu->insert( mReplyAllAction ); mReplyListAction = new KAction( i18n("Reply to Mailing-&List..."), "mail_replylist", Key_L, this, SLOT(slotReplyListToMsg()), mActionCollection, "reply_list" ); mReplyActionMenu->insert( mReplyListAction ); mNoQuoteReplyAction = new KAction( i18n("Reply Without &Quote..."), SHIFT+Key_R, this, SLOT(slotNoQuoteReplyToMsg()), mActionCollection, "noquotereply" ); mCreateTodoAction = new KAction( i18n("Create Task..."), "mail_todo", 0, this, SLOT(slotCreateTodo()), mActionCollection, "create_todo" ); mStatusMenu = new KActionMenu ( i18n( "Mar&k Message" ), mActionCollection, "set_status" ); mStatusMenu->insert(new KAction(KGuiItem(i18n("Mark Message as &Read"), "kmmsgread", i18n("Mark selected messages as read")), 0, this, SLOT(slotSetMsgStatusRead()), mActionCollection, "status_read")); mStatusMenu->insert(new KAction(KGuiItem(i18n("Mark Message as &New"), "kmmsgnew", i18n("Mark selected messages as new")), 0, this, SLOT(slotSetMsgStatusNew()), mActionCollection, "status_new" )); mStatusMenu->insert(new KAction(KGuiItem(i18n("Mark Message as &Unread"), "kmmsgunseen", i18n("Mark selected messages as unread")), 0, this, SLOT(slotSetMsgStatusUnread()), mActionCollection, "status_unread")); mStatusMenu->insert( new KActionSeparator( this ) ); mToggleFlagAction = new KToggleAction(i18n("Mark Message as &Important"), "mail_flag", 0, this, SLOT(slotSetMsgStatusFlag()), mActionCollection, "status_flag"); mToggleFlagAction->setCheckedState( i18n("Remove &Important Message Mark") ); mStatusMenu->insert( mToggleFlagAction ); mToggleTodoAction = new KToggleAction(i18n("Mark Message as &Action Item"), "mail_todo", 0, this, SLOT(slotSetMsgStatusTodo()), mActionCollection, "status_todo"); mToggleTodoAction->setCheckedState( i18n("Remove &Action Item Message Mark") ); mStatusMenu->insert( mToggleTodoAction ); mEditAction = new KAction( i18n("&Edit Message"), "edit", Key_T, this, SLOT(editCurrentMessage()), mActionCollection, "edit" ); mEditAction->plugAccel( mActionCollection->kaccel() ); updateActions(); } void MessageActions::setCurrentMessage(KMMessage * msg) { mCurrentMessage = msg; if ( !msg ) { mSelectedSernums.clear(); mVisibleSernums.clear(); } updateActions(); } void MessageActions::setSelectedSernums(const QValueList< Q_UINT32 > & sernums) { mSelectedSernums = sernums; updateActions(); } void MessageActions::setSelectedVisibleSernums(const QValueList< Q_UINT32 > & sernums) { mVisibleSernums = sernums; updateActions(); } void MessageActions::updateActions() { const bool singleMsg = (mCurrentMessage != 0 && mSelectedSernums.count() <= 1); const bool multiVisible = mVisibleSernums.count() > 0 || mCurrentMessage; const bool flagsAvailable = GlobalSettings::self()->allowLocalFlags() || !((mCurrentMessage && mCurrentMessage->parent()) ? mCurrentMessage->parent()->isReadOnly() : true); mCreateTodoAction->setEnabled( singleMsg ); mReplyActionMenu->setEnabled( singleMsg ); mReplyAction->setEnabled( singleMsg ); mNoQuoteReplyAction->setEnabled( singleMsg ); mReplyAuthorAction->setEnabled( singleMsg ); mReplyAllAction->setEnabled( singleMsg ); mReplyListAction->setEnabled( singleMsg ); mNoQuoteReplyAction->setEnabled( singleMsg ); mStatusMenu->setEnabled( multiVisible ); mToggleFlagAction->setEnabled( flagsAvailable ); mToggleTodoAction->setEnabled( flagsAvailable ); if ( mCurrentMessage ) { mToggleTodoAction->setChecked( mCurrentMessage->isTodo() ); mToggleFlagAction->setChecked( mCurrentMessage->isImportant() ); } mEditAction->setEnabled( singleMsg ); } void MessageActions::slotCreateTodo() { if ( !mCurrentMessage ) return; KMCommand *command = new CreateTodoCommand( mParent, mCurrentMessage ); command->start(); } void MessageActions::setMessageView(KMReaderWin * msgView) { mMessageView = msgView; } void MessageActions::slotReplyToMsg() { replyCommand<KMReplyToCommand>(); } void MessageActions::slotReplyAuthorToMsg() { replyCommand<KMReplyAuthorCommand>(); } void MessageActions::slotReplyListToMsg() { replyCommand<KMReplyListCommand>(); } void MessageActions::slotReplyAllToMsg() { replyCommand<KMReplyToAllCommand>(); } void MessageActions::slotNoQuoteReplyToMsg() { if ( !mCurrentMessage ) return; KMCommand *command = new KMNoQuoteReplyToCommand( mParent, mCurrentMessage ); command->start(); } void MessageActions::slotSetMsgStatusNew() { setMessageStatus( KMMsgStatusNew ); } void MessageActions::slotSetMsgStatusUnread() { setMessageStatus( KMMsgStatusUnread ); } void MessageActions::slotSetMsgStatusRead() { setMessageStatus( KMMsgStatusRead ); } void MessageActions::slotSetMsgStatusFlag() { setMessageStatus( KMMsgStatusFlag, true ); } void MessageActions::slotSetMsgStatusTodo() { setMessageStatus( KMMsgStatusTodo, true ); } void MessageActions::setMessageStatus( KMMsgStatus status, bool toggle ) { QValueList<Q_UINT32> serNums = mVisibleSernums; if ( serNums.isEmpty() && mCurrentMessage ) serNums.append( mCurrentMessage->getMsgSerNum() ); if ( serNums.empty() ) return; KMCommand *command = new KMSetStatusCommand( status, serNums, toggle ); command->start(); } void MessageActions::editCurrentMessage() { if ( !mCurrentMessage ) return; KMCommand *command = 0; KMFolder *folder = mCurrentMessage->parent(); // edit, unlike send again, removes the message from the folder // we only want that for templates and drafts folders if ( folder && ( kmkernel->folderIsDraftOrOutbox( folder ) || kmkernel->folderIsTemplates( folder ) ) ) command = new KMEditMsgCommand( mParent, mCurrentMessage ); else command = new KMResendMessageCommand( mParent, mCurrentMessage ); command->start(); } #include "messageactions.moc" <commit_msg>Give a better hint what this action does. kolab/issue2166<commit_after>/* Copyright (c) 2007 Volker Krause <vkrause@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "messageactions.h" #include "globalsettings.h" #include "kmfolder.h" #include "kmmessage.h" #include "kmreaderwin.h" #include <kaction.h> #include <kactioncollection.h> #include <kdebug.h> #include <klocale.h> #include <qwidget.h> using namespace KMail; MessageActions::MessageActions( KActionCollection *ac, QWidget * parent ) : QObject( parent ), mParent( parent ), mActionCollection( ac ), mCurrentMessage( 0 ), mMessageView( 0 ) { mReplyActionMenu = new KActionMenu( i18n("Message->","&Reply"), "mail_reply", mActionCollection, "message_reply_menu" ); connect( mReplyActionMenu, SIGNAL(activated()), this, SLOT(slotReplyToMsg()) ); mReplyAction = new KAction( i18n("&Reply..."), "mail_reply", Key_R, this, SLOT(slotReplyToMsg()), mActionCollection, "reply" ); mReplyActionMenu->insert( mReplyAction ); mReplyAuthorAction = new KAction( i18n("Reply to A&uthor..."), "mail_reply", SHIFT+Key_A, this, SLOT(slotReplyAuthorToMsg()), mActionCollection, "reply_author" ); mReplyActionMenu->insert( mReplyAuthorAction ); mReplyAllAction = new KAction( i18n("Reply to &All..."), "mail_replyall", Key_A, this, SLOT(slotReplyAllToMsg()), mActionCollection, "reply_all" ); mReplyActionMenu->insert( mReplyAllAction ); mReplyListAction = new KAction( i18n("Reply to Mailing-&List..."), "mail_replylist", Key_L, this, SLOT(slotReplyListToMsg()), mActionCollection, "reply_list" ); mReplyActionMenu->insert( mReplyListAction ); mNoQuoteReplyAction = new KAction( i18n("Reply Without &Quote..."), SHIFT+Key_R, this, SLOT(slotNoQuoteReplyToMsg()), mActionCollection, "noquotereply" ); mCreateTodoAction = new KAction( i18n("Create Task/Reminder..."), "mail_todo", 0, this, SLOT(slotCreateTodo()), mActionCollection, "create_todo" ); mStatusMenu = new KActionMenu ( i18n( "Mar&k Message" ), mActionCollection, "set_status" ); mStatusMenu->insert(new KAction(KGuiItem(i18n("Mark Message as &Read"), "kmmsgread", i18n("Mark selected messages as read")), 0, this, SLOT(slotSetMsgStatusRead()), mActionCollection, "status_read")); mStatusMenu->insert(new KAction(KGuiItem(i18n("Mark Message as &New"), "kmmsgnew", i18n("Mark selected messages as new")), 0, this, SLOT(slotSetMsgStatusNew()), mActionCollection, "status_new" )); mStatusMenu->insert(new KAction(KGuiItem(i18n("Mark Message as &Unread"), "kmmsgunseen", i18n("Mark selected messages as unread")), 0, this, SLOT(slotSetMsgStatusUnread()), mActionCollection, "status_unread")); mStatusMenu->insert( new KActionSeparator( this ) ); mToggleFlagAction = new KToggleAction(i18n("Mark Message as &Important"), "mail_flag", 0, this, SLOT(slotSetMsgStatusFlag()), mActionCollection, "status_flag"); mToggleFlagAction->setCheckedState( i18n("Remove &Important Message Mark") ); mStatusMenu->insert( mToggleFlagAction ); mToggleTodoAction = new KToggleAction(i18n("Mark Message as &Action Item"), "mail_todo", 0, this, SLOT(slotSetMsgStatusTodo()), mActionCollection, "status_todo"); mToggleTodoAction->setCheckedState( i18n("Remove &Action Item Message Mark") ); mStatusMenu->insert( mToggleTodoAction ); mEditAction = new KAction( i18n("&Edit Message"), "edit", Key_T, this, SLOT(editCurrentMessage()), mActionCollection, "edit" ); mEditAction->plugAccel( mActionCollection->kaccel() ); updateActions(); } void MessageActions::setCurrentMessage(KMMessage * msg) { mCurrentMessage = msg; if ( !msg ) { mSelectedSernums.clear(); mVisibleSernums.clear(); } updateActions(); } void MessageActions::setSelectedSernums(const QValueList< Q_UINT32 > & sernums) { mSelectedSernums = sernums; updateActions(); } void MessageActions::setSelectedVisibleSernums(const QValueList< Q_UINT32 > & sernums) { mVisibleSernums = sernums; updateActions(); } void MessageActions::updateActions() { const bool singleMsg = (mCurrentMessage != 0 && mSelectedSernums.count() <= 1); const bool multiVisible = mVisibleSernums.count() > 0 || mCurrentMessage; const bool flagsAvailable = GlobalSettings::self()->allowLocalFlags() || !((mCurrentMessage && mCurrentMessage->parent()) ? mCurrentMessage->parent()->isReadOnly() : true); mCreateTodoAction->setEnabled( singleMsg ); mReplyActionMenu->setEnabled( singleMsg ); mReplyAction->setEnabled( singleMsg ); mNoQuoteReplyAction->setEnabled( singleMsg ); mReplyAuthorAction->setEnabled( singleMsg ); mReplyAllAction->setEnabled( singleMsg ); mReplyListAction->setEnabled( singleMsg ); mNoQuoteReplyAction->setEnabled( singleMsg ); mStatusMenu->setEnabled( multiVisible ); mToggleFlagAction->setEnabled( flagsAvailable ); mToggleTodoAction->setEnabled( flagsAvailable ); if ( mCurrentMessage ) { mToggleTodoAction->setChecked( mCurrentMessage->isTodo() ); mToggleFlagAction->setChecked( mCurrentMessage->isImportant() ); } mEditAction->setEnabled( singleMsg ); } void MessageActions::slotCreateTodo() { if ( !mCurrentMessage ) return; KMCommand *command = new CreateTodoCommand( mParent, mCurrentMessage ); command->start(); } void MessageActions::setMessageView(KMReaderWin * msgView) { mMessageView = msgView; } void MessageActions::slotReplyToMsg() { replyCommand<KMReplyToCommand>(); } void MessageActions::slotReplyAuthorToMsg() { replyCommand<KMReplyAuthorCommand>(); } void MessageActions::slotReplyListToMsg() { replyCommand<KMReplyListCommand>(); } void MessageActions::slotReplyAllToMsg() { replyCommand<KMReplyToAllCommand>(); } void MessageActions::slotNoQuoteReplyToMsg() { if ( !mCurrentMessage ) return; KMCommand *command = new KMNoQuoteReplyToCommand( mParent, mCurrentMessage ); command->start(); } void MessageActions::slotSetMsgStatusNew() { setMessageStatus( KMMsgStatusNew ); } void MessageActions::slotSetMsgStatusUnread() { setMessageStatus( KMMsgStatusUnread ); } void MessageActions::slotSetMsgStatusRead() { setMessageStatus( KMMsgStatusRead ); } void MessageActions::slotSetMsgStatusFlag() { setMessageStatus( KMMsgStatusFlag, true ); } void MessageActions::slotSetMsgStatusTodo() { setMessageStatus( KMMsgStatusTodo, true ); } void MessageActions::setMessageStatus( KMMsgStatus status, bool toggle ) { QValueList<Q_UINT32> serNums = mVisibleSernums; if ( serNums.isEmpty() && mCurrentMessage ) serNums.append( mCurrentMessage->getMsgSerNum() ); if ( serNums.empty() ) return; KMCommand *command = new KMSetStatusCommand( status, serNums, toggle ); command->start(); } void MessageActions::editCurrentMessage() { if ( !mCurrentMessage ) return; KMCommand *command = 0; KMFolder *folder = mCurrentMessage->parent(); // edit, unlike send again, removes the message from the folder // we only want that for templates and drafts folders if ( folder && ( kmkernel->folderIsDraftOrOutbox( folder ) || kmkernel->folderIsTemplates( folder ) ) ) command = new KMEditMsgCommand( mParent, mCurrentMessage ); else command = new KMResendMessageCommand( mParent, mCurrentMessage ); command->start(); } #include "messageactions.moc" <|endoftext|>
<commit_before>/* * galleryenlargeshrinkplugin.cpp * * Copyright (C) 2012 Igalia, S.L. * Author: Antia Puentes <apuentes@igalia.com> * * This file is part of the Gallery Enlarge/Shrink Plugin. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see http://www.gnu.org/licenses/ * */ #include "galleryenlargeshrinkplugin.h" #include "galleryenlargeshrinkplugin_p.h" #include "galleryenlargeshrinkwidget.h" #include <galleryedituiprovider.h> #include <MLibrary> #include <MApplication> #include <MBanner> #include <MMessageBox> #include <MLabel> #include <QGraphicsSceneMouseEvent> #include <QDesktopServices> #include <QUrl> #include <QTextOption> #include <QuillImageFilter> static const float EFFECT_FORCE = 1.0; static const int TAP_DISTANCE = 20; static const int PORTRAIT_HEIGHT = 224; static const int LANDSCAPE_HEIGHT = 112; static const int INFOBANNER_TIMEOUT = 2 * 1000; static const int IMAGE_MAX_HEIGHT = 512; static const int IMAGE_MAX_WIDTH = 512; M_LIBRARY GalleryEnlargeShrinkPluginPrivate::GalleryEnlargeShrinkPluginPrivate() : m_focusPosition(), m_validImage(true) { } GalleryEnlargeShrinkPluginPrivate::~GalleryEnlargeShrinkPluginPrivate() { } GalleryEnlargeShrinkPlugin::GalleryEnlargeShrinkPlugin(QObject* parent) : GalleryEditPlugin(parent), d_ptr(new GalleryEnlargeShrinkPluginPrivate()) { } GalleryEnlargeShrinkPlugin::~GalleryEnlargeShrinkPlugin() { delete d_ptr; } QString GalleryEnlargeShrinkPlugin::name() const { return QString("Enlarge - Shrink"); } QString GalleryEnlargeShrinkPlugin::iconID() const { return QString("icon-m-image-edit-enlarge-shrink"); } bool GalleryEnlargeShrinkPlugin::containsUi() const { return true; } bool GalleryEnlargeShrinkPlugin::zoomingAllowed() const { return true; } QGraphicsWidget* GalleryEnlargeShrinkPlugin::createToolBarWidget(QGraphicsItem* parent) { GalleryEnlargeShrinkWidget* widget = new GalleryEnlargeShrinkWidget(parent); connect(widget, SIGNAL(aboutLinkActivated(QString)), this, SLOT(onAboutLinkActivated(QString))); return widget; } const QSize GalleryEnlargeShrinkPlugin::toolBarWidgetSize(const M::Orientation& orientation) const { QSize size = GalleryEditPlugin::toolBarWidgetSize(orientation); if (M::Portrait == orientation) { size.setHeight(PORTRAIT_HEIGHT); } else { size.setHeight(LANDSCAPE_HEIGHT); } return size; } bool GalleryEnlargeShrinkPlugin::receiveMouseEvent(QGraphicsSceneMouseEvent *event) { if (event && event->type() == QEvent::GraphicsSceneMouseRelease && event->button() == Qt::LeftButton && (event->scenePos() - event->buttonDownScenePos(Qt::LeftButton)).manhattanLength() < TAP_DISTANCE) { Q_D(GalleryEnlargeShrinkPlugin); if (d->m_validImage) { d->m_focusPosition = event->pos().toPoint(); performEditOperation(); return true; } else { showInfoBanner("Plugin disabled for this image size"); } } return false; } void GalleryEnlargeShrinkPlugin::activate() { if (editUiProvider()) { Q_D(GalleryEnlargeShrinkPlugin); d->m_validImage = editUiProvider()->fullImageSize().height() <= IMAGE_MAX_HEIGHT && editUiProvider()->fullImageSize().width() <= IMAGE_MAX_WIDTH; if (d->m_validImage) { showInfoBanner("Tap on an area to keep it focused"); } else { showMessageBox("Enlarge Shrink plugin limitations", "Gallery Enlarge Shrink plugin is currently limited to " "small images (512x512)<br />" "For a given image:" "<ol>" "<li>Scale it or crop it</li>" "<li>Save it with a different name</li>" "<li>Apply the filter to the new one</li>" "</ol>"); GalleryEnlargeShrinkWidget* widget = static_cast<GalleryEnlargeShrinkWidget*>(toolBarWidget()); widget->enableInput(d->m_validImage); } } } void GalleryEnlargeShrinkPlugin::performEditOperation() { if (editUiProvider()) { Q_D(GalleryEnlargeShrinkPlugin); QHash<QuillImageFilter::QuillFilterOption, QVariant> optionHash; const QPoint imagePosition = editUiProvider()->convertScreenCoordToImageCoord(d->m_focusPosition); if (imagePosition != QPoint(-1, -1)) { GalleryEnlargeShrinkWidget* widget = static_cast<GalleryEnlargeShrinkWidget*>(toolBarWidget()); optionHash.insert(QuillImageFilter::Center, QVariant(imagePosition)); double radius = widget->radius() / 100.0 * qMin(editUiProvider()->fullImageSize().width(), editUiProvider()->fullImageSize().height()); optionHash.insert(QuillImageFilter::Radius, radius); // To enlarge (punch effect) "force" must be positive // To shrink (pinch effect) "force" must be negative optionHash.insert("force", EFFECT_FORCE * (widget->shrink()? -1 : 1)); editUiProvider()->runEditFilter("com.igalia.enlargeshrink", optionHash); emit editOperationPerformed(); } } } MMessageBox* GalleryEnlargeShrinkPlugin::showMessageBox(const QString& title, const QString& text) const { MMessageBox* messageBox = new MMessageBox(title, ""); MLabel* innerLabel = new MLabel(messageBox); innerLabel->setWordWrap(true); innerLabel->setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); innerLabel->setStyleName("CommonQueryText"); innerLabel->setText(text); innerLabel->setAlignment(Qt::AlignHCenter); messageBox->setCentralWidget(innerLabel); connect(this, SIGNAL(deactivated()), messageBox, SLOT(disappear())); messageBox->appear(MSceneWindow::DestroyWhenDone); return messageBox; } MBanner* GalleryEnlargeShrinkPlugin::showInfoBanner(const QString& title) const { MBanner *infoBanner = new MBanner; infoBanner->setStyleName(MBannerType::InformationBanner); infoBanner->setTitle(title); infoBanner->model()->setDisappearTimeout(INFOBANNER_TIMEOUT); connect(this, SIGNAL(deactivated()), infoBanner, SLOT(disappear())); infoBanner->appear(MApplication::activeWindow(), MSceneWindow::DestroyWhenDone); return infoBanner; } void GalleryEnlargeShrinkPlugin::onAboutLinkActivated(const QString &link) { Q_UNUSED(link) if (link.toLower().startsWith("http") || link.toLower().startsWith("mailto")) { QDesktopServices::openUrl(QUrl(link)); } else { showMessageBox("About Enlarge Shrink plugin", "Copyright (c) 2012 Igalia S.L." "<br /><br />" "<a href=\"mailto:apuentes@igalia.com\">apuentes@igalia.com</a> | " "<a href=\"http://www.igalia.com\">www.igalia.com</a>" "<br /><br />" "This library is free software; you can redistribute it and/or " "modify it under the terms of the GNU Lesser General Public License " "as published by the Free Software Foundation; version 2.1 of " "the License, or (at your option) any later version."); } } Q_EXPORT_PLUGIN2(galleryenlargeshrinkplugin, GalleryEnlargeShrinkPlugin) <commit_msg>GalleryEnlargeShrinkPlugin: remove unneeded Q_UNUSED macro<commit_after>/* * galleryenlargeshrinkplugin.cpp * * Copyright (C) 2012 Igalia, S.L. * Author: Antia Puentes <apuentes@igalia.com> * * This file is part of the Gallery Enlarge/Shrink Plugin. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see http://www.gnu.org/licenses/ * */ #include "galleryenlargeshrinkplugin.h" #include "galleryenlargeshrinkplugin_p.h" #include "galleryenlargeshrinkwidget.h" #include <galleryedituiprovider.h> #include <MLibrary> #include <MApplication> #include <MBanner> #include <MMessageBox> #include <MLabel> #include <QGraphicsSceneMouseEvent> #include <QDesktopServices> #include <QUrl> #include <QTextOption> #include <QuillImageFilter> static const float EFFECT_FORCE = 1.0; static const int TAP_DISTANCE = 20; static const int PORTRAIT_HEIGHT = 224; static const int LANDSCAPE_HEIGHT = 112; static const int INFOBANNER_TIMEOUT = 2 * 1000; static const int IMAGE_MAX_HEIGHT = 512; static const int IMAGE_MAX_WIDTH = 512; M_LIBRARY GalleryEnlargeShrinkPluginPrivate::GalleryEnlargeShrinkPluginPrivate() : m_focusPosition(), m_validImage(true) { } GalleryEnlargeShrinkPluginPrivate::~GalleryEnlargeShrinkPluginPrivate() { } GalleryEnlargeShrinkPlugin::GalleryEnlargeShrinkPlugin(QObject* parent) : GalleryEditPlugin(parent), d_ptr(new GalleryEnlargeShrinkPluginPrivate()) { } GalleryEnlargeShrinkPlugin::~GalleryEnlargeShrinkPlugin() { delete d_ptr; } QString GalleryEnlargeShrinkPlugin::name() const { return QString("Enlarge - Shrink"); } QString GalleryEnlargeShrinkPlugin::iconID() const { return QString("icon-m-image-edit-enlarge-shrink"); } bool GalleryEnlargeShrinkPlugin::containsUi() const { return true; } bool GalleryEnlargeShrinkPlugin::zoomingAllowed() const { return true; } QGraphicsWidget* GalleryEnlargeShrinkPlugin::createToolBarWidget(QGraphicsItem* parent) { GalleryEnlargeShrinkWidget* widget = new GalleryEnlargeShrinkWidget(parent); connect(widget, SIGNAL(aboutLinkActivated(QString)), this, SLOT(onAboutLinkActivated(QString))); return widget; } const QSize GalleryEnlargeShrinkPlugin::toolBarWidgetSize(const M::Orientation& orientation) const { QSize size = GalleryEditPlugin::toolBarWidgetSize(orientation); if (M::Portrait == orientation) { size.setHeight(PORTRAIT_HEIGHT); } else { size.setHeight(LANDSCAPE_HEIGHT); } return size; } bool GalleryEnlargeShrinkPlugin::receiveMouseEvent(QGraphicsSceneMouseEvent *event) { if (event && event->type() == QEvent::GraphicsSceneMouseRelease && event->button() == Qt::LeftButton && (event->scenePos() - event->buttonDownScenePos(Qt::LeftButton)).manhattanLength() < TAP_DISTANCE) { Q_D(GalleryEnlargeShrinkPlugin); if (d->m_validImage) { d->m_focusPosition = event->pos().toPoint(); performEditOperation(); return true; } else { showInfoBanner("Plugin disabled for this image size"); } } return false; } void GalleryEnlargeShrinkPlugin::activate() { if (editUiProvider()) { Q_D(GalleryEnlargeShrinkPlugin); d->m_validImage = editUiProvider()->fullImageSize().height() <= IMAGE_MAX_HEIGHT && editUiProvider()->fullImageSize().width() <= IMAGE_MAX_WIDTH; if (d->m_validImage) { showInfoBanner("Tap on an area to keep it focused"); } else { showMessageBox("Enlarge Shrink plugin limitations", "Gallery Enlarge Shrink plugin is currently limited to " "small images (512x512)<br />" "For a given image:" "<ol>" "<li>Scale it or crop it</li>" "<li>Save it with a different name</li>" "<li>Apply the filter to the new one</li>" "</ol>"); GalleryEnlargeShrinkWidget* widget = static_cast<GalleryEnlargeShrinkWidget*>(toolBarWidget()); widget->enableInput(d->m_validImage); } } } void GalleryEnlargeShrinkPlugin::performEditOperation() { if (editUiProvider()) { Q_D(GalleryEnlargeShrinkPlugin); QHash<QuillImageFilter::QuillFilterOption, QVariant> optionHash; const QPoint imagePosition = editUiProvider()->convertScreenCoordToImageCoord(d->m_focusPosition); if (imagePosition != QPoint(-1, -1)) { GalleryEnlargeShrinkWidget* widget = static_cast<GalleryEnlargeShrinkWidget*>(toolBarWidget()); optionHash.insert(QuillImageFilter::Center, QVariant(imagePosition)); double radius = widget->radius() / 100.0 * qMin(editUiProvider()->fullImageSize().width(), editUiProvider()->fullImageSize().height()); optionHash.insert(QuillImageFilter::Radius, radius); // To enlarge (punch effect) "force" must be positive // To shrink (pinch effect) "force" must be negative optionHash.insert("force", EFFECT_FORCE * (widget->shrink()? -1 : 1)); editUiProvider()->runEditFilter("com.igalia.enlargeshrink", optionHash); emit editOperationPerformed(); } } } MMessageBox* GalleryEnlargeShrinkPlugin::showMessageBox(const QString& title, const QString& text) const { MMessageBox* messageBox = new MMessageBox(title, ""); MLabel* innerLabel = new MLabel(messageBox); innerLabel->setWordWrap(true); innerLabel->setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); innerLabel->setStyleName("CommonQueryText"); innerLabel->setText(text); innerLabel->setAlignment(Qt::AlignHCenter); messageBox->setCentralWidget(innerLabel); connect(this, SIGNAL(deactivated()), messageBox, SLOT(disappear())); messageBox->appear(MSceneWindow::DestroyWhenDone); return messageBox; } MBanner* GalleryEnlargeShrinkPlugin::showInfoBanner(const QString& title) const { MBanner *infoBanner = new MBanner; infoBanner->setStyleName(MBannerType::InformationBanner); infoBanner->setTitle(title); infoBanner->model()->setDisappearTimeout(INFOBANNER_TIMEOUT); connect(this, SIGNAL(deactivated()), infoBanner, SLOT(disappear())); infoBanner->appear(MApplication::activeWindow(), MSceneWindow::DestroyWhenDone); return infoBanner; } void GalleryEnlargeShrinkPlugin::onAboutLinkActivated(const QString &link) { if (link.toLower().startsWith("http") || link.toLower().startsWith("mailto")) { QDesktopServices::openUrl(QUrl(link)); } else { showMessageBox("About Enlarge Shrink plugin", "Copyright (c) 2012 Igalia S.L." "<br /><br />" "<a href=\"mailto:apuentes@igalia.com\">apuentes@igalia.com</a> | " "<a href=\"http://www.igalia.com\">www.igalia.com</a>" "<br /><br />" "This library is free software; you can redistribute it and/or " "modify it under the terms of the GNU Lesser General Public License " "as published by the Free Software Foundation; version 2.1 of " "the License, or (at your option) any later version."); } } Q_EXPORT_PLUGIN2(galleryenlargeshrinkplugin, GalleryEnlargeShrinkPlugin) <|endoftext|>
<commit_before>// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Alexander Chemeris <Alexander DOT Chemeris AT SIPez DOT com> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <sipxunit/TestUtilities.h> #include <mp/MpOutputDeviceManager.h> #include <mp/MpAudioBuf.h> #include <mp/MpSineWaveGeneratorDeviceDriver.h> #include <os/OsTask.h> #include <os/OsEvent.h> #define TEST_SAMPLES_PER_FRAME_SIZE 80 #define BUFFER_NUM 500 #define TEST_SAMPLES_PER_SECOND 8000 #define TEST_SAMPLE_DATA_SIZE (TEST_SAMPLES_PER_SECOND*1) #define TEST_SAMPLE_DATA_MAGNITUDE 32000 #define TEST_SAMPLE_DATA_PERIOD (1000000/60) //in microseconds 60 Hz #define CREATE_TEST_RUNS_NUMBER 3 #define ENABLE_DISABLE_TEST_RUNS_NUMBER 5 #define ENABLE_DISABLE_FAST_TEST_RUNS_NUMBER 10 #define DIRECT_WRITE_TEST_RUNS_NUMBER 3 #define TICKER_TEST_WRITE_RUNS_NUMBER 3 #undef USE_TEST_DRIVER #ifdef USE_TEST_DRIVER // USE_TEST_DRIVER [ #include <mp/MpodBufferRecorder.h> #define OUTPUT_DRIVER MpodBufferRecorder #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "default", TEST_SAMPLE_DATA_SIZE*1000/TEST_SAMPLES_PER_SECOND #elif defined(WIN32) // USE_TEST_DRIVER ][ WIN32 #include <mp/MpodWinMM.h> #define OUTPUT_DRIVER MpodWinMM #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS MpodWinMM::getDefaultDeviceName() #elif defined(__pingtel_on_posix__) // WIN32 ][ __pingtel_on_posix__ #include <mp/MpodOss.h> #define OUTPUT_DRIVER MpodOss #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "/dev/dsp" #else // __pingtel_on_posix__ ] #error Unknown platform! #endif //static MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE]; //static UtlBoolean sampleDataInitialized=FALSE; static void calculateSampleData(int frequency, MpAudioSample sampleData[], int sampleDataSz, int samplesPerFrame, int samplesPerSecond) { for (int i=0; i<sampleDataSz; i++) { sampleData[i] = MpSineWaveGeneratorDeviceDriver::calculateSample(0, TEST_SAMPLE_DATA_MAGNITUDE, 1000000 / frequency, i, samplesPerFrame, samplesPerSecond); } } /** * Unittest for MpOutputDeviceDriver */ class MpOutputDeviceDriverTest : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(MpOutputDeviceDriverTest); CPPUNIT_TEST(testCreate); CPPUNIT_TEST(testEnableDisable); CPPUNIT_TEST(testEnableDisableFast); CPPUNIT_TEST(testDirectWrite); CPPUNIT_TEST(testTickerNotification); CPPUNIT_TEST_SUITE_END(); public: void setUp() { // Create pool for data buffers mpPool = new MpBufPool(TEST_SAMPLES_PER_FRAME_SIZE * sizeof(MpAudioSample) + MpArrayBuf::getHeaderSize(), BUFFER_NUM); CPPUNIT_ASSERT(mpPool != NULL); // Create pool for buffer headers mpHeadersPool = new MpBufPool(sizeof(MpAudioBuf), BUFFER_NUM); CPPUNIT_ASSERT(mpHeadersPool != NULL); // Set mpHeadersPool as default pool for audio and data pools. MpAudioBuf::smpDefaultPool = mpHeadersPool; MpDataBuf::smpDefaultPool = mpHeadersPool; } void tearDown() { if (mpPool != NULL) { delete mpPool; } if (mpHeadersPool != NULL) { delete mpHeadersPool; } } void testCreate() { for (int i=0; i<CREATE_TEST_RUNS_NUMBER; i++) { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testEnableDisable() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<ENABLE_DISABLE_TEST_RUNS_NUMBER; i++) { driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); CPPUNIT_ASSERT(driver.isEnabled()); OsTask::delay(50); driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testEnableDisableFast() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<ENABLE_DISABLE_FAST_TEST_RUNS_NUMBER; i++) { driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); CPPUNIT_ASSERT(driver.isEnabled()); driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testDirectWrite() { MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE]; calculateSampleData(440, sampleData, TEST_SAMPLE_DATA_SIZE, 80, 8000); OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<DIRECT_WRITE_TEST_RUNS_NUMBER; i++) { MpFrameTime frameTime=0; driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); CPPUNIT_ASSERT(driver.isEnabled()); // Write some data to device. for (int frame=0; frame<TEST_SAMPLE_DATA_SIZE/TEST_SAMPLES_PER_FRAME_SIZE; frame++) { OsTask::delay(1000*TEST_SAMPLES_PER_FRAME_SIZE/TEST_SAMPLES_PER_SECOND); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.pushFrame(TEST_SAMPLES_PER_FRAME_SIZE, sampleData + TEST_SAMPLES_PER_FRAME_SIZE*frame, frameTime)); frameTime += TEST_SAMPLES_PER_FRAME_SIZE*1000/TEST_SAMPLES_PER_SECOND; } driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testTickerNotification() { OsEvent notificationEvent; int sampleRates[]={8000, 16000, 32000, 48000}; int numRates = sizeof(sampleRates)/sizeof(int); int frequencies[] = {1000, 2000, 4000, 8000, 16000, 20000, 24000, 28000}; int numFreqs = sizeof(frequencies)/sizeof(int); int rateIndex = 0; int sampleDataSz = sampleRates[rateIndex]; MpAudioSample* sampleData = new MpAudioSample[sampleDataSz]; OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<numFreqs; i++) { printf("Frequency: %d (Hz) Sample rate: %d/sec.\n", frequencies[i], sampleRates[rateIndex]); calculateSampleData(frequencies[i], sampleData, sampleDataSz, sampleRates[rateIndex]/100, sampleRates[rateIndex]); MpFrameTime frameTime=0; driver.enableDevice(sampleRates[rateIndex]/100, sampleRates[rateIndex], 0); CPPUNIT_ASSERT(driver.isEnabled()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.setTickerNotification(&notificationEvent)); // Write some data to device. for (int frame=0; frame<100; frame++) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, notificationEvent.wait(OsTime(1000))); notificationEvent.reset(); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.pushFrame(sampleRates[rateIndex]/100, sampleData + sampleRates[rateIndex]/100*frame, frameTime)); frameTime += sampleRates[rateIndex]/100*1000/sampleRates[rateIndex]; } CPPUNIT_ASSERT(driver.setTickerNotification(NULL) == OS_SUCCESS); driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } delete[] sampleData; } protected: MpBufPool *mpPool; ///< Pool for data buffers MpBufPool *mpHeadersPool; ///< Pool for buffers headers }; CPPUNIT_TEST_SUITE_REGISTRATION(MpOutputDeviceDriverTest); <commit_msg>In addition to 8KHz, loop and test other sample rates in MpOutputDeviceDriverTest::testTickerNotification.<commit_after>// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Alexander Chemeris <Alexander DOT Chemeris AT SIPez DOT com> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <sipxunit/TestUtilities.h> #include <mp/MpOutputDeviceManager.h> #include <mp/MpAudioBuf.h> #include <mp/MpSineWaveGeneratorDeviceDriver.h> #include <os/OsTask.h> #include <os/OsEvent.h> #define TEST_SAMPLES_PER_FRAME_SIZE 80 #define BUFFER_NUM 500 #define TEST_SAMPLES_PER_SECOND 8000 #define TEST_SAMPLE_DATA_SIZE (TEST_SAMPLES_PER_SECOND*1) #define TEST_SAMPLE_DATA_MAGNITUDE 32000 #define TEST_SAMPLE_DATA_PERIOD (1000000/60) //in microseconds 60 Hz #define CREATE_TEST_RUNS_NUMBER 3 #define ENABLE_DISABLE_TEST_RUNS_NUMBER 5 #define ENABLE_DISABLE_FAST_TEST_RUNS_NUMBER 10 #define DIRECT_WRITE_TEST_RUNS_NUMBER 3 #define TICKER_TEST_WRITE_RUNS_NUMBER 3 #undef USE_TEST_DRIVER #ifdef USE_TEST_DRIVER // USE_TEST_DRIVER [ #include <mp/MpodBufferRecorder.h> #define OUTPUT_DRIVER MpodBufferRecorder #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "default", TEST_SAMPLE_DATA_SIZE*1000/TEST_SAMPLES_PER_SECOND #elif defined(WIN32) // USE_TEST_DRIVER ][ WIN32 #include <mp/MpodWinMM.h> #define OUTPUT_DRIVER MpodWinMM #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS MpodWinMM::getDefaultDeviceName() #elif defined(__pingtel_on_posix__) // WIN32 ][ __pingtel_on_posix__ #include <mp/MpodOss.h> #define OUTPUT_DRIVER MpodOss #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "/dev/dsp" #else // __pingtel_on_posix__ ] #error Unknown platform! #endif //static MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE]; //static UtlBoolean sampleDataInitialized=FALSE; static void calculateSampleData(int frequency, MpAudioSample sampleData[], int sampleDataSz, int samplesPerFrame, int samplesPerSecond) { for (int i=0; i<sampleDataSz; i++) { sampleData[i] = MpSineWaveGeneratorDeviceDriver::calculateSample(0, TEST_SAMPLE_DATA_MAGNITUDE, 1000000 / frequency, i, samplesPerFrame, samplesPerSecond); } } /** * Unittest for MpOutputDeviceDriver */ class MpOutputDeviceDriverTest : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(MpOutputDeviceDriverTest); CPPUNIT_TEST(testCreate); CPPUNIT_TEST(testEnableDisable); CPPUNIT_TEST(testEnableDisableFast); CPPUNIT_TEST(testDirectWrite); CPPUNIT_TEST(testTickerNotification); CPPUNIT_TEST_SUITE_END(); public: void setUp() { // Create pool for data buffers mpPool = new MpBufPool(TEST_SAMPLES_PER_FRAME_SIZE * sizeof(MpAudioSample) + MpArrayBuf::getHeaderSize(), BUFFER_NUM); CPPUNIT_ASSERT(mpPool != NULL); // Create pool for buffer headers mpHeadersPool = new MpBufPool(sizeof(MpAudioBuf), BUFFER_NUM); CPPUNIT_ASSERT(mpHeadersPool != NULL); // Set mpHeadersPool as default pool for audio and data pools. MpAudioBuf::smpDefaultPool = mpHeadersPool; MpDataBuf::smpDefaultPool = mpHeadersPool; } void tearDown() { if (mpPool != NULL) { delete mpPool; } if (mpHeadersPool != NULL) { delete mpHeadersPool; } } void testCreate() { for (int i=0; i<CREATE_TEST_RUNS_NUMBER; i++) { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testEnableDisable() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<ENABLE_DISABLE_TEST_RUNS_NUMBER; i++) { driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); CPPUNIT_ASSERT(driver.isEnabled()); OsTask::delay(50); driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testEnableDisableFast() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<ENABLE_DISABLE_FAST_TEST_RUNS_NUMBER; i++) { driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); CPPUNIT_ASSERT(driver.isEnabled()); driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testDirectWrite() { MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE]; calculateSampleData(440, sampleData, TEST_SAMPLE_DATA_SIZE, 80, 8000); OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); for (int i=0; i<DIRECT_WRITE_TEST_RUNS_NUMBER; i++) { MpFrameTime frameTime=0; driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); CPPUNIT_ASSERT(driver.isEnabled()); // Write some data to device. for (int frame=0; frame<TEST_SAMPLE_DATA_SIZE/TEST_SAMPLES_PER_FRAME_SIZE; frame++) { OsTask::delay(1000*TEST_SAMPLES_PER_FRAME_SIZE/TEST_SAMPLES_PER_SECOND); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.pushFrame(TEST_SAMPLES_PER_FRAME_SIZE, sampleData + TEST_SAMPLES_PER_FRAME_SIZE*frame, frameTime)); frameTime += TEST_SAMPLES_PER_FRAME_SIZE*1000/TEST_SAMPLES_PER_SECOND; } driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } } void testTickerNotification() { OsEvent notificationEvent; int sampleRates[]={8000, 16000, 32000, 48000}; int numRates = sizeof(sampleRates)/sizeof(int); int frequencies[] = {1000, 2000, 4000, 8000, 16000, 20000, 24000, 28000}; int numFreqs = sizeof(frequencies)/sizeof(int); OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); CPPUNIT_ASSERT(!driver.isEnabled()); int rateIndex; for(rateIndex = 0; rateIndex < numRates; rateIndex++) { int sampleDataSz = sampleRates[rateIndex]; MpAudioSample* sampleData = new MpAudioSample[sampleDataSz]; for (int i=0; i<numFreqs; i++) { printf("Frequency: %d (Hz) Sample rate: %d/sec.\n", frequencies[i], sampleRates[rateIndex]); calculateSampleData(frequencies[i], sampleData, sampleDataSz, sampleRates[rateIndex]/100, sampleRates[rateIndex]); MpFrameTime frameTime=0; driver.enableDevice(sampleRates[rateIndex]/100, sampleRates[rateIndex], 0); CPPUNIT_ASSERT(driver.isEnabled()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.setTickerNotification(&notificationEvent)); // Write some data to device. for (int frame=0; frame<100; frame++) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, notificationEvent.wait(OsTime(1000))); notificationEvent.reset(); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.pushFrame(sampleRates[rateIndex]/100, sampleData + sampleRates[rateIndex]/100*frame, frameTime)); frameTime += sampleRates[rateIndex]/100*1000/sampleRates[rateIndex]; } CPPUNIT_ASSERT(driver.setTickerNotification(NULL) == OS_SUCCESS); driver.disableDevice(); CPPUNIT_ASSERT(!driver.isEnabled()); } delete[] sampleData; } } protected: MpBufPool *mpPool; ///< Pool for data buffers MpBufPool *mpHeadersPool; ///< Pool for buffers headers }; CPPUNIT_TEST_SUITE_REGISTRATION(MpOutputDeviceDriverTest); <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: itkNeighborhoodIteratorTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include "itkImage.h" #include "vnl/vnl_vector.h" #include "itkNeighborhoodAllocator.h" #include "itkNeighborhood.h" #include "itkNeighborhoodIterator.h" #include "itkRegionNeighborhoodIterator.h" #include "itkRegionNonBoundaryNeighborhoodIterator.h" #include "itkRandomAccessNeighborhoodIterator.h" #include "itkRegionBoundaryNeighborhoodIterator.h" #include "itkImageRegionIterator.h" #include <iostream> inline void println(char *s) { std::cout << s << std::endl; } int main() { typedef itk::Image<float, 2> ImageType2D; typedef itk::Image<float, 3> ImageType3D; typedef itk::Image<float, 4> ImageTypeND; println("Creating some images"); // Create some images itk::ImageRegion<2> Region2D; itk::ImageRegion<3> Region3D; itk::ImageRegion<4> RegionND; itk::Size<2> size2D; size2D[0] = 123; size2D[1] = 241; itk::Size<3> size3D; size3D[0] = 100; size3D[1] = 100; size3D[2] = 10; itk::Size<4> sizeND; sizeND[0] = 10; sizeND[1] = 10; sizeND[2] = 4; sizeND[3] = 2; itk::Index<2> orig2D; orig2D[0] = 0; orig2D[1] = 0; itk::Index<3> orig3D; orig3D[0] = 0; orig3D[1] = 0; orig3D[2] = 0; itk::Index<4> origND; origND[0] = 0; origND[1] = 0; origND[2] = 0; origND[3] = 0; Region2D.SetSize(size2D); Region3D.SetSize(size3D); RegionND.SetSize(sizeND); Region2D.SetIndex(orig2D); Region3D.SetIndex(orig3D); RegionND.SetIndex(origND); ImageType2D::Pointer image2D = ImageType2D::New(); ImageType3D::Pointer image3D = ImageType3D::New(); ImageTypeND::Pointer imageND = ImageTypeND::New(); image2D->SetLargestPossibleRegion(Region2D); image3D->SetLargestPossibleRegion(Region3D); imageND->SetLargestPossibleRegion(RegionND); image2D->SetBufferedRegion(Region2D); image3D->SetBufferedRegion(Region3D); imageND->SetBufferedRegion(RegionND); image2D->SetRequestedRegion(Region2D); image3D->SetRequestedRegion(Region3D); imageND->SetRequestedRegion(RegionND); image2D->Allocate(); image3D->Allocate(); imageND->Allocate(); itk::ImageRegionIterator<float, 2> it2D(image2D, image2D->GetRequestedRegion()); itk::ImageRegionIterator<float, 3> it3D(image3D, image3D->GetRequestedRegion()); itk::ImageRegionIterator<float, 4> itND(imageND, imageND->GetRequestedRegion()); println("Initializing some images"); for (it2D = it2D.Begin(); it2D != it2D.End(); ++it2D) *it2D = 1.0f; for (it3D = it3D.Begin(); it3D != it3D.End(); ++it3D) *it3D = 1.0f; for (itND = itND.Begin(); itND != itND.End(); ++itND) *itND = 1.0f; // Set up some neighborhood iterators println("Setting up some neighborhood iterators"); itk::Size<2> sz2; sz2[0] = 2; sz2[1] = 1; itk::Size<3> sz3; sz3[0] = 2; sz3[1] = 3; sz3[2] = 1; itk::Size<4> szN; szN[0] = 1; szN[1] = 3; szN[2] = 1; szN[3] = 1; itk::RegionNeighborhoodIterator<float, 2,itk::NeighborhoodAllocator<float *>, vnl_vector<float> > rni2D(sz2, image2D, image2D->GetRequestedRegion()); itk::RegionNeighborhoodIterator<float, 3> rni3D(sz3, image3D, image3D->GetRequestedRegion()); itk::RegionNeighborhoodIterator<float, 4> rniND(szN, imageND, imageND->GetRequestedRegion()); rni2D.Print(std::cout); std::cout << std::endl; rni2D.Begin().Print(std::cout); std::cout << std::endl; rni2D.End().Print(std::cout); int i=0; for (rni2D = rni2D.Begin(); rni2D < rni2D.End(); ++rni2D) { ++i; } std::cout << i << std::endl; i=0; for (rni3D = rni3D.Begin(); rni3D < rni3D.End(); ++rni3D) { ++i; } std::cout << i << std::endl; i=0; for (rniND = rniND.Begin(); rniND < rniND.End(); ++rniND) { ++i; } std::cout << i << std::endl; println("Testing RandomAccessNeighborhoodIterator"); itk::RandomAccessNeighborhoodIterator<float, 3, itk::NeighborhoodAllocator<float *>, vnl_vector<float> > rri3D(sz3, image3D, image3D->GetRequestedRegion()); println("Testing forward iteration"); i =0; for (rri3D = rri3D.Begin(); rri3D < rri3D.End(); ++rri3D) {++i;} std::cout << i << std::endl; println("Testing backward iteration"); i=0; rri3D = rri3D.End(); --rri3D; for (; rri3D >= rri3D.Begin(); --rri3D) {++i;} std::cout << i << std::endl; println("Testing random access"); itk::Index<3> offset = { 12, 11, 2}; rri3D = rri3D.Begin() + offset; rri3D.Print(std::cout); (rri3D - offset).Print(std::cout); rri3D = offset + rri3D.Begin(); rri3D.Print(std::cout); println("Testing iterator subtraction (distance between iterators)"); std::cout << (rri3D - rri3D.Begin()) << std::endl; println("Testing RegionNonBoundaryNeighborhoodIterator"); itk::RegionNonBoundaryNeighborhoodIterator<float, 3, itk::NeighborhoodAllocator<float *>, vnl_vector<float> > rnbi3D(sz3, image3D, image3D->GetRequestedRegion()); rnbi3D.Print(std::cout); println("Testing SmartRegionNeighborhoodIterator"); itk::SmartRegionNeighborhoodIterator<float, 3, itk::NeighborhoodAllocator<float *>, vnl_vector<float> > rsbi3D(sz3, image3D, image3D->GetRequestedRegion()); rsbi3D.Print(std::cout); println("Testing RegionBoundaryNeighborhoodIterator"); itk::RegionBoundaryNeighborhoodIterator<float, 3, itk::NeighborhoodAllocator<float *>, vnl_vector<float> > rbni3D (sz3, image3D, image3D->GetRequestedRegion() ); rbni3D.Print(std::cout); return 0; } <commit_msg>FIX: Warning fixes on gcc<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: itkNeighborhoodIteratorTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include "itkImage.h" #include "vnl/vnl_vector.h" #include "itkNeighborhoodAllocator.h" #include "itkNeighborhood.h" #include "itkNeighborhoodIterator.h" #include "itkRegionNeighborhoodIterator.h" #include "itkRegionNonBoundaryNeighborhoodIterator.h" #include "itkRandomAccessNeighborhoodIterator.h" #include "itkRegionBoundaryNeighborhoodIterator.h" #include "itkImageRegionIterator.h" #include <iostream> inline void println(char *s) { std::cout << s << std::endl; } int main() { typedef itk::Image<float, 2> ImageType2D; typedef itk::Image<float, 3> ImageType3D; typedef itk::Image<float, 4> ImageTypeND; println("Creating some images"); // Create some images itk::ImageRegion<2> Region2D; itk::ImageRegion<3> Region3D; itk::ImageRegion<4> RegionND; itk::Size<2> size2D; size2D[0] = 123; size2D[1] = 241; itk::Size<3> size3D; size3D[0] = 100; size3D[1] = 100; size3D[2] = 10; itk::Size<4> sizeND; sizeND[0] = 10; sizeND[1] = 10; sizeND[2] = 4; sizeND[3] = 2; itk::Index<2> orig2D; orig2D[0] = 0; orig2D[1] = 0; itk::Index<3> orig3D; orig3D[0] = 0; orig3D[1] = 0; orig3D[2] = 0; itk::Index<4> origND; origND[0] = 0; origND[1] = 0; origND[2] = 0; origND[3] = 0; Region2D.SetSize(size2D); Region3D.SetSize(size3D); RegionND.SetSize(sizeND); Region2D.SetIndex(orig2D); Region3D.SetIndex(orig3D); RegionND.SetIndex(origND); ImageType2D::Pointer image2D = ImageType2D::New(); ImageType3D::Pointer image3D = ImageType3D::New(); ImageTypeND::Pointer imageND = ImageTypeND::New(); image2D->SetLargestPossibleRegion(Region2D); image3D->SetLargestPossibleRegion(Region3D); imageND->SetLargestPossibleRegion(RegionND); image2D->SetBufferedRegion(Region2D); image3D->SetBufferedRegion(Region3D); imageND->SetBufferedRegion(RegionND); image2D->SetRequestedRegion(Region2D); image3D->SetRequestedRegion(Region3D); imageND->SetRequestedRegion(RegionND); image2D->Allocate(); image3D->Allocate(); imageND->Allocate(); itk::ImageRegionIterator<float, 2> it2D(image2D, image2D->GetRequestedRegion()); itk::ImageRegionIterator<float, 3> it3D(image3D, image3D->GetRequestedRegion()); itk::ImageRegionIterator<float, 4> itND(imageND, imageND->GetRequestedRegion()); println("Initializing some images"); for (it2D = it2D.Begin(); it2D != it2D.End(); ++it2D) *it2D = 1.0f; for (it3D = it3D.Begin(); it3D != it3D.End(); ++it3D) *it3D = 1.0f; for (itND = itND.Begin(); itND != itND.End(); ++itND) *itND = 1.0f; // Set up some neighborhood iterators println("Setting up some neighborhood iterators"); itk::Size<2> sz2; sz2[0] = 2; sz2[1] = 1; itk::Size<3> sz3; sz3[0] = 2; sz3[1] = 3; sz3[2] = 1; itk::Size<4> szN; szN[0] = 1; szN[1] = 3; szN[2] = 1; szN[3] = 1; itk::RegionNeighborhoodIterator<float, 2,itk::NeighborhoodAllocator<float *>, vnl_vector<float> > rni2D(sz2, image2D, image2D->GetRequestedRegion()); itk::RegionNeighborhoodIterator<float, 3> rni3D(sz3, image3D, image3D->GetRequestedRegion()); itk::RegionNeighborhoodIterator<float, 4> rniND(szN, imageND, imageND->GetRequestedRegion()); rni2D.Print(std::cout); std::cout << std::endl; rni2D.Begin().Print(std::cout); std::cout << std::endl; rni2D.End().Print(std::cout); int i=0; for (rni2D = rni2D.Begin(); rni2D < rni2D.End(); ++rni2D) { ++i; } std::cout << i << std::endl; i=0; for (rni3D = rni3D.Begin(); rni3D < rni3D.End(); ++rni3D) { ++i; } std::cout << i << std::endl; i=0; for (rniND = rniND.Begin(); rniND < rniND.End(); ++rniND) { ++i; } std::cout << i << std::endl; println("Testing RandomAccessNeighborhoodIterator"); itk::RandomAccessNeighborhoodIterator<float, 3, itk::NeighborhoodAllocator<float *>, vnl_vector<float> > rri3D(sz3, image3D, image3D->GetRequestedRegion()); println("Testing forward iteration"); i =0; for (rri3D = rri3D.Begin(); rri3D < rri3D.End(); ++rri3D) {++i;} std::cout << i << std::endl; println("Testing backward iteration"); i=0; rri3D = rri3D.End(); --rri3D; for (; rri3D >= rri3D.Begin(); --rri3D) {++i;} std::cout << i << std::endl; println("Testing random access"); itk::Index<3> offset; offset[0] = 12; offset[1] = 11; offset[2] = 2; rri3D = rri3D.Begin() + offset; rri3D.Print(std::cout); (rri3D - offset).Print(std::cout); rri3D = offset + rri3D.Begin(); rri3D.Print(std::cout); println("Testing iterator subtraction (distance between iterators)"); std::cout << (rri3D - rri3D.Begin()) << std::endl; println("Testing RegionNonBoundaryNeighborhoodIterator"); itk::RegionNonBoundaryNeighborhoodIterator<float, 3, itk::NeighborhoodAllocator<float *>, vnl_vector<float> > rnbi3D(sz3, image3D, image3D->GetRequestedRegion()); rnbi3D.Print(std::cout); println("Testing SmartRegionNeighborhoodIterator"); itk::SmartRegionNeighborhoodIterator<float, 3, itk::NeighborhoodAllocator<float *>, vnl_vector<float> > rsbi3D(sz3, image3D, image3D->GetRequestedRegion()); rsbi3D.Print(std::cout); println("Testing RegionBoundaryNeighborhoodIterator"); itk::RegionBoundaryNeighborhoodIterator<float, 3, itk::NeighborhoodAllocator<float *>, vnl_vector<float> > rbni3D (sz3, image3D, image3D->GetRequestedRegion() ); rbni3D.Print(std::cout); return 0; } <|endoftext|>
<commit_before>#include "StorageManageWidget.h" #include <QVBoxLayout> #include <QHeaderView> #include <QFileDialog> #include <QLabel> #include <QApplication> #include <QDebug> StorageManageWidget::StorageManageWidget (QWidget * parent) : QWidget (parent) , tableCodes (nullptr) , tableSequences (nullptr) , tableReferences (nullptr) , modelCodes (nullptr) , modelSequences (nullptr) , modelReferences (nullptr) , tableFocused (nullptr) , buttonDataSourceOpen (nullptr) , buttonDataSourceClose (nullptr) , buttonDataSourceBrowse (nullptr) , buttonDataSave (nullptr) , buttonItemAdd (nullptr) , buttonItemRemove (nullptr) , editDataSource (nullptr) , xmlManager (nullptr) { createWidgets (); createLayouts (); createConnections (); } StorageManageWidget::~StorageManageWidget () { onDataSourceClosing (); delete xmlManager; } void StorageManageWidget::createWidgets () { tableCodes = new QTableView (this); tableSequences = new QTableView (this); tableReferences = new QTableView (this); modelCodes = new QStandardItemModel (this); modelSequences = new QStandardItemModel (this); modelReferences = new QStandardItemModel (this); modelCodes->setHorizontalHeaderLabels ({tr ("ID"), tr ("Length"), tr ("MSL")}); modelCodes->setColumnCount (columnCountTableCodes); tableCodes->setModel (modelCodes); tableCodes->horizontalHeader ()->setSectionResizeMode (columnNumberId, QHeaderView::Stretch); tableCodes->horizontalHeader ()->setSectionResizeMode (columnNumberLength, QHeaderView::Stretch); tableCodes->horizontalHeader ()->setSectionResizeMode (columnNumberMsl, QHeaderView::Stretch); modelSequences->setHorizontalHeaderLabels ({tr ("Sequence")}); modelSequences->setColumnCount (columnCountTableSequences); tableSequences->setModel (modelSequences); tableSequences->horizontalHeader ()->setSectionResizeMode (columnNumberSequence, QHeaderView::Stretch); modelReferences->setHorizontalHeaderLabels ({tr ("Article"), tr ("Author"), tr ("Link")}); modelReferences->setColumnCount (columnCountTableReferences); tableReferences->setModel (modelReferences); tableReferences->horizontalHeader ()->setSectionResizeMode (columnNumberArticle, QHeaderView::Stretch); tableReferences->horizontalHeader ()->setSectionResizeMode (columnNumberAuthor, QHeaderView::Stretch); tableReferences->horizontalHeader ()->setSectionResizeMode (columnNumberLink, QHeaderView::Stretch); buttonDataSourceBrowse = new QPushButton (tr ("..."), this); buttonDataSourceOpen = new QPushButton (tr ("Open"), this); buttonDataSourceClose = new QPushButton (tr ("Close"), this); buttonDataSave = new QPushButton (tr ("Save"), this); buttonItemAdd = new QPushButton (tr ("Add"), this); buttonItemRemove = new QPushButton (tr ("Remove"), this); buttonDataSourceClose->setDisabled (true); buttonDataSave->setDisabled (true); buttonItemAdd->setDisabled (true); buttonItemRemove->setDisabled (true); editDataSource = new QLineEdit (this); } void StorageManageWidget::createLayouts () { QHBoxLayout * layoutDataSource = new QHBoxLayout (); layoutDataSource->addWidget (new QLabel (tr ("Data source:"), this) ); layoutDataSource->addWidget (editDataSource); layoutDataSource->addWidget (buttonDataSourceBrowse); QHBoxLayout * layoutActions = new QHBoxLayout (); layoutActions->addWidget (buttonItemAdd); layoutActions->addWidget (buttonItemRemove); layoutActions->addStretch (); layoutActions->addWidget (buttonDataSave); layoutActions->addWidget (buttonDataSourceOpen); layoutActions->addWidget (buttonDataSourceClose); QVBoxLayout * layoutControl = new QVBoxLayout (); layoutControl->addLayout (layoutDataSource); layoutControl->addLayout (layoutActions); QVBoxLayout * layoutTop = new QVBoxLayout (); layoutTop->addLayout (layoutControl); layoutTop->addWidget (tableCodes); layoutTop->addWidget (tableSequences); layoutTop->addWidget (tableReferences); this->setLayout (layoutTop); } void StorageManageWidget::createConnections () { connect (buttonDataSourceBrowse, SIGNAL (clicked () ), this, SLOT (onDataSourceBrowsing () ) ); connect (buttonDataSourceOpen, SIGNAL (clicked () ), this, SLOT (onDataSourceOpening () ) ); connect (buttonDataSourceClose, SIGNAL (clicked () ), this, SLOT (onDataSourceClosing () ) ); connect (buttonDataSave, SIGNAL (clicked () ), this, SLOT (onDataSourceSaving () ) ); connect (buttonItemAdd, SIGNAL (clicked () ), this, SLOT (onItemAdding () ) ); connect (buttonItemRemove, SIGNAL (clicked () ), this, SLOT (onItemRemoving () ) ); connect (tableCodes->selectionModel (), SIGNAL (selectionChanged (QItemSelection, QItemSelection) ), this, SLOT (onModelCodesSelectionChanged (QItemSelection, QItemSelection) ) ); connect (qApp, SIGNAL (focusChanged (QWidget *, QWidget *) ), this, SLOT (onFocusChanged (QWidget *, QWidget *) ) ); connect (modelCodes, SIGNAL (itemChanged (QStandardItem *) ), this, SLOT (onModelCodesItemChanged (QStandardItem *) ) ); connect (modelSequences, SIGNAL (itemChanged (QStandardItem *) ), this, SLOT (onModelSequencesItemChanged (QStandardItem *) ) ); connect (modelReferences, SIGNAL (itemChanged (QStandardItem *) ), this, SLOT (onModelReferencesItemChanged (QStandardItem *) ) ); } void StorageManageWidget::onDataSourceBrowsing () { QFileDialog dialog; dialog.setFileMode (QFileDialog::AnyFile); editDataSource->setText (dialog.getOpenFileName () ); } void StorageManageWidget::onDataSourceOpening () { xmlManager = new Pslrk::Core::XmlManager (editDataSource->text ().toStdString () ); const pugi::xml_node codes = xmlManager->Select ("/").node (); for (const auto & code : codes.child ("codes").children ("code") ) { QStandardItem * cellId = new QStandardItem (); cellId->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellId->setData (code.attribute ("id").value (), Qt::DisplayRole); QStandardItem * cellLength = new QStandardItem (); cellLength->setTextAlignment (Qt::AlignCenter); cellLength->setData (code.attribute ("length").value (), Qt::DisplayRole); QStandardItem * cellMsl = new QStandardItem (); cellMsl->setTextAlignment (Qt::AlignCenter); cellMsl->setData (code.attribute ("maxpsl").value (), Qt::DisplayRole); QList <QStandardItem *> cells {cellId, cellLength, cellMsl}; int row {0}; for (const auto & sequence : code.children ("sequence") ) { QStandardItem * cellSequence = new QStandardItem (); cellSequence->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellSequence->setData (sequence.text ().get (), Qt::DisplayRole); cellSequence->setData (DataTypeSequence, DataTypeRole); cellId->setChild (row, columnNumberId, cellSequence); ++row; } for (const auto & reference : code.children ("reference") ) { QStandardItem * cellAuthor = new QStandardItem (); cellAuthor->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellAuthor->setData (reference.attribute ("author").value (), Qt::DisplayRole); cellAuthor->setData (DataTypeReference, DataTypeRole); QStandardItem * cellArticle = new QStandardItem (); cellArticle->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellArticle->setData (reference.attribute ("article").value (), Qt::DisplayRole); cellArticle->setData (DataTypeReference, DataTypeRole); QStandardItem * cellLink = new QStandardItem (); cellLink->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellLink->setData (reference.attribute ("link").value (), Qt::DisplayRole); cellLink->setData (DataTypeReference, DataTypeRole); cellId->setChild (row, columnNumberArticle, cellArticle); cellId->setChild (row, columnNumberAuthor, cellAuthor); cellId->setChild (row, columnNumberLink, cellLink); ++row; } modelCodes->appendRow (cells); } buttonDataSourceOpen->setDisabled (true); buttonDataSourceClose->setDisabled (false); } void StorageManageWidget::onDataSourceClosing () { delete xmlManager; xmlManager = nullptr; modelCodes->removeRows (0, modelCodes->rowCount () ); modelSequences->removeRows (0, modelSequences->rowCount () ); modelReferences->removeRows (0, modelReferences->rowCount () ); buttonDataSourceOpen->setDisabled (false); buttonDataSourceClose->setDisabled (true); buttonDataSave->setDisabled (true); } void StorageManageWidget::onDataSourceSaving () { xmlManager->Clear (); for (int i = 0; i < modelCodes->rowCount (); ++i) { const std::string id = modelCodes->item (i, columnNumberId )->data (Qt::DisplayRole).toString ().toStdString (); const std::string length = modelCodes->item (i, columnNumberLength)->data (Qt::DisplayRole).toString ().toStdString (); const std::string maxpsl = modelCodes->item (i, columnNumberMsl )->data (Qt::DisplayRole).toString ().toStdString (); xmlManager->InsertCode (id, std::stoi (length), std::stoi (maxpsl) ); QModelIndex indexId = modelCodes->item (i, columnNumberId)->index (); for (int j = 0; j < modelCodes->itemFromIndex (indexId)->rowCount (); ++j) { switch (modelCodes->data (modelCodes->index (j, columnNumberId, indexId), DataTypeRole).toInt () ) { case DataTypeSequence: { const std::string sequence {modelCodes->data (modelCodes->index (j, columnNumberId, indexId), Qt::DisplayRole).toString ().toStdString ()}; xmlManager->InsertCodeSequence (id, sequence); break; } case DataTypeReference: { const std::string article {modelCodes->data (modelCodes->index (j, columnNumberArticle, indexId), Qt::DisplayRole).toString ().toStdString ()}; const std::string author {modelCodes->data (modelCodes->index (j, columnNumberAuthor, indexId), Qt::DisplayRole).toString ().toStdString ()}; const std::string link {modelCodes->data (modelCodes->index (j, columnNumberLink, indexId), Qt::DisplayRole).toString ().toStdString ()}; xmlManager->InsertCodeReference (id, article, author, link); break; } } } } xmlManager->Save (); buttonDataSave->setDisabled (true); } void StorageManageWidget::onModelCodesSelectionChanged (QItemSelection selectedItem, QItemSelection deselectedItem) { if (deselectedItem.indexes ().size () ) { QModelIndex index = modelCodes->item (deselectedItem.indexes ().first ().row (), columnNumberId)->index (); modelCodes->itemFromIndex (index)->removeRows (0, modelCodes->itemFromIndex (index)->rowCount () ); const int modelSequencesRowCount {modelSequences->rowCount ()}; for (int i = 0; i < modelSequencesRowCount; ++i) { modelCodes->itemFromIndex (index)->appendRow (modelSequences->takeRow (0) ); } const int modelReferencesRowCount {modelReferences->rowCount ()}; for (int i = 0; i < modelReferencesRowCount; ++i) { modelCodes->itemFromIndex (index)->appendRow (modelReferences->takeRow (0) ); } } if (selectedItem.indexes ().size () ) { QModelIndex index = modelCodes->item (selectedItem.indexes ().first ().row (), columnNumberId)->index (); modelSequences->removeRows (0, modelSequences->rowCount () ); modelReferences->removeRows (0, modelReferences->rowCount () ); for (int i = 0; i < modelCodes->itemFromIndex (index)->rowCount (); ++i) { switch (modelCodes->data (modelCodes->index (i, columnNumberId, index), DataTypeRole).toInt () ) { case DataTypeSequence: { QStandardItem * cell = new QStandardItem (); cell->setData (modelCodes->data (modelCodes->index (i, columnNumberId, index), Qt::DisplayRole), Qt::DisplayRole); cell->setData (DataTypeSequence, DataTypeRole); modelSequences->appendRow ({cell}); break; } case DataTypeReference: { QStandardItem * cellAuthor = new QStandardItem (); QStandardItem * cellArticle = new QStandardItem (); QStandardItem * cellLink = new QStandardItem (); cellArticle->setData (modelCodes->data (modelCodes->index (i, columnNumberArticle, index), Qt::DisplayRole), Qt::DisplayRole); cellAuthor->setData (modelCodes->data (modelCodes->index (i, columnNumberAuthor, index), Qt::DisplayRole), Qt::DisplayRole); cellLink->setData (modelCodes->data (modelCodes->index (i, columnNumberLink, index), Qt::DisplayRole), Qt::DisplayRole); cellArticle->setData (DataTypeReference, DataTypeRole); modelReferences->appendRow ({cellArticle, cellAuthor, cellLink}); break; } } } } } void StorageManageWidget::onModelCodesItemChanged (QStandardItem * item) { buttonDataSave->setDisabled (false); } void StorageManageWidget::onModelSequencesItemChanged (QStandardItem * item) { buttonDataSave->setDisabled (false); } void StorageManageWidget::onModelReferencesItemChanged (QStandardItem * item) { buttonDataSave->setDisabled (false); } void StorageManageWidget::onFocusChanged (QWidget *, QWidget * widgetFocused) { if (widgetFocused == tableCodes || widgetFocused == tableSequences || widgetFocused == tableReferences) { buttonItemAdd->setDisabled (false); buttonItemRemove->setDisabled (false); tableFocused = widgetFocused; } else if (widgetFocused == buttonItemAdd || widgetFocused == buttonItemRemove) { } else { buttonItemAdd->setDisabled (true); buttonItemRemove->setDisabled (true); widgetFocused = nullptr; } } void StorageManageWidget::onItemAdding () { if (tableFocused == tableCodes) { QStandardItem * cellId = new QStandardItem (); QStandardItem * cellLength = new QStandardItem (); QStandardItem * cellMsl = new QStandardItem (); cellId->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellLength->setTextAlignment (Qt::AlignCenter); cellMsl->setTextAlignment (Qt::AlignCenter); modelCodes->appendRow ({cellId, cellLength, cellMsl}); } else if (tableFocused == tableSequences) { QStandardItem * cellSequence = new QStandardItem (); cellSequence->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellSequence->setData (DataTypeSequence, DataTypeRole); modelSequences->appendRow ({cellSequence}); } else if (tableFocused == tableReferences) { QStandardItem * cellArticle = new QStandardItem (); QStandardItem * cellAuthor = new QStandardItem (); QStandardItem * cellLink = new QStandardItem (); cellArticle->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellAuthor->setTextAlignment (Qt::AlignCenter); cellLink->setTextAlignment (Qt::AlignCenter); cellArticle->setData (DataTypeReference, DataTypeRole); modelReferences->appendRow ({cellArticle, cellAuthor, cellLink}); } buttonDataSave->setDisabled (false); } void StorageManageWidget::onItemRemoving () { if (tableFocused == tableCodes) { while (tableCodes->selectionModel ()->hasSelection () ) { modelCodes->removeRow (tableCodes->selectionModel ()->selectedIndexes ().first ().row () ); } } else if (tableFocused == tableSequences) { while (tableSequences->selectionModel ()->hasSelection () ) { modelSequences->removeRow (tableSequences->selectionModel ()->selectedIndexes ().first ().row () ); } } else if (tableFocused == tableReferences) { while (tableReferences->selectionModel ()->hasSelection () ) { modelReferences->removeRow (tableReferences->selectionModel ()->selectedIndexes ().first ().row () ); } } buttonDataSave->setDisabled (false); }<commit_msg>Fixed bug in CodeManager GUI (missing some data during saving).<commit_after>#include "StorageManageWidget.h" #include <QVBoxLayout> #include <QHeaderView> #include <QFileDialog> #include <QLabel> #include <QApplication> #include <QDebug> StorageManageWidget::StorageManageWidget (QWidget * parent) : QWidget (parent) , tableCodes (nullptr) , tableSequences (nullptr) , tableReferences (nullptr) , modelCodes (nullptr) , modelSequences (nullptr) , modelReferences (nullptr) , tableFocused (nullptr) , buttonDataSourceOpen (nullptr) , buttonDataSourceClose (nullptr) , buttonDataSourceBrowse (nullptr) , buttonDataSave (nullptr) , buttonItemAdd (nullptr) , buttonItemRemove (nullptr) , editDataSource (nullptr) , xmlManager (nullptr) { createWidgets (); createLayouts (); createConnections (); } StorageManageWidget::~StorageManageWidget () { onDataSourceClosing (); delete xmlManager; } void StorageManageWidget::createWidgets () { tableCodes = new QTableView (this); tableSequences = new QTableView (this); tableReferences = new QTableView (this); modelCodes = new QStandardItemModel (this); modelSequences = new QStandardItemModel (this); modelReferences = new QStandardItemModel (this); modelCodes->setHorizontalHeaderLabels ({tr ("ID"), tr ("Length"), tr ("MSL")}); modelCodes->setColumnCount (columnCountTableCodes); tableCodes->setModel (modelCodes); tableCodes->horizontalHeader ()->setSectionResizeMode (columnNumberId, QHeaderView::Stretch); tableCodes->horizontalHeader ()->setSectionResizeMode (columnNumberLength, QHeaderView::Stretch); tableCodes->horizontalHeader ()->setSectionResizeMode (columnNumberMsl, QHeaderView::Stretch); modelSequences->setHorizontalHeaderLabels ({tr ("Sequence")}); modelSequences->setColumnCount (columnCountTableSequences); tableSequences->setModel (modelSequences); tableSequences->horizontalHeader ()->setSectionResizeMode (columnNumberSequence, QHeaderView::Stretch); modelReferences->setHorizontalHeaderLabels ({tr ("Article"), tr ("Author"), tr ("Link")}); modelReferences->setColumnCount (columnCountTableReferences); tableReferences->setModel (modelReferences); tableReferences->horizontalHeader ()->setSectionResizeMode (columnNumberArticle, QHeaderView::Stretch); tableReferences->horizontalHeader ()->setSectionResizeMode (columnNumberAuthor, QHeaderView::Stretch); tableReferences->horizontalHeader ()->setSectionResizeMode (columnNumberLink, QHeaderView::Stretch); buttonDataSourceBrowse = new QPushButton (tr ("..."), this); buttonDataSourceOpen = new QPushButton (tr ("Open"), this); buttonDataSourceClose = new QPushButton (tr ("Close"), this); buttonDataSave = new QPushButton (tr ("Save"), this); buttonItemAdd = new QPushButton (tr ("Add"), this); buttonItemRemove = new QPushButton (tr ("Remove"), this); buttonDataSourceClose->setDisabled (true); buttonDataSave->setDisabled (true); buttonItemAdd->setDisabled (true); buttonItemRemove->setDisabled (true); editDataSource = new QLineEdit (this); } void StorageManageWidget::createLayouts () { QHBoxLayout * layoutDataSource = new QHBoxLayout (); layoutDataSource->addWidget (new QLabel (tr ("Data source:"), this) ); layoutDataSource->addWidget (editDataSource); layoutDataSource->addWidget (buttonDataSourceBrowse); QHBoxLayout * layoutActions = new QHBoxLayout (); layoutActions->addWidget (buttonItemAdd); layoutActions->addWidget (buttonItemRemove); layoutActions->addStretch (); layoutActions->addWidget (buttonDataSave); layoutActions->addWidget (buttonDataSourceOpen); layoutActions->addWidget (buttonDataSourceClose); QVBoxLayout * layoutControl = new QVBoxLayout (); layoutControl->addLayout (layoutDataSource); layoutControl->addLayout (layoutActions); QVBoxLayout * layoutTop = new QVBoxLayout (); layoutTop->addLayout (layoutControl); layoutTop->addWidget (tableCodes); layoutTop->addWidget (tableSequences); layoutTop->addWidget (tableReferences); this->setLayout (layoutTop); } void StorageManageWidget::createConnections () { connect (buttonDataSourceBrowse, SIGNAL (clicked () ), this, SLOT (onDataSourceBrowsing () ) ); connect (buttonDataSourceOpen, SIGNAL (clicked () ), this, SLOT (onDataSourceOpening () ) ); connect (buttonDataSourceClose, SIGNAL (clicked () ), this, SLOT (onDataSourceClosing () ) ); connect (buttonDataSave, SIGNAL (clicked () ), this, SLOT (onDataSourceSaving () ) ); connect (buttonItemAdd, SIGNAL (clicked () ), this, SLOT (onItemAdding () ) ); connect (buttonItemRemove, SIGNAL (clicked () ), this, SLOT (onItemRemoving () ) ); connect (tableCodes->selectionModel (), SIGNAL (selectionChanged (QItemSelection, QItemSelection) ), this, SLOT (onModelCodesSelectionChanged (QItemSelection, QItemSelection) ) ); connect (qApp, SIGNAL (focusChanged (QWidget *, QWidget *) ), this, SLOT (onFocusChanged (QWidget *, QWidget *) ) ); connect (modelCodes, SIGNAL (itemChanged (QStandardItem *) ), this, SLOT (onModelCodesItemChanged (QStandardItem *) ) ); connect (modelSequences, SIGNAL (itemChanged (QStandardItem *) ), this, SLOT (onModelSequencesItemChanged (QStandardItem *) ) ); connect (modelReferences, SIGNAL (itemChanged (QStandardItem *) ), this, SLOT (onModelReferencesItemChanged (QStandardItem *) ) ); } void StorageManageWidget::onDataSourceBrowsing () { QFileDialog dialog; dialog.setFileMode (QFileDialog::AnyFile); editDataSource->setText (dialog.getOpenFileName () ); } void StorageManageWidget::onDataSourceOpening () { xmlManager = new Pslrk::Core::XmlManager (editDataSource->text ().toStdString () ); const pugi::xml_node codes = xmlManager->Select ("/").node (); for (const auto & code : codes.child ("codes").children ("code") ) { QStandardItem * cellId = new QStandardItem (); cellId->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellId->setData (code.attribute ("id").value (), Qt::DisplayRole); QStandardItem * cellLength = new QStandardItem (); cellLength->setTextAlignment (Qt::AlignCenter); cellLength->setData (code.attribute ("length").value (), Qt::DisplayRole); QStandardItem * cellMsl = new QStandardItem (); cellMsl->setTextAlignment (Qt::AlignCenter); cellMsl->setData (code.attribute ("maxpsl").value (), Qt::DisplayRole); QList <QStandardItem *> cells {cellId, cellLength, cellMsl}; int row {0}; for (const auto & sequence : code.children ("sequence") ) { QStandardItem * cellSequence = new QStandardItem (); cellSequence->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellSequence->setData (sequence.text ().get (), Qt::DisplayRole); cellSequence->setData (DataTypeSequence, DataTypeRole); cellId->setChild (row, columnNumberId, cellSequence); ++row; } for (const auto & reference : code.children ("reference") ) { QStandardItem * cellAuthor = new QStandardItem (); cellAuthor->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellAuthor->setData (reference.attribute ("author").value (), Qt::DisplayRole); cellAuthor->setData (DataTypeReference, DataTypeRole); QStandardItem * cellArticle = new QStandardItem (); cellArticle->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellArticle->setData (reference.attribute ("article").value (), Qt::DisplayRole); cellArticle->setData (DataTypeReference, DataTypeRole); QStandardItem * cellLink = new QStandardItem (); cellLink->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellLink->setData (reference.attribute ("link").value (), Qt::DisplayRole); cellLink->setData (DataTypeReference, DataTypeRole); cellId->setChild (row, columnNumberArticle, cellArticle); cellId->setChild (row, columnNumberAuthor, cellAuthor); cellId->setChild (row, columnNumberLink, cellLink); ++row; } modelCodes->appendRow (cells); } buttonDataSourceOpen->setDisabled (true); buttonDataSourceClose->setDisabled (false); } void StorageManageWidget::onDataSourceClosing () { delete xmlManager; xmlManager = nullptr; modelCodes->removeRows (0, modelCodes->rowCount () ); modelSequences->removeRows (0, modelSequences->rowCount () ); modelReferences->removeRows (0, modelReferences->rowCount () ); buttonDataSourceOpen->setDisabled (false); buttonDataSourceClose->setDisabled (true); buttonDataSave->setDisabled (true); } void StorageManageWidget::onDataSourceSaving () { // HACK: Ugly hack for explicit call onModelCodesSelectionChanged. // Needed for update modelCodes by data from modelSequences and modelReferences. if (tableCodes->selectionModel ()->hasSelection () ) { const QModelIndex index {tableCodes->selectionModel ()->selectedIndexes ().first ()}; tableCodes->selectionModel ()->select (index, QItemSelectionModel::Toggle); tableCodes->selectionModel ()->select (index, QItemSelectionModel::Toggle); } xmlManager->Clear (); for (int i = 0; i < modelCodes->rowCount (); ++i) { const std::string id = modelCodes->item (i, columnNumberId )->data (Qt::DisplayRole).toString ().toStdString (); const std::string length = modelCodes->item (i, columnNumberLength)->data (Qt::DisplayRole).toString ().toStdString (); const std::string maxpsl = modelCodes->item (i, columnNumberMsl )->data (Qt::DisplayRole).toString ().toStdString (); xmlManager->InsertCode (id, std::stoi (length), std::stoi (maxpsl) ); QModelIndex indexId = modelCodes->item (i, columnNumberId)->index (); for (int j = 0; j < modelCodes->itemFromIndex (indexId)->rowCount (); ++j) { switch (modelCodes->data (modelCodes->index (j, columnNumberId, indexId), DataTypeRole).toInt () ) { case DataTypeSequence: { const std::string sequence {modelCodes->data (modelCodes->index (j, columnNumberId, indexId), Qt::DisplayRole).toString ().toStdString ()}; xmlManager->InsertCodeSequence (id, sequence); break; } case DataTypeReference: { const std::string article {modelCodes->data (modelCodes->index (j, columnNumberArticle, indexId), Qt::DisplayRole).toString ().toStdString ()}; const std::string author {modelCodes->data (modelCodes->index (j, columnNumberAuthor, indexId), Qt::DisplayRole).toString ().toStdString ()}; const std::string link {modelCodes->data (modelCodes->index (j, columnNumberLink, indexId), Qt::DisplayRole).toString ().toStdString ()}; xmlManager->InsertCodeReference (id, article, author, link); break; } } } } xmlManager->Save (); buttonDataSave->setDisabled (true); } void StorageManageWidget::onModelCodesSelectionChanged (QItemSelection selectedItem, QItemSelection deselectedItem) { if (deselectedItem.indexes ().size () ) { QModelIndex index = modelCodes->item (deselectedItem.indexes ().first ().row (), columnNumberId)->index (); modelCodes->itemFromIndex (index)->removeRows (0, modelCodes->itemFromIndex (index)->rowCount () ); const int modelSequencesRowCount {modelSequences->rowCount ()}; for (int i = 0; i < modelSequencesRowCount; ++i) { modelCodes->itemFromIndex (index)->appendRow (modelSequences->takeRow (0) ); } const int modelReferencesRowCount {modelReferences->rowCount ()}; for (int i = 0; i < modelReferencesRowCount; ++i) { modelCodes->itemFromIndex (index)->appendRow (modelReferences->takeRow (0) ); } } if (selectedItem.indexes ().size () ) { QModelIndex index = modelCodes->item (selectedItem.indexes ().first ().row (), columnNumberId)->index (); modelSequences->removeRows (0, modelSequences->rowCount () ); modelReferences->removeRows (0, modelReferences->rowCount () ); for (int i = 0; i < modelCodes->itemFromIndex (index)->rowCount (); ++i) { switch (modelCodes->data (modelCodes->index (i, columnNumberId, index), DataTypeRole).toInt () ) { case DataTypeSequence: { QStandardItem * cell = new QStandardItem (); cell->setData (modelCodes->data (modelCodes->index (i, columnNumberId, index), Qt::DisplayRole), Qt::DisplayRole); cell->setData (DataTypeSequence, DataTypeRole); modelSequences->appendRow ({cell}); break; } case DataTypeReference: { QStandardItem * cellAuthor = new QStandardItem (); QStandardItem * cellArticle = new QStandardItem (); QStandardItem * cellLink = new QStandardItem (); cellArticle->setData (modelCodes->data (modelCodes->index (i, columnNumberArticle, index), Qt::DisplayRole), Qt::DisplayRole); cellAuthor->setData (modelCodes->data (modelCodes->index (i, columnNumberAuthor, index), Qt::DisplayRole), Qt::DisplayRole); cellLink->setData (modelCodes->data (modelCodes->index (i, columnNumberLink, index), Qt::DisplayRole), Qt::DisplayRole); cellArticle->setData (DataTypeReference, DataTypeRole); modelReferences->appendRow ({cellArticle, cellAuthor, cellLink}); break; } } } } } void StorageManageWidget::onModelCodesItemChanged (QStandardItem * item) { buttonDataSave->setDisabled (false); } void StorageManageWidget::onModelSequencesItemChanged (QStandardItem * item) { buttonDataSave->setDisabled (false); } void StorageManageWidget::onModelReferencesItemChanged (QStandardItem * item) { buttonDataSave->setDisabled (false); } void StorageManageWidget::onFocusChanged (QWidget *, QWidget * widgetFocused) { if (widgetFocused == tableCodes || widgetFocused == tableSequences || widgetFocused == tableReferences) { buttonItemAdd->setDisabled (false); buttonItemRemove->setDisabled (false); tableFocused = widgetFocused; } else if (widgetFocused == buttonItemAdd || widgetFocused == buttonItemRemove) { } else { buttonItemAdd->setDisabled (true); buttonItemRemove->setDisabled (true); widgetFocused = nullptr; } } void StorageManageWidget::onItemAdding () { if (tableFocused == tableCodes) { QStandardItem * cellId = new QStandardItem (); QStandardItem * cellLength = new QStandardItem (); QStandardItem * cellMsl = new QStandardItem (); cellId->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellLength->setTextAlignment (Qt::AlignCenter); cellMsl->setTextAlignment (Qt::AlignCenter); modelCodes->appendRow ({cellId, cellLength, cellMsl}); } else if (tableFocused == tableSequences) { QStandardItem * cellSequence = new QStandardItem (); cellSequence->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellSequence->setData (DataTypeSequence, DataTypeRole); modelSequences->appendRow ({cellSequence}); } else if (tableFocused == tableReferences) { QStandardItem * cellArticle = new QStandardItem (); QStandardItem * cellAuthor = new QStandardItem (); QStandardItem * cellLink = new QStandardItem (); cellArticle->setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); cellAuthor->setTextAlignment (Qt::AlignCenter); cellLink->setTextAlignment (Qt::AlignCenter); cellArticle->setData (DataTypeReference, DataTypeRole); modelReferences->appendRow ({cellArticle, cellAuthor, cellLink}); } buttonDataSave->setDisabled (false); } void StorageManageWidget::onItemRemoving () { if (tableFocused == tableCodes) { while (tableCodes->selectionModel ()->hasSelection () ) { modelCodes->removeRow (tableCodes->selectionModel ()->selectedIndexes ().first ().row () ); } } else if (tableFocused == tableSequences) { while (tableSequences->selectionModel ()->hasSelection () ) { modelSequences->removeRow (tableSequences->selectionModel ()->selectedIndexes ().first ().row () ); } } else if (tableFocused == tableReferences) { while (tableReferences->selectionModel ()->hasSelection () ) { modelReferences->removeRow (tableReferences->selectionModel ()->selectedIndexes ().first ().row () ); } } buttonDataSave->setDisabled (false); }<|endoftext|>
<commit_before>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file linear_observation_model.hpp * \date October 2014 * \author Jan Issac (jan.issac@gmail.com) */ #ifndef FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP #define FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP #include <fl/util/traits.hpp> #include <fl/distribution/gaussian.hpp> #include <fl/model/observation/observation_model_interface.hpp> namespace fl { // Forward declarations template < typename Obsrv, typename State> class LinearGaussianObservationModel; /** * Linear Gaussian observation model traits. This trait definition contains all * types used internally within the model. Additionally, it provides the types * needed externally to use the linear Gaussian model. */ template < typename Obsrv_, typename State_> struct Traits< LinearGaussianObservationModel<Obsrv_, State_>> { typedef State_ State; typedef Obsrv_ Obsrv; typedef Gaussian<Obsrv> GaussianBase; typedef typename Traits<GaussianBase>::Scalar Scalar; typedef typename Traits<GaussianBase>::SecondMoment SecondMoment; typedef typename Traits<GaussianBase>::StandardVariate Noise; typedef Eigen::Matrix< Scalar, Obsrv::SizeAtCompileTime, State::SizeAtCompileTime > SensorMatrix; typedef ObservationModelInterface< Obsrv, State, Noise > ObservationModelBase; }; /** * \ingroup observation_models */ template <typename Obsrv,typename State> class LinearGaussianObservationModel : public Traits< LinearGaussianObservationModel<Obsrv, State> >::ObservationModelBase, public Traits< LinearGaussianObservationModel<Obsrv, State> >::GaussianBase { public: typedef LinearGaussianObservationModel<Obsrv, State> This; typedef typename Traits<This>::Noise Noise; typedef typename Traits<This>::Scalar Scalar; typedef typename Traits<This>::SecondMoment SecondMoment; typedef typename Traits<This>::SensorMatrix SensorMatrix; using Traits<This>::GaussianBase::mean; using Traits<This>::GaussianBase::covariance; using Traits<This>::GaussianBase::dimension; public: LinearGaussianObservationModel( const SecondMoment& noise_covariance, const int observation_dim = DimensionOf<Obsrv>(), const int state_dim = DimensionOf<State>()) : Traits<This>::GaussianBase(observation_dim), state_dimension_(state_dim), H_(SensorMatrix::Ones(obsrv_dimension(), state_dimension())) { covariance(noise_covariance); } ~LinearGaussianObservationModel() { } virtual void condition(const State& x) { mean(H_ * x); } virtual const SensorMatrix& H() const { return H_; } virtual void H(const SensorMatrix& sensor_matrix) { H_ = sensor_matrix; } virtual Obsrv predict_observation(const State& state, const Noise& noise, double delta_time) { condition(state); return Traits<This>::GaussianBase::map_standard_normal(noise); } virtual int obsrv_dimension() const { return Traits<This>::GaussianBase::dimension(); } virtual int noise_dimension() const { return Traits<This>::GaussianBase::standard_variate_dimension(); } virtual int state_dimension() const { return state_dimension_; } protected: int state_dimension_; SensorMatrix H_; }; } #endif <commit_msg>LinearGaussianObservationModel updates<commit_after>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file linear_observation_model.hpp * \date October 2014 * \author Jan Issac (jan.issac@gmail.com) */ #ifndef FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP #define FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP #include <fl/util/traits.hpp> #include <fl/distribution/gaussian.hpp> #include <fl/model/observation/observation_model_interface.hpp> namespace fl { // Forward declarations template < typename Obsrv, typename State> class LinearGaussianObservationModel; /** * Linear Gaussian observation model traits. This trait definition contains all * types used internally within the model. Additionally, it provides the types * needed externally to use the linear Gaussian model. */ template < typename Obsrv_, typename State_> struct Traits< LinearGaussianObservationModel<Obsrv_, State_>> { typedef State_ State; typedef Obsrv_ Obsrv; typedef Gaussian<Obsrv> GaussianBase; typedef typename Traits<GaussianBase>::Scalar Scalar; typedef typename Traits<GaussianBase>::SecondMoment SecondMoment; typedef typename Traits<GaussianBase>::StandardVariate Noise; typedef Eigen::Matrix< Scalar, Obsrv::SizeAtCompileTime, State::SizeAtCompileTime > SensorMatrix; typedef ObservationModelInterface< Obsrv, State, Noise > ObservationModelBase; }; /** * \ingroup observation_models */ template <typename Obsrv,typename State> class LinearGaussianObservationModel : public Traits< LinearGaussianObservationModel<Obsrv, State> >::ObservationModelBase, public Traits< LinearGaussianObservationModel<Obsrv, State> >::GaussianBase { public: typedef LinearGaussianObservationModel<Obsrv, State> This; typedef typename Traits<This>::Noise Noise; typedef typename Traits<This>::Scalar Scalar; typedef typename Traits<This>::SecondMoment SecondMoment; typedef typename Traits<This>::SensorMatrix SensorMatrix; using Traits<This>::GaussianBase::mean; using Traits<This>::GaussianBase::covariance; using Traits<This>::GaussianBase::dimension; public: explicit LinearGaussianObservationModel( const SecondMoment& noise_covariance, const int obsrv_dim = DimensionOf<Obsrv>(), const int state_dim = DimensionOf<State>()) : Traits<This>::GaussianBase(obsrv_dim), state_dimension_(state_dim), H_(SensorMatrix::Ones(obsrv_dimension(), state_dimension())) { covariance(noise_covariance); } explicit LinearGaussianObservationModel( const int obsrv_dim = DimensionOf<Obsrv>(), const int state_dim = DimensionOf<State>()) : Traits<This>::GaussianBase(obsrv_dim), state_dimension_(state_dim), H_(SensorMatrix::Ones(obsrv_dimension(), state_dimension())) { covariance(SecondMoment::Identity(obsrv_dim, obsrv_dim)); } ~LinearGaussianObservationModel() { } virtual void condition(const State& x) { mean(H_ * x); } virtual const SensorMatrix& H() const { return H_; } virtual void H(const SensorMatrix& sensor_matrix) { H_ = sensor_matrix; } virtual Obsrv predict_obsrv(const State& state, const Noise& noise, double delta_time) { condition(state); return Traits<This>::GaussianBase::map_standard_normal(noise); } virtual int obsrv_dimension() const { return Traits<This>::GaussianBase::dimension(); } virtual int noise_dimension() const { return Traits<This>::GaussianBase::standard_variate_dimension(); } virtual int state_dimension() const { return state_dimension_; } protected: int state_dimension_; SensorMatrix H_; }; } #endif <|endoftext|>
<commit_before>// Copyright (C) 2010-2015 Joshua Boyce // See the file COPYING for copying permission. #pragma warning(push, 1) #pragma warning(disable : 4505 4702 4996) #pragma warning(disable : 6011 6102 6201 6239 6244 6246 6295) #pragma warning(disable : 6305 6326 6334 6385 6386 6387) #pragma warning(disable : 28159 28197 28251 28285) <commit_msg>[Warning] Add another suppression.<commit_after>// Copyright (C) 2010-2015 Joshua Boyce // See the file COPYING for copying permission. #pragma warning(push, 1) #pragma warning(disable : 4505 4702 4996) #pragma warning(disable : 6011 6102 6201 6239 6244 6246 6295) #pragma warning(disable : 6305 6308 6326 6334 6385 6386 6387) #pragma warning(disable : 28159 28197 28251 28285) <|endoftext|>
<commit_before>#pragma once #ifndef KENGINE_TEXTURE_PATH_MAX_LENGTH # define KENGINE_TEXTURE_PATH_MAX_LENGTH 256 #endif namespace kengine { struct TextureDataComponent { void * data; GLuint * textureID; int width; int height; int components; using FreeFunc = void(*)(void * data); FreeFunc free; }; } <commit_msg>default values for TextureDataComponent<commit_after>#pragma once #ifndef KENGINE_TEXTURE_PATH_MAX_LENGTH # define KENGINE_TEXTURE_PATH_MAX_LENGTH 256 #endif namespace kengine { struct TextureDataComponent { void * data = nullptr; GLuint * textureID = nullptr; int width = 0; int height = 0; int components = 0; using FreeFunc = void(*)(void * data); FreeFunc free = nullptr; }; } <|endoftext|>
<commit_before>/** * Copyright 2008 Matthew Graham * 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 "message.h" #include <testpp/test.h> TESTPP( test_message_constructor ) { message_c msg; assertpp( msg.argc() ) == 0; } TESTPP( test_message_add_arg ) { message_c msg; msg.add_arg( "hello" ); msg.add_arg( "world!" ); msg.add_arg( "hello world!" ); assertpp( msg.argc() ) == 3; assertpp( msg.argv( 0 ) ) == "hello"; assertpp( msg.argv( 1 ) ) == "world!"; assertpp( msg.argv( 2 ) ) == "hello world!"; } <commit_msg>added tests for the message import/export<commit_after>/** * Copyright 2008 Matthew Graham * 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 "message.h" #include <testpp/test.h> TESTPP( test_message_constructor ) { message_c msg; assertpp( msg.argc() ) == 0; } TESTPP( test_message_add_arg ) { message_c msg; msg.add_arg( "hello" ); msg.add_arg( "world!" ); msg.add_arg( "hello world!" ); assertpp( msg.argc() ) == 3; assertpp( msg.argv( 0 ) ) == "hello"; assertpp( msg.argv( 1 ) ) == "world!"; assertpp( msg.argv( 2 ) ) == "hello world!"; } TESTPP( test_message_export_string ) { message_c msg; msg.add_arg( "dog" ); msg.add_arg( "cat" ); msg.add_arg( "mouse" ); message_export_c exp( msg ); std::string dog, cat, mouse; exp + dog + cat + mouse; assertpp( dog ) == "dog"; assertpp( cat ) == "cat"; assertpp( mouse ) == "mouse"; } TESTPP( test_message_import_mixed ) { std::string dog( "dog" ); int five( 5 ); bool t( true ); message_c msg; message_import_c import( msg ); import + dog + five + t; assertpp( msg.argc() ) == 3; assertpp( msg.argv( 0 ) ) == "dog"; assertpp( msg.argv( 1 ) ) == "5"; assertpp( msg.argv( 2 ) ) == "1"; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: defaultprovider.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: ihi $ $Date: 2007-11-23 14:18:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONFIGMGR_DEFAULTPROVIDER_HXX #define CONFIGMGR_DEFAULTPROVIDER_HXX #ifndef _CONFIGMGR_TREE_VALUENODE_HXX #include "valuenode.hxx" #endif #ifndef CONFIGMGR_UTILITY_HXX_ #include "utility.hxx" #endif #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_ #include <com/sun/star/uno/Exception.hpp> #endif #ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_ #include <com/sun/star/uno/RuntimeException.hpp> #endif #ifndef INCLUDED_MEMORY #include <memory> #define INCLUDED_MEMORY #endif namespace configmgr { namespace uno = com::sun::star::uno; using ::rtl::OUString; //////////////////////////////////////////////////////////////////////////////// namespace configuration { class AbsolutePath; } //------------------------- class ISubtree; class RequestOptions; //========================================================================== //= IDefaultProvider //========================================================================== /* is an interface that can be implemented by an <type>ITreeProvider</type> or <type>ITreeManager</type>. <p>Supports functionality to fetch only the default data corresponding to a tree</p> */ class SAL_NO_VTABLE IDefaultProvider { public: /** load the default version of the tree named by a path using certain options and requiring a specific loading depth @returns the default data tree, yielding ownership of it <NULL/>if no default data is available for the tree */ virtual std::auto_ptr<ISubtree> requestDefaultData( configuration::AbsolutePath const& aSubtreePath, const RequestOptions& _aOptions ) CFG_UNO_THROW_ALL( ) = 0; }; //========================================================================== /// a refcounted <type>IDefaultProvider</type>. class SAL_NO_VTABLE IConfigDefaultProvider : public Refcounted , public IDefaultProvider { }; //========================================================================== //= IDefaultableTreeManager //========================================================================== /* is a supplementary interface for a <type>ITreeManager</type>. <p>Supports functionality to load default data into the managed tree</p> */ class SAL_NO_VTABLE IDefaultableTreeManager { public: /** attempt to load default data into the tree named by a path using certain options and requiring a specific loading depth. @returns <TRUE/>, if some default data is available within the tree <FALSE/>, if no default data is available for the tree */ virtual sal_Bool fetchDefaultData(configuration::AbsolutePath const& aSubtreePath, const RequestOptions& _xOptions ) CFG_UNO_THROW_ALL( ) = 0; }; //////////////////////////////////////////////////////////////////////////////// } // namespace configmgr #endif <commit_msg>INTEGRATION: CWS changefileheader (1.7.16); FILE MERGED 2008/04/01 12:27:23 thb 1.7.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:43 rt 1.7.16.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: defaultprovider.hxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef CONFIGMGR_DEFAULTPROVIDER_HXX #define CONFIGMGR_DEFAULTPROVIDER_HXX #include "valuenode.hxx" #include "utility.hxx" #include <com/sun/star/uno/Exception.hpp> #include <com/sun/star/uno/RuntimeException.hpp> #ifndef INCLUDED_MEMORY #include <memory> #define INCLUDED_MEMORY #endif namespace configmgr { namespace uno = com::sun::star::uno; using ::rtl::OUString; //////////////////////////////////////////////////////////////////////////////// namespace configuration { class AbsolutePath; } //------------------------- class ISubtree; class RequestOptions; //========================================================================== //= IDefaultProvider //========================================================================== /* is an interface that can be implemented by an <type>ITreeProvider</type> or <type>ITreeManager</type>. <p>Supports functionality to fetch only the default data corresponding to a tree</p> */ class SAL_NO_VTABLE IDefaultProvider { public: /** load the default version of the tree named by a path using certain options and requiring a specific loading depth @returns the default data tree, yielding ownership of it <NULL/>if no default data is available for the tree */ virtual std::auto_ptr<ISubtree> requestDefaultData( configuration::AbsolutePath const& aSubtreePath, const RequestOptions& _aOptions ) CFG_UNO_THROW_ALL( ) = 0; }; //========================================================================== /// a refcounted <type>IDefaultProvider</type>. class SAL_NO_VTABLE IConfigDefaultProvider : public Refcounted , public IDefaultProvider { }; //========================================================================== //= IDefaultableTreeManager //========================================================================== /* is a supplementary interface for a <type>ITreeManager</type>. <p>Supports functionality to load default data into the managed tree</p> */ class SAL_NO_VTABLE IDefaultableTreeManager { public: /** attempt to load default data into the tree named by a path using certain options and requiring a specific loading depth. @returns <TRUE/>, if some default data is available within the tree <FALSE/>, if no default data is available for the tree */ virtual sal_Bool fetchDefaultData(configuration::AbsolutePath const& aSubtreePath, const RequestOptions& _xOptions ) CFG_UNO_THROW_ALL( ) = 0; }; //////////////////////////////////////////////////////////////////////////////// } // namespace configmgr #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AKey.cxx,v $ * * $Revision: 1.18 $ * * last change: $Author: rt $ $Date: 2005-09-08 05:29:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_ADO_KEY_HXX_ #include "ado/AKey.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _CONNECTIVITY_ADO_COLUMNS_HXX_ #include "ado/AColumns.hxx" #endif #ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_ #include "ado/AConnection.hxx" #endif using namespace connectivity::ado; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; using namespace com::sun::star::sdbcx; // ------------------------------------------------------------------------- OAdoKey::OAdoKey(sal_Bool _bCase,OConnection* _pConnection, ADOKey* _pKey) : OKey_ADO(_bCase) ,m_pConnection(_pConnection) { construct(); m_aKey = WpADOKey(_pKey); fillPropertyValues(); } // ------------------------------------------------------------------------- OAdoKey::OAdoKey(sal_Bool _bCase,OConnection* _pConnection) : OKey_ADO(_bCase) ,m_pConnection(_pConnection) { construct(); m_aKey.Create(); } // ------------------------------------------------------------------------- void OAdoKey::refreshColumns() { TStringVector aVector; WpADOColumns aColumns; if ( m_aKey.IsValid() ) { aColumns = m_aKey.get_Columns(); aColumns.fillElementNames(aVector); } if(m_pColumns) m_pColumns->reFill(aVector); else m_pColumns = new OColumns(*this,m_aMutex,aVector,aColumns,isCaseSensitive(),m_pConnection); } // ------------------------------------------------------------------------- Sequence< sal_Int8 > OAdoKey::getUnoTunnelImplementationId() { static ::cppu::OImplementationId * pId = 0; if (! pId) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (! pId) { static ::cppu::OImplementationId aId; pId = &aId; } } return pId->getImplementationId(); } // com::sun::star::lang::XUnoTunnel //------------------------------------------------------------------ sal_Int64 OAdoKey::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException) { return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) ) ? (sal_Int64)this : OKey_ADO::getSomething(rId); } // ------------------------------------------------------------------------- void OAdoKey::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception) { if(m_aKey.IsValid()) { switch(nHandle) { case PROPERTY_ID_NAME: { ::rtl::OUString aVal; rValue >>= aVal; m_aKey.put_Name(aVal); ADOS::ThrowException(*m_pConnection->getConnection(),*this); } break; case PROPERTY_ID_TYPE: { sal_Int32 nVal=0; rValue >>= nVal; m_aKey.put_Type(Map2KeyRule(nVal)); ADOS::ThrowException(*m_pConnection->getConnection(),*this); } break; case PROPERTY_ID_REFERENCEDTABLE: { ::rtl::OUString aVal; rValue >>= aVal; m_aKey.put_RelatedTable(aVal); ADOS::ThrowException(*m_pConnection->getConnection(),*this); } break; case PROPERTY_ID_UPDATERULE: { sal_Int32 nVal=0; rValue >>= nVal; m_aKey.put_UpdateRule(Map2Rule(nVal)); ADOS::ThrowException(*m_pConnection->getConnection(),*this); } break; case PROPERTY_ID_DELETERULE: { sal_Int32 nVal=0; rValue >>= nVal; m_aKey.put_DeleteRule(Map2Rule(nVal)); ADOS::ThrowException(*m_pConnection->getConnection(),*this); } break; } } OKey_ADO::setFastPropertyValue_NoBroadcast(nHandle,rValue); } // ------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void SAL_CALL OAdoKey::acquire() throw(::com::sun::star::uno::RuntimeException) { OKey_ADO::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL OAdoKey::release() throw(::com::sun::star::uno::RuntimeException) { OKey_ADO::release(); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS warnings01 (1.18.30); FILE MERGED 2005/11/07 14:43:07 fs 1.18.30.1: #i57457# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AKey.cxx,v $ * * $Revision: 1.19 $ * * last change: $Author: hr $ $Date: 2006-06-20 01:14:19 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_ADO_KEY_HXX_ #include "ado/AKey.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _CONNECTIVITY_ADO_COLUMNS_HXX_ #include "ado/AColumns.hxx" #endif #ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_ #include "ado/AConnection.hxx" #endif using namespace connectivity::ado; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; using namespace com::sun::star::sdbcx; // ------------------------------------------------------------------------- OAdoKey::OAdoKey(sal_Bool _bCase,OConnection* _pConnection, ADOKey* _pKey) : OKey_ADO(_bCase) ,m_pConnection(_pConnection) { construct(); m_aKey = WpADOKey(_pKey); fillPropertyValues(); } // ------------------------------------------------------------------------- OAdoKey::OAdoKey(sal_Bool _bCase,OConnection* _pConnection) : OKey_ADO(_bCase) ,m_pConnection(_pConnection) { construct(); m_aKey.Create(); } // ------------------------------------------------------------------------- void OAdoKey::refreshColumns() { TStringVector aVector; WpADOColumns aColumns; if ( m_aKey.IsValid() ) { aColumns = m_aKey.get_Columns(); aColumns.fillElementNames(aVector); } if(m_pColumns) m_pColumns->reFill(aVector); else m_pColumns = new OColumns(*this,m_aMutex,aVector,aColumns,isCaseSensitive(),m_pConnection); } // ------------------------------------------------------------------------- Sequence< sal_Int8 > OAdoKey::getUnoTunnelImplementationId() { static ::cppu::OImplementationId * pId = 0; if (! pId) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (! pId) { static ::cppu::OImplementationId aId; pId = &aId; } } return pId->getImplementationId(); } // com::sun::star::lang::XUnoTunnel //------------------------------------------------------------------ sal_Int64 OAdoKey::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException) { return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) ) ? reinterpret_cast< sal_Int64 >( this ) : OKey_ADO::getSomething(rId); } // ------------------------------------------------------------------------- void OAdoKey::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception) { if(m_aKey.IsValid()) { switch(nHandle) { case PROPERTY_ID_NAME: { ::rtl::OUString aVal; rValue >>= aVal; m_aKey.put_Name(aVal); ADOS::ThrowException(*m_pConnection->getConnection(),*this); } break; case PROPERTY_ID_TYPE: { sal_Int32 nVal=0; rValue >>= nVal; m_aKey.put_Type(Map2KeyRule(nVal)); ADOS::ThrowException(*m_pConnection->getConnection(),*this); } break; case PROPERTY_ID_REFERENCEDTABLE: { ::rtl::OUString aVal; rValue >>= aVal; m_aKey.put_RelatedTable(aVal); ADOS::ThrowException(*m_pConnection->getConnection(),*this); } break; case PROPERTY_ID_UPDATERULE: { sal_Int32 nVal=0; rValue >>= nVal; m_aKey.put_UpdateRule(Map2Rule(nVal)); ADOS::ThrowException(*m_pConnection->getConnection(),*this); } break; case PROPERTY_ID_DELETERULE: { sal_Int32 nVal=0; rValue >>= nVal; m_aKey.put_DeleteRule(Map2Rule(nVal)); ADOS::ThrowException(*m_pConnection->getConnection(),*this); } break; } } OKey_ADO::setFastPropertyValue_NoBroadcast(nHandle,rValue); } // ------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void SAL_CALL OAdoKey::acquire() throw(::com::sun::star::uno::RuntimeException) { OKey_ADO::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL OAdoKey::release() throw(::com::sun::star::uno::RuntimeException) { OKey_ADO::release(); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>#include <iostream> #include <ncurses.h> #include "../src/newmove.hh" #include "../src/configuration.hh" #include "catch.hpp" TEST_CASE("mvsot") { contents contents; contents.push_back(" hello"); initscr(); mvsot(contents); endwin(); REQUIRE(0 ==contents.y); REQUIRE(4 ==contents.x); } TEST_CASE("mvcol") { contents contents; contents.push_back("asert"); initscr(); mvcol(contents,3); int y1 = contents.y, x1 = contents.x; mvcol(contents,10); //doesn't do anything int y2 = contents.y, x2 = contents.x; mvcol(contents,0); int y3 = contents.y, x3 = contents.x; endwin(); REQUIRE(0 ==y1); REQUIRE(0 ==y2); REQUIRE(0 ==y3); REQUIRE(3 ==x1); REQUIRE(3 ==x2); REQUIRE(0 ==x3); } TEST_CASE("mvsol") { contents contents (0,5); contents.push_back(" assert"); initscr(); mvsol(contents); int y = contents.y, x = contents.x; endwin(); REQUIRE(0 ==y); REQUIRE(0 ==x); } TEST_CASE("mvd") { contents contents; contents.push_back("assert"); contents.push_back("hello"); contents.push_back("aseuirpo"); initscr(); mvd(contents,2); int y = contents.y, x = contents.x; mvd(contents); int y1 = contents.y, x1 = contents.x; endwin(); REQUIRE(0 ==x); REQUIRE(0 ==x1); REQUIRE(2 ==y); REQUIRE(2 ==y1); } TEST_CASE("mvf") { contents contents; contents.push_back("assert"); contents.push_back("hello"); initscr(); mvf(contents,3); int y = contents.y, x = contents.x; mvf(contents,4); int y1 = contents.y, x1 = contents.x; endwin(); REQUIRE(0 ==y); REQUIRE(3 ==x); REQUIRE(1 ==y1); REQUIRE(1 ==x1); } TEST_CASE("mvb") { contents contents (1,0); contents.push_back("assert"); contents.push_back("back"); initscr(); mvb(contents,2); int y = contents.y, x = contents.x; endwin(); REQUIRE(0 ==y); REQUIRE(4 ==x); } TEST_CASE("mvf_2") { contents contents; contents.push_back("CFLAGS=-lncurses -Wall"); contents.push_back("O=out"); contents.push_back("S=src"); contents.push_back("T=test"); contents.push_back("TO=testout"); contents.push_back("CC=g++"); initscr(); mveol(contents); int y = contents.y, x = contents.x; mvf(contents,2); int y1 = contents.y, x1 = contents.x; endwin(); REQUIRE(0 ==y); REQUIRE(21 ==x); REQUIRE(1 ==y1); REQUIRE(1 ==x1); } TEST_CASE("mveol") { contents contents; contents.push_back("Aesop"); initscr(); mveol(contents); int y = contents.y, x = contents.x; endwin(); REQUIRE(4 ==x); REQUIRE(0 ==y); } TEST_CASE("mvu") { contents contents (1,6); contents.push_back("hi"); contents.push_back("Alabama"); initscr(); mvu(contents); int y1 = contents.y, x1 = contents.x; endwin(); REQUIRE(0 ==y1); REQUIRE(1 ==x1); REQUIRE(true ==contents.waiting_for_desired); REQUIRE(6 ==contents.desired_x); } TEST_CASE("mvd_2") { contents contents; contents.push_back("CFLAGS=-lncurses -Wall"); contents.push_back("O=out"); contents.push_back("S=src"); contents.push_back("T=test"); initscr(); mveol(contents); int y = contents.y, x = contents.x; mvd(contents); int y1 = contents.y, x1 = contents.x; int d1 = contents.desired_x; bool w1 = contents.waiting_for_desired; mvd(contents); int y2 = contents.y, x2 = contents.x; int d2 = contents.desired_x; bool w2 = contents.waiting_for_desired; endwin(); REQUIRE(0 ==y); REQUIRE(21 ==x); REQUIRE(1 ==y1); REQUIRE(4 ==x1); REQUIRE(21 ==d1); REQUIRE(true ==w1); REQUIRE(2 ==y2); REQUIRE(4 ==x2); REQUIRE(21 ==d2); REQUIRE(true ==w2); } TEST_CASE("mvf_over_empty_lines") { contents contents (0,1); contents.push_back("hi"); contents.push_back(""); contents.push_back("hi"); initscr(); mvf(contents); endwin(); REQUIRE(0 ==contents.x); REQUIRE(1 ==contents.y); } TEST_CASE("mvf_over_tabs") { contents contents (0,25); contents.push_back("testVI: ${files} $O/main.o"); contents.push_back("\t${CC} -o testVI $^ $(CFLAGS)"); initscr(); mvf(contents); int vis_y,vis_x,y,x; getyx(stdscr,vis_y,vis_x); y = contents.y; x = contents.x; mvf(contents); int vis_y1,vis_x1,y1,x1; getyx(stdscr,vis_y1,vis_x1); y1= contents.y; x1= contents.x; endwin(); REQUIRE(1 ==y); REQUIRE(0 ==x); REQUIRE(1 ==vis_y); REQUIRE(7 ==vis_x); REQUIRE(1 ==y1); REQUIRE(1 ==x1); REQUIRE(1 ==vis_y1); REQUIRE(8 ==vis_x1); } TEST_CASE("to_visual") { std::string first("assert"), second("\tblah"); for(int i = 0; i < first.size(); i++) REQUIRE(i == to_visual(first,i)); for(int i = 0; i < second.size(); i++) REQUIRE(TAB_SIZE() - 1 + i == to_visual(second,i)); } TEST_CASE("from_visual") { std::string first("\thi"), second("\t\thi"); for(int i = 1; i < TAB_SIZE() - 1; i++) { if(0 != from_visual(first,TAB_SIZE() - i)) std::cout << i << std::endl; REQUIRE(0 == from_visual(first, TAB_SIZE() - i)); } REQUIRE(0 == from_visual(first,TAB_SIZE() - 1)); REQUIRE(1 == from_visual(first,TAB_SIZE())); REQUIRE(2 == from_visual(first,TAB_SIZE() + 1)); } <commit_msg>Fix tests<commit_after>#include <iostream> #include <ncurses.h> #include "../src/newmove.hh" #include "../src/configuration.hh" #include "catch.hpp" TEST_CASE("mvsot") { contents contents; contents.push_back(" hello"); initscr(); mvsot(contents); endwin(); REQUIRE(0 == contents.y); REQUIRE(4 == contents.x); } TEST_CASE("mvcol") { contents contents; contents.push_back("asert"); initscr(); mvcol(contents,3); int y1 = contents.y, x1 = contents.x; mvcol(contents,10); //doesn't do anything int y2 = contents.y, x2 = contents.x; mvcol(contents,0); int y3 = contents.y, x3 = contents.x; endwin(); REQUIRE(0 == y1); REQUIRE(0 == y2); REQUIRE(0 == y3); REQUIRE(3 == x1); REQUIRE(3 == x2); REQUIRE(0 == x3); } TEST_CASE("mvsol") { contents contents (0,5); contents.push_back(" assert"); initscr(); mvsol(contents); int y = contents.y, x = contents.x; endwin(); REQUIRE(0 == y); REQUIRE(0 == x); } TEST_CASE("mvd") { contents contents; contents.push_back("assert"); contents.push_back("hello"); contents.push_back("aseuirpo"); initscr(); mvd(contents,2); int y = contents.y, x = contents.x; mvd(contents); int y1 = contents.y, x1 = contents.x; endwin(); REQUIRE(0 == x); REQUIRE(0 == x1); REQUIRE(2 == y); REQUIRE(2 == y1); } TEST_CASE("mvf") { contents contents; contents.push_back("assert"); contents.push_back("hello"); initscr(); mvf(contents,3); int y = contents.y, x = contents.x; mvf(contents,4); int y1 = contents.y, x1 = contents.x; endwin(); REQUIRE(0 == y); REQUIRE(3 == x); REQUIRE(1 == y1); REQUIRE(1 == x1); } TEST_CASE("mvb") { contents contents (1,0); contents.push_back("assert"); contents.push_back("back"); initscr(); mvb(contents,2); int y = contents.y, x = contents.x; endwin(); REQUIRE(0 == y); REQUIRE(4 == x); } TEST_CASE("mvf_2") { contents contents; contents.push_back("CFLAGS=-lncurses -Wall"); contents.push_back("O=out"); contents.push_back("S=src"); contents.push_back("T=test"); contents.push_back("TO=testout"); contents.push_back("CC=g++"); initscr(); mveol(contents); int y = contents.y, x = contents.x; mvf(contents,2); int y1 = contents.y, x1 = contents.x; endwin(); REQUIRE(0 == y); REQUIRE(21 == x); REQUIRE(1 == y1); REQUIRE(1 == x1); } TEST_CASE("mveol") { contents contents; contents.push_back("Aesop"); initscr(); mveol(contents); int y = contents.y, x = contents.x; endwin(); REQUIRE(4 == x); REQUIRE(0 == y); } TEST_CASE("mvu") { contents contents (1,6); contents.push_back("hi"); contents.push_back("Alabama"); initscr(); mvu(contents); int y1 = contents.y, x1 = contents.x; endwin(); REQUIRE(0 == y1); REQUIRE(1 == x1); REQUIRE(true == contents.waiting_for_desired); REQUIRE(6 == contents.desired_x); } TEST_CASE("mvd_2") { contents contents; contents.push_back("CFLAGS=-lncurses -Wall"); contents.push_back("O=out"); contents.push_back("S=src"); contents.push_back("T=test"); initscr(); mveol(contents); int y = contents.y, x = contents.x; mvd(contents); int y1 = contents.y, x1 = contents.x; int d1 = contents.desired_x; bool w1 = contents.waiting_for_desired; mvd(contents); int y2 = contents.y, x2 = contents.x; int d2 = contents.desired_x; bool w2 = contents.waiting_for_desired; endwin(); REQUIRE(0 == y); REQUIRE(21 == x); REQUIRE(1 == y1); REQUIRE(4 == x1); REQUIRE(21 == d1); REQUIRE(true == w1); REQUIRE(2 == y2); REQUIRE(4 == x2); REQUIRE(21 == d2); REQUIRE(true == w2); } TEST_CASE("mvf_over_empty_lines") { contents contents (0,1); contents.push_back("hi"); contents.push_back(""); contents.push_back("hi"); initscr(); mvf(contents); endwin(); REQUIRE(0 == contents.x); REQUIRE(1 == contents.y); } TEST_CASE("mvf_over_tabs") { contents contents (0,25); contents.push_back("testVI: ${files} $O/main.o"); contents.push_back("\t${CC} -o testVI $^ $(CFLAGS)"); initscr(); mvf(contents); int y,x; y = contents.y; x = contents.x; mvf(contents); int y1,x1; y1= contents.y; x1= contents.x; endwin(); REQUIRE(1 == y); REQUIRE(0 == x); REQUIRE(1 == y1); REQUIRE(1 == x1); } TEST_CASE("to_visual") { std::string first("assert"), second("\tblah"); for(int i = 0; i < first.size(); i++) REQUIRE(i == to_visual(first,i)); for(int i = 0; i < second.size(); i++) REQUIRE(TAB_SIZE() - 1 + i == to_visual(second,i)); } TEST_CASE("from_visual") { std::string first("\thi"), second("\t\thi"); for(int i = 1; i < TAB_SIZE() - 1; i++) { if(0 != from_visual(first,TAB_SIZE() - i)) std::cout << i << std::endl; REQUIRE(0 == from_visual(first, TAB_SIZE() - i)); } REQUIRE(0 == from_visual(first,TAB_SIZE() - 1)); REQUIRE(1 == from_visual(first,TAB_SIZE())); REQUIRE(2 == from_visual(first,TAB_SIZE() + 1)); } <|endoftext|>
<commit_before>/* * KENLM.cpp * * Created on: 4 Nov 2015 * Author: hieu */ #include <sstream> #include <vector> #include "KENLM.h" #include "../TargetPhrase.h" #include "../Scores.h" #include "../System.h" #include "../Search/Hypothesis.h" #include "../Search/Manager.h" #include "lm/state.hh" #include "lm/left.hh" #include "../legacy/FactorCollection.h" using namespace std; namespace Moses2 { struct KenLMState : public FFState { const lm::ngram::State *state; virtual size_t hash() const { return (size_t) state; } virtual bool operator==(const FFState& o) const { const KenLMState &other = static_cast<const KenLMState &>(o); bool ret = state == other.state; return ret; } virtual std::string ToString() const { stringstream ss; for (size_t i = 0; i < state->Length(); ++i) { ss << state->words[i] << " "; } return ss.str(); } }; ///////////////////////////////////////////////////////////////// class MappingBuilder : public lm::EnumerateVocab { public: MappingBuilder(FactorCollection &factorCollection, System &system, std::vector<lm::WordIndex> &mapping) : m_factorCollection(factorCollection) , m_system(system) , m_mapping(mapping) {} void Add(lm::WordIndex index, const StringPiece &str) { std::size_t factorId = m_factorCollection.AddFactor(str, m_system)->GetId(); if (m_mapping.size() <= factorId) { // 0 is <unk> :-) m_mapping.resize(factorId + 1); } m_mapping[factorId] = index; } private: FactorCollection &m_factorCollection; std::vector<lm::WordIndex> &m_mapping; System &m_system; }; ///////////////////////////////////////////////////////////////// KENLM::KENLM(size_t startInd, const std::string &line) :StatefulFeatureFunction(startInd, line) ,m_lazy(false) { ReadParameters(); } KENLM::~KENLM() { // TODO Auto-generated destructor stub } void KENLM::Load(System &system) { FactorCollection &fc = system.GetVocab(); m_bos = fc.AddFactor(BOS_, system, false); m_eos = fc.AddFactor(EOS_, system, false); lm::ngram::Config config; config.messages = NULL; FactorCollection &collection = system.GetVocab(); MappingBuilder builder(collection, system, m_lmIdLookup); config.enumerate_vocab = &builder; config.load_method = m_lazy ? util::LAZY : util::POPULATE_OR_READ; m_ngram.reset(new Model(m_path.c_str(), config)); } void KENLM::InitializeForInput(const Manager &mgr) const { CacheColl &cache = GetCache(); cache.clear(); mgr.lmCache = &cache; } // clean up temporary memory, called after processing each sentence void KENLM::CleanUpAfterSentenceProcessing(const Manager &mgr) const { } void KENLM::SetParameter(const std::string& key, const std::string& value) { if (key == "path") { m_path = value; } else if (key == "factor") { m_factorType = Scan<FactorType>(value); } else if (key == "lazyken") { m_lazy = Scan<bool>(value); } else if (key == "order") { // don't need to store it } else { StatefulFeatureFunction::SetParameter(key, value); } } FFState* KENLM::BlankState(MemPool &pool) const { KenLMState *ret = new (pool.Allocate<KenLMState>()) KenLMState(); return ret; } //! return the state associated with the empty hypothesis for a given sentence void KENLM::EmptyHypothesisState(FFState &state, const Manager &mgr, const InputType &input, const Hypothesis &hypo) const { KenLMState &stateCast = static_cast<KenLMState&>(state); stateCast.state = &m_ngram->BeginSentenceState(); } void KENLM::EvaluateInIsolation(MemPool &pool, const System &system, const Phrase &source, const TargetPhrase &targetPhrase, Scores &scores, SCORE *estimatedScore) const { // contains factors used by this LM float fullScore, nGramScore; size_t oovCount; CalcScore(targetPhrase, fullScore, nGramScore, oovCount); float estimateScore = fullScore - nGramScore; bool GetLMEnableOOVFeature = false; if (GetLMEnableOOVFeature) { float scoresVec[2], estimateScoresVec[2]; scoresVec[0] = nGramScore; scoresVec[1] = oovCount; scores.PlusEquals(system, *this, scoresVec); estimateScoresVec[0] = estimateScore; estimateScoresVec[1] = 0; SCORE weightedScore = Scores::CalcWeightedScore(system, *this, estimateScoresVec); (*estimatedScore) += weightedScore; } else { scores.PlusEquals(system, *this, nGramScore); SCORE weightedScore = Scores::CalcWeightedScore(system, *this, estimateScore); (*estimatedScore) += weightedScore; } } void KENLM::EvaluateWhenApplied(const Manager &mgr, const Hypothesis &hypo, const FFState &prevState, Scores &scores, FFState &state) const { MemPool &pool = mgr.GetPool(); KenLMState &stateCast = static_cast<KenLMState&>(state); const System &system = mgr.system; const lm::ngram::State *in_state = static_cast<const KenLMState&>(prevState).state; if (!hypo.GetTargetPhrase().GetSize()) { stateCast.state = in_state; return; } const std::size_t begin = hypo.GetCurrTargetWordsRange().GetStartPos(); //[begin, end) in STL-like fashion. const std::size_t end = hypo.GetCurrTargetWordsRange().GetEndPos() + 1; const std::size_t adjust_end = std::min(end, begin + m_ngram->Order() - 1); std::size_t position = begin; typename Model::State aux_state; const Model::State *state0 = stateCast.state; const Model::State *state1 = &aux_state; const LMCacheValue &val = ScoreAndCache(mgr, *in_state, TranslateID(hypo.GetWord(position))); float score = val.first; state0 = val.second; ++position; for (; position < adjust_end; ++position) { const LMCacheValue &val = ScoreAndCache(mgr, *state0, TranslateID(hypo.GetWord(position))); score += val.first; state1 = val.second; std::swap(state0, state1); } if (hypo.GetBitmap().IsComplete()) { // Score end of sentence. std::vector<lm::WordIndex> indices(m_ngram->Order() - 1); const lm::WordIndex *last = LastIDs(hypo, &indices.front()); lm::ngram::State *newState = new (pool.Allocate<lm::ngram::State>()) lm::ngram::State(); score += m_ngram->FullScoreForgotState(&indices.front(), last, m_ngram->GetVocabulary().EndSentence(), *newState).prob; stateCast.state = newState; } else if (adjust_end < end) { // Get state after adding a long phrase. std::vector<lm::WordIndex> indices(m_ngram->Order() - 1); const lm::WordIndex *last = LastIDs(hypo, &indices.front()); lm::ngram::State *newState = new (pool.Allocate<lm::ngram::State>()) lm::ngram::State(); m_ngram->GetState(&indices.front(), last, *newState); stateCast.state = newState; } else { // Short enough phrase that we can just reuse the state. stateCast.state = state0; } score = TransformLMScore(score); bool OOVFeatureEnabled = false; if (OOVFeatureEnabled) { std::vector<float> scoresVec(2); scoresVec[0] = score; scoresVec[1] = 0.0; scores.PlusEquals(system, *this, scoresVec); } else { scores.PlusEquals(system, *this, score); } } void KENLM::CalcScore(const Phrase &phrase, float &fullScore, float &ngramScore, std::size_t &oovCount) const { fullScore = 0; ngramScore = 0; oovCount = 0; if (!phrase.GetSize()) return; lm::ngram::ChartState discarded_sadly; lm::ngram::RuleScore<Model> scorer(*m_ngram, discarded_sadly); size_t position; if (m_bos == phrase[0][m_factorType]) { scorer.BeginSentence(); position = 1; } else { position = 0; } size_t ngramBoundary = m_ngram->Order() - 1; size_t end_loop = std::min(ngramBoundary, phrase.GetSize()); for (; position < end_loop; ++position) { const Word &word = phrase[position]; lm::WordIndex index = TranslateID(word); scorer.Terminal(index); if (!index) ++oovCount; } float before_boundary = fullScore + scorer.Finish(); for (; position < phrase.GetSize(); ++position) { const Word &word = phrase[position]; lm::WordIndex index = TranslateID(word); scorer.Terminal(index); if (!index) ++oovCount; } fullScore += scorer.Finish(); ngramScore = TransformLMScore(fullScore - before_boundary); fullScore = TransformLMScore(fullScore); } // Convert last words of hypothesis into vocab ids, returning an end pointer. lm::WordIndex *KENLM::LastIDs(const Hypothesis &hypo, lm::WordIndex *indices) const { lm::WordIndex *index = indices; lm::WordIndex *end = indices + m_ngram->Order() - 1; int position = hypo.GetCurrTargetWordsRange().GetEndPos(); for (; ; ++index, --position) { if (index == end) return index; if (position == -1) { *index = m_ngram->GetVocabulary().BeginSentence(); return index + 1; } *index = TranslateID(hypo.GetWord(position)); } } const KENLM::LMCacheValue &KENLM::ScoreAndCache(const Manager &mgr, const lm::ngram::State &in_state, const lm::WordIndex new_word) const { MemPool &pool = mgr.GetPool(); //cerr << "score="; LMCacheValue *val; CacheColl &lmCache = *((CacheColl*)mgr.lmCache); LMCacheKey key(&in_state, new_word); CacheColl::iterator iter; iter = lmCache.find(key); if (iter == lmCache.end()) { lm::ngram::State *newState = new (pool.Allocate<lm::ngram::State>()) lm::ngram::State(); float score = m_ngram->Score(in_state, new_word, *newState); val = &lmCache[key]; val->first = score; val->second = newState; } else { val = &iter->second; } //cerr << score << " " << (int) out_state.length << endl; return *val; } KENLM::CacheColl &KENLM::GetCache() const { return GetThreadSpecificObj(m_cache); } } <commit_msg>cleanup<commit_after>/* * KENLM.cpp * * Created on: 4 Nov 2015 * Author: hieu */ #include <sstream> #include <vector> #include "KENLM.h" #include "../TargetPhrase.h" #include "../Scores.h" #include "../System.h" #include "../Search/Hypothesis.h" #include "../Search/Manager.h" #include "lm/state.hh" #include "lm/left.hh" #include "../legacy/FactorCollection.h" using namespace std; namespace Moses2 { struct KenLMState : public FFState { const lm::ngram::State *state; virtual size_t hash() const { return (size_t) state; } virtual bool operator==(const FFState& o) const { const KenLMState &other = static_cast<const KenLMState &>(o); bool ret = state == other.state; return ret; } virtual std::string ToString() const { stringstream ss; for (size_t i = 0; i < state->Length(); ++i) { ss << state->words[i] << " "; } return ss.str(); } }; ///////////////////////////////////////////////////////////////// class MappingBuilder : public lm::EnumerateVocab { public: MappingBuilder(FactorCollection &factorCollection, System &system, std::vector<lm::WordIndex> &mapping) : m_factorCollection(factorCollection) , m_system(system) , m_mapping(mapping) {} void Add(lm::WordIndex index, const StringPiece &str) { std::size_t factorId = m_factorCollection.AddFactor(str, m_system)->GetId(); if (m_mapping.size() <= factorId) { // 0 is <unk> :-) m_mapping.resize(factorId + 1); } m_mapping[factorId] = index; } private: FactorCollection &m_factorCollection; std::vector<lm::WordIndex> &m_mapping; System &m_system; }; ///////////////////////////////////////////////////////////////// KENLM::KENLM(size_t startInd, const std::string &line) :StatefulFeatureFunction(startInd, line) ,m_lazy(false) { ReadParameters(); } KENLM::~KENLM() { // TODO Auto-generated destructor stub } void KENLM::Load(System &system) { FactorCollection &fc = system.GetVocab(); m_bos = fc.AddFactor(BOS_, system, false); m_eos = fc.AddFactor(EOS_, system, false); lm::ngram::Config config; config.messages = NULL; FactorCollection &collection = system.GetVocab(); MappingBuilder builder(collection, system, m_lmIdLookup); config.enumerate_vocab = &builder; config.load_method = m_lazy ? util::LAZY : util::POPULATE_OR_READ; m_ngram.reset(new Model(m_path.c_str(), config)); } void KENLM::InitializeForInput(const Manager &mgr) const { CacheColl &cache = GetCache(); cache.clear(); mgr.lmCache = &cache; } // clean up temporary memory, called after processing each sentence void KENLM::CleanUpAfterSentenceProcessing(const Manager &mgr) const { } void KENLM::SetParameter(const std::string& key, const std::string& value) { if (key == "path") { m_path = value; } else if (key == "factor") { m_factorType = Scan<FactorType>(value); } else if (key == "lazyken") { m_lazy = Scan<bool>(value); } else if (key == "order") { // don't need to store it } else { StatefulFeatureFunction::SetParameter(key, value); } } FFState* KENLM::BlankState(MemPool &pool) const { KenLMState *ret = new (pool.Allocate<KenLMState>()) KenLMState(); return ret; } //! return the state associated with the empty hypothesis for a given sentence void KENLM::EmptyHypothesisState(FFState &state, const Manager &mgr, const InputType &input, const Hypothesis &hypo) const { KenLMState &stateCast = static_cast<KenLMState&>(state); stateCast.state = &m_ngram->BeginSentenceState(); } void KENLM::EvaluateInIsolation(MemPool &pool, const System &system, const Phrase &source, const TargetPhrase &targetPhrase, Scores &scores, SCORE *estimatedScore) const { // contains factors used by this LM float fullScore, nGramScore; size_t oovCount; CalcScore(targetPhrase, fullScore, nGramScore, oovCount); float estimateScore = fullScore - nGramScore; bool GetLMEnableOOVFeature = false; if (GetLMEnableOOVFeature) { float scoresVec[2], estimateScoresVec[2]; scoresVec[0] = nGramScore; scoresVec[1] = oovCount; scores.PlusEquals(system, *this, scoresVec); estimateScoresVec[0] = estimateScore; estimateScoresVec[1] = 0; SCORE weightedScore = Scores::CalcWeightedScore(system, *this, estimateScoresVec); (*estimatedScore) += weightedScore; } else { scores.PlusEquals(system, *this, nGramScore); SCORE weightedScore = Scores::CalcWeightedScore(system, *this, estimateScore); (*estimatedScore) += weightedScore; } } void KENLM::EvaluateWhenApplied(const Manager &mgr, const Hypothesis &hypo, const FFState &prevState, Scores &scores, FFState &state) const { MemPool &pool = mgr.GetPool(); KenLMState &stateCast = static_cast<KenLMState&>(state); const System &system = mgr.system; const lm::ngram::State *in_state = static_cast<const KenLMState&>(prevState).state; if (!hypo.GetTargetPhrase().GetSize()) { stateCast.state = in_state; return; } const std::size_t begin = hypo.GetCurrTargetWordsRange().GetStartPos(); //[begin, end) in STL-like fashion. const std::size_t end = hypo.GetCurrTargetWordsRange().GetEndPos() + 1; const std::size_t adjust_end = std::min(end, begin + m_ngram->Order() - 1); std::size_t position = begin; const Model::State *state0 = stateCast.state; const Model::State *state1; const LMCacheValue &val = ScoreAndCache(mgr, *in_state, TranslateID(hypo.GetWord(position))); float score = val.first; state0 = val.second; ++position; for (; position < adjust_end; ++position) { const LMCacheValue &val = ScoreAndCache(mgr, *state0, TranslateID(hypo.GetWord(position))); score += val.first; state1 = val.second; std::swap(state0, state1); } if (hypo.GetBitmap().IsComplete()) { // Score end of sentence. std::vector<lm::WordIndex> indices(m_ngram->Order() - 1); const lm::WordIndex *last = LastIDs(hypo, &indices.front()); lm::ngram::State *newState = new (pool.Allocate<lm::ngram::State>()) lm::ngram::State(); score += m_ngram->FullScoreForgotState(&indices.front(), last, m_ngram->GetVocabulary().EndSentence(), *newState).prob; stateCast.state = newState; } else if (adjust_end < end) { // Get state after adding a long phrase. std::vector<lm::WordIndex> indices(m_ngram->Order() - 1); const lm::WordIndex *last = LastIDs(hypo, &indices.front()); lm::ngram::State *newState = new (pool.Allocate<lm::ngram::State>()) lm::ngram::State(); m_ngram->GetState(&indices.front(), last, *newState); stateCast.state = newState; } else { // Short enough phrase that we can just reuse the state. stateCast.state = state0; } score = TransformLMScore(score); bool OOVFeatureEnabled = false; if (OOVFeatureEnabled) { std::vector<float> scoresVec(2); scoresVec[0] = score; scoresVec[1] = 0.0; scores.PlusEquals(system, *this, scoresVec); } else { scores.PlusEquals(system, *this, score); } } void KENLM::CalcScore(const Phrase &phrase, float &fullScore, float &ngramScore, std::size_t &oovCount) const { fullScore = 0; ngramScore = 0; oovCount = 0; if (!phrase.GetSize()) return; lm::ngram::ChartState discarded_sadly; lm::ngram::RuleScore<Model> scorer(*m_ngram, discarded_sadly); size_t position; if (m_bos == phrase[0][m_factorType]) { scorer.BeginSentence(); position = 1; } else { position = 0; } size_t ngramBoundary = m_ngram->Order() - 1; size_t end_loop = std::min(ngramBoundary, phrase.GetSize()); for (; position < end_loop; ++position) { const Word &word = phrase[position]; lm::WordIndex index = TranslateID(word); scorer.Terminal(index); if (!index) ++oovCount; } float before_boundary = fullScore + scorer.Finish(); for (; position < phrase.GetSize(); ++position) { const Word &word = phrase[position]; lm::WordIndex index = TranslateID(word); scorer.Terminal(index); if (!index) ++oovCount; } fullScore += scorer.Finish(); ngramScore = TransformLMScore(fullScore - before_boundary); fullScore = TransformLMScore(fullScore); } // Convert last words of hypothesis into vocab ids, returning an end pointer. lm::WordIndex *KENLM::LastIDs(const Hypothesis &hypo, lm::WordIndex *indices) const { lm::WordIndex *index = indices; lm::WordIndex *end = indices + m_ngram->Order() - 1; int position = hypo.GetCurrTargetWordsRange().GetEndPos(); for (; ; ++index, --position) { if (index == end) return index; if (position == -1) { *index = m_ngram->GetVocabulary().BeginSentence(); return index + 1; } *index = TranslateID(hypo.GetWord(position)); } } const KENLM::LMCacheValue &KENLM::ScoreAndCache(const Manager &mgr, const lm::ngram::State &in_state, const lm::WordIndex new_word) const { MemPool &pool = mgr.GetPool(); //cerr << "score="; LMCacheValue *val; CacheColl &lmCache = *((CacheColl*)mgr.lmCache); LMCacheKey key(&in_state, new_word); CacheColl::iterator iter; iter = lmCache.find(key); if (iter == lmCache.end()) { lm::ngram::State *newState = new (pool.Allocate<lm::ngram::State>()) lm::ngram::State(); float score = m_ngram->Score(in_state, new_word, *newState); val = &lmCache[key]; val->first = score; val->second = newState; } else { val = &iter->second; } //cerr << score << " " << (int) out_state.length << endl; return *val; } KENLM::CacheColl &KENLM::GetCache() const { return GetThreadSpecificObj(m_cache); } } <|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010-2021 Belledonne Communications SARL, All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <string> #include <flexisip/logmanager.hh> #include "firebase-client.hh" #include "utils/string-formater.hh" #include "firebase-request.hh" using namespace std; namespace flexisip { namespace pushnotification { // redundant declaration (required for C++14 compatibility) constexpr int FirebaseRequest::FIREBASE_MAX_TTL; FirebaseRequest::FirebaseRequest(const PushInfo& pinfo) : Request(pinfo.mAppId, "firebase") { const string& from = pinfo.mFromName.empty() ? pinfo.mFromUri : pinfo.mFromName; auto ttl = min(pinfo.mTtl, FIREBASE_MAX_TTL); // clang-format off StringFormater strFormatter( R"json({ "to":"@to@", "time_to_live": @ttl@, "priority":"high", "data":{ "uuid":"@uuid@", "from-uri":"@from-uri@", "display-name":"@display-name@", "call-id":"@call-id@", "sip-from":"@sip-from@", "loc-key":"@loc-key@", "loc-args":"@loc-args@", "send-time":"@send-time@" } })json", '@', '@'); std::map<std::string, std::string> values = { {"to", pinfo.mDeviceToken}, {"ttl", to_string(ttl)}, {"uuid", pinfo.mUid}, {"from-uri", pinfo.mFromUri}, {"display-name", pinfo.mFromName}, {"call-id", pinfo.mCallId}, {"sip-from", from}, {"loc-key", pinfo.mAlertMsgId}, {"loc-args", from}, {"send-time", getPushTimeStamp()} }; // clang-format on auto formatedBody = strFormatter.format(values); mBody.assign(formatedBody.begin(), formatedBody.end()); SLOGD << "Firebase request creation " << this << " payload is :\n" << formatedBody; HttpHeaders headers{}; headers.add(":method", "POST"); headers.add(":scheme", "https"); headers.add(":path", "/fcm/send"); headers.add(":authority", string(FirebaseClient::FIREBASE_ADDRESS) + ":" + string(FirebaseClient::FIREBASE_PORT)); headers.add("content-type", "application/json"); headers.add("authorization", "key=" + pinfo.mApiKey); this->setHeaders(headers); SLOGD << "Firebase request creation " << this << " https headers are :\n" << headers.toString(); } } // namespace pushnotification } // namespace flexisip <commit_msg>Remove double-quotes from the UID before inserting into Firebase PNR body<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010-2021 Belledonne Communications SARL, All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <string> #include "flexisip/logmanager.hh" #include "firebase-client.hh" #include "utils/string-formater.hh" #include "utils/string-utils.hh" #include "firebase-request.hh" using namespace std; namespace flexisip { namespace pushnotification { // redundant declaration (required for C++14 compatibility) constexpr int FirebaseRequest::FIREBASE_MAX_TTL; FirebaseRequest::FirebaseRequest(const PushInfo& pinfo) : Request(pinfo.mAppId, "firebase") { const string& from = pinfo.mFromName.empty() ? pinfo.mFromUri : pinfo.mFromName; auto ttl = min(pinfo.mTtl, FIREBASE_MAX_TTL); // clang-format off StringFormater strFormatter( R"json({ "to":"@to@", "time_to_live": @ttl@, "priority":"high", "data":{ "uuid":"@uuid@", "from-uri":"@from-uri@", "display-name":"@display-name@", "call-id":"@call-id@", "sip-from":"@sip-from@", "loc-key":"@loc-key@", "loc-args":"@loc-args@", "send-time":"@send-time@" } })json", '@', '@'); std::map<std::string, std::string> values = { {"to", pinfo.mDeviceToken}, {"ttl", to_string(ttl)}, {"uuid", StringUtils::unquote(pinfo.mUid)}, {"from-uri", pinfo.mFromUri}, {"display-name", pinfo.mFromName}, {"call-id", pinfo.mCallId}, {"sip-from", from}, {"loc-key", pinfo.mAlertMsgId}, {"loc-args", from}, {"send-time", getPushTimeStamp()} }; // clang-format on auto formatedBody = strFormatter.format(values); mBody.assign(formatedBody.begin(), formatedBody.end()); SLOGD << "Firebase request creation " << this << " payload is :\n" << formatedBody; HttpHeaders headers{}; headers.add(":method", "POST"); headers.add(":scheme", "https"); headers.add(":path", "/fcm/send"); headers.add(":authority", string(FirebaseClient::FIREBASE_ADDRESS) + ":" + string(FirebaseClient::FIREBASE_PORT)); headers.add("content-type", "application/json"); headers.add("authorization", "key=" + pinfo.mApiKey); this->setHeaders(headers); SLOGD << "Firebase request creation " << this << " https headers are :\n" << headers.toString(); } } // namespace pushnotification } // namespace flexisip <|endoftext|>
<commit_before>//===-- CodeGen/AsmPrinter/Win64Exception.cpp - Dwarf Exception Impl ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains support for writing Win64 exception info into asm files. // //===----------------------------------------------------------------------===// #include "DwarfException.h" #include "llvm/Module.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineLocation.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Target/Mangler.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormattedStream.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" using namespace llvm; Win64Exception::Win64Exception(AsmPrinter *A) : DwarfException(A), shouldEmitPersonality(false), shouldEmitLSDA(false), shouldEmitMoves(false) {} Win64Exception::~Win64Exception() {} /// EndModule - Emit all exception information that should come after the /// content. void Win64Exception::EndModule() { } /// BeginFunction - Gather pre-function exception information. Assumes it's /// being emitted immediately after the function entry point. void Win64Exception::BeginFunction(const MachineFunction *MF) { shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false; // If any landing pads survive, we need an EH table. bool hasLandingPads = !MMI->getLandingPads().empty(); shouldEmitMoves = Asm->needsSEHMoves(); const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); unsigned PerEncoding = TLOF.getPersonalityEncoding(); const Function *Per = MMI->getPersonalities()[MMI->getPersonalityIndex()]; shouldEmitPersonality = hasLandingPads && PerEncoding != dwarf::DW_EH_PE_omit && Per; unsigned LSDAEncoding = TLOF.getLSDAEncoding(); shouldEmitLSDA = shouldEmitPersonality && LSDAEncoding != dwarf::DW_EH_PE_omit; if (!shouldEmitPersonality && !shouldEmitMoves) return; Asm->OutStreamer.EmitWin64EHStartProc(Asm->CurrentFnSym); if (!shouldEmitPersonality) return; MCSymbol *GCCHandlerSym = Asm->GetExternalSymbolSymbol("_GCC_specific_handler"); Asm->OutStreamer.EmitWin64EHHandler(GCCHandlerSym, true, true); } /// EndFunction - Gather and emit post-function exception information. /// void Win64Exception::EndFunction() { if (!shouldEmitPersonality && !shouldEmitMoves) return; Asm->OutStreamer.EmitWin64EHEndProc(); } <commit_msg>Emit the handler's data area. For GCC-style exceptions under Win64, the handler's data area starts with a 4-byte reference to the personality function, followed by the DWARF LSDA.<commit_after>//===-- CodeGen/AsmPrinter/Win64Exception.cpp - Dwarf Exception Impl ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains support for writing Win64 exception info into asm files. // //===----------------------------------------------------------------------===// #include "DwarfException.h" #include "llvm/Module.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineLocation.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Target/Mangler.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormattedStream.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" using namespace llvm; Win64Exception::Win64Exception(AsmPrinter *A) : DwarfException(A), shouldEmitPersonality(false), shouldEmitLSDA(false), shouldEmitMoves(false) {} Win64Exception::~Win64Exception() {} /// EndModule - Emit all exception information that should come after the /// content. void Win64Exception::EndModule() { } /// BeginFunction - Gather pre-function exception information. Assumes it's /// being emitted immediately after the function entry point. void Win64Exception::BeginFunction(const MachineFunction *MF) { shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false; // If any landing pads survive, we need an EH table. bool hasLandingPads = !MMI->getLandingPads().empty(); shouldEmitMoves = Asm->needsSEHMoves(); const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); unsigned PerEncoding = TLOF.getPersonalityEncoding(); const Function *Per = MMI->getPersonalities()[MMI->getPersonalityIndex()]; shouldEmitPersonality = hasLandingPads && PerEncoding != dwarf::DW_EH_PE_omit && Per; unsigned LSDAEncoding = TLOF.getLSDAEncoding(); shouldEmitLSDA = shouldEmitPersonality && LSDAEncoding != dwarf::DW_EH_PE_omit; if (!shouldEmitPersonality && !shouldEmitMoves) return; Asm->OutStreamer.EmitWin64EHStartProc(Asm->CurrentFnSym); if (!shouldEmitPersonality) return; MCSymbol *GCCHandlerSym = Asm->GetExternalSymbolSymbol("_GCC_specific_handler"); Asm->OutStreamer.EmitWin64EHHandler(GCCHandlerSym, true, true); Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_begin", Asm->getFunctionNumber())); } /// EndFunction - Gather and emit post-function exception information. /// void Win64Exception::EndFunction() { if (!shouldEmitPersonality && !shouldEmitMoves) return; Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_end", Asm->getFunctionNumber())); // Map all labels and get rid of any dead landing pads. MMI->TidyLandingPads(); if (shouldEmitPersonality) { const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); const Function *Per = MMI->getPersonalities()[MMI->getPersonalityIndex()]; const MCSymbol *Sym = TLOF.getCFIPersonalitySymbol(Per, Asm->Mang, MMI); Asm->OutStreamer.PushSection(); Asm->OutStreamer.EmitWin64EHHandlerData(); Asm->OutStreamer.EmitValue(MCSymbolRefExpr::Create(Sym, Asm->OutContext), 4); EmitExceptionTable(); Asm->OutStreamer.PopSection(); } Asm->OutStreamer.EmitWin64EHEndProc(); } <|endoftext|>
<commit_before>// @(#)root/test:$Name: $:$Id: MainEvent.cxx,v 1.9 2001/02/09 10:24:46 brun Exp $ // Author: Rene Brun 19/01/97 //////////////////////////////////////////////////////////////////////// // // A simple example with a ROOT tree // ================================= // // This program creates : // - a ROOT file // - a tree // Additional arguments can be passed to the program to control the flow // of execution. (see comments describing the arguments in the code). // Event nevent comp split fill // All arguments are optional: Default is // Event 400 1 1 1 // // In this example, the tree consists of one single "super branch" // The statement ***tree->Branch("event", event, 64000,split);*** below // will parse the structure described in Event.h and will make // a new branch for each data member of the class if split is set to 1. // - 5 branches corresponding to the basic types fNtrack,fNseg,fNvertex // ,fFlag and fTemperature. // - 3 branches corresponding to the members of the subobject EventHeader. // - one branch for each data member of the class Track of TClonesArray. // - one branch for the object fH (histogram of class TH1F). // // if split = 0 only one single branch is created and the complete event // is serialized in one single buffer. // if comp = 0 no compression at all. // if comp = 1 event is compressed. // if comp = 2 same as 1. In addition branches with floats in the TClonesArray // are also compressed. // The 4th argument fill can be set to 0 if one wants to time // the percentage of time spent in creating the event structure and // not write the event in the file. // In this example, one loops over nevent events. // The branch "event" is created at the first event. // The branch address is set for all other events. // For each event, the event header is filled and ntrack tracks // are generated and added to the TClonesArray list. // For each event the event histogram is saved as well as the list // of all tracks. // // The number of events can be given as the first argument to the program. // By default 400 events are generated. // The compression option can be activated/deactivated via the second argument. // // ---Running/Linking instructions---- // This program consists of the following files and procedures. // - Event.h event class description // - Event.C event class implementation // - MainEvent.C the main program to demo this class might be used (this file) // - EventCint.C the CINT dictionary for the event and Track classes // this file is automatically generated by rootcint (see Makefile), // when the class definition in Event.h is modified. // // ---Analyzing the Event.root file with the interactive root // example of a simple session // Root > TFile f("Event.root") // Root > T.Draw("fNtrack") //histogram the number of tracks per event // Root > T.Draw("fPx") //histogram fPx for all tracks in all events // Root > T.Draw("fXfirst:fYfirst","fNtrack>600") // //scatter-plot for x versus y of first point of each track // Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram // // Look also in the same directory at the following macros: // - eventa.C an example how to read the tree // - eventb.C how to read events conditionally // //////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "TROOT.h" #include "TFile.h" #include "TNetFile.h" #include "TRandom.h" #include "TTree.h" #include "TBranch.h" #include "TClonesArray.h" #include "TStopwatch.h" #include "Event.h" //______________________________________________________________________________ int main(int argc, char **argv) { TROOT simple("simple","Example of creation of a tree"); Int_t nevent = 400; // by default create 400 events Int_t comp = 1; // by default file is compressed Int_t split = 1; // by default, split Event in sub branches Int_t write = 1; // by default the tree is filled Int_t hfill = 0; // by default histograms are not filled Int_t read = 0; Int_t arg4 = 1; Int_t arg5 = 600; //default number of tracks per event Int_t netf = 0; if (argc > 1) nevent = atoi(argv[1]); if (argc > 2) comp = atoi(argv[2]); if (argc > 3) split = atoi(argv[3]); if (argc > 4) arg4 = atoi(argv[4]); if (argc > 5) arg5 = atoi(argv[5]); if (arg4 == 0) { write = 0; hfill = 0; read = 1;} if (arg4 == 1) { write = 1; hfill = 0;} if (arg4 == 2) { write = 0; hfill = 0;} if (arg4 == 10) { write = 0; hfill = 1;} if (arg4 == 11) { write = 1; hfill = 1;} if (arg4 == 20) { write = 0; read = 1;} //read sequential if (arg4 == 25) { write = 0; read = 2;} //read random if (arg4 >= 30) { netf = 1; } //use TNetFile if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential if (arg4 == 35) { write = 0; read = 2;} //netfile + read random if (arg4 == 36) { write = 1; } //netfile + write sequential TFile *hfile; TTree *tree; Event *event = 0; // Fill event, header and tracks with some random numbers // Create a timer object to benchmark this loop TStopwatch timer; timer.Start(); Int_t nb = 0; Int_t ev; Int_t bufsize; Double_t told = 0; Double_t tnew = 0; Int_t printev = 100; if (arg5 < 100) printev = 1000; if (arg5 < 10) printev = 10000; Track::Class()->IgnoreTObjectStreamer(); Track::Class()->BypassStreamer(); // Read case if (read) { if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root"); hfile->UseCache(10); } else hfile = new TFile("Event.root"); tree = (TTree*)hfile->Get("T"); TBranch *branch = tree->GetBranch("event"); branch->SetAddress(&event); Int_t nentries = (Int_t)tree->GetEntries(); nevent = TMath::Max(nevent,nentries); if (read == 1) { //read sequential for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); told=tnew; timer.Continue(); } nb += tree->GetEntry(ev); //read complete event in memory } } else { //read random Int_t evrandom; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) cout<<"event="<<ev<<endl; evrandom = Int_t(nevent*gRandom->Rndm(1)); nb += tree->GetEntry(evrandom); //read complete event in memory } } } else { // Write case // Create a new ROOT binary machine independent file. // Note that this file may contain any kind of ROOT objects, histograms, // pictures, graphics objects, detector geometries, tracks, events, etc.. // This file is now becoming the current directory. if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file"); hfile->UseCache(10); } else hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file"); hfile->SetCompressionLevel(comp); // Create histogram to show write_time in function of time Float_t curtime = -0.5; Int_t ntime = nevent/printev; TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime); HistogramManager *hm = 0; if (hfill) { TDirectory *hdir = new TDirectory("histograms", "all histograms"); hm = new HistogramManager(hdir); } // Create a ROOT Tree and one superbranch TTree *tree = new TTree("T","An example of a ROOT tree"); tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written bufsize = 64000; if (split) bufsize /= 4; event = new Event(); TBranch *branch = tree->Branch("event", "Event", &event, bufsize,split); branch->SetAutoDelete(kFALSE); char etype[20]; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); htime->Fill(curtime,tnew-told); curtime += 1; told=tnew; timer.Continue(); } Float_t sigmat, sigmas; gRandom->Rannor(sigmat,sigmas); Int_t ntrack = Int_t(arg5 +arg5*sigmat/120.); Float_t random = gRandom->Rndm(1); sprintf(etype,"type%d",ev%5); event->SetType(etype); event->SetHeader(ev, 200, 960312, random); event->SetNseg(Int_t(10*ntrack+20*sigmas)); event->SetNvertex(Int_t(1+20*gRandom->Rndm())); event->SetFlag(UInt_t(random+0.5)); event->SetTemperature(random+20.); for(UChar_t m = 0; m < 10; m++) { event->SetMeasure(m, Int_t(gRandom->Gaus(m,m+1))); } for(UChar_t i0 = 0; i0 < 4; i0++) { for(UChar_t i1 = 0; i1 < 4; i1++) { event->SetMatrix(i0,i1,gRandom->Gaus(i0*i1,1)); } } // Create and Fill the Track objects for (Int_t t = 0; t < ntrack; t++) event->AddTrack(random); if (write) nb += tree->Fill(); //fill the tree if (hm) hm->Hfill(event); //fill histograms event->Clear(); } if (write) { hfile->Write(); tree->Print(); } } // Stop timer and print results timer.Stop(); Float_t mbytes = 0.000001*nb; Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); printf("\n%d events and %d bytes processed.\n",nevent,nb); printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime); if (read) { printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime); } else { printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4); printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime); //printf("file compression factor = %f\n",hfile.GetCompressionFactor()); } hfile->Close(); return 0; } <commit_msg>Remove call to Track::BypassStreamer. This is now the default behaviour for classes in a TClonesArray.<commit_after>// @(#)root/test:$Name: $:$Id: MainEvent.cxx,v 1.10 2001/02/09 17:01:52 brun Exp $ // Author: Rene Brun 19/01/97 //////////////////////////////////////////////////////////////////////// // // A simple example with a ROOT tree // ================================= // // This program creates : // - a ROOT file // - a tree // Additional arguments can be passed to the program to control the flow // of execution. (see comments describing the arguments in the code). // Event nevent comp split fill // All arguments are optional: Default is // Event 400 1 1 1 // // In this example, the tree consists of one single "super branch" // The statement ***tree->Branch("event", event, 64000,split);*** below // will parse the structure described in Event.h and will make // a new branch for each data member of the class if split is set to 1. // - 5 branches corresponding to the basic types fNtrack,fNseg,fNvertex // ,fFlag and fTemperature. // - 3 branches corresponding to the members of the subobject EventHeader. // - one branch for each data member of the class Track of TClonesArray. // - one branch for the object fH (histogram of class TH1F). // // if split = 0 only one single branch is created and the complete event // is serialized in one single buffer. // if comp = 0 no compression at all. // if comp = 1 event is compressed. // if comp = 2 same as 1. In addition branches with floats in the TClonesArray // are also compressed. // The 4th argument fill can be set to 0 if one wants to time // the percentage of time spent in creating the event structure and // not write the event in the file. // In this example, one loops over nevent events. // The branch "event" is created at the first event. // The branch address is set for all other events. // For each event, the event header is filled and ntrack tracks // are generated and added to the TClonesArray list. // For each event the event histogram is saved as well as the list // of all tracks. // // The number of events can be given as the first argument to the program. // By default 400 events are generated. // The compression option can be activated/deactivated via the second argument. // // ---Running/Linking instructions---- // This program consists of the following files and procedures. // - Event.h event class description // - Event.C event class implementation // - MainEvent.C the main program to demo this class might be used (this file) // - EventCint.C the CINT dictionary for the event and Track classes // this file is automatically generated by rootcint (see Makefile), // when the class definition in Event.h is modified. // // ---Analyzing the Event.root file with the interactive root // example of a simple session // Root > TFile f("Event.root") // Root > T.Draw("fNtrack") //histogram the number of tracks per event // Root > T.Draw("fPx") //histogram fPx for all tracks in all events // Root > T.Draw("fXfirst:fYfirst","fNtrack>600") // //scatter-plot for x versus y of first point of each track // Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram // // Look also in the same directory at the following macros: // - eventa.C an example how to read the tree // - eventb.C how to read events conditionally // //////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "TROOT.h" #include "TFile.h" #include "TNetFile.h" #include "TRandom.h" #include "TTree.h" #include "TBranch.h" #include "TClonesArray.h" #include "TStopwatch.h" #include "Event.h" //______________________________________________________________________________ int main(int argc, char **argv) { TROOT simple("simple","Example of creation of a tree"); Int_t nevent = 400; // by default create 400 events Int_t comp = 1; // by default file is compressed Int_t split = 1; // by default, split Event in sub branches Int_t write = 1; // by default the tree is filled Int_t hfill = 0; // by default histograms are not filled Int_t read = 0; Int_t arg4 = 1; Int_t arg5 = 600; //default number of tracks per event Int_t netf = 0; if (argc > 1) nevent = atoi(argv[1]); if (argc > 2) comp = atoi(argv[2]); if (argc > 3) split = atoi(argv[3]); if (argc > 4) arg4 = atoi(argv[4]); if (argc > 5) arg5 = atoi(argv[5]); if (arg4 == 0) { write = 0; hfill = 0; read = 1;} if (arg4 == 1) { write = 1; hfill = 0;} if (arg4 == 2) { write = 0; hfill = 0;} if (arg4 == 10) { write = 0; hfill = 1;} if (arg4 == 11) { write = 1; hfill = 1;} if (arg4 == 20) { write = 0; read = 1;} //read sequential if (arg4 == 25) { write = 0; read = 2;} //read random if (arg4 >= 30) { netf = 1; } //use TNetFile if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential if (arg4 == 35) { write = 0; read = 2;} //netfile + read random if (arg4 == 36) { write = 1; } //netfile + write sequential TFile *hfile; TTree *tree; Event *event = 0; // Fill event, header and tracks with some random numbers // Create a timer object to benchmark this loop TStopwatch timer; timer.Start(); Int_t nb = 0; Int_t ev; Int_t bufsize; Double_t told = 0; Double_t tnew = 0; Int_t printev = 100; if (arg5 < 100) printev = 1000; if (arg5 < 10) printev = 10000; Track::Class()->IgnoreTObjectStreamer(); // Read case if (read) { if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root"); hfile->UseCache(10); } else hfile = new TFile("Event.root"); tree = (TTree*)hfile->Get("T"); TBranch *branch = tree->GetBranch("event"); branch->SetAddress(&event); Int_t nentries = (Int_t)tree->GetEntries(); nevent = TMath::Max(nevent,nentries); if (read == 1) { //read sequential for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); told=tnew; timer.Continue(); } nb += tree->GetEntry(ev); //read complete event in memory } } else { //read random Int_t evrandom; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) cout<<"event="<<ev<<endl; evrandom = Int_t(nevent*gRandom->Rndm(1)); nb += tree->GetEntry(evrandom); //read complete event in memory } } } else { // Write case // Create a new ROOT binary machine independent file. // Note that this file may contain any kind of ROOT objects, histograms, // pictures, graphics objects, detector geometries, tracks, events, etc.. // This file is now becoming the current directory. if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file"); hfile->UseCache(10); } else hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file"); hfile->SetCompressionLevel(comp); // Create histogram to show write_time in function of time Float_t curtime = -0.5; Int_t ntime = nevent/printev; TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime); HistogramManager *hm = 0; if (hfill) { TDirectory *hdir = new TDirectory("histograms", "all histograms"); hm = new HistogramManager(hdir); } // Create a ROOT Tree and one superbranch TTree *tree = new TTree("T","An example of a ROOT tree"); tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written bufsize = 64000; if (split) bufsize /= 4; event = new Event(); TBranch *branch = tree->Branch("event", "Event", &event, bufsize,split); branch->SetAutoDelete(kFALSE); char etype[20]; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); htime->Fill(curtime,tnew-told); curtime += 1; told=tnew; timer.Continue(); } Float_t sigmat, sigmas; gRandom->Rannor(sigmat,sigmas); Int_t ntrack = Int_t(arg5 +arg5*sigmat/120.); Float_t random = gRandom->Rndm(1); sprintf(etype,"type%d",ev%5); event->SetType(etype); event->SetHeader(ev, 200, 960312, random); event->SetNseg(Int_t(10*ntrack+20*sigmas)); event->SetNvertex(Int_t(1+20*gRandom->Rndm())); event->SetFlag(UInt_t(random+0.5)); event->SetTemperature(random+20.); for(UChar_t m = 0; m < 10; m++) { event->SetMeasure(m, Int_t(gRandom->Gaus(m,m+1))); } for(UChar_t i0 = 0; i0 < 4; i0++) { for(UChar_t i1 = 0; i1 < 4; i1++) { event->SetMatrix(i0,i1,gRandom->Gaus(i0*i1,1)); } } // Create and Fill the Track objects for (Int_t t = 0; t < ntrack; t++) event->AddTrack(random); if (write) nb += tree->Fill(); //fill the tree if (hm) hm->Hfill(event); //fill histograms event->Clear(); } if (write) { hfile->Write(); tree->Print(); } } // Stop timer and print results timer.Stop(); Float_t mbytes = 0.000001*nb; Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); printf("\n%d events and %d bytes processed.\n",nevent,nb); printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime); if (read) { printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime); } else { printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4); printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime); //printf("file compression factor = %f\n",hfile.GetCompressionFactor()); } hfile->Close(); return 0; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <iostream> #include <fstream> #include <istream> #include <sstream> #include <exception> #include <stdexcept> #include <test/unit/gm/utility.hpp> TEST(gm_parser, block_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/block"); } TEST(gm_parser, broadcast_infix_operators_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/broadcast_infix_operators"); } TEST(gm_parser, cholesky_decompose_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/cholesky_decompose"); } TEST(gm_parser, col_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/col"); } TEST(gm_parser, cols_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/cols"); } TEST(gm_parser, columns_dot_product_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/columns_dot_product"); } TEST(gm_parser, columns_dot_self_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/columns_dot_self"); } TEST(gm_parser, crossprod_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/crossprod"); } TEST(gm_parser, cumulative_sum_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/cumulative_sum"); } TEST(gm_parser, determinant_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/determinant"); } TEST(gm_parser, diag_matrix_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/diag_matrix"); } TEST(gm_parser, diag_post_multiply_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/diag_post_multiply"); } TEST(gm_parser, diag_pre_multiply_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/diag_pre_multiply"); } TEST(gm_parser, diagonal_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/diagonal"); } TEST(gm_parser, dims_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/dims"); } TEST(gm_parser, distance_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/distance"); } TEST(gm_parser, dot_product_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/dot_product"); } TEST(gm_parser, dot_self_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/dot_self"); } TEST(gm_parser, eigenvalues_sym_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/eigenvalues_sym"); } TEST(gm_parser, eigenvectors_sym_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/eigenvectors_sym"); } TEST(gm_parser, elementwise_products_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/elementwise_products"); } TEST(gm_parser, exp_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/exp"); } TEST(gm_parser, head_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/head"); } TEST(gm_parser, infix_matrix_operators_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/infix_matrix_operators"); } TEST(gm_parser, inverse_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/inverse"); } TEST(gm_parser, inverse_spd_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/inverse_spd"); } TEST(gm_parser, log_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/log"); } TEST(gm_parser, log_determinant_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/log_determinant"); } TEST(gm_parser, log_softmax_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/log_softmax"); } TEST(gm_parser, log_sum_exp_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/log_sum_exp"); } TEST(gm_parser, division_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/matrix_division"); } TEST(gm_parser, max_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/max"); } TEST(gm_parser, mdivide_left_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/mdivide_left"); } TEST(gm_parser, mdivide_left_tri_low_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/mdivide_left_tri_low"); } TEST(gm_parser, mdivide_right_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/mdivide_right"); } TEST(gm_parser, mdivide_right_tri_low_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/mdivide_right_tri_low"); } TEST(gm_parser, mean_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/mean"); } TEST(gm_parser, min_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/min"); } TEST(gm_parser, multiply_lower_tri_self_transpose_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/multiply_lower_tri_self_transpose"); } TEST(gm_parser, negation_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/negation"); } TEST(gm_parser, prod_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/prod"); } TEST(gm_parser, qr_Q_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/qr_Q"); } TEST(gm_parser, qr_R_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/qr_R"); } TEST(gm_parser, quad_form_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/quad_form"); } TEST(gm_parser, quad_form_diag_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/quad_form_diag"); } TEST(gm_parser, quad_form_sym_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/quad_form_sym"); } TEST(gm_parser, rank_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rep_matrix"); } TEST(gm_parser, rep_matrix_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rank"); } TEST(gm_parser, rep_param_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rep_param"); //mostly rep_array with some other rep_ tests } TEST(gm_parser, rep_row_vector_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rep_row_vector"); } TEST(gm_parser, rep_vector_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rep_vector"); } TEST(gm_parser, row_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/row"); } TEST(gm_parser, rows_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rows"); } TEST(gm_parser, rows_dot_product_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rows_dot_product"); } TEST(gm_parser, rows_dot_self_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rows_dot_self"); } TEST(gm_parser, singular_values_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/singular_values"); } TEST(gm_parser, segment_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/segment"); } TEST(gm_parser, size_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/size"); } TEST(gm_parser, sd_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sd"); } TEST(gm_parser, softmax_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/softmax"); } TEST(gm_parser, sort_asc_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sort_asc"); } TEST(gm_parser, sort_desc_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sort_desc"); } TEST(gm_parser, sort_indices_asc_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sort_indices_asc"); } TEST(gm_parser, sort_indices_desc_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sort_indices_desc"); } TEST(gm_parser, squared_distance_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/squared_distance"); } TEST(gm_parser, sub_col_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sub_col"); } TEST(gm_parser, sub_row_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sub_row"); } TEST(gm_parser, sum_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sum"); } TEST(gm_parser, tail_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/tail"); } TEST(gm_parser, tcrossprod_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/tcrossprod"); } TEST(gm_parser, to_array_1d_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/to_array_1d"); } TEST(gm_parser, to_array_2d_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/to_array_2d"); } TEST(gm_parser, to_matrix_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/to_matrix"); } TEST(gm_parser, to_row_vector_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/to_row_vector"); } TEST(gm_parser, to_vector_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/to_vector"); } TEST(gm_parser, trace_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/trace"); } TEST(gm_parser, trace_gen_quad_form_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/trace_gen_quad_form"); } TEST(gm_parser, trace_quad_form_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/trace_quad_form"); } TEST(gm_parser, transpose_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/transpose"); } TEST(gm_parser, variance_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/variance"); } <commit_msg>added append_row and append_col to parser_tests<commit_after>#include <gtest/gtest.h> #include <iostream> #include <fstream> #include <istream> #include <sstream> #include <exception> #include <stdexcept> #include <test/unit/gm/utility.hpp> TEST(gm_parser, append_col_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/append_col"); } TEST(gm_parser, append_row_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/append_row"); } TEST(gm_parser, block_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/block"); } TEST(gm_parser, broadcast_infix_operators_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/broadcast_infix_operators"); } TEST(gm_parser, cholesky_decompose_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/cholesky_decompose"); } TEST(gm_parser, col_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/col"); } TEST(gm_parser, cols_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/cols"); } TEST(gm_parser, columns_dot_product_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/columns_dot_product"); } TEST(gm_parser, columns_dot_self_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/columns_dot_self"); } TEST(gm_parser, crossprod_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/crossprod"); } TEST(gm_parser, cumulative_sum_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/cumulative_sum"); } TEST(gm_parser, determinant_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/determinant"); } TEST(gm_parser, diag_matrix_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/diag_matrix"); } TEST(gm_parser, diag_post_multiply_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/diag_post_multiply"); } TEST(gm_parser, diag_pre_multiply_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/diag_pre_multiply"); } TEST(gm_parser, diagonal_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/diagonal"); } TEST(gm_parser, dims_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/dims"); } TEST(gm_parser, distance_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/distance"); } TEST(gm_parser, dot_product_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/dot_product"); } TEST(gm_parser, dot_self_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/dot_self"); } TEST(gm_parser, eigenvalues_sym_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/eigenvalues_sym"); } TEST(gm_parser, eigenvectors_sym_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/eigenvectors_sym"); } TEST(gm_parser, elementwise_products_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/elementwise_products"); } TEST(gm_parser, exp_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/exp"); } TEST(gm_parser, head_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/head"); } TEST(gm_parser, infix_matrix_operators_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/infix_matrix_operators"); } TEST(gm_parser, inverse_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/inverse"); } TEST(gm_parser, inverse_spd_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/inverse_spd"); } TEST(gm_parser, log_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/log"); } TEST(gm_parser, log_determinant_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/log_determinant"); } TEST(gm_parser, log_softmax_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/log_softmax"); } TEST(gm_parser, log_sum_exp_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/log_sum_exp"); } TEST(gm_parser, division_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/matrix_division"); } TEST(gm_parser, max_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/max"); } TEST(gm_parser, mdivide_left_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/mdivide_left"); } TEST(gm_parser, mdivide_left_tri_low_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/mdivide_left_tri_low"); } TEST(gm_parser, mdivide_right_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/mdivide_right"); } TEST(gm_parser, mdivide_right_tri_low_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/mdivide_right_tri_low"); } TEST(gm_parser, mean_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/mean"); } TEST(gm_parser, min_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/min"); } TEST(gm_parser, multiply_lower_tri_self_transpose_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/multiply_lower_tri_self_transpose"); } TEST(gm_parser, negation_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/negation"); } TEST(gm_parser, prod_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/prod"); } TEST(gm_parser, qr_Q_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/qr_Q"); } TEST(gm_parser, qr_R_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/qr_R"); } TEST(gm_parser, quad_form_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/quad_form"); } TEST(gm_parser, quad_form_diag_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/quad_form_diag"); } TEST(gm_parser, quad_form_sym_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/quad_form_sym"); } TEST(gm_parser, rank_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rep_matrix"); } TEST(gm_parser, rep_matrix_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rank"); } TEST(gm_parser, rep_param_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rep_param"); //mostly rep_array with some other rep_ tests } TEST(gm_parser, rep_row_vector_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rep_row_vector"); } TEST(gm_parser, rep_vector_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rep_vector"); } TEST(gm_parser, row_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/row"); } TEST(gm_parser, rows_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rows"); } TEST(gm_parser, rows_dot_product_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rows_dot_product"); } TEST(gm_parser, rows_dot_self_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/rows_dot_self"); } TEST(gm_parser, singular_values_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/singular_values"); } TEST(gm_parser, segment_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/segment"); } TEST(gm_parser, size_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/size"); } TEST(gm_parser, sd_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sd"); } TEST(gm_parser, softmax_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/softmax"); } TEST(gm_parser, sort_asc_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sort_asc"); } TEST(gm_parser, sort_desc_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sort_desc"); } TEST(gm_parser, sort_indices_asc_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sort_indices_asc"); } TEST(gm_parser, sort_indices_desc_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sort_indices_desc"); } TEST(gm_parser, squared_distance_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/squared_distance"); } TEST(gm_parser, sub_col_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sub_col"); } TEST(gm_parser, sub_row_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sub_row"); } TEST(gm_parser, sum_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/sum"); } TEST(gm_parser, tail_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/tail"); } TEST(gm_parser, tcrossprod_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/tcrossprod"); } TEST(gm_parser, to_array_1d_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/to_array_1d"); } TEST(gm_parser, to_array_2d_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/to_array_2d"); } TEST(gm_parser, to_matrix_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/to_matrix"); } TEST(gm_parser, to_row_vector_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/to_row_vector"); } TEST(gm_parser, to_vector_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/to_vector"); } TEST(gm_parser, trace_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/trace"); } TEST(gm_parser, trace_gen_quad_form_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/trace_gen_quad_form"); } TEST(gm_parser, trace_quad_form_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/trace_quad_form"); } TEST(gm_parser, transpose_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/transpose"); } TEST(gm_parser, variance_matrix_function_signatures) { test_parsable("function-signatures/math/matrix/variance"); } <|endoftext|>
<commit_before>#include <pcl/console/parse.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/point_representation.h> #include <pcl/io/pcd_io.h> #include <pcl/ros/conversions.h> #include <pcl/keypoints/uniform_sampling.h> #include <pcl/features/normal_3d.h> #include <pcl/features/fpfh.h> #include <pcl/registration/correspondence_estimation.h> #include <pcl/registration/correspondence_rejection_distance.h> #include <pcl/registration/transformation_estimation_svd.h> using namespace std; using namespace sensor_msgs; using namespace pcl; using namespace pcl::io; using namespace pcl::console; using namespace pcl::registration; PointCloud<PointXYZ>::Ptr src, tgt; //////////////////////////////////////////////////////////////////////////////// void estimateKeypoints (const PointCloud<PointXYZ>::Ptr &src, const PointCloud<PointXYZ>::Ptr &tgt, PointCloud<PointXYZ> &keypoints_src, PointCloud<PointXYZ> &keypoints_tgt) { PointCloud<int> keypoints_src_idx, keypoints_tgt_idx; // Get an uniform grid of keypoints UniformSampling<PointXYZ> uniform; uniform.setRadiusSearch (1); // 1m uniform.setInputCloud (src); uniform.compute (keypoints_src_idx); copyPointCloud<PointXYZ, PointXYZ> (*src, keypoints_src_idx.points, keypoints_src); uniform.setInputCloud (tgt); uniform.compute (keypoints_tgt_idx); copyPointCloud<PointXYZ, PointXYZ> (*tgt, keypoints_tgt_idx.points, keypoints_tgt); // For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.: // pcd_viewer source_pcd keypoints_src.pcd -ps 1 -ps 10 savePCDFileBinary ("keypoints_src.pcd", keypoints_src); savePCDFileBinary ("keypoints_tgt.pcd", keypoints_tgt); } //////////////////////////////////////////////////////////////////////////////// void estimateNormals (const PointCloud<PointXYZ>::Ptr &src, const PointCloud<PointXYZ>::Ptr &tgt, PointCloud<Normal> &normals_src, PointCloud<Normal> &normals_tgt) { NormalEstimation<PointXYZ, Normal> normal_est; normal_est.setInputCloud (src); normal_est.setRadiusSearch (0.5); // 50cm normal_est.compute (normals_src); normal_est.setInputCloud (tgt); normal_est.compute (normals_tgt); // For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.: // pcd_viewer normals_src.pcd PointCloud<PointNormal> s, t; copyPointCloud<PointXYZ, PointNormal> (*src, s); copyPointCloud<Normal, PointNormal> (normals_src, s); copyPointCloud<PointXYZ, PointNormal> (*tgt, t); copyPointCloud<Normal, PointNormal> (normals_tgt, t); savePCDFileBinary ("normals_src.pcd", s); savePCDFileBinary ("normals_tgt.pcd", t); } //////////////////////////////////////////////////////////////////////////////// void estimateFPFH (const PointCloud<PointXYZ>::Ptr &src, const PointCloud<PointXYZ>::Ptr &tgt, const PointCloud<Normal>::Ptr &normals_src, const PointCloud<Normal>::Ptr &normals_tgt, const PointCloud<PointXYZ>::Ptr &keypoints_src, const PointCloud<PointXYZ>::Ptr &keypoints_tgt, PointCloud<FPFHSignature33> &fpfhs_src, PointCloud<FPFHSignature33> &fpfhs_tgt) { FPFHEstimation<PointXYZ, Normal, FPFHSignature33> fpfh_est; fpfh_est.setInputCloud (keypoints_src); fpfh_est.setInputNormals (normals_src); fpfh_est.setRadiusSearch (1); // 1m fpfh_est.setSearchSurface (src); fpfh_est.compute (fpfhs_src); fpfh_est.setInputCloud (keypoints_tgt); fpfh_est.setInputNormals (normals_tgt); fpfh_est.setSearchSurface (tgt); fpfh_est.compute (fpfhs_tgt); // For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.: // pcd_viewer fpfhs_src.pcd PointCloud2 s, t, out; toROSMsg (*src, s); toROSMsg (fpfhs_src, t); concatenateFields (s, t, out); savePCDFile ("fpfhs_src.pcd", out); toROSMsg (*tgt, s); toROSMsg (fpfhs_tgt, t); concatenateFields (s, t, out); savePCDFile ("fpfhs_tgt.pcd", out); } //////////////////////////////////////////////////////////////////////////////// void findCorrespondences (const PointCloud<FPFHSignature33>::Ptr &fpfhs_src, const PointCloud<FPFHSignature33>::Ptr &fpfhs_tgt, Correspondences &all_correspondences) { CorrespondenceEstimation<FPFHSignature33, FPFHSignature33> est; est.setInputCloud (fpfhs_src); est.setInputTarget (fpfhs_tgt); est.determineReciprocalCorrespondences (all_correspondences); } //////////////////////////////////////////////////////////////////////////////// void rejectBadCorrespondences (const CorrespondencesPtr &all_correspondences, const PointCloud<PointXYZ>::Ptr &keypoints_src, const PointCloud<PointXYZ>::Ptr &keypoints_tgt, Correspondences &remaining_correspondences) { CorrespondenceRejectorDistance rej; rej.setInputCloud<PointXYZ> (keypoints_src); rej.setInputTarget<PointXYZ> (keypoints_tgt); rej.setMaximumDistance (1); // 1m rej.setInputCorrespondences (all_correspondences); rej.getCorrespondences (remaining_correspondences); } //////////////////////////////////////////////////////////////////////////////// void computeTransformation (const PointCloud<PointXYZ>::Ptr &src, const PointCloud<PointXYZ>::Ptr &tgt, Eigen::Matrix4f &transform) { // Get an uniform grid of keypoints PointCloud<PointXYZ>::Ptr keypoints_src (new PointCloud<PointXYZ>), keypoints_tgt (new PointCloud<PointXYZ>); estimateKeypoints (src, tgt, *keypoints_src, *keypoints_tgt); print_info ("Found %zu and %zu keypoints for the source and target datasets.\n", keypoints_src->points.size (), keypoints_tgt->points.size ()); // Compute normals for all points keypoint PointCloud<Normal>::Ptr normals_src (new PointCloud<Normal>), normals_tgt (new PointCloud<Normal>); estimateNormals (src, tgt, *normals_src, *normals_tgt); print_info ("Estimated %zu and %zu normals for the source and target datasets.\n", normals_src->points.size (), normals_tgt->points.size ()); // Compute FPFH features at each keypoint PointCloud<FPFHSignature33>::Ptr fpfhs_src (new PointCloud<FPFHSignature33>), fpfhs_tgt (new PointCloud<FPFHSignature33>); estimateFPFH (src, tgt, normals_src, normals_tgt, keypoints_src, keypoints_tgt, *fpfhs_src, *fpfhs_tgt); // Copy the data and save it to disk /* PointCloud<PointNormal> s, t; copyPointCloud<PointXYZ, PointNormal> (*keypoints_src, s); copyPointCloud<Normal, PointNormal> (normals_src, s); copyPointCloud<PointXYZ, PointNormal> (*keypoints_tgt, t); copyPointCloud<Normal, PointNormal> (normals_tgt, t);*/ // Find correspondences between keypoints in FPFH space CorrespondencesPtr all_correspondences (new Correspondences), good_correspondences (new Correspondences); findCorrespondences (fpfhs_src, fpfhs_tgt, *all_correspondences); // Reject correspondences based on their XYZ distance rejectBadCorrespondences (all_correspondences, keypoints_src, keypoints_tgt, *good_correspondences); for (int i = 0; i < good_correspondences->size (); ++i) std::cerr << good_correspondences->at (i) << std::endl; // Obtain the best transformation between the two sets of keypoints given the remaining correspondences TransformationEstimationSVD<PointXYZ, PointXYZ> trans_est; trans_est.estimateRigidTransformation (*keypoints_src, *keypoints_tgt, *good_correspondences, transform); } /* ---[ */ int main (int argc, char** argv) { // Parse the command line arguments for .pcd files std::vector<int> p_file_indices; p_file_indices = parse_file_extension_argument (argc, argv, ".pcd"); if (p_file_indices.size () != 2) { print_error ("Need one input source PCD file and one input target PCD file to continue.\n"); print_error ("Example: %s source.pcd target.pcd\n", argv[0]); return (-1); } // Load the files print_info ("Loading %s as source and %s as target...\n", argv[p_file_indices[0]], argv[p_file_indices[1]]); src.reset (new PointCloud<PointXYZ>); tgt.reset (new PointCloud<PointXYZ>); if (loadPCDFile (argv[p_file_indices[0]], *src) == -1 || loadPCDFile (argv[p_file_indices[1]], *tgt) == -1) { print_error ("Error reading the input files!\n"); return (-1); } // Compute the best transformtion Eigen::Matrix4f transform; computeTransformation (src, tgt, transform); std::cerr << transform << std::endl; // Transform the data and write it to disk PointCloud<PointXYZ> output; transformPointCloud (*src, output, transform); savePCDFileBinary ("source_transformed.pcd", output); } /* ]--- */ <commit_msg>Minor bug fixed in registration_api tutorial code<commit_after>#include <pcl/console/parse.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/point_representation.h> #include <pcl/io/pcd_io.h> #include <pcl/ros/conversions.h> #include <pcl/keypoints/uniform_sampling.h> #include <pcl/features/normal_3d.h> #include <pcl/features/fpfh.h> #include <pcl/registration/correspondence_estimation.h> #include <pcl/registration/correspondence_rejection_distance.h> #include <pcl/registration/transformation_estimation_svd.h> using namespace std; using namespace sensor_msgs; using namespace pcl; using namespace pcl::io; using namespace pcl::console; using namespace pcl::registration; PointCloud<PointXYZ>::Ptr src, tgt; //////////////////////////////////////////////////////////////////////////////// void estimateKeypoints (const PointCloud<PointXYZ>::Ptr &src, const PointCloud<PointXYZ>::Ptr &tgt, PointCloud<PointXYZ> &keypoints_src, PointCloud<PointXYZ> &keypoints_tgt) { PointCloud<int> keypoints_src_idx, keypoints_tgt_idx; // Get an uniform grid of keypoints UniformSampling<PointXYZ> uniform; uniform.setRadiusSearch (1); // 1m uniform.setInputCloud (src); uniform.compute (keypoints_src_idx); copyPointCloud<PointXYZ, PointXYZ> (*src, keypoints_src_idx.points, keypoints_src); uniform.setInputCloud (tgt); uniform.compute (keypoints_tgt_idx); copyPointCloud<PointXYZ, PointXYZ> (*tgt, keypoints_tgt_idx.points, keypoints_tgt); // For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.: // pcd_viewer source_pcd keypoints_src.pcd -ps 1 -ps 10 savePCDFileBinary ("keypoints_src.pcd", keypoints_src); savePCDFileBinary ("keypoints_tgt.pcd", keypoints_tgt); } //////////////////////////////////////////////////////////////////////////////// void estimateNormals (const PointCloud<PointXYZ>::Ptr &src, const PointCloud<PointXYZ>::Ptr &tgt, PointCloud<Normal> &normals_src, PointCloud<Normal> &normals_tgt) { NormalEstimation<PointXYZ, Normal> normal_est; normal_est.setInputCloud (src); normal_est.setRadiusSearch (0.5); // 50cm normal_est.compute (normals_src); normal_est.setInputCloud (tgt); normal_est.compute (normals_tgt); // For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.: // pcd_viewer normals_src.pcd PointCloud<PointNormal> s, t; copyPointCloud<PointXYZ, PointNormal> (*src, s); copyPointCloud<Normal, PointNormal> (normals_src, s); copyPointCloud<PointXYZ, PointNormal> (*tgt, t); copyPointCloud<Normal, PointNormal> (normals_tgt, t); savePCDFileBinary ("normals_src.pcd", s); savePCDFileBinary ("normals_tgt.pcd", t); } //////////////////////////////////////////////////////////////////////////////// void estimateFPFH (const PointCloud<PointXYZ>::Ptr &src, const PointCloud<PointXYZ>::Ptr &tgt, const PointCloud<Normal>::Ptr &normals_src, const PointCloud<Normal>::Ptr &normals_tgt, const PointCloud<PointXYZ>::Ptr &keypoints_src, const PointCloud<PointXYZ>::Ptr &keypoints_tgt, PointCloud<FPFHSignature33> &fpfhs_src, PointCloud<FPFHSignature33> &fpfhs_tgt) { FPFHEstimation<PointXYZ, Normal, FPFHSignature33> fpfh_est; fpfh_est.setInputCloud (keypoints_src); fpfh_est.setInputNormals (normals_src); fpfh_est.setRadiusSearch (1); // 1m fpfh_est.setSearchSurface (src); fpfh_est.compute (fpfhs_src); fpfh_est.setInputCloud (keypoints_tgt); fpfh_est.setInputNormals (normals_tgt); fpfh_est.setSearchSurface (tgt); fpfh_est.compute (fpfhs_tgt); // For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.: // pcd_viewer fpfhs_src.pcd PointCloud2 s, t, out; toROSMsg (*keypoints_src, s); toROSMsg (fpfhs_src, t); concatenateFields (s, t, out); savePCDFile ("fpfhs_src.pcd", out); toROSMsg (*keypoints_tgt, s); toROSMsg (fpfhs_tgt, t); concatenateFields (s, t, out); savePCDFile ("fpfhs_tgt.pcd", out); } //////////////////////////////////////////////////////////////////////////////// void findCorrespondences (const PointCloud<FPFHSignature33>::Ptr &fpfhs_src, const PointCloud<FPFHSignature33>::Ptr &fpfhs_tgt, Correspondences &all_correspondences) { CorrespondenceEstimation<FPFHSignature33, FPFHSignature33> est; est.setInputCloud (fpfhs_src); est.setInputTarget (fpfhs_tgt); est.determineReciprocalCorrespondences (all_correspondences); } //////////////////////////////////////////////////////////////////////////////// void rejectBadCorrespondences (const CorrespondencesPtr &all_correspondences, const PointCloud<PointXYZ>::Ptr &keypoints_src, const PointCloud<PointXYZ>::Ptr &keypoints_tgt, Correspondences &remaining_correspondences) { CorrespondenceRejectorDistance rej; rej.setInputCloud<PointXYZ> (keypoints_src); rej.setInputTarget<PointXYZ> (keypoints_tgt); rej.setMaximumDistance (1); // 1m rej.setInputCorrespondences (all_correspondences); rej.getCorrespondences (remaining_correspondences); } //////////////////////////////////////////////////////////////////////////////// void computeTransformation (const PointCloud<PointXYZ>::Ptr &src, const PointCloud<PointXYZ>::Ptr &tgt, Eigen::Matrix4f &transform) { // Get an uniform grid of keypoints PointCloud<PointXYZ>::Ptr keypoints_src (new PointCloud<PointXYZ>), keypoints_tgt (new PointCloud<PointXYZ>); estimateKeypoints (src, tgt, *keypoints_src, *keypoints_tgt); print_info ("Found %zu and %zu keypoints for the source and target datasets.\n", keypoints_src->points.size (), keypoints_tgt->points.size ()); // Compute normals for all points keypoint PointCloud<Normal>::Ptr normals_src (new PointCloud<Normal>), normals_tgt (new PointCloud<Normal>); estimateNormals (src, tgt, *normals_src, *normals_tgt); print_info ("Estimated %zu and %zu normals for the source and target datasets.\n", normals_src->points.size (), normals_tgt->points.size ()); // Compute FPFH features at each keypoint PointCloud<FPFHSignature33>::Ptr fpfhs_src (new PointCloud<FPFHSignature33>), fpfhs_tgt (new PointCloud<FPFHSignature33>); estimateFPFH (src, tgt, normals_src, normals_tgt, keypoints_src, keypoints_tgt, *fpfhs_src, *fpfhs_tgt); // Copy the data and save it to disk /* PointCloud<PointNormal> s, t; copyPointCloud<PointXYZ, PointNormal> (*keypoints_src, s); copyPointCloud<Normal, PointNormal> (normals_src, s); copyPointCloud<PointXYZ, PointNormal> (*keypoints_tgt, t); copyPointCloud<Normal, PointNormal> (normals_tgt, t);*/ // Find correspondences between keypoints in FPFH space CorrespondencesPtr all_correspondences (new Correspondences), good_correspondences (new Correspondences); findCorrespondences (fpfhs_src, fpfhs_tgt, *all_correspondences); // Reject correspondences based on their XYZ distance rejectBadCorrespondences (all_correspondences, keypoints_src, keypoints_tgt, *good_correspondences); for (int i = 0; i < good_correspondences->size (); ++i) std::cerr << good_correspondences->at (i) << std::endl; // Obtain the best transformation between the two sets of keypoints given the remaining correspondences TransformationEstimationSVD<PointXYZ, PointXYZ> trans_est; trans_est.estimateRigidTransformation (*keypoints_src, *keypoints_tgt, *good_correspondences, transform); } /* ---[ */ int main (int argc, char** argv) { // Parse the command line arguments for .pcd files std::vector<int> p_file_indices; p_file_indices = parse_file_extension_argument (argc, argv, ".pcd"); if (p_file_indices.size () != 2) { print_error ("Need one input source PCD file and one input target PCD file to continue.\n"); print_error ("Example: %s source.pcd target.pcd\n", argv[0]); return (-1); } // Load the files print_info ("Loading %s as source and %s as target...\n", argv[p_file_indices[0]], argv[p_file_indices[1]]); src.reset (new PointCloud<PointXYZ>); tgt.reset (new PointCloud<PointXYZ>); if (loadPCDFile (argv[p_file_indices[0]], *src) == -1 || loadPCDFile (argv[p_file_indices[1]], *tgt) == -1) { print_error ("Error reading the input files!\n"); return (-1); } // Compute the best transformtion Eigen::Matrix4f transform; computeTransformation (src, tgt, transform); std::cerr << transform << std::endl; // Transform the data and write it to disk PointCloud<PointXYZ> output; transformPointCloud (*src, output, transform); savePCDFileBinary ("source_transformed.pcd", output); } /* ]--- */ <|endoftext|>
<commit_before>/* $Id$ */ /* Copyright (C) 2001 The gtkmm Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gtkmm/main.h> #include <gtkmm/cellrenderertext.h> #include <gtkmm/treeviewcolumn.h> #include <gtkmm/box.h> #include <glibmm/convert.h> #include <glibmm/fileutils.h> #include "demowindow.h" #include "textwidget.h" #include "demos.h" #include <vector> #include <cctype> #include <cerrno> #include <stdio.h> #include <cstring> using std::isspace; using std::strlen; #include "demo-common.h" #ifdef NEED_FLOCKFILE_PROTO extern "C" void flockfile (FILE *); #endif #ifdef NEED_FUNLOCKFILE_PROTO extern "C" void funlockfile (FILE *); #endif #ifdef NEED_GETC_UNLOCKED_PROTO extern "C" int getc_unlocked (FILE *); #endif namespace { struct DemoColumns : public Gtk::TreeModelColumnRecord { Gtk::TreeModelColumn<Glib::ustring> title; Gtk::TreeModelColumn<Glib::ustring> filename; Gtk::TreeModelColumn<type_slotDo> slot; Gtk::TreeModelColumn<bool> italic; DemoColumns() { add(title); add(filename); add(slot); add(italic); } }; // Singleton accessor function. const DemoColumns& demo_columns() { static DemoColumns column_record; return column_record; } } // anonymous namespace DemoWindow::DemoWindow() : m_RunButton("Run"), m_HBox(Gtk::ORIENTATION_HORIZONTAL), m_TextWidget_Info(false), m_TextWidget_Source(true) { m_pWindow_Example = 0; configure_header_bar(); add(m_HBox); //Tree: m_refTreeStore = Gtk::TreeStore::create(demo_columns()); m_TreeView.set_model(m_refTreeStore); m_refTreeSelection = m_TreeView.get_selection(); m_refTreeSelection->set_mode(Gtk::SELECTION_BROWSE); m_refTreeSelection->set_select_function( sigc::ptr_fun(&DemoWindow::select_function) ); m_TreeView.set_size_request(200, -1); fill_tree(); //SideBar m_SideBar.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); m_SideBar.get_style_context()->add_class("sidebar"); m_SideBar.add(m_TreeView); m_HBox.pack_start(m_SideBar, Gtk::PACK_SHRINK); //Notebook: m_Notebook.append_page(m_TextWidget_Info, "_Info", true); //true = use mnemonic. m_Notebook.append_page(m_TextWidget_Source, "_Source", true); //true = use mnemonic. m_Notebook.child_property_tab_expand(m_TextWidget_Info) = true; m_Notebook.child_property_tab_expand(m_TextWidget_Source) = true; m_HBox.pack_start(m_Notebook); set_default_size (800, 600); load_file (testgtk_demos[0].filename); show_all(); } void DemoWindow::configure_header_bar() { m_HeaderBar.set_show_close_button(); m_HeaderBar.pack_start(m_RunButton); m_RunButton.get_style_context()->add_class("suggested-action"); m_RunButton.signal_clicked().connect(sigc::mem_fun(*this, &DemoWindow::on_run_button_clicked)); set_titlebar(m_HeaderBar); } void DemoWindow::fill_tree() { const DemoColumns& columns = demo_columns(); /* this code only supports 1 level of children. If we * want more we probably have to use a recursing function. */ for(Demo* d = testgtk_demos; d && d->title; ++d) { Gtk::TreeRow row = *(m_refTreeStore->append()); row[columns.title] = d->title; row[columns.filename] = d->filename; row[columns.slot] = d->slot; row[columns.italic] = false; for(Demo* child = d->children; child && child->title; ++child) { Gtk::TreeRow child_row = *(m_refTreeStore->append(row.children())); child_row[columns.title] = child->title; child_row[columns.filename] = child->filename; child_row[columns.slot] = child->slot; child_row[columns.italic] = false; } } Gtk::CellRendererText* pCell = Gtk::manage(new Gtk::CellRendererText()); pCell->property_style() = Pango::STYLE_ITALIC; Gtk::TreeViewColumn* pColumn = new Gtk::TreeViewColumn("Widget (double click for demo)", *pCell); pColumn->add_attribute(pCell->property_text(), columns.title); pColumn->add_attribute(pCell->property_style_set(), columns.italic); m_TreeView.append_column(*pColumn); m_refTreeSelection->signal_changed().connect(sigc::mem_fun(*this, &DemoWindow::on_treeselection_changed)); m_TreeView.signal_row_activated().connect(sigc::mem_fun(*this, &DemoWindow::on_treeview_row_activated)); m_TreeView.expand_all(); } DemoWindow::~DemoWindow() { on_example_window_hide(); //delete the example window if there is one. } void DemoWindow::on_run_button_clicked() { if(m_pWindow_Example == 0) //Don't open a second window. { if(const Gtk::TreeModel::iterator iter = m_refTreeSelection->get_selected()) { m_TreePath = m_refTreeStore->get_path(iter); run_example(*iter); } } } void DemoWindow::on_treeview_row_activated(const Gtk::TreeModel::Path& path, Gtk::TreeViewColumn* /* model */) { m_TreePath = path; if(m_pWindow_Example == 0) //Don't open a second window. { if(const Gtk::TreeModel::iterator iter = m_TreeView.get_model()->get_iter(m_TreePath)) { run_example(*iter); } } } void DemoWindow::run_example(const Gtk::TreeModel::Row& row) { const DemoColumns& columns = demo_columns(); const type_slotDo& slot = row[columns.slot]; if(slot && (m_pWindow_Example = slot())) { row[columns.italic] = true; m_pWindow_Example->signal_hide().connect(sigc::mem_fun(*this, &DemoWindow::on_example_window_hide)); m_pWindow_Example->show(); } } bool DemoWindow::select_function(const Glib::RefPtr<Gtk::TreeModel>& model, const Gtk::TreeModel::Path& path, bool) { const Gtk::TreeModel::iterator iter = model->get_iter(path); return iter->children().empty(); // only allow leaf nodes to be selected } void DemoWindow::on_treeselection_changed() { if(const Gtk::TreeModel::iterator iter = m_refTreeSelection->get_selected()) { const Glib::ustring filename = (*iter)[demo_columns().filename]; const Glib::ustring title = (*iter)[demo_columns().title]; load_file(Glib::filename_from_utf8(filename)); m_HeaderBar.set_title(title); } } bool DemoWindow::read_line (FILE *stream, GString *str) { int n_read = 0; #ifdef HAVE_FLOCKFILE flockfile (stream); #endif g_string_truncate (str, 0); while (1) { int c; #ifdef HAVE_GETC_UNLOCKED c = getc_unlocked (stream); #endif //GLIBMM_PROPERTIES_ENABLED if (c == EOF) goto done; else n_read++; switch (c) { case '\r': case '\n': { #ifdef HAVE_GETC_UNLOCKED int next_c = getc_unlocked (stream); #endif //GLIBMM_PROPERTIES_ENABLED if (!(next_c == EOF || (c == '\r' && next_c == '\n') || (c == '\n' && next_c == '\r'))) ungetc (next_c, stream); goto done; } default: g_string_append_c (str, c); } } done: #ifdef HAVE_FUNLOCKFILE funlockfile (stream); #endif return n_read > 0; } void DemoWindow::load_file(const std::string& filename) { if ( m_current_filename == filename ) { return; } else { m_current_filename = filename; m_TextWidget_Info.wipe(); m_TextWidget_Source.wipe(); Glib::RefPtr<Gtk::TextBuffer> refBufferInfo = m_TextWidget_Info.get_buffer(); Glib::RefPtr<Gtk::TextBuffer> refBufferSource = m_TextWidget_Source.get_buffer(); FILE* file = fopen (filename.c_str(), "r"); if (!file) { try { std::string installed = demo_find_file(filename); file = fopen (installed.c_str(), "r"); } catch (const Glib::FileError& ex) { g_warning ("%s\n", ex.what().c_str()); return; } } if (!file) { g_warning ("Cannot open %s: %s\n", filename.c_str(), g_strerror (errno)); return; } GString *buffer = g_string_new (NULL); int state = 0; bool in_para = false; Gtk::TextBuffer::iterator start = refBufferInfo->get_iter_at_offset(0); while (read_line (file, buffer)) { gchar *p = buffer->str; gchar *q = 0; gchar *r = 0; switch (state) { case 0: /* Reading title */ while (*p == '/' || *p == '*' || isspace (*p)) p++; r = p; while (*r != '/' && strlen (r)) r++; if (strlen (r) > 0) p = r + 1; q = p + strlen (p); while (q > p && isspace (*(q - 1))) q--; if (q > p) { Gtk::TextBuffer::iterator end = start; const Glib::ustring strTemp (p, q); end = refBufferInfo->insert(end, strTemp); start = end; start.backward_chars(strTemp.length()); refBufferInfo->apply_tag_by_name("title", start, end); start = end; state++; } break; case 1: /* Reading body of info section */ while (isspace (*p)) p++; if (*p == '*' && *(p + 1) == '/') { start = refBufferSource->get_iter_at_offset(0); state++; } else { int len; while (*p == '*' || isspace (*p)) p++; len = strlen (p); while (isspace (*(p + len - 1))) len--; if (len > 0) { if (in_para) { start = refBufferInfo->insert(start, " "); } start = refBufferInfo->insert(start, Glib::ustring(p, p + len)); in_para = 1; } else { start = refBufferInfo->insert(start, "\n"); in_para = 0; } } break; case 2: /* Skipping blank lines */ while (isspace (*p)) p++; if (*p) { p = buffer->str; state++; /* Fall through */ } else break; case 3: /* Reading program body */ start = refBufferSource->insert(start, p); start = refBufferSource->insert(start, "\n"); break; } } m_TextWidget_Source.fontify(); } } void DemoWindow::on_example_window_hide() { if(m_pWindow_Example) { if(const Gtk::TreeModel::iterator iter = m_refTreeStore->get_iter(m_TreePath)) { (*iter)[demo_columns().italic] = false; delete m_pWindow_Example; m_pWindow_Example = 0; } } } <commit_msg>demos: Use getc() if HAVE_GETC_UNLOCKED is not defined<commit_after>/* $Id$ */ /* Copyright (C) 2001 The gtkmm Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gtkmm/main.h> #include <gtkmm/cellrenderertext.h> #include <gtkmm/treeviewcolumn.h> #include <gtkmm/box.h> #include <glibmm/convert.h> #include <glibmm/fileutils.h> #include "demowindow.h" #include "textwidget.h" #include "demos.h" #include <vector> #include <cctype> #include <cerrno> #include <stdio.h> #include <cstring> using std::isspace; using std::strlen; #include "demo-common.h" #ifdef NEED_FLOCKFILE_PROTO extern "C" void flockfile (FILE *); #endif #ifdef NEED_FUNLOCKFILE_PROTO extern "C" void funlockfile (FILE *); #endif #ifdef NEED_GETC_UNLOCKED_PROTO extern "C" int getc_unlocked (FILE *); #endif namespace { struct DemoColumns : public Gtk::TreeModelColumnRecord { Gtk::TreeModelColumn<Glib::ustring> title; Gtk::TreeModelColumn<Glib::ustring> filename; Gtk::TreeModelColumn<type_slotDo> slot; Gtk::TreeModelColumn<bool> italic; DemoColumns() { add(title); add(filename); add(slot); add(italic); } }; // Singleton accessor function. const DemoColumns& demo_columns() { static DemoColumns column_record; return column_record; } } // anonymous namespace DemoWindow::DemoWindow() : m_RunButton("Run"), m_HBox(Gtk::ORIENTATION_HORIZONTAL), m_TextWidget_Info(false), m_TextWidget_Source(true) { m_pWindow_Example = 0; configure_header_bar(); add(m_HBox); //Tree: m_refTreeStore = Gtk::TreeStore::create(demo_columns()); m_TreeView.set_model(m_refTreeStore); m_refTreeSelection = m_TreeView.get_selection(); m_refTreeSelection->set_mode(Gtk::SELECTION_BROWSE); m_refTreeSelection->set_select_function( sigc::ptr_fun(&DemoWindow::select_function) ); m_TreeView.set_size_request(200, -1); fill_tree(); //SideBar m_SideBar.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); m_SideBar.get_style_context()->add_class("sidebar"); m_SideBar.add(m_TreeView); m_HBox.pack_start(m_SideBar, Gtk::PACK_SHRINK); //Notebook: m_Notebook.append_page(m_TextWidget_Info, "_Info", true); //true = use mnemonic. m_Notebook.append_page(m_TextWidget_Source, "_Source", true); //true = use mnemonic. m_Notebook.child_property_tab_expand(m_TextWidget_Info) = true; m_Notebook.child_property_tab_expand(m_TextWidget_Source) = true; m_HBox.pack_start(m_Notebook); set_default_size (800, 600); load_file (testgtk_demos[0].filename); show_all(); } void DemoWindow::configure_header_bar() { m_HeaderBar.set_show_close_button(); m_HeaderBar.pack_start(m_RunButton); m_RunButton.get_style_context()->add_class("suggested-action"); m_RunButton.signal_clicked().connect(sigc::mem_fun(*this, &DemoWindow::on_run_button_clicked)); set_titlebar(m_HeaderBar); } void DemoWindow::fill_tree() { const DemoColumns& columns = demo_columns(); /* this code only supports 1 level of children. If we * want more we probably have to use a recursing function. */ for(Demo* d = testgtk_demos; d && d->title; ++d) { Gtk::TreeRow row = *(m_refTreeStore->append()); row[columns.title] = d->title; row[columns.filename] = d->filename; row[columns.slot] = d->slot; row[columns.italic] = false; for(Demo* child = d->children; child && child->title; ++child) { Gtk::TreeRow child_row = *(m_refTreeStore->append(row.children())); child_row[columns.title] = child->title; child_row[columns.filename] = child->filename; child_row[columns.slot] = child->slot; child_row[columns.italic] = false; } } Gtk::CellRendererText* pCell = Gtk::manage(new Gtk::CellRendererText()); pCell->property_style() = Pango::STYLE_ITALIC; Gtk::TreeViewColumn* pColumn = new Gtk::TreeViewColumn("Widget (double click for demo)", *pCell); pColumn->add_attribute(pCell->property_text(), columns.title); pColumn->add_attribute(pCell->property_style_set(), columns.italic); m_TreeView.append_column(*pColumn); m_refTreeSelection->signal_changed().connect(sigc::mem_fun(*this, &DemoWindow::on_treeselection_changed)); m_TreeView.signal_row_activated().connect(sigc::mem_fun(*this, &DemoWindow::on_treeview_row_activated)); m_TreeView.expand_all(); } DemoWindow::~DemoWindow() { on_example_window_hide(); //delete the example window if there is one. } void DemoWindow::on_run_button_clicked() { if(m_pWindow_Example == 0) //Don't open a second window. { if(const Gtk::TreeModel::iterator iter = m_refTreeSelection->get_selected()) { m_TreePath = m_refTreeStore->get_path(iter); run_example(*iter); } } } void DemoWindow::on_treeview_row_activated(const Gtk::TreeModel::Path& path, Gtk::TreeViewColumn* /* model */) { m_TreePath = path; if(m_pWindow_Example == 0) //Don't open a second window. { if(const Gtk::TreeModel::iterator iter = m_TreeView.get_model()->get_iter(m_TreePath)) { run_example(*iter); } } } void DemoWindow::run_example(const Gtk::TreeModel::Row& row) { const DemoColumns& columns = demo_columns(); const type_slotDo& slot = row[columns.slot]; if(slot && (m_pWindow_Example = slot())) { row[columns.italic] = true; m_pWindow_Example->signal_hide().connect(sigc::mem_fun(*this, &DemoWindow::on_example_window_hide)); m_pWindow_Example->show(); } } bool DemoWindow::select_function(const Glib::RefPtr<Gtk::TreeModel>& model, const Gtk::TreeModel::Path& path, bool) { const Gtk::TreeModel::iterator iter = model->get_iter(path); return iter->children().empty(); // only allow leaf nodes to be selected } void DemoWindow::on_treeselection_changed() { if(const Gtk::TreeModel::iterator iter = m_refTreeSelection->get_selected()) { const Glib::ustring filename = (*iter)[demo_columns().filename]; const Glib::ustring title = (*iter)[demo_columns().title]; load_file(Glib::filename_from_utf8(filename)); m_HeaderBar.set_title(title); } } bool DemoWindow::read_line (FILE *stream, GString *str) { int n_read = 0; #ifdef HAVE_FLOCKFILE flockfile (stream); #endif g_string_truncate (str, 0); while (1) { int c; #ifdef HAVE_GETC_UNLOCKED c = getc_unlocked (stream); #else c = getc (stream); #endif if (c == EOF) goto done; else n_read++; switch (c) { case '\r': case '\n': { #ifdef HAVE_GETC_UNLOCKED int next_c = getc_unlocked (stream); #else int next_c = getc (stream); #endif if (!(next_c == EOF || (c == '\r' && next_c == '\n') || (c == '\n' && next_c == '\r'))) ungetc (next_c, stream); goto done; } default: g_string_append_c (str, c); } } done: #ifdef HAVE_FUNLOCKFILE funlockfile (stream); #endif return n_read > 0; } void DemoWindow::load_file(const std::string& filename) { if ( m_current_filename == filename ) { return; } else { m_current_filename = filename; m_TextWidget_Info.wipe(); m_TextWidget_Source.wipe(); Glib::RefPtr<Gtk::TextBuffer> refBufferInfo = m_TextWidget_Info.get_buffer(); Glib::RefPtr<Gtk::TextBuffer> refBufferSource = m_TextWidget_Source.get_buffer(); FILE* file = fopen (filename.c_str(), "r"); if (!file) { try { std::string installed = demo_find_file(filename); file = fopen (installed.c_str(), "r"); } catch (const Glib::FileError& ex) { g_warning ("%s\n", ex.what().c_str()); return; } } if (!file) { g_warning ("Cannot open %s: %s\n", filename.c_str(), g_strerror (errno)); return; } GString *buffer = g_string_new (NULL); int state = 0; bool in_para = false; Gtk::TextBuffer::iterator start = refBufferInfo->get_iter_at_offset(0); while (read_line (file, buffer)) { gchar *p = buffer->str; gchar *q = 0; gchar *r = 0; switch (state) { case 0: /* Reading title */ while (*p == '/' || *p == '*' || isspace (*p)) p++; r = p; while (*r != '/' && strlen (r)) r++; if (strlen (r) > 0) p = r + 1; q = p + strlen (p); while (q > p && isspace (*(q - 1))) q--; if (q > p) { Gtk::TextBuffer::iterator end = start; const Glib::ustring strTemp (p, q); end = refBufferInfo->insert(end, strTemp); start = end; start.backward_chars(strTemp.length()); refBufferInfo->apply_tag_by_name("title", start, end); start = end; state++; } break; case 1: /* Reading body of info section */ while (isspace (*p)) p++; if (*p == '*' && *(p + 1) == '/') { start = refBufferSource->get_iter_at_offset(0); state++; } else { int len; while (*p == '*' || isspace (*p)) p++; len = strlen (p); while (isspace (*(p + len - 1))) len--; if (len > 0) { if (in_para) { start = refBufferInfo->insert(start, " "); } start = refBufferInfo->insert(start, Glib::ustring(p, p + len)); in_para = 1; } else { start = refBufferInfo->insert(start, "\n"); in_para = 0; } } break; case 2: /* Skipping blank lines */ while (isspace (*p)) p++; if (*p) { p = buffer->str; state++; /* Fall through */ } else break; case 3: /* Reading program body */ start = refBufferSource->insert(start, p); start = refBufferSource->insert(start, "\n"); break; } } m_TextWidget_Source.fontify(); } } void DemoWindow::on_example_window_hide() { if(m_pWindow_Example) { if(const Gtk::TreeModel::iterator iter = m_refTreeStore->get_iter(m_TreePath)) { (*iter)[demo_columns().italic] = false; delete m_pWindow_Example; m_pWindow_Example = 0; } } } <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIXercesParser.cpp created: Sat Mar 12 2005 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUIXercesParser.h" #include "CEGUIString.h" #include "CEGUIExceptions.h" #include "CEGUILogger.h" #include "CEGUIResourceProvider.h" #include "CEGUISystem.h" #include "CEGUIXMLHandler.h" #include "CEGUIXMLAttributes.h" #include "CEGUIPropertyHelper.h" #include <iostream> // Debug // Start of CEGUI namespace section namespace CEGUI { // Static data definition for default schema resource group name String XercesParser::d_defaultSchemaResourceGroup(""); //////////////////////////////////////////////////////////////////////////////// // // XercesParser methods // //////////////////////////////////////////////////////////////////////////////// XercesParser::XercesParser(void) { // set ID string d_identifierString = "CEGUI::XercesParser - Official Xerces-C++ based parser module for CEGUI"; } XercesParser::~XercesParser(void) {} void XercesParser::parseXMLFile(XMLHandler& handler, const String& filename, const String& schemaName, const String& resourceGroup) { XERCES_CPP_NAMESPACE_USE; XercesHandler xercesHandler(handler); // create parser SAX2XMLReader* reader = createReader(xercesHandler); try { // set up schema initialiseSchema(reader, schemaName, filename, resourceGroup); // do parse doParse(reader, filename, resourceGroup); } catch(const XMLException& exc) { if (exc.getCode() != XMLExcepts::NoError) { delete reader; char* excmsg = XMLString::transcode(exc.getMessage()); String message("XercesParser::parseXMLFile - An error occurred at line nr. " + PropertyHelper::uintToString((uint)exc.getSrcLine()) + " while parsing XML file '" + filename + "'. Additional information: "); message += excmsg; XMLString::release(&excmsg); throw FileIOException(message); } } catch(const SAXParseException& exc) { delete reader; char* excmsg = XMLString::transcode(exc.getMessage()); String message("XercesParser::parseXMLFile - An error occurred at line nr. " + PropertyHelper::uintToString((uint)exc.getLineNumber()) + " while parsing XML file '" + filename + "'. Additional information: "); message += excmsg; XMLString::release(&excmsg); throw FileIOException(message); } catch(...) { delete reader; Logger::getSingleton().logEvent("XercesParser::parseXMLFile - An unexpected error occurred while parsing XML file '" + filename + "'.", Errors); throw; } // cleanup delete reader; } bool XercesParser::initialiseImpl(void) { XERCES_CPP_NAMESPACE_USE; // initialise Xerces-C XML system try { XMLPlatformUtils::Initialize(); } catch(XMLException& exc) { // prepare a message about the failure char* excmsg = XMLString::transcode(exc.getMessage()); String message("An exception occurred while initialising the Xerces-C XML system. Additional information: "); message += excmsg; XMLString::release(&excmsg); // throw a C string (because it won't try and use logger, which may not be available) throw message.c_str(); } return true; } void XercesParser::cleanupImpl(void) { // cleanup XML stuff XERCES_CPP_NAMESPACE_USE; XMLPlatformUtils::Terminate(); } void XercesParser::populateAttributesBlock(const XERCES_CPP_NAMESPACE::Attributes& src, XMLAttributes& dest) { XERCES_CPP_NAMESPACE_USE; String attributeName; String attributeValue; for (uint i = 0; i < src.getLength(); ++i) { // TODO dalfy: Optimize this using temporary value. attributeName = transcodeXmlCharToString(src.getLocalName(i), XMLString::stringLen(src.getLocalName(i))); attributeValue = transcodeXmlCharToString(src.getValue(i), XMLString::stringLen(src.getValue(i))); dest.add(attributeName, attributeValue); } } String XercesParser::transcodeXmlCharToString(const XMLCh* const xmlch_str, unsigned int inputLength) { XERCES_CPP_NAMESPACE_USE; XMLTransService::Codes res; XMLTranscoder* transcoder = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(XMLRecognizer::UTF_8, res, 4096, XMLPlatformUtils::fgMemoryManager ); if (res == XMLTransService::Ok) { String out; utf8 outBuff[128]; unsigned int outputLength; unsigned int eaten = 0; unsigned int offset = 0; // unsigned int inputLength = XMLString::stringLen(xmlch_str); // dalfy caracters node need to transcode but give the size while (inputLength) { outputLength = transcoder->transcodeTo(xmlch_str + offset, inputLength, outBuff, 128, eaten, XMLTranscoder::UnRep_RepChar); out.append(outBuff, outputLength); offset += eaten; inputLength -= eaten; } delete transcoder; return out; } else { throw GenericException("XercesParser::transcodeXmlCharToString - Internal Error: Could not create UTF-8 string transcoder."); } } void XercesParser::initialiseSchema(XERCES_CPP_NAMESPACE::SAX2XMLReader* reader, const String& schemaName, const String& xmlFilename, const String& resourceGroup) { XERCES_CPP_NAMESPACE_USE; // enable schema use and set validation options reader->setFeature(XMLUni::fgXercesSchema, true); reader->setFeature(XMLUni::fgSAX2CoreValidation, true); reader->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true); // load in the raw schema data RawDataContainer rawSchemaData; // try base filename first, from default resource group try { Logger::getSingleton().logEvent("XercesParser::initialiseSchema - Attempting to load schema from file '" + schemaName + "'."); System::getSingleton().getResourceProvider()->loadRawDataContainer(schemaName, rawSchemaData, d_defaultSchemaResourceGroup); } // oops, no file. Try an alternative instead, using base path and // resource group from the XML file we're going to be processing. catch(InvalidRequestException) { // get path from filename String schemaFilename; size_t pos = xmlFilename.rfind("/"); if (pos == String::npos) pos = xmlFilename.rfind("\\"); if (pos != String::npos) schemaFilename.assign(xmlFilename, 0, pos + 1); // append schema filename schemaFilename += schemaName; // re-try the load operation. Logger::getSingleton().logEvent("XercesParser::initialiseSchema - Attempting to load schema from file '" + schemaFilename + "'."); System::getSingleton().getResourceProvider()->loadRawDataContainer(schemaFilename, rawSchemaData, resourceGroup); } // wrap schema data in a xerces MemBufInputSource object MemBufInputSource schemaData( rawSchemaData.getDataPtr(), static_cast<const unsigned int>(rawSchemaData.getSize()), schemaName.c_str(), false); reader->loadGrammar(schemaData, Grammar::SchemaGrammarType, true); // enable grammar reuse reader->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true); // set schema for usage XMLCh* pval = XMLString::transcode(schemaName.c_str()); reader->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation, pval); XMLString::release(&pval); Logger::getSingleton().logEvent("XercesParser::initialiseSchema - XML schema file '" + schemaName + "' has been initialised."); // use resource provider to release loaded schema data (if it supports this) System::getSingleton().getResourceProvider()->unloadRawDataContainer(rawSchemaData); } XERCES_CPP_NAMESPACE::SAX2XMLReader* XercesParser::createReader(XERCES_CPP_NAMESPACE::DefaultHandler& handler) { XERCES_CPP_NAMESPACE_USE; SAX2XMLReader* reader = XMLReaderFactory::createXMLReader(); // set basic settings we want from parser reader->setFeature(XMLUni::fgSAX2CoreNameSpaces, true); // set handlers reader->setContentHandler(&handler); reader->setErrorHandler(&handler); return reader; } void XercesParser::doParse(XERCES_CPP_NAMESPACE::SAX2XMLReader* parser, const String& xmlFilename, const String& resourceGroup) { XERCES_CPP_NAMESPACE_USE; // use resource provider to load file data RawDataContainer rawXMLData; System::getSingleton().getResourceProvider()->loadRawDataContainer(xmlFilename, rawXMLData, resourceGroup); MemBufInputSource fileData( rawXMLData.getDataPtr(), static_cast<const unsigned int>(rawXMLData.getSize()), xmlFilename.c_str(), false); // perform parse try { parser->parse(fileData); } catch(...) { // use resource provider to release loaded XML source (if it supports this) System::getSingleton().getResourceProvider()->unloadRawDataContainer(rawXMLData); throw; } // use resource provider to release loaded XML source (if it supports this) System::getSingleton().getResourceProvider()->unloadRawDataContainer(rawXMLData); } //////////////////////////////////////////////////////////////////////////////// // // XercesHandler methods // //////////////////////////////////////////////////////////////////////////////// XercesHandler::XercesHandler(XMLHandler& handler) : d_handler(handler) {} XercesHandler::~XercesHandler(void) {} void XercesHandler::startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const XERCES_CPP_NAMESPACE::Attributes& attrs) { XERCES_CPP_NAMESPACE_USE; XMLAttributes cegui_attributes; XercesParser::populateAttributesBlock(attrs, cegui_attributes); String element(XercesParser::transcodeXmlCharToString(localname, XMLString::stringLen(localname))); d_handler.elementStart(element, cegui_attributes); } void XercesHandler::endElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname) { XERCES_CPP_NAMESPACE_USE; String element(XercesParser::transcodeXmlCharToString(localname,XMLString::stringLen(localname))); d_handler.elementEnd(element); } void XercesHandler::characters (const XMLCh *const chars, const unsigned int length) { d_handler.text(XercesParser::transcodeXmlCharToString(chars, length)); } void XercesHandler::warning (const XERCES_CPP_NAMESPACE::SAXParseException &exc) { XERCES_CPP_NAMESPACE_USE; // prepare a message about the warning char* excmsg = XMLString::transcode(exc.getMessage()); String message("Xerces warning: "); message += excmsg; XMLString::release(&excmsg); Logger::getSingleton().logEvent(message); } void XercesHandler::error (const XERCES_CPP_NAMESPACE::SAXParseException &exc) { throw exc; } void XercesHandler::fatalError (const XERCES_CPP_NAMESPACE::SAXParseException &exc) { throw exc; } } // End of CEGUI namespace section <commit_msg>FIX: CEGUIXercesParser was not compiling with 2.8 version of xerces-c++. (http://www.cegui.org.uk/mantis/view.php?id=163).<commit_after>/*********************************************************************** filename: CEGUIXercesParser.cpp created: Sat Mar 12 2005 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUIXercesParser.h" #include "CEGUIString.h" #include "CEGUIExceptions.h" #include "CEGUILogger.h" #include "CEGUIResourceProvider.h" #include "CEGUISystem.h" #include "CEGUIXMLHandler.h" #include "CEGUIXMLAttributes.h" #include "CEGUIPropertyHelper.h" #include <xercesc/validators/schema/SchemaValidator.hpp> #include <iostream> // Debug // Start of CEGUI namespace section namespace CEGUI { // Static data definition for default schema resource group name String XercesParser::d_defaultSchemaResourceGroup(""); //////////////////////////////////////////////////////////////////////////////// // // XercesParser methods // //////////////////////////////////////////////////////////////////////////////// XercesParser::XercesParser(void) { // set ID string d_identifierString = "CEGUI::XercesParser - Official Xerces-C++ based parser module for CEGUI"; } XercesParser::~XercesParser(void) {} void XercesParser::parseXMLFile(XMLHandler& handler, const String& filename, const String& schemaName, const String& resourceGroup) { XERCES_CPP_NAMESPACE_USE; XercesHandler xercesHandler(handler); // create parser SAX2XMLReader* reader = createReader(xercesHandler); try { // set up schema initialiseSchema(reader, schemaName, filename, resourceGroup); // do parse doParse(reader, filename, resourceGroup); } catch(const XMLException& exc) { if (exc.getCode() != XMLExcepts::NoError) { delete reader; char* excmsg = XMLString::transcode(exc.getMessage()); String message("XercesParser::parseXMLFile - An error occurred at line nr. " + PropertyHelper::uintToString((uint)exc.getSrcLine()) + " while parsing XML file '" + filename + "'. Additional information: "); message += excmsg; XMLString::release(&excmsg); throw FileIOException(message); } } catch(const SAXParseException& exc) { delete reader; char* excmsg = XMLString::transcode(exc.getMessage()); String message("XercesParser::parseXMLFile - An error occurred at line nr. " + PropertyHelper::uintToString((uint)exc.getLineNumber()) + " while parsing XML file '" + filename + "'. Additional information: "); message += excmsg; XMLString::release(&excmsg); throw FileIOException(message); } catch(...) { delete reader; Logger::getSingleton().logEvent("XercesParser::parseXMLFile - An unexpected error occurred while parsing XML file '" + filename + "'.", Errors); throw; } // cleanup delete reader; } bool XercesParser::initialiseImpl(void) { XERCES_CPP_NAMESPACE_USE; // initialise Xerces-C XML system try { XMLPlatformUtils::Initialize(); } catch(XMLException& exc) { // prepare a message about the failure char* excmsg = XMLString::transcode(exc.getMessage()); String message("An exception occurred while initialising the Xerces-C XML system. Additional information: "); message += excmsg; XMLString::release(&excmsg); // throw a C string (because it won't try and use logger, which may not be available) throw message.c_str(); } return true; } void XercesParser::cleanupImpl(void) { // cleanup XML stuff XERCES_CPP_NAMESPACE_USE; XMLPlatformUtils::Terminate(); } void XercesParser::populateAttributesBlock(const XERCES_CPP_NAMESPACE::Attributes& src, XMLAttributes& dest) { XERCES_CPP_NAMESPACE_USE; String attributeName; String attributeValue; for (uint i = 0; i < src.getLength(); ++i) { // TODO dalfy: Optimize this using temporary value. attributeName = transcodeXmlCharToString(src.getLocalName(i), XMLString::stringLen(src.getLocalName(i))); attributeValue = transcodeXmlCharToString(src.getValue(i), XMLString::stringLen(src.getValue(i))); dest.add(attributeName, attributeValue); } } String XercesParser::transcodeXmlCharToString(const XMLCh* const xmlch_str, unsigned int inputLength) { XERCES_CPP_NAMESPACE_USE; XMLTransService::Codes res; XMLTranscoder* transcoder = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(XMLRecognizer::UTF_8, res, 4096, XMLPlatformUtils::fgMemoryManager ); if (res == XMLTransService::Ok) { String out; utf8 outBuff[128]; unsigned int outputLength; unsigned int eaten = 0; unsigned int offset = 0; // unsigned int inputLength = XMLString::stringLen(xmlch_str); // dalfy caracters node need to transcode but give the size while (inputLength) { outputLength = transcoder->transcodeTo(xmlch_str + offset, inputLength, outBuff, 128, eaten, XMLTranscoder::UnRep_RepChar); out.append(outBuff, outputLength); offset += eaten; inputLength -= eaten; } delete transcoder; return out; } else { throw GenericException("XercesParser::transcodeXmlCharToString - Internal Error: Could not create UTF-8 string transcoder."); } } void XercesParser::initialiseSchema(XERCES_CPP_NAMESPACE::SAX2XMLReader* reader, const String& schemaName, const String& xmlFilename, const String& resourceGroup) { XERCES_CPP_NAMESPACE_USE; // enable schema use and set validation options reader->setFeature(XMLUni::fgXercesSchema, true); reader->setFeature(XMLUni::fgSAX2CoreValidation, true); reader->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true); // load in the raw schema data RawDataContainer rawSchemaData; // try base filename first, from default resource group try { Logger::getSingleton().logEvent("XercesParser::initialiseSchema - Attempting to load schema from file '" + schemaName + "'."); System::getSingleton().getResourceProvider()->loadRawDataContainer(schemaName, rawSchemaData, d_defaultSchemaResourceGroup); } // oops, no file. Try an alternative instead, using base path and // resource group from the XML file we're going to be processing. catch(InvalidRequestException) { // get path from filename String schemaFilename; size_t pos = xmlFilename.rfind("/"); if (pos == String::npos) pos = xmlFilename.rfind("\\"); if (pos != String::npos) schemaFilename.assign(xmlFilename, 0, pos + 1); // append schema filename schemaFilename += schemaName; // re-try the load operation. Logger::getSingleton().logEvent("XercesParser::initialiseSchema - Attempting to load schema from file '" + schemaFilename + "'."); System::getSingleton().getResourceProvider()->loadRawDataContainer(schemaFilename, rawSchemaData, resourceGroup); } // wrap schema data in a xerces MemBufInputSource object MemBufInputSource schemaData( rawSchemaData.getDataPtr(), static_cast<const unsigned int>(rawSchemaData.getSize()), schemaName.c_str(), false); reader->loadGrammar(schemaData, Grammar::SchemaGrammarType, true); // enable grammar reuse reader->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true); // set schema for usage XMLCh* pval = XMLString::transcode(schemaName.c_str()); reader->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation, pval); XMLString::release(&pval); Logger::getSingleton().logEvent("XercesParser::initialiseSchema - XML schema file '" + schemaName + "' has been initialised."); // use resource provider to release loaded schema data (if it supports this) System::getSingleton().getResourceProvider()->unloadRawDataContainer(rawSchemaData); } XERCES_CPP_NAMESPACE::SAX2XMLReader* XercesParser::createReader(XERCES_CPP_NAMESPACE::DefaultHandler& handler) { XERCES_CPP_NAMESPACE_USE; SAX2XMLReader* reader = XMLReaderFactory::createXMLReader(); // set basic settings we want from parser reader->setFeature(XMLUni::fgSAX2CoreNameSpaces, true); // set handlers reader->setContentHandler(&handler); reader->setErrorHandler(&handler); return reader; } void XercesParser::doParse(XERCES_CPP_NAMESPACE::SAX2XMLReader* parser, const String& xmlFilename, const String& resourceGroup) { XERCES_CPP_NAMESPACE_USE; // use resource provider to load file data RawDataContainer rawXMLData; System::getSingleton().getResourceProvider()->loadRawDataContainer(xmlFilename, rawXMLData, resourceGroup); MemBufInputSource fileData( rawXMLData.getDataPtr(), static_cast<const unsigned int>(rawXMLData.getSize()), xmlFilename.c_str(), false); // perform parse try { parser->parse(fileData); } catch(...) { // use resource provider to release loaded XML source (if it supports this) System::getSingleton().getResourceProvider()->unloadRawDataContainer(rawXMLData); throw; } // use resource provider to release loaded XML source (if it supports this) System::getSingleton().getResourceProvider()->unloadRawDataContainer(rawXMLData); } //////////////////////////////////////////////////////////////////////////////// // // XercesHandler methods // //////////////////////////////////////////////////////////////////////////////// XercesHandler::XercesHandler(XMLHandler& handler) : d_handler(handler) {} XercesHandler::~XercesHandler(void) {} void XercesHandler::startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const XERCES_CPP_NAMESPACE::Attributes& attrs) { XERCES_CPP_NAMESPACE_USE; XMLAttributes cegui_attributes; XercesParser::populateAttributesBlock(attrs, cegui_attributes); String element(XercesParser::transcodeXmlCharToString(localname, XMLString::stringLen(localname))); d_handler.elementStart(element, cegui_attributes); } void XercesHandler::endElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname) { XERCES_CPP_NAMESPACE_USE; String element(XercesParser::transcodeXmlCharToString(localname,XMLString::stringLen(localname))); d_handler.elementEnd(element); } void XercesHandler::characters (const XMLCh *const chars, const unsigned int length) { d_handler.text(XercesParser::transcodeXmlCharToString(chars, length)); } void XercesHandler::warning (const XERCES_CPP_NAMESPACE::SAXParseException &exc) { XERCES_CPP_NAMESPACE_USE; // prepare a message about the warning char* excmsg = XMLString::transcode(exc.getMessage()); String message("Xerces warning: "); message += excmsg; XMLString::release(&excmsg); Logger::getSingleton().logEvent(message); } void XercesHandler::error (const XERCES_CPP_NAMESPACE::SAXParseException &exc) { throw exc; } void XercesHandler::fatalError (const XERCES_CPP_NAMESPACE::SAXParseException &exc) { throw exc; } } // End of CEGUI namespace section <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2013 Hauke Heibel <hauke.heibel@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" #include <Eigen/Core> #if EIGEN_HAS_RVALUE_REFERENCES template <typename MatrixType> void rvalue_copyassign(const MatrixType& m) { typedef typename internal::traits<MatrixType>::Scalar Scalar; // create a temporary which we are about to destroy by moving MatrixType tmp = m; long src_address = reinterpret_cast<long>(tmp.data()); // move the temporary to n MatrixType n = std::move(tmp); long dst_address = reinterpret_cast<long>(n.data()); if (MatrixType::RowsAtCompileTime==Dynamic|| MatrixType::ColsAtCompileTime==Dynamic) { // verify that we actually moved the guts VERIFY_IS_EQUAL(src_address, dst_address); } // verify that the content did not change Scalar abs_diff = (m-n).array().abs().sum(); VERIFY_IS_EQUAL(abs_diff, Scalar(0)); } #else template <typename MatrixType> void rvalue_copyassign(const MatrixType&) {} #endif void test_rvalue_types() { CALL_SUBTEST_1(rvalue_copyassign( MatrixXf::Random(50,50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( ArrayXXf::Random(50,50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( Matrix<float,1,Dynamic>::Random(50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( Array<float,1,Dynamic>::Random(50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( Matrix<float,Dynamic,1>::Random(50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( Array<float,Dynamic,1>::Random(50).eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,2,1>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,3,1>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,4,1>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,2,2>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,3,3>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,4,4>::Random().eval() )); } <commit_msg>Fix pointer to long conversion warning.<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2013 Hauke Heibel <hauke.heibel@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" #include <Eigen/Core> using internal::UIntPtr; #if EIGEN_HAS_RVALUE_REFERENCES template <typename MatrixType> void rvalue_copyassign(const MatrixType& m) { typedef typename internal::traits<MatrixType>::Scalar Scalar; // create a temporary which we are about to destroy by moving MatrixType tmp = m; UIntPtr src_address = reinterpret_cast<UIntPtr>(tmp.data()); // move the temporary to n MatrixType n = std::move(tmp); UIntPtr dst_address = reinterpret_cast<UIntPtr>(n.data()); if (MatrixType::RowsAtCompileTime==Dynamic|| MatrixType::ColsAtCompileTime==Dynamic) { // verify that we actually moved the guts VERIFY_IS_EQUAL(src_address, dst_address); } // verify that the content did not change Scalar abs_diff = (m-n).array().abs().sum(); VERIFY_IS_EQUAL(abs_diff, Scalar(0)); } #else template <typename MatrixType> void rvalue_copyassign(const MatrixType&) {} #endif void test_rvalue_types() { CALL_SUBTEST_1(rvalue_copyassign( MatrixXf::Random(50,50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( ArrayXXf::Random(50,50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( Matrix<float,1,Dynamic>::Random(50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( Array<float,1,Dynamic>::Random(50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( Matrix<float,Dynamic,1>::Random(50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( Array<float,Dynamic,1>::Random(50).eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,2,1>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,3,1>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,4,1>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,2,2>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,3,3>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,4,4>::Random().eval() )); } <|endoftext|>
<commit_before>#include "PlaceholderParser.hpp" #include <ctime> #include <iomanip> #include <sstream> #include <unistd.h> // provides **environ extern char **environ; namespace Slic3r { PlaceholderParser::PlaceholderParser() { this->set("version", SLIC3R_VERSION); this->apply_env_variables(); this->update_timestamp(); } void PlaceholderParser::update_timestamp() { time_t rawtime; time(&rawtime); struct tm* timeinfo = localtime(&rawtime); { std::ostringstream ss; ss << (1900 + timeinfo->tm_year); ss << std::setw(2) << std::setfill('0') << (1 + timeinfo->tm_mon); ss << std::setw(2) << std::setfill('0') << timeinfo->tm_mday; ss << "-"; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_hour; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_min; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_sec; this->set("timestamp", ss.str()); } this->set("year", 1900 + timeinfo->tm_year); this->set("month", 1 + timeinfo->tm_mon); this->set("day", timeinfo->tm_mday); this->set("hour", timeinfo->tm_hour); this->set("minute", timeinfo->tm_min); this->set("second", timeinfo->tm_sec); } void PlaceholderParser::apply_config(const DynamicPrintConfig &config) { t_config_option_keys opt_keys = config.keys(); for (t_config_option_keys::const_iterator i = opt_keys.begin(); i != opt_keys.end(); ++i) { const t_config_option_key &opt_key = *i; const ConfigOptionDef* def = config.def->get(opt_key); if (def->multiline) continue; const ConfigOption* opt = config.option(opt_key); if (const ConfigOptionVectorBase* optv = dynamic_cast<const ConfigOptionVectorBase*>(opt)) { // set placeholders for options with multiple values // TODO: treat [bed_shape] as single, not multiple this->set(opt_key, optv->vserialize()); } else if (const ConfigOptionPoint* optp = dynamic_cast<const ConfigOptionPoint*>(opt)) { this->set(opt_key, optp->serialize()); Pointf val = *optp; this->set(opt_key + "_X", val.x); this->set(opt_key + "_Y", val.y); } else { // set single-value placeholders this->set(opt_key, opt->serialize()); } } } void PlaceholderParser::apply_env_variables() { for (char** env = environ; *env; env++) { if (strncmp(*env, "SLIC3R_", 7) == 0) { std::stringstream ss(*env); std::string key, value; std::getline(ss, key, '='); ss >> value; this->set(key, value); } } } void PlaceholderParser::set(const std::string &key, const std::string &value) { this->_single[key] = value; this->_multiple.erase(key); } void PlaceholderParser::set(const std::string &key, int value) { std::ostringstream ss; ss << value; this->set(key, ss.str()); } void PlaceholderParser::set(const std::string &key, std::vector<std::string> values) { if (values.empty()) { this->_multiple.erase(key); this->_single.erase(key); } else { this->_multiple[key] = values; this->_single[key] = values.front(); } } std::string PlaceholderParser::process(std::string str) const { // replace single options, like [foo] for (t_strstr_map::const_iterator it = this->_single.begin(); it != this->_single.end(); ++it) { std::stringstream ss; ss << '[' << it->first << ']'; this->find_and_replace(str, ss.str(), it->second); } // replace multiple options like [foo_0] by looping until we have enough values // or until a previous match was found (this handles non-existing indices reasonably // without a regex) for (t_strstrs_map::const_iterator it = this->_multiple.begin(); it != this->_multiple.end(); ++it) { const std::vector<std::string> &values = it->second; bool found = false; for (size_t i = 0; (i < values.size()) || found; ++i) { std::stringstream ss; ss << '[' << it->first << '_' << i << ']'; if (i < values.size()) { found = this->find_and_replace(str, ss.str(), values[i]); } else { found = this->find_and_replace(str, ss.str(), values.front()); } } } return str; } bool PlaceholderParser::find_and_replace(std::string &source, std::string const &find, std::string const &replace) const { bool found = false; for (std::string::size_type i = 0; (i = source.find(find, i)) != std::string::npos; ) { source.replace(i, find.length(), replace); i += replace.length(); found = true; } return found; } } <commit_msg>Fix compilation<commit_after>#include "PlaceholderParser.hpp" #include <cstring> #include <ctime> #include <iomanip> #include <sstream> #include <unistd.h> // provides **environ extern char **environ; namespace Slic3r { PlaceholderParser::PlaceholderParser() { this->set("version", SLIC3R_VERSION); this->apply_env_variables(); this->update_timestamp(); } void PlaceholderParser::update_timestamp() { time_t rawtime; time(&rawtime); struct tm* timeinfo = localtime(&rawtime); { std::ostringstream ss; ss << (1900 + timeinfo->tm_year); ss << std::setw(2) << std::setfill('0') << (1 + timeinfo->tm_mon); ss << std::setw(2) << std::setfill('0') << timeinfo->tm_mday; ss << "-"; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_hour; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_min; ss << std::setw(2) << std::setfill('0') << timeinfo->tm_sec; this->set("timestamp", ss.str()); } this->set("year", 1900 + timeinfo->tm_year); this->set("month", 1 + timeinfo->tm_mon); this->set("day", timeinfo->tm_mday); this->set("hour", timeinfo->tm_hour); this->set("minute", timeinfo->tm_min); this->set("second", timeinfo->tm_sec); } void PlaceholderParser::apply_config(const DynamicPrintConfig &config) { t_config_option_keys opt_keys = config.keys(); for (t_config_option_keys::const_iterator i = opt_keys.begin(); i != opt_keys.end(); ++i) { const t_config_option_key &opt_key = *i; const ConfigOptionDef* def = config.def->get(opt_key); if (def->multiline) continue; const ConfigOption* opt = config.option(opt_key); if (const ConfigOptionVectorBase* optv = dynamic_cast<const ConfigOptionVectorBase*>(opt)) { // set placeholders for options with multiple values // TODO: treat [bed_shape] as single, not multiple this->set(opt_key, optv->vserialize()); } else if (const ConfigOptionPoint* optp = dynamic_cast<const ConfigOptionPoint*>(opt)) { this->set(opt_key, optp->serialize()); Pointf val = *optp; this->set(opt_key + "_X", val.x); this->set(opt_key + "_Y", val.y); } else { // set single-value placeholders this->set(opt_key, opt->serialize()); } } } void PlaceholderParser::apply_env_variables() { for (char** env = environ; *env; env++) { if (strncmp(*env, "SLIC3R_", 7) == 0) { std::stringstream ss(*env); std::string key, value; std::getline(ss, key, '='); ss >> value; this->set(key, value); } } } void PlaceholderParser::set(const std::string &key, const std::string &value) { this->_single[key] = value; this->_multiple.erase(key); } void PlaceholderParser::set(const std::string &key, int value) { std::ostringstream ss; ss << value; this->set(key, ss.str()); } void PlaceholderParser::set(const std::string &key, std::vector<std::string> values) { if (values.empty()) { this->_multiple.erase(key); this->_single.erase(key); } else { this->_multiple[key] = values; this->_single[key] = values.front(); } } std::string PlaceholderParser::process(std::string str) const { // replace single options, like [foo] for (t_strstr_map::const_iterator it = this->_single.begin(); it != this->_single.end(); ++it) { std::stringstream ss; ss << '[' << it->first << ']'; this->find_and_replace(str, ss.str(), it->second); } // replace multiple options like [foo_0] by looping until we have enough values // or until a previous match was found (this handles non-existing indices reasonably // without a regex) for (t_strstrs_map::const_iterator it = this->_multiple.begin(); it != this->_multiple.end(); ++it) { const std::vector<std::string> &values = it->second; bool found = false; for (size_t i = 0; (i < values.size()) || found; ++i) { std::stringstream ss; ss << '[' << it->first << '_' << i << ']'; if (i < values.size()) { found = this->find_and_replace(str, ss.str(), values[i]); } else { found = this->find_and_replace(str, ss.str(), values.front()); } } } return str; } bool PlaceholderParser::find_and_replace(std::string &source, std::string const &find, std::string const &replace) const { bool found = false; for (std::string::size_type i = 0; (i = source.find(find, i)) != std::string::npos; ) { source.replace(i, find.length(), replace); i += replace.length(); found = true; } return found; } } <|endoftext|>
<commit_before><commit_msg>we can stop the loop as soon as we found something<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <osrm/Coordinate.h> #include "DouglasPeucker.h" #include "../DataStructures/SegmentInformation.h" #include "../Util/SimpleLogger.h" #include <boost/assert.hpp> #include <cmath> #include <limits> struct CoordinatePairCalculator { CoordinatePairCalculator() = delete; CoordinatePairCalculator(const FixedPointCoordinate & coordinate_a, const FixedPointCoordinate &coordinate_b) { const float RAD = 0.017453292519943295769236907684886; first_lat = (coordinate_a.lat / COORDINATE_PRECISION) * RAD; first_lon = (coordinate_a.lon / COORDINATE_PRECISION) * RAD; second_lat = (coordinate_b.lat / COORDINATE_PRECISION) * RAD; second_lon = (coordinate_b.lon / COORDINATE_PRECISION) * RAD; } int operator()(FixedPointCoordinate & other) const { const float RAD = 0.017453292519943295769236907684886; const float earth_radius = 6372797.560856; const float float_lat1 = (other.lat / COORDINATE_PRECISION) * RAD; const float float_lon1 = (other.lon / COORDINATE_PRECISION) * RAD; const float x_value_1 = (first_lon - float_lon1) * cos((float_lat1 + first_lat) / 2.); const float y_value_1 = first_lat - float_lat1; const float dist1 = sqrt(std::pow(x_value_1, 2) + std::pow(y_value_1,2)) * earth_radius; const float x_value_2 = (second_lon - float_lon1) * cos((float_lat1 + second_lat) / 2.); const float y_value_2 = second_lat - float_lat1; const float dist2 = sqrt(std::pow(x_value_2, 2) + std::pow(y_value_2,2)) * earth_radius; const int other_dist = std::min(dist1, dist2); return other_dist; } float first_lat; float first_lon; float second_lat; float second_lon; }; DouglasPeucker::DouglasPeucker() : douglas_peucker_thresholds({512440, // z0 256720, // z1 122560, // z2 56780, // z3 28800, // z4 14400, // z5 7200, // z6 3200, // z7 2400, // z8 1000, // z9 600, // z10 120, // z11 60, // z12 45, // z13 36, // z14 20, // z15 8, // z16 6, // z17 4 // z18 }) { } void DouglasPeucker::Run(std::vector<SegmentInformation> &input_geometry, const unsigned zoom_level) { input_geometry.front().necessary = true; input_geometry.back().necessary = true; unsigned point_count = 2; BOOST_ASSERT_MSG(!input_geometry.empty(), "geometry invalid"); if (input_geometry.size() < 2) { return; } { BOOST_ASSERT_MSG(zoom_level < 19, "unsupported zoom level"); unsigned left_border = 0; unsigned right_border = 1; // Sweep over array and identify those ranges that need to be checked do { if (input_geometry[right_border].necessary) { BOOST_ASSERT(input_geometry[left_border].necessary); BOOST_ASSERT(input_geometry[right_border].necessary); recursion_stack.emplace(left_border, right_border); left_border = right_border; } ++right_border; } while (right_border < input_geometry.size()); } while (!recursion_stack.empty()) { // pop next element const GeometryRange pair = recursion_stack.top(); recursion_stack.pop(); BOOST_ASSERT_MSG(input_geometry[pair.first].necessary, "left border mus be necessary"); BOOST_ASSERT_MSG(input_geometry[pair.second].necessary, "right border must be necessary"); BOOST_ASSERT_MSG(pair.second < input_geometry.size(), "right border outside of geometry"); BOOST_ASSERT_MSG(pair.first < pair.second, "left border on the wrong side"); int max_int_distance = 0; unsigned farthest_element_index = pair.second; const CoordinatePairCalculator DistCalc(input_geometry[pair.first].location, input_geometry[pair.second].location); for (unsigned i = pair.first + 1; i < pair.second; ++i) { const int distance = DistCalc(input_geometry[i].location); if (distance > max_int_distance && distance > douglas_peucker_thresholds[zoom_level]) { farthest_element_index = i; max_int_distance = distance; } } if (max_int_distance > douglas_peucker_thresholds[zoom_level]) { // mark idx as necessary input_geometry[farthest_element_index].necessary = true; ++point_count; if (1 < (farthest_element_index - pair.first)) { recursion_stack.emplace(pair.first, farthest_element_index); } if (1 < (pair.second - farthest_element_index)) { recursion_stack.emplace(farthest_element_index, pair.second); } } } } <commit_msg>unlinting DouglasPeucker<commit_after>/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <osrm/Coordinate.h> #include "DouglasPeucker.h" #include "../DataStructures/SegmentInformation.h" #include "../Util/SimpleLogger.h" #include <boost/assert.hpp> #include <cmath> #include <limits> struct CoordinatePairCalculator { CoordinatePairCalculator() = delete; CoordinatePairCalculator(const FixedPointCoordinate &coordinate_a, const FixedPointCoordinate &coordinate_b) { // initialize distance calculator with two fixed coordinates a, b const float RAD = 0.017453292519943295769236907684886; first_lat = (coordinate_a.lat / COORDINATE_PRECISION) * RAD; first_lon = (coordinate_a.lon / COORDINATE_PRECISION) * RAD; second_lat = (coordinate_b.lat / COORDINATE_PRECISION) * RAD; second_lon = (coordinate_b.lon / COORDINATE_PRECISION) * RAD; } int operator()(FixedPointCoordinate &other) const { // set third coordinate c const float RAD = 0.017453292519943295769236907684886; const float earth_radius = 6372797.560856; const float float_lat1 = (other.lat / COORDINATE_PRECISION) * RAD; const float float_lon1 = (other.lon / COORDINATE_PRECISION) * RAD; // compute distance (a,c) const float x_value_1 = (first_lon - float_lon1) * cos((float_lat1 + first_lat) / 2.); const float y_value_1 = first_lat - float_lat1; const float dist1 = sqrt(std::pow(x_value_1, 2) + std::pow(y_value_1, 2)) * earth_radius; // compute distance (b,c) const float x_value_2 = (second_lon - float_lon1) * cos((float_lat1 + second_lat) / 2.); const float y_value_2 = second_lat - float_lat1; const float dist2 = sqrt(std::pow(x_value_2, 2) + std::pow(y_value_2, 2)) * earth_radius; // return the minimum return std::min(dist1, dist2); } float first_lat; float first_lon; float second_lat; float second_lon; }; DouglasPeucker::DouglasPeucker() : douglas_peucker_thresholds({512440, // z0 256720, // z1 122560, // z2 56780, // z3 28800, // z4 14400, // z5 7200, // z6 3200, // z7 2400, // z8 1000, // z9 600, // z10 120, // z11 60, // z12 45, // z13 36, // z14 20, // z15 8, // z16 6, // z17 4 // z18 }) { } void DouglasPeucker::Run(std::vector<SegmentInformation> &input_geometry, const unsigned zoom_level) { // check if input data is invalid BOOST_ASSERT_MSG(!input_geometry.empty(), "geometry invalid"); if (input_geometry.size() < 2) { return; } input_geometry.front().necessary = true; input_geometry.back().necessary = true; { BOOST_ASSERT_MSG(zoom_level < 19, "unsupported zoom level"); unsigned left_border = 0; unsigned right_border = 1; // Sweep over array and identify those ranges that need to be checked do { if (input_geometry[right_border].necessary) { BOOST_ASSERT(input_geometry[left_border].necessary); BOOST_ASSERT(input_geometry[right_border].necessary); recursion_stack.emplace(left_border, right_border); left_border = right_border; } ++right_border; } while (right_border < input_geometry.size()); } // mark locations as 'necessary' by divide-and-conquer while (!recursion_stack.empty()) { // pop next element const GeometryRange pair = recursion_stack.top(); recursion_stack.pop(); BOOST_ASSERT_MSG(input_geometry[pair.first].necessary, "left border mus be necessary"); BOOST_ASSERT_MSG(input_geometry[pair.second].necessary, "right border must be necessary"); BOOST_ASSERT_MSG(pair.second < input_geometry.size(), "right border outside of geometry"); BOOST_ASSERT_MSG(pair.first < pair.second, "left border on the wrong side"); int max_int_distance = 0; unsigned farthest_entry_index = pair.second; const CoordinatePairCalculator DistCalc(input_geometry[pair.first].location, input_geometry[pair.second].location); // sweep over range to find the maximum for (unsigned i = pair.first + 1; i < pair.second; ++i) { const int distance = DistCalc(input_geometry[i].location); if (distance > max_int_distance && distance > douglas_peucker_thresholds[zoom_level]) { farthest_entry_index = i; max_int_distance = distance; } } // check if maximum violates a zoom level dependent threshold if (max_int_distance > douglas_peucker_thresholds[zoom_level]) { // mark idx as necessary input_geometry[farthest_entry_index].necessary = true; if (1 < (farthest_entry_index - pair.first)) { recursion_stack.emplace(pair.first, farthest_entry_index); } if (1 < (pair.second - farthest_entry_index)) { recursion_stack.emplace(farthest_entry_index, pair.second); } } } } <|endoftext|>
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <graph/dkrtj_sort.hh> #include <max_clique/colourise.hh> #include <algorithm> #include <iterator> auto parasols::dkrtj_sort(const Graph & graph, std::vector<int> & p) -> void { // pre-calculate degrees and ex-degrees std::vector<std::pair<unsigned, unsigned> > degrees; unsigned max_degree = 0; std::transform(p.begin(), p.end(), std::back_inserter(degrees), [&] (int v) { return std::make_pair(graph.degree(v), 0); }); for (auto & v : p) { if (degrees[v].first > max_degree) max_degree = degrees[v].first; for (auto & w : p) if (graph.adjacent(v, w)) degrees[v].second += degrees[w].first; } auto orig_degrees = degrees; for (auto p_end_unsorted = p.end() ; p_end_unsorted != p.begin() ; ) { // find vertex of minumum degree, with ex-degree tiebreaking. also find // the vertex of max degree, so we can see if all our degrees are the // same. auto p_min_max = std::minmax_element(p.begin(), p_end_unsorted, [&] (int a, int b) { return ( (degrees[a].first < degrees[b].first) || (degrees[a].first == degrees[b].first && degrees[a].second < degrees[b].second) || (degrees[a] == degrees[b] && a > b)); }); // does everything remaining have the same degree? auto all_same = (degrees[*p_min_max.first].first == degrees[*p_min_max.second].first); // update degrees, but not ex-degrees, because it's what DKRTJ does. for (auto & w : p) if (graph.adjacent(*p_min_max.first, w)) --degrees[w].first; // move to end std::swap(*p_min_max.first, *(p_end_unsorted - 1)); --p_end_unsorted; if (all_same) { // this tie-breaking rule is totally sensible, is founded upon // logical mathematical principles, and is not in any way voodoo or // witchcraft. std::sort(p.begin(), p_end_unsorted); std::vector<std::vector<int> > buckets; buckets.resize(std::distance(p.begin(), p_end_unsorted)); for (auto & bucket : buckets) bucket.reserve(buckets.size()); // now colour for (auto v = p.begin() ; v != p_end_unsorted ; ++v) { // find it an appropriate bucket auto bucket = buckets.begin(); for ( ; ; ++bucket) { // is this bucket any good? auto conflicts = false; for (auto & w : *bucket) { if (graph.adjacent(*v, w)) { conflicts = true; break; } } if (! conflicts) break; } bucket->push_back(*v); } // now empty our buckets, in turn, into the result. auto i = 0; for (auto bucket = buckets.begin(), bucket_end = buckets.end() ; bucket != bucket_end ; ++bucket) for (const auto & v : *bucket) p.at(i++) = v; break; } } } <commit_msg>We don't need orig_degrees<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <graph/dkrtj_sort.hh> #include <max_clique/colourise.hh> #include <algorithm> #include <iterator> auto parasols::dkrtj_sort(const Graph & graph, std::vector<int> & p) -> void { // pre-calculate degrees and ex-degrees std::vector<std::pair<unsigned, unsigned> > degrees; unsigned max_degree = 0; std::transform(p.begin(), p.end(), std::back_inserter(degrees), [&] (int v) { return std::make_pair(graph.degree(v), 0); }); for (auto & v : p) { if (degrees[v].first > max_degree) max_degree = degrees[v].first; for (auto & w : p) if (graph.adjacent(v, w)) degrees[v].second += degrees[w].first; } for (auto p_end_unsorted = p.end() ; p_end_unsorted != p.begin() ; ) { // find vertex of minumum degree, with ex-degree tiebreaking. also find // the vertex of max degree, so we can see if all our degrees are the // same. auto p_min_max = std::minmax_element(p.begin(), p_end_unsorted, [&] (int a, int b) { return ( (degrees[a].first < degrees[b].first) || (degrees[a].first == degrees[b].first && degrees[a].second < degrees[b].second) || (degrees[a] == degrees[b] && a > b)); }); // does everything remaining have the same degree? auto all_same = (degrees[*p_min_max.first].first == degrees[*p_min_max.second].first); // update degrees, but not ex-degrees, because it's what DKRTJ does. for (auto & w : p) if (graph.adjacent(*p_min_max.first, w)) --degrees[w].first; // move to end std::swap(*p_min_max.first, *(p_end_unsorted - 1)); --p_end_unsorted; if (all_same) { // this tie-breaking rule is totally sensible, is founded upon // logical mathematical principles, and is not in any way voodoo or // witchcraft. std::sort(p.begin(), p_end_unsorted); std::vector<std::vector<int> > buckets; buckets.resize(std::distance(p.begin(), p_end_unsorted)); for (auto & bucket : buckets) bucket.reserve(buckets.size()); // now colour for (auto v = p.begin() ; v != p_end_unsorted ; ++v) { // find it an appropriate bucket auto bucket = buckets.begin(); for ( ; ; ++bucket) { // is this bucket any good? auto conflicts = false; for (auto & w : *bucket) { if (graph.adjacent(*v, w)) { conflicts = true; break; } } if (! conflicts) break; } bucket->push_back(*v); } // now empty our buckets, in turn, into the result. auto i = 0; for (auto bucket = buckets.begin(), bucket_end = buckets.end() ; bucket != bucket_end ; ++bucket) for (const auto & v : *bucket) p.at(i++) = v; break; } } } <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <gtest/gtest.h> #include <arrayfire.h> #include <af/dim4.hpp> #include <af/traits.hpp> #include <string> #include <vector> #include <iostream> #include <testHelpers.hpp> using std::string; using std::vector; template<typename T> class Histogram : public ::testing::Test { public: virtual void SetUp() {} }; // create a list of types to be tested typedef ::testing::Types<float, double, int, uint, char, uchar> TestTypes; // register the type list TYPED_TEST_CASE(Histogram, TestTypes); template<typename inType, typename outType> void histTest(string pTestFile, unsigned nbins, double minval, double maxval) { if (noDoubleTests<inType>()) return; if (noDoubleTests<outType>()) return; vector<af::dim4> numDims; vector<vector<inType> > in; vector<vector<outType> > tests; readTests<inType,uint,int>(pTestFile,numDims,in,tests); af::dim4 dims = numDims[0]; af_array outArray = 0; af_array inArray = 0; outType *outData; ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<inType>::af_type)); ASSERT_EQ(AF_SUCCESS,af_histogram(&outArray,inArray,nbins,minval,maxval)); outData = new outType[dims.elements()]; ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray)); for (size_t testIter=0; testIter<tests.size(); ++testIter) { vector<outType> currGoldBar = tests[testIter]; size_t nElems = currGoldBar.size(); for (size_t elIter=0; elIter<nElems; ++elIter) { ASSERT_EQ(currGoldBar[elIter],outData[elIter])<< "at: " << elIter<< std::endl; } } // cleanup delete[] outData; ASSERT_EQ(AF_SUCCESS, af_release_array(inArray)); ASSERT_EQ(AF_SUCCESS, af_release_array(outArray)); } TYPED_TEST(Histogram,256Bins0min255max_ones) { histTest<TypeParam,uint>(string(TEST_DIR"/histogram/256bin1min1max.test"),256,0,255); } TYPED_TEST(Histogram,100Bins0min99max) { histTest<TypeParam,uint>(string(TEST_DIR"/histogram/100bin0min99max.test"),100,0,99); } TYPED_TEST(Histogram,40Bins0min100max) { histTest<TypeParam,uint>(string(TEST_DIR"/histogram/40bin0min100max.test"),40,0,100); } TYPED_TEST(Histogram,40Bins0min100max_Batch) { histTest<TypeParam,uint>(string(TEST_DIR"/histogram/40bin0min100max_batch.test"),40,0,100); } TYPED_TEST(Histogram,256Bins0min255max_zeros) { histTest<TypeParam,uint>(string(TEST_DIR"/histogram/256bin0min0max.test"),256,0,255); } /////////////////////////////////// CPP ////////////////////////////////// // TEST(Histogram, CPP) { if (noDoubleTests<float>()) return; if (noDoubleTests<int>()) return; const unsigned nbins = 100; const double minval = 0.0; const double maxval = 99.0; vector<af::dim4> numDims; vector<vector<float> > in; vector<vector<uint> > tests; readTests<float,uint,int>(string(TEST_DIR"/histogram/100bin0min99max.test"),numDims,in,tests); //! [hist_nominmax] af::array input(numDims[0], &(in[0].front())); af::array output = histogram(input, nbins, minval, maxval); //! [hist_nominmax] uint *outData = new uint[output.elements()]; output.host((void*)outData); for (size_t testIter=0; testIter<tests.size(); ++testIter) { vector<uint> currGoldBar = tests[testIter]; size_t nElems = currGoldBar.size(); for (size_t elIter=0; elIter<nElems; ++elIter) { ASSERT_EQ(currGoldBar[elIter],outData[elIter])<< "at: " << elIter<< std::endl; } } // cleanup delete[] outData; } /////////////////////////////////// Documentation Snippets ////////////////////////////////// // TEST(Histogram, SNIPPET_hist_nominmax) { using af::array; using af::histogram; using std::ostream_iterator; using std::cout; using std::endl; unsigned output[] = {3, 1, 2, 0, 0, 0, 0, 1, 1, 1}; //! [ex_image_hist_nominmax] float input[] = {1, 2, 1, 1, 3, 6, 7, 8, 3}; int nbins = 10; size_t nElems = sizeof(input)/sizeof(float); array hist_in(nElems, input); array hist_out = histogram(hist_in, nbins); // hist_out = {3, 1, 2, 0, 0, 0, 0, 1, 1, 1} //! [ex_image_hist_nominmax] vector<unsigned> h_out(nbins); hist_out.host((void*)h_out.data()); if( false == equal(h_out.begin(), h_out.end(), output) ) { cout << "Expected: "; copy(output, output + nbins, ostream_iterator<unsigned>(cout, ", ")); cout << endl << "Actual: "; copy(h_out.begin(), h_out.end(), ostream_iterator<unsigned>(cout, ", ")); FAIL() << "Output did not match"; } } TEST(Histogram, SNIPPET_hist_minmax) { using af::array; using af::histogram; using std::ostream_iterator; using std::cout; using std::endl; unsigned output[] = {0, 3, 1, 2, 0, 0, 1, 1, 1, 0}; //! [ex_image_hist_minmax] float input[] = {1, 2, 1, 1, 3, 6, 7, 8, 3}; int nbins = 10; size_t nElems = sizeof(input)/sizeof(float); array hist_in(nElems, input); array hist_out = histogram(hist_in, nbins, 0, 9); // hist_out = {0, 3, 1, 2, 0, 0, 1, 1, 1, 0} //! [ex_image_hist_minmax] vector<unsigned> h_out(nbins); hist_out.host((void*)h_out.data()); if( false == equal(h_out.begin(), h_out.end(), output) ) { cout << "Expected: "; copy(output, output + nbins, ostream_iterator<unsigned>(cout, ", ")); cout << endl << "Actual: "; copy(h_out.begin(), h_out.end(), ostream_iterator<unsigned>(cout, ", ")); FAIL() << "Output did not match"; } } TEST(Histogram, SNIPPET_histequal) { using af::array; using af::histogram; using std::ostream_iterator; using std::cout; using std::endl; float output[] = { 1.5, 4.5, 1.5, 1.5, 4.5, 4.5, 6.0, 7.5, 4.5 }; //! [ex_image_histequal] float input[] = {1, 2, 1, 1, 3, 6, 7, 8, 3}; int nbins = 10; size_t nElems = sizeof(input)/sizeof(float); array hist_in(nElems, input); array hist_out = histogram(hist_in, nbins); // input after histogram equalization or normalization // based on histogram provided array eq_out = histEqual(hist_in, hist_out); // eq_out = { 1.5, 4.5, 1.5, 1.5, 4.5, 4.5, 6.0, 7.5, 4.5 } //! [ex_image_histequal] vector<float> h_out(nElems); eq_out.host((void*)h_out.data()); if( false == equal(h_out.begin(), h_out.end(), output) ) { cout << "Expected: "; copy(output, output + nbins, ostream_iterator<float>(cout, ", ")); cout << endl << "Actual: "; copy(h_out.begin(), h_out.end(), ostream_iterator<float>(cout, ", ")); FAIL() << "Output did not match"; } } TEST(histogram, GFOR) { using namespace af; dim4 dims = dim4(100, 100, 3); array A = round(100 * randu(dims)); array B = constant(0, 100, 1, 3); gfor(seq ii, 3) { B(span, span, ii) = histogram(A(span, span, ii), 100); } for(int ii = 0; ii < 3; ii++) { array c_ii = histogram(A(span, span, ii), 100); array b_ii = B(span, span, ii); ASSERT_EQ(max<double>(abs(c_ii - b_ii)) < 1E-5, true); } } TEST(histogram, IndexedArray) { using namespace af; const long int LEN = 32; array A = range(LEN, 2); for (int i=16; i<28; ++i) { A(seq(i, i+3), span) = i/4 - 1; } array B = A(seq(20), span); array C = histogram(B, 4); unsigned out[4]; C.host((void*)out); ASSERT_EQ(true, out[0] == 16); ASSERT_EQ(true, out[1] == 8); ASSERT_EQ(true, out[2] == 8); ASSERT_EQ(true, out[3] == 8); } <commit_msg>type cast fix in histogram unit test<commit_after>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <gtest/gtest.h> #include <arrayfire.h> #include <af/dim4.hpp> #include <af/traits.hpp> #include <string> #include <vector> #include <iostream> #include <testHelpers.hpp> using std::string; using std::vector; template<typename T> class Histogram : public ::testing::Test { public: virtual void SetUp() {} }; // create a list of types to be tested typedef ::testing::Types<float, double, int, uint, char, uchar> TestTypes; // register the type list TYPED_TEST_CASE(Histogram, TestTypes); template<typename inType, typename outType> void histTest(string pTestFile, unsigned nbins, double minval, double maxval) { if (noDoubleTests<inType>()) return; if (noDoubleTests<outType>()) return; vector<af::dim4> numDims; vector<vector<inType> > in; vector<vector<outType> > tests; readTests<inType,uint,int>(pTestFile,numDims,in,tests); af::dim4 dims = numDims[0]; af_array outArray = 0; af_array inArray = 0; outType *outData; ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<inType>::af_type)); ASSERT_EQ(AF_SUCCESS,af_histogram(&outArray,inArray,nbins,minval,maxval)); outData = new outType[dims.elements()]; ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray)); for (size_t testIter=0; testIter<tests.size(); ++testIter) { vector<outType> currGoldBar = tests[testIter]; size_t nElems = currGoldBar.size(); for (size_t elIter=0; elIter<nElems; ++elIter) { ASSERT_EQ(currGoldBar[elIter],outData[elIter])<< "at: " << elIter<< std::endl; } } // cleanup delete[] outData; ASSERT_EQ(AF_SUCCESS, af_release_array(inArray)); ASSERT_EQ(AF_SUCCESS, af_release_array(outArray)); } TYPED_TEST(Histogram,256Bins0min255max_ones) { histTest<TypeParam,uint>(string(TEST_DIR"/histogram/256bin1min1max.test"),256,0,255); } TYPED_TEST(Histogram,100Bins0min99max) { histTest<TypeParam,uint>(string(TEST_DIR"/histogram/100bin0min99max.test"),100,0,99); } TYPED_TEST(Histogram,40Bins0min100max) { histTest<TypeParam,uint>(string(TEST_DIR"/histogram/40bin0min100max.test"),40,0,100); } TYPED_TEST(Histogram,40Bins0min100max_Batch) { histTest<TypeParam,uint>(string(TEST_DIR"/histogram/40bin0min100max_batch.test"),40,0,100); } TYPED_TEST(Histogram,256Bins0min255max_zeros) { histTest<TypeParam,uint>(string(TEST_DIR"/histogram/256bin0min0max.test"),256,0,255); } /////////////////////////////////// CPP ////////////////////////////////// // TEST(Histogram, CPP) { if (noDoubleTests<float>()) return; if (noDoubleTests<int>()) return; const unsigned nbins = 100; const double minval = 0.0; const double maxval = 99.0; vector<af::dim4> numDims; vector<vector<float> > in; vector<vector<uint> > tests; readTests<float,uint,int>(string(TEST_DIR"/histogram/100bin0min99max.test"),numDims,in,tests); //! [hist_nominmax] af::array input(numDims[0], &(in[0].front())); af::array output = histogram(input, nbins, minval, maxval); //! [hist_nominmax] uint *outData = new uint[output.elements()]; output.host((void*)outData); for (size_t testIter=0; testIter<tests.size(); ++testIter) { vector<uint> currGoldBar = tests[testIter]; size_t nElems = currGoldBar.size(); for (size_t elIter=0; elIter<nElems; ++elIter) { ASSERT_EQ(currGoldBar[elIter],outData[elIter])<< "at: " << elIter<< std::endl; } } // cleanup delete[] outData; } /////////////////////////////////// Documentation Snippets ////////////////////////////////// // TEST(Histogram, SNIPPET_hist_nominmax) { using af::array; using af::histogram; using std::ostream_iterator; using std::cout; using std::endl; unsigned output[] = {3, 1, 2, 0, 0, 0, 0, 1, 1, 1}; //! [ex_image_hist_nominmax] float input[] = {1, 2, 1, 1, 3, 6, 7, 8, 3}; int nbins = 10; size_t nElems = sizeof(input)/sizeof(float); array hist_in(nElems, input); array hist_out = histogram(hist_in, nbins); // hist_out = {3, 1, 2, 0, 0, 0, 0, 1, 1, 1} //! [ex_image_hist_nominmax] vector<unsigned> h_out(nbins); hist_out.host((void*)h_out.data()); if( false == equal(h_out.begin(), h_out.end(), output) ) { cout << "Expected: "; copy(output, output + nbins, ostream_iterator<unsigned>(cout, ", ")); cout << endl << "Actual: "; copy(h_out.begin(), h_out.end(), ostream_iterator<unsigned>(cout, ", ")); FAIL() << "Output did not match"; } } TEST(Histogram, SNIPPET_hist_minmax) { using af::array; using af::histogram; using std::ostream_iterator; using std::cout; using std::endl; unsigned output[] = {0, 3, 1, 2, 0, 0, 1, 1, 1, 0}; //! [ex_image_hist_minmax] float input[] = {1, 2, 1, 1, 3, 6, 7, 8, 3}; int nbins = 10; size_t nElems = sizeof(input)/sizeof(float); array hist_in(nElems, input); array hist_out = histogram(hist_in, nbins, 0, 9); // hist_out = {0, 3, 1, 2, 0, 0, 1, 1, 1, 0} //! [ex_image_hist_minmax] vector<unsigned> h_out(nbins); hist_out.host((void*)h_out.data()); if( false == equal(h_out.begin(), h_out.end(), output) ) { cout << "Expected: "; copy(output, output + nbins, ostream_iterator<unsigned>(cout, ", ")); cout << endl << "Actual: "; copy(h_out.begin(), h_out.end(), ostream_iterator<unsigned>(cout, ", ")); FAIL() << "Output did not match"; } } TEST(Histogram, SNIPPET_histequal) { using af::array; using af::histogram; using std::ostream_iterator; using std::cout; using std::endl; float output[] = { 1.5, 4.5, 1.5, 1.5, 4.5, 4.5, 6.0, 7.5, 4.5 }; //! [ex_image_histequal] float input[] = {1, 2, 1, 1, 3, 6, 7, 8, 3}; int nbins = 10; size_t nElems = sizeof(input)/sizeof(float); array hist_in(nElems, input); array hist_out = histogram(hist_in, nbins); // input after histogram equalization or normalization // based on histogram provided array eq_out = histEqual(hist_in, hist_out); // eq_out = { 1.5, 4.5, 1.5, 1.5, 4.5, 4.5, 6.0, 7.5, 4.5 } //! [ex_image_histequal] vector<float> h_out(nElems); eq_out.host((void*)h_out.data()); if( false == equal(h_out.begin(), h_out.end(), output) ) { cout << "Expected: "; copy(output, output + nbins, ostream_iterator<float>(cout, ", ")); cout << endl << "Actual: "; copy(h_out.begin(), h_out.end(), ostream_iterator<float>(cout, ", ")); FAIL() << "Output did not match"; } } TEST(histogram, GFOR) { using namespace af; dim4 dims = dim4(100, 100, 3); array A = round(100 * randu(dims)); array B = constant(0, 100, 1, 3); gfor(seq ii, 3) { B(span, span, ii) = histogram(A(span, span, ii), 100); } for(int ii = 0; ii < 3; ii++) { array c_ii = histogram(A(span, span, ii), 100); array b_ii = B(span, span, ii); ASSERT_EQ(max<double>(abs(c_ii - b_ii)) < 1E-5, true); } } TEST(histogram, IndexedArray) { using namespace af; const dim_t LEN = 32; array A = range(LEN, (dim_t)2); for (int i=16; i<28; ++i) { A(seq(i, i+3), span) = i/4 - 1; } array B = A(seq(20), span); array C = histogram(B, 4); unsigned out[4]; C.host((void*)out); ASSERT_EQ(true, out[0] == 16); ASSERT_EQ(true, out[1] == 8); ASSERT_EQ(true, out[2] == 8); ASSERT_EQ(true, out[3] == 8); } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 2004, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //____________________________________________________________________ // // Concrete implementation of AliFMDDetector // // This implements the geometry for FMD1 // #include "AliFMD1.h" // ALIFMD1_H #include "AliFMDRing.h" // ALIFMDRING_H //==================================================================== ClassImp(AliFMD1) #if 0 ; // This is to keep Emacs from indenting the next line #endif //____________________________________________________________________ AliFMD1::AliFMD1(AliFMDRing* inner) : AliFMDDetector(1, inner, 0) { SetInnerZ(340); } //____________________________________________________________________ // // EOF // <commit_msg>FMD1 position at 320 (see FMD TDR table 4.1)<commit_after>/************************************************************************** * Copyright(c) 2004, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //____________________________________________________________________ // // Concrete implementation of AliFMDDetector // // This implements the geometry for FMD1 // #include "AliFMD1.h" // ALIFMD1_H #include "AliFMDRing.h" // ALIFMDRING_H //==================================================================== ClassImp(AliFMD1) #if 0 ; // This is to keep Emacs from indenting the next line #endif //____________________________________________________________________ AliFMD1::AliFMD1(AliFMDRing* inner) : AliFMDDetector(1, inner, 0) { SetInnerZ(320); } //____________________________________________________________________ // // EOF // <|endoftext|>
<commit_before>//===--- DeadFunctionElimination.cpp - Eliminate dead functions -----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-dead-function-elimination" #include "swift/SILAnalysis/CallGraphAnalysis.h" #include "swift/SILPasses/Passes.h" #include "swift/SILPasses/Transforms.h" #include "swift/SIL/PatternMatch.h" #include "swift/SIL/Projection.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILVisitor.h" #include "swift/SILPasses/Utils/Local.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Debug.h" using namespace swift; STATISTIC(NumDeadFunc, "Number of dead functions eliminated"); namespace { struct FinalEliminator { llvm::SmallSetVector<SILFunction*, 16> Worklist; // Update module information before actually removing a SILFunction. void updateBeforeRemoveFunction(SILFunction *F) { // Collect all FRIs and insert the callees to the work list. for (auto &BB : *F) for (auto &I : BB) if (auto FRI = dyn_cast<FunctionRefInst>(&I)) Worklist.insert(FRI->getReferencedFunction()); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Utility Functions //===----------------------------------------------------------------------===// bool tryToRemoveFunction(SILFunction *F, FinalEliminator *FE = nullptr) { // Remove internal functions that are not referenced by anything. // TODO: top_level_code is currently marked as internal so we explicitly check // for functions with this name and keep them around. if (isPossiblyUsedExternally(F->getLinkage()) || F->getRefCount() || F->getName() == SWIFT_ENTRY_POINT_FUNCTION) return false; DEBUG(llvm::dbgs() << "DEAD FUNCTION ELIMINATION: Erasing:" << F->getName() << "\n"); if (FE) { FE->updateBeforeRemoveFunction(F); } F->getModule().eraseFunction(F); NumDeadFunc++; return true; } //===----------------------------------------------------------------------===// // Pass Definition and Entry Points //===----------------------------------------------------------------------===// namespace { class SILDeadFuncElimination : public SILModuleTransform { void run() override { CallGraphAnalysis *CGA = PM->getAnalysis<CallGraphAnalysis>(); SILModule *M = getModule(); bool Changed = false; // Erase trivially dead functions that may not be a part of the call graph. for (auto FI = M->begin(), EI = M->end(); FI != EI;) { SILFunction *F = FI++; Changed |= tryToRemoveFunction(F); } if (Changed) CGA->invalidate(SILAnalysis::InvalidationKind::CallGraph); // If we are debugging serialization, don't eliminate any dead functions. if (getOptions().DebugSerialization) return; // A bottom-up list of functions, leafs first. const std::vector<SILFunction *> &Order = CGA->bottomUpCallGraphOrder(); // Scan the call graph top-down (caller first) because eliminating functions // can generate more opportunities. for (int i = Order.size() - 1; i >= 0; i--) Changed |= tryToRemoveFunction(Order[i]); // Invalidate the call graph. if (Changed) invalidateAnalysis(SILAnalysis::InvalidationKind::CallGraph); } StringRef getName() override { return "Dead Function Elimination"; } }; } // end anonymous namespace SILTransform *swift::createDeadFunctionElimination() { return new SILDeadFuncElimination(); } bool swift::performSILElimination(SILModule *M) { bool Changed = false; llvm::SmallSet<SILFunction *, 16> removedFuncs; FinalEliminator FE; for (auto FI = M->begin(), EI = M->end(); FI != EI;) { SILFunction *F = FI++; if (tryToRemoveFunction(F, &FE)) { Changed = true; removedFuncs.insert(F); } } while (!FE.Worklist.empty()) { llvm::SmallSetVector<SILFunction *, 16> CurrWorklist = FE.Worklist; FE.Worklist.clear(); for (auto entry : CurrWorklist) if (!removedFuncs.count(entry)) if (tryToRemoveFunction(entry, &FE)) { Changed = true; removedFuncs.insert(entry); } } return Changed; } <commit_msg>Small clean-up in dead function elimination.<commit_after>//===--- DeadFunctionElimination.cpp - Eliminate dead functions -----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-dead-function-elimination" #include "swift/SILAnalysis/CallGraphAnalysis.h" #include "swift/SILPasses/Passes.h" #include "swift/SILPasses/Transforms.h" #include "swift/SIL/PatternMatch.h" #include "swift/SIL/Projection.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILVisitor.h" #include "swift/SILPasses/Utils/Local.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Debug.h" using namespace swift; STATISTIC(NumDeadFunc, "Number of dead functions eliminated"); namespace { struct FinalEliminator { llvm::SmallSetVector<SILFunction*, 16> Worklist; // Update module information before actually removing a SILFunction. void updateBeforeRemoveFunction(SILFunction *F) { // Collect all FRIs and insert the callees to the work list. for (auto &BB : *F) for (auto &I : BB) if (auto FRI = dyn_cast<FunctionRefInst>(&I)) Worklist.insert(FRI->getReferencedFunction()); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Utility Functions //===----------------------------------------------------------------------===// bool tryToRemoveFunction(SILFunction *F, FinalEliminator *FE = nullptr) { // Remove internal functions that are not referenced by anything. // TODO: top_level_code is currently marked as internal so we explicitly check // for functions with this name and keep them around. if (isPossiblyUsedExternally(F->getLinkage()) || F->getRefCount() || F->getName() == SWIFT_ENTRY_POINT_FUNCTION) return false; DEBUG(llvm::dbgs() << "DEAD FUNCTION ELIMINATION: Erasing:" << F->getName() << "\n"); if (FE) { FE->updateBeforeRemoveFunction(F); } F->getModule().eraseFunction(F); NumDeadFunc++; return true; } //===----------------------------------------------------------------------===// // Pass Definition and Entry Points //===----------------------------------------------------------------------===// namespace { class SILDeadFuncElimination : public SILModuleTransform { void run() override { CallGraphAnalysis *CGA = PM->getAnalysis<CallGraphAnalysis>(); SILModule *M = getModule(); bool Changed = false; // Erase trivially dead functions that may not be a part of the call graph. for (auto FI = M->begin(), EI = M->end(); FI != EI;) { SILFunction *F = FI++; Changed |= tryToRemoveFunction(F); } if (Changed) CGA->invalidate(SILAnalysis::InvalidationKind::CallGraph); // If we are debugging serialization, don't eliminate any dead functions. if (getOptions().DebugSerialization) return; // A bottom-up list of functions, leafs first. const std::vector<SILFunction *> &Order = CGA->bottomUpCallGraphOrder(); // Scan the call graph top-down (caller first) because eliminating functions // can generate more opportunities. for (auto I = Order.rbegin(), E = Order.rend(); I != E; ++I) Changed |= tryToRemoveFunction(*I); // Invalidate the call graph. if (Changed) invalidateAnalysis(SILAnalysis::InvalidationKind::CallGraph); } StringRef getName() override { return "Dead Function Elimination"; } }; } // end anonymous namespace SILTransform *swift::createDeadFunctionElimination() { return new SILDeadFuncElimination(); } bool swift::performSILElimination(SILModule *M) { bool Changed = false; llvm::SmallSet<SILFunction *, 16> removedFuncs; FinalEliminator FE; for (auto FI = M->begin(), EI = M->end(); FI != EI;) { SILFunction *F = FI++; if (tryToRemoveFunction(F, &FE)) { Changed = true; removedFuncs.insert(F); } } while (!FE.Worklist.empty()) { llvm::SmallSetVector<SILFunction *, 16> CurrWorklist = FE.Worklist; FE.Worklist.clear(); for (auto entry : CurrWorklist) if (!removedFuncs.count(entry)) if (tryToRemoveFunction(entry, &FE)) { Changed = true; removedFuncs.insert(entry); } } return Changed; } <|endoftext|>
<commit_before>//===-- SIFixSGPRLiveRanges.cpp - Fix SGPR live ranges ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file SALU instructions ignore the execution mask, so we need to modify the /// live ranges of the registers they define in some cases. /// /// The main case we need to handle is when a def is used in one side of a /// branch and not another. For example: /// /// %def /// IF /// ... /// ... /// ELSE /// %use /// ... /// ENDIF /// /// Here we need the register allocator to avoid assigning any of the defs /// inside of the IF to the same register as %def. In traditional live /// interval analysis %def is not live inside the IF branch, however, since /// SALU instructions inside of IF will be executed even if the branch is not /// taken, there is the chance that one of the instructions will overwrite the /// value of %def, so the use in ELSE will see the wrong value. /// /// The strategy we use for solving this is to add an extra use after the ENDIF: /// /// %def /// IF /// ... /// ... /// ELSE /// %use /// ... /// ENDIF /// %use /// /// Adding this use will make the def live throughout the IF branch, which is /// what we want. #include "AMDGPU.h" #include "SIInstrInfo.h" #include "SIRegisterInfo.h" #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachinePostDominators.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" using namespace llvm; #define DEBUG_TYPE "si-fix-sgpr-live-ranges" namespace { class SIFixSGPRLiveRanges : public MachineFunctionPass { public: static char ID; public: SIFixSGPRLiveRanges() : MachineFunctionPass(ID) { initializeSIFixSGPRLiveRangesPass(*PassRegistry::getPassRegistry()); } bool runOnMachineFunction(MachineFunction &MF) override; const char *getPassName() const override { return "SI Fix SGPR live ranges"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<LiveIntervals>(); AU.addRequired<MachinePostDominatorTree>(); AU.setPreservesCFG(); MachineFunctionPass::getAnalysisUsage(AU); } }; } // End anonymous namespace. INITIALIZE_PASS_BEGIN(SIFixSGPRLiveRanges, DEBUG_TYPE, "SI Fix SGPR Live Ranges", false, false) INITIALIZE_PASS_DEPENDENCY(LiveIntervals) INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree) INITIALIZE_PASS_END(SIFixSGPRLiveRanges, DEBUG_TYPE, "SI Fix SGPR Live Ranges", false, false) char SIFixSGPRLiveRanges::ID = 0; char &llvm::SIFixSGPRLiveRangesID = SIFixSGPRLiveRanges::ID; FunctionPass *llvm::createSIFixSGPRLiveRangesPass() { return new SIFixSGPRLiveRanges(); } bool SIFixSGPRLiveRanges::runOnMachineFunction(MachineFunction &MF) { MachineRegisterInfo &MRI = MF.getRegInfo(); const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>( MF.getSubtarget().getRegisterInfo()); LiveIntervals *LIS = &getAnalysis<LiveIntervals>(); MachinePostDominatorTree *PDT = &getAnalysis<MachinePostDominatorTree>(); std::vector<std::pair<unsigned, LiveRange *>> SGPRLiveRanges; // First pass, collect all live intervals for SGPRs for (const MachineBasicBlock &MBB : MF) { for (const MachineInstr &MI : MBB) { for (const MachineOperand &MO : MI.defs()) { if (MO.isImplicit()) continue; unsigned Def = MO.getReg(); if (TargetRegisterInfo::isVirtualRegister(Def)) { if (TRI->isSGPRClass(MRI.getRegClass(Def))) SGPRLiveRanges.push_back( std::make_pair(Def, &LIS->getInterval(Def))); } else if (TRI->isSGPRClass(TRI->getPhysRegClass(Def))) { SGPRLiveRanges.push_back( std::make_pair(Def, &LIS->getRegUnit(Def))); } } } } // Second pass fix the intervals for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE; ++BI) { MachineBasicBlock &MBB = *BI; if (MBB.succ_size() < 2) continue; // We have structured control flow, so the number of successors should be // two. assert(MBB.succ_size() == 2); MachineBasicBlock *SuccA = *MBB.succ_begin(); MachineBasicBlock *SuccB = *(++MBB.succ_begin()); MachineBasicBlock *NCD = PDT->findNearestCommonDominator(SuccA, SuccB); if (!NCD) continue; MachineBasicBlock::iterator NCDTerm = NCD->getFirstTerminator(); if (NCDTerm != NCD->end() && NCDTerm->getOpcode() == AMDGPU::SI_ELSE) { assert(NCD->succ_size() == 2); // We want to make sure we insert the Use after the ENDIF, not after // the ELSE. NCD = PDT->findNearestCommonDominator(*NCD->succ_begin(), *(++NCD->succ_begin())); } assert(SuccA && SuccB); for (std::pair<unsigned, LiveRange*> RegLR : SGPRLiveRanges) { unsigned Reg = RegLR.first; LiveRange *LR = RegLR.second; // FIXME: We could be smarter here. If the register is Live-In to one // block, but the other doesn't have any SGPR defs, then there won't be a // conflict. Also, if the branch condition is uniform then there will be // no conflict. bool LiveInToA = LIS->isLiveInToMBB(*LR, SuccA); bool LiveInToB = LIS->isLiveInToMBB(*LR, SuccB); if ((!LiveInToA && !LiveInToB) || (LiveInToA && LiveInToB)) continue; // This interval is live in to one successor, but not the other, so // we need to update its range so it is live in to both. DEBUG(dbgs() << "Possible SGPR conflict detected " << " in " << *LR << " BB#" << SuccA->getNumber() << ", BB#" << SuccB->getNumber() << " with NCD = " << NCD->getNumber() << '\n'); // FIXME: Need to figure out how to update LiveRange here so this pass // will be able to preserve LiveInterval analysis. BuildMI(*NCD, NCD->getFirstNonPHI(), DebugLoc(), TII->get(AMDGPU::SGPR_USE)) .addReg(Reg, RegState::Implicit); DEBUG(NCD->getFirstNonPHI()->dump()); } } return false; } <commit_msg>AMDGPU: Remove unnecessary assert<commit_after>//===-- SIFixSGPRLiveRanges.cpp - Fix SGPR live ranges ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file SALU instructions ignore the execution mask, so we need to modify the /// live ranges of the registers they define in some cases. /// /// The main case we need to handle is when a def is used in one side of a /// branch and not another. For example: /// /// %def /// IF /// ... /// ... /// ELSE /// %use /// ... /// ENDIF /// /// Here we need the register allocator to avoid assigning any of the defs /// inside of the IF to the same register as %def. In traditional live /// interval analysis %def is not live inside the IF branch, however, since /// SALU instructions inside of IF will be executed even if the branch is not /// taken, there is the chance that one of the instructions will overwrite the /// value of %def, so the use in ELSE will see the wrong value. /// /// The strategy we use for solving this is to add an extra use after the ENDIF: /// /// %def /// IF /// ... /// ... /// ELSE /// %use /// ... /// ENDIF /// %use /// /// Adding this use will make the def live throughout the IF branch, which is /// what we want. #include "AMDGPU.h" #include "SIInstrInfo.h" #include "SIRegisterInfo.h" #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachinePostDominators.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" using namespace llvm; #define DEBUG_TYPE "si-fix-sgpr-live-ranges" namespace { class SIFixSGPRLiveRanges : public MachineFunctionPass { public: static char ID; public: SIFixSGPRLiveRanges() : MachineFunctionPass(ID) { initializeSIFixSGPRLiveRangesPass(*PassRegistry::getPassRegistry()); } bool runOnMachineFunction(MachineFunction &MF) override; const char *getPassName() const override { return "SI Fix SGPR live ranges"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<LiveIntervals>(); AU.addRequired<MachinePostDominatorTree>(); AU.setPreservesCFG(); MachineFunctionPass::getAnalysisUsage(AU); } }; } // End anonymous namespace. INITIALIZE_PASS_BEGIN(SIFixSGPRLiveRanges, DEBUG_TYPE, "SI Fix SGPR Live Ranges", false, false) INITIALIZE_PASS_DEPENDENCY(LiveIntervals) INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree) INITIALIZE_PASS_END(SIFixSGPRLiveRanges, DEBUG_TYPE, "SI Fix SGPR Live Ranges", false, false) char SIFixSGPRLiveRanges::ID = 0; char &llvm::SIFixSGPRLiveRangesID = SIFixSGPRLiveRanges::ID; FunctionPass *llvm::createSIFixSGPRLiveRangesPass() { return new SIFixSGPRLiveRanges(); } bool SIFixSGPRLiveRanges::runOnMachineFunction(MachineFunction &MF) { MachineRegisterInfo &MRI = MF.getRegInfo(); const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>( MF.getSubtarget().getRegisterInfo()); LiveIntervals *LIS = &getAnalysis<LiveIntervals>(); MachinePostDominatorTree *PDT = &getAnalysis<MachinePostDominatorTree>(); std::vector<std::pair<unsigned, LiveRange *>> SGPRLiveRanges; // First pass, collect all live intervals for SGPRs for (const MachineBasicBlock &MBB : MF) { for (const MachineInstr &MI : MBB) { for (const MachineOperand &MO : MI.defs()) { if (MO.isImplicit()) continue; unsigned Def = MO.getReg(); if (TargetRegisterInfo::isVirtualRegister(Def)) { if (TRI->isSGPRClass(MRI.getRegClass(Def))) SGPRLiveRanges.push_back( std::make_pair(Def, &LIS->getInterval(Def))); } else if (TRI->isSGPRClass(TRI->getPhysRegClass(Def))) { SGPRLiveRanges.push_back( std::make_pair(Def, &LIS->getRegUnit(Def))); } } } } // Second pass fix the intervals for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE; ++BI) { MachineBasicBlock &MBB = *BI; if (MBB.succ_size() < 2) continue; // We have structured control flow, so the number of successors should be // two. assert(MBB.succ_size() == 2); MachineBasicBlock *SuccA = *MBB.succ_begin(); MachineBasicBlock *SuccB = *(++MBB.succ_begin()); MachineBasicBlock *NCD = PDT->findNearestCommonDominator(SuccA, SuccB); if (!NCD) continue; MachineBasicBlock::iterator NCDTerm = NCD->getFirstTerminator(); if (NCDTerm != NCD->end() && NCDTerm->getOpcode() == AMDGPU::SI_ELSE) { assert(NCD->succ_size() == 2); // We want to make sure we insert the Use after the ENDIF, not after // the ELSE. NCD = PDT->findNearestCommonDominator(*NCD->succ_begin(), *(++NCD->succ_begin())); } for (std::pair<unsigned, LiveRange*> RegLR : SGPRLiveRanges) { unsigned Reg = RegLR.first; LiveRange *LR = RegLR.second; // FIXME: We could be smarter here. If the register is Live-In to one // block, but the other doesn't have any SGPR defs, then there won't be a // conflict. Also, if the branch condition is uniform then there will be // no conflict. bool LiveInToA = LIS->isLiveInToMBB(*LR, SuccA); bool LiveInToB = LIS->isLiveInToMBB(*LR, SuccB); if ((!LiveInToA && !LiveInToB) || (LiveInToA && LiveInToB)) continue; // This interval is live in to one successor, but not the other, so // we need to update its range so it is live in to both. DEBUG(dbgs() << "Possible SGPR conflict detected " << " in " << *LR << " BB#" << SuccA->getNumber() << ", BB#" << SuccB->getNumber() << " with NCD = " << NCD->getNumber() << '\n'); // FIXME: Need to figure out how to update LiveRange here so this pass // will be able to preserve LiveInterval analysis. BuildMI(*NCD, NCD->getFirstNonPHI(), DebugLoc(), TII->get(AMDGPU::SGPR_USE)) .addReg(Reg, RegState::Implicit); DEBUG(NCD->getFirstNonPHI()->dump()); } } return false; } <|endoftext|>
<commit_before>#include <iostream> #include <Start.h> #include "MyModel.h" #include "Data.h" using namespace std; using namespace DNest3; int main(int argc, char** argv) { // Load the data CommandLineOptions options(argc, argv); string dataFile = options.get_dataFile(); if(dataFile.compare("") == 0) cerr << "# ERROR: Kepler FITS filename required with -d argument." <<endl; else Data::get_instance().load(dataFile.c_str()); MTSampler<MyModel> sampler = setup_mt<MyModel>(argc, argv); sampler.run(); return 0; } <commit_msg>Fixed the bug that broke being able to use multiple threads<commit_after>#include <iostream> #include <Start.h> #include "MyModel.h" #include "Data.h" using namespace std; using namespace DNest3; int main(int argc, char** argv) { // Load the data CommandLineOptions options(argc, argv); string dataFile = options.get_dataFile(); if(dataFile.compare("") == 0) cerr << "# ERROR: Kepler FITS filename required with -d argument." <<endl; else Data::get_instance().load(dataFile.c_str()); MTSampler<MyModel> sampler = setup_mt<MyModel>(options); sampler.run(); return 0; } <|endoftext|>
<commit_before>/* * This file is a part of Xpiks - cross platform application for * keywording and uploading images for microstocks * Copyright (C) 2014-2016 Taras Kushnir <kushnirTV@gmail.com> * * Xpiks is distributed under the GNU General Public License, version 3.0 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "imagecachingworker.h" #include <QDir> #include <QFile> #include <QImage> #include <QString> #include <QFileInfo> #include <QByteArray> #include <QDataStream> #include <QReadLocker> #include <QWriteLocker> #include <QCryptographicHash> #include "../Common/defines.h" #include "../Helpers/constants.h" #include "imagecacherequest.h" namespace QMLExtensions { QString getPathHash(const QString &path) { return QString::fromLatin1(QCryptographicHash::hash(path.toUtf8(), QCryptographicHash::Sha256).toHex()); } QDataStream &operator<<(QDataStream &out, const CachedImage &v) { out << v.m_Filename << v.m_LastModified << v.m_Size << v.m_RequestsServed << v.m_AdditionalData; return out; } QDataStream &operator>>(QDataStream &in, CachedImage &v) { in >> v.m_Filename >> v.m_LastModified >> v.m_Size >> v.m_RequestsServed >> v.m_AdditionalData; return in; } ImageCachingWorker::ImageCachingWorker(QObject *parent): QObject(parent), m_ProcessedItemsCount(0) { } bool ImageCachingWorker::initWorker() { LOG_DEBUG << "#"; m_ProcessedItemsCount = 0; QString appDataPath = XPIKS_USERDATA_PATH; if (!appDataPath.isEmpty()) { m_ImagesCacheDir = QDir::cleanPath(appDataPath + QDir::separator() + Constants::IMAGES_CACHE_DIR); QDir appDataDir(appDataPath); m_IndexFilepath = appDataDir.filePath(Constants::IMAGES_CACHE_INDEX); QDir imagesCacheDir(m_ImagesCacheDir); if (!imagesCacheDir.exists()) { LOG_DEBUG << "Creating cache dir" << m_ImagesCacheDir; QDir().mkpath(m_ImagesCacheDir); } } else { m_ImagesCacheDir = QDir::currentPath(); m_IndexFilepath = Constants::IMAGES_CACHE_INDEX; } LOG_INFO << "Using" << m_ImagesCacheDir << "for images cache"; readIndex(); return true; } bool ImageCachingWorker::processOneItem(ImageCacheRequest *item) { if (isProcessed(item)) { return true; } const QString &originalPath = item->getFilepath(); QSize requestedSize = item->getRequestedSize(); LOG_DEBUG << (item->getNeedRecache() ? "Recaching" : "Caching") << originalPath << "with size" << requestedSize; if (!requestedSize.isValid()) { LOG_WARNING << "Invalid requestedSize for" << originalPath; requestedSize.setHeight(300); requestedSize.setWidth(300); } QImage img(originalPath); QImage resizedImage = img.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); QFileInfo fi(originalPath); QString pathHash = getPathHash(originalPath) + "." + fi.completeSuffix(); QString cachedFilepath = QDir::cleanPath(m_ImagesCacheDir + QDir::separator() + pathHash); if (resizedImage.save(cachedFilepath)) { CachedImage cachedImage; cachedImage.m_Filename = pathHash; cachedImage.m_LastModified = fi.lastModified(); cachedImage.m_Size = requestedSize; { QWriteLocker locker(&m_CacheLock); Q_UNUSED(locker); if (m_CacheIndex.contains(originalPath)) { cachedImage.m_RequestsServed = m_CacheIndex[originalPath].m_RequestsServed + 1; } else { cachedImage.m_RequestsServed = 1; } m_CacheIndex.insert(originalPath, cachedImage); } m_ProcessedItemsCount++; } else { LOG_WARNING << "Failed to save image. Path:" << cachedFilepath << "size" << requestedSize; } if (m_ProcessedItemsCount % 50 == 0) { saveIndex(); } if (item->getWithDelay()) { // force context switch for more imporant tasks QThread::msleep(500); } return true; } bool ImageCachingWorker::tryGetCachedImage(const QString &key, const QSize &requestedSize, QString &cachedPath, bool &needsUpdate) { bool found = false; QReadLocker locker(&m_CacheLock); Q_UNUSED(locker); if (m_CacheIndex.contains(key)) { CachedImage &cachedImage = m_CacheIndex[key]; QString cachedValue = QDir::cleanPath(m_ImagesCacheDir + QDir::separator() + cachedImage.m_Filename); QFileInfo fi(cachedValue); if (fi.exists()) { cachedImage.m_RequestsServed++; cachedPath = cachedValue; needsUpdate = (QFileInfo(key).lastModified() > cachedImage.m_LastModified) || (cachedImage.m_Size != requestedSize); found = true; } } return found; } void ImageCachingWorker::splitToCachedAndNot(const QVector<ImageCacheRequest *> allRequests, QVector<ImageCacheRequest *> &unknownRequests, QVector<ImageCacheRequest *> &knownRequests) { int size = allRequests.size(); if (size == 0) { return; } LOG_DEBUG << "#"; QReadLocker locker(&m_CacheLock); Q_UNUSED(locker); knownRequests.reserve(size); unknownRequests.reserve(size); for (int i = 0; i < size; ++i) { ImageCacheRequest *item = allRequests.at(i); if (m_CacheIndex.contains(item->getFilepath())) { knownRequests.append(item); } else { unknownRequests.append(item); } } } void ImageCachingWorker::readIndex() { QFile file(m_IndexFilepath); if (file.exists() && file.open(QIODevice::ReadOnly)) { QHash<QString, CachedImage> cacheIndex; QDataStream in(&file); // read the data in >> cacheIndex; file.close(); m_CacheIndex.swap(cacheIndex); LOG_INFO << "Images cache index read:" << m_CacheIndex.size() << "entries"; } else { LOG_WARNING << "File not found:" << m_IndexFilepath; } } void ImageCachingWorker::saveIndex() { LOG_DEBUG << "#"; QFile file(m_IndexFilepath); if (file.open(QIODevice::WriteOnly)) { QReadLocker locker(&m_CacheLock); Q_UNUSED(locker); QDataStream out(&file); // write the data out << m_CacheIndex; file.close(); LOG_INFO << "Images cache index saved:" << m_CacheIndex.size() << "entries"; } } bool ImageCachingWorker::isProcessed(ImageCacheRequest *item) { if (item->getNeedRecache()) { return false; } const QString &originalPath = item->getFilepath(); const QSize &requestedSize = item->getRequestedSize(); bool isAlreadyProcessed = false; QString cachedPath; bool needsUpdate = false; if (this->tryGetCachedImage(originalPath, requestedSize, cachedPath, needsUpdate)) { isAlreadyProcessed = !needsUpdate; } return isAlreadyProcessed; } } <commit_msg>Fix for caching size [ci skip]<commit_after>/* * This file is a part of Xpiks - cross platform application for * keywording and uploading images for microstocks * Copyright (C) 2014-2016 Taras Kushnir <kushnirTV@gmail.com> * * Xpiks is distributed under the GNU General Public License, version 3.0 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "imagecachingworker.h" #include <QDir> #include <QFile> #include <QImage> #include <QString> #include <QFileInfo> #include <QByteArray> #include <QDataStream> #include <QReadLocker> #include <QWriteLocker> #include <QCryptographicHash> #include "../Common/defines.h" #include "../Helpers/constants.h" #include "imagecacherequest.h" namespace QMLExtensions { QString getPathHash(const QString &path) { return QString::fromLatin1(QCryptographicHash::hash(path.toUtf8(), QCryptographicHash::Sha256).toHex()); } QDataStream &operator<<(QDataStream &out, const CachedImage &v) { out << v.m_Filename << v.m_LastModified << v.m_Size << v.m_RequestsServed << v.m_AdditionalData; return out; } QDataStream &operator>>(QDataStream &in, CachedImage &v) { in >> v.m_Filename >> v.m_LastModified >> v.m_Size >> v.m_RequestsServed >> v.m_AdditionalData; return in; } ImageCachingWorker::ImageCachingWorker(QObject *parent): QObject(parent), m_ProcessedItemsCount(0) { } bool ImageCachingWorker::initWorker() { LOG_DEBUG << "#"; m_ProcessedItemsCount = 0; QString appDataPath = XPIKS_USERDATA_PATH; if (!appDataPath.isEmpty()) { m_ImagesCacheDir = QDir::cleanPath(appDataPath + QDir::separator() + Constants::IMAGES_CACHE_DIR); QDir appDataDir(appDataPath); m_IndexFilepath = appDataDir.filePath(Constants::IMAGES_CACHE_INDEX); QDir imagesCacheDir(m_ImagesCacheDir); if (!imagesCacheDir.exists()) { LOG_DEBUG << "Creating cache dir" << m_ImagesCacheDir; QDir().mkpath(m_ImagesCacheDir); } } else { m_ImagesCacheDir = QDir::currentPath(); m_IndexFilepath = Constants::IMAGES_CACHE_INDEX; } LOG_INFO << "Using" << m_ImagesCacheDir << "for images cache"; readIndex(); return true; } bool ImageCachingWorker::processOneItem(ImageCacheRequest *item) { if (isProcessed(item)) { return true; } const QString &originalPath = item->getFilepath(); QSize requestedSize = item->getRequestedSize(); LOG_DEBUG << (item->getNeedRecache() ? "Recaching" : "Caching") << originalPath << "with size" << requestedSize; if (!requestedSize.isValid()) { LOG_WARNING << "Invalid requestedSize for" << originalPath; requestedSize.setHeight(150); requestedSize.setWidth(150); } QImage img(originalPath); QImage resizedImage = img.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); QFileInfo fi(originalPath); QString pathHash = getPathHash(originalPath) + "." + fi.completeSuffix(); QString cachedFilepath = QDir::cleanPath(m_ImagesCacheDir + QDir::separator() + pathHash); if (resizedImage.save(cachedFilepath)) { CachedImage cachedImage; cachedImage.m_Filename = pathHash; cachedImage.m_LastModified = fi.lastModified(); cachedImage.m_Size = requestedSize; { QWriteLocker locker(&m_CacheLock); Q_UNUSED(locker); if (m_CacheIndex.contains(originalPath)) { cachedImage.m_RequestsServed = m_CacheIndex[originalPath].m_RequestsServed + 1; } else { cachedImage.m_RequestsServed = 1; } m_CacheIndex.insert(originalPath, cachedImage); } m_ProcessedItemsCount++; } else { LOG_WARNING << "Failed to save image. Path:" << cachedFilepath << "size" << requestedSize; } if (m_ProcessedItemsCount % 50 == 0) { saveIndex(); } if (item->getWithDelay()) { // force context switch for more imporant tasks QThread::msleep(500); } return true; } bool ImageCachingWorker::tryGetCachedImage(const QString &key, const QSize &requestedSize, QString &cachedPath, bool &needsUpdate) { bool found = false; QReadLocker locker(&m_CacheLock); Q_UNUSED(locker); if (m_CacheIndex.contains(key)) { CachedImage &cachedImage = m_CacheIndex[key]; QString cachedValue = QDir::cleanPath(m_ImagesCacheDir + QDir::separator() + cachedImage.m_Filename); QFileInfo fi(cachedValue); if (fi.exists()) { cachedImage.m_RequestsServed++; cachedPath = cachedValue; needsUpdate = (QFileInfo(key).lastModified() > cachedImage.m_LastModified) || (cachedImage.m_Size != requestedSize); found = true; } } return found; } void ImageCachingWorker::splitToCachedAndNot(const QVector<ImageCacheRequest *> allRequests, QVector<ImageCacheRequest *> &unknownRequests, QVector<ImageCacheRequest *> &knownRequests) { int size = allRequests.size(); if (size == 0) { return; } LOG_DEBUG << "#"; QReadLocker locker(&m_CacheLock); Q_UNUSED(locker); knownRequests.reserve(size); unknownRequests.reserve(size); for (int i = 0; i < size; ++i) { ImageCacheRequest *item = allRequests.at(i); if (m_CacheIndex.contains(item->getFilepath())) { knownRequests.append(item); } else { unknownRequests.append(item); } } } void ImageCachingWorker::readIndex() { QFile file(m_IndexFilepath); if (file.exists() && file.open(QIODevice::ReadOnly)) { QHash<QString, CachedImage> cacheIndex; QDataStream in(&file); // read the data in >> cacheIndex; file.close(); m_CacheIndex.swap(cacheIndex); LOG_INFO << "Images cache index read:" << m_CacheIndex.size() << "entries"; } else { LOG_WARNING << "File not found:" << m_IndexFilepath; } } void ImageCachingWorker::saveIndex() { LOG_DEBUG << "#"; QFile file(m_IndexFilepath); if (file.open(QIODevice::WriteOnly)) { QReadLocker locker(&m_CacheLock); Q_UNUSED(locker); QDataStream out(&file); // write the data out << m_CacheIndex; file.close(); LOG_INFO << "Images cache index saved:" << m_CacheIndex.size() << "entries"; } } bool ImageCachingWorker::isProcessed(ImageCacheRequest *item) { if (item->getNeedRecache()) { return false; } const QString &originalPath = item->getFilepath(); const QSize &requestedSize = item->getRequestedSize(); bool isAlreadyProcessed = false; QString cachedPath; bool needsUpdate = false; if (this->tryGetCachedImage(originalPath, requestedSize, cachedPath, needsUpdate)) { isAlreadyProcessed = !needsUpdate; } return isAlreadyProcessed; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: htmlexp2.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2005-01-11 13:17:18 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------------ #ifdef MAC #define _SYSDEP_HXX #endif #include <svx/svditer.hxx> #include <svx/svdograf.hxx> #include <svx/svdoole2.hxx> #include <svx/svdpage.hxx> #include <svx/xoutbmp.hxx> #ifndef _SVDXCGV_HXX #include <svx/svdxcgv.hxx> #endif #include <sot/exchange.hxx> #include <svtools/htmlkywd.hxx> #include <svtools/htmlout.hxx> #include <svtools/transfer.hxx> #include <svtools/embedtransfer.hxx> #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #include <tools/urlobj.hxx> #if defined(WIN) || defined(WNT) #ifndef _SVWIN_H #include <tools/svwin.h> #endif #endif #include "htmlexp.hxx" #include "global.hxx" #include "flttools.hxx" #include "document.hxx" #include "drwlayer.hxx" using namespace com::sun::star; //------------------------------------------------------------------------ void ScHTMLExport::PrepareGraphics( ScDrawLayer* pDrawLayer, SCTAB nTab, SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow ) { if ( pDrawLayer->HasObjectsInRows( nTab, nStartRow, nEndRow ) ) { SdrPage* pDrawPage = pDrawLayer->GetPage( static_cast<sal_uInt16>(nTab) ); if ( pDrawPage ) { bTabHasGraphics = TRUE; FillGraphList( pDrawPage, nTab, nStartCol, nStartRow, nEndCol, nEndRow ); for ( ScHTMLGraphEntry* pE = aGraphList.First(); pE; pE = aGraphList.Next() ) { if ( !pE->bInCell ) { // nicht alle in Zellen: einige neben Tabelle bTabAlignedLeft = TRUE; break; } } } } } void ScHTMLExport::FillGraphList( const SdrPage* pPage, SCTAB nTab, SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow ) { ULONG nObjCount = pPage->GetObjCount(); if ( nObjCount ) { Rectangle aRect; if ( !bAll ) aRect = pDoc->GetMMRect( nStartCol, nStartRow, nEndCol, nEndRow, nTab ); SdrObjListIter aIter( *pPage, IM_FLAT ); SdrObject* pObject = aIter.Next(); while ( pObject ) { Rectangle aObjRect = pObject->GetCurrentBoundRect(); if ( bAll || aRect.IsInside( aObjRect ) ) { Size aSpace; ScRange aR = pDoc->GetRange( nTab, aObjRect ); // Rectangle in mm/100 Size aSize( MMToPixel( aObjRect.GetSize() ) ); // If the image is somewhere in a merged range we must // move the anchor to the upper left (THE span cell). pDoc->ExtendOverlapped( aR ); SCCOL nCol1 = aR.aStart.Col(); SCROW nRow1 = aR.aStart.Row(); SCCOL nCol2 = aR.aEnd.Col(); SCROW nRow2 = aR.aEnd.Row(); // All cells empty under object? BOOL bInCell = (pDoc->GetEmptyLinesInBlock( nCol1, nRow1, nTab, nCol2, nRow2, nTab, DIR_TOP ) == (nRow2 - nRow1)); // rows-1 ! if ( bInCell ) { // Spacing in spanning cell Rectangle aCellRect = pDoc->GetMMRect( nCol1, nRow1, nCol2, nRow2, nTab ); aSpace = MMToPixel( Size( aCellRect.GetWidth() - aObjRect.GetWidth(), aCellRect.GetHeight() - aObjRect.GetHeight() )); aSpace.Width() += (nCol2-nCol1) * (nCellSpacing+1); aSpace.Height() += (nRow2-nRow1) * (nCellSpacing+1); aSpace.Width() /= 2; aSpace.Height() /= 2; } ScHTMLGraphEntry* pE = new ScHTMLGraphEntry( pObject, aR, aSize, bInCell, aSpace ); aGraphList.Insert( pE, LIST_APPEND ); } pObject = aIter.Next(); } } } void ScHTMLExport::WriteGraphEntry( ScHTMLGraphEntry* pE ) { SdrObject* pObject = pE->pObject; ByteString aOpt; (((aOpt += ' ') += sHTML_O_width) += '=') += ByteString::CreateFromInt32( pE->aSize.Width() ); (((aOpt += ' ') += sHTML_O_height) += '=') += ByteString::CreateFromInt32( pE->aSize.Height() ); if ( pE->bInCell ) { (((aOpt += ' ') += sHTML_O_hspace) += '=') += ByteString::CreateFromInt32( pE->aSpace.Width() ); (((aOpt += ' ') += sHTML_O_vspace) += '=') += ByteString::CreateFromInt32( pE->aSpace.Height() ); } switch ( pObject->GetObjIdentifier() ) { case OBJ_GRAF: { const SdrGrafObj* pSGO = (SdrGrafObj*)pObject; const SdrGrafObjGeoData* pGeo = (SdrGrafObjGeoData*)pSGO->GetGeoData(); USHORT nMirrorCase = (pGeo->aGeo.nDrehWink == 18000 ? ( pGeo->bMirrored ? 3 : 4 ) : ( pGeo->bMirrored ? 2 : 1 )); BOOL bHMirr = ( ( nMirrorCase == 2 ) || ( nMirrorCase == 4 ) ); BOOL bVMirr = ( ( nMirrorCase == 3 ) || ( nMirrorCase == 4 ) ); ULONG nXOutFlags = 0; if ( bHMirr ) nXOutFlags |= XOUTBMP_MIRROR_HORZ; if ( bVMirr ) nXOutFlags |= XOUTBMP_MIRROR_VERT; String aLinkName; if ( pSGO->IsLinkedGraphic() ) aLinkName = pSGO->GetFileName(); WriteImage( aLinkName, pSGO->GetGraphic(), aOpt, nXOutFlags ); pE->bWritten = TRUE; } break; case OBJ_OLE2: { uno::Reference < embed::XEmbeddedObject > xObj = ((SdrOle2Obj*)pObject)->GetObjRef(); DBG_ASSERT( xObj.is(), "WriteGraphEntry: no OLE ObjRef" ); if ( xObj.is() ) { TransferableDataHelper aOleData( new SvEmbedTransferHelper( xObj ) ); GDIMetaFile aMtf; if( aOleData.GetGDIMetaFile( FORMAT_GDIMETAFILE, aMtf ) ) { Graphic aGraph( aMtf ); String aLinkName; WriteImage( aLinkName, aGraph, aOpt ); pE->bWritten = TRUE; } } } break; default: { Graphic aGraph( SdrExchangeView::GetObjGraphic( pDoc->GetDrawLayer(), pObject ) ); String aLinkName; WriteImage( aLinkName, aGraph, aOpt ); pE->bWritten = TRUE; } } } void ScHTMLExport::WriteImage( String& rLinkName, const Graphic& rGrf, const ByteString& rImgOptions, ULONG nXOutFlags ) { // embeddete Grafik -> via WriteGraphic schreiben if( !rLinkName.Len() ) { if( aStreamPath.Len() > 0 ) { // Grafik als (JPG-)File speichern String aGrfNm( aStreamPath ); nXOutFlags |= XOUTBMP_USE_NATIVE_IF_POSSIBLE; USHORT nErr = XOutBitmap::WriteGraphic( rGrf, aGrfNm, _STRINGCONST( "JPG" ), nXOutFlags ); if( !nErr ) // sonst fehlerhaft, da ist nichts auszugeben { rLinkName = URIHelper::SmartRel2Abs( INetURLObject(aBaseURL), aGrfNm, URIHelper::GetMaybeFileHdl()); if ( HasCId() ) MakeCIdURL( rLinkName ); } } } else { if( bCopyLocalFileToINet || HasCId() ) { CopyLocalFileToINet( rLinkName, aStreamPath ); if ( HasCId() ) MakeCIdURL( rLinkName ); } else rLinkName = URIHelper::SmartRel2Abs( INetURLObject(aBaseURL), rLinkName, URIHelper::GetMaybeFileHdl()); } if( rLinkName.Len() ) { // <IMG SRC="..."[ rImgOptions]> rStrm << '<' << sHTML_image << ' ' << sHTML_O_src << "=\""; HTMLOutFuncs::Out_String( rStrm, URIHelper::simpleNormalizedMakeRelative( aBaseURL, rLinkName ), eDestEnc ) << '\"'; if ( rImgOptions.Len() ) rStrm << rImgOptions.GetBuffer(); rStrm << '>' << sNewLine << GetIndentStr(); } } <commit_msg>INTEGRATION: CWS dr32 (1.9.144); FILE MERGED 2005/01/18 12:07:49 dr 1.9.144.2: RESYNC: (1.9-1.10); FILE MERGED 2005/01/13 14:28:17 dr 1.9.144.1: #i40570# remove flttools.hxx<commit_after>/************************************************************************* * * $RCSfile: htmlexp2.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: vg $ $Date: 2005-02-21 13:36:25 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------------ #ifdef MAC #define _SYSDEP_HXX #endif #include <svx/svditer.hxx> #include <svx/svdograf.hxx> #include <svx/svdoole2.hxx> #include <svx/svdpage.hxx> #include <svx/xoutbmp.hxx> #ifndef _SVDXCGV_HXX #include <svx/svdxcgv.hxx> #endif #include <sot/exchange.hxx> #include <svtools/htmlkywd.hxx> #include <svtools/htmlout.hxx> #include <svtools/transfer.hxx> #include <svtools/embedtransfer.hxx> #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #include <tools/urlobj.hxx> #if defined(WIN) || defined(WNT) #ifndef _SVWIN_H #include <tools/svwin.h> #endif #endif #include "htmlexp.hxx" #include "global.hxx" #include "document.hxx" #include "drwlayer.hxx" #include "ftools.hxx" using namespace com::sun::star; //------------------------------------------------------------------------ void ScHTMLExport::PrepareGraphics( ScDrawLayer* pDrawLayer, SCTAB nTab, SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow ) { if ( pDrawLayer->HasObjectsInRows( nTab, nStartRow, nEndRow ) ) { SdrPage* pDrawPage = pDrawLayer->GetPage( static_cast<sal_uInt16>(nTab) ); if ( pDrawPage ) { bTabHasGraphics = TRUE; FillGraphList( pDrawPage, nTab, nStartCol, nStartRow, nEndCol, nEndRow ); for ( ScHTMLGraphEntry* pE = aGraphList.First(); pE; pE = aGraphList.Next() ) { if ( !pE->bInCell ) { // nicht alle in Zellen: einige neben Tabelle bTabAlignedLeft = TRUE; break; } } } } } void ScHTMLExport::FillGraphList( const SdrPage* pPage, SCTAB nTab, SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow ) { ULONG nObjCount = pPage->GetObjCount(); if ( nObjCount ) { Rectangle aRect; if ( !bAll ) aRect = pDoc->GetMMRect( nStartCol, nStartRow, nEndCol, nEndRow, nTab ); SdrObjListIter aIter( *pPage, IM_FLAT ); SdrObject* pObject = aIter.Next(); while ( pObject ) { Rectangle aObjRect = pObject->GetCurrentBoundRect(); if ( bAll || aRect.IsInside( aObjRect ) ) { Size aSpace; ScRange aR = pDoc->GetRange( nTab, aObjRect ); // Rectangle in mm/100 Size aSize( MMToPixel( aObjRect.GetSize() ) ); // If the image is somewhere in a merged range we must // move the anchor to the upper left (THE span cell). pDoc->ExtendOverlapped( aR ); SCCOL nCol1 = aR.aStart.Col(); SCROW nRow1 = aR.aStart.Row(); SCCOL nCol2 = aR.aEnd.Col(); SCROW nRow2 = aR.aEnd.Row(); // All cells empty under object? BOOL bInCell = (pDoc->GetEmptyLinesInBlock( nCol1, nRow1, nTab, nCol2, nRow2, nTab, DIR_TOP ) == (nRow2 - nRow1)); // rows-1 ! if ( bInCell ) { // Spacing in spanning cell Rectangle aCellRect = pDoc->GetMMRect( nCol1, nRow1, nCol2, nRow2, nTab ); aSpace = MMToPixel( Size( aCellRect.GetWidth() - aObjRect.GetWidth(), aCellRect.GetHeight() - aObjRect.GetHeight() )); aSpace.Width() += (nCol2-nCol1) * (nCellSpacing+1); aSpace.Height() += (nRow2-nRow1) * (nCellSpacing+1); aSpace.Width() /= 2; aSpace.Height() /= 2; } ScHTMLGraphEntry* pE = new ScHTMLGraphEntry( pObject, aR, aSize, bInCell, aSpace ); aGraphList.Insert( pE, LIST_APPEND ); } pObject = aIter.Next(); } } } void ScHTMLExport::WriteGraphEntry( ScHTMLGraphEntry* pE ) { SdrObject* pObject = pE->pObject; ByteString aOpt; (((aOpt += ' ') += sHTML_O_width) += '=') += ByteString::CreateFromInt32( pE->aSize.Width() ); (((aOpt += ' ') += sHTML_O_height) += '=') += ByteString::CreateFromInt32( pE->aSize.Height() ); if ( pE->bInCell ) { (((aOpt += ' ') += sHTML_O_hspace) += '=') += ByteString::CreateFromInt32( pE->aSpace.Width() ); (((aOpt += ' ') += sHTML_O_vspace) += '=') += ByteString::CreateFromInt32( pE->aSpace.Height() ); } switch ( pObject->GetObjIdentifier() ) { case OBJ_GRAF: { const SdrGrafObj* pSGO = (SdrGrafObj*)pObject; const SdrGrafObjGeoData* pGeo = (SdrGrafObjGeoData*)pSGO->GetGeoData(); USHORT nMirrorCase = (pGeo->aGeo.nDrehWink == 18000 ? ( pGeo->bMirrored ? 3 : 4 ) : ( pGeo->bMirrored ? 2 : 1 )); BOOL bHMirr = ( ( nMirrorCase == 2 ) || ( nMirrorCase == 4 ) ); BOOL bVMirr = ( ( nMirrorCase == 3 ) || ( nMirrorCase == 4 ) ); ULONG nXOutFlags = 0; if ( bHMirr ) nXOutFlags |= XOUTBMP_MIRROR_HORZ; if ( bVMirr ) nXOutFlags |= XOUTBMP_MIRROR_VERT; String aLinkName; if ( pSGO->IsLinkedGraphic() ) aLinkName = pSGO->GetFileName(); WriteImage( aLinkName, pSGO->GetGraphic(), aOpt, nXOutFlags ); pE->bWritten = TRUE; } break; case OBJ_OLE2: { uno::Reference < embed::XEmbeddedObject > xObj = ((SdrOle2Obj*)pObject)->GetObjRef(); DBG_ASSERT( xObj.is(), "WriteGraphEntry: no OLE ObjRef" ); if ( xObj.is() ) { TransferableDataHelper aOleData( new SvEmbedTransferHelper( xObj ) ); GDIMetaFile aMtf; if( aOleData.GetGDIMetaFile( FORMAT_GDIMETAFILE, aMtf ) ) { Graphic aGraph( aMtf ); String aLinkName; WriteImage( aLinkName, aGraph, aOpt ); pE->bWritten = TRUE; } } } break; default: { Graphic aGraph( SdrExchangeView::GetObjGraphic( pDoc->GetDrawLayer(), pObject ) ); String aLinkName; WriteImage( aLinkName, aGraph, aOpt ); pE->bWritten = TRUE; } } } void ScHTMLExport::WriteImage( String& rLinkName, const Graphic& rGrf, const ByteString& rImgOptions, ULONG nXOutFlags ) { // embeddete Grafik -> via WriteGraphic schreiben if( !rLinkName.Len() ) { if( aStreamPath.Len() > 0 ) { // Grafik als (JPG-)File speichern String aGrfNm( aStreamPath ); nXOutFlags |= XOUTBMP_USE_NATIVE_IF_POSSIBLE; USHORT nErr = XOutBitmap::WriteGraphic( rGrf, aGrfNm, CREATE_STRING( "JPG" ), nXOutFlags ); if( !nErr ) // sonst fehlerhaft, da ist nichts auszugeben { rLinkName = URIHelper::SmartRel2Abs( INetURLObject(aBaseURL), aGrfNm, URIHelper::GetMaybeFileHdl()); if ( HasCId() ) MakeCIdURL( rLinkName ); } } } else { if( bCopyLocalFileToINet || HasCId() ) { CopyLocalFileToINet( rLinkName, aStreamPath ); if ( HasCId() ) MakeCIdURL( rLinkName ); } else rLinkName = URIHelper::SmartRel2Abs( INetURLObject(aBaseURL), rLinkName, URIHelper::GetMaybeFileHdl()); } if( rLinkName.Len() ) { // <IMG SRC="..."[ rImgOptions]> rStrm << '<' << sHTML_image << ' ' << sHTML_O_src << "=\""; HTMLOutFuncs::Out_String( rStrm, URIHelper::simpleNormalizedMakeRelative( aBaseURL, rLinkName ), eDestEnc ) << '\"'; if ( rImgOptions.Len() ) rStrm << rImgOptions.GetBuffer(); rStrm << '>' << sNewLine << GetIndentStr(); } } <|endoftext|>
<commit_before>/* *********************************************************************************************************************** * * Copyright (c) 2019-2020 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************************************/ /** *********************************************************************************************************************** * @file LgcContext.cpp * @brief LLPC source file: implementation of llpc::LgcContext class for creating and using lgc::Builder *********************************************************************************************************************** */ #include "lgc/LgcContext.h" #include "lgc/Builder.h" #include "lgc/PassManager.h" #include "lgc/patch/Patch.h" #include "lgc/state/PassManagerCache.h" #include "lgc/state/PipelineState.h" #include "lgc/state/TargetInfo.h" #include "lgc/util/Debug.h" #include "lgc/util/Internal.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Bitcode/BitcodeWriterPass.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/InitializePasses.h" #include "llvm/Support/CodeGen.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #define DEBUG_TYPE "lgc-context" namespace llvm { namespace cl { // Set the optimization level extern opt<CodeGenOpt::Level> OptLevel; } // namespace cl } // namespace llvm using namespace lgc; using namespace llvm; namespace llvm { void initializeBuilderReplayerPass(PassRegistry &); } // namespace llvm static codegen::RegisterCodeGenFlags CGF; #ifndef NDEBUG static bool Initialized; #endif raw_ostream *LgcContext::m_llpcOuts; // -emit-llvm: emit LLVM assembly instead of ISA static cl::opt<bool> EmitLlvm("emit-llvm", cl::desc("Emit LLVM assembly instead of AMD GPU ISA"), cl::init(false)); // -emit-llvm-bc: emit LLVM bitcode instead of ISA static cl::opt<bool> EmitLlvmBc("emit-llvm-bc", cl::desc("Emit LLVM bitcode instead of AMD GPU ISA"), cl::init(false)); // -emit-lgc: emit LLVM assembly suitable for input to LGC (middle-end compiler) static cl::opt<bool> EmitLgc("emit-lgc", cl::desc("Emit LLVM assembly suitable for input to LGC (middle-end compiler)"), cl::init(false)); // -show-encoding: show the instruction encoding when emitting assembler. This mirrors llvm-mc behaviour static cl::opt<bool> ShowEncoding("show-encoding", cl::desc("Show instruction encodings"), cl::init(false)); // ===================================================================================================================== // Set default for a command-line option, but only if command-line processing has not happened yet, or did not see // an occurrence of this option. // // @param name : Option name // @param value : Default option value static void setOptionDefault(const char *name, StringRef value) { auto optIterator = cl::getRegisteredOptions().find(name); assert(optIterator != cl::getRegisteredOptions().end() && "Failed to find option to set default"); cl::Option *opt = optIterator->second; if (opt->getNumOccurrences()) return; // Setting MultiArg means that addOccurrence will not increment the option's occurrence count, so the user // can still specify it to override our default here. bool setFailed = opt->addOccurrence(0, opt->ArgStr, value, /*MultiArg=*/true); assert(!setFailed && "Failed to set default for option"); ((void)setFailed); } // ===================================================================================================================== // Initialize the middle-end. This must be called before the first LgcContext::Create, although you are // allowed to call it again after that. It must also be called before LLVM command-line processing, so // that you can use a pass name in an option such as -print-after. If multiple concurrent compiles are // possible, this should be called in a thread-safe way. void LgcContext::initialize() { #ifndef NDEBUG Initialized = true; #endif auto &passRegistry = *PassRegistry::getPassRegistry(); // Initialize LLVM target: AMDGPU LLVMInitializeAMDGPUTargetInfo(); LLVMInitializeAMDGPUTarget(); LLVMInitializeAMDGPUTargetMC(); LLVMInitializeAMDGPUAsmPrinter(); LLVMInitializeAMDGPUAsmParser(); LLVMInitializeAMDGPUDisassembler(); // Initialize core LLVM passes so they can be referenced by -stop-before etc. initializeCore(passRegistry); initializeTransformUtils(passRegistry); initializeScalarOpts(passRegistry); initializeVectorization(passRegistry); initializeInstCombine(passRegistry); initializeAggressiveInstCombine(passRegistry); initializeIPO(passRegistry); initializeCodeGen(passRegistry); initializeShadowStackGCLoweringPass(passRegistry); initializeExpandReductionsPass(passRegistry); initializeRewriteSymbolsLegacyPassPass(passRegistry); // Initialize LGC passes so they can be referenced by -stop-before etc. initializeUtilPasses(passRegistry); initializeStatePasses(passRegistry); initializeBuilderReplayerPass(passRegistry); initializePatchPasses(passRegistry); // Initialize some command-line option defaults. setOptionDefault("filetype", "obj"); setOptionDefault("unroll-max-percent-threshold-boost", "1000"); setOptionDefault("pragma-unroll-threshold", "1000"); setOptionDefault("unroll-allow-partial", "1"); setOptionDefault("simplifycfg-sink-common", "0"); setOptionDefault("amdgpu-vgpr-index-mode", "1"); // force VGPR indexing on GFX8 setOptionDefault("amdgpu-atomic-optimizations", "1"); setOptionDefault("use-gpu-divergence-analysis", "1"); setOptionDefault("structurizecfg-skip-uniform-regions", "1"); #if !defined(LLVM_HAVE_BRANCH_AMD_GFX) #warning[!amd-gfx] Conditional discard transformations not supported #else setOptionDefault("amdgpu-conditional-discard-transformations", "1"); #endif } // ===================================================================================================================== // Create the LgcContext. Returns nullptr on failure to recognize the AMDGPU target whose name is specified // // @param context : LLVM context to give each Builder // @param gpuName : LLVM GPU name (e.g. "gfx900"); empty to use -mcpu option setting // @param palAbiVersion : PAL pipeline ABI version to compile for LgcContext *LgcContext::Create(LLVMContext &context, StringRef gpuName, unsigned palAbiVersion) { assert(Initialized && "Must call LgcContext::Initialize before LgcContext::Create"); LgcContext *builderContext = new LgcContext(context, palAbiVersion); std::string mcpuName = codegen::getMCPU(); // -mcpu setting from llvm/CodeGen/CommandFlags.h if (gpuName == "") gpuName = mcpuName; builderContext->m_targetInfo = new TargetInfo; if (!builderContext->m_targetInfo->setTargetInfo(gpuName)) { delete builderContext; return nullptr; } // Get the LLVM target and create the target machine. This should not fail, as we determined above // that we support the requested target. const std::string triple = "amdgcn--amdpal"; std::string errMsg; const Target *target = TargetRegistry::lookupTarget(triple, errMsg); // Allow no signed zeros - this enables omod modifiers (div:2, mul:2) TargetOptions targetOpts; targetOpts.NoSignedZerosFPMath = true; // Enable instruction encoding output - outputs hex in comment mirroring // llvm-mc behaviour if (ShowEncoding) { targetOpts.MCOptions.ShowMCEncoding = true; targetOpts.MCOptions.AsmVerbose = true; } LLPC_OUTS("TargetMachine optimization level = " << cl::OptLevel << "\n"); builderContext->m_targetMachine = target->createTargetMachine(triple, gpuName, "", targetOpts, Optional<Reloc::Model>(), None, cl::OptLevel); assert(builderContext->m_targetMachine); return builderContext; } // ===================================================================================================================== // // @param context : LLVM context to give each Builder // @param palAbiVersion : PAL pipeline ABI version to compile for LgcContext::LgcContext(LLVMContext &context, unsigned palAbiVersion) : m_context(context) { } // ===================================================================================================================== LgcContext::~LgcContext() { delete m_targetMachine; delete m_targetInfo; delete m_passManagerCache; } // ===================================================================================================================== // Create a Pipeline object for a pipeline compile. // This actually creates a PipelineState, but returns the Pipeline superclass that is visible to // the front-end. Pipeline *LgcContext::createPipeline() { return new PipelineState(this, EmitLgc); } // ===================================================================================================================== // Create a Builder object. For a shader compile (pPipeline is nullptr), useBuilderRecorder is ignored // because it always uses BuilderRecorder. // // @param pipeline : Pipeline object for pipeline compile, nullptr for shader compile // @param useBuilderRecorder : True to use BuilderRecorder, false to use BuilderImpl Builder *LgcContext::createBuilder(Pipeline *pipeline, bool useBuilderRecorder) { if (!pipeline || useBuilderRecorder || EmitLgc) return Builder::createBuilderRecorder(this, pipeline, EmitLgc); return Builder::createBuilderImpl(this, pipeline); } // ===================================================================================================================== // Prepare a pass manager. This manually adds a target-aware TLI pass, so middle-end optimizations do not think that // we have library functions. // // @param [in/out] passMgr : Pass manager void LgcContext::preparePassManager(legacy::PassManager *passMgr) { TargetLibraryInfoImpl targetLibInfo(getTargetMachine()->getTargetTriple()); // Adjust it to allow memcpy and memset. // TODO: Investigate why the latter is necessary. I found that // test/shaderdb/ObjStorageBlock_TestMemCpyInt32.comp // got unrolled far too much, and at too late a stage for the descriptor loads to be commoned up. It might // be an unfortunate interaction between LoopIdiomRecognize and fat pointer laundering. targetLibInfo.setAvailable(LibFunc_memcpy); targetLibInfo.setAvailable(LibFunc_memset); auto targetLibInfoPass = new TargetLibraryInfoWrapperPass(targetLibInfo); passMgr->add(targetLibInfoPass); } // ===================================================================================================================== // Adds target passes to pass manager, depending on "-filetype" and "-emit-llvm" options // // @param [in/out] passMgr : Pass manager to add passes to // @param codeGenTimer : Timer to time target passes with, nullptr if not timing // @param [out] outStream : Output stream void LgcContext::addTargetPasses(lgc::PassManager &passMgr, Timer *codeGenTimer, raw_pwrite_stream &outStream) { // Start timer for codegen passes. if (codeGenTimer) passMgr.add(createStartStopTimer(codeGenTimer, true)); // Dump the module just before codegen. if (raw_ostream *outs = getLgcOuts()) { passMgr.add( createPrintModulePass(*outs, "===============================================================================\n" "// LLPC final pipeline module info\n")); } if (EmitLlvm && EmitLlvmBc) report_fatal_error("-emit-llvm conflicts with -emit-llvm-bc"); if (EmitLlvm) { // For -emit-llvm, add a pass to output the LLVM IR, then tell the pass manager to stop adding // passes. We do it this way to ensure that we still get the immutable passes from // TargetMachine::addPassesToEmitFile, as they can affect LLVM middle-end optimizations. passMgr.add(createPrintModulePass(outStream)); passMgr.stop(); } if (EmitLlvmBc) { // For -emit-llvm-bc, add a pass to output the LLVM IR, then tell the pass manager to stop adding // passes. We do it this way to ensure that we still get the immutable passes from // TargetMachine::addPassesToEmitFile, as they can affect LLVM middle-end optimizations. passMgr.add(createBitcodeWriterPass(outStream)); passMgr.stop(); } // TODO: We should probably be using InitTargetOptionsFromCodeGenFlags() here. // Currently we are not, and it would give an "unused function" warning when compiled with // CLANG. So we avoid the warning by referencing it here. (void(&codegen::InitTargetOptionsFromCodeGenFlags)); // unused if (getTargetMachine()->addPassesToEmitFile(passMgr, outStream, nullptr, codegen::getFileType())) report_fatal_error("Target machine cannot emit a file of this type"); // Stop timer for codegen passes. if (codeGenTimer) passMgr.add(createStartStopTimer(codeGenTimer, false)); } // ===================================================================================================================== // Get pass manager cache PassManagerCache *LgcContext::getPassManagerCache() { if (!m_passManagerCache) m_passManagerCache = new PassManagerCache(this); return m_passManagerCache; } <commit_msg>Fix for effects of upstream LLVM change<commit_after>/* *********************************************************************************************************************** * * Copyright (c) 2019-2020 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************************************/ /** *********************************************************************************************************************** * @file LgcContext.cpp * @brief LLPC source file: implementation of llpc::LgcContext class for creating and using lgc::Builder *********************************************************************************************************************** */ #include "lgc/LgcContext.h" #include "lgc/Builder.h" #include "lgc/PassManager.h" #include "lgc/patch/Patch.h" #include "lgc/state/PassManagerCache.h" #include "lgc/state/PipelineState.h" #include "lgc/state/TargetInfo.h" #include "lgc/util/Debug.h" #include "lgc/util/Internal.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Bitcode/BitcodeWriterPass.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/InitializePasses.h" #include "llvm/Support/CodeGen.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #define DEBUG_TYPE "lgc-context" namespace llvm { namespace cl { // Set the optimization level extern opt<CodeGenOpt::Level> OptLevel; } // namespace cl } // namespace llvm using namespace lgc; using namespace llvm; namespace llvm { void initializeBuilderReplayerPass(PassRegistry &); } // namespace llvm static codegen::RegisterCodeGenFlags CGF; #ifndef NDEBUG static bool Initialized; #endif raw_ostream *LgcContext::m_llpcOuts; // -emit-llvm: emit LLVM assembly instead of ISA static cl::opt<bool> EmitLlvm("emit-llvm", cl::desc("Emit LLVM assembly instead of AMD GPU ISA"), cl::init(false)); // -emit-llvm-bc: emit LLVM bitcode instead of ISA static cl::opt<bool> EmitLlvmBc("emit-llvm-bc", cl::desc("Emit LLVM bitcode instead of AMD GPU ISA"), cl::init(false)); // -emit-lgc: emit LLVM assembly suitable for input to LGC (middle-end compiler) static cl::opt<bool> EmitLgc("emit-lgc", cl::desc("Emit LLVM assembly suitable for input to LGC (middle-end compiler)"), cl::init(false)); // -show-encoding: show the instruction encoding when emitting assembler. This mirrors llvm-mc behaviour static cl::opt<bool> ShowEncoding("show-encoding", cl::desc("Show instruction encodings"), cl::init(false)); // ===================================================================================================================== // Set default for a command-line option, but only if command-line processing has not happened yet, or did not see // an occurrence of this option. // // @param name : Option name // @param value : Default option value static void setOptionDefault(const char *name, StringRef value) { auto optIterator = cl::getRegisteredOptions().find(name); assert(optIterator != cl::getRegisteredOptions().end() && "Failed to find option to set default"); cl::Option *opt = optIterator->second; if (opt->getNumOccurrences()) return; // Setting MultiArg means that addOccurrence will not increment the option's occurrence count, so the user // can still specify it to override our default here. bool setFailed = opt->addOccurrence(0, opt->ArgStr, value, /*MultiArg=*/true); assert(!setFailed && "Failed to set default for option"); ((void)setFailed); } // ===================================================================================================================== // Initialize the middle-end. This must be called before the first LgcContext::Create, although you are // allowed to call it again after that. It must also be called before LLVM command-line processing, so // that you can use a pass name in an option such as -print-after. If multiple concurrent compiles are // possible, this should be called in a thread-safe way. void LgcContext::initialize() { #ifndef NDEBUG Initialized = true; #endif auto &passRegistry = *PassRegistry::getPassRegistry(); // Initialize LLVM target: AMDGPU LLVMInitializeAMDGPUTargetInfo(); LLVMInitializeAMDGPUTarget(); LLVMInitializeAMDGPUTargetMC(); LLVMInitializeAMDGPUAsmPrinter(); LLVMInitializeAMDGPUAsmParser(); LLVMInitializeAMDGPUDisassembler(); // Initialize core LLVM passes so they can be referenced by -stop-before etc. initializeCore(passRegistry); initializeTransformUtils(passRegistry); initializeScalarOpts(passRegistry); initializeVectorization(passRegistry); initializeInstCombine(passRegistry); initializeAggressiveInstCombine(passRegistry); initializeIPO(passRegistry); initializeCodeGen(passRegistry); initializeShadowStackGCLoweringPass(passRegistry); initializeExpandReductionsPass(passRegistry); initializeRewriteSymbolsLegacyPassPass(passRegistry); // Initialize LGC passes so they can be referenced by -stop-before etc. initializeUtilPasses(passRegistry); initializeStatePasses(passRegistry); initializeBuilderReplayerPass(passRegistry); initializePatchPasses(passRegistry); // Initialize some command-line option defaults. setOptionDefault("filetype", "obj"); setOptionDefault("amdgpu-unroll-max-block-to-analyze", "20"); setOptionDefault("unroll-max-percent-threshold-boost", "1000"); setOptionDefault("pragma-unroll-threshold", "1000"); setOptionDefault("unroll-allow-partial", "1"); setOptionDefault("simplifycfg-sink-common", "0"); setOptionDefault("amdgpu-vgpr-index-mode", "1"); // force VGPR indexing on GFX8 setOptionDefault("amdgpu-atomic-optimizations", "1"); setOptionDefault("use-gpu-divergence-analysis", "1"); setOptionDefault("structurizecfg-skip-uniform-regions", "1"); #if !defined(LLVM_HAVE_BRANCH_AMD_GFX) #warning[!amd-gfx] Conditional discard transformations not supported #else setOptionDefault("amdgpu-conditional-discard-transformations", "1"); #endif } // ===================================================================================================================== // Create the LgcContext. Returns nullptr on failure to recognize the AMDGPU target whose name is specified // // @param context : LLVM context to give each Builder // @param gpuName : LLVM GPU name (e.g. "gfx900"); empty to use -mcpu option setting // @param palAbiVersion : PAL pipeline ABI version to compile for LgcContext *LgcContext::Create(LLVMContext &context, StringRef gpuName, unsigned palAbiVersion) { assert(Initialized && "Must call LgcContext::Initialize before LgcContext::Create"); LgcContext *builderContext = new LgcContext(context, palAbiVersion); std::string mcpuName = codegen::getMCPU(); // -mcpu setting from llvm/CodeGen/CommandFlags.h if (gpuName == "") gpuName = mcpuName; builderContext->m_targetInfo = new TargetInfo; if (!builderContext->m_targetInfo->setTargetInfo(gpuName)) { delete builderContext; return nullptr; } // Get the LLVM target and create the target machine. This should not fail, as we determined above // that we support the requested target. const std::string triple = "amdgcn--amdpal"; std::string errMsg; const Target *target = TargetRegistry::lookupTarget(triple, errMsg); // Allow no signed zeros - this enables omod modifiers (div:2, mul:2) TargetOptions targetOpts; targetOpts.NoSignedZerosFPMath = true; // Enable instruction encoding output - outputs hex in comment mirroring // llvm-mc behaviour if (ShowEncoding) { targetOpts.MCOptions.ShowMCEncoding = true; targetOpts.MCOptions.AsmVerbose = true; } LLPC_OUTS("TargetMachine optimization level = " << cl::OptLevel << "\n"); builderContext->m_targetMachine = target->createTargetMachine(triple, gpuName, "", targetOpts, Optional<Reloc::Model>(), None, cl::OptLevel); assert(builderContext->m_targetMachine); return builderContext; } // ===================================================================================================================== // // @param context : LLVM context to give each Builder // @param palAbiVersion : PAL pipeline ABI version to compile for LgcContext::LgcContext(LLVMContext &context, unsigned palAbiVersion) : m_context(context) { } // ===================================================================================================================== LgcContext::~LgcContext() { delete m_targetMachine; delete m_targetInfo; delete m_passManagerCache; } // ===================================================================================================================== // Create a Pipeline object for a pipeline compile. // This actually creates a PipelineState, but returns the Pipeline superclass that is visible to // the front-end. Pipeline *LgcContext::createPipeline() { return new PipelineState(this, EmitLgc); } // ===================================================================================================================== // Create a Builder object. For a shader compile (pPipeline is nullptr), useBuilderRecorder is ignored // because it always uses BuilderRecorder. // // @param pipeline : Pipeline object for pipeline compile, nullptr for shader compile // @param useBuilderRecorder : True to use BuilderRecorder, false to use BuilderImpl Builder *LgcContext::createBuilder(Pipeline *pipeline, bool useBuilderRecorder) { if (!pipeline || useBuilderRecorder || EmitLgc) return Builder::createBuilderRecorder(this, pipeline, EmitLgc); return Builder::createBuilderImpl(this, pipeline); } // ===================================================================================================================== // Prepare a pass manager. This manually adds a target-aware TLI pass, so middle-end optimizations do not think that // we have library functions. // // @param [in/out] passMgr : Pass manager void LgcContext::preparePassManager(legacy::PassManager *passMgr) { TargetLibraryInfoImpl targetLibInfo(getTargetMachine()->getTargetTriple()); // Adjust it to allow memcpy and memset. // TODO: Investigate why the latter is necessary. I found that // test/shaderdb/ObjStorageBlock_TestMemCpyInt32.comp // got unrolled far too much, and at too late a stage for the descriptor loads to be commoned up. It might // be an unfortunate interaction between LoopIdiomRecognize and fat pointer laundering. targetLibInfo.setAvailable(LibFunc_memcpy); targetLibInfo.setAvailable(LibFunc_memset); auto targetLibInfoPass = new TargetLibraryInfoWrapperPass(targetLibInfo); passMgr->add(targetLibInfoPass); } // ===================================================================================================================== // Adds target passes to pass manager, depending on "-filetype" and "-emit-llvm" options // // @param [in/out] passMgr : Pass manager to add passes to // @param codeGenTimer : Timer to time target passes with, nullptr if not timing // @param [out] outStream : Output stream void LgcContext::addTargetPasses(lgc::PassManager &passMgr, Timer *codeGenTimer, raw_pwrite_stream &outStream) { // Start timer for codegen passes. if (codeGenTimer) passMgr.add(createStartStopTimer(codeGenTimer, true)); // Dump the module just before codegen. if (raw_ostream *outs = getLgcOuts()) { passMgr.add( createPrintModulePass(*outs, "===============================================================================\n" "// LLPC final pipeline module info\n")); } if (EmitLlvm && EmitLlvmBc) report_fatal_error("-emit-llvm conflicts with -emit-llvm-bc"); if (EmitLlvm) { // For -emit-llvm, add a pass to output the LLVM IR, then tell the pass manager to stop adding // passes. We do it this way to ensure that we still get the immutable passes from // TargetMachine::addPassesToEmitFile, as they can affect LLVM middle-end optimizations. passMgr.add(createPrintModulePass(outStream)); passMgr.stop(); } if (EmitLlvmBc) { // For -emit-llvm-bc, add a pass to output the LLVM IR, then tell the pass manager to stop adding // passes. We do it this way to ensure that we still get the immutable passes from // TargetMachine::addPassesToEmitFile, as they can affect LLVM middle-end optimizations. passMgr.add(createBitcodeWriterPass(outStream)); passMgr.stop(); } // TODO: We should probably be using InitTargetOptionsFromCodeGenFlags() here. // Currently we are not, and it would give an "unused function" warning when compiled with // CLANG. So we avoid the warning by referencing it here. (void(&codegen::InitTargetOptionsFromCodeGenFlags)); // unused if (getTargetMachine()->addPassesToEmitFile(passMgr, outStream, nullptr, codegen::getFileType())) report_fatal_error("Target machine cannot emit a file of this type"); // Stop timer for codegen passes. if (codeGenTimer) passMgr.add(createStartStopTimer(codeGenTimer, false)); } // ===================================================================================================================== // Get pass manager cache PassManagerCache *LgcContext::getPassManagerCache() { if (!m_passManagerCache) m_passManagerCache = new PassManagerCache(this); return m_passManagerCache; } <|endoftext|>
<commit_before>//===-- SparcV9CodeEmitter.cpp - --------===// // // //===----------------------------------------------------------------------===// #include "llvm/PassManager.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/Target/TargetMachine.h" #include "SparcInternals.h" #include "SparcV9CodeEmitter.h" MachineCodeEmitter * SparcV9CodeEmitter::MCE = 0; TargetMachine * SparcV9CodeEmitter::TM = 0; bool UltraSparc::addPassesToEmitMachineCode(PassManager &PM, MachineCodeEmitter &MCE) { //PM.add(new SparcV9CodeEmitter(MCE)); //MachineCodeEmitter *M = MachineCodeEmitter::createDebugMachineCodeEmitter(); MachineCodeEmitter *M = MachineCodeEmitter::createFilePrinterMachineCodeEmitter(MCE); PM.add(new SparcV9CodeEmitter(this, *M)); return false; } void SparcV9CodeEmitter::emitConstant(unsigned Val, unsigned Size) { // Output the constant in big endian byte order... unsigned byteVal; for (int i = Size-1; i >= 0; --i) { byteVal = Val >> 8*i; MCE->emitByte(byteVal & 255); } #if 0 MCE->emitByte((Val >> 16) & 255); // byte 2 MCE->emitByte((Val >> 24) & 255); // byte 3 MCE->emitByte((Val >> 8) & 255); // byte 1 MCE->emitByte(Val & 255); // byte 0 #endif } unsigned getRealRegNum(unsigned fakeReg, unsigned regClass) { switch (regClass) { case UltraSparcRegInfo::IntRegType: { // Sparc manual, p31 static const unsigned IntRegMap[] = { // "o0", "o1", "o2", "o3", "o4", "o5", "o7", 8, 9, 10, 11, 12, 13, 15, // "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7", 16, 17, 18, 19, 20, 21, 22, 23, // "i0", "i1", "i2", "i3", "i4", "i5", 24, 25, 26, 27, 28, 29, // "i6", "i7", 30, 31, // "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7", 0, 1, 2, 3, 4, 5, 6, 7, // "o6" 14 }; return IntRegMap[fakeReg]; break; } case UltraSparcRegInfo::FPSingleRegType: { return fakeReg; } case UltraSparcRegInfo::FPDoubleRegType: { return fakeReg; } case UltraSparcRegInfo::FloatCCRegType: { return fakeReg; } case UltraSparcRegInfo::IntCCRegType: { return fakeReg; } default: assert(0 && "Invalid unified register number in getRegType"); return fakeReg; } } int64_t SparcV9CodeEmitter::getMachineOpValue(MachineInstr &MI, MachineOperand &MO) { if (MO.isPhysicalRegister()) { // This is necessary because the Sparc doesn't actually lay out registers // in the real fashion -- it skips those that it chooses not to allocate, // i.e. those that are the SP, etc. unsigned fakeReg = MO.getReg(), realReg, regClass, regType; regType = TM->getRegInfo().getRegType(fakeReg); // At least map fakeReg into its class fakeReg = TM->getRegInfo().getClassRegNum(fakeReg, regClass); // Find the real register number for use in an instruction realReg = getRealRegNum(fakeReg, regClass); std::cerr << "Reg[" << fakeReg << "] = " << realReg << "\n"; return realReg; } else if (MO.isImmediate()) { return MO.getImmedValue(); } else if (MO.isPCRelativeDisp()) { std::cerr << "Saving reference to BB (PCRelDisp)\n"; MCE->saveBBreference((BasicBlock*)MO.getVRegValue(), MI); return 0; } else if (MO.isMachineBasicBlock()) { std::cerr << "Saving reference to BB (MBB)\n"; MCE->saveBBreference(MO.getMachineBasicBlock()->getBasicBlock(), MI); return 0; } else if (MO.isFrameIndex()) { std::cerr << "ERROR: Frame index unhandled.\n"; return 0; } else if (MO.isConstantPoolIndex()) { std::cerr << "ERROR: Constant Pool index unhandled.\n"; return 0; } else if (MO.isGlobalAddress()) { std::cerr << "ERROR: Global addr unhandled.\n"; return 0; } else if (MO.isExternalSymbol()) { std::cerr << "ERROR: External symbol unhandled.\n"; return 0; } else { std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n"; //abort(); return 0; } } unsigned SparcV9CodeEmitter::getValueBit(int64_t Val, unsigned bit) { Val >>= bit; return (Val & 1); } bool SparcV9CodeEmitter::runOnMachineFunction(MachineFunction &MF) { MCE->startFunction(MF); MCE->emitConstantPool(MF.getConstantPool()); for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) emitBasicBlock(*I); MCE->finishFunction(MF); return false; } void SparcV9CodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) { currBB = MBB.getBasicBlock(); MCE->startBasicBlock(MBB); for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I) emitInstruction(**I); } void SparcV9CodeEmitter::emitInstruction(MachineInstr &MI) { emitConstant(getBinaryCodeForInstr(MI), 4); } #include "SparcV9CodeEmitter.inc" <commit_msg>Removed useless code -- the byte order of output code is correct as is.<commit_after>//===-- SparcV9CodeEmitter.cpp - --------===// // // //===----------------------------------------------------------------------===// #include "llvm/PassManager.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/Target/TargetMachine.h" #include "SparcInternals.h" #include "SparcV9CodeEmitter.h" MachineCodeEmitter * SparcV9CodeEmitter::MCE = 0; TargetMachine * SparcV9CodeEmitter::TM = 0; bool UltraSparc::addPassesToEmitMachineCode(PassManager &PM, MachineCodeEmitter &MCE) { //PM.add(new SparcV9CodeEmitter(MCE)); //MachineCodeEmitter *M = MachineCodeEmitter::createDebugMachineCodeEmitter(); MachineCodeEmitter *M = MachineCodeEmitter::createFilePrinterMachineCodeEmitter(MCE); PM.add(new SparcV9CodeEmitter(this, *M)); PM.add(createMachineCodeDestructionPass()); // Free stuff no longer needed return false; } void SparcV9CodeEmitter::emitConstant(unsigned Val, unsigned Size) { // Output the constant in big endian byte order... unsigned byteVal; for (int i = Size-1; i >= 0; --i) { byteVal = Val >> 8*i; MCE->emitByte(byteVal & 255); } } unsigned getRealRegNum(unsigned fakeReg, unsigned regClass) { switch (regClass) { case UltraSparcRegInfo::IntRegType: { // Sparc manual, p31 static const unsigned IntRegMap[] = { // "o0", "o1", "o2", "o3", "o4", "o5", "o7", 8, 9, 10, 11, 12, 13, 15, // "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7", 16, 17, 18, 19, 20, 21, 22, 23, // "i0", "i1", "i2", "i3", "i4", "i5", 24, 25, 26, 27, 28, 29, // "i6", "i7", 30, 31, // "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7", 0, 1, 2, 3, 4, 5, 6, 7, // "o6" 14 }; return IntRegMap[fakeReg]; break; } case UltraSparcRegInfo::FPSingleRegType: { return fakeReg; } case UltraSparcRegInfo::FPDoubleRegType: { return fakeReg; } case UltraSparcRegInfo::FloatCCRegType: { return fakeReg; } case UltraSparcRegInfo::IntCCRegType: { return fakeReg; } default: assert(0 && "Invalid unified register number in getRegType"); return fakeReg; } } int64_t SparcV9CodeEmitter::getMachineOpValue(MachineInstr &MI, MachineOperand &MO) { if (MO.isPhysicalRegister()) { // This is necessary because the Sparc doesn't actually lay out registers // in the real fashion -- it skips those that it chooses not to allocate, // i.e. those that are the SP, etc. unsigned fakeReg = MO.getReg(), realReg, regClass, regType; regType = TM->getRegInfo().getRegType(fakeReg); // At least map fakeReg into its class fakeReg = TM->getRegInfo().getClassRegNum(fakeReg, regClass); // Find the real register number for use in an instruction realReg = getRealRegNum(fakeReg, regClass); std::cerr << "Reg[" << fakeReg << "] = " << realReg << "\n"; return realReg; } else if (MO.isImmediate()) { return MO.getImmedValue(); } else if (MO.isPCRelativeDisp()) { std::cerr << "Saving reference to BB (PCRelDisp)\n"; MCE->saveBBreference((BasicBlock*)MO.getVRegValue(), MI); return 0; } else if (MO.isMachineBasicBlock()) { std::cerr << "Saving reference to BB (MBB)\n"; MCE->saveBBreference(MO.getMachineBasicBlock()->getBasicBlock(), MI); return 0; } else if (MO.isFrameIndex()) { std::cerr << "ERROR: Frame index unhandled.\n"; return 0; } else if (MO.isConstantPoolIndex()) { std::cerr << "ERROR: Constant Pool index unhandled.\n"; return 0; } else if (MO.isGlobalAddress()) { std::cerr << "ERROR: Global addr unhandled.\n"; return 0; } else if (MO.isExternalSymbol()) { std::cerr << "ERROR: External symbol unhandled.\n"; return 0; } else { std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n"; //abort(); return 0; } } unsigned SparcV9CodeEmitter::getValueBit(int64_t Val, unsigned bit) { Val >>= bit; return (Val & 1); } bool SparcV9CodeEmitter::runOnMachineFunction(MachineFunction &MF) { MCE->startFunction(MF); MCE->emitConstantPool(MF.getConstantPool()); for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) emitBasicBlock(*I); MCE->finishFunction(MF); return false; } void SparcV9CodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) { currBB = MBB.getBasicBlock(); MCE->startBasicBlock(MBB); for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I) emitInstruction(**I); } void SparcV9CodeEmitter::emitInstruction(MachineInstr &MI) { emitConstant(getBinaryCodeForInstr(MI), 4); } #include "SparcV9CodeEmitter.inc" <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: lotread.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: dr $ $Date: 2001-04-12 08:45:10 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------------ #include "document.hxx" #include "scerrors.hxx" #include "root.hxx" #include "lotimpop.hxx" #include "fltprgrs.hxx" #include "lotattr.hxx" class ScFormulaCell; FltError ImportLotus::Read() { enum STATE { S_START, // analyse first BOF S_WK1, // in WK1-Stream S_WK3, // in WK3-Section S_WK4, // ... S_FM3, // ... S_END // Import finished }; UINT16 nOp; UINT16 nSubType; UINT16 nRecLen; UINT32 nNextRec = 0UL; FltError eRet = eERR_OK; // ScFormulaCell *pLastFormCell; STATE eAkt = S_START; nTab = 0; nExtTab = -2; pIn->Seek( nNextRec ); // Progressbar starten FilterProgressBar aPrgrsBar( *pIn ); while( eAkt != S_END ) { *pIn >> nOp >> nRecLen; if( pIn->IsEof() ) eAkt = S_END; nNextRec += nRecLen + 4; switch( eAkt ) { // ----------------------------------------------------------- case S_START: // S_START if( nOp ) { eRet = SCERR_IMPORT_UNKNOWN_WK; eAkt = S_END; } else { if( nRecLen > 2 ) { Bof(); switch( pLotusRoot->eFirstType ) { case Lotus_WK1: eAkt = S_WK1; break; case Lotus_WK3: eAkt = S_WK3; break; case Lotus_WK4: eAkt = S_WK4; break; case Lotus_FM3: eAkt = S_FM3; break; default: eRet = SCERR_IMPORT_UNKNOWN_WK; eAkt = S_END; } } else { eAkt = S_END; // hier kommt wat fuer <= WK1 hinne! eRet = 0xFFFFFFFF; } } break; // ----------------------------------------------------------- case S_WK1: // S_WK1 break; // ----------------------------------------------------------- case S_WK3: // S_WK3 case S_WK4: // S_WK4 switch( nOp ) { case 0x0001: // EOF eAkt = S_FM3; nTab++; break; case 0x0002: // PASSWORD eRet = eERR_FILEPASSWD; eAkt = S_END; break; case 0x0007: // COLUMNWIDTH Columnwidth( nRecLen ); break; case 0x0008: // HIDDENCOLUMN Hiddencolumn( nRecLen ); break; case 0x0009: // USERRANGE Userrange(); break; case 0x0013: // FORMAT break; case 0x0014: // ERRCELL Errcell(); break; case 0x0015: // NACELL Nacell(); break; case 0x0016: // LABELCELL Labelcell(); break; case 0x0017: // NUMBERCELL Numbercell(); break; case 0x0018: // SMALLNUMCELL Smallnumcell(); break; case 0x0019: // FORMULACELL Formulacell( nRecLen ); break; case 0x001b: // extended attributes Read( nSubType ); nRecLen -= 2; switch( nSubType ) { case 2007: // ROW PRESENTATION RowPresentation( nRecLen ); break; case 14000: // NAMED SHEET NamedSheet(); break; } } break; // ----------------------------------------------------------- case S_FM3: // S_FM3 break; // ----------------------------------------------------------- case S_END: // S_END break; // ----------------------------------------------------------- #ifdef DBG_UTIL default: DBG_ERROR( "*ImportLotus::Read(): State unbekannt!" ); eAkt = S_END; #endif } DBG_ASSERT( nNextRec >= pIn->Tell(), "*ImportLotus::Read(): Etwas zu gierig..." ); pIn->Seek( nNextRec ); aPrgrsBar.Progress(); } // duemmliche Namen eliminieren UINT16 nTabs = pD->GetTableCount(); UINT16 nCnt; String aTabName; String aBaseName; String aRef( RTL_CONSTASCII_USTRINGPARAM( "temp" ) ); if( nTabs ) { if( nTabs > 1 ) { pD->GetName( 0, aBaseName ); aBaseName.Erase( aBaseName.Len() - 1 ); } for( nCnt = 1 ; nCnt < nTabs ; nCnt++ ) { DBG_ASSERT( pD->HasTable( nCnt ), "-ImportLotus::Read(): Wo ist meine Tabelle?!" ); pD->GetName( nCnt, aTabName ); if( aTabName == aRef ) { aTabName = aBaseName; pD->CreateValidTabName( aTabName ); pD->RenameTab( nCnt, aTabName ); } } } pD->CalcAfterLoad(); return eRet; } FltError ImportLotus::Read( SvStream& rIn ) { pIn = &rIn; BOOL bRead = TRUE; UINT16 nOp; UINT16 nRecLen; UINT32 nNextRec = 0UL; FltError eRet = eERR_OK; nTab = 0; nExtTab = -1; pIn->Seek( nNextRec ); // Progressbar starten FilterProgressBar aPrgrsBar( *pIn ); while( bRead ) { *pIn >> nOp >> nRecLen; if( pIn->IsEof() ) bRead = FALSE; else { nNextRec += nRecLen + 4; switch( nOp ) { case 0x0000: // BOF if( nRecLen != 26 || !BofFm3() ) { bRead = FALSE; eRet = eERR_FORMAT; } break; case 0x0001: // EOF bRead = FALSE; DBG_ASSERT( nTab == 0, "-ImportLotus::Read( SvStream& ): Zweimal EOF nicht erlaubt" ); nTab++; break; case 174: // FONT_FACE Font_Face(); break; case 176: // FONT_TYPE Font_Type(); break; case 177: // FONT_YSIZE Font_Ysize(); break; case 195: if( nExtTab >= 0 ) pLotusRoot->pAttrTable->Apply( ( UINT16 ) nExtTab ); nExtTab++; break; case 197: _Row( nRecLen ); break; } DBG_ASSERT( nNextRec >= pIn->Tell(), "*ImportLotus::Read(): Etwas zu gierig..." ); pIn->Seek( nNextRec ); aPrgrsBar.Progress(); } } pLotusRoot->pAttrTable->Apply( ( UINT16 ) nExtTab ); return eRet; } <commit_msg>#65293# Corrected for Solaris<commit_after>/************************************************************************* * * $RCSfile: lotread.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2001-05-18 12:28:04 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------------ #include "document.hxx" #include "scerrors.hxx" #include "root.hxx" #include "lotimpop.hxx" #include "fltprgrs.hxx" #include "lotattr.hxx" class ScFormulaCell; FltError ImportLotus::Read() { enum STATE { S_START, // analyse first BOF S_WK1, // in WK1-Stream S_WK3, // in WK3-Section S_WK4, // ... S_FM3, // ... S_END // Import finished }; UINT16 nOp; UINT16 nSubType; UINT16 nRecLen; UINT32 nNextRec = 0UL; FltError eRet = eERR_OK; // ScFormulaCell *pLastFormCell; STATE eAkt = S_START; nTab = 0; nExtTab = -2; pIn->Seek( nNextRec ); // Progressbar starten FilterProgressBar aPrgrsBar( *pIn ); while( eAkt != S_END ) { *pIn >> nOp >> nRecLen; if( pIn->IsEof() ) eAkt = S_END; nNextRec += nRecLen + 4; switch( eAkt ) { // ----------------------------------------------------------- case S_START: // S_START if( nOp ) { eRet = SCERR_IMPORT_UNKNOWN_WK; eAkt = S_END; } else { if( nRecLen > 2 ) { Bof(); switch( pLotusRoot->eFirstType ) { case Lotus_WK1: eAkt = S_WK1; break; case Lotus_WK3: eAkt = S_WK3; break; case Lotus_WK4: eAkt = S_WK4; break; case Lotus_FM3: eAkt = S_FM3; break; default: eRet = SCERR_IMPORT_UNKNOWN_WK; eAkt = S_END; } } else { eAkt = S_END; // hier kommt wat fuer <= WK1 hinne! eRet = 0xFFFFFFFF; } } break; // ----------------------------------------------------------- case S_WK1: // S_WK1 break; // ----------------------------------------------------------- case S_WK3: // S_WK3 case S_WK4: // S_WK4 switch( nOp ) { case 0x0001: // EOF eAkt = S_FM3; nTab++; break; case 0x0002: // PASSWORD eRet = eERR_FILEPASSWD; eAkt = S_END; break; case 0x0007: // COLUMNWIDTH Columnwidth( nRecLen ); break; case 0x0008: // HIDDENCOLUMN Hiddencolumn( nRecLen ); break; case 0x0009: // USERRANGE Userrange(); break; case 0x0013: // FORMAT break; case 0x0014: // ERRCELL Errcell(); break; case 0x0015: // NACELL Nacell(); break; case 0x0016: // LABELCELL Labelcell(); break; case 0x0017: // NUMBERCELL Numbercell(); break; case 0x0018: // SMALLNUMCELL Smallnumcell(); break; case 0x0019: // FORMULACELL Formulacell( nRecLen ); break; case 0x001b: // extended attributes Read( nSubType ); nRecLen -= 2; switch( nSubType ) { case 2007: // ROW PRESENTATION RowPresentation( nRecLen ); break; case 14000: // NAMED SHEET NamedSheet(); break; } } break; // ----------------------------------------------------------- case S_FM3: // S_FM3 break; // ----------------------------------------------------------- case S_END: // S_END break; // ----------------------------------------------------------- #ifdef DBG_UTIL default: DBG_ERROR( "*ImportLotus::Read(): State unbekannt!" ); eAkt = S_END; #endif } DBG_ASSERT( nNextRec >= pIn->Tell(), "*ImportLotus::Read(): Etwas zu gierig..." ); pIn->Seek( nNextRec ); aPrgrsBar.Progress(); } // duemmliche Namen eliminieren UINT16 nTabs = pD->GetTableCount(); UINT16 nCnt; String aTabName; String aBaseName; String aRef( RTL_CONSTASCII_USTRINGPARAM( "temp" ) ); if( nTabs ) { if( nTabs > 1 ) { pD->GetName( 0, aBaseName ); aBaseName.Erase( aBaseName.Len() - 1 ); } for( nCnt = 1 ; nCnt < nTabs ; nCnt++ ) { DBG_ASSERT( pD->HasTable( nCnt ), "-ImportLotus::Read(): Wo ist meine Tabelle?!" ); pD->GetName( nCnt, aTabName ); if( aTabName == aRef ) { aTabName = aBaseName; pD->CreateValidTabName( aTabName ); pD->RenameTab( nCnt, aTabName ); } } } pD->CalcAfterLoad(); return eRet; } FltError ImportLotus::Read( SvStream& rIn ) { pIn = &rIn; BOOL bRead = TRUE; UINT16 nOp; UINT16 nRecLen; UINT32 nNextRec = 0UL; FltError eRet = eERR_OK; nTab = 0; nExtTab = -1; pIn->Seek( nNextRec ); // Progressbar starten FilterProgressBar aPrgrsBar( *pIn ); while( bRead ) { *pIn >> nOp >> nRecLen; if( pIn->IsEof() ) bRead = FALSE; else { nNextRec += nRecLen + 4; switch( nOp ) { case 0x0000: // BOF if( nRecLen != 26 || !BofFm3() ) { bRead = FALSE; eRet = eERR_FORMAT; } break; case 0x0001: // EOF bRead = FALSE; DBG_ASSERT( nTab == 0, "-ImportLotus::Read( SvStream& ): Zweimal EOF nicht erlaubt" ); nTab++; break; case 174: // FONT_FACE Font_Face(); break; case 176: // FONT_TYPE Font_Type(); break; case 177: // FONT_YSIZE Font_Ysize(); break; case 195: if( nExtTab >= 0 ) pLotusRoot->pAttrTable->Apply( ( UINT16 ) nExtTab ); nExtTab++; break; case 197: _Row( nRecLen ); break; } DBG_ASSERT( nNextRec >= pIn->Tell(), "*ImportLotus::Read(): Etwas zu gierig..." ); pIn->Seek( nNextRec ); aPrgrsBar.Progress(); } } pLotusRoot->pAttrTable->Apply( ( UINT16 ) nExtTab ); return eRet; } <|endoftext|>
<commit_before>//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Expr constant evaluator. // //===----------------------------------------------------------------------===// #include "clang/AST/APValue.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Expr.h" #include "clang/AST/StmtVisitor.h" #include "clang/Basic/TargetInfo.h" #include "llvm/Support/Compiler.h" using namespace clang; using llvm::APSInt; #define USE_NEW_EVALUATOR 0 static bool CalcFakeICEVal(const Expr *Expr, llvm::APSInt &Result, ASTContext &Context) { // Calculate the value of an expression that has a calculatable // value, but isn't an ICE. Currently, this only supports // a very narrow set of extensions, but it can be expanded if needed. if (const ParenExpr *PE = dyn_cast<ParenExpr>(Expr)) return CalcFakeICEVal(PE->getSubExpr(), Result, Context); if (const CastExpr *CE = dyn_cast<CastExpr>(Expr)) { QualType CETy = CE->getType(); if ((CETy->isIntegralType() && !CETy->isBooleanType()) || CETy->isPointerType()) { if (CalcFakeICEVal(CE->getSubExpr(), Result, Context)) { Result.extOrTrunc(Context.getTypeSize(CETy)); // FIXME: This assumes pointers are signed. Result.setIsSigned(CETy->isSignedIntegerType() || CETy->isPointerType()); return true; } } } if (Expr->getType()->isIntegralType()) return Expr->isIntegerConstantExpr(Result, Context); return false; } static bool EvaluatePointer(const Expr *E, APValue &Result, ASTContext &Ctx); static bool EvaluateInteger(const Expr *E, APSInt &Result, ASTContext &Ctx); //===----------------------------------------------------------------------===// // Pointer Evaluation //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN PointerExprEvaluator : public StmtVisitor<PointerExprEvaluator, APValue> { ASTContext &Ctx; public: PointerExprEvaluator(ASTContext &ctx) : Ctx(ctx) {} APValue VisitStmt(Stmt *S) { // FIXME: Remove this when we support more expressions. printf("Unhandled pointer statement\n"); S->dump(); return APValue(); } APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } APValue VisitBinaryOperator(const BinaryOperator *E); APValue VisitCastExpr(const CastExpr* E); }; } // end anonymous namespace static bool EvaluatePointer(const Expr* E, APValue& Result, ASTContext &Ctx) { if (!E->getType()->isPointerType()) return false; Result = PointerExprEvaluator(Ctx).Visit(const_cast<Expr*>(E)); return Result.isLValue(); } APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { if (E->getOpcode() != BinaryOperator::Add && E->getOpcode() != BinaryOperator::Sub) return APValue(); const Expr *PExp = E->getLHS(); const Expr *IExp = E->getRHS(); if (IExp->getType()->isPointerType()) std::swap(PExp, IExp); APValue ResultLValue; if (!EvaluatePointer(PExp, ResultLValue, Ctx)) return APValue(); llvm::APSInt AdditionalOffset(32); if (!EvaluateInteger(IExp, AdditionalOffset, Ctx)) return APValue(); uint64_t Offset = ResultLValue.getLValueOffset(); if (E->getOpcode() == BinaryOperator::Add) Offset += AdditionalOffset.getZExtValue(); else Offset -= AdditionalOffset.getZExtValue(); return APValue(ResultLValue.getLValueBase(), Offset); } APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { const Expr* SubExpr = E->getSubExpr(); // Check for pointer->pointer cast if (SubExpr->getType()->isPointerType()) { APValue Result; if (EvaluatePointer(SubExpr, Result, Ctx)) return Result; return APValue(); } if (SubExpr->getType()->isArithmeticType()) { llvm::APSInt Result(32); if (EvaluateInteger(SubExpr, Result, Ctx)) { Result.extOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(E->getType()))); return APValue(0, Result.getZExtValue()); } } assert(0 && "Unhandled cast"); return APValue(); } //===----------------------------------------------------------------------===// // Integer Evaluation //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN IntExprEvaluator : public StmtVisitor<IntExprEvaluator, bool> { ASTContext &Ctx; APSInt &Result; public: IntExprEvaluator(ASTContext &ctx, APSInt &result) : Ctx(ctx), Result(result){} unsigned getIntTypeSizeInBits(QualType T) const { return (unsigned)Ctx.getTypeSize(T); } //===--------------------------------------------------------------------===// // Visitor Methods //===--------------------------------------------------------------------===// bool VisitStmt(Stmt *S) { // FIXME: Remove this when we support more expressions. printf("unhandled int expression"); S->dump(); return false; } bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } bool VisitBinaryOperator(const BinaryOperator *E); bool VisitUnaryOperator(const UnaryOperator *E); bool VisitCastExpr(const CastExpr* E) { return HandleCast(E->getSubExpr(), E->getType()); } bool VisitImplicitCastExpr(const ImplicitCastExpr* E) { return HandleCast(E->getSubExpr(), E->getType()); } bool VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) { return EvaluateSizeAlignOf(E->isSizeOf(),E->getArgumentType(),E->getType()); } bool VisitIntegerLiteral(const IntegerLiteral *E) { Result = E->getValue(); return true; } private: bool HandleCast(const Expr* SubExpr, QualType DestType); bool EvaluateSizeAlignOf(bool isSizeOf, QualType SrcTy, QualType DstTy); }; } // end anonymous namespace static bool EvaluateInteger(const Expr* E, APSInt &Result, ASTContext &Ctx) { return IntExprEvaluator(Ctx, Result).Visit(const_cast<Expr*>(E)); } bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { // The LHS of a constant expr is always evaluated and needed. if (!Visit(E->getLHS())) return false; llvm::APSInt RHS(32); if (!EvaluateInteger(E->getRHS(), RHS, Ctx)) return false; switch (E->getOpcode()) { default: return false; case BinaryOperator::Mul: Result *= RHS; break; case BinaryOperator::Div: if (RHS == 0) return false; Result /= RHS; break; case BinaryOperator::Rem: if (RHS == 0) return false; Result %= RHS; break; case BinaryOperator::Add: Result += RHS; break; case BinaryOperator::Sub: Result -= RHS; break; case BinaryOperator::And: Result &= RHS; break; case BinaryOperator::Xor: Result ^= RHS; break; case BinaryOperator::Or: Result |= RHS; break; case BinaryOperator::Shl: Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1); break; case BinaryOperator::Shr: Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1); break; case BinaryOperator::LT: Result = Result < RHS; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); break; case BinaryOperator::GT: Result = Result > RHS; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); break; case BinaryOperator::LE: Result = Result <= RHS; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); break; case BinaryOperator::GE: Result = Result >= RHS; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); break; case BinaryOperator::EQ: Result = Result == RHS; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); break; case BinaryOperator::NE: Result = Result != RHS; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); break; case BinaryOperator::Comma: // C99 6.6p3: "shall not contain assignment, ..., or comma operators, // *except* when they are contained within a subexpression that is not // evaluated". Note that Assignment can never happen due to constraints // on the LHS subexpr, so we don't need to check it here. // FIXME: Need to come up with an efficient way to deal with the C99 // rules on evaluation while still evaluating this. Maybe a // "evaluated comma" out parameter? return false; } Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); return true; } /// EvaluateSizeAlignOf - Evaluate sizeof(SrcTy) or alignof(SrcTy) with a result /// as a DstTy type. bool IntExprEvaluator::EvaluateSizeAlignOf(bool isSizeOf, QualType SrcTy, QualType DstTy) { // Return the result in the right width. Result.zextOrTrunc(getIntTypeSizeInBits(DstTy)); Result.setIsUnsigned(DstTy->isUnsignedIntegerType()); // sizeof(void) and __alignof__(void) = 1 as a gcc extension. if (SrcTy->isVoidType()) Result = 1; // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. if (!SrcTy->isConstantSizeType()) { // FIXME: Should we attempt to evaluate this? return false; } // GCC extension: sizeof(function) = 1. if (SrcTy->isFunctionType()) { // FIXME: AlignOf shouldn't be unconditionally 4! Result = isSizeOf ? 1 : 4; return true; } // Get information about the size or align. unsigned CharSize = Ctx.Target.getCharWidth(); if (isSizeOf) Result = getIntTypeSizeInBits(SrcTy) / CharSize; else Result = Ctx.getTypeAlign(SrcTy) / CharSize; return true; } bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { if (E->isOffsetOfOp()) Result = E->evaluateOffsetOf(Ctx); else if (E->isSizeOfAlignOfOp()) return EvaluateSizeAlignOf(E->getOpcode() == UnaryOperator::SizeOf, E->getSubExpr()->getType(), E->getType()); else { // Get the operand value. If this is sizeof/alignof, do not evalute the // operand. This affects C99 6.6p3. if (!EvaluateInteger(E->getSubExpr(), Result, Ctx)) return false; switch (E->getOpcode()) { // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. // See C99 6.6p3. default: return false; case UnaryOperator::LNot: { bool Val = Result == 0; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); Result = Val; break; } case UnaryOperator::Extension: case UnaryOperator::Plus: // The result is always just the subexpr break; case UnaryOperator::Minus: Result = -Result; break; case UnaryOperator::Not: Result = ~Result; break; } } Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); return true; } bool IntExprEvaluator::HandleCast(const Expr* SubExpr, QualType DestType) { unsigned DestWidth = getIntTypeSizeInBits(DestType); // Handle simple integer->integer casts. if (SubExpr->getType()->isIntegerType()) { if (!EvaluateInteger(SubExpr, Result, Ctx)) return false; // Figure out if this is a truncate, extend or noop cast. // If the input is signed, do a sign extend, noop, or truncate. if (DestType->isBooleanType()) { // Conversion to bool compares against zero. Result = Result != 0; Result.zextOrTrunc(DestWidth); } else Result.extOrTrunc(DestWidth); } else if (SubExpr->getType()->isPointerType()) { APValue LV; if (!EvaluatePointer(SubExpr, LV, Ctx)) return false; if (LV.getLValueBase()) return false; Result.extOrTrunc(DestWidth); Result = LV.getLValueOffset(); } else { assert(0 && "Unhandled cast!"); } Result.setIsUnsigned(DestType->isUnsignedIntegerType()); return true; } //===----------------------------------------------------------------------===// // Top level TryEvaluate. //===----------------------------------------------------------------------===// bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const { llvm::APSInt sInt(32); #if USE_NEW_EVALUATOR if (getType()->isIntegerType()) { if (EvaluateInteger(this, sInt, Ctx)) { Result = APValue(sInt); return true; } } else return false; #else if (CalcFakeICEVal(this, sInt, Ctx)) { Result = APValue(sInt); return true; } #endif return false; } <commit_msg>simplify some code a bit.<commit_after>//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Expr constant evaluator. // //===----------------------------------------------------------------------===// #include "clang/AST/APValue.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Expr.h" #include "clang/AST/StmtVisitor.h" #include "clang/Basic/TargetInfo.h" #include "llvm/Support/Compiler.h" using namespace clang; using llvm::APSInt; #define USE_NEW_EVALUATOR 0 static bool CalcFakeICEVal(const Expr *Expr, llvm::APSInt &Result, ASTContext &Context) { // Calculate the value of an expression that has a calculatable // value, but isn't an ICE. Currently, this only supports // a very narrow set of extensions, but it can be expanded if needed. if (const ParenExpr *PE = dyn_cast<ParenExpr>(Expr)) return CalcFakeICEVal(PE->getSubExpr(), Result, Context); if (const CastExpr *CE = dyn_cast<CastExpr>(Expr)) { QualType CETy = CE->getType(); if ((CETy->isIntegralType() && !CETy->isBooleanType()) || CETy->isPointerType()) { if (CalcFakeICEVal(CE->getSubExpr(), Result, Context)) { Result.extOrTrunc(Context.getTypeSize(CETy)); // FIXME: This assumes pointers are signed. Result.setIsSigned(CETy->isSignedIntegerType() || CETy->isPointerType()); return true; } } } if (Expr->getType()->isIntegralType()) return Expr->isIntegerConstantExpr(Result, Context); return false; } static bool EvaluatePointer(const Expr *E, APValue &Result, ASTContext &Ctx); static bool EvaluateInteger(const Expr *E, APSInt &Result, ASTContext &Ctx); //===----------------------------------------------------------------------===// // Pointer Evaluation //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN PointerExprEvaluator : public StmtVisitor<PointerExprEvaluator, APValue> { ASTContext &Ctx; public: PointerExprEvaluator(ASTContext &ctx) : Ctx(ctx) {} APValue VisitStmt(Stmt *S) { // FIXME: Remove this when we support more expressions. printf("Unhandled pointer statement\n"); S->dump(); return APValue(); } APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } APValue VisitBinaryOperator(const BinaryOperator *E); APValue VisitCastExpr(const CastExpr* E); }; } // end anonymous namespace static bool EvaluatePointer(const Expr* E, APValue& Result, ASTContext &Ctx) { if (!E->getType()->isPointerType()) return false; Result = PointerExprEvaluator(Ctx).Visit(const_cast<Expr*>(E)); return Result.isLValue(); } APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { if (E->getOpcode() != BinaryOperator::Add && E->getOpcode() != BinaryOperator::Sub) return APValue(); const Expr *PExp = E->getLHS(); const Expr *IExp = E->getRHS(); if (IExp->getType()->isPointerType()) std::swap(PExp, IExp); APValue ResultLValue; if (!EvaluatePointer(PExp, ResultLValue, Ctx)) return APValue(); llvm::APSInt AdditionalOffset(32); if (!EvaluateInteger(IExp, AdditionalOffset, Ctx)) return APValue(); uint64_t Offset = ResultLValue.getLValueOffset(); if (E->getOpcode() == BinaryOperator::Add) Offset += AdditionalOffset.getZExtValue(); else Offset -= AdditionalOffset.getZExtValue(); return APValue(ResultLValue.getLValueBase(), Offset); } APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { const Expr* SubExpr = E->getSubExpr(); // Check for pointer->pointer cast if (SubExpr->getType()->isPointerType()) { APValue Result; if (EvaluatePointer(SubExpr, Result, Ctx)) return Result; return APValue(); } if (SubExpr->getType()->isArithmeticType()) { llvm::APSInt Result(32); if (EvaluateInteger(SubExpr, Result, Ctx)) { Result.extOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(E->getType()))); return APValue(0, Result.getZExtValue()); } } assert(0 && "Unhandled cast"); return APValue(); } //===----------------------------------------------------------------------===// // Integer Evaluation //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN IntExprEvaluator : public StmtVisitor<IntExprEvaluator, bool> { ASTContext &Ctx; APSInt &Result; public: IntExprEvaluator(ASTContext &ctx, APSInt &result) : Ctx(ctx), Result(result){} unsigned getIntTypeSizeInBits(QualType T) const { return (unsigned)Ctx.getTypeSize(T); } //===--------------------------------------------------------------------===// // Visitor Methods //===--------------------------------------------------------------------===// bool VisitStmt(Stmt *S) { // FIXME: Remove this when we support more expressions. printf("unhandled int expression"); S->dump(); return false; } bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } bool VisitBinaryOperator(const BinaryOperator *E); bool VisitUnaryOperator(const UnaryOperator *E); bool VisitCastExpr(const CastExpr* E) { return HandleCast(E->getSubExpr(), E->getType()); } bool VisitImplicitCastExpr(const ImplicitCastExpr* E) { return HandleCast(E->getSubExpr(), E->getType()); } bool VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) { return EvaluateSizeAlignOf(E->isSizeOf(),E->getArgumentType(),E->getType()); } bool VisitIntegerLiteral(const IntegerLiteral *E) { Result = E->getValue(); return true; } private: bool HandleCast(const Expr* SubExpr, QualType DestType); bool EvaluateSizeAlignOf(bool isSizeOf, QualType SrcTy, QualType DstTy); }; } // end anonymous namespace static bool EvaluateInteger(const Expr* E, APSInt &Result, ASTContext &Ctx) { return IntExprEvaluator(Ctx, Result).Visit(const_cast<Expr*>(E)); } bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { // The LHS of a constant expr is always evaluated and needed. llvm::APSInt RHS(32); if (!Visit(E->getLHS()) || !EvaluateInteger(E->getRHS(), RHS, Ctx)) return false; switch (E->getOpcode()) { default: return false; case BinaryOperator::Mul: Result *= RHS; break; case BinaryOperator::Add: Result += RHS; break; case BinaryOperator::Sub: Result -= RHS; break; case BinaryOperator::And: Result &= RHS; break; case BinaryOperator::Xor: Result ^= RHS; break; case BinaryOperator::Or: Result |= RHS; break; case BinaryOperator::Div: if (RHS == 0) return false; Result /= RHS; break; case BinaryOperator::Rem: if (RHS == 0) return false; Result %= RHS; break; case BinaryOperator::Shl: Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1); break; case BinaryOperator::Shr: Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1); break; case BinaryOperator::LT: Result = Result < RHS; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); break; case BinaryOperator::GT: Result = Result > RHS; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); break; case BinaryOperator::LE: Result = Result <= RHS; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); break; case BinaryOperator::GE: Result = Result >= RHS; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); break; case BinaryOperator::EQ: Result = Result == RHS; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); break; case BinaryOperator::NE: Result = Result != RHS; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); break; case BinaryOperator::Comma: // C99 6.6p3: "shall not contain assignment, ..., or comma operators, // *except* when they are contained within a subexpression that is not // evaluated". Note that Assignment can never happen due to constraints // on the LHS subexpr, so we don't need to check it here. // FIXME: Need to come up with an efficient way to deal with the C99 // rules on evaluation while still evaluating this. Maybe a // "evaluated comma" out parameter? return false; } Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); return true; } /// EvaluateSizeAlignOf - Evaluate sizeof(SrcTy) or alignof(SrcTy) with a result /// as a DstTy type. bool IntExprEvaluator::EvaluateSizeAlignOf(bool isSizeOf, QualType SrcTy, QualType DstTy) { // Return the result in the right width. Result.zextOrTrunc(getIntTypeSizeInBits(DstTy)); Result.setIsUnsigned(DstTy->isUnsignedIntegerType()); // sizeof(void) and __alignof__(void) = 1 as a gcc extension. if (SrcTy->isVoidType()) Result = 1; // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. if (!SrcTy->isConstantSizeType()) { // FIXME: Should we attempt to evaluate this? return false; } // GCC extension: sizeof(function) = 1. if (SrcTy->isFunctionType()) { // FIXME: AlignOf shouldn't be unconditionally 4! Result = isSizeOf ? 1 : 4; return true; } // Get information about the size or align. unsigned CharSize = Ctx.Target.getCharWidth(); if (isSizeOf) Result = getIntTypeSizeInBits(SrcTy) / CharSize; else Result = Ctx.getTypeAlign(SrcTy) / CharSize; return true; } bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { if (E->isOffsetOfOp()) { Result = E->evaluateOffsetOf(Ctx); Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); return true; } if (E->isSizeOfAlignOfOp()) return EvaluateSizeAlignOf(E->getOpcode() == UnaryOperator::SizeOf, E->getSubExpr()->getType(), E->getType()); // Get the operand value. if (!EvaluateInteger(E->getSubExpr(), Result, Ctx)) return false; switch (E->getOpcode()) { // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. // See C99 6.6p3. default: return false; case UnaryOperator::LNot: { bool Val = Result == 0; Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); Result = Val; break; } case UnaryOperator::Extension: case UnaryOperator::Plus: // The result is always just the subexpr break; case UnaryOperator::Minus: Result = -Result; break; case UnaryOperator::Not: Result = ~Result; break; } Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); return true; } bool IntExprEvaluator::HandleCast(const Expr* SubExpr, QualType DestType) { unsigned DestWidth = getIntTypeSizeInBits(DestType); // Handle simple integer->integer casts. if (SubExpr->getType()->isIntegerType()) { if (!EvaluateInteger(SubExpr, Result, Ctx)) return false; // Figure out if this is a truncate, extend or noop cast. // If the input is signed, do a sign extend, noop, or truncate. if (DestType->isBooleanType()) { // Conversion to bool compares against zero. Result = Result != 0; Result.zextOrTrunc(DestWidth); } else Result.extOrTrunc(DestWidth); } else if (SubExpr->getType()->isPointerType()) { APValue LV; if (!EvaluatePointer(SubExpr, LV, Ctx)) return false; if (LV.getLValueBase()) return false; Result.extOrTrunc(DestWidth); Result = LV.getLValueOffset(); } else { assert(0 && "Unhandled cast!"); } Result.setIsUnsigned(DestType->isUnsignedIntegerType()); return true; } //===----------------------------------------------------------------------===// // Top level TryEvaluate. //===----------------------------------------------------------------------===// bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const { llvm::APSInt sInt(32); #if USE_NEW_EVALUATOR if (getType()->isIntegerType()) { if (EvaluateInteger(this, sInt, Ctx)) { Result = APValue(sInt); return true; } } else return false; #else if (CalcFakeICEVal(this, sInt, Ctx)) { Result = APValue(sInt); return true; } #endif return false; } <|endoftext|>
<commit_before>//===- SymbolStripping.cpp - Strip symbols for functions and modules ------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements stripping symbols out of symbol tables. // // Specifically, this allows you to strip all of the symbols out of: // * A function // * All functions in a module // * All symbols in a module (all function symbols + all module scope symbols) // // Notice that: // * This pass makes code much less readable, so it should only be used in // situations where the 'strip' utility would be used (such as reducing // code size, and making it harder to reverse engineer code). // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Module.h" #include "llvm/SymbolTable.h" #include "llvm/Pass.h" namespace llvm { static bool StripSymbolTable(SymbolTable &SymTab) { bool RemovedSymbol = false; for (SymbolTable::iterator I = SymTab.begin(); I != SymTab.end(); ++I) { std::map<const std::string, Value *> &Plane = I->second; SymbolTable::type_iterator B; while ((B = Plane.begin()) != Plane.end()) { // Found nonempty type plane! Value *V = B->second; if (isa<Constant>(V) || isa<Type>(V)) SymTab.type_remove(B); else V->setName("", &SymTab); // Set name to "", removing from symbol table! RemovedSymbol = true; assert(Plane.begin() != B && "Symbol not removed from table!"); } } return RemovedSymbol; } namespace { struct SymbolStripping : public FunctionPass { virtual bool runOnFunction(Function &F) { return StripSymbolTable(F.getSymbolTable()); } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; RegisterOpt<SymbolStripping> X("strip", "Strip symbols from functions"); struct FullSymbolStripping : public SymbolStripping { virtual bool doInitialization(Module &M) { return StripSymbolTable(M.getSymbolTable()); } }; RegisterOpt<FullSymbolStripping> Y("mstrip", "Strip symbols from module and functions"); } Pass *createSymbolStrippingPass() { return new SymbolStripping(); } Pass *createFullSymbolStrippingPass() { return new FullSymbolStripping(); } } // End llvm namespace <commit_msg>Finegrainify namespacification The module stripping pass should not strip symbols on external globals<commit_after>//===- SymbolStripping.cpp - Strip symbols for functions and modules ------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements stripping symbols out of symbol tables. // // Specifically, this allows you to strip all of the symbols out of: // * A function // * All functions in a module // * All symbols in a module (all function symbols + all module scope symbols) // // Notice that: // * This pass makes code much less readable, so it should only be used in // situations where the 'strip' utility would be used (such as reducing // code size, and making it harder to reverse engineer code). // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Module.h" #include "llvm/SymbolTable.h" #include "llvm/Pass.h" using namespace llvm; static bool StripSymbolTable(SymbolTable &SymTab) { bool RemovedSymbol = false; for (SymbolTable::iterator I = SymTab.begin(); I != SymTab.end(); ++I) { std::map<const std::string, Value *> &Plane = I->second; SymbolTable::type_iterator B = Plane.begin(); while (B != Plane.end()) { // Found nonempty type plane! Value *V = B->second; if (isa<Constant>(V) || isa<Type>(V)) { SymTab.type_remove(B++); RemovedSymbol = true; } else { ++B; if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasInternalLinkage()){ // Set name to "", removing from symbol table! V->setName("", &SymTab); RemovedSymbol = true; } } } } return RemovedSymbol; } namespace { struct SymbolStripping : public FunctionPass { virtual bool runOnFunction(Function &F) { return StripSymbolTable(F.getSymbolTable()); } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; RegisterOpt<SymbolStripping> X("strip", "Strip symbols from functions"); struct FullSymbolStripping : public SymbolStripping { virtual bool doInitialization(Module &M) { return StripSymbolTable(M.getSymbolTable()); } }; RegisterOpt<FullSymbolStripping> Y("mstrip", "Strip symbols from module and functions"); } Pass *llvm::createSymbolStrippingPass() { return new SymbolStripping(); } Pass *llvm::createFullSymbolStrippingPass() { return new FullSymbolStripping(); } <|endoftext|>
<commit_before><commit_msg>coverity#1242751 Uninitialized scalar field<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: strindlg.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-01-05 16:28:29 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #include <tools/debug.hxx> #include "strindlg.hxx" #include "scresid.hxx" #include "miscdlgs.hrc" //================================================================== ScStringInputDlg::ScStringInputDlg( Window* pParent, const String& rTitle, const String& rEditTitle, const String& rDefault, ULONG nHelpId ) : ModalDialog ( pParent, ScResId( RID_SCDLG_STRINPUT ) ), // aEdInput ( this, ScResId( ED_INPUT ) ), aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ), aFtEditTitle ( this, ScResId( FT_LABEL ) ) { SetHelpId( nHelpId ); SetText( rTitle ); aFtEditTitle.SetText( rEditTitle ); aEdInput.SetText( rDefault ); aEdInput.SetSelection(Selection(SELECTION_MIN, SELECTION_MAX)); // HelpId for Edit different for different uses DBG_ASSERT( nHelpId == FID_TAB_APPEND || nHelpId == FID_TAB_RENAME || nHelpId == HID_SC_ADD_AUTOFMT || nHelpId == HID_SC_RENAME_AUTOFMT || nHelpId == SID_RENAME_OBJECT, "unknown ID" ); if ( nHelpId == FID_TAB_APPEND ) aEdInput.SetHelpId( HID_SC_APPEND_NAME ); else if ( nHelpId == FID_TAB_RENAME ) aEdInput.SetHelpId( HID_SC_RENAME_NAME ); else if ( nHelpId == HID_SC_ADD_AUTOFMT ) aEdInput.SetHelpId( HID_SC_AUTOFMT_NAME ); else if ( nHelpId == HID_SC_RENAME_AUTOFMT ) aEdInput.SetHelpId( HID_SC_REN_AFMT_NAME ); else if ( nHelpId == SID_RENAME_OBJECT ) aEdInput.SetHelpId( HID_SC_RENAME_OBJECT ); //------------- FreeResource(); } //------------------------------------------------------------------------ void ScStringInputDlg::GetInputString( String& rString ) const { rString = aEdInput.GetText(); } __EXPORT ScStringInputDlg::~ScStringInputDlg() { } <commit_msg>INTEGRATION: CWS tune03 (1.3.172); FILE MERGED 2004/07/08 16:45:15 mhu 1.3.172.1: #i29979# Added SC_DLLPUBLIC/PRIVATE (see scdllapi.h) to exported symbols/classes.<commit_after>/************************************************************************* * * $RCSfile: strindlg.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-08-23 09:38:54 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #undef SC_DLLIMPLEMENTATION #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #include <tools/debug.hxx> #include "strindlg.hxx" #include "scresid.hxx" #include "miscdlgs.hrc" //================================================================== ScStringInputDlg::ScStringInputDlg( Window* pParent, const String& rTitle, const String& rEditTitle, const String& rDefault, ULONG nHelpId ) : ModalDialog ( pParent, ScResId( RID_SCDLG_STRINPUT ) ), // aEdInput ( this, ScResId( ED_INPUT ) ), aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ), aFtEditTitle ( this, ScResId( FT_LABEL ) ) { SetHelpId( nHelpId ); SetText( rTitle ); aFtEditTitle.SetText( rEditTitle ); aEdInput.SetText( rDefault ); aEdInput.SetSelection(Selection(SELECTION_MIN, SELECTION_MAX)); // HelpId for Edit different for different uses DBG_ASSERT( nHelpId == FID_TAB_APPEND || nHelpId == FID_TAB_RENAME || nHelpId == HID_SC_ADD_AUTOFMT || nHelpId == HID_SC_RENAME_AUTOFMT || nHelpId == SID_RENAME_OBJECT, "unknown ID" ); if ( nHelpId == FID_TAB_APPEND ) aEdInput.SetHelpId( HID_SC_APPEND_NAME ); else if ( nHelpId == FID_TAB_RENAME ) aEdInput.SetHelpId( HID_SC_RENAME_NAME ); else if ( nHelpId == HID_SC_ADD_AUTOFMT ) aEdInput.SetHelpId( HID_SC_AUTOFMT_NAME ); else if ( nHelpId == HID_SC_RENAME_AUTOFMT ) aEdInput.SetHelpId( HID_SC_REN_AFMT_NAME ); else if ( nHelpId == SID_RENAME_OBJECT ) aEdInput.SetHelpId( HID_SC_RENAME_OBJECT ); //------------- FreeResource(); } //------------------------------------------------------------------------ void ScStringInputDlg::GetInputString( String& rString ) const { rString = aEdInput.GetText(); } __EXPORT ScStringInputDlg::~ScStringInputDlg() { } <|endoftext|>
<commit_before>#include "musicabstracttablewidget.h" MusicAbstractTableWidget::MusicAbstractTableWidget(QWidget *parent) : QTableWidget(parent) { setAttribute(Qt::WA_TranslucentBackground, true); setFont(QFont("Helvetica")); setColumnCount(3); setRowCount(0); setShowGrid(false);//Does not display the grid QHeaderView *headerview = horizontalHeader(); headerview->setVisible(false); headerview->resizeSection(0, 20); headerview->resizeSection(1, 277); headerview->resizeSection(2, 26); verticalHeader()->setVisible(false); setMouseTracking(true); //Open the capture mouse function setStyleSheet(MusicUIObject::MTableWidgetStyle01 + \ MusicUIObject::MScrollBarStyle01 + \ MusicUIObject::MLineEditStyle02 ); //Set the color of selected row setFrameShape(QFrame::NoFrame);//Set No Border setEditTriggers(QTableWidget::NoEditTriggers);//No edit setSelectionBehavior(QTableWidget::SelectRows); //Multi-line election setSelectionMode(QAbstractItemView::SingleSelection); setFocusPolicy(Qt::NoFocus); setTransparent(80); m_previousColorRow = -1; m_previousClickRow = -1; m_defaultBkColor = QColor(255, 255, 255, 0); connect(this, SIGNAL(cellEntered(int,int)), SLOT(listCellEntered(int,int))); connect(this, SIGNAL(cellClicked(int,int)), SLOT(listCellClicked(int,int))); } MusicAbstractTableWidget::~MusicAbstractTableWidget() { } void MusicAbstractTableWidget::clear() { clearContents(); setRowCount(0); } void MusicAbstractTableWidget::setTransparent(int angle) { QPalette pal = palette(); pal.setBrush(QPalette::Base, QBrush(QColor(255, 255, 255, angle))); setPalette(pal); } void MusicAbstractTableWidget::listCellEntered(int row, int column) { QTableWidgetItem *it = item(m_previousColorRow, 0); if(it != 0) { setRowColor(m_previousColorRow, m_defaultBkColor); } it = item(row, column); if(it != 0 && !it->isSelected() && !it->text().isEmpty()) { setRowColor(row, QColor(20, 20, 20, 40)); } m_previousColorRow = row; } void MusicAbstractTableWidget::setRowColor(int row, const QColor &color) const { for(int col=0; col<columnCount(); col++) { QTableWidgetItem *it = item(row, col); it->setBackgroundColor(color); } } <commit_msg>remove item is empty option not can hover[784596]<commit_after>#include "musicabstracttablewidget.h" MusicAbstractTableWidget::MusicAbstractTableWidget(QWidget *parent) : QTableWidget(parent) { setAttribute(Qt::WA_TranslucentBackground, true); setFont(QFont("Helvetica")); setColumnCount(3); setRowCount(0); setShowGrid(false);//Does not display the grid QHeaderView *headerview = horizontalHeader(); headerview->setVisible(false); headerview->resizeSection(0, 20); headerview->resizeSection(1, 277); headerview->resizeSection(2, 26); verticalHeader()->setVisible(false); setMouseTracking(true); //Open the capture mouse function setStyleSheet(MusicUIObject::MTableWidgetStyle01 + \ MusicUIObject::MScrollBarStyle01 + \ MusicUIObject::MLineEditStyle02 ); //Set the color of selected row setFrameShape(QFrame::NoFrame);//Set No Border setEditTriggers(QTableWidget::NoEditTriggers);//No edit setSelectionBehavior(QTableWidget::SelectRows); //Multi-line election setSelectionMode(QAbstractItemView::SingleSelection); setFocusPolicy(Qt::NoFocus); setTransparent(80); m_previousColorRow = -1; m_previousClickRow = -1; m_defaultBkColor = QColor(255, 255, 255, 0); connect(this, SIGNAL(cellEntered(int,int)), SLOT(listCellEntered(int,int))); connect(this, SIGNAL(cellClicked(int,int)), SLOT(listCellClicked(int,int))); } MusicAbstractTableWidget::~MusicAbstractTableWidget() { } void MusicAbstractTableWidget::clear() { clearContents(); setRowCount(0); } void MusicAbstractTableWidget::setTransparent(int angle) { QPalette pal = palette(); pal.setBrush(QPalette::Base, QBrush(QColor(255, 255, 255, angle))); setPalette(pal); } void MusicAbstractTableWidget::listCellEntered(int row, int column) { QTableWidgetItem *it = item(m_previousColorRow, 0); if(it != 0) { setRowColor(m_previousColorRow, m_defaultBkColor); } it = item(row, column); if(it != NULL) { setRowColor(row, QColor(20, 20, 20, 40)); } m_previousColorRow = row; } void MusicAbstractTableWidget::setRowColor(int row, const QColor &color) const { for(int col=0; col<columnCount(); col++) { QTableWidgetItem *it = item(row, col); it->setBackgroundColor(color); } } <|endoftext|>