text
stringlengths
54
60.6k
<commit_before>// $Id$ // Author: Sergey Linev 21/12/2013 #include "TCivetweb.h" #include "../civetweb/civetweb.h" #include <stdlib.h> #include <string.h> #include "THttpServer.h" #include "TUrl.h" TCivetweb* TCivetweb::fTemp = 0; static int log_message_handler(const struct mg_connection *conn, const char *message) { return TCivetweb::ProcessLogMessage(mg_get_request_info((struct mg_connection *)conn)->user_data, message); } static int begin_request_handler(struct mg_connection *conn) { TCivetweb *engine = (TCivetweb *) mg_get_request_info(conn)->user_data; if (engine == 0) return 0; THttpServer *serv = engine->GetServer(); if (serv == 0) return 0; const struct mg_request_info *request_info = mg_get_request_info(conn); THttpCallArg arg; TString filename; Bool_t execres = kTRUE, debug = engine->IsDebugMode(); if (!debug && serv->IsFileRequested(request_info->uri, filename)) { if ((filename.Index(".js") != kNPOS) || (filename.Index(".css") != kNPOS)) { Int_t length = 0; char *buf = THttpServer::ReadFileContent(filename.Data(), length); if (buf == 0) { arg.Set404(); } else { arg.SetContentType(THttpServer::GetMimeType(filename.Data())); arg.SetBinData(buf, length); arg.AddHeader("Cache-Control", "max-age=3600"); arg.SetZipping(2); } } else { arg.SetFile(filename.Data()); } } else { arg.SetPathAndFileName(request_info->uri); // path and file name arg.SetQuery(request_info->query_string); // query arguments arg.SetTopName(engine->GetTopName()); arg.SetMethod(request_info->request_method); // method like GET or POST if (request_info->remote_user!=0) arg.SetUserName(request_info->remote_user); TString header; for (int n = 0; n < request_info->num_headers; n++) header.Append(TString::Format("%s: %s\r\n", request_info->http_headers[n].name, request_info->http_headers[n].value)); arg.SetRequestHeader(header); const char* len = mg_get_header(conn, "Content-Length"); Int_t ilen = len!=0 ? TString(len).Atoi() : 0; if (ilen>0) { void* buf = malloc(ilen+1); // one byte more for null-termination Int_t iread = mg_read(conn, buf, ilen); if (iread==ilen) arg.SetPostData(buf, ilen); else free(buf); } if (debug) { TString cont; cont.Append("<title>Civetweb echo</title>"); cont.Append("<h1>Civetweb echo</h1>\n"); static int count = 0; cont.Append(TString::Format("Request %d:<br/>\n<pre>\n", ++count)); cont.Append(TString::Format(" Method : %s\n", arg.GetMethod())); cont.Append(TString::Format(" PathName : %s\n", arg.GetPathName())); cont.Append(TString::Format(" FileName : %s\n", arg.GetFileName())); cont.Append(TString::Format(" Query : %s\n", arg.GetQuery())); cont.Append(TString::Format(" PostData : %ld\n", arg.GetPostDataLength())); if (arg.GetUserName()) cont.Append(TString::Format(" User : %s\n", arg.GetUserName())); cont.Append("</pre><p>\n"); cont.Append("Environment:<br/>\n<pre>\n"); for (int n = 0; n < request_info->num_headers; n++) cont.Append(TString::Format(" %s = %s\n", request_info->http_headers[n].name, request_info->http_headers[n].value)); cont.Append("</pre><p>\n"); arg.SetContentType("text/html"); arg.SetContent(cont); } else { execres = serv->ExecuteHttp(&arg); } } if (!execres || arg.Is404()) { TString hdr; arg.FillHttpHeader(hdr, "HTTP/1.1"); mg_printf(conn, "%s", hdr.Data()); } else if (arg.IsFile()) { mg_send_file(conn, (const char *) arg.GetContent()); } else { Bool_t dozip = arg.GetZipping() > 0; switch (arg.GetZipping()) { case 2: if (arg.GetContentLength() < 10000) { dozip = kFALSE; break; } case 1: // check if request header has Accept-Encoding dozip = kFALSE; for (int n = 0; n < request_info->num_headers; n++) { TString name = request_info->http_headers[n].name; if (name.Index("Accept-Encoding", 0, TString::kIgnoreCase) != 0) continue; TString value = request_info->http_headers[n].value; dozip = (value.Index("gzip", 0, TString::kIgnoreCase) != kNPOS); break; } break; case 3: dozip = kTRUE; break; } if (dozip) arg.CompressWithGzip(); TString hdr; arg.FillHttpHeader(hdr, "HTTP/1.1"); mg_printf(conn, "%s", hdr.Data()); if (arg.GetContentLength() > 0) mg_write(conn, arg.GetContent(), (size_t) arg.GetContentLength()); } // Returning non-zero tells civetweb that our function has replied to // the client, and civetweb should not send client any more data. return 1; } ////////////////////////////////////////////////////////////////////////// // // // TCivetweb // // // // http server implementation, based on civetweb embedded server // // It is default kind of engine, created for THttpServer // // // // Following additional options can be specified // // top=foldername - name of top folder, seen in the browser // // thrds=N - use N threads to run civetweb server (default 5) // // auth_file - global authentication file // // auth_domain - domain name, used for authentication // // // // Example: // // new THttpServer("http:8080?top=MyApp&thrds=3"); // // // // Authentication: // // When auth_file and auth_domain parameters are specified, access // // to running http server will be possible only after user // // authentication, using so-call digest method. To generate // // authentication file, htdigest routine should be used: // // // // [shell] htdigest -c .htdigest domain_name user // // // // When creating server, parameters should be: // // // // new THttpServer("http:8080?auth_file=.htdigets&auth_domain=domain_name"); // // // ////////////////////////////////////////////////////////////////////////// ClassImp(TCivetweb) //______________________________________________________________________________ TCivetweb::TCivetweb() : THttpEngine("civetweb", "compact embedded http server"), fCtx(0), fCallbacks(0), fTopName(), fDebug(kFALSE), fStartError(kFALSE) { // constructor } //______________________________________________________________________________ TCivetweb::~TCivetweb() { // destructor if (fCtx != 0) mg_stop((struct mg_context *) fCtx); if (fCallbacks != 0) free(fCallbacks); fCtx = 0; fCallbacks = 0; } //______________________________________________________________________________ Int_t TCivetweb::ProcessLogMessage(void *instance, const char* message) { // static method to process log messages from civetweb server // introduced to resolve civetweb problem, that messages cannot be delivered directly // during mg_start() call TCivetweb* engine = (TCivetweb*) instance; if (engine==0) engine = fTemp; if (engine) return engine->ProcessLog(message); // provide debug output if (gDebug>0) printf("<TCivetweb::Log> %s\n",message); return 0; } //______________________________________________________________________________ Int_t TCivetweb::ProcessLog(const char* message) { // process civetweb log message, used to detect critical errors Bool_t critical = kFALSE; if ((strstr(message,"cannot bind to")!=0) && (strstr(message,"(Address already in use)")!=0)) { fStartError = kTRUE; critical = kTRUE; } if (critical || (gDebug>0)) Error("Log", message); return 0; } //______________________________________________________________________________ Bool_t TCivetweb::Create(const char *args) { // Creates embedded civetweb server // As main argument, http port should be specified like "8090". // Or one can provide combination of ipaddress and portnumber like 127.0.0.1:8090 // Extra parameters like in URL string could be specified after '?' mark: // thrds=N - there N is number of threads used by the civetweb (default is 5) // top=name - configure top name, visible in the web browser // auth_file=filename - authentication file name, created with htdigets utility // auth_domain=domain - authentication domain // loopback - bind specified port to loopback 127.0.0.1 address // debug - enable debug mode, server always returns html page with request info fCallbacks = malloc(sizeof(struct mg_callbacks)); memset(fCallbacks, 0, sizeof(struct mg_callbacks)); ((struct mg_callbacks *) fCallbacks)->begin_request = begin_request_handler; ((struct mg_callbacks *) fCallbacks)->log_message = log_message_handler; TString sport = "8080"; TString num_threads = "5"; TString auth_file, auth_domain, log_file; // extract arguments if ((args != 0) && (strlen(args) > 0)) { // first extract port number sport = ""; while ((*args != 0) && (*args != '?') && (*args != '/')) sport.Append(*args++); // than search for extra parameters while ((*args != 0) && (*args != '?')) args++; if (*args == '?') { TUrl url(TString::Format("http://localhost/folder%s", args)); if (url.IsValid()) { url.ParseOptions(); const char *top = url.GetValueFromOptions("top"); if (top != 0) fTopName = top; const char *log = url.GetValueFromOptions("log"); if (log != 0) log_file = log; Int_t thrds = url.GetIntValueFromOptions("thrds"); if (thrds > 0) num_threads.Form("%d", thrds); const char *afile = url.GetValueFromOptions("auth_file"); if (afile != 0) auth_file = afile; const char *adomain = url.GetValueFromOptions("auth_domain"); if (adomain != 0) auth_domain = adomain; if (url.HasOption("debug")) fDebug = kTRUE; if (url.HasOption("loopback") && (sport.Index(":")==kNPOS)) sport = TString("127.0.0.1:") + sport; } } } const char *options[20]; int op(0); Info("Create", "Starting HTTP server on port %s", sport.Data()); options[op++] = "listening_ports"; options[op++] = sport.Data(); options[op++] = "num_threads"; options[op++] = num_threads.Data(); if ((auth_file.Length() > 0) && (auth_domain.Length() > 0)) { options[op++] = "global_auth_file"; options[op++] = auth_file.Data(); options[op++] = "authentication_domain"; options[op++] = auth_domain.Data(); } if (log_file.Length() > 0) { options[op++] = "error_log_file"; options[op++] = log_file.Data(); } options[op++] = 0; // workaround for civetweb if (fTemp==0) fTemp = this; // Start the web server. fCtx = mg_start((struct mg_callbacks *) fCallbacks, this, options); if (fTemp==this) fTemp = 0; if (fStartError) return kFALSE; return kTRUE; } <commit_msg>Fix compilation warning (format not a string literal and no format arguments)<commit_after>// $Id$ // Author: Sergey Linev 21/12/2013 #include "TCivetweb.h" #include "../civetweb/civetweb.h" #include <stdlib.h> #include <string.h> #include "THttpServer.h" #include "TUrl.h" TCivetweb* TCivetweb::fTemp = 0; static int log_message_handler(const struct mg_connection *conn, const char *message) { return TCivetweb::ProcessLogMessage(mg_get_request_info((struct mg_connection *)conn)->user_data, message); } static int begin_request_handler(struct mg_connection *conn) { TCivetweb *engine = (TCivetweb *) mg_get_request_info(conn)->user_data; if (engine == 0) return 0; THttpServer *serv = engine->GetServer(); if (serv == 0) return 0; const struct mg_request_info *request_info = mg_get_request_info(conn); THttpCallArg arg; TString filename; Bool_t execres = kTRUE, debug = engine->IsDebugMode(); if (!debug && serv->IsFileRequested(request_info->uri, filename)) { if ((filename.Index(".js") != kNPOS) || (filename.Index(".css") != kNPOS)) { Int_t length = 0; char *buf = THttpServer::ReadFileContent(filename.Data(), length); if (buf == 0) { arg.Set404(); } else { arg.SetContentType(THttpServer::GetMimeType(filename.Data())); arg.SetBinData(buf, length); arg.AddHeader("Cache-Control", "max-age=3600"); arg.SetZipping(2); } } else { arg.SetFile(filename.Data()); } } else { arg.SetPathAndFileName(request_info->uri); // path and file name arg.SetQuery(request_info->query_string); // query arguments arg.SetTopName(engine->GetTopName()); arg.SetMethod(request_info->request_method); // method like GET or POST if (request_info->remote_user!=0) arg.SetUserName(request_info->remote_user); TString header; for (int n = 0; n < request_info->num_headers; n++) header.Append(TString::Format("%s: %s\r\n", request_info->http_headers[n].name, request_info->http_headers[n].value)); arg.SetRequestHeader(header); const char* len = mg_get_header(conn, "Content-Length"); Int_t ilen = len!=0 ? TString(len).Atoi() : 0; if (ilen>0) { void* buf = malloc(ilen+1); // one byte more for null-termination Int_t iread = mg_read(conn, buf, ilen); if (iread==ilen) arg.SetPostData(buf, ilen); else free(buf); } if (debug) { TString cont; cont.Append("<title>Civetweb echo</title>"); cont.Append("<h1>Civetweb echo</h1>\n"); static int count = 0; cont.Append(TString::Format("Request %d:<br/>\n<pre>\n", ++count)); cont.Append(TString::Format(" Method : %s\n", arg.GetMethod())); cont.Append(TString::Format(" PathName : %s\n", arg.GetPathName())); cont.Append(TString::Format(" FileName : %s\n", arg.GetFileName())); cont.Append(TString::Format(" Query : %s\n", arg.GetQuery())); cont.Append(TString::Format(" PostData : %ld\n", arg.GetPostDataLength())); if (arg.GetUserName()) cont.Append(TString::Format(" User : %s\n", arg.GetUserName())); cont.Append("</pre><p>\n"); cont.Append("Environment:<br/>\n<pre>\n"); for (int n = 0; n < request_info->num_headers; n++) cont.Append(TString::Format(" %s = %s\n", request_info->http_headers[n].name, request_info->http_headers[n].value)); cont.Append("</pre><p>\n"); arg.SetContentType("text/html"); arg.SetContent(cont); } else { execres = serv->ExecuteHttp(&arg); } } if (!execres || arg.Is404()) { TString hdr; arg.FillHttpHeader(hdr, "HTTP/1.1"); mg_printf(conn, "%s", hdr.Data()); } else if (arg.IsFile()) { mg_send_file(conn, (const char *) arg.GetContent()); } else { Bool_t dozip = arg.GetZipping() > 0; switch (arg.GetZipping()) { case 2: if (arg.GetContentLength() < 10000) { dozip = kFALSE; break; } case 1: // check if request header has Accept-Encoding dozip = kFALSE; for (int n = 0; n < request_info->num_headers; n++) { TString name = request_info->http_headers[n].name; if (name.Index("Accept-Encoding", 0, TString::kIgnoreCase) != 0) continue; TString value = request_info->http_headers[n].value; dozip = (value.Index("gzip", 0, TString::kIgnoreCase) != kNPOS); break; } break; case 3: dozip = kTRUE; break; } if (dozip) arg.CompressWithGzip(); TString hdr; arg.FillHttpHeader(hdr, "HTTP/1.1"); mg_printf(conn, "%s", hdr.Data()); if (arg.GetContentLength() > 0) mg_write(conn, arg.GetContent(), (size_t) arg.GetContentLength()); } // Returning non-zero tells civetweb that our function has replied to // the client, and civetweb should not send client any more data. return 1; } ////////////////////////////////////////////////////////////////////////// // // // TCivetweb // // // // http server implementation, based on civetweb embedded server // // It is default kind of engine, created for THttpServer // // // // Following additional options can be specified // // top=foldername - name of top folder, seen in the browser // // thrds=N - use N threads to run civetweb server (default 5) // // auth_file - global authentication file // // auth_domain - domain name, used for authentication // // // // Example: // // new THttpServer("http:8080?top=MyApp&thrds=3"); // // // // Authentication: // // When auth_file and auth_domain parameters are specified, access // // to running http server will be possible only after user // // authentication, using so-call digest method. To generate // // authentication file, htdigest routine should be used: // // // // [shell] htdigest -c .htdigest domain_name user // // // // When creating server, parameters should be: // // // // new THttpServer("http:8080?auth_file=.htdigets&auth_domain=domain_name"); // // // ////////////////////////////////////////////////////////////////////////// ClassImp(TCivetweb) //______________________________________________________________________________ TCivetweb::TCivetweb() : THttpEngine("civetweb", "compact embedded http server"), fCtx(0), fCallbacks(0), fTopName(), fDebug(kFALSE), fStartError(kFALSE) { // constructor } //______________________________________________________________________________ TCivetweb::~TCivetweb() { // destructor if (fCtx != 0) mg_stop((struct mg_context *) fCtx); if (fCallbacks != 0) free(fCallbacks); fCtx = 0; fCallbacks = 0; } //______________________________________________________________________________ Int_t TCivetweb::ProcessLogMessage(void *instance, const char* message) { // static method to process log messages from civetweb server // introduced to resolve civetweb problem, that messages cannot be delivered directly // during mg_start() call TCivetweb* engine = (TCivetweb*) instance; if (engine==0) engine = fTemp; if (engine) return engine->ProcessLog(message); // provide debug output if (gDebug>0) printf("<TCivetweb::Log> %s\n",message); return 0; } //______________________________________________________________________________ Int_t TCivetweb::ProcessLog(const char* message) { // process civetweb log message, used to detect critical errors Bool_t critical = kFALSE; if ((strstr(message,"cannot bind to")!=0) && (strstr(message,"(Address already in use)")!=0)) { fStartError = kTRUE; critical = kTRUE; } if (critical || (gDebug>0)) Error("Log", "%s", message); return 0; } //______________________________________________________________________________ Bool_t TCivetweb::Create(const char *args) { // Creates embedded civetweb server // As main argument, http port should be specified like "8090". // Or one can provide combination of ipaddress and portnumber like 127.0.0.1:8090 // Extra parameters like in URL string could be specified after '?' mark: // thrds=N - there N is number of threads used by the civetweb (default is 5) // top=name - configure top name, visible in the web browser // auth_file=filename - authentication file name, created with htdigets utility // auth_domain=domain - authentication domain // loopback - bind specified port to loopback 127.0.0.1 address // debug - enable debug mode, server always returns html page with request info fCallbacks = malloc(sizeof(struct mg_callbacks)); memset(fCallbacks, 0, sizeof(struct mg_callbacks)); ((struct mg_callbacks *) fCallbacks)->begin_request = begin_request_handler; ((struct mg_callbacks *) fCallbacks)->log_message = log_message_handler; TString sport = "8080"; TString num_threads = "5"; TString auth_file, auth_domain, log_file; // extract arguments if ((args != 0) && (strlen(args) > 0)) { // first extract port number sport = ""; while ((*args != 0) && (*args != '?') && (*args != '/')) sport.Append(*args++); // than search for extra parameters while ((*args != 0) && (*args != '?')) args++; if (*args == '?') { TUrl url(TString::Format("http://localhost/folder%s", args)); if (url.IsValid()) { url.ParseOptions(); const char *top = url.GetValueFromOptions("top"); if (top != 0) fTopName = top; const char *log = url.GetValueFromOptions("log"); if (log != 0) log_file = log; Int_t thrds = url.GetIntValueFromOptions("thrds"); if (thrds > 0) num_threads.Form("%d", thrds); const char *afile = url.GetValueFromOptions("auth_file"); if (afile != 0) auth_file = afile; const char *adomain = url.GetValueFromOptions("auth_domain"); if (adomain != 0) auth_domain = adomain; if (url.HasOption("debug")) fDebug = kTRUE; if (url.HasOption("loopback") && (sport.Index(":")==kNPOS)) sport = TString("127.0.0.1:") + sport; } } } const char *options[20]; int op(0); Info("Create", "Starting HTTP server on port %s", sport.Data()); options[op++] = "listening_ports"; options[op++] = sport.Data(); options[op++] = "num_threads"; options[op++] = num_threads.Data(); if ((auth_file.Length() > 0) && (auth_domain.Length() > 0)) { options[op++] = "global_auth_file"; options[op++] = auth_file.Data(); options[op++] = "authentication_domain"; options[op++] = auth_domain.Data(); } if (log_file.Length() > 0) { options[op++] = "error_log_file"; options[op++] = log_file.Data(); } options[op++] = 0; // workaround for civetweb if (fTemp==0) fTemp = this; // Start the web server. fCtx = mg_start((struct mg_callbacks *) fCallbacks, this, options); if (fTemp==this) fTemp = 0; if (fStartError) return kFALSE; return kTRUE; } <|endoftext|>
<commit_before>// Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/application/extension/application_widget_storage.h" #include <string> #include "base/file_util.h" #include "base/strings/utf_string_conversions.h" #include "sql/statement.h" #include "sql/transaction.h" #include "xwalk/application/common/application_manifest_constants.h" #include "xwalk/application/common/manifest_handlers/widget_handler.h" namespace { namespace widget_keys = xwalk::application_widget_keys; const char kPreferences[] = "preferences"; const char kPreferencesName[] = "name"; const char kPreferencesValue[] = "value"; const char kPreferencesReadonly[] = "readonly"; const char kStorageTableName[] = "widget_storage"; const char kCreateStorageTableOp[] = "CREATE TABLE widget_storage (" "key TEXT NOT NULL UNIQUE PRIMARY KEY," "value TEXT NOT NULL," "read_only INTEGER )"; const char kClearStorageTableWithBindOp[] = "DELETE FROM widget_storage WHERE read_only = ? "; const char kInsertItemWithBindOp[] = "INSERT INTO widget_storage (value, read_only, key) " "VALUES(?,?,?)"; const char kUpdateItemWithBindOp[] = "UPDATE widget_storage SET value = ? , read_only = ? " "WHERE key = ?"; const char kRemoveItemWithBindOp[] = "DELETE FROM widget_storage WHERE key = ?"; const char kSelectTableLength[] = "SELECT count(*) FROM widget_storage "; const char kSelectCountWithBindOp[] = "SELECT count(*) FROM widget_storage " "WHERE key = ?"; const char kSelectAllItem[] = "SELECT key, value FROM widget_storage "; const char kSelectReadOnlyWithBindOp[] = "SELECT read_only FROM widget_storage " "WHERE key = ?"; } // namespace namespace xwalk { namespace application { AppWidgetStorage::AppWidgetStorage(Application* application, const base::FilePath& data_dir) : application_(application), db_initialized_(false), data_path_(data_dir) { sqlite_db_.reset(new sql::Connection); if (!Init()) { LOG(ERROR) << "Initialize widget storage failed."; return; } } AppWidgetStorage::~AppWidgetStorage() { } bool AppWidgetStorage::Init() { if (!sqlite_db_->Open(data_path_)) { LOG(ERROR) << "Unable to open widget storage DB."; return false; } sqlite_db_->Preload(); if (!InitStorageTable()) { LOG(ERROR) << "Unable to init widget storage table."; return false; } return db_initialized_; } bool AppWidgetStorage::SaveConfigInfoItem(base::DictionaryValue* dict) { DCHECK(dict); std::string key; std::string value; bool read_only = false; dict->GetString(kPreferencesName, &key); dict->GetString(kPreferencesValue, &value); dict->GetBoolean(kPreferencesReadonly, &read_only); return AddEntry(key, value, read_only); } bool AppWidgetStorage::SaveConfigInfoInDB() { WidgetInfo* info = static_cast<WidgetInfo*>( application_->data()->GetManifestData(widget_keys::kWidgetKey)); base::DictionaryValue* widget_info = info->GetWidgetInfo(); if (!widget_info) { LOG(ERROR) << "Fail to get parsed widget information."; return false; } base::Value* pref_value = NULL; widget_info->Get(kPreferences, &pref_value); if (pref_value && pref_value->IsType(base::Value::TYPE_DICTIONARY)) { base::DictionaryValue* dict; pref_value->GetAsDictionary(&dict); return SaveConfigInfoItem(dict); } else if (pref_value && pref_value->IsType(base::Value::TYPE_LIST)) { base::ListValue* list; pref_value->GetAsList(&list); for (base::ListValue::iterator it = list->begin(); it != list->end(); ++it) { base::DictionaryValue* dict; (*it)->GetAsDictionary(&dict); if (!SaveConfigInfoItem(dict)) return false; } } else { LOG(INFO) << "No widget preferences or preference type is not supported."; } return true; } bool AppWidgetStorage::InitStorageTable() { if (sqlite_db_->DoesTableExist(kStorageTableName)) { db_initialized_ = (sqlite_db_ && sqlite_db_->is_open()); return true; } sql::Transaction transaction(sqlite_db_.get()); transaction.Begin(); if (!sqlite_db_->Execute(kCreateStorageTableOp)) return false; if (!transaction.Commit()) return false; db_initialized_ = (sqlite_db_ && sqlite_db_->is_open()); SaveConfigInfoInDB(); return true; } bool AppWidgetStorage::EntryExists(const std::string& key) const { sql::Transaction transaction(sqlite_db_.get()); if (!transaction.Begin()) return false; sql::Statement stmt(sqlite_db_->GetUniqueStatement( kSelectCountWithBindOp)); stmt.BindString(0, key); if (!stmt.Step()) { LOG(ERROR) << "An error occured when selecting count from DB."; return false; } if (!transaction.Commit()) return false; int exist = stmt.ColumnInt(0); return exist > 0; } bool AppWidgetStorage::IsReadOnly(const std::string& key) { sql::Transaction transaction(sqlite_db_.get()); if (!transaction.Begin()) return true; sql::Statement stmt(sqlite_db_->GetUniqueStatement( kSelectReadOnlyWithBindOp)); stmt.BindString(0, key); if (!stmt.Step()) { LOG(ERROR) << "An error occured when selecting count from DB."; return true; } if (!transaction.Commit()) return true; return stmt.ColumnBool(0); } bool AppWidgetStorage::AddEntry(const std::string& key, const std::string& value, bool read_only) { if (!db_initialized_ && !Init()) return false; std::string operation; if (!EntryExists(key)) { operation = kInsertItemWithBindOp; } else if (!IsReadOnly(key)) { operation = kUpdateItemWithBindOp; } else { LOG(ERROR) << "Could not set read only item " << key; return false; } sql::Transaction transaction(sqlite_db_.get()); if (!transaction.Begin()) return false; sql::Statement stmt(sqlite_db_->GetUniqueStatement( operation.c_str())); stmt.BindString(0, value); stmt.BindBool(1, read_only); stmt.BindString(2, key); if (!stmt.Run()) { LOG(ERROR) << "An error occured when set item into DB."; return false; } return transaction.Commit(); } bool AppWidgetStorage::RemoveEntry(const std::string& key) { if (!db_initialized_ && !Init()) return false; if (IsReadOnly(key)) { LOG(ERROR) << "Could not remove read only item " << key; return false; } sql::Transaction transaction(sqlite_db_.get()); if (!transaction.Begin()) return false; sql::Statement stmt(sqlite_db_->GetUniqueStatement( kRemoveItemWithBindOp)); stmt.BindString(0, key); if (!stmt.Run()) { LOG(ERROR) << "An error occured when removing item into DB."; return false; } return transaction.Commit(); } bool AppWidgetStorage::Clear() { if (!db_initialized_ && !Init()) return false; sql::Transaction transaction(sqlite_db_.get()); transaction.Begin(); sql::Statement stmt(sqlite_db_->GetUniqueStatement( kClearStorageTableWithBindOp)); stmt.BindBool(0, false); if (!stmt.Run()) { LOG(ERROR) << "An error occured when removing item into DB."; return false; } return transaction.Commit(); } bool AppWidgetStorage::GetAllEntries(base::DictionaryValue* result) { std::string key; std::string value; DCHECK(result); if (!db_initialized_ && !Init()) return false; sql::Statement stmt(sqlite_db_->GetUniqueStatement(kSelectAllItem)); while (stmt.Step()) { key = stmt.ColumnString(0); value = stmt.ColumnString(1); result->SetString(key, value); } return true; } } // namespace application } // namespace xwalk <commit_msg>[Application] application_widget_storage: Add the check for return value.<commit_after>// Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/application/extension/application_widget_storage.h" #include <string> #include "base/file_util.h" #include "base/strings/utf_string_conversions.h" #include "sql/statement.h" #include "sql/transaction.h" #include "xwalk/application/common/application_manifest_constants.h" #include "xwalk/application/common/manifest_handlers/widget_handler.h" namespace { namespace widget_keys = xwalk::application_widget_keys; const char kPreferences[] = "preferences"; const char kPreferencesName[] = "name"; const char kPreferencesValue[] = "value"; const char kPreferencesReadonly[] = "readonly"; const char kStorageTableName[] = "widget_storage"; const char kCreateStorageTableOp[] = "CREATE TABLE widget_storage (" "key TEXT NOT NULL UNIQUE PRIMARY KEY," "value TEXT NOT NULL," "read_only INTEGER )"; const char kClearStorageTableWithBindOp[] = "DELETE FROM widget_storage WHERE read_only = ? "; const char kInsertItemWithBindOp[] = "INSERT INTO widget_storage (value, read_only, key) " "VALUES(?,?,?)"; const char kUpdateItemWithBindOp[] = "UPDATE widget_storage SET value = ? , read_only = ? " "WHERE key = ?"; const char kRemoveItemWithBindOp[] = "DELETE FROM widget_storage WHERE key = ?"; const char kSelectTableLength[] = "SELECT count(*) FROM widget_storage "; const char kSelectCountWithBindOp[] = "SELECT count(*) FROM widget_storage " "WHERE key = ?"; const char kSelectAllItem[] = "SELECT key, value FROM widget_storage "; const char kSelectReadOnlyWithBindOp[] = "SELECT read_only FROM widget_storage " "WHERE key = ?"; } // namespace namespace xwalk { namespace application { AppWidgetStorage::AppWidgetStorage(Application* application, const base::FilePath& data_dir) : application_(application), db_initialized_(false), data_path_(data_dir) { sqlite_db_.reset(new sql::Connection); if (!Init()) { LOG(ERROR) << "Initialize widget storage failed."; return; } } AppWidgetStorage::~AppWidgetStorage() { } bool AppWidgetStorage::Init() { if (!sqlite_db_->Open(data_path_)) { LOG(ERROR) << "Unable to open widget storage DB."; return false; } sqlite_db_->Preload(); if (!InitStorageTable()) { LOG(ERROR) << "Unable to init widget storage table."; return false; } return db_initialized_; } bool AppWidgetStorage::SaveConfigInfoItem(base::DictionaryValue* dict) { DCHECK(dict); std::string key; std::string value; bool read_only = false; if (dict->GetString(kPreferencesName, &key) && dict->GetString(kPreferencesValue, &value) && dict->GetBoolean(kPreferencesReadonly, &read_only)) return AddEntry(key, value, read_only); return false; } bool AppWidgetStorage::SaveConfigInfoInDB() { WidgetInfo* info = static_cast<WidgetInfo*>( application_->data()->GetManifestData(widget_keys::kWidgetKey)); base::DictionaryValue* widget_info = info->GetWidgetInfo(); if (!widget_info) { LOG(ERROR) << "Fail to get parsed widget information."; return false; } base::Value* pref_value = NULL; widget_info->Get(kPreferences, &pref_value); if (pref_value && pref_value->IsType(base::Value::TYPE_DICTIONARY)) { base::DictionaryValue* dict; pref_value->GetAsDictionary(&dict); return SaveConfigInfoItem(dict); } else if (pref_value && pref_value->IsType(base::Value::TYPE_LIST)) { base::ListValue* list; pref_value->GetAsList(&list); for (base::ListValue::iterator it = list->begin(); it != list->end(); ++it) { base::DictionaryValue* dict; (*it)->GetAsDictionary(&dict); if (!SaveConfigInfoItem(dict)) return false; } } else { LOG(INFO) << "No widget preferences or preference type is not supported."; } return true; } bool AppWidgetStorage::InitStorageTable() { if (sqlite_db_->DoesTableExist(kStorageTableName)) { db_initialized_ = (sqlite_db_ && sqlite_db_->is_open()); return true; } sql::Transaction transaction(sqlite_db_.get()); transaction.Begin(); if (!sqlite_db_->Execute(kCreateStorageTableOp)) return false; if (!transaction.Commit()) return false; db_initialized_ = (sqlite_db_ && sqlite_db_->is_open()); SaveConfigInfoInDB(); return true; } bool AppWidgetStorage::EntryExists(const std::string& key) const { sql::Transaction transaction(sqlite_db_.get()); if (!transaction.Begin()) return false; sql::Statement stmt(sqlite_db_->GetUniqueStatement( kSelectCountWithBindOp)); stmt.BindString(0, key); if (!stmt.Step()) { LOG(ERROR) << "An error occured when selecting count from DB."; return false; } if (!transaction.Commit()) return false; int exist = stmt.ColumnInt(0); return exist > 0; } bool AppWidgetStorage::IsReadOnly(const std::string& key) { sql::Transaction transaction(sqlite_db_.get()); if (!transaction.Begin()) return true; sql::Statement stmt(sqlite_db_->GetUniqueStatement( kSelectReadOnlyWithBindOp)); stmt.BindString(0, key); if (!stmt.Step()) { LOG(ERROR) << "An error occured when selecting count from DB."; return true; } if (!transaction.Commit()) return true; return stmt.ColumnBool(0); } bool AppWidgetStorage::AddEntry(const std::string& key, const std::string& value, bool read_only) { if (!db_initialized_ && !Init()) return false; std::string operation; if (!EntryExists(key)) { operation = kInsertItemWithBindOp; } else if (!IsReadOnly(key)) { operation = kUpdateItemWithBindOp; } else { LOG(ERROR) << "Could not set read only item " << key; return false; } sql::Transaction transaction(sqlite_db_.get()); if (!transaction.Begin()) return false; sql::Statement stmt(sqlite_db_->GetUniqueStatement( operation.c_str())); stmt.BindString(0, value); stmt.BindBool(1, read_only); stmt.BindString(2, key); if (!stmt.Run()) { LOG(ERROR) << "An error occured when set item into DB."; return false; } return transaction.Commit(); } bool AppWidgetStorage::RemoveEntry(const std::string& key) { if (!db_initialized_ && !Init()) return false; if (IsReadOnly(key)) { LOG(ERROR) << "Could not remove read only item " << key; return false; } sql::Transaction transaction(sqlite_db_.get()); if (!transaction.Begin()) return false; sql::Statement stmt(sqlite_db_->GetUniqueStatement( kRemoveItemWithBindOp)); stmt.BindString(0, key); if (!stmt.Run()) { LOG(ERROR) << "An error occured when removing item into DB."; return false; } return transaction.Commit(); } bool AppWidgetStorage::Clear() { if (!db_initialized_ && !Init()) return false; sql::Transaction transaction(sqlite_db_.get()); transaction.Begin(); sql::Statement stmt(sqlite_db_->GetUniqueStatement( kClearStorageTableWithBindOp)); stmt.BindBool(0, false); if (!stmt.Run()) { LOG(ERROR) << "An error occured when removing item into DB."; return false; } return transaction.Commit(); } bool AppWidgetStorage::GetAllEntries(base::DictionaryValue* result) { std::string key; std::string value; DCHECK(result); if (!db_initialized_ && !Init()) return false; sql::Statement stmt(sqlite_db_->GetUniqueStatement(kSelectAllItem)); while (stmt.Step()) { key = stmt.ColumnString(0); value = stmt.ColumnString(1); result->SetString(key, value); } return true; } } // namespace application } // namespace xwalk <|endoftext|>
<commit_before>// ThreadedAudioDevice.cpp // // Base class for all classes which spawn thread to run loop. // #include "ThreadedAudioDevice.h" #include <sys/time.h> #include <sys/resource.h> // setpriority() #include <sys/select.h> #include <string.h> // memset() #include <stdio.h> #include <assert.h> #include <errno.h> ThreadedAudioDevice::ThreadedAudioDevice() : _device(-1), _thread(0), _frameCount(0), _paused(false), _stopping(false), _closing(false) { } int ThreadedAudioDevice::startThread() { stopping(false); // Reset. if (isPassive()) // Nothing else to do here if passive mode. return 0; // printf("\tThreadedAudioDevice::startThread: starting thread\n"); int status = pthread_create(&_thread, NULL, _runProcess, this); if (status < 0) { error("Failed to create thread"); } return status; } int ThreadedAudioDevice::doStop() { if (!stopping()) { // printf("\tThreadedAudioDevice::doStop\n"); stopping(true); // signals play thread paused(false); waitForThread(); } return 0; } int ThreadedAudioDevice::doGetFrameCount() const { return frameCount(); } // Local method definitions void ThreadedAudioDevice::waitForThread(int waitMs) { if (!isPassive()) { assert(_thread != 0); // should not get called again! // printf("ThreadedAudioDevice::waitForThread: waiting for thread to finish\n"); if (pthread_join(_thread, NULL) == -1) { // printf("ThreadedAudioDevice::doStop: terminating thread!\n"); pthread_cancel(_thread); _thread = 0; } // printf("\tThreadedAudioDevice::waitForThread: thread done\n"); } } inline void ThreadedAudioDevice::setFDSet() { fd_set *thisSet = NULL; #ifdef PREFER_SELECT_ON_WRITE if (isRecording() && !isPlaying()) // Use read fd_set for half-duplex record only. thisSet = &_rfdset; else if (isPlaying()) // Use write fd_set for full-duplex and half-duplex play. thisSet = &_wfdset; #else if (isRecording()) // Use read fd_set for for full-duplex and half-duplex record. thisSet = &_rfdset; else if (isPlaying() && !isRecording()) // Use write fd_set for half-duplex play only. thisSet = &_wfdset; #endif FD_SET(_device, thisSet); } void ThreadedAudioDevice::setDevice(int dev) { _device = dev; if (_device > 0) { FD_ZERO(&_rfdset); FD_ZERO(&_wfdset); setFDSet(); } } bool ThreadedAudioDevice::waitForDevice(unsigned int wTime) { bool ret = false; unsigned waitSecs = int(wTime / 1000.0); unsigned waitUsecs = (wTime * 1000) - unsigned(waitSecs * 1.0e+06); // Wait wTime msecs for select to return, then bail. if (!stopping()) { int nfds = _device + 1; struct timeval tv; tv.tv_sec = waitSecs; tv.tv_usec = waitUsecs; // If wTime == 0, wait forever by passing NULL as the final arg. // if (!isPlaying()) // printf("select(%d, 0x%x, 0x%x, NULL, 0x%x)...\n", // nfds, &_rfdset, &_wfdset, wTime == 0 ? NULL : &tv); int selret = ::select(nfds, &_rfdset, &_wfdset, NULL, wTime == 0 ? NULL : &tv); if (selret <= 0) { if (errno != EINTR) fprintf(stderr, "ThreadedAudioDevice::waitForDevice: select %s\n", (selret == 0) ? "timed out" : "returned error"); ret = false; } else { setFDSet(); ret = true; } } else { // printf("ThreadedAudioDevice::waitForDevice: stopping == true\n"); } return ret; } void *ThreadedAudioDevice::_runProcess(void *context) { ThreadedAudioDevice *device = (ThreadedAudioDevice *) context; pthread_attr_t attr; pthread_attr_init(&attr); int status = pthread_attr_setschedpolicy(&attr, SCHED_RR); pthread_attr_destroy(&attr); if (status != 0) { device->error("Failed to set scheduling policy of thread"); return NULL; } if (setpriority(PRIO_PROCESS, 0, -20) != 0) { // perror("ThreadedAudioDevice::startThread: Failed to set priority of thread."); } device->run(); return NULL; } <commit_msg>Added profiling support, off by default.<commit_after>// ThreadedAudioDevice.cpp // // Base class for all classes which spawn thread to run loop. // #include "ThreadedAudioDevice.h" #include <sys/time.h> #include <sys/resource.h> // setpriority() #include <sys/select.h> #include <string.h> // memset() #include <stdio.h> #include <assert.h> #include <errno.h> // Uncomment this to make it possible to profile RTcmix code w/ gprof //#define PROFILE #ifdef PROFILE static struct itimerval globalTimerVal; #endif ThreadedAudioDevice::ThreadedAudioDevice() : _device(-1), _thread(0), _frameCount(0), _paused(false), _stopping(false), _closing(false) { } int ThreadedAudioDevice::startThread() { stopping(false); // Reset. if (isPassive()) // Nothing else to do here if passive mode. return 0; #ifdef PROFILE getitimer(ITIMER_PROF, &globalTimerVal); #endif // printf("\tThreadedAudioDevice::startThread: starting thread\n"); int status = pthread_create(&_thread, NULL, _runProcess, this); if (status < 0) { error("Failed to create thread"); } return status; } int ThreadedAudioDevice::doStop() { if (!stopping()) { // printf("\tThreadedAudioDevice::doStop\n"); stopping(true); // signals play thread paused(false); waitForThread(); } return 0; } int ThreadedAudioDevice::doGetFrameCount() const { return frameCount(); } // Local method definitions void ThreadedAudioDevice::waitForThread(int waitMs) { if (!isPassive()) { assert(_thread != 0); // should not get called again! // printf("ThreadedAudioDevice::waitForThread: waiting for thread to finish\n"); if (pthread_join(_thread, NULL) == -1) { // printf("ThreadedAudioDevice::doStop: terminating thread!\n"); pthread_cancel(_thread); _thread = 0; } // printf("\tThreadedAudioDevice::waitForThread: thread done\n"); } } inline void ThreadedAudioDevice::setFDSet() { fd_set *thisSet = NULL; #ifdef PREFER_SELECT_ON_WRITE if (isRecording() && !isPlaying()) // Use read fd_set for half-duplex record only. thisSet = &_rfdset; else if (isPlaying()) // Use write fd_set for full-duplex and half-duplex play. thisSet = &_wfdset; #else if (isRecording()) // Use read fd_set for for full-duplex and half-duplex record. thisSet = &_rfdset; else if (isPlaying() && !isRecording()) // Use write fd_set for half-duplex play only. thisSet = &_wfdset; #endif FD_SET(_device, thisSet); } void ThreadedAudioDevice::setDevice(int dev) { _device = dev; if (_device > 0) { FD_ZERO(&_rfdset); FD_ZERO(&_wfdset); setFDSet(); } } bool ThreadedAudioDevice::waitForDevice(unsigned int wTime) { bool ret = false; unsigned waitSecs = int(wTime / 1000.0); unsigned waitUsecs = (wTime * 1000) - unsigned(waitSecs * 1.0e+06); // Wait wTime msecs for select to return, then bail. if (!stopping()) { int nfds = _device + 1; struct timeval tv; tv.tv_sec = waitSecs; tv.tv_usec = waitUsecs; // If wTime == 0, wait forever by passing NULL as the final arg. // if (!isPlaying()) // printf("select(%d, 0x%x, 0x%x, NULL, 0x%x)...\n", // nfds, &_rfdset, &_wfdset, wTime == 0 ? NULL : &tv); int selret = ::select(nfds, &_rfdset, &_wfdset, NULL, wTime == 0 ? NULL : &tv); if (selret <= 0) { if (errno != EINTR) fprintf(stderr, "ThreadedAudioDevice::waitForDevice: select %s\n", (selret == 0) ? "timed out" : "returned error"); ret = false; } else { setFDSet(); ret = true; } } else { // printf("ThreadedAudioDevice::waitForDevice: stopping == true\n"); } return ret; } void *ThreadedAudioDevice::_runProcess(void *context) { #ifdef PROFILE setitimer(ITIMER_PROF, &globalTimerVal, NULL); getitimer(ITIMER_PROF, &globalTimerVal); #endif ThreadedAudioDevice *device = (ThreadedAudioDevice *) context; pthread_attr_t attr; pthread_attr_init(&attr); int status = pthread_attr_setschedpolicy(&attr, SCHED_RR); pthread_attr_destroy(&attr); if (status != 0) { device->error("Failed to set scheduling policy of thread"); return NULL; } if (setpriority(PRIO_PROCESS, 0, -20) != 0) { // perror("ThreadedAudioDevice::startThread: Failed to set priority of thread."); } device->run(); return NULL; } <|endoftext|>
<commit_before>/* * File: main_voctreeLocalizer.cpp * Author: sgaspari * * Created on September 12, 2015, 3:16 PM */ #include <openMVG/localization/VoctreeLocalizer.hpp> #include <openMVG/localization/CCTagLocalizer.hpp> #include <openMVG/localization/optimization.hpp> #include <openMVG/sfm/pipelines/localization/SfM_Localizer.hpp> #include <openMVG/image/image_io.hpp> #include <openMVG/dataio/FeedProvider.hpp> #include <openMVG/localization/LocalizationResult.hpp> #include <boost/filesystem.hpp> #include <boost/progress.hpp> #include <boost/program_options.hpp> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/mean.hpp> #include <boost/accumulators/statistics/min.hpp> #include <boost/accumulators/statistics/max.hpp> #include <boost/accumulators/statistics/sum.hpp> #include <iostream> #include <string> #include <chrono> #if HAVE_ALEMBIC #include <openMVG/dataio/AlembicExporter.hpp> #endif // HAVE_ALEMBIC #define POPART_COUT(x) std::cout << x << std::endl #define POPART_CERR(x) std::cerr << x << std::endl namespace bfs = boost::filesystem; namespace bacc = boost::accumulators; namespace po = boost::program_options; using namespace openMVG; std::string myToString(std::size_t i, std::size_t zeroPadding) { std::stringstream ss; ss << std::setw(zeroPadding) << std::setfill('0') << i; return ss.str(); } int main(int argc, char** argv) { std::string calibFile; //< the calibration file std::string sfmFilePath; //< the OpenMVG .json data file std::string descriptorsFolder; //< the OpenMVG .json data file std::string mediaFilepath; //< the media file to localize localization::CCTagLocalizer::Parameters param = localization::CCTagLocalizer::Parameters(); std::string preset = features::describerPreset_enumToString(param._featurePreset); //< the preset for the feature extractor #if HAVE_ALEMBIC std::string exportFile = "trackedcameras.abc"; //!< the export file #endif bool globalBundle = false; //< If !param._refineIntrinsics it can run a final global budndle to refine the scene po::options_description desc( "This program takes as input a media (image, image sequence, video) and a database (voctree, 3D structure data) \n" "and returns for each frame a pose estimation for the camera."); desc.add_options() ("help,h", "Print this message") ("results,r", po::value<size_t>(&param._nNearestKeyFrames)->default_value(param._nNearestKeyFrames), "Number of images to retrieve in database") ("preset", po::value<std::string>(&preset)->default_value(preset), "Preset for the feature extractor when localizing a new image {LOW,NORMAL,HIGH,ULTRA}") ("calibration,c", po::value<std::string>(&calibFile)/*->required( )*/, "Calibration file") ("sfmdata,d", po::value<std::string>(&sfmFilePath)->required(), "The sfm_data.json kind of file generated by OpenMVG [it could be also a bundle.out to use an older version of OpenMVG]") ("siftPath,s", po::value<std::string>(&descriptorsFolder), "Folder containing the .desc. If not provided, it will be assumed to be parent(sfmdata)/matches [for the older version of openMVG it is the list.txt]") ("mediafile,m", po::value<std::string>(&mediaFilepath)->required(), "The folder path or the filename for the media to track") ("refineIntrinsics", po::bool_switch(&param._refineIntrinsics), "Enable/Disable camera intrinsics refinement for each localized image") ("globalBundle", po::bool_switch(&globalBundle), "If --refineIntrinsics is not set, this option allows to run a final global budndle adjustment to refine the scene") ("visualDebug", po::value<std::string>(&param._visualDebug), "If a directory is provided it enables visual debug and saves all the debugging info in that directory") #if HAVE_ALEMBIC ("export,e", po::value<std::string>(&exportFile)->default_value(exportFile), "Filename for the SfM_Data export file (where camera poses will be stored). Default : trackedcameras.json If Alambic is enable it will also export an .abc file of the scene with the same name") #endif ; po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); if(vm.count("help") || (argc == 1)) { POPART_COUT(desc); return EXIT_SUCCESS; } po::notify(vm); } catch(boost::program_options::required_option& e) { POPART_CERR("ERROR: " << e.what() << std::endl); POPART_COUT("Usage:\n\n" << desc); return EXIT_FAILURE; } catch(boost::program_options::error& e) { POPART_CERR("ERROR: " << e.what() << std::endl); POPART_COUT("Usage:\n\n" << desc); return EXIT_FAILURE; } if(vm.count("preset")) { param._featurePreset = features::describerPreset_stringToEnum(preset); } { // the bundle adjustment can be run for now only if the refine intrinsics option is not set globalBundle = (globalBundle && !param._refineIntrinsics); POPART_COUT("Program called with the following parameters:"); POPART_COUT("\tcalibration: " << calibFile); POPART_COUT("\tsfmdata: " << sfmFilePath); POPART_COUT("\tmediafile: " << mediaFilepath); POPART_COUT("\tsiftPath: " << descriptorsFolder); POPART_COUT("\tresults: " << param._nNearestKeyFrames); POPART_COUT("\trefineIntrinsics: " << param._refineIntrinsics); POPART_COUT("\tpreset: " << features::describerPreset_enumToString(param._featurePreset)); POPART_COUT("\tglobalBundle: " << globalBundle); POPART_COUT("\tvisual debug: " << param._visualDebug); } if(!param._visualDebug.empty() && !bfs::exists(param._visualDebug)) { bfs::create_directories(param._visualDebug); } // init the localizer localization::CCTagLocalizer localizer(sfmFilePath, descriptorsFolder); if(!localizer.isInit()) { POPART_CERR("ERROR while initializing the localizer!"); return EXIT_FAILURE; } // create the feedProvider dataio::FeedProvider feed(mediaFilepath, calibFile); if(!feed.isInit()) { POPART_CERR("ERROR while initializing the FeedProvider!"); return EXIT_FAILURE; } bool feedIsVideo = feed.isVideo(); #if HAVE_ALEMBIC dataio::AlembicExporter exporter(exportFile); exporter.addPoints(localizer.getSfMData().GetLandmarks()); #endif image::Image<unsigned char> imageGrey; cameras::Pinhole_Intrinsic_Radial_K3 queryIntrinsics; bool hasIntrinsics = false; size_t frameCounter = 0; size_t goodFrameCounter = 0; vector<string> goodFrameList; std::string currentImgName; // Define an accumulator set for computing the mean and the // standard deviation of the time taken for localization bacc::accumulator_set<double, bacc::stats<bacc::tag::mean, bacc::tag::min, bacc::tag::max, bacc::tag::sum > > stats; std::vector<localization::LocalizationResult> vec_localizationResults; while(feed.next(imageGrey, queryIntrinsics, currentImgName, hasIntrinsics)) { POPART_COUT("******************************"); POPART_COUT("FRAME " << myToString(frameCounter, 4)); POPART_COUT("******************************"); auto detect_start = std::chrono::steady_clock::now(); localization::LocalizationResult localizationResult; localizer.localize(imageGrey, &param, hasIntrinsics/*useInputIntrinsics*/, queryIntrinsics, // todo: put as const and use the intrinsic result store in localizationResult afterward localizationResult, (feedIsVideo) ? "" : currentImgName); auto detect_end = std::chrono::steady_clock::now(); auto detect_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(detect_end - detect_start); POPART_COUT("\nLocalization took " << detect_elapsed.count() << " [ms]"); stats(detect_elapsed.count()); // save data if(localizationResult.isValid()) { #if HAVE_ALEMBIC exporter.appendCamera("camera." + myToString(frameCounter, 4), localizationResult.getPose(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); #endif goodFrameCounter++; goodFrameList.push_back(currentImgName + " : " + std::to_string(localizationResult.getIndMatch3D2D().size()) ); if(globalBundle) { vec_localizationResults.emplace_back(localizationResult); } } else { #if HAVE_ALEMBIC // @fixme for now just add a fake camera so that it still can be see in MAYA exporter.appendCamera("camera.V." + myToString(frameCounter, 4), geometry::Pose3(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); #endif POPART_CERR("Unable to localize frame " << frameCounter); } ++frameCounter; } if(globalBundle) { // run a bundle adjustment const bool BAresult = localization::refineSequence(&queryIntrinsics, vec_localizationResults); if(!BAresult) { POPART_CERR("Bundle Adjustment failed!"); } else { #if HAVE_ALEMBIC // now copy back in a new abc with the same name file and BUNDLE appended at the end dataio::AlembicExporter exporterBA(bfs::path(exportFile).stem().string() + ".BUNDLE.abc"); size_t idx = 0; for(const localization::LocalizationResult &res : vec_localizationResults) { if(res.isValid()) { assert(idx < vec_localizationResults.size()); exporterBA.appendCamera("camera." + myToString(idx, 4), res.getPose(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); } else { exporterBA.appendCamera("camera.V." + myToString(idx, 4), geometry::Pose3(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); } idx++; } exporterBA.addPoints(localizer.getSfMData().GetLandmarks()); #endif } } // print out some time stats POPART_COUT("\n\n******************************"); POPART_COUT("Localized " << goodFrameCounter << "/" << frameCounter << " images"); POPART_COUT("Images localized with the number of 2D/3D matches during localization :"); for(int i = 0; i < goodFrameList.size(); i++) POPART_COUT(goodFrameList[i]); POPART_COUT("Processing took " << bacc::sum(stats)/1000 << " [s] overall"); POPART_COUT("Mean time for localization: " << bacc::mean(stats) << " [ms]"); POPART_COUT("Max time for localization: " << bacc::max(stats) << " [ms]"); POPART_COUT("Min time for localization: " << bacc::min(stats) << " [ms]"); } <commit_msg>[localization] CCTag localizer now export animated camera<commit_after>/* * File: main_voctreeLocalizer.cpp * Author: sgaspari * * Created on September 12, 2015, 3:16 PM */ #include <openMVG/localization/VoctreeLocalizer.hpp> #include <openMVG/localization/CCTagLocalizer.hpp> #include <openMVG/localization/optimization.hpp> #include <openMVG/sfm/pipelines/localization/SfM_Localizer.hpp> #include <openMVG/image/image_io.hpp> #include <openMVG/dataio/FeedProvider.hpp> #include <openMVG/localization/LocalizationResult.hpp> #include <boost/filesystem.hpp> #include <boost/progress.hpp> #include <boost/program_options.hpp> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/mean.hpp> #include <boost/accumulators/statistics/min.hpp> #include <boost/accumulators/statistics/max.hpp> #include <boost/accumulators/statistics/sum.hpp> #include <iostream> #include <string> #include <chrono> #if HAVE_ALEMBIC #include <openMVG/dataio/AlembicExporter.hpp> #endif // HAVE_ALEMBIC #define POPART_COUT(x) std::cout << x << std::endl #define POPART_CERR(x) std::cerr << x << std::endl namespace bfs = boost::filesystem; namespace bacc = boost::accumulators; namespace po = boost::program_options; using namespace openMVG; std::string myToString(std::size_t i, std::size_t zeroPadding) { std::stringstream ss; ss << std::setw(zeroPadding) << std::setfill('0') << i; return ss.str(); } int main(int argc, char** argv) { std::string calibFile; //< the calibration file std::string sfmFilePath; //< the OpenMVG .json data file std::string descriptorsFolder; //< the OpenMVG .json data file std::string mediaFilepath; //< the media file to localize localization::CCTagLocalizer::Parameters param = localization::CCTagLocalizer::Parameters(); std::string preset = features::describerPreset_enumToString(param._featurePreset); //< the preset for the feature extractor #if HAVE_ALEMBIC std::string exportFile = "trackedcameras.abc"; //!< the export file #endif bool globalBundle = false; //< If !param._refineIntrinsics it can run a final global budndle to refine the scene po::options_description desc( "This program takes as input a media (image, image sequence, video) and a database (voctree, 3D structure data) \n" "and returns for each frame a pose estimation for the camera."); desc.add_options() ("help,h", "Print this message") ("results,r", po::value<size_t>(&param._nNearestKeyFrames)->default_value(param._nNearestKeyFrames), "Number of images to retrieve in database") ("preset", po::value<std::string>(&preset)->default_value(preset), "Preset for the feature extractor when localizing a new image {LOW,NORMAL,HIGH,ULTRA}") ("calibration,c", po::value<std::string>(&calibFile)/*->required( )*/, "Calibration file") ("sfmdata,d", po::value<std::string>(&sfmFilePath)->required(), "The sfm_data.json kind of file generated by OpenMVG [it could be also a bundle.out to use an older version of OpenMVG]") ("siftPath,s", po::value<std::string>(&descriptorsFolder), "Folder containing the .desc. If not provided, it will be assumed to be parent(sfmdata)/matches [for the older version of openMVG it is the list.txt]") ("mediafile,m", po::value<std::string>(&mediaFilepath)->required(), "The folder path or the filename for the media to track") ("refineIntrinsics", po::bool_switch(&param._refineIntrinsics), "Enable/Disable camera intrinsics refinement for each localized image") ("globalBundle", po::bool_switch(&globalBundle), "If --refineIntrinsics is not set, this option allows to run a final global budndle adjustment to refine the scene") ("visualDebug", po::value<std::string>(&param._visualDebug), "If a directory is provided it enables visual debug and saves all the debugging info in that directory") #if HAVE_ALEMBIC ("export,e", po::value<std::string>(&exportFile)->default_value(exportFile), "Filename for the SfM_Data export file (where camera poses will be stored). Default : trackedcameras.json If Alambic is enable it will also export an .abc file of the scene with the same name") #endif ; po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); if(vm.count("help") || (argc == 1)) { POPART_COUT(desc); return EXIT_SUCCESS; } po::notify(vm); } catch(boost::program_options::required_option& e) { POPART_CERR("ERROR: " << e.what() << std::endl); POPART_COUT("Usage:\n\n" << desc); return EXIT_FAILURE; } catch(boost::program_options::error& e) { POPART_CERR("ERROR: " << e.what() << std::endl); POPART_COUT("Usage:\n\n" << desc); return EXIT_FAILURE; } if(vm.count("preset")) { param._featurePreset = features::describerPreset_stringToEnum(preset); } { // the bundle adjustment can be run for now only if the refine intrinsics option is not set globalBundle = (globalBundle && !param._refineIntrinsics); POPART_COUT("Program called with the following parameters:"); POPART_COUT("\tcalibration: " << calibFile); POPART_COUT("\tsfmdata: " << sfmFilePath); POPART_COUT("\tmediafile: " << mediaFilepath); POPART_COUT("\tsiftPath: " << descriptorsFolder); POPART_COUT("\tresults: " << param._nNearestKeyFrames); POPART_COUT("\trefineIntrinsics: " << param._refineIntrinsics); POPART_COUT("\tpreset: " << features::describerPreset_enumToString(param._featurePreset)); POPART_COUT("\tglobalBundle: " << globalBundle); POPART_COUT("\tvisual debug: " << param._visualDebug); } if(!param._visualDebug.empty() && !bfs::exists(param._visualDebug)) { bfs::create_directories(param._visualDebug); } // init the localizer localization::CCTagLocalizer localizer(sfmFilePath, descriptorsFolder); if(!localizer.isInit()) { POPART_CERR("ERROR while initializing the localizer!"); return EXIT_FAILURE; } // create the feedProvider dataio::FeedProvider feed(mediaFilepath, calibFile); if(!feed.isInit()) { POPART_CERR("ERROR while initializing the FeedProvider!"); return EXIT_FAILURE; } bool feedIsVideo = feed.isVideo(); #if HAVE_ALEMBIC dataio::AlembicExporter exporter(exportFile); exporter.addPoints(localizer.getSfMData().GetLandmarks()); exporter.initAnimatedCamera("camera"); #endif image::Image<unsigned char> imageGrey; cameras::Pinhole_Intrinsic_Radial_K3 queryIntrinsics; bool hasIntrinsics = false; size_t frameCounter = 0; size_t goodFrameCounter = 0; vector<string> goodFrameList; std::string currentImgName; // Define an accumulator set for computing the mean and the // standard deviation of the time taken for localization bacc::accumulator_set<double, bacc::stats<bacc::tag::mean, bacc::tag::min, bacc::tag::max, bacc::tag::sum > > stats; std::vector<localization::LocalizationResult> vec_localizationResults; while(feed.next(imageGrey, queryIntrinsics, currentImgName, hasIntrinsics)) { POPART_COUT("******************************"); POPART_COUT("FRAME " << myToString(frameCounter, 4)); POPART_COUT("******************************"); auto detect_start = std::chrono::steady_clock::now(); localization::LocalizationResult localizationResult; localizer.localize(imageGrey, &param, hasIntrinsics/*useInputIntrinsics*/, queryIntrinsics, // todo: put as const and use the intrinsic result store in localizationResult afterward localizationResult, (feedIsVideo) ? "" : currentImgName); auto detect_end = std::chrono::steady_clock::now(); auto detect_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(detect_end - detect_start); POPART_COUT("\nLocalization took " << detect_elapsed.count() << " [ms]"); stats(detect_elapsed.count()); // save data if(localizationResult.isValid()) { #if HAVE_ALEMBIC //exporter.appendCamera("camera." + myToString(frameCounter, 4), localizationResult.getPose(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); exporter.addCameraKeyframe(localizationResult.getPose(), &queryIntrinsics, currentImgName, frameCounter, frameCounter); #endif goodFrameCounter++; goodFrameList.push_back(currentImgName + " : " + std::to_string(localizationResult.getIndMatch3D2D().size()) ); if(globalBundle) { vec_localizationResults.emplace_back(localizationResult); } } else { #if HAVE_ALEMBIC // @fixme for now just add a fake camera so that it still can be see in MAYA //exporter.appendCamera("camera.V." + myToString(frameCounter, 4), geometry::Pose3(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); std::cout << "frameCounter = " << frameCounter << std::endl; exporter.addCameraKeyframe(geometry::Pose3(), &queryIntrinsics, currentImgName, frameCounter, frameCounter); #endif POPART_CERR("Unable to localize frame " << frameCounter); } ++frameCounter; } if(globalBundle) { // run a bundle adjustment const bool BAresult = localization::refineSequence(&queryIntrinsics, vec_localizationResults); if(!BAresult) { POPART_CERR("Bundle Adjustment failed!"); } else { #if HAVE_ALEMBIC // now copy back in a new abc with the same name file and BUNDLE appended at the end dataio::AlembicExporter exporterBA(bfs::path(exportFile).stem().string() + ".BUNDLE.abc"); size_t idx = 0; for(const localization::LocalizationResult &res : vec_localizationResults) { if(res.isValid()) { assert(idx < vec_localizationResults.size()); exporterBA.appendCamera("camera." + myToString(idx, 4), res.getPose(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); } else { exporterBA.appendCamera("camera.V." + myToString(idx, 4), geometry::Pose3(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); } idx++; } exporterBA.addPoints(localizer.getSfMData().GetLandmarks()); #endif } } // print out some time stats POPART_COUT("\n\n******************************"); POPART_COUT("Localized " << goodFrameCounter << "/" << frameCounter << " images"); POPART_COUT("Images localized with the number of 2D/3D matches during localization :"); for(int i = 0; i < goodFrameList.size(); i++) POPART_COUT(goodFrameList[i]); POPART_COUT("Processing took " << bacc::sum(stats)/1000 << " [s] overall"); POPART_COUT("Mean time for localization: " << bacc::mean(stats) << " [ms]"); POPART_COUT("Max time for localization: " << bacc::max(stats) << " [ms]"); POPART_COUT("Min time for localization: " << bacc::min(stats) << " [ms]"); } <|endoftext|>
<commit_before>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Cards/Cards.hpp> #include <Rosetta/Games/Game.hpp> #include <Rosetta/Models/Enchantment.hpp> #include <Rosetta/Tasks/SimpleTasks/AddEnchantmentTask.hpp> #include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp> namespace RosettaStone::SimpleTasks { AddEnchantmentTask::AddEnchantmentTask(std::string&& cardID, EntityType entityType) : ITask(entityType), m_cardID(cardID) { // Do nothing } TaskID AddEnchantmentTask::GetTaskID() const { return TaskID::ADD_ENCHANTMENT; } TaskStatus AddEnchantmentTask::Impl(Player& player) { Card enchantmentCard = Cards::FindCardByID(m_cardID); if (enchantmentCard.id.empty()) { return TaskStatus::STOP; } auto entities = IncludeTask::GetEntities(m_entityType, player, m_source, m_target); Power power = Cards::FindCardByID(m_cardID).power; for (auto& entity : entities) { const auto enchantment = Enchantment::GetInstance(player, enchantmentCard, entity); if (power.GetAura().has_value()) { power.GetAura().value().Activate(*enchantment); } if (power.GetTrigger().has_value()) { power.GetTrigger().value().Activate(*enchantment); } if (power.GetEnchant().has_value()) { const auto& taskStack = player.GetGame()->taskStack; power.GetEnchant().value().ActivateTo(entity, taskStack.num, taskStack.num1); } } return TaskStatus::COMPLETE; } } // namespace RosettaStone::SimpleTasks <commit_msg>refactor: Change 'Cards::FindCardByID(m_cardID)' to 'enchantmentCard'<commit_after>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Cards/Cards.hpp> #include <Rosetta/Games/Game.hpp> #include <Rosetta/Models/Enchantment.hpp> #include <Rosetta/Tasks/SimpleTasks/AddEnchantmentTask.hpp> #include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp> namespace RosettaStone::SimpleTasks { AddEnchantmentTask::AddEnchantmentTask(std::string&& cardID, EntityType entityType) : ITask(entityType), m_cardID(cardID) { // Do nothing } TaskID AddEnchantmentTask::GetTaskID() const { return TaskID::ADD_ENCHANTMENT; } TaskStatus AddEnchantmentTask::Impl(Player& player) { Card enchantmentCard = Cards::FindCardByID(m_cardID); if (enchantmentCard.id.empty()) { return TaskStatus::STOP; } auto entities = IncludeTask::GetEntities(m_entityType, player, m_source, m_target); Power power = enchantmentCard.power; for (auto& entity : entities) { const auto enchantment = Enchantment::GetInstance(player, enchantmentCard, entity); if (power.GetAura().has_value()) { power.GetAura().value().Activate(*enchantment); } if (power.GetTrigger().has_value()) { power.GetTrigger().value().Activate(*enchantment); } if (power.GetEnchant().has_value()) { const auto& taskStack = player.GetGame()->taskStack; power.GetEnchant().value().ActivateTo(entity, taskStack.num, taskStack.num1); } } return TaskStatus::COMPLETE; } } // namespace RosettaStone::SimpleTasks <|endoftext|>
<commit_before>/* Copyright 2014 Sarah Wong 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 "configuration.h" #include "ui_configuration.h" #include <QDebug> #include <QResource> #include <portaudiocpp/System.hxx> #include <portaudiocpp/SystemHostApiIterator.hxx> #include <portaudiocpp/SystemDeviceIterator.hxx> #include "tinyscheme/scheme-private.h" #include "tinyscheme/scheme.h" namespace { template <class IndexMapType, class ItemIter, class ItemType, class Callable1, class Callable2> static void insertWithDefault(QComboBox *comboBox, IndexMapType &map, ItemIter begin, ItemIter end, ItemType& defaultItem, Callable1 stringGenerator, Callable2 mapItemGenerator) { int itemPosition = 0; comboBox->clear(); map.clear(); { map[itemPosition] = mapItemGenerator(defaultItem); comboBox->insertItem(itemPosition++, QLatin1String("Default: ") + stringGenerator(defaultItem)); } comboBox->insertSeparator(itemPosition++); while (begin != end) { ItemType& item = *begin; map[itemPosition] = mapItemGenerator(item); comboBox->insertItem(itemPosition++, stringGenerator(item)); ++begin; } } struct GetDataFromResource { GetDataFromResource(const char *file) { QResource resource(file); Q_ASSERT(resource.isValid()); if (resource.isCompressed()) m_byteArray = qUncompress(resource.data(), resource.size()); else m_byteArray = QByteArray(reinterpret_cast<const char*>(resource.data()), resource.size()); } const QByteArray& byteArray() const { return m_byteArray; } QByteArray m_byteArray; }; } // namespace anonymous Configuration::Configuration(QWidget *parent) : QDialog(parent), ui(new Ui::Configuration) { ui->setupUi(this); GetDataFromResource defaultConfigScm(":/tinyscheme/default-config.scm"); ui->txtConfig->setPlainText( QString::fromUtf8(defaultConfigScm.byteArray().data(), defaultConfigScm.byteArray().size())); portaudio::System& sys = portaudio::System::instance(); insertWithDefault( ui->cmbAudioHost, m_indexToHostApiTypeId, sys.hostApisBegin(), sys.hostApisEnd(), sys.defaultHostApi(), [](portaudio::HostApi &hostApi) { return hostApi.name(); }, [](portaudio::HostApi &hostApi) { return hostApi.typeId(); }); } PaDeviceIndex Configuration::getDeviceIndex() const { auto index = ui->cmbInputDevice->currentIndex(); Q_ASSERT(index != -1); return m_indexToDeviceIndex[index]; } void Configuration::on_cmbAudioHost_currentIndexChanged(int index) { if (index == -1) return; portaudio::HostApi &hostApi = portaudio::System::instance().hostApiByTypeId( m_indexToHostApiTypeId[index]); insertWithDefault( ui->cmbInputDevice, m_indexToDeviceIndex, hostApi.devicesBegin(), hostApi.devicesEnd(), hostApi.defaultInputDevice(), [](portaudio::Device &device) { return device.name(); }, [](portaudio::Device &device) { return device.index(); }); } namespace { struct Ptr { scheme *sc_; pointer p_; Ptr(scheme *sc, pointer p) : sc_(sc), p_(p) {} bool is_nil (pointer p) { return p == sc_->NIL; } //\n bool is_string (pointer p) { return sc_->vptr->is_string(p); } char *string_value (pointer p) { return sc_->vptr->string_value(p); } bool is_number (pointer p) { return sc_->vptr->is_number(p); } num nvalue (pointer p) { return sc_->vptr->nvalue(p); } long ivalue (pointer p) { return sc_->vptr->ivalue(p); } double rvalue (pointer p) { return sc_->vptr->rvalue(p); } bool is_integer (pointer p) { return sc_->vptr->is_integer(p); } bool is_real (pointer p) { return sc_->vptr->is_real(p); } bool is_character (pointer p) { return sc_->vptr->is_character(p); } long charvalue (pointer p) { return sc_->vptr->charvalue(p); } bool is_list (pointer p) { return sc_->vptr->is_list(sc_, p); } bool is_vector (pointer p) { return sc_->vptr->is_vector(p); } int list_length (pointer vec) { return sc_->vptr->list_length(sc_, vec); } long vector_length (pointer vec) { return sc_->vptr->vector_length(vec); } pointer vector_elem (pointer vec, int ielem) { return sc_->vptr->vector_elem(vec, ielem); } bool is_pair (pointer p) { return sc_->vptr->is_pair(p); } pointer pair_car (pointer p) { return sc_->vptr->pair_car(p); } pointer pair_cdr (pointer p) { return sc_->vptr->pair_cdr(p); } //\n bool is_symbol (pointer p) { return sc_->vptr->is_symbol(p); } char *symname (pointer p) { return sc_->vptr->symname(p); } }; struct Config { Config(const char *configScript) : sc_(scheme_init_new()) { Q_ASSERT(sc_ != nullptr); scheme_set_output_port_file(sc_, stdout); loadResource(":/tinyscheme/init.scm"); loadResource(":/tinyscheme/config-helper.scm"); read_eval("(begin (display 1337) (newline))"); scheme_load_string(sc_, configScript); if (sc_->retcode != 0) qDebug() << "Scheme failed" << __LINE__; pointer ret = read_eval("(cdr (assv ':sample-rate (cdr (assv 'audio-config config))))"); qDebug() << sc_->vptr->ivalue(ret); } void loadResource(const char *resource) { GetDataFromResource gdfr(resource); scheme_load_string(sc_, gdfr.byteArray().data()); } pointer read_eval(const char* script) { // tinyscheme bug: When executing // // (read (open-input-string script)) // // sc_->inport needs to be set, or there will be an error when // read is restoring the previous inport value when returning. scheme_set_input_port_file(sc_, stdin); // TODO stdin? pointer fun = scheme_eval(sc_, mk_symbol(sc_, "read-eval")); pointer arg = mk_string(sc_, script); return scheme_call(sc_, fun, _cons(sc_, arg, sc_->NIL, 0)); } scheme *sc_; }; } // namespace anonymous void Configuration::on_buttonBox_accepted() { QString configText = ui->txtConfig->toPlainText(); QByteArray configTextBa = configText.toUtf8(); Config cfg(configTextBa.constData()); emit accept(); } Configuration::~Configuration() { delete ui; } <commit_msg>Wrap returns to Ptr<commit_after>/* Copyright 2014 Sarah Wong 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 "configuration.h" #include "ui_configuration.h" #include <QDebug> #include <QResource> #include <portaudiocpp/System.hxx> #include <portaudiocpp/SystemHostApiIterator.hxx> #include <portaudiocpp/SystemDeviceIterator.hxx> #include "tinyscheme/scheme-private.h" #include "tinyscheme/scheme.h" namespace { template <class IndexMapType, class ItemIter, class ItemType, class Callable1, class Callable2> static void insertWithDefault(QComboBox *comboBox, IndexMapType &map, ItemIter begin, ItemIter end, ItemType& defaultItem, Callable1 stringGenerator, Callable2 mapItemGenerator) { int itemPosition = 0; comboBox->clear(); map.clear(); { map[itemPosition] = mapItemGenerator(defaultItem); comboBox->insertItem(itemPosition++, QLatin1String("Default: ") + stringGenerator(defaultItem)); } comboBox->insertSeparator(itemPosition++); while (begin != end) { ItemType& item = *begin; map[itemPosition] = mapItemGenerator(item); comboBox->insertItem(itemPosition++, stringGenerator(item)); ++begin; } } struct GetDataFromResource { GetDataFromResource(const char *file) { QResource resource(file); Q_ASSERT(resource.isValid()); if (resource.isCompressed()) m_byteArray = qUncompress(resource.data(), resource.size()); else m_byteArray = QByteArray(reinterpret_cast<const char*>(resource.data()), resource.size()); } const QByteArray& byteArray() const { return m_byteArray; } QByteArray m_byteArray; }; } // namespace anonymous Configuration::Configuration(QWidget *parent) : QDialog(parent), ui(new Ui::Configuration) { ui->setupUi(this); GetDataFromResource defaultConfigScm(":/tinyscheme/default-config.scm"); ui->txtConfig->setPlainText( QString::fromUtf8(defaultConfigScm.byteArray().data(), defaultConfigScm.byteArray().size())); portaudio::System& sys = portaudio::System::instance(); insertWithDefault( ui->cmbAudioHost, m_indexToHostApiTypeId, sys.hostApisBegin(), sys.hostApisEnd(), sys.defaultHostApi(), [](portaudio::HostApi &hostApi) { return hostApi.name(); }, [](portaudio::HostApi &hostApi) { return hostApi.typeId(); }); } PaDeviceIndex Configuration::getDeviceIndex() const { auto index = ui->cmbInputDevice->currentIndex(); Q_ASSERT(index != -1); return m_indexToDeviceIndex[index]; } void Configuration::on_cmbAudioHost_currentIndexChanged(int index) { if (index == -1) return; portaudio::HostApi &hostApi = portaudio::System::instance().hostApiByTypeId( m_indexToHostApiTypeId[index]); insertWithDefault( ui->cmbInputDevice, m_indexToDeviceIndex, hostApi.devicesBegin(), hostApi.devicesEnd(), hostApi.defaultInputDevice(), [](portaudio::Device &device) { return device.name(); }, [](portaudio::Device &device) { return device.index(); }); } namespace { struct Ptr { scheme *sc_; pointer p_; Ptr(scheme *sc, pointer p) : sc_(sc), p_(p) {} #define P(v) Ptr(sc_, v) bool is_nil (pointer p) { return p == sc_->NIL; } //\n bool is_string (pointer p) { return sc_->vptr->is_string(p); } char *string_value (pointer p) { return sc_->vptr->string_value(p); } bool is_number (pointer p) { return sc_->vptr->is_number(p); } num nvalue (pointer p) { return sc_->vptr->nvalue(p); } long ivalue (pointer p) { return sc_->vptr->ivalue(p); } double rvalue (pointer p) { return sc_->vptr->rvalue(p); } bool is_integer (pointer p) { return sc_->vptr->is_integer(p); } bool is_real (pointer p) { return sc_->vptr->is_real(p); } bool is_character (pointer p) { return sc_->vptr->is_character(p); } long charvalue (pointer p) { return sc_->vptr->charvalue(p); } bool is_list (pointer p) { return sc_->vptr->is_list(sc_, p); } bool is_vector (pointer p) { return sc_->vptr->is_vector(p); } int list_length (pointer vec) { return sc_->vptr->list_length(sc_, vec); } long vector_length (pointer vec) { return sc_->vptr->vector_length(vec); } Ptr vector_elem (pointer vec, int ielem) { return P(sc_->vptr->vector_elem(vec, ielem)); } bool is_pair (pointer p) { return sc_->vptr->is_pair(p); } Ptr pair_car (pointer p) { return P(sc_->vptr->pair_car(p)); } Ptr pair_cdr (pointer p) { return P(sc_->vptr->pair_cdr(p)); } //\n bool is_symbol (pointer p) { return sc_->vptr->is_symbol(p); } char *symname (pointer p) { return sc_->vptr->symname(p); } #undef P }; struct Config { Config(const char *configScript) : sc_(scheme_init_new()) { Q_ASSERT(sc_ != nullptr); scheme_set_output_port_file(sc_, stdout); loadResource(":/tinyscheme/init.scm"); loadResource(":/tinyscheme/config-helper.scm"); read_eval("(begin (display 1337) (newline))"); scheme_load_string(sc_, configScript); if (sc_->retcode != 0) qDebug() << "Scheme failed" << __LINE__; pointer ret = read_eval("(cdr (assv ':sample-rate (cdr (assv 'audio-config config))))"); qDebug() << sc_->vptr->ivalue(ret); } void loadResource(const char *resource) { GetDataFromResource gdfr(resource); scheme_load_string(sc_, gdfr.byteArray().data()); } pointer read_eval(const char* script) { // tinyscheme bug: When executing // // (read (open-input-string script)) // // sc_->inport needs to be set, or there will be an error when // read is restoring the previous inport value when returning. scheme_set_input_port_file(sc_, stdin); // TODO stdin? pointer fun = scheme_eval(sc_, mk_symbol(sc_, "read-eval")); pointer arg = mk_string(sc_, script); return scheme_call(sc_, fun, _cons(sc_, arg, sc_->NIL, 0)); } scheme *sc_; }; } // namespace anonymous void Configuration::on_buttonBox_accepted() { QString configText = ui->txtConfig->toPlainText(); QByteArray configTextBa = configText.toUtf8(); Config cfg(configTextBa.constData()); emit accept(); } Configuration::~Configuration() { delete ui; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "maya/MGlobal.h" #include "IECorePython/RefCountedBinding.h" #include "IECorePython/Wrapper.h" #include "IECorePython/ScopedGILLock.h" #include "IECore/Exception.h" #include "IECoreMaya/StatusException.h" #include "IECoreMaya/bindings/ImageViewportPostProcessBinding.h" #include "IECoreMaya/ImageViewportPostProcess.h" using namespace IECore; using namespace IECorePython; using namespace boost::python; namespace IECoreMaya { struct ImageViewportPostProcessWrapper : public ImageViewportPostProcess, Wrapper< ImageViewportPostProcess > { ImageViewportPostProcessWrapper(PyObject *self ) : ImageViewportPostProcess(), Wrapper<ImageViewportPostProcess>( self, this ) { } virtual ~ImageViewportPostProcessWrapper() { } virtual bool needsDepth () const { ScopedGILLock gilLock; override o = this->get_override( "needsDepth" ); if( o ) { try { return o(); } catch ( error_already_set ) { PyErr_Print(); return false; } } else { return ImageViewportPostProcess::needsDepth(); } } virtual void preRender( const std::string &panelName ) { ScopedGILLock gilLock; override o = this->get_override( "preRender" ); if( o ) { try { o( panelName ); } catch ( error_already_set ) { PyErr_Print(); } } else { ImageViewportPostProcess::preRender( panelName ); } } virtual void postRender( const std::string &panelName, IECore::ImagePrimitivePtr image ) { ScopedGILLock gilLock; override o = this->get_override( "postRender" ); if( o ) { try { o( panelName, image ); } catch ( error_already_set ) { PyErr_Print(); } } else { /// Maya would crash if we were to throw an exception here MGlobal::displayError( "ImageViewportPostProcess: postRender() python method not defined" ); } } }; void bindImageViewportPostProcess() { RefCountedClass<ImageViewportPostProcess, ViewportPostProcess, ImageViewportPostProcessWrapper>( "ImageViewportPostProcess" ) .def( init<>() ) .def( "needsDepth", &ImageViewportPostProcessWrapper::needsDepth ) .def( "preRender", &ImageViewportPostProcessWrapper::preRender ) .def( "postRender", pure_virtual( &ImageViewportPostProcessWrapper::postRender ) ) ; } } <commit_msg>IECoreMaya::ImageViewPostProcess Binding : Use RefCountedWrapper<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "maya/MGlobal.h" #include "IECorePython/RefCountedBinding.h" #include "IECorePython/ScopedGILLock.h" #include "IECore/Exception.h" #include "IECoreMaya/StatusException.h" #include "IECoreMaya/bindings/ImageViewportPostProcessBinding.h" #include "IECoreMaya/ImageViewportPostProcess.h" using namespace IECore; using namespace IECorePython; using namespace boost::python; namespace IECoreMaya { struct ImageViewportPostProcessWrapper : RefCountedWrapper< ImageViewportPostProcess > { ImageViewportPostProcessWrapper(PyObject *self ) : RefCountedWrapper<ImageViewportPostProcess>( self ) { } virtual ~ImageViewportPostProcessWrapper() { } virtual bool needsDepth () const { if( isSubclassed() ) { ScopedGILLock gilLock; object o = this->methodOverride( "needsDepth" ); if( o ) { try { return o(); } catch( error_already_set ) { PyErr_Print(); return false; } } } return ImageViewportPostProcess::needsDepth(); } virtual void preRender( const std::string &panelName ) { ScopedGILLock gilLock; object o = this->methodOverride( "preRender" ); if( o ) { try { o( panelName ); } catch ( error_already_set ) { PyErr_Print(); } } else { ImageViewportPostProcess::preRender( panelName ); } } virtual void postRender( const std::string &panelName, IECore::ImagePrimitivePtr image ) { ScopedGILLock gilLock; object o = this->methodOverride( "postRender" ); if( o ) { try { o( panelName, image ); } catch ( error_already_set ) { PyErr_Print(); } } else { /// Maya would crash if we were to throw an exception here MGlobal::displayError( "ImageViewportPostProcess: postRender() python method not defined" ); } } }; void bindImageViewportPostProcess() { RefCountedClass<ImageViewportPostProcess, ViewportPostProcess, ImageViewportPostProcessWrapper>( "ImageViewportPostProcess" ) .def( init<>() ) .def( "needsDepth", &ImageViewportPostProcessWrapper::needsDepth ) .def( "preRender", &ImageViewportPostProcessWrapper::preRender ) .def( "postRender", pure_virtual( &ImageViewportPostProcessWrapper::postRender ) ) ; } } <|endoftext|>
<commit_before>/* * Qumulus UML editor * Author: Frank Erens * Author: Randy Thiemann * */ #include "Operation.h" #include <Uml/Kernel/Class.h> #include "Parameter.h" #include "Class.h" QUML_BEGIN_NAMESPACE_UK Operation::Operation(QString name, Class* c) : mClass(c), mQuery(false) { setName(name); if(c) c->addOperation(this); } Parameter* Operation::returnResult() const { for(auto&& p : parameters()) { if(p->direction() == ParameterDirectionKind::Return) return p; } return nullptr; } Type* Operation::type() const { return returnResult()->type(); } QuUD::Label* Operation::diagramElement() const { return static_cast<QuUD::Label*>(mDiagramElement); } void Operation::updateDiagramElement(QuUD::Diagram*, QSizeF) { if(!mDiagramElement) { mDiagramElement = new QuUD::Label(*name(), this, mClass->diagramElement()); } auto d = static_cast<QuUD::Label*>(mDiagramElement); QString str = ""; if(visibility()) { str += QString(QuUK::toChar(*visibility())); str += " "; str += *name(); } else { str += *name(); } str += "("; for(Parameter* p : parameters()) { if(p->direction() == ParameterDirectionKind::Return) continue; // Parameter name str += *(p->name()); // Parameter type if(p->type()) { str += " : "; str += *(p->type()->name()); } // Parameter multiplicity if(p->multiplicityString() != "") { str += " "; str += p->multiplicityString(); } // Parameter default if(p->defaultValue()) { str += " = "; str += *(p->defaultValue()); } if(p != *(parameters().end()-1)) { str += ", "; } } str += ")"; if(type()) { str += " : "; str += *(type()->name()); } if(isQuery()) { str += " {query}"; } d->setText(str); if(isStatic()) { d->setHtml(QString("<u>")+str+"</u>"); } d->resize(static_cast<QuUD::Shape*>( mClass->diagramElement())->width(), 0); } QUML_END_NAMESPACE_UK <commit_msg>Fix Operation segfault.<commit_after>/* * Qumulus UML editor * Author: Frank Erens * Author: Randy Thiemann * */ #include "Operation.h" #include <Uml/Kernel/Class.h> #include "Parameter.h" #include "Class.h" QUML_BEGIN_NAMESPACE_UK Operation::Operation(QString name, Class* c) : mClass(c), mQuery(false) { setName(name); if(c) c->addOperation(this); } Parameter* Operation::returnResult() const { for(auto&& p : parameters()) { if(p->direction() == ParameterDirectionKind::Return) return p; } return nullptr; } Type* Operation::type() const { if(returnResult()) return returnResult()->type(); else return nullptr; } QuUD::Label* Operation::diagramElement() const { return static_cast<QuUD::Label*>(mDiagramElement); } void Operation::updateDiagramElement(QuUD::Diagram*, QSizeF) { if(!mDiagramElement) { mDiagramElement = new QuUD::Label(*name(), this, mClass->diagramElement()); } auto d = static_cast<QuUD::Label*>(mDiagramElement); QString str = ""; if(visibility()) { str += QString(QuUK::toChar(*visibility())); str += " "; str += *name(); } else { str += *name(); } str += "("; for(Parameter* p : parameters()) { if(p->direction() == ParameterDirectionKind::Return) continue; // Parameter direction if(p->direction() == ParameterDirectionKind::Out) { str += "out "; } if(p->direction() == ParameterDirectionKind::InOut) { str += "inout "; } // Parameter name str += *(p->name()); // Parameter type if(p->type()) { str += " : "; str += *(p->type()->name()); } // Parameter multiplicity if(p->multiplicityString() != "") { str += " "; str += p->multiplicityString(); } // Parameter default if(p->defaultValue()) { str += " = "; str += *(p->defaultValue()); } if(p != *(parameters().end()-1)) { str += ", "; } } str += ")"; if(type()) { str += " : "; str += *(type()->name()); } if(isQuery()) { str += " {query}"; } d->setText(str); d->resize(static_cast<QuUD::Shape*>( mClass->diagramElement())->width(), 0); if(isStatic()) { d->setHtml(QString("<u>")+str+"</u>"); } } QUML_END_NAMESPACE_UK <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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 <Windowsx.h> #include "base/registry.h" #include "Resource.h" // This enum needs to be in sync with the strings below. enum Branch { UNKNOWN_BRANCH = 0, DEV_BRANCH, BETA_BRANCH, STABLE_BRANCH, }; // This vector of strings needs to be in sync with the Branch enum above. static const wchar_t* const kBranchStrings[] = { L"?", L"1.1-dev", L"1.1-beta", L"", }; // This vector of strings needs to be in sync with the Branch enum above. static const wchar_t* const kBranchStringsReadable[] = { L"?", L"Dev", L"Beta", L"Stable", }; // The Registry Hive to write to. Points to the hive where we found the 'ap' key // unless there is an error, in which case it is 0. HKEY registry_hive = 0; // The value of the 'ap' key under the registry hive specified in // |registry_hive|. std::wstring update_branch; // The Google Update key to read to find out which branch you are on. static const wchar_t* const kGoogleUpdateKey = L"Software\\Google\\Update\\ClientState\\" L"{8A69D345-D564-463C-AFF1-A69D9E530F96}"; // The Google Update value that defines which branch you are on. static const wchar_t* const kBranchKey = L"ap"; // The suffix Google Update sometimes adds to the channel name (channel names // are defined in kBranchStrings), indicating that a full install is needed. We // strip this out (if present) for the purpose of determining which channel you // are on. static const wchar_t* const kChannelSuffix = L"-full"; // Title to show in the MessageBoxes. static const wchar_t* const kMessageBoxTitle = L"Google Chrome Channel Changer"; // A parameter passed into us when we are trying to elevate. This is used as a // safeguard to make sure we only try to elevate once (so that if it fails we // don't create an infinite process spawn loop). static const wchar_t* const kElevationParam = L"--elevation-attempt"; // The icon to use. static HICON dlg_icon = NULL; void DetectBranch() { // See if we can find the 'ap' key on the HKCU branch. registry_hive = HKEY_CURRENT_USER; RegKey google_update_hkcu(registry_hive, kGoogleUpdateKey, KEY_READ); if (!google_update_hkcu.Valid() || !google_update_hkcu.ReadValue(kBranchKey, &update_branch)) { // HKCU failed us, try the same for the HKLM branch. registry_hive = HKEY_LOCAL_MACHINE; RegKey google_update_hklm(registry_hive, kGoogleUpdateKey, KEY_READ); if (!google_update_hklm.Valid() || !google_update_hklm.ReadValue(kBranchKey, &update_branch)) { // HKLM also failed us! "Set condition 1 throughout the ship!" registry_hive = 0; // Failed to find the 'ap' key. update_branch = kBranchStrings[UNKNOWN_BRANCH]; } } // We look for '1.1-beta' or '1.1-dev', but Google Update might have added // '-full' to the channel name, which we need to strip out to determine what // channel you are on. std::wstring suffix = kChannelSuffix; if (update_branch.length() > suffix.length()) { size_t index = update_branch.rfind(suffix); if (index != std::wstring::npos && index == update_branch.length() - suffix.length()) { update_branch = update_branch.substr(0, index); } } } void SetMainLabel(HWND dialog, Branch branch) { std::wstring main_label = L"You are currently on "; if (branch == DEV_BRANCH || branch == BETA_BRANCH || branch == STABLE_BRANCH) main_label += std::wstring(L"the ") + kBranchStringsReadable[branch] + std::wstring(L" channel"); else main_label += L"NO UPDATE CHANNEL"; main_label += L". Choose a different channel and click Update, " L"or click Close to stay on this channel."; SetWindowText(GetDlgItem(dialog, IDC_LABEL_MAIN), main_label.c_str()); } void OnInitDialog(HWND dialog) { SendMessage(dialog, WM_SETICON, (WPARAM) false, (LPARAM) dlg_icon); Branch branch = UNKNOWN_BRANCH; if (update_branch == kBranchStrings[STABLE_BRANCH]) { branch = STABLE_BRANCH; } else if (update_branch == kBranchStrings[DEV_BRANCH]) { branch = DEV_BRANCH; } else if (update_branch == kBranchStrings[BETA_BRANCH]) { branch = BETA_BRANCH; } else { // Hide the controls we can't use. EnableWindow(GetDlgItem(dialog, IDOK), false); EnableWindow(GetDlgItem(dialog, IDC_STABLE), false); EnableWindow(GetDlgItem(dialog, IDC_BETA), false); EnableWindow(GetDlgItem(dialog, IDC_CUTTING_EDGE), false); MessageBox(dialog, L"KEY NOT FOUND\n\nGoogle Chrome is not installed, or " L"is not using GoogleUpdate for updates.", kMessageBoxTitle, MB_ICONEXCLAMATION | MB_OK); } SetMainLabel(dialog, branch); CheckDlgButton(dialog, IDC_STABLE, branch == STABLE_BRANCH ? BST_CHECKED : BST_UNCHECKED); CheckDlgButton(dialog, IDC_CUTTING_EDGE, branch == DEV_BRANCH ? BST_CHECKED : BST_UNCHECKED); CheckDlgButton(dialog, IDC_BETA, branch == BETA_BRANCH ? BST_CHECKED : BST_UNCHECKED); } INT_PTR OnCtlColorStatic(HWND dialog, WPARAM wparam, LPARAM lparam) { HDC hdc = reinterpret_cast<HDC>(wparam); HWND control_wnd = reinterpret_cast<HWND>(lparam); if (GetDlgItem(dialog, IDC_STABLE) == control_wnd || GetDlgItem(dialog, IDC_BETA) == control_wnd || GetDlgItem(dialog, IDC_CUTTING_EDGE) == control_wnd || GetDlgItem(dialog, IDC_LABEL_MAIN) == control_wnd || GetDlgItem(dialog, IDC_SECONDARY_LABEL) == control_wnd) { SetBkMode(hdc, TRANSPARENT); SetTextColor(hdc, RGB(0, 0, 0)); return reinterpret_cast<INT_PTR>(GetSysColorBrush(COLOR_WINDOW)); } return static_cast<INT_PTR>(FALSE); } void SaveChanges(HWND dialog) { Branch branch = UNKNOWN_BRANCH; if (IsDlgButtonChecked(dialog, IDC_STABLE)) branch = STABLE_BRANCH; else if (IsDlgButtonChecked(dialog, IDC_BETA)) branch = BETA_BRANCH; else if (IsDlgButtonChecked(dialog, IDC_CUTTING_EDGE)) branch = DEV_BRANCH; if (branch != UNKNOWN_BRANCH) { RegKey google_update(registry_hive, kGoogleUpdateKey, KEY_WRITE); if (!google_update.WriteValue(kBranchKey, kBranchStrings[branch])) { MessageBox(dialog, L"Unable to change value. Please make sure you\n" L"have permission to change registry keys.", L"Unable to update branch info", MB_OK | MB_ICONERROR); } else { std::wstring save_msg = L"Your changes have been saved.\nYou are now " L"on the " + std::wstring(kBranchStringsReadable[branch]) + L" branch."; MessageBox(dialog, save_msg.c_str(), L"Changes were saved", MB_OK | MB_ICONINFORMATION); SetMainLabel(dialog, branch); } } } INT_PTR CALLBACK DialogWndProc(HWND dialog, UINT message_id, WPARAM wparam, LPARAM lparam) { UNREFERENCED_PARAMETER(lparam); switch (message_id) { case WM_INITDIALOG: OnInitDialog(dialog); return static_cast<INT_PTR>(TRUE); case WM_CTLCOLORSTATIC: return OnCtlColorStatic(dialog, wparam, lparam); case WM_COMMAND: // If the user presses the OK button. if (LOWORD(wparam) == IDOK) { SaveChanges(dialog); return static_cast<INT_PTR>(TRUE); } // If the user presses the Cancel button. if (LOWORD(wparam) == IDCANCEL) { ::EndDialog(dialog, LOWORD(wparam)); return static_cast<INT_PTR>(TRUE); } break; case WM_ERASEBKGND: PAINTSTRUCT paint; HDC hdc = BeginPaint(dialog, &paint); if (!hdc) return static_cast<INT_PTR>(FALSE); // We didn't handle it. // Fill the background with White. HBRUSH brush = GetStockBrush(WHITE_BRUSH); HGDIOBJ old_brush = SelectObject(hdc, brush); RECT rc; GetClientRect(dialog, &rc); FillRect(hdc, &rc, brush); // Clean up. SelectObject(hdc, old_brush); EndPaint(dialog, &paint); return static_cast<INT_PTR>(TRUE); } return static_cast<INT_PTR>(FALSE); } // This function checks to see if we are running elevated. This function will // return false on error and on success will modify the parameter |elevated| // to specify whether we are running elevated or not. This function should only // be called for Vista or later. bool IsRunningElevated(bool* elevated) { HANDLE process_token; if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &process_token)) return false; TOKEN_ELEVATION_TYPE elevation_type = TokenElevationTypeDefault; DWORD size_returned = 0; if (!::GetTokenInformation(process_token, TokenElevationType, &elevation_type, sizeof(elevation_type), &size_returned)) { ::CloseHandle(process_token); return false; } ::CloseHandle(process_token); *elevated = (elevation_type == TokenElevationTypeFull); return true; } // This function checks to see if we need to elevate. Essentially, we need to // elevate if ALL of the following conditions are true: // - The OS is Vista or later. // - UAC is enabled. // - We are not already elevated. // - The registry hive we are working with is HKLM. // This function will return false on error and on success will modify the // parameter |elevation_required| to specify whether we need to elevated or not. bool ElevationIsRequired(bool* elevation_required) { *elevation_required = false; // First, make sure we are running on Vista or more recent. OSVERSIONINFO info = {0}; info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!::GetVersionEx(&info)) return false; // Failure. // Unless we are Vista or newer, we don't need to elevate. if (info.dwMajorVersion < 6) return true; // No error, we just don't need to elevate. // Make sure UAC is not disabled. RegKey key(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"); DWORD uac_enabled; if (!key.ReadValueDW(L"EnableLUA", &uac_enabled)) uac_enabled = true; // If the value doesn't exist, then UAC is enabled. if (!uac_enabled) return true; // No error, but UAC is disabled, so elevation is futile! // This is Vista or more recent, so check if already running elevated. bool elevated = false; if (!IsRunningElevated(&elevated)) return false; // Error checking to see if we already elevated. if (elevated) return true; // No error, but we are already elevated. // We are not already running elevated, check if we found our key under HKLM // because then we need to elevate us so that our writes don't get // virtualized. *elevation_required = (registry_hive == HKEY_LOCAL_MACHINE); return true; // Success. } int RelaunchProcessWithElevation() { // Get the path and EXE name of this process so we can relaunch it. wchar_t executable[MAX_PATH]; if (!::GetModuleFileName(0, &executable[0], MAX_PATH)) return 0; SHELLEXECUTEINFO info; ZeroMemory(&info, sizeof(info)); info.hwnd = GetDesktopWindow(); info.cbSize = sizeof(SHELLEXECUTEINFOW); info.lpVerb = L"runas"; // Relaunch with elevation. info.lpFile = executable; info.lpParameters = kElevationParam; // Our special notification param. info.nShow = SW_SHOWNORMAL; return ::ShellExecuteEx(&info); } BOOL RestartWithElevationIfRequired(const std::wstring& cmd_line) { bool elevation_required = false; if (!ElevationIsRequired(&elevation_required)) { ::MessageBox(NULL, L"Cannot determine if Elevation is required", kMessageBoxTitle, MB_OK | MB_ICONERROR); return TRUE; // This causes the app to exit. } if (elevation_required) { if (cmd_line.find(kElevationParam) != std::wstring::npos) { // If we get here, that means we tried to elevate but it failed. // We break here to prevent an infinite spawning loop. ::MessageBox(NULL, L"Second elevation attempted", kMessageBoxTitle, MB_OK | MB_ICONERROR); return TRUE; // This causes the app to exit. } // Restart this application with elevation. if (!RelaunchProcessWithElevation()) { ::MessageBox(NULL, L"Elevation attempt failed", kMessageBoxTitle, MB_OK | MB_ICONERROR); } return TRUE; // This causes the app to exit. } return FALSE; // No elevation required, Channel Changer can continue running. } int APIENTRY _tWinMain(HINSTANCE instance, HINSTANCE previous_instance, LPTSTR cmd_line, int cmd_show) { UNREFERENCED_PARAMETER(previous_instance); UNREFERENCED_PARAMETER(cmd_show); // Detect which update path the user is on. This also sets the registry_hive // parameter to the right Registry hive, which we will use later to determine // if we need to elevate (Vista and later only). DetectBranch(); // If we detect that we need to elevate then we will restart this process // as an elevated process, so all this process needs to do is exit. // NOTE: We need to elevate on Vista if we detect that Chrome was installed // system-wide (because then we'll be modifying Google Update keys under // HKLM). We don't want to set the elevation policy in the manifest because // then we block non-admin users (that want to modify user-level Chrome // installation) from running the channel changer. if (RestartWithElevationIfRequired(cmd_line)) return TRUE; dlg_icon = ::LoadIcon(instance, MAKEINTRESOURCE(IDI_BRANCH_SWITCHER)); ::DialogBox(instance, MAKEINTRESOURCE(IDD_MAIN_DIALOG), ::GetDesktopWindow(), DialogWndProc); return TRUE; } <commit_msg>Changing which installation the Channel Changer uses.<commit_after>// Copyright (c) 2006-2008 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 <Windowsx.h> #include "base/registry.h" #include "Resource.h" // This enum needs to be in sync with the strings below. enum Branch { UNKNOWN_BRANCH = 0, DEV_BRANCH, BETA_BRANCH, STABLE_BRANCH, }; // This vector of strings needs to be in sync with the Branch enum above. static const wchar_t* const kBranchStrings[] = { L"?", L"1.1-dev", L"1.1-beta", L"", }; // This vector of strings needs to be in sync with the Branch enum above. static const wchar_t* const kBranchStringsReadable[] = { L"?", L"Dev", L"Beta", L"Stable", }; // The Registry Hive to write to. Points to the hive where we found the 'ap' key // unless there is an error, in which case it is 0. HKEY registry_hive = 0; // The value of the 'ap' key under the registry hive specified in // |registry_hive|. std::wstring update_branch; // The Google Update key to read to find out which branch you are on. static const wchar_t* const kChromeClientStateKey = L"Software\\Google\\Update\\ClientState\\" L"{8A69D345-D564-463C-AFF1-A69D9E530F96}"; // The Google Client key to read to find out which branch you are on. static const wchar_t* const kChromeClientsKey = L"Software\\Google\\Update\\Clients\\" L"{8A69D345-D564-463C-AFF1-A69D9E530F96}"; // The Google Update value that defines which branch you are on. static const wchar_t* const kBranchKey = L"ap"; // The suffix Google Update sometimes adds to the channel name (channel names // are defined in kBranchStrings), indicating that a full install is needed. We // strip this out (if present) for the purpose of determining which channel you // are on. static const wchar_t* const kChannelSuffix = L"-full"; // Title to show in the MessageBoxes. static const wchar_t* const kMessageBoxTitle = L"Google Chrome Channel Changer"; // A parameter passed into us when we are trying to elevate. This is used as a // safeguard to make sure we only try to elevate once (so that if it fails we // don't create an infinite process spawn loop). static const wchar_t* const kElevationParam = L"--elevation-attempt"; // The icon to use. static HICON dlg_icon = NULL; // We need to detect which update branch the user is on. We do this by checking // under the Google Update 'Clients\<Chrome GUID>' key for HKLM (for // system-level installs) and then HKCU (for user-level installs). Once we find // the right registry hive, we read the current value of the 'ap' key under // Google Update 'ClientState\<Chrome GUID>' key. void DetectBranch() { // See if we can find the Clients key on the HKLM branch. registry_hive = HKEY_LOCAL_MACHINE; RegKey google_update_hklm(registry_hive, kChromeClientsKey, KEY_READ); if (!google_update_hklm.Valid()) { // HKLM failed us, try the same for the HKCU branch. registry_hive = HKEY_CURRENT_USER; RegKey google_update_hkcu(registry_hive, kChromeClientsKey, KEY_READ); if (!google_update_hkcu.Valid()) { // HKCU also failed us! "Set condition 1 throughout the ship!" registry_hive = 0; // Failed to find Google Update Chrome key. update_branch = kBranchStrings[UNKNOWN_BRANCH]; } } if (registry_hive != 0) { // Now that we know which hive to use, read the 'ap' key from it. RegKey client_state(registry_hive, kChromeClientStateKey, KEY_READ); client_state.ReadValue(kBranchKey, &update_branch); // We look for '1.1-beta' or '1.1-dev', but Google Update might have added // '-full' to the channel name, which we need to strip out to determine what // channel you are on. std::wstring suffix = kChannelSuffix; if (update_branch.length() > suffix.length()) { size_t index = update_branch.rfind(suffix); if (index != std::wstring::npos && index == update_branch.length() - suffix.length()) { update_branch = update_branch.substr(0, index); } } } } void SetMainLabel(HWND dialog, Branch branch) { std::wstring main_label = L"You are currently on "; if (branch == DEV_BRANCH || branch == BETA_BRANCH || branch == STABLE_BRANCH) main_label += std::wstring(L"the ") + kBranchStringsReadable[branch] + std::wstring(L" channel"); else main_label += L"NO UPDATE CHANNEL"; main_label += L". Choose a different channel and click Update, " L"or click Close to stay on this channel."; SetWindowText(GetDlgItem(dialog, IDC_LABEL_MAIN), main_label.c_str()); } void OnInitDialog(HWND dialog) { SendMessage(dialog, WM_SETICON, (WPARAM) false, (LPARAM) dlg_icon); Branch branch = UNKNOWN_BRANCH; if (update_branch == kBranchStrings[STABLE_BRANCH]) { branch = STABLE_BRANCH; } else if (update_branch == kBranchStrings[DEV_BRANCH]) { branch = DEV_BRANCH; } else if (update_branch == kBranchStrings[BETA_BRANCH]) { branch = BETA_BRANCH; } else { // Hide the controls we can't use. EnableWindow(GetDlgItem(dialog, IDOK), false); EnableWindow(GetDlgItem(dialog, IDC_STABLE), false); EnableWindow(GetDlgItem(dialog, IDC_BETA), false); EnableWindow(GetDlgItem(dialog, IDC_CUTTING_EDGE), false); MessageBox(dialog, L"KEY NOT FOUND\n\nGoogle Chrome is not installed, or " L"is not using GoogleUpdate for updates.", kMessageBoxTitle, MB_ICONEXCLAMATION | MB_OK); } SetMainLabel(dialog, branch); CheckDlgButton(dialog, IDC_STABLE, branch == STABLE_BRANCH ? BST_CHECKED : BST_UNCHECKED); CheckDlgButton(dialog, IDC_CUTTING_EDGE, branch == DEV_BRANCH ? BST_CHECKED : BST_UNCHECKED); CheckDlgButton(dialog, IDC_BETA, branch == BETA_BRANCH ? BST_CHECKED : BST_UNCHECKED); } INT_PTR OnCtlColorStatic(HWND dialog, WPARAM wparam, LPARAM lparam) { HDC hdc = reinterpret_cast<HDC>(wparam); HWND control_wnd = reinterpret_cast<HWND>(lparam); if (GetDlgItem(dialog, IDC_STABLE) == control_wnd || GetDlgItem(dialog, IDC_BETA) == control_wnd || GetDlgItem(dialog, IDC_CUTTING_EDGE) == control_wnd || GetDlgItem(dialog, IDC_LABEL_MAIN) == control_wnd || GetDlgItem(dialog, IDC_SECONDARY_LABEL) == control_wnd) { SetBkMode(hdc, TRANSPARENT); SetTextColor(hdc, RGB(0, 0, 0)); return reinterpret_cast<INT_PTR>(GetSysColorBrush(COLOR_WINDOW)); } return static_cast<INT_PTR>(FALSE); } void SaveChanges(HWND dialog) { Branch branch = UNKNOWN_BRANCH; if (IsDlgButtonChecked(dialog, IDC_STABLE)) branch = STABLE_BRANCH; else if (IsDlgButtonChecked(dialog, IDC_BETA)) branch = BETA_BRANCH; else if (IsDlgButtonChecked(dialog, IDC_CUTTING_EDGE)) branch = DEV_BRANCH; if (branch != UNKNOWN_BRANCH) { RegKey google_update(registry_hive, kChromeClientStateKey, KEY_WRITE); if (!google_update.WriteValue(kBranchKey, kBranchStrings[branch])) { MessageBox(dialog, L"Unable to change value. Please make sure you\n" L"have permission to change registry keys.", L"Unable to update branch info", MB_OK | MB_ICONERROR); } else { std::wstring save_msg = L"Your changes have been saved.\nYou are now " L"on the " + std::wstring(kBranchStringsReadable[branch]) + L" branch."; MessageBox(dialog, save_msg.c_str(), L"Changes were saved", MB_OK | MB_ICONINFORMATION); SetMainLabel(dialog, branch); } } } INT_PTR CALLBACK DialogWndProc(HWND dialog, UINT message_id, WPARAM wparam, LPARAM lparam) { UNREFERENCED_PARAMETER(lparam); switch (message_id) { case WM_INITDIALOG: OnInitDialog(dialog); return static_cast<INT_PTR>(TRUE); case WM_CTLCOLORSTATIC: return OnCtlColorStatic(dialog, wparam, lparam); case WM_COMMAND: // If the user presses the OK button. if (LOWORD(wparam) == IDOK) { SaveChanges(dialog); return static_cast<INT_PTR>(TRUE); } // If the user presses the Cancel button. if (LOWORD(wparam) == IDCANCEL) { ::EndDialog(dialog, LOWORD(wparam)); return static_cast<INT_PTR>(TRUE); } break; case WM_ERASEBKGND: PAINTSTRUCT paint; HDC hdc = BeginPaint(dialog, &paint); if (!hdc) return static_cast<INT_PTR>(FALSE); // We didn't handle it. // Fill the background with White. HBRUSH brush = GetStockBrush(WHITE_BRUSH); HGDIOBJ old_brush = SelectObject(hdc, brush); RECT rc; GetClientRect(dialog, &rc); FillRect(hdc, &rc, brush); // Clean up. SelectObject(hdc, old_brush); EndPaint(dialog, &paint); return static_cast<INT_PTR>(TRUE); } return static_cast<INT_PTR>(FALSE); } // This function checks to see if we are running elevated. This function will // return false on error and on success will modify the parameter |elevated| // to specify whether we are running elevated or not. This function should only // be called for Vista or later. bool IsRunningElevated(bool* elevated) { HANDLE process_token; if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &process_token)) return false; TOKEN_ELEVATION_TYPE elevation_type = TokenElevationTypeDefault; DWORD size_returned = 0; if (!::GetTokenInformation(process_token, TokenElevationType, &elevation_type, sizeof(elevation_type), &size_returned)) { ::CloseHandle(process_token); return false; } ::CloseHandle(process_token); *elevated = (elevation_type == TokenElevationTypeFull); return true; } // This function checks to see if we need to elevate. Essentially, we need to // elevate if ALL of the following conditions are true: // - The OS is Vista or later. // - UAC is enabled. // - We are not already elevated. // - The registry hive we are working with is HKLM. // This function will return false on error and on success will modify the // parameter |elevation_required| to specify whether we need to elevated or not. bool ElevationIsRequired(bool* elevation_required) { *elevation_required = false; // First, make sure we are running on Vista or more recent. OSVERSIONINFO info = {0}; info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!::GetVersionEx(&info)) return false; // Failure. // Unless we are Vista or newer, we don't need to elevate. if (info.dwMajorVersion < 6) return true; // No error, we just don't need to elevate. // Make sure UAC is not disabled. RegKey key(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"); DWORD uac_enabled; if (!key.ReadValueDW(L"EnableLUA", &uac_enabled)) uac_enabled = true; // If the value doesn't exist, then UAC is enabled. if (!uac_enabled) return true; // No error, but UAC is disabled, so elevation is futile! // This is Vista or more recent, so check if already running elevated. bool elevated = false; if (!IsRunningElevated(&elevated)) return false; // Error checking to see if we already elevated. if (elevated) return true; // No error, but we are already elevated. // We are not already running elevated, check if we found our key under HKLM // because then we need to elevate us so that our writes don't get // virtualized. *elevation_required = (registry_hive == HKEY_LOCAL_MACHINE); return true; // Success. } int RelaunchProcessWithElevation() { // Get the path and EXE name of this process so we can relaunch it. wchar_t executable[MAX_PATH]; if (!::GetModuleFileName(0, &executable[0], MAX_PATH)) return 0; SHELLEXECUTEINFO info; ZeroMemory(&info, sizeof(info)); info.hwnd = GetDesktopWindow(); info.cbSize = sizeof(SHELLEXECUTEINFOW); info.lpVerb = L"runas"; // Relaunch with elevation. info.lpFile = executable; info.lpParameters = kElevationParam; // Our special notification param. info.nShow = SW_SHOWNORMAL; return ::ShellExecuteEx(&info); } BOOL RestartWithElevationIfRequired(const std::wstring& cmd_line) { bool elevation_required = false; if (!ElevationIsRequired(&elevation_required)) { ::MessageBox(NULL, L"Cannot determine if Elevation is required", kMessageBoxTitle, MB_OK | MB_ICONERROR); return TRUE; // This causes the app to exit. } if (elevation_required) { if (cmd_line.find(kElevationParam) != std::wstring::npos) { // If we get here, that means we tried to elevate but it failed. // We break here to prevent an infinite spawning loop. ::MessageBox(NULL, L"Second elevation attempted", kMessageBoxTitle, MB_OK | MB_ICONERROR); return TRUE; // This causes the app to exit. } // Restart this application with elevation. if (!RelaunchProcessWithElevation()) { ::MessageBox(NULL, L"Elevation attempt failed", kMessageBoxTitle, MB_OK | MB_ICONERROR); } return TRUE; // This causes the app to exit. } return FALSE; // No elevation required, Channel Changer can continue running. } int APIENTRY _tWinMain(HINSTANCE instance, HINSTANCE previous_instance, LPTSTR cmd_line, int cmd_show) { UNREFERENCED_PARAMETER(previous_instance); UNREFERENCED_PARAMETER(cmd_show); // Detect which update path the user is on. This also sets the registry_hive // parameter to the right Registry hive, which we will use later to determine // if we need to elevate (Vista and later only). DetectBranch(); // If we detect that we need to elevate then we will restart this process // as an elevated process, so all this process needs to do is exit. // NOTE: We need to elevate on Vista if we detect that Chrome was installed // system-wide (because then we'll be modifying Google Update keys under // HKLM). We don't want to set the elevation policy in the manifest because // then we block non-admin users (that want to modify user-level Chrome // installation) from running the channel changer. if (RestartWithElevationIfRequired(cmd_line)) return TRUE; dlg_icon = ::LoadIcon(instance, MAKEINTRESOURCE(IDI_BRANCH_SWITCHER)); ::DialogBox(instance, MAKEINTRESOURCE(IDD_MAIN_DIALOG), ::GetDesktopWindow(), DialogWndProc); return TRUE; } <|endoftext|>
<commit_before><commit_msg>Removed unused headers<commit_after><|endoftext|>
<commit_before>#include <stan/math/prim/mat/fun/value_of.hpp> #include <test/unit/math/rev/mat/fun/util.hpp> #include <gtest/gtest.h> TEST(MathMatrix,value_of) { using stan::math::value_of; using std::vector; vector<double> a_vals; for (size_t i = 0; i < 10; ++i) a_vals.push_back(i + 1); vector<double> b_vals; for (size_t i = 10; i < 15; ++i) b_vals.push_back(i + 1); Eigen::Matrix<double,2,5> a; fill(a_vals, a); Eigen::Matrix<double,5,1> b; fill(b_vals, b); Eigen::MatrixXd d_a = value_of(a); Eigen::VectorXd d_b = value_of(b); for (size_type i = 0; i < 5; ++i){ EXPECT_FLOAT_EQ(b(i), d_b(i)); } for (size_type i = 0; i < 2; ++i) for (size_type j = 0; j < 5; ++j){ EXPECT_FLOAT_EQ(a(i,j), d_a(i,j)); } } <commit_msg>updating prim/mat/fun<commit_after>#include <stan/math/prim/mat/fun/value_of.hpp> #include <gtest/gtest.h> template<typename T, int R, int C> void fill(const std::vector<double>& contents, Eigen::Matrix<T,R,C>& M){ size_t ij = 0; for (int j = 0; j < C; ++j) for (int i = 0; i < R; ++i) M(i,j) = T(contents[ij++]); } TEST(MathMatrix,value_of) { using stan::math::value_of; using std::vector; vector<double> a_vals; for (size_t i = 0; i < 10; ++i) a_vals.push_back(i + 1); vector<double> b_vals; for (size_t i = 10; i < 15; ++i) b_vals.push_back(i + 1); Eigen::Matrix<double,2,5> a; fill(a_vals, a); Eigen::Matrix<double,5,1> b; fill(b_vals, b); Eigen::MatrixXd d_a = value_of(a); Eigen::VectorXd d_b = value_of(b); for (int i = 0; i < 5; ++i) EXPECT_FLOAT_EQ(b(i), d_b(i)); for (int i = 0; i < 2; ++i) for (int j = 0; j < 5; ++j) EXPECT_FLOAT_EQ(a(i,j), d_a(i,j)); } <|endoftext|>
<commit_before>// Copyright (c) 2011, Christian Rorvik // Distributed under the Simplified BSD License (See accompanying file LICENSE.txt) #include "crunch/concurrency/detail/system_mutex.hpp" #include <windows.h> namespace Crunch { namespace Concurrency { namespace Detail { SystemMutex::SystemMutex() { static_assert(sizeof(CriticalSectionStorageType) <= sizeof(CRITICAL_SECTION), "Insufficient storage space for CRITICAL_SECTION"); InitializeCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&mCriticalSectionStorage)); } SystemMutex::~SystemMutex() { DeleteCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&mCriticalSectionStorage)); } bool SystemMutex::TryLock() { return TryEnterCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&mCriticalSectionStorage)) == TRUE; } void SystemMutex::Lock() { EnterCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&mCriticalSectionStorage)); } void SystemMutex::Unlock() { LeaveCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&mCriticalSectionStorage)); } }}} <commit_msg>crunch_concurrency - Fixed bug in SystemMutex static assert on CRITICAL_SECTION size.<commit_after>// Copyright (c) 2011, Christian Rorvik // Distributed under the Simplified BSD License (See accompanying file LICENSE.txt) #include "crunch/concurrency/detail/system_mutex.hpp" #include <windows.h> namespace Crunch { namespace Concurrency { namespace Detail { SystemMutex::SystemMutex() { static_assert(sizeof(CriticalSectionStorageType) >= sizeof(CRITICAL_SECTION), "Insufficient storage space for CRITICAL_SECTION"); InitializeCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&mCriticalSectionStorage)); } SystemMutex::~SystemMutex() { DeleteCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&mCriticalSectionStorage)); } bool SystemMutex::TryLock() { return TryEnterCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&mCriticalSectionStorage)) == TRUE; } void SystemMutex::Lock() { EnterCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&mCriticalSectionStorage)); } void SystemMutex::Unlock() { LeaveCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&mCriticalSectionStorage)); } }}} <|endoftext|>
<commit_before>#include "Sofa/Components/StaticSolver.h" #include "Sofa/Core/MechanicalGroup.h" #include "Sofa/Core/MultiVector.h" #include "XML/SolverNode.h" #include <math.h> #include <iostream> using std::cout; using std::cerr; using std::endl; namespace Sofa { namespace Components { using namespace Common; using namespace Core; StaticSolver::StaticSolver() { maxCGIter = 25; smallDenominatorThreshold = 1e-5; } void StaticSolver::solve(double) { MultiVector pos(group, VecId::position()); MultiVector vel(group, VecId::velocity()); MultiVector dx(group, VecId::dx()); MultiVector f(group, VecId::force()); MultiVector b(group, V_DERIV); MultiVector p(group, V_DERIV); MultiVector q(group, V_DERIV); MultiVector r(group, V_DERIV); MultiVector x(group, V_DERIV); MultiVector z(group, V_DERIV); // compute the right-hand term of the equation system group->computeForce(b); // b = f0 b.teq(-1); // b = -f0 group->applyConstraints(b); // b is projected to the constrained space // -- solve the system using a conjugate gradient solution double rho, rho_1=0, alpha, beta; group->v_clear( x ); group->v_eq(r,b); // initial residual unsigned nb_iter; for( nb_iter=1; nb_iter<=maxCGIter; nb_iter++ ) { z = r; // no precond rho = r.dot(z); if( nb_iter==1 ) p = z; else { beta = rho / rho_1; p *= beta; p += z; } // matrix-vector product group->propagateDx(p); // dx = p group->computeDf(q); // q = df/dx p // filter the product to take the constraints into account group->applyConstraints(q); // q is projected to the constrained space double den = p.dot(q); if( fabs(den)<smallDenominatorThreshold ) break; alpha = rho/den; x.peq(p,alpha); // x = x + alpha p r.peq(q,-alpha); // r = r - alpha r rho_1 = rho; } // x is the solution of the system // apply the solution pos.peq( x ); } void create(StaticSolver*& obj, XML::Node<Core::OdeSolver>* /*arg*/) { obj = new StaticSolver(); } SOFA_DECL_CLASS(StaticSolver) Creator<XML::SolverNode::Factory, StaticSolver> StaticSolverClass("Static"); } // namespace Components } // namespace Sofa <commit_msg>r229/sofa-dev : Add "iterations" and "threshold" parameters in XML for StaticSolver.<commit_after>#include "Sofa/Components/StaticSolver.h" #include "Sofa/Core/MechanicalGroup.h" #include "Sofa/Core/MultiVector.h" #include "XML/SolverNode.h" #include <math.h> #include <iostream> using std::cout; using std::cerr; using std::endl; namespace Sofa { namespace Components { using namespace Common; using namespace Core; StaticSolver::StaticSolver() { maxCGIter = 25; smallDenominatorThreshold = 1e-5; } void StaticSolver::solve(double) { MultiVector pos(group, VecId::position()); MultiVector vel(group, VecId::velocity()); MultiVector dx(group, VecId::dx()); MultiVector f(group, VecId::force()); MultiVector b(group, V_DERIV); MultiVector p(group, V_DERIV); MultiVector q(group, V_DERIV); MultiVector r(group, V_DERIV); MultiVector x(group, V_DERIV); MultiVector z(group, V_DERIV); // compute the right-hand term of the equation system group->computeForce(b); // b = f0 b.teq(-1); // b = -f0 group->applyConstraints(b); // b is projected to the constrained space // -- solve the system using a conjugate gradient solution double rho, rho_1=0, alpha, beta; group->v_clear( x ); group->v_eq(r,b); // initial residual unsigned nb_iter; for( nb_iter=1; nb_iter<=maxCGIter; nb_iter++ ) { z = r; // no precond rho = r.dot(z); if( nb_iter==1 ) p = z; else { beta = rho / rho_1; p *= beta; p += z; } // matrix-vector product group->propagateDx(p); // dx = p group->computeDf(q); // q = df/dx p // filter the product to take the constraints into account group->applyConstraints(q); // q is projected to the constrained space double den = p.dot(q); if( fabs(den)<smallDenominatorThreshold ) break; alpha = rho/den; x.peq(p,alpha); // x = x + alpha p r.peq(q,-alpha); // r = r - alpha r rho_1 = rho; } // x is the solution of the system // apply the solution pos.peq( x ); } void create(StaticSolver*& obj, XML::Node<Core::OdeSolver>* arg) { obj = new StaticSolver(); if (arg->getAttribute("iterations")) obj->maxCGIter = atoi(arg->getAttribute("iterations")); if (arg->getAttribute("threshold")) obj->smallDenominatorThreshold = atof(arg->getAttribute("threshold")); } SOFA_DECL_CLASS(StaticSolver) Creator<XML::SolverNode::Factory, StaticSolver> StaticSolverClass("Static"); } // namespace Components } // namespace Sofa <|endoftext|>
<commit_before>/* This file is part of MMOServer. For more information, visit http://swganh.com Copyright (c) 2006 - 2010 The SWG:ANH Team MMOServer 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. MMOServer 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 MMOServer. If not, see <http://www.gnu.org/licenses/>. */ #include "anh/event_dispatcher/event_dispatcher.h" #include <cassert> #include <algorithm> #include <boost/date_time/posix_time/posix_time.hpp> using namespace anh::event_dispatcher; using namespace boost::posix_time; using namespace std; EventDispatcher::EventDispatcher() : event_queues_(NUM_QUEUES) , active_queue_(0) { next_event_listener_id_.fetch_and_store(1); } EventDispatcher::~EventDispatcher() { active_queue_ = 0; } uint64_t EventDispatcher::subscribe(const EventType& event_type, EventListenerCallback listener) { if (!validateEventType_(event_type)) { throw anh::event_dispatcher::InvalidEventType( "Invalid event type specified"); } registerEventType(event_type); EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { // Check if there was an insertion failure if (!event_listeners_.insert(a,event_type)) { throw std::runtime_error("Insertion failure"); } a->second = EventListenerList(); } EventListenerList& listener_list = a->second; uint64_t next_listener_id = next_event_listener_id_.fetch_and_increment(); listener_list.push_back(make_pair(next_listener_id, listener)); return next_listener_id; } bool EventDispatcher::hasListeners(const EventType& event_type) const { EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return false; } const EventListenerList& listener_list = a->second; return !listener_list.empty(); } bool EventDispatcher::hasRegisteredEventType(const EventType& event_type) { boost::lock_guard<boost::recursive_mutex> lk(event_set_mutex_); if (registered_event_types_.find(event_type) != registered_event_types_.end()) { return true; } return false; } bool EventDispatcher::hasEvents() const { return !event_queues_[active_queue_].empty(); } void EventDispatcher::registerEventType(EventType event_type) { boost::lock_guard<boost::recursive_mutex> lk(event_set_mutex_); if (hasRegisteredEventType(event_type)) { return; } registered_event_types_.insert(std::move(event_type)); } EventTypeSet EventDispatcher::registered_event_types() const { return registered_event_types_; } void EventDispatcher::unsubscribe(const EventType& event_type, uint64_t listener_id) { EventListenerMap::accessor a; if (event_listeners_.find(a, event_type)) { return; } EventListenerList& listener_list = a->second; EventListenerList tmp; for_each(listener_list.begin(), listener_list.end(), [&tmp, &listener_id] (EventListener& list_listener) { if (list_listener.first == listener_id) { tmp.push_back(list_listener); } }); listener_list.swap(tmp); } void EventDispatcher::unsubscribe(const EventType& event_type) { EventListenerMap::accessor a; if (event_listeners_.find(a, event_type)) { return; } a->second.clear(); } bool EventDispatcher::trigger(std::shared_ptr<EventInterface> incoming_event) { const EventType& event_type = incoming_event->type(); if (!validateEventType_(event_type)) { assert(false && "Event was triggered before its type was registered"); return false; } EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { // No Listeners attached of this event type, do nothing. return false; } if (!incoming_event->timestamp()) { time_duration duration = microsec_clock::local_time().time_of_day(); incoming_event->timestamp(duration.total_milliseconds()); } EventListenerList& listener_list = a->second; bool processed = false; for_each(listener_list.begin(), listener_list.end(), [incoming_event, &processed] (EventListener& list_listener) { if (list_listener.second(incoming_event)) { processed = true; } }); return processed; } bool EventDispatcher::trigger(std::shared_ptr<EventInterface> incoming_event, PostTriggerCallback callback) { bool processed = trigger(incoming_event); callback(incoming_event, processed); return processed; } void EventDispatcher::triggerWhen(std::shared_ptr<EventInterface> incoming_event, TriggerCondition condition) { // Do a few quick sanity checks in debug mode to ensure our queue cycling is always on track. assert(active_queue_ >= 0); assert(active_queue_ < NUM_QUEUES); const EventType& event_type = incoming_event->type(); if (!validateEventType_(event_type)) { assert(false && "Event was triggered before its type was registered"); return; } EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return; } if (!incoming_event->timestamp()) { time_duration duration = microsec_clock::local_time().time_of_day(); incoming_event->timestamp(duration.total_milliseconds()); } uint32_t placement_queue = calculatePlacementQueue_(incoming_event->priority()); event_queues_[placement_queue].push(make_tuple(incoming_event, condition, boost::optional<PostTriggerCallback>())); } void EventDispatcher::triggerWhen(std::shared_ptr<EventInterface> incoming_event, TriggerCondition condition, PostTriggerCallback callback) { // Do a few quick sanity checks in debug mode to ensure our queue cycling is always on track. assert(active_queue_ >= 0); assert(active_queue_ < NUM_QUEUES); const EventType& event_type = incoming_event->type(); if (!validateEventType_(event_type)) { assert(false && "Event was triggered before its type was registered"); return; } EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return; } if (!incoming_event->timestamp()) { time_duration duration = microsec_clock::local_time().time_of_day(); incoming_event->timestamp(duration.total_milliseconds()); } uint32_t placement_queue = calculatePlacementQueue_(incoming_event->priority()); event_queues_[placement_queue].push(make_tuple(incoming_event, condition, callback)); } bool EventDispatcher::triggerAsync(std::shared_ptr<EventInterface> incoming_event) { // Do a few quick sanity checks in debug mode to ensure our queue cycling is always on track. assert(active_queue_ >= 0); assert(active_queue_ < NUM_QUEUES); const EventType& event_type = incoming_event->type(); if (!validateEventType_(event_type)) { assert(false && "Event was triggered before its type was registered"); return false; } EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return false; } if (!incoming_event->timestamp()) { time_duration duration = microsec_clock::local_time().time_of_day(); incoming_event->timestamp(duration.total_milliseconds()); } uint32_t placement_queue = calculatePlacementQueue_(incoming_event->priority()); event_queues_[placement_queue].push(make_tuple(incoming_event, boost::optional<TriggerCondition>(), boost::optional<PostTriggerCallback>())); return true; } bool EventDispatcher::triggerAsync(std::shared_ptr<EventInterface> incoming_event, PostTriggerCallback callback) { // Do a few quick sanity checks in debug mode to ensure our queue cycling is always on track. assert(active_queue_ >= 0); assert(active_queue_ < NUM_QUEUES); const EventType& event_type = incoming_event->type(); if (!validateEventType_(event_type)) { assert(false && "Event was triggered before its type was registered"); return false; } EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return false; } if (!incoming_event->timestamp()) { time_duration duration = microsec_clock::local_time().time_of_day(); incoming_event->timestamp(duration.total_milliseconds()); } uint32_t placement_queue = calculatePlacementQueue_(incoming_event->priority()); event_queues_[placement_queue].push(make_tuple(incoming_event, boost::optional<TriggerCondition>(), callback)); return true; } bool EventDispatcher::abort(const EventType& event_type, bool all_of_type) { // Do a few quick sanity checks in debug mode to ensure our queue cycling is always on track. assert(active_queue_ >= 0); assert(active_queue_ < NUM_QUEUES); if (!validateEventType_(event_type)) { assert(false && "Event was triggered before its type was registered"); return false; } // See if any events have registered for this type of event. EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return false; } bool removed = false; // cycle through each of the queues starting with the current for (uint32_t i = 0, current = 0; i < NUM_QUEUES; ++i) { // If we've already found an item and we're not search for all events break now. if (removed && !all_of_type) { break; } current = calculatePlacementQueue_(i); EventQueue tmp_queue = std::move(event_queues_[current]); event_queues_[current].clear(); // Only place items back in the queue as needed. for_each(tmp_queue.unsafe_begin(), tmp_queue.unsafe_end(), [this, current, &event_type, all_of_type, &removed] (EventQueueItem& queued_event) { if (!removed || all_of_type) { if (get<0>(queued_event)->type() == event_type) { removed = true; return; } } event_queues_[current].push(queued_event); }); } return removed; } bool EventDispatcher::tick(uint64_t timeout_ms) { // Create a new empty queue and swap it with the current active queue. int to_process = active_queue_; active_queue_ = (active_queue_ + 1) % NUM_QUEUES; ptime current_time = microsec_clock::local_time(); time_duration max_time = milliseconds(timeout_ms); time_period tick_period(current_time, current_time + max_time); EventQueueItem tick_event; uint32_t new_placement_queue = 0; while(!event_queues_[to_process].empty()) { if (!event_queues_[to_process].try_pop(tick_event)) { continue; } // Check to see if we have a conditional for our event and if so test it if (get<1>(tick_event).is_initialized()) { time_duration duration = microsec_clock::local_time().time_of_day(); if (!get<1>(tick_event).get()(duration.total_milliseconds())) { new_placement_queue = calculatePlacementQueue_(get<0>(tick_event)->priority()); // If the condition failed put the event back to wait. event_queues_[new_placement_queue].push(tick_event); continue; } } // If there was a callback given with the event call the appropriate trigger. if (get<2>(tick_event).is_initialized()) { trigger(get<0>(tick_event), get<2>(tick_event).get()); } else { trigger(get<0>(tick_event)); } if (timeout_ms == INFINITE_TIMEOUT) { continue; } current_time = microsec_clock::local_time(); if (current_time >= tick_period.end()) { break; } } bool queue_flushed = event_queues_[to_process].empty(); if (!queue_flushed) { while (!event_queues_[to_process].empty()) { if (event_queues_[to_process].try_pop(tick_event)) { new_placement_queue = calculatePlacementQueue_(get<0>(tick_event)->priority()); event_queues_[new_placement_queue].push(tick_event); } } } return queue_flushed; } bool EventDispatcher::validateEventType_(const EventType& event_type) const { if (! event_type.ident()) { return false; } return true; } uint32_t EventDispatcher::calculatePlacementQueue_(uint32_t priority) const { priority = min(priority, static_cast<uint32_t>(NUM_QUEUES)); return (active_queue_ + priority) % NUM_QUEUES; } <commit_msg>Regression fix from last commit.<commit_after>/* This file is part of MMOServer. For more information, visit http://swganh.com Copyright (c) 2006 - 2010 The SWG:ANH Team MMOServer 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. MMOServer 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 MMOServer. If not, see <http://www.gnu.org/licenses/>. */ #include "anh/event_dispatcher/event_dispatcher.h" #include <cassert> #include <algorithm> #include <boost/date_time/posix_time/posix_time.hpp> using namespace anh::event_dispatcher; using namespace boost::posix_time; using namespace std; EventDispatcher::EventDispatcher() : event_queues_(NUM_QUEUES) , active_queue_(0) { next_event_listener_id_.fetch_and_store(1); } EventDispatcher::~EventDispatcher() { active_queue_ = 0; } uint64_t EventDispatcher::subscribe(const EventType& event_type, EventListenerCallback listener) { if (!validateEventType_(event_type)) { throw anh::event_dispatcher::InvalidEventType( "Invalid event type specified"); } registerEventType(event_type); EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { // Check if there was an insertion failure if (!event_listeners_.insert(a,event_type)) { throw std::runtime_error("Insertion failure"); } a->second = EventListenerList(); } EventListenerList& listener_list = a->second; uint64_t next_listener_id = next_event_listener_id_.fetch_and_increment(); listener_list.push_back(make_pair(next_listener_id, listener)); return next_listener_id; } bool EventDispatcher::hasListeners(const EventType& event_type) const { EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return false; } const EventListenerList& listener_list = a->second; return !listener_list.empty(); } bool EventDispatcher::hasRegisteredEventType(const EventType& event_type) { boost::lock_guard<boost::recursive_mutex> lk(event_set_mutex_); if (registered_event_types_.find(event_type) != registered_event_types_.end()) { return true; } return false; } bool EventDispatcher::hasEvents() const { return !event_queues_[active_queue_].empty(); } void EventDispatcher::registerEventType(EventType event_type) { boost::lock_guard<boost::recursive_mutex> lk(event_set_mutex_); if (hasRegisteredEventType(event_type)) { return; } registered_event_types_.insert(std::move(event_type)); } EventTypeSet EventDispatcher::registered_event_types() const { return registered_event_types_; } void EventDispatcher::unsubscribe(const EventType& event_type, uint64_t listener_id) { EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return; } EventListenerList& listener_list = a->second; EventListenerList tmp; for_each(listener_list.begin(), listener_list.end(), [&tmp, &listener_id] (EventListener& list_listener) { if (list_listener.first != listener_id) { tmp.push_back(list_listener); } }); listener_list.swap(tmp); } void EventDispatcher::unsubscribe(const EventType& event_type) { EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return; } a->second.clear(); } bool EventDispatcher::trigger(std::shared_ptr<EventInterface> incoming_event) { const EventType& event_type = incoming_event->type(); if (!validateEventType_(event_type)) { assert(false && "Event was triggered before its type was registered"); return false; } EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { // No Listeners attached of this event type, do nothing. return false; } if (!incoming_event->timestamp()) { time_duration duration = microsec_clock::local_time().time_of_day(); incoming_event->timestamp(duration.total_milliseconds()); } EventListenerList& listener_list = a->second; bool processed = false; for_each(listener_list.begin(), listener_list.end(), [incoming_event, &processed] (EventListener& list_listener) { if (list_listener.second(incoming_event)) { processed = true; } }); return processed; } bool EventDispatcher::trigger(std::shared_ptr<EventInterface> incoming_event, PostTriggerCallback callback) { bool processed = trigger(incoming_event); callback(incoming_event, processed); return processed; } void EventDispatcher::triggerWhen(std::shared_ptr<EventInterface> incoming_event, TriggerCondition condition) { // Do a few quick sanity checks in debug mode to ensure our queue cycling is always on track. assert(active_queue_ >= 0); assert(active_queue_ < NUM_QUEUES); const EventType& event_type = incoming_event->type(); if (!validateEventType_(event_type)) { assert(false && "Event was triggered before its type was registered"); return; } EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return; } if (!incoming_event->timestamp()) { time_duration duration = microsec_clock::local_time().time_of_day(); incoming_event->timestamp(duration.total_milliseconds()); } uint32_t placement_queue = calculatePlacementQueue_(incoming_event->priority()); event_queues_[placement_queue].push(make_tuple(incoming_event, condition, boost::optional<PostTriggerCallback>())); } void EventDispatcher::triggerWhen(std::shared_ptr<EventInterface> incoming_event, TriggerCondition condition, PostTriggerCallback callback) { // Do a few quick sanity checks in debug mode to ensure our queue cycling is always on track. assert(active_queue_ >= 0); assert(active_queue_ < NUM_QUEUES); const EventType& event_type = incoming_event->type(); if (!validateEventType_(event_type)) { assert(false && "Event was triggered before its type was registered"); return; } EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return; } if (!incoming_event->timestamp()) { time_duration duration = microsec_clock::local_time().time_of_day(); incoming_event->timestamp(duration.total_milliseconds()); } uint32_t placement_queue = calculatePlacementQueue_(incoming_event->priority()); event_queues_[placement_queue].push(make_tuple(incoming_event, condition, callback)); } bool EventDispatcher::triggerAsync(std::shared_ptr<EventInterface> incoming_event) { // Do a few quick sanity checks in debug mode to ensure our queue cycling is always on track. assert(active_queue_ >= 0); assert(active_queue_ < NUM_QUEUES); const EventType& event_type = incoming_event->type(); if (!validateEventType_(event_type)) { assert(false && "Event was triggered before its type was registered"); return false; } EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return false; } if (!incoming_event->timestamp()) { time_duration duration = microsec_clock::local_time().time_of_day(); incoming_event->timestamp(duration.total_milliseconds()); } uint32_t placement_queue = calculatePlacementQueue_(incoming_event->priority()); event_queues_[placement_queue].push(make_tuple(incoming_event, boost::optional<TriggerCondition>(), boost::optional<PostTriggerCallback>())); return true; } bool EventDispatcher::triggerAsync(std::shared_ptr<EventInterface> incoming_event, PostTriggerCallback callback) { // Do a few quick sanity checks in debug mode to ensure our queue cycling is always on track. assert(active_queue_ >= 0); assert(active_queue_ < NUM_QUEUES); const EventType& event_type = incoming_event->type(); if (!validateEventType_(event_type)) { assert(false && "Event was triggered before its type was registered"); return false; } EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return false; } if (!incoming_event->timestamp()) { time_duration duration = microsec_clock::local_time().time_of_day(); incoming_event->timestamp(duration.total_milliseconds()); } uint32_t placement_queue = calculatePlacementQueue_(incoming_event->priority()); event_queues_[placement_queue].push(make_tuple(incoming_event, boost::optional<TriggerCondition>(), callback)); return true; } bool EventDispatcher::abort(const EventType& event_type, bool all_of_type) { // Do a few quick sanity checks in debug mode to ensure our queue cycling is always on track. assert(active_queue_ >= 0); assert(active_queue_ < NUM_QUEUES); if (!validateEventType_(event_type)) { assert(false && "Event was triggered before its type was registered"); return false; } // See if any events have registered for this type of event. EventListenerMap::accessor a; if (!event_listeners_.find(a, event_type)) { return false; } bool removed = false; // cycle through each of the queues starting with the current for (uint32_t i = 0, current = 0; i < NUM_QUEUES; ++i) { // If we've already found an item and we're not search for all events break now. if (removed && !all_of_type) { break; } current = calculatePlacementQueue_(i); EventQueue tmp_queue = std::move(event_queues_[current]); event_queues_[current].clear(); // Only place items back in the queue as needed. for_each(tmp_queue.unsafe_begin(), tmp_queue.unsafe_end(), [this, current, &event_type, all_of_type, &removed] (EventQueueItem& queued_event) { if (!removed || all_of_type) { if (get<0>(queued_event)->type() == event_type) { removed = true; return; } } event_queues_[current].push(queued_event); }); } return removed; } bool EventDispatcher::tick(uint64_t timeout_ms) { // Create a new empty queue and swap it with the current active queue. int to_process = active_queue_; active_queue_ = (active_queue_ + 1) % NUM_QUEUES; ptime current_time = microsec_clock::local_time(); time_duration max_time = milliseconds(timeout_ms); time_period tick_period(current_time, current_time + max_time); EventQueueItem tick_event; uint32_t new_placement_queue = 0; while(!event_queues_[to_process].empty()) { if (!event_queues_[to_process].try_pop(tick_event)) { continue; } // Check to see if we have a conditional for our event and if so test it if (get<1>(tick_event).is_initialized()) { time_duration duration = microsec_clock::local_time().time_of_day(); if (!get<1>(tick_event).get()(duration.total_milliseconds())) { new_placement_queue = calculatePlacementQueue_(get<0>(tick_event)->priority()); // If the condition failed put the event back to wait. event_queues_[new_placement_queue].push(tick_event); continue; } } // If there was a callback given with the event call the appropriate trigger. if (get<2>(tick_event).is_initialized()) { trigger(get<0>(tick_event), get<2>(tick_event).get()); } else { trigger(get<0>(tick_event)); } if (timeout_ms == INFINITE_TIMEOUT) { continue; } current_time = microsec_clock::local_time(); if (current_time >= tick_period.end()) { break; } } bool queue_flushed = event_queues_[to_process].empty(); if (!queue_flushed) { while (!event_queues_[to_process].empty()) { if (event_queues_[to_process].try_pop(tick_event)) { new_placement_queue = calculatePlacementQueue_(get<0>(tick_event)->priority()); event_queues_[new_placement_queue].push(tick_event); } } } return queue_flushed; } bool EventDispatcher::validateEventType_(const EventType& event_type) const { if (! event_type.ident()) { return false; } return true; } uint32_t EventDispatcher::calculatePlacementQueue_(uint32_t priority) const { priority = min(priority, static_cast<uint32_t>(NUM_QUEUES)); return (active_queue_ + priority) % NUM_QUEUES; } <|endoftext|>
<commit_before>#include <nan.h> #include "env-rocks.h" using namespace v8; using namespace rocksdb; namespace kv { namespace rocks { void env::setup_export(v8::Handle<v8::Object>& exports) { // Prepare constructor template Local<FunctionTemplate> envTpl = NanNew<FunctionTemplate>(env::ctor); envTpl->SetClassName(NanNew("Env")); envTpl->InstanceTemplate()->SetInternalFieldCount(1); // Add functions to the prototype NODE_SET_PROTOTYPE_METHOD(envTpl, "open", env::open); // Set exports exports->Set(NanNew("Env"), envTpl->GetFunction()); } NAN_METHOD(env::ctor) { NanScope(); env* ptr = new env(); ptr->Wrap(args.This()); NanReturnValue(args.This()); } NAN_METHOD(env::open) { NanScope(); env* envw = node::ObjectWrap::Unwrap<env>(args.This()); NanUtf8String path(args[0]); DB* pdb; Options opt; opt.create_if_missing = true; if (args[1]->IsNumber()) opt.write_buffer_size = size_t(args[1]->NumberValue()); Status s = DB::Open(opt, *path, envw->_desc, &envw->_handles, &pdb); if (!s.ok()) { NanThrowError(s.ToString().c_str()); NanReturnUndefined(); } envw->_db = pdb; NanReturnUndefined(); } env::env() : _db(NULL) { } env::~env() { delete _db; } int env::register_db(const ColumnFamilyDescriptor& desc) { _desc.push_back(desc); return _desc.size() - 1; } } } // namespace kv | namespace rocks <commit_msg>add default column when init rocksdb env.<commit_after>#include <nan.h> #include "env-rocks.h" using namespace v8; using namespace rocksdb; namespace kv { namespace rocks { void env::setup_export(v8::Handle<v8::Object>& exports) { // Prepare constructor template Local<FunctionTemplate> envTpl = NanNew<FunctionTemplate>(env::ctor); envTpl->SetClassName(NanNew("Env")); envTpl->InstanceTemplate()->SetInternalFieldCount(1); // Add functions to the prototype NODE_SET_PROTOTYPE_METHOD(envTpl, "open", env::open); // Set exports exports->Set(NanNew("Env"), envTpl->GetFunction()); } NAN_METHOD(env::ctor) { NanScope(); env* ptr = new env(); ptr->Wrap(args.This()); NanReturnValue(args.This()); } NAN_METHOD(env::open) { NanScope(); env* envw = node::ObjectWrap::Unwrap<env>(args.This()); NanUtf8String path(args[0]); DB* pdb; Options opt; opt.create_if_missing = true; if (args[1]->IsNumber()) opt.write_buffer_size = size_t(args[1]->NumberValue()); Status s = DB::Open(opt, *path, envw->_desc, &envw->_handles, &pdb); if (!s.ok()) { NanThrowError(s.ToString().c_str()); NanReturnUndefined(); } envw->_db = pdb; NanReturnUndefined(); } env::env() : _db(NULL) { _desc.push_back(ColumnFamilyDescriptor(kDefaultColumnFamilyName, ColumnFamilyOptions())); } env::~env() { delete _db; } int env::register_db(const ColumnFamilyDescriptor& desc) { _desc.push_back(desc); return _desc.size() - 1; } } } // namespace kv | namespace rocks <|endoftext|>
<commit_before>/* Compile with: * g++ -Wall -Wextra -Werror -std=gnu++11 -o tlist tlist.cpp */ #include <iostream> #include <cassert> #include <string> template<int T, class U> struct tlist { typedef int head; typedef U tail; }; struct null_type {}; template<class tlist> struct length; template<> struct length<null_type> { enum { value = 0 }; }; template<int T, class U> struct length<tlist<T,U> > { enum { value = 1 + length<U>::value }; }; template<class tlist> struct sum; template<> struct sum<null_type> { enum { value = 0 }; }; template<int T, class U> struct sum<tlist<T,U> > { enum { value = T + sum<U>::value }; }; template<class tlist1, class tlist2> struct concat; template<class tlist2> struct concat<null_type, tlist2> { typedef tlist2 result; }; template<int T, class U, class tlist2> struct concat<tlist<T,U>, tlist2> { private: typedef typename concat<U, tlist2>::result tail; public: typedef tlist<T, tail> result; }; template<bool B, class T, class U> struct take; template<class T, class U> struct take<true, T, U> { typedef T result; }; template<class T, class U> struct take<false, T, U> { typedef U result; }; template<class tlist, int F> struct filter_less; template<int F> struct filter_less<null_type, F> { typedef null_type result; }; template<int T, class U, int F> struct filter_less<tlist<T,U>, F> { private: typedef typename filter_less<U, F>::result tail; public: typedef typename take<(F < T), tlist<T, tail>, tail>::result result; }; template<class tlist, int F> struct filter_ge; template<int F> struct filter_ge<null_type, F> { typedef null_type result; }; template<int T, class U, int F> struct filter_ge<tlist<T,U>, F> { private: typedef typename filter_ge<U, F>::result tail; public: typedef typename take<(F >= T), tlist<T, tail>, tail>::result result; }; template<class tlist> struct quicksort; template<> struct quicksort<null_type> { typedef null_type result; }; template<int T, class U> struct quicksort<tlist<T,U> > { private: typedef typename quicksort<typename filter_less<U, T>::result >::result left; typedef typename quicksort<typename filter_ge<U, T>::result >::result right; public: typedef typename concat<left, tlist<T, right> >::result result; }; int main(int argc, char const* argv[]) { assert(argc==1); assert(argv[0]); typedef tlist<1, tlist<5, tlist<2, null_type> > > numlist; typedef tlist<7, numlist> numlist2; std::cout << "length 1: " << length<numlist>::value << std::endl; std::cout << "length 2: " << length<numlist2>::value << std::endl; std::cout << "sum 1: " << sum<numlist>::value << std::endl; std::cout << "sum 2: " << sum<numlist2>::value << std::endl; std::cout << "filtered sum 1: " << sum<filter_less<numlist2, 4>::result>::value << std::endl; typedef concat<numlist, numlist2>::result combined; std::cout << "sum combined: " << sum<combined>::value << std::endl; return 0; } <commit_msg>concat reverses left-right<commit_after>/* Compile with: * g++ -Wall -Wextra -Werror -std=gnu++11 -o tlist tlist.cpp */ #include <iostream> #include <cassert> #include <string> template<int T, class U> struct tlist { typedef int head; typedef U tail; }; struct null_type {}; template<class tlist> struct length; template<> struct length<null_type> { enum { value = 0 }; }; template<int T, class U> struct length<tlist<T,U> > { enum { value = 1 + length<U>::value }; }; template<class tlist> struct sum; template<> struct sum<null_type> { enum { value = 0 }; }; template<int T, class U> struct sum<tlist<T,U> > { enum { value = T + sum<U>::value }; }; template<class tlist1, class tlist2> struct concat; template<class tlist2> struct concat<null_type, tlist2> { typedef tlist2 result; }; template<int T, class U, class tlist2> struct concat<tlist<T,U>, tlist2> { private: typedef typename concat<U, tlist2>::result tail; public: typedef tlist<T, tail> result; }; template<bool B, class T, class U> struct take; template<class T, class U> struct take<true, T, U> { typedef T result; }; template<class T, class U> struct take<false, T, U> { typedef U result; }; template<class tlist, int F> struct filter_less; template<int F> struct filter_less<null_type, F> { typedef null_type result; }; template<int T, class U, int F> struct filter_less<tlist<T,U>, F> { private: typedef typename filter_less<U, F>::result tail; public: typedef typename take<(F < T), tlist<T, tail>, tail>::result result; }; template<class tlist, int F> struct filter_ge; template<int F> struct filter_ge<null_type, F> { typedef null_type result; }; template<int T, class U, int F> struct filter_ge<tlist<T,U>, F> { private: typedef typename filter_ge<U, F>::result tail; public: typedef typename take<(F >= T), tlist<T, tail>, tail>::result result; }; template<class tlist> struct quicksort; template<> struct quicksort<null_type> { typedef null_type result; }; template<int T, class U> struct quicksort<tlist<T,U> > { private: typedef typename quicksort<typename filter_less<U, T>::result >::result right; typedef typename quicksort<typename filter_ge<U, T>::result >::result left; public: typedef typename concat<left, tlist<T, right> >::result result; }; int main(int argc, char const* argv[]) { assert(argc==1); assert(argv[0]); typedef tlist<1, tlist<5, tlist<2, null_type> > > numlist; typedef tlist<7, numlist> numlist2; std::cout << "length 1: " << length<numlist>::value << std::endl; std::cout << "length 2: " << length<numlist2>::value << std::endl; std::cout << "sum 1: " << sum<numlist>::value << std::endl; std::cout << "sum 2: " << sum<numlist2>::value << std::endl; std::cout << "filtered sum 1: " << sum<filter_less<numlist2, 4>::result>::value << std::endl; typedef concat<numlist, numlist2>::result combined; std::cout << "sum combined: " << sum<combined>::value << std::endl; return 0; } <|endoftext|>
<commit_before>//=========================================== // Lumina-DE source code // Copyright (c) 2012, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "WMProcess.h" #include "LSession.h" WMProcess::WMProcess() : QProcess(){ connect(this,SIGNAL(finished(int, QProcess::ExitStatus)),this,SLOT(processFinished(int, QProcess::ExitStatus)) ); this->setProcessChannelMode(QProcess::MergedChannels); QString log = QDir::homePath()+"/.lumina/logs/wm.log"; if(QFile::exists(log)){ QFile::remove(log); } this->setStandardOutputFile(log); ssaver = new QProcess(0); inShutdown = false; } WMProcess::~WMProcess(){ } // ======================= // PUBLIC FUNCTIONS // ======================= void WMProcess::startWM(){ inShutdown = false; QString cmd = setupWM(); this->start(cmd); ssaver->start("xscreensaver -no-splash"); } void WMProcess::stopWM(){ if(isRunning()){ inShutdown = true; //QProcess::startDetached("fluxbox-remote closeallwindows"); ssaver->kill(); this->kill(); if(!this->waitForFinished(10000)){ this->terminate(); }; }else{ qWarning() << "WM already closed - did it crash?"; } } void WMProcess::updateWM(){ if(isRunning()){ ::kill(this->pid(), SIGUSR2); //send fluxbox the signal to reload it's configuration } } // ======================= // PRIVATE FUNCTIONS // ======================= bool WMProcess::isRunning(){ return (this->state() != QProcess::NotRunning); } QString WMProcess::setupWM(){ QString WM = LSession::sessionSettings()->value("WindowManager", "fluxbox").toString(); QString cmd="echo WM Disabled"; //leave the option to add other window managers here (for testing purposes) if(WM=="openbox"){ QString confDir = QDir::homePath()+"/.config/openbox"; if(!QFile::exists(confDir)){ QDir dir(confDir); dir.mkpath(confDir); } if(!QFile::exists(confDir+"lumina-rc.xml")){ QFile::copy(":/openboxconf/lumina-rc.xml",confDir+"/lumina-rc.xml"); QFile::setPermissions(confDir+"/lumina-rc.xml", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup); } if(!QFile::exists(confDir+"lumina-menu.xml")){ QFile::copy(":/openboxconf/lumina-menu.xml",confDir+"/lumina-menu.xml"); QFile::setPermissions(confDir+"/lumina-menu.xml", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup); } //Now copy the configuration files around as necessary //if(QFile::exists(confDir+"/rc.xml")){ QFile::rename(confDir+"/rc.xml",confDir+"/openbox-rc.xml"); } //QFile::copy(confDir+"/lumina-rc.xml",confDir+"/rc.xml"); cmd = "openbox --debug --sm-disable --config-file "+confDir+"/lumina-rc.xml"; }else if(WM=="fluxbox"){ QString confDir = QDir::homePath()+"/.lumina"; if(!QFile::exists(confDir)){ QDir dir(confDir); dir.mkpath(confDir); } if(!QFile::exists(confDir+"/fluxbox-init")){ QFile::copy(":/fluxboxconf/fluxbox-init-rc",confDir+"/fluxbox-init"); QFile::setPermissions(confDir+"/fluxbox-init", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup); } /*if(!QFile::exists(confDir+"lumina-menu.xml")){ QFile::copy(":/openboxconf/lumina-menu.xml",confDir+"/lumina-menu.xml"); QFile::setPermissions(confDir+"/lumina-menu.xml", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup); }*/ cmd = "fluxbox -rc "+confDir+"/fluxbox-init"; }else { cmd = WM; } return cmd; } void WMProcess::cleanupConfig(){ //QString confDir = QDir::homePath()+"/.config/openbox"; //if(!QFile::exists(confDir+"/rc.xml")){ return; } //Make sure that there is a current config file //if(QFile::exists(confDir+"/lumina-rc.xml")){ QFile::remove(confDir+"/lumina-rc.xml"); } //QFile::rename(confDir+"/rc.xml",confDir+"/lumina-rc.xml"); //if(QFile::exists(confDir+"/openbox-rc.xml")){ QFile::rename(confDir+"/openbox-rc.xml",confDir+"/rc.xml"); } } // ======================= // PRIVATE SLOTS // ======================= void WMProcess::processFinished(int exitcode, QProcess::ExitStatus status){ if(!inShutdown){ if(exitcode == 0 && status == QProcess::NormalExit){ cleanupConfig(); emit WMShutdown(); }else{ //restart the Window manager this->startWM(); } }else{ cleanupConfig(); } } <commit_msg>Add a workaround for a fluxbox bug: If the ~/.fluxbox directory does not exist, Fluxbox will ignore the given config file. So make sure that directory exists before starting Fluxbox.<commit_after>//=========================================== // Lumina-DE source code // Copyright (c) 2012, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "WMProcess.h" #include "LSession.h" WMProcess::WMProcess() : QProcess(){ connect(this,SIGNAL(finished(int, QProcess::ExitStatus)),this,SLOT(processFinished(int, QProcess::ExitStatus)) ); this->setProcessChannelMode(QProcess::MergedChannels); QString log = QDir::homePath()+"/.lumina/logs/wm.log"; if(QFile::exists(log)){ QFile::remove(log); } this->setStandardOutputFile(log); ssaver = new QProcess(0); inShutdown = false; } WMProcess::~WMProcess(){ } // ======================= // PUBLIC FUNCTIONS // ======================= void WMProcess::startWM(){ inShutdown = false; QString cmd = setupWM(); this->start(cmd); ssaver->start("xscreensaver -no-splash"); } void WMProcess::stopWM(){ if(isRunning()){ inShutdown = true; //QProcess::startDetached("fluxbox-remote closeallwindows"); ssaver->kill(); this->kill(); if(!this->waitForFinished(10000)){ this->terminate(); }; }else{ qWarning() << "WM already closed - did it crash?"; } } void WMProcess::updateWM(){ if(isRunning()){ ::kill(this->pid(), SIGUSR2); //send fluxbox the signal to reload it's configuration } } // ======================= // PRIVATE FUNCTIONS // ======================= bool WMProcess::isRunning(){ return (this->state() != QProcess::NotRunning); } QString WMProcess::setupWM(){ QString WM = LSession::sessionSettings()->value("WindowManager", "fluxbox").toString(); QString cmd="echo WM Disabled"; //leave the option to add other window managers here (for testing purposes) if(WM=="openbox"){ QString confDir = QDir::homePath()+"/.config/openbox"; if(!QFile::exists(confDir)){ QDir dir(confDir); dir.mkpath(confDir); } if(!QFile::exists(confDir+"lumina-rc.xml")){ QFile::copy(":/openboxconf/lumina-rc.xml",confDir+"/lumina-rc.xml"); QFile::setPermissions(confDir+"/lumina-rc.xml", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup); } if(!QFile::exists(confDir+"lumina-menu.xml")){ QFile::copy(":/openboxconf/lumina-menu.xml",confDir+"/lumina-menu.xml"); QFile::setPermissions(confDir+"/lumina-menu.xml", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup); } //Now copy the configuration files around as necessary //if(QFile::exists(confDir+"/rc.xml")){ QFile::rename(confDir+"/rc.xml",confDir+"/openbox-rc.xml"); } //QFile::copy(confDir+"/lumina-rc.xml",confDir+"/rc.xml"); cmd = "openbox --debug --sm-disable --config-file "+confDir+"/lumina-rc.xml"; }else if(WM=="fluxbox"){ QString confDir = QDir::homePath()+"/.lumina"; if(!QFile::exists(confDir)){ QDir dir(confDir); dir.mkpath(confDir); } if(!QFile::exists(confDir+"/fluxbox-init")){ QFile::copy(":/fluxboxconf/fluxbox-init-rc",confDir+"/fluxbox-init"); QFile::setPermissions(confDir+"/fluxbox-init", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup); } // FLUXBOX BUG BYPASS: if the ~/.fluxbox dir does not exist, it will ignore the given config file if(!QFile::exists(QDir::homePath()+"/.fluxbox")){ QDir dir; dir.mkpath(QDir::homePath()+"/.fluxbox"); } cmd = "fluxbox -rc "+confDir+"/fluxbox-init"; }else { cmd = WM; } return cmd; } void WMProcess::cleanupConfig(){ //QString confDir = QDir::homePath()+"/.config/openbox"; //if(!QFile::exists(confDir+"/rc.xml")){ return; } //Make sure that there is a current config file //if(QFile::exists(confDir+"/lumina-rc.xml")){ QFile::remove(confDir+"/lumina-rc.xml"); } //QFile::rename(confDir+"/rc.xml",confDir+"/lumina-rc.xml"); //if(QFile::exists(confDir+"/openbox-rc.xml")){ QFile::rename(confDir+"/openbox-rc.xml",confDir+"/rc.xml"); } } // ======================= // PRIVATE SLOTS // ======================= void WMProcess::processFinished(int exitcode, QProcess::ExitStatus status){ if(!inShutdown){ if(exitcode == 0 && status == QProcess::NormalExit){ cleanupConfig(); emit WMShutdown(); }else{ //restart the Window manager this->startWM(); } }else{ cleanupConfig(); } } <|endoftext|>
<commit_before>#pragma once #include <string> #include <sstream> #include "But/assert.hpp" #include "detail/parse.hpp" #include "detail/argumentsCount.hpp" #include "detail/allArgumentsUsed.hpp" #include "But/Log/Backend/toValue.hpp" #include "But/Log/Backend/toType.hpp" #include "Invalid.hpp" #include "detail/StreamVisitor.hpp" namespace But { namespace Format { /** @brief represents a parsed format, from a given text with. set of parameters can be applied to get a final message. * @note format of the parameter is defined by its type, via toValue() function. it * is not specified for a given type usage. this way formatting for a given parameters * is always constant. */ template<size_t ArgumentsCount, size_t MaxSegments> class Parsed final { public: /** @brief parses input format and constructs the object. * @param format - format is a string with positional arguments, in a form: * $N - expands to N-th argument. * ${N} - the same as $N. * ${N#some text} - the same as $N, but allowing some textual description along (useful for translations!). * ${TN} - prints type of N-th argument, using toType() function and ADL. * ${TN#some text} - the same as ${TN}, but allowing some textual description along (useful for translations!). * ${VN} - the same as $N. * ${VN#some text} - the same as $N, but allowing some textual description along (useful for translations!). * $$ - liternal '$' character. * @note all numbers are 0-based (i.e. 1st argument has index 0). */ constexpr explicit Parsed(char const* format): ps_{ detail::parseCt<MaxSegments>(format) }, format_{format} { } constexpr auto inputFormat() const { return format_; } //constexpr auto expectedArguments() const { return detail::argumentsCount(ps_); } // note: would not work with static_assert... static constexpr auto expectedArguments() { return ArgumentsCount; } template<typename ...Args> std::string format(Args const& ...args) const { static_assert( sizeof...(args) == expectedArguments(), "arity missmatch between provided format and arguments to be formated" ); BUT_ASSERT( expectedArguments() == detail::argumentsCount(ps_) ); std::ostringstream os; for(auto& e: ps_.segments_) formatBlock(os, e, args...); return os.str(); } private: template<typename F> void processArgument(F&& /*f*/, const size_t /*pos*/) const { BUT_ASSERT(!"this overload should never really be called"); std::terminate(); } template<typename F, typename Head> void processArgument(F&& f, const size_t pos, Head const& head) const { (void)pos; BUT_ASSERT( pos == 0u && "format is not alligned with arguments" ); f(head); } template<typename F, typename Head, typename ...Tail> void processArgument(F&& f, const size_t pos, Head const& head, Tail const& ...tail) const { // TODO: replace this with a compile-time-generated construct... if( pos == 0u ) f(head); else processArgument( std::forward<F>(f), pos-1u, tail... ); } template<typename ...Args> void streamArgumentType(std::ostream& os, const size_t pos, Args const& ...args) const { auto proc = [&os](auto& e) { using Log::Backend::toType; os << toType(e); }; processArgument(proc, pos, args... ); } template<typename ...Args> void streamArgumentValue(std::ostream& os, const size_t pos, Args const& ...args) const { auto proc = [&os](auto& e) { using Log::Backend::toValue; toValue(e).visit( detail::StreamVisitor{&os} ); }; processArgument( proc, pos, args... ); } template<typename ...Args> void formatBlock(std::ostringstream& os, detail::Segment const& segment, Args const& ...args) const { switch(segment.type_) { case detail::Segment::Type::String: os.write( segment.begin_, segment.end_ - segment.begin_ ); return; case detail::Segment::Type::Value: streamArgumentValue(os, segment.referencedArgument_, args...); return; case detail::Segment::Type::TypeName: streamArgumentType(os, segment.referencedArgument_, args...); return; } BUT_ASSERT(!"missing type handle"); } const detail::ParsedFormatCt<MaxSegments> ps_; char const* format_; }; template<size_t N, size_t M> std::string toValue(Parsed<N,M> const&) = delete; template<size_t N, size_t M> std::string toType(Parsed<N,M> const&) = delete; } } <commit_msg>temporary removed all the code for formatting<commit_after>#pragma once #include <string> #include <sstream> #include "But/assert.hpp" #include "detail/parse.hpp" #include "detail/argumentsCount.hpp" #include "detail/allArgumentsUsed.hpp" #include "Invalid.hpp" #include "detail/StreamVisitor.hpp" namespace But { namespace Format { /** @brief represents a parsed format, from a given text with. set of parameters can be applied to get a final message. * @note format of the parameter is defined by its type, via toFieldInfo() function. it * is not specified for a given type usage. this way formatting for a given parameters * is always constant. */ template<size_t ArgumentsCount, size_t MaxSegments> class Parsed final { public: /** @brief parses input format and constructs the object. * @param format - format is a string with positional arguments, in a form: * $N - expands to N-th argument. * ${N} - the same as $N. * ${N#some text} - the same as $N, but allowing some textual description along (useful for translations!). * ${TN} - prints type of N-th argument, using toFieldInfo().type() function and ADL. * ${TN#some text} - the same as ${TN}, but allowing some textual description along (useful for translations!). * ${VN} - the same as $N. * ${VN#some text} - the same as $N, but allowing some textual description along (useful for translations!). * $$ - liternal '$' character. * @note all numbers are 0-based (i.e. 1st argument has index 0). */ constexpr explicit Parsed(char const* format): ps_{ detail::parseCt<MaxSegments>(format) }, format_{format} { } constexpr auto inputFormat() const { return format_; } //constexpr auto expectedArguments() const { return detail::argumentsCount(ps_); } // note: would not work with static_assert... static constexpr auto expectedArguments() { return ArgumentsCount; } template<typename ...Args> std::string format(Args const& ...args) const { static_assert( sizeof...(args) == expectedArguments(), "arity missmatch between provided format and arguments to be formated" ); BUT_ASSERT( expectedArguments() == detail::argumentsCount(ps_) ); std::ostringstream os; for(auto& e: ps_.segments_) formatBlock(os, e, args...); return os.str(); } private: template<typename F> void processArgument(F&& /*f*/, const size_t /*pos*/) const { BUT_ASSERT(!"this overload should never really be called"); std::terminate(); } template<typename F, typename Head> void processArgument(F&& f, const size_t pos, Head const& head) const { (void)pos; BUT_ASSERT( pos == 0u && "format is not alligned with arguments" ); f(head); } template<typename F, typename Head, typename ...Tail> void processArgument(F&& f, const size_t pos, Head const& head, Tail const& ...tail) const { // TODO: replace this with a compile-time-generated construct... if( pos == 0u ) f(head); else processArgument( std::forward<F>(f), pos-1u, tail... ); } template<typename ...Args> void streamArgumentType(std::ostream& os, const size_t pos, Args const& .../*args*/) const { // TODO.... (void)os; (void)pos; /* auto proc = [&os](auto& e) { using Log::Backend::toType; os << toType(e); }; processArgument(proc, pos, args... ); */ } template<typename ...Args> void streamArgumentValue(std::ostream& os, const size_t pos, Args const& .../*args*/) const { // TODO.... (void)os; (void)pos; /* auto proc = [&os](auto& e) { using Log::Backend::toValue; toValue(e).visit( detail::StreamVisitor{&os} ); }; processArgument( proc, pos, args... ); */ } template<typename ...Args> void formatBlock(std::ostringstream& os, detail::Segment const& segment, Args const& ...args) const { switch(segment.type_) { case detail::Segment::Type::String: os.write( segment.begin_, segment.end_ - segment.begin_ ); return; case detail::Segment::Type::Value: streamArgumentValue(os, segment.referencedArgument_, args...); return; case detail::Segment::Type::TypeName: streamArgumentType(os, segment.referencedArgument_, args...); return; } BUT_ASSERT(!"missing type handle"); } const detail::ParsedFormatCt<MaxSegments> ps_; char const* format_; }; template<size_t N, size_t M> std::string toValue(Parsed<N,M> const&) = delete; template<size_t N, size_t M> std::string toType(Parsed<N,M> const&) = delete; } } <|endoftext|>
<commit_before><commit_msg>Addressed review comments (MLDB-1738)<commit_after><|endoftext|>
<commit_before>#include "Client.h" #include "../Service/Exception/Exception.h" using namespace qReal; using namespace client; Client::Client() { loadFromDisk(); } Client::~Client() { saveToDisk(); } IdTypeList Client::children( IdType id ) { if (mObjects.contains(id)) { return mObjects[id]->children(); } else { throw Exception("Client: Requesting children of nonexistent object " + id); } } IdTypeList Client::parents( IdType id ) { if (mObjects.contains(id)) { return mObjects[id]->parents(); } else { throw Exception("Client: Requesting parents of nonexistent object " + id); } } void Client::addParent( IdType id, IdType parent ) { if (mObjects.contains(id)) { mObjects[id]->addParent(parent); } else { throw Exception("Client: Adding parent " + parent + " to nonexistent object " + id); } } void Client::addChild( IdType id, IdType child ) { if (id=="") { mObjects.insert(child,new LogicObject(child,"")); } else { if (mObjects.contains(id)) { mObjects[id]->addChild(child); if (mObjects.contains(child)) { mObjects[child]->addParent(id); } else { mObjects.insert(child,new LogicObject(child,id)); } } else { throw Exception("Client: Adding child " + child + " to nonexistent object " + id); } } } void Client::removeParent( IdType id, IdType parent ) { if (mObjects.contains(id)) { mObjects[id]->removeParent(parent); } else { throw Exception("Client: Removing parent " + parent + " from nonexistent object " + id); } } void Client::removeChild( IdType id, IdType child ) { if (mObjects.contains(id)) { mObjects[id]->removeChild(child); } else { throw Exception("Client: removing child " + child + " from nonexistent object " + id); } } void Client::setProperty( IdType id, PropertyType type, QVariant value ) { if (mObjects.contains(id)) { mObjects[id]->setProperty(type,value); } else { throw Exception("Client: Setting property of nonexistent object " + id); } } void Client::property( IdType id, PropertyType type ) { if (mObjects.contains(id)) { mObjects[id]->property(type); } else { throw Exception("Client: Requesting property of nonexistent object " + id); } } void Client::loadFromDisk() { } void Client::saveToDisk() { }<commit_msg>Logical structure of new client improved<commit_after>#include "Client.h" #include "../Service/Exception/Exception.h" using namespace qReal; using namespace client; Client::Client() { loadFromDisk(); } Client::~Client() { saveToDisk(); } IdTypeList Client::children( IdType id ) { if (mObjects.contains(id)) { return mObjects[id]->children(); } else { throw Exception("Client: Requesting children of nonexistent object " + id); } } IdTypeList Client::parents( IdType id ) { if (mObjects.contains(id)) { return mObjects[id]->parents(); } else { throw Exception("Client: Requesting parents of nonexistent object " + id); } } void Client::addParent( IdType id, IdType parent ) { if (mObjects.contains(id)) { if (mObjects.contains(parent)) { mObjects[id]->addParent(parent); mObjects[parent]->addChild(id); } else { throw Exception("Client: Adding nonexistent parent " + parent + " to object " + id); } } else { throw Exception("Client: Adding parent " + parent + " to nonexistent object " + id); } } void Client::addChild( IdType id, IdType child ) { if (id=="") { mObjects.insert(child,new LogicObject(child,"")); } else { if (mObjects.contains(id)) { mObjects[id]->addChild(child); if (mObjects.contains(child)) { mObjects[child]->addParent(id); } else { mObjects.insert(child,new LogicObject(child,id)); } } else { throw Exception("Client: Adding child " + child + " to nonexistent object " + id); } } } void Client::removeParent( IdType id, IdType parent ) { if (mObjects.contains(id)) { if (mObjects.contains(parent)) { mObjects[id]->removeParent(parent); mObjects[parent]->removeChild(id); } else { throw Exception("Client: Removing nonexistent parent " + parent + " from object " + id); } } else { throw Exception("Client: Removing parent " + parent + " from nonexistent object " + id); } } void Client::removeChild( IdType id, IdType child ) { if (mObjects.contains(id)) { if (mObjects.contains(child)) { mObjects[id]->removeChild(child); if (mObjects[child]->parents().size()!=1) { mObjects[child]->removeParent(id); } else { if (mObjects[child]->parents().first()==id) { delete mObjects[child]; mObjects.remove(child); } else { throw Exception("Client: removing child " + child + " from object " + id + ", which is not his parent"); } } } else { throw Exception("Client: removing nonexistent child " + child + " from object " + id); } } else { throw Exception("Client: removing child " + child + " from nonexistent object " + id); } } void Client::setProperty( IdType id, PropertyType type, QVariant value ) { if (mObjects.contains(id)) { mObjects[id]->setProperty(type,value); } else { throw Exception("Client: Setting property of nonexistent object " + id); } } void Client::property( IdType id, PropertyType type ) { if (mObjects.contains(id)) { mObjects[id]->property(type); } else { throw Exception("Client: Requesting property of nonexistent object " + id); } } void Client::loadFromDisk() { } void Client::saveToDisk() { }<|endoftext|>
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/session.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; struct entry_to_python { static object convert(entry::list_type const& l) { list result; for (entry::list_type::const_iterator i(l.begin()), e(l.end()); i != e; ++i) { result.append(*i); } return result; } static object convert(entry::dictionary_type const& d) { dict result; for (entry::dictionary_type::const_iterator i(d.begin()), e(d.end()); i != e; ++i) result[i->first] = i->second; return result; } static object convert0(entry const& e) { switch (e.type()) { case entry::int_t: return object(e.integer()); case entry::string_t: return object(e.string()); case entry::list_t: return convert(e.list()); case entry::dictionary_t: return convert(e.dict()); default: return object(); } } static PyObject* convert(entry const& e) { return incref(convert0(e).ptr()); } }; struct entry_from_python { entry_from_python() { converter::registry::push_back( &convertible, &construct, type_id<entry>() ); } static void* convertible(PyObject* e) { return e; } static entry construct0(object e) { if (extract<dict>(e).check()) { dict d = extract<dict>(e); list items(d.items()); std::size_t length = extract<std::size_t>(items.attr("__len__")()); entry result(entry::dictionary_t); for (std::size_t i = 0; i < length; ++i) { result.dict().insert( std::make_pair( extract<char const*>(items[i][0])() , construct0(items[i][1]) ) ); } return result; } else if (extract<list>(e).check()) { list l = extract<list>(e); std::size_t length = extract<std::size_t>(l.attr("__len__")()); entry result(entry::list_t); for (std::size_t i = 0; i < length; ++i) { result.list().push_back(construct0(l[i])); } return result; } else if (extract<str>(e).check()) { return entry(extract<std::string>(e)()); } else if (extract<entry::integer_type>(e).check()) { return entry(extract<entry::integer_type>(e)()); } return entry(); } static void construct(PyObject* e, converter::rvalue_from_python_stage1_data* data) { void* storage = ((converter::rvalue_from_python_storage<entry>*)data)->storage.bytes; new (storage) entry(construct0(object(borrowed(e)))); data->convertible = storage; } }; void bind_entry() { to_python_converter<entry, entry_to_python>(); entry_from_python(); } <commit_msg>Register to_python converter for shared_ptr<entry><commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/session.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; struct entry_to_python { static object convert(entry::list_type const& l) { list result; for (entry::list_type::const_iterator i(l.begin()), e(l.end()); i != e; ++i) { result.append(*i); } return result; } static object convert(entry::dictionary_type const& d) { dict result; for (entry::dictionary_type::const_iterator i(d.begin()), e(d.end()); i != e; ++i) result[i->first] = i->second; return result; } static object convert0(entry const& e) { switch (e.type()) { case entry::int_t: return object(e.integer()); case entry::string_t: return object(e.string()); case entry::list_t: return convert(e.list()); case entry::dictionary_t: return convert(e.dict()); default: return object(); } } static PyObject* convert(boost::shared_ptr<entry> const& e) { if (!e) return incref(Py_None); return convert(*e); } static PyObject* convert(entry const& e) { return incref(convert0(e).ptr()); } }; struct entry_from_python { entry_from_python() { converter::registry::push_back( &convertible, &construct, type_id<entry>() ); } static void* convertible(PyObject* e) { return e; } static entry construct0(object e) { if (extract<dict>(e).check()) { dict d = extract<dict>(e); list items(d.items()); std::size_t length = extract<std::size_t>(items.attr("__len__")()); entry result(entry::dictionary_t); for (std::size_t i = 0; i < length; ++i) { result.dict().insert( std::make_pair( extract<char const*>(items[i][0])() , construct0(items[i][1]) ) ); } return result; } else if (extract<list>(e).check()) { list l = extract<list>(e); std::size_t length = extract<std::size_t>(l.attr("__len__")()); entry result(entry::list_t); for (std::size_t i = 0; i < length; ++i) { result.list().push_back(construct0(l[i])); } return result; } else if (extract<str>(e).check()) { return entry(extract<std::string>(e)()); } else if (extract<entry::integer_type>(e).check()) { return entry(extract<entry::integer_type>(e)()); } return entry(); } static void construct(PyObject* e, converter::rvalue_from_python_stage1_data* data) { void* storage = ((converter::rvalue_from_python_storage<entry>*)data)->storage.bytes; new (storage) entry(construct0(object(borrowed(e)))); data->convertible = storage; } }; void bind_entry() { to_python_converter<boost::shared_ptr<libtorrent::entry>, entry_to_python>(); to_python_converter<entry, entry_to_python>(); entry_from_python(); } <|endoftext|>
<commit_before>#pragma once #include <string> #include <sstream> #include "But/assert.hpp" #include "detail/parse.hpp" #include "detail/argumentsCount.hpp" #include "detail/allArgumentsUsed.hpp" #include "Invalid.hpp" #include "detail/StreamVisitor.hpp" namespace But { namespace Format { /** @brief represents a parsed format, from a given text with. set of parameters can be applied to get a final message. * @note format of the parameter is defined by its type, via toFieldInfo() function. it * is not specified for a given type usage. this way formatting for a given parameters * is always constant. */ template<size_t ArgumentsCount, size_t MaxSegments> class Parsed final { public: /** @brief parses input format and constructs the object. * @param format - format is a string with positional arguments, in a form: * $N - expands to N-th argument. * ${N} - the same as $N. * ${N#some text} - the same as $N, but allowing some textual description along (useful for translations!). * ${TN} - prints type of N-th argument, using toFieldInfo().type() function and ADL. * ${TN#some text} - the same as ${TN}, but allowing some textual description along (useful for translations!). * ${VN} - the same as $N. * ${VN#some text} - the same as $N, but allowing some textual description along (useful for translations!). * $$ - liternal '$' character. * @note all numbers are 0-based (i.e. 1st argument has index 0). */ constexpr explicit Parsed(char const* format): ps_{ detail::parse<MaxSegments>(format) }, format_{format} { } auto inputFormat() const { return format_; } static constexpr auto expectedArguments() { return ArgumentsCount; } template<typename ...Args> std::string format(Args const& ...args) const { static_assert( sizeof...(args) == expectedArguments(), "arity missmatch between provided format and arguments to be formated" ); BUT_ASSERT( expectedArguments() == detail::argumentsCount(ps_) ); std::ostringstream os; for(auto& e: ps_.segments_) formatBlock(os, e, args...); return os.str(); } private: template<typename F> void processArgument(F&& /*f*/, const size_t /*pos*/) const { BUT_ASSERT(!"this overload should never really be called"); std::terminate(); } template<typename F, typename Head> void processArgument(F&& f, const size_t pos, Head const& head) const { (void)pos; BUT_ASSERT( pos == 0u && "format is not alligned with arguments" ); f(head); } template<typename F, typename Head, typename ...Tail> void processArgument(F&& f, const size_t pos, Head const& head, Tail const& ...tail) const { // TODO: replace this with a compile-time-generated construct... if( pos == 0u ) f(head); else processArgument( std::forward<F>(f), pos-1u, tail... ); } template<typename ...Args> void streamArgumentType(std::ostream& os, const size_t pos, Args const& .../*args*/) const { // TODO.... (void)os; (void)pos; /* auto proc = [&os](auto& e) { using Log::Backend::toType; os << toType(e); }; processArgument(proc, pos, args... ); */ } template<typename ...Args> void streamArgumentValue(std::ostream& os, const size_t pos, Args const& .../*args*/) const { // TODO.... (void)os; (void)pos; /* auto proc = [&os](auto& e) { using Log::Backend::toValue; toValue(e).visit( detail::StreamVisitor{&os} ); }; processArgument( proc, pos, args... ); */ } template<typename ...Args> void formatBlock(std::ostringstream& os, detail::Segment const& segment, Args const& ...args) const { switch(segment.type_) { case detail::Segment::Type::String: os.write( segment.begin_, segment.end_ - segment.begin_ ); return; case detail::Segment::Type::Value: streamArgumentValue(os, segment.referencedArgument_, args...); return; case detail::Segment::Type::TypeName: streamArgumentType(os, segment.referencedArgument_, args...); return; } BUT_ASSERT(!"missing type handle"); } const detail::ParsedFormat<MaxSegments> ps_; char const* format_; }; } } <commit_msg>removed complicated format for getting value and added runtime-proxy for arguments, that are to be used as strings<commit_after>#pragma once #include <string> #include <sstream> #include "But/assert.hpp" #include "detail/parse.hpp" #include "detail/argumentsCount.hpp" #include "detail/allArgumentsUsed.hpp" #include "Invalid.hpp" #include "detail/StreamVisitor.hpp" namespace But { namespace Format { /** @brief represents a parsed format, from a given text with. set of parameters can be applied to get a final message. * @note format of the parameter is defined by its type, via toFieldInfo() function. it * is not specified for a given type usage. this way formatting for a given parameters * is always constant. */ class Parsed final { public: /** @brief parses input format and constructs the object. * @param format - format is a string with positional arguments, in a form: * $N - expands to N-th argument. * ${N} - the same as $N. * ${N#some text} - the same as $N, but allowing some textual description along (useful for translations!). * $$ - liternal '$' character. * @note all numbers are 0-based (i.e. 1st argument has index 0). * @note ADL-based to_string(x) free function is used to convert 'X' into a string. strings are then used to add to a stream. */ constexpr explicit Parsed(char const* format): ps_{ detail::parse<MaxSegments>(format) }, format_{format} { } auto inputFormat() const { return format_; } static constexpr auto expectedArguments() { return ArgumentsCount; } template<typename ...Args> std::string format(Args const& ...args) const { static_assert( sizeof...(args) == expectedArguments(), "arity missmatch between provided format and arguments to be formated" ); BUT_ASSERT( expectedArguments() == detail::argumentsCount(ps_) ); using std::to_string; const std::vector<std::string> arguments{ to_string(args)... }; return formatImpl(arguments); } private: std::string formatImpl(std::vector<std::string> const& args) const { BUT_ASSERT( expectedArguments() == args.size() ); std::ostringstream os; for(auto& e: ps_.segments_) formatBlock(os, e, arguments); return os.str(); } void formatBlock(std::ostringstream& os, detail::Segment const& segment, std::vector<std::string> const& arguments) const { switch(segment.type_) { case detail::Segment::Type::String: os.write( segment.begin_, segment.end_ - segment.begin_ ); return; case detail::Segment::Type::Value: os << arguments[segment.referencedArgument_]; return; } BUT_ASSERT(!"missing type handle"); } const detail::ParsedFormat<MaxSegments> ps_; char const* format_; }; } } <|endoftext|>
<commit_before>#include <osgProducer/Viewer> #include <osg/Projection> #include <osg/Geometry> #include <osg/Texture> #include <osg/TexGen> #include <osg/Geode> #include <osg/ShapeDrawable> #include <osg/PolygonOffset> #include <osg/CullFace> #include <osg/TextureCubeMap> #include <osg/TexMat> #include <osg/MatrixTransform> #include <osg/Light> #include <osg/LightSource> #include <osg/PolygonOffset> #include <osg/CullFace> #include <osg/Material> #include <osg/RefNodePath> #include <osgUtil/TransformCallback> #include <osg/CameraNode> #include <osg/TexGenNode> using namespace osg; ref_ptr<Group> _create_scene() { ref_ptr<Group> scene = new Group; ref_ptr<Geode> geode_1 = new Geode; scene->addChild(geode_1.get()); ref_ptr<Geode> geode_2 = new Geode; ref_ptr<MatrixTransform> transform_2 = new MatrixTransform; transform_2->addChild(geode_2.get()); transform_2->setUpdateCallback(new osgUtil::TransformCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(45.0f))); scene->addChild(transform_2.get()); ref_ptr<Geode> geode_3 = new Geode; ref_ptr<MatrixTransform> transform_3 = new MatrixTransform; transform_3->addChild(geode_3.get()); transform_3->setUpdateCallback(new osgUtil::TransformCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(-22.5f))); scene->addChild(transform_3.get()); const float radius = 0.8f; const float height = 1.0f; ref_ptr<TessellationHints> hints = new TessellationHints; hints->setDetailRatio(2.0f); ref_ptr<ShapeDrawable> shape; shape = new ShapeDrawable(new Box(Vec3(0.0f, -2.0f, 0.0f), 10, 0.1f, 10), hints.get()); shape->setColor(Vec4(0.5f, 0.5f, 0.7f, 1.0f)); geode_1->addDrawable(shape.get()); shape = new ShapeDrawable(new Sphere(Vec3(-3.0f, 0.0f, 0.0f), radius), hints.get()); shape->setColor(Vec4(0.6f, 0.8f, 0.8f, 1.0f)); geode_2->addDrawable(shape.get()); shape = new ShapeDrawable(new Box(Vec3(3.0f, 0.0f, 0.0f), 2 * radius), hints.get()); shape->setColor(Vec4(0.4f, 0.9f, 0.3f, 1.0f)); geode_2->addDrawable(shape.get()); shape = new ShapeDrawable(new Cone(Vec3(0.0f, 0.0f, -3.0f), radius, height), hints.get()); shape->setColor(Vec4(0.2f, 0.5f, 0.7f, 1.0f)); geode_2->addDrawable(shape.get()); shape = new ShapeDrawable(new Cylinder(Vec3(0.0f, 0.0f, 3.0f), radius, height), hints.get()); shape->setColor(Vec4(1.0f, 0.3f, 0.3f, 1.0f)); geode_2->addDrawable(shape.get()); shape = new ShapeDrawable(new Box(Vec3(0.0f, 3.0f, 0.0f), 2, 0.1f, 2), hints.get()); shape->setColor(Vec4(0.8f, 0.8f, 0.4f, 1.0f)); geode_3->addDrawable(shape.get()); // material ref_ptr<Material> matirial = new Material; matirial->setColorMode(Material::DIFFUSE); matirial->setAmbient(Material::FRONT_AND_BACK, Vec4(0, 0, 0, 1)); matirial->setSpecular(Material::FRONT_AND_BACK, Vec4(1, 1, 1, 1)); matirial->setShininess(Material::FRONT_AND_BACK, 64.0f); scene->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), StateAttribute::ON); return scene; } osg::RefNodePath createReflector() { ref_ptr<Group> scene = new Group; ref_ptr<Geode> geode_1 = new Geode; scene->addChild(geode_1.get()); const float radius = 0.8f; ref_ptr<TessellationHints> hints = new TessellationHints; hints->setDetailRatio(2.0f); ref_ptr<ShapeDrawable> shape = new ShapeDrawable(new Sphere(Vec3(0.0f, 0.0f, 0.0f), radius * 1.5f), hints.get()); shape->setColor(Vec4(0.8f, 0.8f, 0.8f, 1.0f)); geode_1->addDrawable(shape.get()); osg::RefNodePath refNodeList; refNodeList.push_back(scene.get()); refNodeList.push_back(geode_1.get()); return refNodeList; } class UpdateCameraAndTexGenCallback : public osg::NodeCallback { public: typedef std::vector< osg::ref_ptr<osg::CameraNode> > CameraList; UpdateCameraAndTexGenCallback(osg::RefNodePath& reflectorNodePath, CameraList& cameraNodes): _reflectorNodePath(reflectorNodePath), _cameraNodes(cameraNodes) { } virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { // first update subgraph to make sure objects are all moved into postion traverse(node,nv); // compute the position of the center of the reflector subgraph osg::Matrixd matrix = osg::computeLocalToWorld(_reflectorNodePath); osg::BoundingSphere bs = _reflectorNodePath.back()->getBound(); osg::Vec3 position = bs.center() * matrix; typedef std::pair<osg::Vec3, osg::Vec3> ImageData; const ImageData id[] = { ImageData( osg::Vec3( 1, 0, 0), osg::Vec3( 0, -1, 0) ), // +X ImageData( osg::Vec3(-1, 0, 0), osg::Vec3( 0, -1, 0) ), // -X ImageData( osg::Vec3( 0, 1, 0), osg::Vec3( 0, 0, 1) ), // +Y ImageData( osg::Vec3( 0, -1, 0), osg::Vec3( 0, 0, -1) ), // -Y ImageData( osg::Vec3( 0, 0, 1), osg::Vec3( 0, -1, 0) ), // +Z ImageData( osg::Vec3( 0, 0, -1), osg::Vec3( 0, -1, 0) ) // -Z }; for(unsigned int i=0; i<6 && i<_cameraNodes.size(); ++i) { _cameraNodes[i]->setReferenceFrame(osg::CameraNode::ABSOLUTE_RF); _cameraNodes[i]->setProjectionMatrixAsFrustum(-1.0,1.0,-1.0,1.0,1.0,10000.0); _cameraNodes[i]->setViewMatrixAsLookAt(position,position+id[i].first,id[i].second); } } protected: virtual ~UpdateCameraAndTexGenCallback() {} osg::RefNodePath _reflectorNodePath; CameraList _cameraNodes; }; class TexMatCullCallback : public osg::NodeCallback { public: TexMatCullCallback(osg::TexMat* texmat): _texmat(texmat) { } virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { // first update subgraph to make sure objects are all moved into postion traverse(node,nv); osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(nv); if (cv) { osg::Quat quat; cv->getModelViewMatrix().get(quat); _texmat->setMatrix(osg::Matrix::rotate(quat.inverse())); } } protected: osg::ref_ptr<TexMat> _texmat; }; osg::Group* createShadowedScene(osg::Node* reflectedSubgraph, osg::RefNodePath reflectorNodePath, unsigned int unit, const osg::Vec4& clearColor, unsigned tex_width, unsigned tex_height, osg::CameraNode::RenderTargetImplementation renderImplementation) { osg::Group* group = new osg::Group; osg::TextureCubeMap* texture = new osg::TextureCubeMap; texture->setTextureSize(tex_width, tex_height); texture->setInternalFormat(GL_RGB); texture->setFilter(osg::TextureCubeMap::MIN_FILTER,osg::TextureCubeMap::LINEAR); texture->setFilter(osg::TextureCubeMap::MAG_FILTER,osg::TextureCubeMap::LINEAR); // set up the render to texture cameras. UpdateCameraAndTexGenCallback::CameraList cameraNodes; for(unsigned int i=0; i<6; ++i) { // create the camera osg::CameraNode* camera = new osg::CameraNode; camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); camera->setClearColor(clearColor); // set viewport camera->setViewport(0,0,tex_width,tex_height); // set the camera to render before the main camera. camera->setRenderOrder(osg::CameraNode::PRE_RENDER); // tell the camera to use OpenGL frame buffer object where supported. camera->setRenderTargetImplementation(renderImplementation); // attach the texture and use it as the color buffer. camera->attach(osg::CameraNode::COLOR_BUFFER, texture, 0, i); // add subgraph to render camera->addChild(reflectedSubgraph); group->addChild(camera); cameraNodes.push_back(camera); } // create the texgen node to project the tex coords onto the subgraph osg::TexGenNode* texgenNode = new osg::TexGenNode; texgenNode->getTexGen()->setMode(osg::TexGen::REFLECTION_MAP); texgenNode->setTextureUnit(unit); group->addChild(texgenNode); // set the reflected subgraph so that it uses the texture and tex gen settings. { osg::Node* reflectorNode = reflectorNodePath.front().get(); group->addChild(reflectorNode); osg::StateSet* stateset = reflectorNode->getOrCreateStateSet(); stateset->setTextureAttributeAndModes(unit,texture,osg::StateAttribute::ON); stateset->setTextureMode(unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON); stateset->setTextureMode(unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON); stateset->setTextureMode(unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON); stateset->setTextureMode(unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON); osg::TexMat* texmat = new osg::TexMat; stateset->setTextureAttributeAndModes(unit,texmat,osg::StateAttribute::ON); reflectorNode->setCullCallback(new TexMatCullCallback(texmat)); } // add the reflector scene to draw just as normal group->addChild(reflectedSubgraph); // set an update callback to keep moving the camera and tex gen in the right direction. group->setUpdateCallback(new UpdateCameraAndTexGenCallback(reflectorNodePath, cameraNodes)); return group; } int main(int argc, char** argv) { // use an ArgumentParser object to manage the program arguments. 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 using of GL_ARB_shadow extension implemented in osg::Texture class"); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()); arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information"); arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported."); arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture."); arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported."); arguments.getApplicationUsage()->addCommandLineOption("--window","Use a seperate Window for render to texture."); arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture"); arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture"); // 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; } unsigned tex_width = 512; unsigned tex_height = 512; while (arguments.read("--width", tex_width)) {} while (arguments.read("--height", tex_height)) {} osg::CameraNode::RenderTargetImplementation renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT; while (arguments.read("--fbo")) { renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT; } while (arguments.read("--pbuffer")) { renderImplementation = osg::CameraNode::PIXEL_BUFFER; } while (arguments.read("--fb")) { renderImplementation = osg::CameraNode::FRAME_BUFFER; } while (arguments.read("--window")) { renderImplementation = osg::CameraNode::SEPERATE_WINDOW; } // 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; } ref_ptr<MatrixTransform> scene = new MatrixTransform; scene->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(125.0),1.0,0.0,0.0)); ref_ptr<Group> reflectedSubgraph = _create_scene(); if (!reflectedSubgraph.valid()) return 1; ref_ptr<Group> reflectedScene = createShadowedScene(reflectedSubgraph.get(), createReflector(), 0, viewer.getClearColor(), tex_width, tex_height, renderImplementation); scene->addChild(reflectedScene.get()); viewer.setSceneData(scene.get()); // 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>Improved the UpdateCameraAndTexGenCallback so it properly handles rotation and translations within the reflector nodepath.<commit_after>#include <osgProducer/Viewer> #include <osg/Projection> #include <osg/Geometry> #include <osg/Texture> #include <osg/TexGen> #include <osg/Geode> #include <osg/ShapeDrawable> #include <osg/PolygonOffset> #include <osg/CullFace> #include <osg/TextureCubeMap> #include <osg/TexMat> #include <osg/MatrixTransform> #include <osg/Light> #include <osg/LightSource> #include <osg/PolygonOffset> #include <osg/CullFace> #include <osg/Material> #include <osg/RefNodePath> #include <osg/PositionAttitudeTransform> #include <osgUtil/TransformCallback> #include <osg/CameraNode> #include <osg/TexGenNode> using namespace osg; ref_ptr<Group> _create_scene() { ref_ptr<Group> scene = new Group; ref_ptr<Geode> geode_1 = new Geode; scene->addChild(geode_1.get()); ref_ptr<Geode> geode_2 = new Geode; ref_ptr<MatrixTransform> transform_2 = new MatrixTransform; transform_2->addChild(geode_2.get()); transform_2->setUpdateCallback(new osgUtil::TransformCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(45.0f))); scene->addChild(transform_2.get()); ref_ptr<Geode> geode_3 = new Geode; ref_ptr<MatrixTransform> transform_3 = new MatrixTransform; transform_3->addChild(geode_3.get()); transform_3->setUpdateCallback(new osgUtil::TransformCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(-22.5f))); scene->addChild(transform_3.get()); const float radius = 0.8f; const float height = 1.0f; ref_ptr<TessellationHints> hints = new TessellationHints; hints->setDetailRatio(2.0f); ref_ptr<ShapeDrawable> shape; shape = new ShapeDrawable(new Box(Vec3(0.0f, -2.0f, 0.0f), 10, 0.1f, 10), hints.get()); shape->setColor(Vec4(0.5f, 0.5f, 0.7f, 1.0f)); geode_1->addDrawable(shape.get()); shape = new ShapeDrawable(new Sphere(Vec3(-3.0f, 0.0f, 0.0f), radius), hints.get()); shape->setColor(Vec4(0.6f, 0.8f, 0.8f, 1.0f)); geode_2->addDrawable(shape.get()); shape = new ShapeDrawable(new Box(Vec3(3.0f, 0.0f, 0.0f), 2 * radius), hints.get()); shape->setColor(Vec4(0.4f, 0.9f, 0.3f, 1.0f)); geode_2->addDrawable(shape.get()); shape = new ShapeDrawable(new Cone(Vec3(0.0f, 0.0f, -3.0f), radius, height), hints.get()); shape->setColor(Vec4(0.2f, 0.5f, 0.7f, 1.0f)); geode_2->addDrawable(shape.get()); shape = new ShapeDrawable(new Cylinder(Vec3(0.0f, 0.0f, 3.0f), radius, height), hints.get()); shape->setColor(Vec4(1.0f, 0.3f, 0.3f, 1.0f)); geode_2->addDrawable(shape.get()); shape = new ShapeDrawable(new Box(Vec3(0.0f, 3.0f, 0.0f), 2, 0.1f, 2), hints.get()); shape->setColor(Vec4(0.8f, 0.8f, 0.4f, 1.0f)); geode_3->addDrawable(shape.get()); // material ref_ptr<Material> matirial = new Material; matirial->setColorMode(Material::DIFFUSE); matirial->setAmbient(Material::FRONT_AND_BACK, Vec4(0, 0, 0, 1)); matirial->setSpecular(Material::FRONT_AND_BACK, Vec4(1, 1, 1, 1)); matirial->setShininess(Material::FRONT_AND_BACK, 64.0f); scene->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), StateAttribute::ON); return scene; } osg::RefNodePath createReflector() { ref_ptr<osg::PositionAttitudeTransform> pat = new osg::PositionAttitudeTransform; pat->setPosition(osg::Vec3(0.0f,0.0f,0.0f)); pat->setAttitude(osg::Quat(osg::inDegrees(0.0f),osg::Vec3(0.0f,0.0f,1.0f))); ref_ptr<Geode> geode_1 = new Geode; pat->addChild(geode_1.get()); const float radius = 0.8f; ref_ptr<TessellationHints> hints = new TessellationHints; hints->setDetailRatio(2.0f); ref_ptr<ShapeDrawable> shape = new ShapeDrawable(new Sphere(Vec3(0.0f, 0.0f, 0.0f), radius * 1.5f), hints.get()); shape->setColor(Vec4(0.8f, 0.8f, 0.8f, 1.0f)); geode_1->addDrawable(shape.get()); osg::RefNodePath refNodeList; refNodeList.push_back(pat.get()); refNodeList.push_back(geode_1.get()); return refNodeList; } class UpdateCameraAndTexGenCallback : public osg::NodeCallback { public: typedef std::vector< osg::ref_ptr<osg::CameraNode> > CameraList; UpdateCameraAndTexGenCallback(osg::RefNodePath& reflectorNodePath, CameraList& cameraNodes): _reflectorNodePath(reflectorNodePath), _cameraNodes(cameraNodes) { } virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { // first update subgraph to make sure objects are all moved into postion traverse(node,nv); // compute the position of the center of the reflector subgraph osg::Matrixd worldToLocal = osg::computeWorldToLocal(_reflectorNodePath); osg::BoundingSphere bs = _reflectorNodePath.back()->getBound(); osg::Vec3 position = bs.center(); typedef std::pair<osg::Vec3, osg::Vec3> ImageData; const ImageData id[] = { ImageData( osg::Vec3( 1, 0, 0), osg::Vec3( 0, -1, 0) ), // +X ImageData( osg::Vec3(-1, 0, 0), osg::Vec3( 0, -1, 0) ), // -X ImageData( osg::Vec3( 0, 1, 0), osg::Vec3( 0, 0, 1) ), // +Y ImageData( osg::Vec3( 0, -1, 0), osg::Vec3( 0, 0, -1) ), // -Y ImageData( osg::Vec3( 0, 0, 1), osg::Vec3( 0, -1, 0) ), // +Z ImageData( osg::Vec3( 0, 0, -1), osg::Vec3( 0, -1, 0) ) // -Z }; for(unsigned int i=0; i<6 && i<_cameraNodes.size(); ++i) { osg::Matrix localOffset; localOffset.makeLookAt(position,position+id[i].first,id[i].second); osg::Matrix viewMatrix = worldToLocal*localOffset; _cameraNodes[i]->setReferenceFrame(osg::CameraNode::ABSOLUTE_RF); _cameraNodes[i]->setProjectionMatrixAsFrustum(-1.0,1.0,-1.0,1.0,1.0,10000.0); _cameraNodes[i]->setViewMatrix(viewMatrix); } } protected: virtual ~UpdateCameraAndTexGenCallback() {} osg::RefNodePath _reflectorNodePath; CameraList _cameraNodes; }; class TexMatCullCallback : public osg::NodeCallback { public: TexMatCullCallback(osg::TexMat* texmat): _texmat(texmat) { } virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { // first update subgraph to make sure objects are all moved into postion traverse(node,nv); osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(nv); if (cv) { osg::Quat quat; cv->getModelViewMatrix().get(quat); _texmat->setMatrix(osg::Matrix::rotate(quat.inverse())); } } protected: osg::ref_ptr<TexMat> _texmat; }; osg::Group* createShadowedScene(osg::Node* reflectedSubgraph, osg::RefNodePath reflectorNodePath, unsigned int unit, const osg::Vec4& clearColor, unsigned tex_width, unsigned tex_height, osg::CameraNode::RenderTargetImplementation renderImplementation) { osg::Group* group = new osg::Group; osg::TextureCubeMap* texture = new osg::TextureCubeMap; texture->setTextureSize(tex_width, tex_height); texture->setInternalFormat(GL_RGB); texture->setFilter(osg::TextureCubeMap::MIN_FILTER,osg::TextureCubeMap::LINEAR); texture->setFilter(osg::TextureCubeMap::MAG_FILTER,osg::TextureCubeMap::LINEAR); // set up the render to texture cameras. UpdateCameraAndTexGenCallback::CameraList cameraNodes; for(unsigned int i=0; i<6; ++i) { // create the camera osg::CameraNode* camera = new osg::CameraNode; camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); camera->setClearColor(clearColor); // set viewport camera->setViewport(0,0,tex_width,tex_height); // set the camera to render before the main camera. camera->setRenderOrder(osg::CameraNode::PRE_RENDER); // tell the camera to use OpenGL frame buffer object where supported. camera->setRenderTargetImplementation(renderImplementation); // attach the texture and use it as the color buffer. camera->attach(osg::CameraNode::COLOR_BUFFER, texture, 0, i); // add subgraph to render camera->addChild(reflectedSubgraph); group->addChild(camera); cameraNodes.push_back(camera); } // create the texgen node to project the tex coords onto the subgraph osg::TexGenNode* texgenNode = new osg::TexGenNode; texgenNode->getTexGen()->setMode(osg::TexGen::REFLECTION_MAP); texgenNode->setTextureUnit(unit); group->addChild(texgenNode); // set the reflected subgraph so that it uses the texture and tex gen settings. { osg::Node* reflectorNode = reflectorNodePath.front().get(); group->addChild(reflectorNode); osg::StateSet* stateset = reflectorNode->getOrCreateStateSet(); stateset->setTextureAttributeAndModes(unit,texture,osg::StateAttribute::ON); stateset->setTextureMode(unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON); stateset->setTextureMode(unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON); stateset->setTextureMode(unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON); stateset->setTextureMode(unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON); osg::TexMat* texmat = new osg::TexMat; stateset->setTextureAttributeAndModes(unit,texmat,osg::StateAttribute::ON); reflectorNode->setCullCallback(new TexMatCullCallback(texmat)); } // add the reflector scene to draw just as normal group->addChild(reflectedSubgraph); // set an update callback to keep moving the camera and tex gen in the right direction. group->setUpdateCallback(new UpdateCameraAndTexGenCallback(reflectorNodePath, cameraNodes)); return group; } int main(int argc, char** argv) { // use an ArgumentParser object to manage the program arguments. 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 using of GL_ARB_shadow extension implemented in osg::Texture class"); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()); arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information"); arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported."); arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture."); arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported."); arguments.getApplicationUsage()->addCommandLineOption("--window","Use a seperate Window for render to texture."); arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture"); arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture"); // 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; } unsigned tex_width = 512; unsigned tex_height = 512; while (arguments.read("--width", tex_width)) {} while (arguments.read("--height", tex_height)) {} osg::CameraNode::RenderTargetImplementation renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT; while (arguments.read("--fbo")) { renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT; } while (arguments.read("--pbuffer")) { renderImplementation = osg::CameraNode::PIXEL_BUFFER; } while (arguments.read("--fb")) { renderImplementation = osg::CameraNode::FRAME_BUFFER; } while (arguments.read("--window")) { renderImplementation = osg::CameraNode::SEPERATE_WINDOW; } // 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; } ref_ptr<MatrixTransform> scene = new MatrixTransform; scene->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(125.0),1.0,0.0,0.0)); ref_ptr<Group> reflectedSubgraph = _create_scene(); if (!reflectedSubgraph.valid()) return 1; ref_ptr<Group> reflectedScene = createShadowedScene(reflectedSubgraph.get(), createReflector(), 0, viewer.getClearColor(), tex_width, tex_height, renderImplementation); scene->addChild(reflectedScene.get()); viewer.setSceneData(scene.get()); // 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>/******************************************************************************\ * File: test.cpp * Purpose: Implementation for wxextension cpp unit testing * Author: Anton van Wezenbeek * RCS-ID: $Id$ * Created: za 17 jan 2009 11:51:20 CET * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <TestCaller.h> #include <wx/extension/header.h> #include <wx/extension/tool.h> #include "test.h" #define TEST_FILE "./test.h" void wxExAppTestFixture::setUp() { m_Grid = new wxExGrid(wxTheApp->GetTopWindow()); m_ListView = new wxExListView(wxTheApp->GetTopWindow()); m_Notebook = new wxExNotebook(wxTheApp->GetTopWindow(), NULL); m_STC = new wxExSTC(wxTheApp->GetTopWindow(), wxExFileName(TEST_FILE)); m_STCShell = new wxExSTCShell(wxTheApp->GetTopWindow()); m_SVN = new wxExSVN(SVN_INFO, TEST_FILE); } void wxExAppTestFixture::testConstructors() { } void wxExAppTestFixture::testMethods() { // test wxExApp CPPUNIT_ASSERT(wxExApp::GetConfig() != NULL); CPPUNIT_ASSERT(wxExApp::GetLexers() != NULL); CPPUNIT_ASSERT(wxExApp::GetPrinter() != NULL); CPPUNIT_ASSERT(!wxExTool::GetToolInfo().empty()); // test wxExGrid CPPUNIT_ASSERT(m_Grid->CreateGrid(5, 5)); m_Grid->SelectAll(); m_Grid->SetGridCellValue(wxGridCellCoords(0, 0), "test"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test"); m_Grid->SetCellsValue(wxGridCellCoords(0, 0), "test1\ttest2\ntest3\ttest4\n"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test1"); // test wxExListView m_ListView->SetSingleStyle(wxLC_REPORT); // wxLC_ICON); m_ListView->InsertColumn("String", wxExColumn::COL_STRING); m_ListView->InsertColumn("Number", wxExColumn::COL_INT); CPPUNIT_ASSERT(m_ListView->FindColumn("String") == 0); CPPUNIT_ASSERT(m_ListView->FindColumn("Number") == 1); // test wxExNotebook (parent should not be NULL) wxWindow* page1 = new wxWindow(wxTheApp->GetTopWindow(), wxID_ANY); wxWindow* page2 = new wxWindow(wxTheApp->GetTopWindow(), wxID_ANY); CPPUNIT_ASSERT(m_Notebook->AddPage(page1, "key1") != NULL); CPPUNIT_ASSERT(m_Notebook->AddPage(page2, "key2") != NULL); CPPUNIT_ASSERT(m_Notebook->AddPage(page1, "key1") == NULL); CPPUNIT_ASSERT(m_Notebook->GetKeyByPage(page1) == "key1"); CPPUNIT_ASSERT(m_Notebook->GetPageByKey("key1") == page1); CPPUNIT_ASSERT(m_Notebook->SetPageText("key1", "keyx", "hello")); CPPUNIT_ASSERT(m_Notebook->GetPageByKey("keyx") == page1); CPPUNIT_ASSERT(m_Notebook->DeletePage("keyx")); CPPUNIT_ASSERT(m_Notebook->GetPageByKey("keyx") == NULL); // test wxExSTC // do the same test as with wxExFile in base for a binary file CPPUNIT_ASSERT(m_STC->Open(wxExFileName("../test.bin"))); CPPUNIT_ASSERT(m_STC->GetFlags() == 0); const wxCharBuffer& buffer = m_STC->GetTextRaw(); wxLogMessage(buffer.data()); CPPUNIT_ASSERT(buffer.length() == 40); CPPUNIT_ASSERT(!m_STC->MacroIsRecording()); CPPUNIT_ASSERT(!m_STC->MacroIsRecorded()); m_STC->StartRecord(); CPPUNIT_ASSERT( m_STC->MacroIsRecording()); CPPUNIT_ASSERT(!m_STC->MacroIsRecorded()); m_STC->StopRecord(); CPPUNIT_ASSERT(!m_STC->MacroIsRecording()); CPPUNIT_ASSERT(!m_STC->MacroIsRecorded()); // still no macro // test wxExSTCShell m_STCShell->Prompt("test1"); m_STCShell->Prompt("test2"); m_STCShell->Prompt("test3"); m_STCShell->Prompt("test4"); // Prompting does not add a command to history... // TODO: Make a better test. CPPUNIT_ASSERT(!m_STCShell->GetHistory().Contains("test4")); // test wxExSVN CPPUNIT_ASSERT(m_SVN->Execute(NULL) == 0); // do not use a dialog CPPUNIT_ASSERT(!m_SVN->GetOutput().empty()); // test util CPPUNIT_ASSERT(wxExClipboardAdd("test")); CPPUNIT_ASSERT(wxExClipboardGet() == "test"); CPPUNIT_ASSERT(wxExGetNumberOfLines("test\ntest\n") == 3); CPPUNIT_ASSERT(wxExGetLineNumberFromText("test on line: 1200") == 1200); // Only usefull if the lexers file was present if (wxExApp::GetLexers()->Count() > 0) { wxExApp::GetConfig()->Set(_("Purpose"), "hello test"); const wxExFileName fn(TEST_FILE); const wxString header = wxExHeader(wxExApp::GetConfig()).Get(&fn); CPPUNIT_ASSERT(header.Contains("hello test")); } else { wxLogMessage("No lexers available"); } CPPUNIT_ASSERT(wxExLog("hello from wxextension test")); CPPUNIT_ASSERT(!wxExMatchesOneOf(wxFileName("test.txt"), "*.cpp")); CPPUNIT_ASSERT(wxExMatchesOneOf(wxFileName("test.txt"), "*.cpp;*.txt")); CPPUNIT_ASSERT(wxExSkipWhiteSpace("t es t") == "t es t"); CPPUNIT_ASSERT(!wxExTranslate("hello @PAGENUM@ from @PAGESCNT@", 1, 2).Contains("@")); } void wxExAppTestFixture::tearDown() { } wxExTestSuite::wxExTestSuite() : CppUnit::TestSuite("wxextension test suite") { addTest(new CppUnit::TestCaller<wxExAppTestFixture>( "testConstructors", &wxExAppTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<wxExAppTestFixture>( "testMethods", &wxExAppTestFixture::testMethods)); } <commit_msg>added tests<commit_after>/******************************************************************************\ * File: test.cpp * Purpose: Implementation for wxextension cpp unit testing * Author: Anton van Wezenbeek * RCS-ID: $Id$ * Created: za 17 jan 2009 11:51:20 CET * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <TestCaller.h> #include <wx/extension/header.h> #include <wx/extension/tool.h> #include "test.h" #define TEST_FILE "./test.h" void wxExAppTestFixture::setUp() { m_Grid = new wxExGrid(wxTheApp->GetTopWindow()); m_ListView = new wxExListView(wxTheApp->GetTopWindow()); m_Notebook = new wxExNotebook(wxTheApp->GetTopWindow(), NULL); m_STC = new wxExSTC(wxTheApp->GetTopWindow(), wxExFileName(TEST_FILE)); m_STCShell = new wxExSTCShell(wxTheApp->GetTopWindow()); m_SVN = new wxExSVN(SVN_INFO, TEST_FILE); } void wxExAppTestFixture::testConstructors() { } void wxExAppTestFixture::testMethods() { // test wxExApp CPPUNIT_ASSERT(!wxExApp::GetCatalogDir().empty()); CPPUNIT_ASSERT(wxExApp::GetConfig() != NULL); CPPUNIT_ASSERT(wxExApp::GetLexers() != NULL); CPPUNIT_ASSERT(wxExApp::GetPrinter() != NULL); CPPUNIT_ASSERT(!wxExTool::GetToolInfo().empty()); // test wxExGrid CPPUNIT_ASSERT(m_Grid->CreateGrid(5, 5)); m_Grid->SetGridCellValue(wxGridCellCoords(0, 0), "test"); m_Grid->SelectAll(); CPPUNIT_ASSERT(!m_Grid->GetSelectedCellsValue().empty()); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test"); m_Grid->SetCellsValue(wxGridCellCoords(0, 0), "test1\ttest2\ntest3\ttest4\n"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test1"); // test wxExListView m_ListView->SetSingleStyle(wxLC_REPORT); // wxLC_ICON); m_ListView->InsertColumn("String", wxExColumn::COL_STRING); m_ListView->InsertColumn("Number", wxExColumn::COL_INT); CPPUNIT_ASSERT(m_ListView->FindColumn("String") == 0); CPPUNIT_ASSERT(m_ListView->FindColumn("Number") == 1); // test wxExNotebook (parent should not be NULL) wxWindow* page1 = new wxWindow(wxTheApp->GetTopWindow(), wxID_ANY); wxWindow* page2 = new wxWindow(wxTheApp->GetTopWindow(), wxID_ANY); CPPUNIT_ASSERT(m_Notebook->AddPage(page1, "key1") != NULL); CPPUNIT_ASSERT(m_Notebook->AddPage(page2, "key2") != NULL); CPPUNIT_ASSERT(m_Notebook->AddPage(page1, "key1") == NULL); CPPUNIT_ASSERT(m_Notebook->GetKeyByPage(page1) == "key1"); CPPUNIT_ASSERT(m_Notebook->GetPageByKey("key1") == page1); CPPUNIT_ASSERT(m_Notebook->SetPageText("key1", "keyx", "hello")); CPPUNIT_ASSERT(m_Notebook->GetPageByKey("keyx") == page1); CPPUNIT_ASSERT(m_Notebook->DeletePage("keyx")); CPPUNIT_ASSERT(m_Notebook->GetPageByKey("keyx") == NULL); // test wxExSTC // do the same test as with wxExFile in base for a binary file CPPUNIT_ASSERT(m_STC->Open(wxExFileName("../test.bin"))); CPPUNIT_ASSERT(m_STC->GetFlags() == 0); CPPUNIT_ASSERT(m_STC->GetMenuFlags() == wxExSTC::STC_MENU_DEFAULT); const wxCharBuffer& buffer = m_STC->GetTextRaw(); wxLogMessage(buffer.data()); CPPUNIT_ASSERT(buffer.length() == 40); CPPUNIT_ASSERT(!m_STC->MacroIsRecording()); CPPUNIT_ASSERT(!m_STC->MacroIsRecorded()); m_STC->StartRecord(); CPPUNIT_ASSERT( m_STC->MacroIsRecording()); CPPUNIT_ASSERT(!m_STC->MacroIsRecorded()); m_STC->StopRecord(); CPPUNIT_ASSERT(!m_STC->MacroIsRecording()); CPPUNIT_ASSERT(!m_STC->MacroIsRecorded()); // still no macro // test wxExSTCShell m_STCShell->Prompt("test1"); m_STCShell->Prompt("test2"); m_STCShell->Prompt("test3"); m_STCShell->Prompt("test4"); // Prompting does not add a command to history. CPPUNIT_ASSERT(!m_STCShell->GetHistory().Contains("test4")); // Post 3 'a' chars to the shell, and check whether it comes in the history. wxKeyEvent event(wxEVT_CHAR); event.m_keyCode = 97; // one char 'a' wxPostEvent(m_STCShell, event); wxPostEvent(m_STCShell, event); wxPostEvent(m_STCShell, event); event.m_keyCode = WXK_RETURN; wxPostEvent(m_STCShell, event); CPPUNIT_ASSERT(m_STCShell->GetHistory().Contains("aaa")); // test wxExSVN CPPUNIT_ASSERT(m_SVN->Execute(NULL) == 0); // do not use a dialog CPPUNIT_ASSERT(!m_SVN->GetOutput().empty()); // test util CPPUNIT_ASSERT(wxExClipboardAdd("test")); CPPUNIT_ASSERT(wxExClipboardGet() == "test"); CPPUNIT_ASSERT(wxExGetNumberOfLines("test\ntest\n") == 3); CPPUNIT_ASSERT(wxExGetLineNumberFromText("test on line: 1200") == 1200); // Only usefull if the lexers file was present if (wxExApp::GetLexers()->Count() > 0) { wxExApp::GetConfig()->Set(_("Purpose"), "hello test"); const wxExFileName fn(TEST_FILE); const wxString header = wxExHeader(wxExApp::GetConfig()).Get(&fn); CPPUNIT_ASSERT(header.Contains("hello test")); } else { wxLogMessage("No lexers available"); } CPPUNIT_ASSERT(wxExLog("hello from wxextension test")); CPPUNIT_ASSERT(!wxExMatchesOneOf(wxFileName("test.txt"), "*.cpp")); CPPUNIT_ASSERT(wxExMatchesOneOf(wxFileName("test.txt"), "*.cpp;*.txt")); CPPUNIT_ASSERT(wxExSkipWhiteSpace("t es t") == "t es t"); CPPUNIT_ASSERT(!wxExTranslate("hello @PAGENUM@ from @PAGESCNT@", 1, 2).Contains("@")); } void wxExAppTestFixture::tearDown() { } wxExTestSuite::wxExTestSuite() : CppUnit::TestSuite("wxextension test suite") { addTest(new CppUnit::TestCaller<wxExAppTestFixture>( "testConstructors", &wxExAppTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<wxExAppTestFixture>( "testMethods", &wxExAppTestFixture::testMethods)); } <|endoftext|>
<commit_before><commit_msg>change toml::value::cast to toml::get<commit_after><|endoftext|>
<commit_before>/** * Copyright (c) 2015 Damien Tardy-Panis * * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. **/ #include "TubeyToons.h" #include <QDebug> #include <QRegularExpression> #include <QRegularExpressionMatch> TubeyToons::TubeyToons(QObject *parent) : Comic(parent) { } const QString TubeyToons::_id = QString("tubeytoons"); const QString TubeyToons::_name = QString("Tubey Toons"); const QColor TubeyToons::_color = QColor(254, 180, 64); const QStringList TubeyToons::_authors = QStringList() << "Tubey" << "Wamn"; const QUrl TubeyToons::_homepage = QUrl("http://tubeytoons.com/"); const QLocale::Country TubeyToons::_country = QLocale::UnitedStates; const QLocale::Language TubeyToons::_language = QLocale::English; const QDate TubeyToons::_startDate = QDate::fromString("2013-01-01", Qt::ISODate); const QDate TubeyToons::_endDate = QDate::currentDate(); const QUrl TubeyToons::_stripSourceUrl = QUrl("http://tubeytoons.com/"); QUrl TubeyToons::extractStripUrl(QByteArray data) { QString html(data); QRegularExpression reg("<img[^>]*src=\'(/img/comics/[^\']*)\'"); QRegularExpressionMatch match = reg.match(html); if (!match.hasMatch()) { return QUrl(); } QString src = match.captured(1); return QUrl("http://tubeytoons.com/" + src); } <commit_msg>fix Tubey Toons comic<commit_after>/** * Copyright (c) 2015 Damien Tardy-Panis * * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. **/ #include "TubeyToons.h" #include <QDebug> #include <QRegularExpression> #include <QRegularExpressionMatch> TubeyToons::TubeyToons(QObject *parent) : Comic(parent) { } const QString TubeyToons::_id = QString("tubeytoons"); const QString TubeyToons::_name = QString("Tubey Toons"); const QColor TubeyToons::_color = QColor(254, 180, 64); const QStringList TubeyToons::_authors = QStringList() << "Tubey" << "Wamn"; const QUrl TubeyToons::_homepage = QUrl("http://tubeytoons.com/"); const QLocale::Country TubeyToons::_country = QLocale::UnitedStates; const QLocale::Language TubeyToons::_language = QLocale::English; const QDate TubeyToons::_startDate = QDate::fromString("2013-01-01", Qt::ISODate); const QDate TubeyToons::_endDate = QDate::currentDate(); const QUrl TubeyToons::_stripSourceUrl = QUrl("http://tubeytoons.com/"); QUrl TubeyToons::extractStripUrl(QByteArray data) { QString html(data); QRegularExpression reg("<img[^>]*src=\'(.*/images/comics/[^\']*)\'"); QRegularExpressionMatch match = reg.match(html); if (!match.hasMatch()) { return QUrl(); } QString src = match.captured(1); return QUrl(src); } <|endoftext|>
<commit_before>//=========================================== // Lumina-DE source code // Copyright (c) 2014, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "LPlugins.h" #include <LuminaUtils.h> LPlugins::LPlugins(){ LoadPanelPlugins(); LoadDesktopPlugins(); LoadMenuPlugins(); LoadColorItems(); } LPlugins::~LPlugins(){ } //Plugin lists QStringList LPlugins::panelPlugins(){ QStringList pan = PANEL.keys(); pan.sort(); return pan; } QStringList LPlugins::desktopPlugins(){ QStringList desk = DESKTOP.keys(); desk.sort(); return desk; } QStringList LPlugins::menuPlugins(){ QStringList men = MENU.keys(); men.sort(); return men; } QStringList LPlugins::colorItems(){ return COLORS.keys(); } //Information on individual plugins LPI LPlugins::panelPluginInfo(QString plug){ if(PANEL.contains(plug)){ return PANEL[plug]; } else{ return LPI(); } } LPI LPlugins::desktopPluginInfo(QString plug){ if(DESKTOP.contains(plug)){ return DESKTOP[plug]; } else{ return LPI(); } } LPI LPlugins::menuPluginInfo(QString plug){ if(MENU.contains(plug)){ return MENU[plug]; } else{ return LPI(); } } LPI LPlugins::colorInfo(QString item){ if(COLORS.contains(item)){ return COLORS[item]; } else{ return LPI(); } } //=================== // PLUGINS //=================== void LPlugins::LoadPanelPlugins(){ PANEL.clear(); //User Button LPI info; info.name = QObject::tr("User Button"); info.description = QObject::tr("This is the main system access button for the user (applications, directories, settings, log out)."); info.ID = "userbutton"; info.icon = "user-identity"; PANEL.insert(info.ID, info); //Application Menu info = LPI(); //clear it info.name = QObject::tr("Application Menu"); info.description = QObject::tr("This provides instant-access to application that are installed on the system."); info.ID = "appmenu"; info.icon = "format-list-unordered"; PANEL.insert(info.ID, info); //Desktop Bar info = LPI(); //clear it info.name = QObject::tr("Desktop Bar"); info.description = QObject::tr("This provides shortcuts to everything in the desktop folder - allowing easy access to all your favorite files/applications."); info.ID = "desktopbar"; info.icon = "user-desktop"; PANEL.insert(info.ID, info); //Spacer info = LPI(); //clear it info.name = QObject::tr("Spacer"); info.description = QObject::tr("Invisible spacer to separate plugins."); info.ID = "spacer"; info.icon = "transform-move"; PANEL.insert(info.ID, info); //Desktop Switcher info = LPI(); //clear it info.name = QObject::tr("Desktop Switcher"); info.description = QObject::tr("Controls for switching between the various virtual desktops."); info.ID = "desktopswitcher"; info.icon = "preferences-desktop-display-color"; PANEL.insert(info.ID, info); //Battery info = LPI(); //clear it info.name = QObject::tr("Battery Monitor"); info.description = QObject::tr("Keep track of your battery status."); info.ID = "battery"; info.icon = "battery-charging"; PANEL.insert(info.ID, info); //Clock info = LPI(); //clear it info.name = QObject::tr("Time/Date"); info.description = QObject::tr("View the current time and date."); info.ID = "clock"; info.icon = "preferences-system-time"; PANEL.insert(info.ID, info); //System Dachboard plugin info = LPI(); //clear it info.name = QObject::tr("System Dashboard"); info.description = QObject::tr("View or change system settings (audio volume, screen brightness, battery life, virtual desktops)."); info.ID = "systemdashboard"; info.icon = "dashboard-show"; PANEL.insert(info.ID, info); //Task Manager info = LPI(); //clear it info.name = QObject::tr("Task Manager"); info.description = QObject::tr("View and control any running application windows (every application has a button)"); info.ID = "taskmanager"; info.icon = "preferences-system-windows"; PANEL.insert(info.ID, info); //Task Manager info = LPI(); //clear it info.name = QObject::tr("Task Manager (No Groups)"); info.description = QObject::tr("View and control any running application windows (every window has a button)"); info.ID = "taskmanager-nogroups"; info.icon = "preferences-system-windows"; PANEL.insert(info.ID, info); //System Tray info = LPI(); //clear it info.name = QObject::tr("System Tray"); info.description = QObject::tr("Display area for dockable system applications"); info.ID = "systemtray"; info.icon = "preferences-system-windows-actions"; PANEL.insert(info.ID, info); //Home Button info = LPI(); //clear it info.name = QObject::tr("Home Button"); info.description = QObject::tr("Hide all open windows and show the desktop"); info.ID = "homebutton"; info.icon = "go-home"; PANEL.insert(info.ID, info); //Start Menu info = LPI(); //clear it info.name = QObject::tr("Start Menu"); info.description = QObject::tr("Unified system access and application launch menu."); info.ID = "systemstart"; info.icon = "Lumina-DE"; PANEL.insert(info.ID, info); //Application Launcher info = LPI(); //clear it info.name = QObject::tr("Application Launcher"); info.description = QObject::tr("Pin an application shortcut directly to the panel"); info.ID = "applauncher"; info.icon = "quickopen"; PANEL.insert(info.ID, info); } void LPlugins::LoadDesktopPlugins(){ DESKTOP.clear(); //Calendar Plugin LPI info; info.name = QObject::tr("Calendar"); info.description = QObject::tr("Display a calendar on the desktop"); info.ID = "calendar"; info.icon = "view-calendar"; DESKTOP.insert(info.ID, info); //Application Launcher Plugin info = LPI(); //clear it info.name = QObject::tr("Application Launcher"); info.description = QObject::tr("Desktop button for launching an application"); info.ID = "applauncher"; info.icon = "quickopen"; DESKTOP.insert(info.ID, info); //Desktop View Plugin info = LPI(); //clear it info.name = QObject::tr("Desktop Icons View"); info.description = QObject::tr("Area for automatically showing desktop icons"); info.ID = "desktopview"; info.icon = "preferences-desktop-icons"; DESKTOP.insert(info.ID, info); //Notepad Plugin info = LPI(); //clear it info.name = QObject::tr("Note Pad"); info.description = QObject::tr("Keep simple text notes on your desktop"); info.ID = "notepad"; info.icon = "text-enriched"; DESKTOP.insert(info.ID, info); //Audio Player Plugin info = LPI(); //clear it info.name = QObject::tr("Audio Player"); info.description = QObject::tr("Play through lists of audio files"); info.ID = "audioplayer"; info.icon = "media-playback-start"; DESKTOP.insert(info.ID, info); //System Monitor Plugin info = LPI(); //clear it info.name = QObject::tr("System Monitor"); info.description = QObject::tr("Keep track of system statistics such as CPU/Memory usage and CPU temperatures."); info.ID = "systemmonitor"; info.icon = "cpu"; DESKTOP.insert(info.ID, info); //Available QtQuick scripts QStringList quickID = LUtils::listQuickPlugins(); for(int i=0; i<quickID.length(); i++){ QStringList quickinfo = LUtils::infoQuickPlugin(quickID[i]); //Returns: [name, description, icon] if(quickinfo.length() < 3){ continue; } //invalid file (unreadable/other) info = LPI(); info.name = quickinfo[0]; info.description = quickinfo[1]; info.ID = "quick-"+quickID[i]; //the "quick-" prefix is required for the desktop plugin syntax info.icon = quickinfo[2]; DESKTOP.insert(info.ID, info); } } void LPlugins::LoadMenuPlugins(){ MENU.clear(); //Terminal LPI info; info.name = QObject::tr("Terminal"); info.description = QObject::tr("Start the default system terminal."); info.ID = "terminal"; info.icon = "utilities-terminal"; MENU.insert(info.ID, info); //File Manager info = LPI(); //clear it info.name = QObject::tr("File Manager"); info.description = QObject::tr("Browse the system with the default file manager."); info.ID = "filemanager"; info.icon = "Insight-FileManager"; MENU.insert(info.ID, info); //Applications info = LPI(); //clear it info.name = QObject::tr("Applications"); info.description = QObject::tr("Show the system applications menu."); info.ID = "applications"; info.icon = "system-run"; MENU.insert(info.ID, info); //Line seperator info = LPI(); //clear it info.name = QObject::tr("Separator"); info.description = QObject::tr("Static horizontal line."); info.ID = "line"; info.icon = "insert-horizontal-rule"; MENU.insert(info.ID, info); //Settings info = LPI(); //clear it info.name = QObject::tr("Settings"); info.description = QObject::tr("Show the desktop settings menu."); info.ID = "settings"; info.icon = "configure"; MENU.insert(info.ID, info); //Window List info = LPI(); //clear it info.name = QObject::tr("Window List"); info.description = QObject::tr("List the open application windows"); info.ID = "windowlist"; info.icon = "preferences-system-windows"; MENU.insert(info.ID, info); //Custom Apps info = LPI(); //clear it info.name = QObject::tr("Custom App"); info.description = QObject::tr("Start a custom application"); info.ID = "app"; info.icon = "application-x-desktop"; MENU.insert(info.ID, info); } void LPlugins::LoadColorItems(){ COLORS.clear(); //Text Color LPI info; info.name = QObject::tr("Text"); info.description = QObject::tr("Color to use for all visible text."); info.ID = "TEXTCOLOR"; COLORS.insert(info.ID, info); //Text Color (Disabled) info = LPI(); //clear it info.name = QObject::tr("Text (Disabled)"); info.description = QObject::tr("Text color for disabled or inactive items."); info.ID = "TEXTDISABLECOLOR"; COLORS.insert(info.ID, info); //Text Color (Highlighted) info = LPI(); //clear it info.name = QObject::tr("Text (Highlighted)"); info.description = QObject::tr("Text color when selection is highlighted."); info.ID = "TEXTHIGHLIGHTCOLOR"; COLORS.insert(info.ID, info); //Base Color (Normal) info = LPI(); //clear it info.name = QObject::tr("Base Window Color"); info.description = QObject::tr("Main background color for the window/dialog."); info.ID = "BASECOLOR"; COLORS.insert(info.ID, info); //Base Color (Alternate) info = LPI(); //clear it info.name = QObject::tr("Base Window Color (Alternate)"); info.description = QObject::tr("Main background color for widgets that list or display collections of items."); info.ID = "ALTBASECOLOR"; COLORS.insert(info.ID, info); //Primary Color (Normal) info = LPI(); //clear it info.name = QObject::tr("Primary Color"); info.description = QObject::tr("Dominant color for the theme."); info.ID = "PRIMARYCOLOR"; COLORS.insert(info.ID, info); //Primary Color (Disabled) info = LPI(); //clear it info.name = QObject::tr("Primary Color (Disabled)"); info.description = QObject::tr("Dominant color for the theme (more subdued)."); info.ID = "PRIMARYDISABLECOLOR"; COLORS.insert(info.ID, info); //Secondary Color (Normal) info = LPI(); //clear it info.name = QObject::tr("Secondary Color"); info.description = QObject::tr("Alternate color for the theme."); info.ID = "SECONDARYCOLOR"; COLORS.insert(info.ID, info); //Secondary Color (Disabled) info = LPI(); //clear it info.name = QObject::tr("Secondary Color (Disabled)"); info.description = QObject::tr("Alternate color for the theme (more subdued)."); info.ID = "SECONDARYDISABLECOLOR"; COLORS.insert(info.ID, info); //Accent Color (Normal) info = LPI(); //clear it info.name = QObject::tr("Accent Color"); info.description = QObject::tr("Color used for borders or other accents."); info.ID = "ACCENTCOLOR"; COLORS.insert(info.ID, info); //Accent Color (Disabled) info = LPI(); //clear it info.name = QObject::tr("Accent Color (Disabled)"); info.description = QObject::tr("Color used for borders or other accents (more subdued)."); info.ID = "ACCENTDISABLECOLOR"; COLORS.insert(info.ID, info); //Highlight Color (Normal) info = LPI(); //clear it info.name = QObject::tr("Highlight Color"); info.description = QObject::tr("Color used for highlighting an item."); info.ID = "HIGHLIGHTCOLOR"; COLORS.insert(info.ID, info); //Highlight Color (Disabled) info = LPI(); //clear it info.name = QObject::tr("Highlight Color (Disabled)"); info.description = QObject::tr("Color used for highlighting an item (more subdued)."); info.ID = "HIGHLIGHTDISABLECOLOR"; COLORS.insert(info.ID, info); }<commit_msg>Change the names of a couple panel plugins: 1) Desktop Switcher -> Workspace Switcher 2) Home Button -> Show Desktop<commit_after>//=========================================== // Lumina-DE source code // Copyright (c) 2014, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "LPlugins.h" #include <LuminaUtils.h> LPlugins::LPlugins(){ LoadPanelPlugins(); LoadDesktopPlugins(); LoadMenuPlugins(); LoadColorItems(); } LPlugins::~LPlugins(){ } //Plugin lists QStringList LPlugins::panelPlugins(){ QStringList pan = PANEL.keys(); pan.sort(); return pan; } QStringList LPlugins::desktopPlugins(){ QStringList desk = DESKTOP.keys(); desk.sort(); return desk; } QStringList LPlugins::menuPlugins(){ QStringList men = MENU.keys(); men.sort(); return men; } QStringList LPlugins::colorItems(){ return COLORS.keys(); } //Information on individual plugins LPI LPlugins::panelPluginInfo(QString plug){ if(PANEL.contains(plug)){ return PANEL[plug]; } else{ return LPI(); } } LPI LPlugins::desktopPluginInfo(QString plug){ if(DESKTOP.contains(plug)){ return DESKTOP[plug]; } else{ return LPI(); } } LPI LPlugins::menuPluginInfo(QString plug){ if(MENU.contains(plug)){ return MENU[plug]; } else{ return LPI(); } } LPI LPlugins::colorInfo(QString item){ if(COLORS.contains(item)){ return COLORS[item]; } else{ return LPI(); } } //=================== // PLUGINS //=================== void LPlugins::LoadPanelPlugins(){ PANEL.clear(); //User Button LPI info; info.name = QObject::tr("User Button"); info.description = QObject::tr("This is the main system access button for the user (applications, directories, settings, log out)."); info.ID = "userbutton"; info.icon = "user-identity"; PANEL.insert(info.ID, info); //Application Menu info = LPI(); //clear it info.name = QObject::tr("Application Menu"); info.description = QObject::tr("This provides instant-access to application that are installed on the system."); info.ID = "appmenu"; info.icon = "format-list-unordered"; PANEL.insert(info.ID, info); //Desktop Bar info = LPI(); //clear it info.name = QObject::tr("Desktop Bar"); info.description = QObject::tr("This provides shortcuts to everything in the desktop folder - allowing easy access to all your favorite files/applications."); info.ID = "desktopbar"; info.icon = "user-desktop"; PANEL.insert(info.ID, info); //Spacer info = LPI(); //clear it info.name = QObject::tr("Spacer"); info.description = QObject::tr("Invisible spacer to separate plugins."); info.ID = "spacer"; info.icon = "transform-move"; PANEL.insert(info.ID, info); //Desktop Switcher info = LPI(); //clear it info.name = QObject::tr("Workspace Switcher"); info.description = QObject::tr("Controls for switching between the various virtual desktops."); info.ID = "desktopswitcher"; info.icon = "preferences-desktop-display-color"; PANEL.insert(info.ID, info); //Battery info = LPI(); //clear it info.name = QObject::tr("Battery Monitor"); info.description = QObject::tr("Keep track of your battery status."); info.ID = "battery"; info.icon = "battery-charging"; PANEL.insert(info.ID, info); //Clock info = LPI(); //clear it info.name = QObject::tr("Time/Date"); info.description = QObject::tr("View the current time and date."); info.ID = "clock"; info.icon = "preferences-system-time"; PANEL.insert(info.ID, info); //System Dachboard plugin info = LPI(); //clear it info.name = QObject::tr("System Dashboard"); info.description = QObject::tr("View or change system settings (audio volume, screen brightness, battery life, virtual desktops)."); info.ID = "systemdashboard"; info.icon = "dashboard-show"; PANEL.insert(info.ID, info); //Task Manager info = LPI(); //clear it info.name = QObject::tr("Task Manager"); info.description = QObject::tr("View and control any running application windows (every application has a button)"); info.ID = "taskmanager"; info.icon = "preferences-system-windows"; PANEL.insert(info.ID, info); //Task Manager info = LPI(); //clear it info.name = QObject::tr("Task Manager (No Groups)"); info.description = QObject::tr("View and control any running application windows (every window has a button)"); info.ID = "taskmanager-nogroups"; info.icon = "preferences-system-windows"; PANEL.insert(info.ID, info); //System Tray info = LPI(); //clear it info.name = QObject::tr("System Tray"); info.description = QObject::tr("Display area for dockable system applications"); info.ID = "systemtray"; info.icon = "preferences-system-windows-actions"; PANEL.insert(info.ID, info); //Home Button info = LPI(); //clear it info.name = QObject::tr("Show Desktop"); info.description = QObject::tr("Hide all open windows and show the desktop"); info.ID = "homebutton"; info.icon = "go-home"; PANEL.insert(info.ID, info); //Start Menu info = LPI(); //clear it info.name = QObject::tr("Start Menu"); info.description = QObject::tr("Unified system access and application launch menu."); info.ID = "systemstart"; info.icon = "Lumina-DE"; PANEL.insert(info.ID, info); //Application Launcher info = LPI(); //clear it info.name = QObject::tr("Application Launcher"); info.description = QObject::tr("Pin an application shortcut directly to the panel"); info.ID = "applauncher"; info.icon = "quickopen"; PANEL.insert(info.ID, info); } void LPlugins::LoadDesktopPlugins(){ DESKTOP.clear(); //Calendar Plugin LPI info; info.name = QObject::tr("Calendar"); info.description = QObject::tr("Display a calendar on the desktop"); info.ID = "calendar"; info.icon = "view-calendar"; DESKTOP.insert(info.ID, info); //Application Launcher Plugin info = LPI(); //clear it info.name = QObject::tr("Application Launcher"); info.description = QObject::tr("Desktop button for launching an application"); info.ID = "applauncher"; info.icon = "quickopen"; DESKTOP.insert(info.ID, info); //Desktop View Plugin info = LPI(); //clear it info.name = QObject::tr("Desktop Icons View"); info.description = QObject::tr("Area for automatically showing desktop icons"); info.ID = "desktopview"; info.icon = "preferences-desktop-icons"; DESKTOP.insert(info.ID, info); //Notepad Plugin info = LPI(); //clear it info.name = QObject::tr("Note Pad"); info.description = QObject::tr("Keep simple text notes on your desktop"); info.ID = "notepad"; info.icon = "text-enriched"; DESKTOP.insert(info.ID, info); //Audio Player Plugin info = LPI(); //clear it info.name = QObject::tr("Audio Player"); info.description = QObject::tr("Play through lists of audio files"); info.ID = "audioplayer"; info.icon = "media-playback-start"; DESKTOP.insert(info.ID, info); //System Monitor Plugin info = LPI(); //clear it info.name = QObject::tr("System Monitor"); info.description = QObject::tr("Keep track of system statistics such as CPU/Memory usage and CPU temperatures."); info.ID = "systemmonitor"; info.icon = "cpu"; DESKTOP.insert(info.ID, info); //Available QtQuick scripts QStringList quickID = LUtils::listQuickPlugins(); for(int i=0; i<quickID.length(); i++){ QStringList quickinfo = LUtils::infoQuickPlugin(quickID[i]); //Returns: [name, description, icon] if(quickinfo.length() < 3){ continue; } //invalid file (unreadable/other) info = LPI(); info.name = quickinfo[0]; info.description = quickinfo[1]; info.ID = "quick-"+quickID[i]; //the "quick-" prefix is required for the desktop plugin syntax info.icon = quickinfo[2]; DESKTOP.insert(info.ID, info); } } void LPlugins::LoadMenuPlugins(){ MENU.clear(); //Terminal LPI info; info.name = QObject::tr("Terminal"); info.description = QObject::tr("Start the default system terminal."); info.ID = "terminal"; info.icon = "utilities-terminal"; MENU.insert(info.ID, info); //File Manager info = LPI(); //clear it info.name = QObject::tr("File Manager"); info.description = QObject::tr("Browse the system with the default file manager."); info.ID = "filemanager"; info.icon = "Insight-FileManager"; MENU.insert(info.ID, info); //Applications info = LPI(); //clear it info.name = QObject::tr("Applications"); info.description = QObject::tr("Show the system applications menu."); info.ID = "applications"; info.icon = "system-run"; MENU.insert(info.ID, info); //Line seperator info = LPI(); //clear it info.name = QObject::tr("Separator"); info.description = QObject::tr("Static horizontal line."); info.ID = "line"; info.icon = "insert-horizontal-rule"; MENU.insert(info.ID, info); //Settings info = LPI(); //clear it info.name = QObject::tr("Settings"); info.description = QObject::tr("Show the desktop settings menu."); info.ID = "settings"; info.icon = "configure"; MENU.insert(info.ID, info); //Window List info = LPI(); //clear it info.name = QObject::tr("Window List"); info.description = QObject::tr("List the open application windows"); info.ID = "windowlist"; info.icon = "preferences-system-windows"; MENU.insert(info.ID, info); //Custom Apps info = LPI(); //clear it info.name = QObject::tr("Custom App"); info.description = QObject::tr("Start a custom application"); info.ID = "app"; info.icon = "application-x-desktop"; MENU.insert(info.ID, info); } void LPlugins::LoadColorItems(){ COLORS.clear(); //Text Color LPI info; info.name = QObject::tr("Text"); info.description = QObject::tr("Color to use for all visible text."); info.ID = "TEXTCOLOR"; COLORS.insert(info.ID, info); //Text Color (Disabled) info = LPI(); //clear it info.name = QObject::tr("Text (Disabled)"); info.description = QObject::tr("Text color for disabled or inactive items."); info.ID = "TEXTDISABLECOLOR"; COLORS.insert(info.ID, info); //Text Color (Highlighted) info = LPI(); //clear it info.name = QObject::tr("Text (Highlighted)"); info.description = QObject::tr("Text color when selection is highlighted."); info.ID = "TEXTHIGHLIGHTCOLOR"; COLORS.insert(info.ID, info); //Base Color (Normal) info = LPI(); //clear it info.name = QObject::tr("Base Window Color"); info.description = QObject::tr("Main background color for the window/dialog."); info.ID = "BASECOLOR"; COLORS.insert(info.ID, info); //Base Color (Alternate) info = LPI(); //clear it info.name = QObject::tr("Base Window Color (Alternate)"); info.description = QObject::tr("Main background color for widgets that list or display collections of items."); info.ID = "ALTBASECOLOR"; COLORS.insert(info.ID, info); //Primary Color (Normal) info = LPI(); //clear it info.name = QObject::tr("Primary Color"); info.description = QObject::tr("Dominant color for the theme."); info.ID = "PRIMARYCOLOR"; COLORS.insert(info.ID, info); //Primary Color (Disabled) info = LPI(); //clear it info.name = QObject::tr("Primary Color (Disabled)"); info.description = QObject::tr("Dominant color for the theme (more subdued)."); info.ID = "PRIMARYDISABLECOLOR"; COLORS.insert(info.ID, info); //Secondary Color (Normal) info = LPI(); //clear it info.name = QObject::tr("Secondary Color"); info.description = QObject::tr("Alternate color for the theme."); info.ID = "SECONDARYCOLOR"; COLORS.insert(info.ID, info); //Secondary Color (Disabled) info = LPI(); //clear it info.name = QObject::tr("Secondary Color (Disabled)"); info.description = QObject::tr("Alternate color for the theme (more subdued)."); info.ID = "SECONDARYDISABLECOLOR"; COLORS.insert(info.ID, info); //Accent Color (Normal) info = LPI(); //clear it info.name = QObject::tr("Accent Color"); info.description = QObject::tr("Color used for borders or other accents."); info.ID = "ACCENTCOLOR"; COLORS.insert(info.ID, info); //Accent Color (Disabled) info = LPI(); //clear it info.name = QObject::tr("Accent Color (Disabled)"); info.description = QObject::tr("Color used for borders or other accents (more subdued)."); info.ID = "ACCENTDISABLECOLOR"; COLORS.insert(info.ID, info); //Highlight Color (Normal) info = LPI(); //clear it info.name = QObject::tr("Highlight Color"); info.description = QObject::tr("Color used for highlighting an item."); info.ID = "HIGHLIGHTCOLOR"; COLORS.insert(info.ID, info); //Highlight Color (Disabled) info = LPI(); //clear it info.name = QObject::tr("Highlight Color (Disabled)"); info.description = QObject::tr("Color used for highlighting an item (more subdued)."); info.ID = "HIGHLIGHTDISABLECOLOR"; COLORS.insert(info.ID, info); }<|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include "GArgs.h" #include "gff.h" #include "GIntervalTree.h" using std::cout; #define VERSION "0.10.6" bool simpleOvl=false; bool strictMatching=false; struct GSTree { GIntervalTree it[3]; //0=unstranded, 1: + strand, 2 : - strand }; int main(int argc, char* argv[]) { const std::string usage = std::string("trmap v" VERSION)+ " : transcript to reference mapping and overlap classifier.\nUsage:\n"+ " trmap [-S] [-o <outfile>] [--strict-match] <ref_gff> <query_gff>\n"+ "Positional arguments:\n"+ " <ref_gff> reference annotation file name (GFF/BED format)\n"+ " <query_gff> query file name (GFF/BED format) or \"-\" for stdin\n"+ "Options:\n"+ " -o <outfile> write output to <outfile> instead of stdout\n"+ " -S report only simple reference overlap percentages, without\n"+ " classification (one line per query)\n"+ " --strict-match : when intron chains match, the '=' overlap code is assigned\n"+ " when all exons also match, otherwise assign the '~' code\n"; GArgs args(argc, argv, "help;strict-match;hSo:"); args.printError(usage.c_str(), true); if (args.getOpt('h') || args.getOpt("help")) { cout << usage; exit(EXIT_SUCCESS); } if (args.getOpt('S')) simpleOvl=true; if (args.getOpt("strict-match")) strictMatching=true; GHash<GSTree> map_trees; const char* o_file = args.getOpt('o') ? args.getOpt('o') : "-"; if (args.startNonOpt()!=2) { std::cerr << usage << "\nOnly " << args.startNonOpt() << " arguments provided (expected 2)\n"; exit(1); } const char* ref_file = args.nextNonOpt(); const char* q_file = args.nextNonOpt(); FILE* fr=fopen(ref_file, "r"); //always good to check if the file is actually there and can be read if (fr==NULL) GError("Error: could not open reference annotation file (%s)!\n", ref_file); GffReader myR(fr, true, true); const char* fext=getFileExt(ref_file); if (Gstricmp(fext, "bed")==0) myR.isBED(); GffObj* t=NULL; GPVec<GffObj> toFree(true); while ((t=myR.readNext())!=NULL) { GSTree* cTree=map_trees[t->getGSeqName()]; if (cTree==NULL) { cTree=new GSTree(); map_trees.Add(t->getGSeqName(), cTree); } if (t->strand=='+') cTree->it[1].Insert(t); else if (t->strand=='-') cTree->it[2].Insert(t); else cTree->it[0].Insert(t); toFree.Add(t); } FILE* outFH=NULL; if (strcmp(o_file, "-")==0) outFH=stdout; else { outFH=fopen(o_file, "w"); if (outFH==NULL) GError("Error creating file %s !\n",o_file); } FILE* fq=NULL; fext=NULL; if (strcmp(q_file,"-")==0) fq=stdin; else { fq=fopen(q_file, "r"); if (fq==NULL) GError("Error: could not open query file (%s)!\n", q_file); fext=getFileExt(q_file); } GffReader myQ(fq, true, true); if (fext && Gstricmp(fext, "bed")==0) myQ.isBED(); //myQ.readAll(false, true, true); //for (int i=0; i<myQ.gflst.Count(); i++) { // GffObj* t=myQ.gflst[i]; t=NULL; while ((t=myQ.readNext())!=NULL) { //if (map_trees.count(t->getGSeqName())==0) continue; const char* gseq=t->getGSeqName(); if (!map_trees.hasKey(gseq)) continue; GVec<int> sidx; int v=0; sidx.Add(v); //always search the '.' strand if (t->strand=='+') { v=1; sidx.Add(v); } else if (t->strand=='-') { v=2; sidx.Add(v); } else { v=1; sidx.Add(v); v=2; sidx.Add(v); } for (int k=0;k<sidx.Count();++k) { TemplateStack<GSeg*> * enu = map_trees[gseq]->it[sidx[k]].Enumerate(t->start, t->end); if(enu->Size()!=0) { if (simpleOvl) { fprintf(outFH, "%s\t%s:%d-%d|%c", t->getID(), gseq, t->start, t->end, t->strand); for (int i=0; i<enu->Size(); ++i) { //static_cast<ObjInterval*>((*enu)[i])->obj->printGxf(oFile2); GffObj* r=(GffObj*)((*enu)[i]); int ovlen=t->overlapLen(r); if (ovlen==0) GError("Error: zero length simple overlap reported! (%s vs %s)\n", t->getID(), r->getID()); float ovlcov=(100.00*ovlen)/r->len(); fprintf(outFH, "\t%s:%.1f", r->getID(), ovlcov); //if (i+1<enu->Size()) fprintf(outFH, ","); } fprintf(outFH, "\n"); } else { fprintf(outFH, ">%s %s:%d-%d %c ", t->getID(), t->getGSeqName(), t->start, t->end, t->strand); t->printExonList(outFH); fprintf(outFH, "\n"); for (int i=0; i<enu->Size(); ++i) { //static_cast<ObjInterval*>((*enu)[i])->obj->printGxf(oFile2); GffObj* r=(GffObj*)((*enu)[i]); int ovlen=0; char ovlcode=getOvlCode(*t, *r, ovlen, strictMatching); fprintf(outFH, "%c\t", ovlcode); r->printGTab(outFH); } } } delete enu; } delete t; } fclose(outFH); return 0; } <commit_msg>trmap version bump<commit_after>#include <iostream> #include <fstream> #include <sstream> #include "GArgs.h" #include "gff.h" #include "GIntervalTree.h" using std::cout; #define VERSION "0.11.2" bool simpleOvl=false; bool strictMatching=false; struct GSTree { GIntervalTree it[3]; //0=unstranded, 1: + strand, 2 : - strand }; int main(int argc, char* argv[]) { const std::string usage = std::string("trmap v" VERSION)+ " : transcript to reference mapping and overlap classifier.\nUsage:\n"+ " trmap [-S] [-o <outfile>] [--strict-match] <ref_gff> <query_gff>\n"+ "Positional arguments:\n"+ " <ref_gff> reference annotation file name (GFF/BED format)\n"+ " <query_gff> query file name (GFF/BED format) or \"-\" for stdin\n"+ "Options:\n"+ " -o <outfile> write output to <outfile> instead of stdout\n"+ " -S report only simple reference overlap percentages, without\n"+ " classification (one line per query)\n"+ " --strict-match : when intron chains match, the '=' overlap code is assigned\n"+ " when all exons also match, otherwise assign the '~' code\n"; GArgs args(argc, argv, "help;strict-match;hSo:"); args.printError(usage.c_str(), true); if (args.getOpt('h') || args.getOpt("help")) { cout << usage; exit(EXIT_SUCCESS); } if (args.getOpt('S')) simpleOvl=true; if (args.getOpt("strict-match")) strictMatching=true; GHash<GSTree> map_trees; const char* o_file = args.getOpt('o') ? args.getOpt('o') : "-"; if (args.startNonOpt()!=2) { std::cerr << usage << "\nOnly " << args.startNonOpt() << " arguments provided (expected 2)\n"; exit(1); } const char* ref_file = args.nextNonOpt(); const char* q_file = args.nextNonOpt(); FILE* fr=fopen(ref_file, "r"); //always good to check if the file is actually there and can be read if (fr==NULL) GError("Error: could not open reference annotation file (%s)!\n", ref_file); GffReader myR(fr, true, true); const char* fext=getFileExt(ref_file); if (Gstricmp(fext, "bed")==0) myR.isBED(); GffObj* t=NULL; GPVec<GffObj> toFree(true); while ((t=myR.readNext())!=NULL) { GSTree* cTree=map_trees[t->getGSeqName()]; if (cTree==NULL) { cTree=new GSTree(); map_trees.Add(t->getGSeqName(), cTree); } if (t->strand=='+') cTree->it[1].Insert(t); else if (t->strand=='-') cTree->it[2].Insert(t); else cTree->it[0].Insert(t); toFree.Add(t); } FILE* outFH=NULL; if (strcmp(o_file, "-")==0) outFH=stdout; else { outFH=fopen(o_file, "w"); if (outFH==NULL) GError("Error creating file %s !\n",o_file); } FILE* fq=NULL; fext=NULL; if (strcmp(q_file,"-")==0) fq=stdin; else { fq=fopen(q_file, "r"); if (fq==NULL) GError("Error: could not open query file (%s)!\n", q_file); fext=getFileExt(q_file); } GffReader myQ(fq, true, true); if (fext && Gstricmp(fext, "bed")==0) myQ.isBED(); //myQ.readAll(false, true, true); //for (int i=0; i<myQ.gflst.Count(); i++) { // GffObj* t=myQ.gflst[i]; t=NULL; while ((t=myQ.readNext())!=NULL) { //if (map_trees.count(t->getGSeqName())==0) continue; const char* gseq=t->getGSeqName(); if (!map_trees.hasKey(gseq)) continue; GVec<int> sidx; int v=0; sidx.Add(v); //always search the '.' strand if (t->strand=='+') { v=1; sidx.Add(v); } else if (t->strand=='-') { v=2; sidx.Add(v); } else { v=1; sidx.Add(v); v=2; sidx.Add(v); } for (int k=0;k<sidx.Count();++k) { TemplateStack<GSeg*> * enu = map_trees[gseq]->it[sidx[k]].Enumerate(t->start, t->end); if(enu->Size()!=0) { if (simpleOvl) { fprintf(outFH, "%s\t%s:%d-%d|%c", t->getID(), gseq, t->start, t->end, t->strand); for (int i=0; i<enu->Size(); ++i) { //static_cast<ObjInterval*>((*enu)[i])->obj->printGxf(oFile2); GffObj* r=(GffObj*)((*enu)[i]); int ovlen=t->overlapLen(r); if (ovlen==0) GError("Error: zero length simple overlap reported! (%s vs %s)\n", t->getID(), r->getID()); float ovlcov=(100.00*ovlen)/r->len(); fprintf(outFH, "\t%s:%.1f", r->getID(), ovlcov); //if (i+1<enu->Size()) fprintf(outFH, ","); } fprintf(outFH, "\n"); } else { fprintf(outFH, ">%s %s:%d-%d %c ", t->getID(), t->getGSeqName(), t->start, t->end, t->strand); t->printExonList(outFH); fprintf(outFH, "\n"); for (int i=0; i<enu->Size(); ++i) { //static_cast<ObjInterval*>((*enu)[i])->obj->printGxf(oFile2); GffObj* r=(GffObj*)((*enu)[i]); int ovlen=0; char ovlcode=getOvlCode(*t, *r, ovlen, strictMatching); fprintf(outFH, "%c\t", ovlcode); r->printGTab(outFH); } } } delete enu; } delete t; } fclose(outFH); return 0; } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/storage/bucketdb/storbucketdb.h> #include <vespa/storage/common/bucketmessages.h> #include <vespa/storage/bucketmover/bucketmover.h> #include <vespa/document/test/make_bucket_space.h> #include <vespa/document/test/make_document_bucket.h> #include <tests/common/dummystoragelink.h> #include <tests/common/teststorageapp.h> #include <vespa/config/common/exceptions.h> #include <gtest/gtest.h> bool debug = false; using document::test::makeBucketSpace; using document::test::makeDocumentBucket; namespace storage::bucketmover { struct BucketMoverTest : public ::testing::Test { public: void SetUp() override; void TearDown() override; std::unique_ptr<TestServiceLayerApp> _node; std::unique_ptr<ServiceLayerComponent> _component; std::unique_ptr<BucketMover> _bucketMover; DummyStorageLink* after; void addBucket(const document::BucketId& id, uint16_t idealDiff); }; void BucketMoverTest::TearDown() { _node.reset(0); } void BucketMoverTest::SetUp() { try { _node.reset(new TestServiceLayerApp(DiskCount(4))); _node->setupDummyPersistence(); } catch (config::InvalidConfigException& e) { fprintf(stderr, "%s\n", e.what()); } _component.reset(new ServiceLayerComponent(_node->getComponentRegister(), "foo")); _bucketMover.reset(new BucketMover("raw:", _node->getComponentRegister())); after = new DummyStorageLink(); _bucketMover->push_back(StorageLink::UP(after)); } void BucketMoverTest::addBucket(const document::BucketId& id, uint16_t idealDiff) { StorBucketDatabase::WrappedEntry entry( _component->getBucketDatabase(makeBucketSpace()).get( id, "", StorBucketDatabase::CREATE_IF_NONEXISTING)); entry->setBucketInfo(api::BucketInfo(1,1,1)); uint16_t idealDisk = _component->getIdealPartition(makeDocumentBucket(id)); entry->disk = (idealDisk + idealDiff) % _component->getDiskCount(); entry.write(); } TEST_F(BucketMoverTest, testNormalUsage) { for (uint32_t i = 1; i < 4; ++i) { addBucket(document::BucketId(16, i), 1); } for (uint32_t i = 4; i < 6; ++i) { addBucket(document::BucketId(16, i), 0); } _bucketMover->open(); _bucketMover->tick(); std::vector<api::StorageMessage::SP> msgs = after->getCommandsOnce(); EXPECT_EQ( std::string("BucketDiskMoveCommand(" "BucketId(0x4000000000000002), source 3, target 2)"), msgs[0]->toString()); EXPECT_EQ( std::string("BucketDiskMoveCommand(" "BucketId(0x4000000000000001), source 2, target 1)"), msgs[1]->toString()); EXPECT_EQ( std::string("BucketDiskMoveCommand(" "BucketId(0x4000000000000003), source 1, target 0)"), msgs[2]->toString()); for (uint32_t i = 0; i < 2; ++i) { after->sendUp(std::shared_ptr<api::StorageMessage>( ((api::StorageCommand*)msgs[i].get())-> makeReply().release())); } _bucketMover->tick(); EXPECT_EQ(0, (int)after->getNumCommands()); _bucketMover->finishCurrentRun(); } TEST_F(BucketMoverTest, testMaxPending) { for (uint32_t i = 1; i < 100; ++i) { addBucket(document::BucketId(16, i), 1); } for (uint32_t i = 101; i < 200; ++i) { addBucket(document::BucketId(16, i), 0); } _bucketMover->open(); _bucketMover->tick(); std::vector<api::StorageMessage::SP> msgs = after->getCommandsOnce(); // 5 is the max pending default config. EXPECT_EQ(5, (int)msgs.size()); after->sendUp(std::shared_ptr<api::StorageMessage>( ((api::StorageCommand*)msgs[3].get())-> makeReply().release())); _bucketMover->tick(); std::vector<api::StorageMessage::SP> msgs2 = after->getCommandsOnce(); EXPECT_EQ(1, (int)msgs2.size()); } TEST_F(BucketMoverTest, testErrorHandling) { for (uint32_t i = 1; i < 100; ++i) { addBucket(document::BucketId(16, i), 1); } for (uint32_t i = 101; i < 200; ++i) { addBucket(document::BucketId(16, i), 0); } _bucketMover->open(); _bucketMover->tick(); std::vector<api::StorageMessage::SP> msgs = after->getCommandsOnce(); // 5 is the max pending default config. EXPECT_EQ(5, (int)msgs.size()); BucketDiskMoveCommand& cmd = static_cast<BucketDiskMoveCommand&>(*msgs[0]); uint32_t targetDisk = cmd.getDstDisk(); std::unique_ptr<api::StorageReply> reply(cmd.makeReply().release()); reply->setResult(api::ReturnCode(api::ReturnCode::INTERNAL_FAILURE, "foobar")); after->sendUp(std::shared_ptr<api::StorageMessage>(reply.release())); for (uint32_t i = 1; i < msgs.size(); ++i) { after->sendUp(std::shared_ptr<api::StorageMessage>( ((api::StorageCommand*)msgs[i].get())-> makeReply().release())); } _bucketMover->tick(); std::vector<api::StorageMessage::SP> msgs2 = after->getCommandsOnce(); EXPECT_EQ(5, (int)msgs2.size()); for (uint32_t i = 0; i < msgs2.size(); ++i) { BucketDiskMoveCommand& bdm = static_cast<BucketDiskMoveCommand&>(*msgs2[i]); EXPECT_NE(bdm.getDstDisk(), targetDisk); } } } <commit_msg>Use ASSERT_EQ when checking vector sizes.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/storage/bucketdb/storbucketdb.h> #include <vespa/storage/common/bucketmessages.h> #include <vespa/storage/bucketmover/bucketmover.h> #include <vespa/document/test/make_bucket_space.h> #include <vespa/document/test/make_document_bucket.h> #include <tests/common/dummystoragelink.h> #include <tests/common/teststorageapp.h> #include <vespa/config/common/exceptions.h> #include <gtest/gtest.h> bool debug = false; using document::test::makeBucketSpace; using document::test::makeDocumentBucket; namespace storage::bucketmover { struct BucketMoverTest : public ::testing::Test { public: void SetUp() override; void TearDown() override; std::unique_ptr<TestServiceLayerApp> _node; std::unique_ptr<ServiceLayerComponent> _component; std::unique_ptr<BucketMover> _bucketMover; DummyStorageLink* after; void addBucket(const document::BucketId& id, uint16_t idealDiff); }; void BucketMoverTest::TearDown() { _node.reset(0); } void BucketMoverTest::SetUp() { try { _node.reset(new TestServiceLayerApp(DiskCount(4))); _node->setupDummyPersistence(); } catch (config::InvalidConfigException& e) { fprintf(stderr, "%s\n", e.what()); } _component.reset(new ServiceLayerComponent(_node->getComponentRegister(), "foo")); _bucketMover.reset(new BucketMover("raw:", _node->getComponentRegister())); after = new DummyStorageLink(); _bucketMover->push_back(StorageLink::UP(after)); } void BucketMoverTest::addBucket(const document::BucketId& id, uint16_t idealDiff) { StorBucketDatabase::WrappedEntry entry( _component->getBucketDatabase(makeBucketSpace()).get( id, "", StorBucketDatabase::CREATE_IF_NONEXISTING)); entry->setBucketInfo(api::BucketInfo(1,1,1)); uint16_t idealDisk = _component->getIdealPartition(makeDocumentBucket(id)); entry->disk = (idealDisk + idealDiff) % _component->getDiskCount(); entry.write(); } TEST_F(BucketMoverTest, testNormalUsage) { for (uint32_t i = 1; i < 4; ++i) { addBucket(document::BucketId(16, i), 1); } for (uint32_t i = 4; i < 6; ++i) { addBucket(document::BucketId(16, i), 0); } _bucketMover->open(); _bucketMover->tick(); std::vector<api::StorageMessage::SP> msgs = after->getCommandsOnce(); EXPECT_EQ( std::string("BucketDiskMoveCommand(" "BucketId(0x4000000000000002), source 3, target 2)"), msgs[0]->toString()); EXPECT_EQ( std::string("BucketDiskMoveCommand(" "BucketId(0x4000000000000001), source 2, target 1)"), msgs[1]->toString()); EXPECT_EQ( std::string("BucketDiskMoveCommand(" "BucketId(0x4000000000000003), source 1, target 0)"), msgs[2]->toString()); for (uint32_t i = 0; i < 2; ++i) { after->sendUp(std::shared_ptr<api::StorageMessage>( ((api::StorageCommand*)msgs[i].get())-> makeReply().release())); } _bucketMover->tick(); EXPECT_EQ(0, (int)after->getNumCommands()); _bucketMover->finishCurrentRun(); } TEST_F(BucketMoverTest, testMaxPending) { for (uint32_t i = 1; i < 100; ++i) { addBucket(document::BucketId(16, i), 1); } for (uint32_t i = 101; i < 200; ++i) { addBucket(document::BucketId(16, i), 0); } _bucketMover->open(); _bucketMover->tick(); std::vector<api::StorageMessage::SP> msgs = after->getCommandsOnce(); // 5 is the max pending default config. ASSERT_EQ(5, (int)msgs.size()); after->sendUp(std::shared_ptr<api::StorageMessage>( ((api::StorageCommand*)msgs[3].get())-> makeReply().release())); _bucketMover->tick(); std::vector<api::StorageMessage::SP> msgs2 = after->getCommandsOnce(); ASSERT_EQ(1, (int)msgs2.size()); } TEST_F(BucketMoverTest, testErrorHandling) { for (uint32_t i = 1; i < 100; ++i) { addBucket(document::BucketId(16, i), 1); } for (uint32_t i = 101; i < 200; ++i) { addBucket(document::BucketId(16, i), 0); } _bucketMover->open(); _bucketMover->tick(); std::vector<api::StorageMessage::SP> msgs = after->getCommandsOnce(); // 5 is the max pending default config. ASSERT_EQ(5, (int)msgs.size()); BucketDiskMoveCommand& cmd = static_cast<BucketDiskMoveCommand&>(*msgs[0]); uint32_t targetDisk = cmd.getDstDisk(); std::unique_ptr<api::StorageReply> reply(cmd.makeReply().release()); reply->setResult(api::ReturnCode(api::ReturnCode::INTERNAL_FAILURE, "foobar")); after->sendUp(std::shared_ptr<api::StorageMessage>(reply.release())); for (uint32_t i = 1; i < msgs.size(); ++i) { after->sendUp(std::shared_ptr<api::StorageMessage>( ((api::StorageCommand*)msgs[i].get())-> makeReply().release())); } _bucketMover->tick(); std::vector<api::StorageMessage::SP> msgs2 = after->getCommandsOnce(); ASSERT_EQ(5, (int)msgs2.size()); for (uint32_t i = 0; i < msgs2.size(); ++i) { BucketDiskMoveCommand& bdm = static_cast<BucketDiskMoveCommand&>(*msgs2[i]); EXPECT_NE(bdm.getDstDisk(), targetDisk); } } } <|endoftext|>
<commit_before>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ /* rev'd for v2.3, JGG, 20-Feb-00 */ /* rev'd for v3.7 (converted to C++ source), DS, April-04 */ #include <stdio.h> #include <unistd.h> #include <assert.h> #include <globals.h> #include <prototypes.h> #include <buffers.h> #include "../rtstuff/rtdefs.h" #include "AudioDevice.h" extern AudioDevice *globalAudioDevice; // audio_devices.cpp /* ----------------------------------------------------------- rtgetsamps --- */ void rtgetsamps(AudioDevice *inputDevice) { assert(audio_on == 1); // Sorrowful hack: The dual AudioDevice run the callback on the playback // device, which means it cannot pass the record device to this function. if (globalAudioDevice->getFrames(audioin_buffer, RTBUFSAMPS) < 0) { fprintf(stderr, "rtgetsamps error: %s\n", globalAudioDevice->getLastError()); } } <commit_msg>Cleaned up (removed hack!) and changed audio_on to record_audio.<commit_after>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ /* rev'd for v2.3, JGG, 20-Feb-00 */ /* rev'd for v3.7 (converted to C++ source), DS, April-04 */ #include <stdio.h> #include <unistd.h> #include <assert.h> #include <globals.h> #include <prototypes.h> #include <buffers.h> #include "../rtstuff/rtdefs.h" #include "AudioDevice.h" /* ----------------------------------------------------------- rtgetsamps --- */ void rtgetsamps(AudioDevice *inputDevice) { assert(record_audio == 1); if (inputDevice->getFrames(audioin_buffer, RTBUFSAMPS) < 0) { fprintf(stderr, "rtgetsamps error: %s\n", inputDevice->getLastError()); } } <|endoftext|>
<commit_before>#include <yuni/yuni.h> #include <yuni/core/getopt.h> #include <nany/nany.h> #include <yuni/datetime/timestamp.h> #include <yuni/core/system/cpu.h> #include <yuni/core/system/console/console.h> #include <yuni/io/file.h> #include <set> #include <iostream> #include <cassert> using namespace Yuni; static uint32_t jobCount = 0; static bool hasColorsOut = false; static bool hasColorsErr = false; static int printBugReportInfo() { nylib_print_info_for_bugreport(); return EXIT_SUCCESS; } static int printVersion() { std::cout << nylib_version() << '\n'; return EXIT_SUCCESS; } static int printNoInputScript(const char* argv0) { std::cerr << argv0 << ": no input script file\n"; return EXIT_FAILURE; } static void fetchUnittestList(nyrun_cf_t& runcf, String::Vector& torun, const char** filelist, uint32_t count) { std::cout << "searching for unittests in all source files...\n" << std::flush; runcf.build.entrypoint.size = 0; // disable any compilation by default runcf.build.entrypoint.c_str = nullptr; runcf.program.entrypoint.size = 0; runcf.program.entrypoint.c_str = nullptr; runcf.build.ignore_atoms = nytrue; runcf.build.userdata = &torun; runcf.build.on_unittest = [](void* userdata, const char* mod, uint32_t modlen, const char* name, uint32_t nlen) { AnyString module{mod, modlen}; AnyString testname{name, nlen}; ((String::Vector*) userdata)->emplace_back(); auto& element = ((String::Vector*) userdata)->back(); element << module << ':' << testname; }; int64_t starttime = DateTime::NowMilliSeconds(); nyrun_filelist(&runcf, filelist, count, 0, nullptr); int64_t duration = DateTime::NowMilliSeconds() - starttime; switch (torun.size()) { case 0: std::cout << "0 test found"; break; case 1: std::cout << "1 test found"; break; default: std::cout << torun.size() << " tests found"; break; } std::cout << " (" << duration << "ms)\n\n"; } static int listAllUnittests(nyrun_cf_t& runcf, const char** filelist, uint32_t count) { std::set<std::pair<String, String>> alltests; runcf.build.entrypoint.size = 0; // disable any compilation by default runcf.build.entrypoint.c_str = nullptr; runcf.program.entrypoint.size = 0; runcf.program.entrypoint.c_str = nullptr; runcf.build.ignore_atoms = nytrue; runcf.build.userdata = &alltests; runcf.build.on_unittest = [](void* userdata, const char* mod, uint32_t modlen, const char* name, uint32_t nlen) { AnyString module{mod, modlen}; AnyString testname{name, nlen}; auto& dict = *((std::set<std::pair<String, String>>*) userdata); dict.emplace(std::make_pair(String{module}, String{testname})); }; int64_t starttime = DateTime::NowMilliSeconds(); if (0 != nyrun_filelist(&runcf, filelist, count, 0, nullptr)) { std::cerr << "error: failed to compile. aborting.\n"; return EXIT_FAILURE; } int64_t duration = DateTime::NowMilliSeconds() - starttime; AnyString lastmodule; uint32_t moduleCount = 0; for (auto& pair: alltests) { auto& module = pair.first; if (lastmodule != module) { ++moduleCount; lastmodule = module; if (hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::bold); std::cout << '.' << lastmodule << ":\n"; if (hasColorsOut) System::Console::ResetTextColor(std::cout); } std::cout << " "; if (not module.empty()) std::cout << module << ':'; std::cout << pair.second << '\n'; } std::cout << "\n "; if (hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::lightblue); switch (moduleCount) { case 0: break; case 1: std::cout << "1 module, "; break; default: std::cout << moduleCount << " modules, "; break; } switch (alltests.size()) { case 0: std::cout << "0 test found"; break; case 1: std::cout << "1 test found"; break; default: std::cout << alltests.size() << " tests found"; break; } if (hasColorsOut) System::Console::ResetTextColor(std::cout); std::cout << " (" << duration << "ms)\n\n"; return EXIT_SUCCESS; } template<bool Fancy> static bool runtest(nyrun_cf_t& originalRuncf, const String& testname, const char** filelist, uint32_t count) { ShortString256 entry; entry << "^unittest^" << testname; entry.replace("<nomodule>", "module"); bool interactive = (hasColorsOut and jobCount == 1); auto runcf = originalRuncf; runcf.build.entrypoint.size = entry.size(); runcf.build.entrypoint.c_str = entry.c_str(); runcf.program.entrypoint = runcf.build.entrypoint; runcf.build.ignore_atoms = nyfalse; struct Console { Clob cout; Clob cerr; } console; runcf.console.release = nullptr; runcf.console.internal = &console; runcf.console.flush = [](void*, nyconsole_output_t) {}; runcf.console.set_color = [](void*, nyconsole_output_t, nycolor_t) {}; runcf.console.has_color = [](void*, nyconsole_output_t) { return nyfalse; }; runcf.console.write_stdout = [](void* userdata, const char* text, size_t length) { auto& console = *((Console*) userdata); if (text and length) console.cout.append(text, static_cast<uint32_t>(length)); }; runcf.console.write_stderr = [](void* userdata, const char* text, size_t length) { auto& console = *((Console*) userdata); if (text and length) console.cerr.append(text, static_cast<uint32_t>(length)); }; if (interactive and Fancy) { if (hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::bold); std::cout << " running "; if (hasColorsOut) System::Console::ResetTextColor(std::cout); std::cout << testname << "... " << std::flush; } int64_t starttime = DateTime::NowMilliSeconds(); bool success = !nyrun_filelist(&runcf, filelist, count, 0, nullptr); int64_t duration = DateTime::NowMilliSeconds() - starttime; success &= console.cerr.empty(); if (Fancy) { if (interactive) std::cout << '\r'; if (success) { if (hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::green); #ifndef YUNI_OS_WINDOWS std::cout << " \u2713 "; #else std::cout << " OK "; #endif } else { if (hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::red); std::cout << " ERR "; } if (hasColorsOut) System::Console::ResetTextColor(std::cout); std::cout << testname; if (duration < 1200 or not hasColorsOut) { std::cout << " (" << duration << "ms) "; } else { System::Console::SetTextColor(std::cout, System::Console::purple); std::cout << " (" << duration << "ms) "; System::Console::ResetTextColor(std::cout); } std::cout << '\n'; if (not console.cerr.empty()) { console.cerr.trimRight(); console.cerr.replace("\n", "\n | "); std::cout << " | " << console.cerr << '\n'; } std::cout << std::flush; } return success; } static void printStatstics(const String::Vector& optToRun, int64_t duration, uint32_t successCount, uint32_t failCount) { switch (optToRun.size()) { case 0: std::cout << "\n 0 test, "; break; case 1: std::cout << "\n 1 test"; break; default: std::cout << "\n " << optToRun.size() << " tests, "; break; } if (successCount and hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::green); switch (successCount) { case 0: std::cout << "0 passing"; break; case 1: std::cout << "1 passing"; break; default: std::cout << successCount << " passing"; break; } if (successCount and hasColorsOut) System::Console::ResetTextColor(std::cout); if (failCount) std::cout << ", "; if (failCount and hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::red); switch (failCount) { case 0: break; case 1: std::cout << "1 failed"; break; default: std::cout << "" << failCount << " failed"; break; } if (failCount and hasColorsOut) System::Console::ResetTextColor(std::cout); std::cout << " ("; if (duration < 10000) std::cout << duration << "ms)"; else std::cout << (duration / 1000) << "s)"; std::cout << "\n\n"; } static bool runUnittsts(nyrun_cf_t& runcf, const String::Vector& optToRun, const char** filelist, uint32_t filecount) { if (optToRun.empty()) { std::cerr << "error: no unit test name\n"; return false; } uint32_t successCount = 0; uint32_t failCount = 0; int64_t starttime = DateTime::NowMilliSeconds(); runcf.build.ignore_atoms = nytrue; runcf.build.userdata = nullptr; runcf.build.on_unittest = nullptr; for (auto& testname: optToRun) { bool localsuccess = runtest<true>(runcf, testname, filelist, filecount); ++(localsuccess ? successCount : failCount); } int64_t duration = DateTime::NowMilliSeconds() - starttime; printStatstics(optToRun, duration, successCount, failCount); return (failCount == 0 and successCount != 0); } int main(int argc, char** argv) { // options String::Vector optToRun; String::Vector remainingArgs; bool optListAll = false; bool optWithNSLTests = false; // The command line options parser { GetOpt::Parser options; options.addFlag(optListAll, 'l', "list", "List all unit tests"); options.addFlag(optToRun, 'r', "run", "Run a specific test"); options.add(jobCount, 'j', "job", "Specifies the number of jobs (commands) to run simultaneously"); options.addFlag(optWithNSLTests, ' ', "with-nsl", "Import NSL unittests"); options.remainingArguments(remainingArgs); // Help options.addParagraph("\nHelp"); bool optBugreport = false; options.addFlag(optBugreport, ' ', "bugreport", "Display some useful information to report a bug"); bool optVersion = false; options.addFlag(optVersion, 'v', "version", "Print the version"); if (not options(argc, argv)) { if (options.errors()) { std::cout << "Abort due to error" << std::endl; return 1; } return 0; } if (optVersion) return printVersion(); if (optBugreport) return printBugReportInfo(); } uint32_t filecount = (uint32_t) remainingArgs.size(); if (filecount == 0) return printNoInputScript(argv[0]); auto** filelist = (const char**) malloc(sizeof(char*) * filecount); { String filename; for (uint32_t i = 0; i != filecount; ++i) { IO::Canonicalize(filename, remainingArgs[i]); remainingArgs[i] = filename; filelist[i] = remainingArgs[i].c_str(); } } nyrun_cf_t runcf; nyrun_cf_init(&runcf); if (optWithNSLTests) runcf.project.with_nsl_unittests = nytrue; int exitcode = EXIT_SUCCESS; hasColorsOut = System::Console::IsStdoutTTY(); hasColorsErr = System::Console::IsStderrTTY(); if (optListAll) { exitcode = listAllUnittests(runcf, filelist, filecount); } else { if (hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::bold); std::cout << "nanyc C++/boostrap unittest " << nylib_version(); if (hasColorsOut) System::Console::ResetTextColor(std::cout); std::cout << '\n'; nylib_print_info_for_bugreport(); std::cout << ">\n"; for (uint32_t i = 0; i != filecount; ++i) std::cout << "> from '" << filelist[i] << "'\n"; std::cout << '\n'; if (0 == jobCount) System::CPU::Count(); // no unittest provided from the command - default: all if (optToRun.empty()) fetchUnittestList(runcf, optToRun, filelist, filecount); bool success = runUnittsts(runcf, optToRun, filelist, filecount); exitcode = (success) ? EXIT_SUCCESS : EXIT_FAILURE; } free(filelist); return exitcode; } <commit_msg>style: anonymous namespace instead of static<commit_after>#include <yuni/yuni.h> #include <yuni/core/getopt.h> #include <nany/nany.h> #include <yuni/datetime/timestamp.h> #include <yuni/core/system/cpu.h> #include <yuni/core/system/console/console.h> #include <yuni/io/file.h> #include <set> #include <iostream> #include <cassert> using namespace Yuni; namespace { static uint32_t jobCount = 0; static bool hasColorsOut = false; static bool hasColorsErr = false; int printBugReportInfo() { nylib_print_info_for_bugreport(); return EXIT_SUCCESS; } int printVersion() { std::cout << nylib_version() << '\n'; return EXIT_SUCCESS; } int printNoInputScript(const char* argv0) { std::cerr << argv0 << ": no input script file\n"; return EXIT_FAILURE; } void fetchUnittestList(nyrun_cf_t& runcf, String::Vector& torun, const char** filelist, uint32_t count) { std::cout << "searching for unittests in all source files...\n" << std::flush; runcf.build.entrypoint.size = 0; // disable any compilation by default runcf.build.entrypoint.c_str = nullptr; runcf.program.entrypoint.size = 0; runcf.program.entrypoint.c_str = nullptr; runcf.build.ignore_atoms = nytrue; runcf.build.userdata = &torun; runcf.build.on_unittest = [](void* userdata, const char* mod, uint32_t modlen, const char* name, uint32_t nlen) { AnyString module{mod, modlen}; AnyString testname{name, nlen}; ((String::Vector*) userdata)->emplace_back(); auto& element = ((String::Vector*) userdata)->back(); element << module << ':' << testname; }; int64_t starttime = DateTime::NowMilliSeconds(); nyrun_filelist(&runcf, filelist, count, 0, nullptr); int64_t duration = DateTime::NowMilliSeconds() - starttime; switch (torun.size()) { case 0: std::cout << "0 test found"; break; case 1: std::cout << "1 test found"; break; default: std::cout << torun.size() << " tests found"; break; } std::cout << " (" << duration << "ms)\n\n"; } int listAllUnittests(nyrun_cf_t& runcf, const char** filelist, uint32_t count) { std::set<std::pair<String, String>> alltests; runcf.build.entrypoint.size = 0; // disable any compilation by default runcf.build.entrypoint.c_str = nullptr; runcf.program.entrypoint.size = 0; runcf.program.entrypoint.c_str = nullptr; runcf.build.ignore_atoms = nytrue; runcf.build.userdata = &alltests; runcf.build.on_unittest = [](void* userdata, const char* mod, uint32_t modlen, const char* name, uint32_t nlen) { AnyString module{mod, modlen}; AnyString testname{name, nlen}; auto& dict = *((std::set<std::pair<String, String>>*) userdata); dict.emplace(std::make_pair(String{module}, String{testname})); }; int64_t starttime = DateTime::NowMilliSeconds(); if (0 != nyrun_filelist(&runcf, filelist, count, 0, nullptr)) { std::cerr << "error: failed to compile. aborting.\n"; return EXIT_FAILURE; } int64_t duration = DateTime::NowMilliSeconds() - starttime; AnyString lastmodule; uint32_t moduleCount = 0; for (auto& pair: alltests) { auto& module = pair.first; if (lastmodule != module) { ++moduleCount; lastmodule = module; if (hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::bold); std::cout << '.' << lastmodule << ":\n"; if (hasColorsOut) System::Console::ResetTextColor(std::cout); } std::cout << " "; if (not module.empty()) std::cout << module << ':'; std::cout << pair.second << '\n'; } std::cout << "\n "; if (hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::lightblue); switch (moduleCount) { case 0: break; case 1: std::cout << "1 module, "; break; default: std::cout << moduleCount << " modules, "; break; } switch (alltests.size()) { case 0: std::cout << "0 test found"; break; case 1: std::cout << "1 test found"; break; default: std::cout << alltests.size() << " tests found"; break; } if (hasColorsOut) System::Console::ResetTextColor(std::cout); std::cout << " (" << duration << "ms)\n\n"; return EXIT_SUCCESS; } template<bool Fancy> bool runtest(nyrun_cf_t& originalRuncf, const String& testname, const char** filelist, uint32_t count) { ShortString256 entry; entry << "^unittest^" << testname; entry.replace("<nomodule>", "module"); bool interactive = (hasColorsOut and jobCount == 1); auto runcf = originalRuncf; runcf.build.entrypoint.size = entry.size(); runcf.build.entrypoint.c_str = entry.c_str(); runcf.program.entrypoint = runcf.build.entrypoint; runcf.build.ignore_atoms = nyfalse; struct Console { Clob cout; Clob cerr; } console; runcf.console.release = nullptr; runcf.console.internal = &console; runcf.console.flush = [](void*, nyconsole_output_t) {}; runcf.console.set_color = [](void*, nyconsole_output_t, nycolor_t) {}; runcf.console.has_color = [](void*, nyconsole_output_t) { return nyfalse; }; runcf.console.write_stdout = [](void* userdata, const char* text, size_t length) { auto& console = *((Console*) userdata); if (text and length) console.cout.append(text, static_cast<uint32_t>(length)); }; runcf.console.write_stderr = [](void* userdata, const char* text, size_t length) { auto& console = *((Console*) userdata); if (text and length) console.cerr.append(text, static_cast<uint32_t>(length)); }; if (interactive and Fancy) { if (hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::bold); std::cout << " running "; if (hasColorsOut) System::Console::ResetTextColor(std::cout); std::cout << testname << "... " << std::flush; } int64_t starttime = DateTime::NowMilliSeconds(); bool success = !nyrun_filelist(&runcf, filelist, count, 0, nullptr); int64_t duration = DateTime::NowMilliSeconds() - starttime; success &= console.cerr.empty(); if (Fancy) { if (interactive) std::cout << '\r'; if (success) { if (hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::green); #ifndef YUNI_OS_WINDOWS std::cout << " \u2713 "; #else std::cout << " OK "; #endif } else { if (hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::red); std::cout << " ERR "; } if (hasColorsOut) System::Console::ResetTextColor(std::cout); std::cout << testname; if (duration < 1200 or not hasColorsOut) { std::cout << " (" << duration << "ms) "; } else { System::Console::SetTextColor(std::cout, System::Console::purple); std::cout << " (" << duration << "ms) "; System::Console::ResetTextColor(std::cout); } std::cout << '\n'; if (not console.cerr.empty()) { console.cerr.trimRight(); console.cerr.replace("\n", "\n | "); std::cout << " | " << console.cerr << '\n'; } std::cout << std::flush; } return success; } void printStatstics(const String::Vector& optToRun, int64_t duration, uint32_t successCount, uint32_t failCount) { switch (optToRun.size()) { case 0: std::cout << "\n 0 test, "; break; case 1: std::cout << "\n 1 test"; break; default: std::cout << "\n " << optToRun.size() << " tests, "; break; } if (successCount and hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::green); switch (successCount) { case 0: std::cout << "0 passing"; break; case 1: std::cout << "1 passing"; break; default: std::cout << successCount << " passing"; break; } if (successCount and hasColorsOut) System::Console::ResetTextColor(std::cout); if (failCount) std::cout << ", "; if (failCount and hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::red); switch (failCount) { case 0: break; case 1: std::cout << "1 failed"; break; default: std::cout << "" << failCount << " failed"; break; } if (failCount and hasColorsOut) System::Console::ResetTextColor(std::cout); std::cout << " ("; if (duration < 10000) std::cout << duration << "ms)"; else std::cout << (duration / 1000) << "s)"; std::cout << "\n\n"; } bool runUnittsts(nyrun_cf_t& runcf, const String::Vector& optToRun, const char** filelist, uint32_t filecount) { if (optToRun.empty()) { std::cerr << "error: no unit test name\n"; return false; } uint32_t successCount = 0; uint32_t failCount = 0; int64_t starttime = DateTime::NowMilliSeconds(); runcf.build.ignore_atoms = nytrue; runcf.build.userdata = nullptr; runcf.build.on_unittest = nullptr; for (auto& testname: optToRun) { bool localsuccess = runtest<true>(runcf, testname, filelist, filecount); ++(localsuccess ? successCount : failCount); } int64_t duration = DateTime::NowMilliSeconds() - starttime; printStatstics(optToRun, duration, successCount, failCount); return (failCount == 0 and successCount != 0); } } // anonymous int main(int argc, char** argv) { // options String::Vector optToRun; String::Vector remainingArgs; bool optListAll = false; bool optWithNSLTests = false; // The command line options parser { GetOpt::Parser options; options.addFlag(optListAll, 'l', "list", "List all unit tests"); options.addFlag(optToRun, 'r', "run", "Run a specific test"); options.add(jobCount, 'j', "job", "Specifies the number of jobs (commands) to run simultaneously"); options.addFlag(optWithNSLTests, ' ', "with-nsl", "Import NSL unittests"); options.remainingArguments(remainingArgs); // Help options.addParagraph("\nHelp"); bool optBugreport = false; options.addFlag(optBugreport, ' ', "bugreport", "Display some useful information to report a bug"); bool optVersion = false; options.addFlag(optVersion, 'v', "version", "Print the version"); if (not options(argc, argv)) { if (options.errors()) { std::cout << "Abort due to error" << std::endl; return 1; } return 0; } if (optVersion) return printVersion(); if (optBugreport) return printBugReportInfo(); } uint32_t filecount = (uint32_t) remainingArgs.size(); if (filecount == 0) return printNoInputScript(argv[0]); auto** filelist = (const char**) malloc(sizeof(char*) * filecount); { String filename; for (uint32_t i = 0; i != filecount; ++i) { IO::Canonicalize(filename, remainingArgs[i]); remainingArgs[i] = filename; filelist[i] = remainingArgs[i].c_str(); } } nyrun_cf_t runcf; nyrun_cf_init(&runcf); if (optWithNSLTests) runcf.project.with_nsl_unittests = nytrue; int exitcode = EXIT_SUCCESS; hasColorsOut = System::Console::IsStdoutTTY(); hasColorsErr = System::Console::IsStderrTTY(); if (optListAll) { exitcode = listAllUnittests(runcf, filelist, filecount); } else { if (hasColorsOut) System::Console::SetTextColor(std::cout, System::Console::bold); std::cout << "nanyc C++/boostrap unittest " << nylib_version(); if (hasColorsOut) System::Console::ResetTextColor(std::cout); std::cout << '\n'; nylib_print_info_for_bugreport(); std::cout << ">\n"; for (uint32_t i = 0; i != filecount; ++i) std::cout << "> from '" << filelist[i] << "'\n"; std::cout << '\n'; if (0 == jobCount) System::CPU::Count(); // no unittest provided from the command - default: all if (optToRun.empty()) fetchUnittestList(runcf, optToRun, filelist, filecount); bool success = runUnittsts(runcf, optToRun, filelist, filecount); exitcode = (success) ? EXIT_SUCCESS : EXIT_FAILURE; } free(filelist); return exitcode; } <|endoftext|>
<commit_before>// Copyright (c) 2012 Steinwurf ApS // All Rights Reserved // // Distributed under the "BSD License". See the accompanying LICENSE.rst file. #include "random_buffer.hpp" #include <ctime> #include <cassert> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> #include "convert_endian.hpp" namespace sak { void random_buffer::fill(uint32_t size, bool embed_seed) { buffer::resize(size); // Random generator used to fill the buffer boost::random::mt19937 rng; // Uniform distribution for uint8_t type with range: [0, 255] boost::random::uniform_int_distribution<uint8_t> dist; uint32_t seed = (uint32_t)std::time(0); rng.seed(seed); uint32_t start = 0; uint8_t* buffer = buffer::data(); if (embed_seed) { assert(size > sizeof(uint32_t)); // Write the random seed to the beginning of the buffer big_endian::put<uint32_t>(seed, buffer); start = sizeof(uint32_t); } for (uint32_t i = start; i < size; ++i) { buffer[i] = dist(rng); } } bool random_buffer::verify() { uint32_t size = buffer::size(); assert(size > sizeof(uint32_t)); uint8_t* buffer = buffer::data(); // Read the random seed from the beginning of the buffer uint32_t seed = big_endian::get<uint32_t>(buffer); // Random generator used to verify the contents boost::random::mt19937 rng; // Uniform distribution for uint8_t type with range: [0, 255] boost::random::uniform_int_distribution<uint8_t> dist; // Use the embedded seed rng.seed(seed); uint32_t start = sizeof(uint32_t); for (uint32_t i = start; i < size; ++i) { // Test each byte against the random generated values if (buffer[i] != dist(rng)) return false; } return true; } } <commit_msg>Remove boost random from random_buffer<commit_after>// Copyright (c) 2012 Steinwurf ApS // All Rights Reserved // // Distributed under the "BSD License". See the accompanying LICENSE.rst file. #include "random_buffer.hpp" #include <cstdint> #include <cassert> #include <random> #include "convert_endian.hpp" namespace sak { void random_buffer::fill(uint32_t size, bool embed_seed) { buffer::resize(size); // Random generator used to fill the buffer std::mt19937 rng; // Uniform distribution for uint16_t type with range: [0, 255] // Note: MSVC does not allow uint8_t to be used as an IntType std::uniform_int_distribution<uint16_t> dist(0, 255); // Initialize the generator with a new random seed std::random_device random_device; uint32_t seed = (uint32_t)random_device(); rng.seed(seed); uint32_t start = 0; uint8_t* buffer = buffer::data(); if (embed_seed) { assert(size > sizeof(uint32_t)); // Write the random seed to the beginning of the buffer big_endian::put<uint32_t>(seed, buffer); start = sizeof(uint32_t); } for (uint32_t i = start; i < size; ++i) { buffer[i] = (uint8_t)dist(rng); } } bool random_buffer::verify() { uint32_t size = buffer::size(); assert(size > sizeof(uint32_t)); uint8_t* buffer = buffer::data(); // Read the random seed from the beginning of the buffer uint32_t seed = big_endian::get<uint32_t>(buffer); // Random generator used to verify the buffer contents std::mt19937 rng; // Uniform distribution for uint16_t type with range: [0, 255] // Note: MSVC does not allow uint8_t to be used as an IntType std::uniform_int_distribution<uint16_t> dist(0, 255); // Use the embedded seed rng.seed(seed); uint32_t start = sizeof(uint32_t); for (uint32_t i = start; i < size; ++i) { // Test each byte against the random generated values if (buffer[i] != dist(rng)) return false; } return true; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DescriptionGenerator.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-08 20:21:26 $ * * 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 * ************************************************************************/ #include "DescriptionGenerator.hxx" #ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_ #include <com/sun/star/beans/PropertyState.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_ #include <com/sun/star/beans/XPropertyState.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_ #include <com/sun/star/container/XChild.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_FILLSTYLE_HPP_ #include <com/sun/star/drawing/FillStyle.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPEDESCRIPTOR_HPP_ #include <com/sun/star/drawing/XShapeDescriptor.hpp> #endif #ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_ #include <com/sun/star/lang/IndexOutOfBoundsException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_ #include <com/sun/star/style/XStyle.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #include <com/sun/star/uno/Exception.hpp> // Includes for string resources. #ifndef _SVX_ACCESSIBILITY_HRC #include "accessibility.hrc" #endif #include "svdstr.hrc" #ifndef _SVX_DIALMGR_HXX #include "dialmgr.hxx" #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #include "xdef.hxx" #include "unoapi.hxx" #include "accessibility.hrc" #include "DGColorNameLookUp.hxx" using namespace ::rtl; using namespace ::com::sun::star; void SvxUnogetInternalNameForItem( const sal_Int16 nWhich, const rtl::OUString& rApiName, String& rInternalName ) throw(); namespace accessibility { DescriptionGenerator::DescriptionGenerator ( const uno::Reference<drawing::XShape>& xShape) : mxShape (xShape), mxSet (mxShape, uno::UNO_QUERY), mbIsFirstProperty (true) { } DescriptionGenerator::~DescriptionGenerator (void) { } void DescriptionGenerator::Initialize (sal_Int32 nResourceId) { // Get the string from the resource for the specified id. OUString sPrefix; { ::vos::OGuard aGuard (::Application::GetSolarMutex()); sPrefix = OUString (SVX_RESSTR (nResourceId)); } // Forward the call with the resulting string. Initialize (sPrefix); } void DescriptionGenerator::Initialize (::rtl::OUString sPrefix) { msDescription = sPrefix; if (mxSet.is()) { { ::vos::OGuard aGuard (::Application::GetSolarMutex()); msDescription.append (sal_Unicode (' ')); msDescription.append (OUString (SVX_RESSTR(RID_SVXSTR_A11Y_WITH))); msDescription.append (sal_Unicode (' ')); msDescription.append (OUString (SVX_RESSTR (RID_SVXSTR_A11Y_STYLE))); msDescription.append (sal_Unicode ('=')); } try { if (mxSet.is()) { uno::Any aValue = mxSet->getPropertyValue (OUString::createFromAscii ("Style")); uno::Reference<container::XNamed> xStyle (aValue, uno::UNO_QUERY); if (xStyle.is()) msDescription.append (xStyle->getName()); } else msDescription.append ( OUString::createFromAscii("<no style>")); } catch (::com::sun::star::beans::UnknownPropertyException) { msDescription.append ( OUString::createFromAscii("<unknown>")); } } } ::rtl::OUString DescriptionGenerator::operator() (void) { msDescription.append (sal_Unicode ('.')); return msDescription.makeStringAndClear(); } void DescriptionGenerator::AddProperty ( const OUString& sPropertyName, PropertyType aType, const sal_Int32 nLocalizedNameId, long nWhichId) { OUString sLocalizedName; { ::vos::OGuard aGuard (::Application::GetSolarMutex()); sLocalizedName = SVX_RESSTR (nLocalizedNameId); } AddProperty (sPropertyName, aType, sLocalizedName, nWhichId); } void DescriptionGenerator::AddProperty (const OUString& sPropertyName, PropertyType aType, const OUString& sLocalizedName, long nWhichId) { uno::Reference<beans::XPropertyState> xState (mxShape, uno::UNO_QUERY); if (xState.is() && xState->getPropertyState(sPropertyName)!=beans::PropertyState_DEFAULT_VALUE) if (mxSet.is()) { // Append a seperator from previous Properties. if ( ! mbIsFirstProperty) msDescription.append (sal_Unicode (',')); else { ::vos::OGuard aGuard (::Application::GetSolarMutex()); msDescription.append (sal_Unicode (' ')); msDescription.append (OUString (SVX_RESSTR(RID_SVXSTR_A11Y_AND))); msDescription.append (sal_Unicode (' ')); mbIsFirstProperty = false; } // Delegate to type specific property handling. switch (aType) { case COLOR: AddColor (sPropertyName, sLocalizedName); break; case INTEGER: AddInteger (sPropertyName, sLocalizedName); break; case STRING: AddString (sPropertyName, sLocalizedName, nWhichId); break; case FILL_STYLE: AddFillStyle (sPropertyName, sLocalizedName); break; } } } void DescriptionGenerator::AppendString (const ::rtl::OUString& sString) { msDescription.append (sString); } void DescriptionGenerator::AddLineProperties (void) { AddProperty (OUString::createFromAscii ("LineColor"), DescriptionGenerator::COLOR, SIP_XA_LINECOLOR); AddProperty (OUString::createFromAscii ("LineDashName"), DescriptionGenerator::STRING, SIP_XA_LINEDASH, XATTR_LINEDASH); AddProperty (OUString::createFromAscii ("LineWidth"), DescriptionGenerator::INTEGER, SIP_XA_LINEWIDTH); } /** The fill style is described by the property "FillStyle". Depending on its value a hatch-, gradient-, or bitmap name is appended. */ void DescriptionGenerator::AddFillProperties (void) { AddProperty (OUString::createFromAscii ("FillStyle"), DescriptionGenerator::FILL_STYLE, SIP_XA_FILLSTYLE); } void DescriptionGenerator::Add3DProperties (void) { AddProperty (OUString::createFromAscii ("D3DMaterialColor"), DescriptionGenerator::COLOR, RID_SVXSTR_A11Y_3D_MATERIAL_COLOR); AddLineProperties (); AddFillProperties (); } void DescriptionGenerator::AddTextProperties (void) { AddProperty (OUString::createFromAscii ("CharColor"), DescriptionGenerator::COLOR); AddFillProperties (); } /** Search for the given color in the global color table. If found append its name to the description. Otherwise append its RGB tuple. */ void DescriptionGenerator::AddColor (const OUString& sPropertyName, const OUString& sLocalizedName) { msDescription.append (sLocalizedName); msDescription.append (sal_Unicode('=')); try { long nValue; if (mxSet.is()) { uno::Any aValue = mxSet->getPropertyValue (sPropertyName); aValue >>= nValue; } msDescription.append (DGColorNameLookUp::Instance().LookUpColor (nValue)); } catch (::com::sun::star::beans::UnknownPropertyException) { msDescription.append ( OUString::createFromAscii("<unknown>")); } } void DescriptionGenerator::AddUnknown (const OUString& sPropertyName, const OUString& sLocalizedName) { // uno::Any aValue = mxSet->getPropertyValue (sPropertyName); msDescription.append (sLocalizedName); } void DescriptionGenerator::AddInteger (const OUString& sPropertyName, const OUString& sLocalizedName) { msDescription.append (sLocalizedName); msDescription.append (sal_Unicode('=')); try { if (mxSet.is()) { uno::Any aValue = mxSet->getPropertyValue (sPropertyName); long nValue; aValue >>= nValue; msDescription.append (nValue); } } catch (::com::sun::star::beans::UnknownPropertyException) { msDescription.append ( OUString::createFromAscii("<unknown>")); } } void DescriptionGenerator::AddString (const OUString& sPropertyName, const OUString& sLocalizedName, long nWhichId) { msDescription.append (sLocalizedName); msDescription.append (sal_Unicode('=')); try { if (mxSet.is()) { uno::Any aValue = mxSet->getPropertyValue (sPropertyName); OUString sValue; aValue >>= sValue; if (nWhichId >= 0) { ::vos::OGuard aGuard (::Application::GetSolarMutex()); String sLocalizedValue; SvxUnogetInternalNameForItem (nWhichId, sValue, sLocalizedValue); msDescription.append (sLocalizedValue); } else msDescription.append (sValue); } } catch (::com::sun::star::beans::UnknownPropertyException) { msDescription.append ( OUString::createFromAscii("<unknown>")); } } void DescriptionGenerator::AddFillStyle (const OUString& sPropertyName, const OUString& sLocalizedName) { msDescription.append (sLocalizedName); msDescription.append (sal_Unicode('=')); try { if (mxSet.is()) { uno::Any aValue = mxSet->getPropertyValue (sPropertyName); drawing::FillStyle aFillStyle; aValue >>= aFillStyle; // Get the fill style name from the resource. OUString sFillStyleName; { ::vos::OGuard aGuard (::Application::GetSolarMutex()); switch (aFillStyle) { case drawing::FillStyle_NONE: sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_NONE); break; case drawing::FillStyle_SOLID: sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_SOLID); break; case drawing::FillStyle_GRADIENT: sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_GRADIENT); break; case drawing::FillStyle_HATCH: sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_HATCH); break; case drawing::FillStyle_BITMAP: sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_BITMAP); break; } } msDescription.append (sFillStyleName); // Append the appropriate properties. switch (aFillStyle) { case drawing::FillStyle_NONE: break; case drawing::FillStyle_SOLID: AddProperty (OUString::createFromAscii ("FillColor"), COLOR, SIP_XA_FILLCOLOR); break; case drawing::FillStyle_GRADIENT: AddProperty (OUString::createFromAscii ("FillGradientName"), STRING, SIP_XA_FILLGRADIENT, XATTR_FILLGRADIENT); break; case drawing::FillStyle_HATCH: AddProperty (OUString::createFromAscii ("FillColor"), COLOR, SIP_XA_FILLCOLOR); AddProperty (OUString::createFromAscii ("FillHatchName"), STRING, SIP_XA_FILLHATCH, XATTR_FILLHATCH); break; case drawing::FillStyle_BITMAP: AddProperty (OUString::createFromAscii ("FillBitmapName"), STRING, SIP_XA_FILLBITMAP, XATTR_FILLBITMAP); break; } } } catch (::com::sun::star::beans::UnknownPropertyException) { msDescription.append ( OUString::createFromAscii("<unknown>")); } } void DescriptionGenerator::AddPropertyNames (void) { if (mxSet.is()) { uno::Reference<beans::XPropertySetInfo> xInfo (mxSet->getPropertySetInfo()); if (xInfo.is()) { uno::Sequence<beans::Property> aPropertyList (xInfo->getProperties ()); for (int i=0; i<aPropertyList.getLength(); i++) { msDescription.append (aPropertyList[i].Name); msDescription.append (sal_Unicode(',')); } } } } } // end of namespace accessibility <commit_msg>INTEGRATION: CWS warnings01 (1.7.222); FILE MERGED 2006/01/05 12:02:17 fs 1.7.222.1: #i55991# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DescriptionGenerator.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2006-06-19 14:55:00 $ * * 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 * ************************************************************************/ #include "DescriptionGenerator.hxx" #ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_ #include <com/sun/star/beans/PropertyState.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_ #include <com/sun/star/beans/XPropertyState.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_ #include <com/sun/star/container/XChild.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_FILLSTYLE_HPP_ #include <com/sun/star/drawing/FillStyle.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPEDESCRIPTOR_HPP_ #include <com/sun/star/drawing/XShapeDescriptor.hpp> #endif #ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_ #include <com/sun/star/lang/IndexOutOfBoundsException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_ #include <com/sun/star/style/XStyle.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #include <com/sun/star/uno/Exception.hpp> // Includes for string resources. #ifndef _SVX_ACCESSIBILITY_HRC #include "accessibility.hrc" #endif #include "svdstr.hrc" #ifndef _SVX_DIALMGR_HXX #include "dialmgr.hxx" #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #include "xdef.hxx" #include "unoapi.hxx" #include "accessibility.hrc" #include "DGColorNameLookUp.hxx" using namespace ::rtl; using namespace ::com::sun::star; void SvxUnogetInternalNameForItem( const sal_Int16 nWhich, const rtl::OUString& rApiName, String& rInternalName ) throw(); namespace accessibility { DescriptionGenerator::DescriptionGenerator ( const uno::Reference<drawing::XShape>& xShape) : mxShape (xShape), mxSet (mxShape, uno::UNO_QUERY), mbIsFirstProperty (true) { } DescriptionGenerator::~DescriptionGenerator (void) { } void DescriptionGenerator::Initialize (sal_Int32 nResourceId) { // Get the string from the resource for the specified id. OUString sPrefix; { ::vos::OGuard aGuard (::Application::GetSolarMutex()); sPrefix = OUString (SVX_RESSTR (nResourceId)); } // Forward the call with the resulting string. Initialize (sPrefix); } void DescriptionGenerator::Initialize (::rtl::OUString sPrefix) { msDescription = sPrefix; if (mxSet.is()) { { ::vos::OGuard aGuard (::Application::GetSolarMutex()); msDescription.append (sal_Unicode (' ')); msDescription.append (OUString (SVX_RESSTR(RID_SVXSTR_A11Y_WITH))); msDescription.append (sal_Unicode (' ')); msDescription.append (OUString (SVX_RESSTR (RID_SVXSTR_A11Y_STYLE))); msDescription.append (sal_Unicode ('=')); } try { if (mxSet.is()) { uno::Any aValue = mxSet->getPropertyValue (OUString::createFromAscii ("Style")); uno::Reference<container::XNamed> xStyle (aValue, uno::UNO_QUERY); if (xStyle.is()) msDescription.append (xStyle->getName()); } else msDescription.append ( OUString::createFromAscii("<no style>")); } catch (::com::sun::star::beans::UnknownPropertyException) { msDescription.append ( OUString::createFromAscii("<unknown>")); } } } ::rtl::OUString DescriptionGenerator::operator() (void) { msDescription.append (sal_Unicode ('.')); return msDescription.makeStringAndClear(); } void DescriptionGenerator::AddProperty ( const OUString& sPropertyName, PropertyType aType, const sal_Int32 nLocalizedNameId, long nWhichId) { OUString sLocalizedName; { ::vos::OGuard aGuard (::Application::GetSolarMutex()); sLocalizedName = SVX_RESSTR (nLocalizedNameId); } AddProperty (sPropertyName, aType, sLocalizedName, nWhichId); } void DescriptionGenerator::AddProperty (const OUString& sPropertyName, PropertyType aType, const OUString& sLocalizedName, long nWhichId) { uno::Reference<beans::XPropertyState> xState (mxShape, uno::UNO_QUERY); if (xState.is() && xState->getPropertyState(sPropertyName)!=beans::PropertyState_DEFAULT_VALUE) if (mxSet.is()) { // Append a seperator from previous Properties. if ( ! mbIsFirstProperty) msDescription.append (sal_Unicode (',')); else { ::vos::OGuard aGuard (::Application::GetSolarMutex()); msDescription.append (sal_Unicode (' ')); msDescription.append (OUString (SVX_RESSTR(RID_SVXSTR_A11Y_AND))); msDescription.append (sal_Unicode (' ')); mbIsFirstProperty = false; } // Delegate to type specific property handling. switch (aType) { case COLOR: AddColor (sPropertyName, sLocalizedName); break; case INTEGER: AddInteger (sPropertyName, sLocalizedName); break; case STRING: AddString (sPropertyName, sLocalizedName, nWhichId); break; case FILL_STYLE: AddFillStyle (sPropertyName, sLocalizedName); break; } } } void DescriptionGenerator::AppendString (const ::rtl::OUString& sString) { msDescription.append (sString); } void DescriptionGenerator::AddLineProperties (void) { AddProperty (OUString::createFromAscii ("LineColor"), DescriptionGenerator::COLOR, SIP_XA_LINECOLOR); AddProperty (OUString::createFromAscii ("LineDashName"), DescriptionGenerator::STRING, SIP_XA_LINEDASH, XATTR_LINEDASH); AddProperty (OUString::createFromAscii ("LineWidth"), DescriptionGenerator::INTEGER, SIP_XA_LINEWIDTH); } /** The fill style is described by the property "FillStyle". Depending on its value a hatch-, gradient-, or bitmap name is appended. */ void DescriptionGenerator::AddFillProperties (void) { AddProperty (OUString::createFromAscii ("FillStyle"), DescriptionGenerator::FILL_STYLE, SIP_XA_FILLSTYLE); } void DescriptionGenerator::Add3DProperties (void) { AddProperty (OUString::createFromAscii ("D3DMaterialColor"), DescriptionGenerator::COLOR, RID_SVXSTR_A11Y_3D_MATERIAL_COLOR); AddLineProperties (); AddFillProperties (); } void DescriptionGenerator::AddTextProperties (void) { AddProperty (OUString::createFromAscii ("CharColor"), DescriptionGenerator::COLOR); AddFillProperties (); } /** Search for the given color in the global color table. If found append its name to the description. Otherwise append its RGB tuple. */ void DescriptionGenerator::AddColor (const OUString& sPropertyName, const OUString& sLocalizedName) { msDescription.append (sLocalizedName); msDescription.append (sal_Unicode('=')); try { long nValue; if (mxSet.is()) { uno::Any aValue = mxSet->getPropertyValue (sPropertyName); aValue >>= nValue; } msDescription.append (DGColorNameLookUp::Instance().LookUpColor (nValue)); } catch (::com::sun::star::beans::UnknownPropertyException) { msDescription.append ( OUString::createFromAscii("<unknown>")); } } void DescriptionGenerator::AddUnknown (const OUString& /*sPropertyName*/, const OUString& sLocalizedName) { // uno::Any aValue = mxSet->getPropertyValue (sPropertyName); msDescription.append (sLocalizedName); } void DescriptionGenerator::AddInteger (const OUString& sPropertyName, const OUString& sLocalizedName) { msDescription.append (sLocalizedName); msDescription.append (sal_Unicode('=')); try { if (mxSet.is()) { uno::Any aValue = mxSet->getPropertyValue (sPropertyName); long nValue; aValue >>= nValue; msDescription.append (nValue); } } catch (::com::sun::star::beans::UnknownPropertyException) { msDescription.append ( OUString::createFromAscii("<unknown>")); } } void DescriptionGenerator::AddString (const OUString& sPropertyName, const OUString& sLocalizedName, long nWhichId) { msDescription.append (sLocalizedName); msDescription.append (sal_Unicode('=')); try { if (mxSet.is()) { uno::Any aValue = mxSet->getPropertyValue (sPropertyName); OUString sValue; aValue >>= sValue; if (nWhichId >= 0) { ::vos::OGuard aGuard (::Application::GetSolarMutex()); String sLocalizedValue; SvxUnogetInternalNameForItem (nWhichId, sValue, sLocalizedValue); msDescription.append (sLocalizedValue); } else msDescription.append (sValue); } } catch (::com::sun::star::beans::UnknownPropertyException) { msDescription.append ( OUString::createFromAscii("<unknown>")); } } void DescriptionGenerator::AddFillStyle (const OUString& sPropertyName, const OUString& sLocalizedName) { msDescription.append (sLocalizedName); msDescription.append (sal_Unicode('=')); try { if (mxSet.is()) { uno::Any aValue = mxSet->getPropertyValue (sPropertyName); drawing::FillStyle aFillStyle; aValue >>= aFillStyle; // Get the fill style name from the resource. OUString sFillStyleName; { ::vos::OGuard aGuard (::Application::GetSolarMutex()); switch (aFillStyle) { case drawing::FillStyle_NONE: sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_NONE); break; case drawing::FillStyle_SOLID: sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_SOLID); break; case drawing::FillStyle_GRADIENT: sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_GRADIENT); break; case drawing::FillStyle_HATCH: sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_HATCH); break; case drawing::FillStyle_BITMAP: sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_BITMAP); break; case drawing::FillStyle_MAKE_FIXED_SIZE: break; } } msDescription.append (sFillStyleName); // Append the appropriate properties. switch (aFillStyle) { case drawing::FillStyle_NONE: break; case drawing::FillStyle_SOLID: AddProperty (OUString::createFromAscii ("FillColor"), COLOR, SIP_XA_FILLCOLOR); break; case drawing::FillStyle_GRADIENT: AddProperty (OUString::createFromAscii ("FillGradientName"), STRING, SIP_XA_FILLGRADIENT, XATTR_FILLGRADIENT); break; case drawing::FillStyle_HATCH: AddProperty (OUString::createFromAscii ("FillColor"), COLOR, SIP_XA_FILLCOLOR); AddProperty (OUString::createFromAscii ("FillHatchName"), STRING, SIP_XA_FILLHATCH, XATTR_FILLHATCH); break; case drawing::FillStyle_BITMAP: AddProperty (OUString::createFromAscii ("FillBitmapName"), STRING, SIP_XA_FILLBITMAP, XATTR_FILLBITMAP); break; case drawing::FillStyle_MAKE_FIXED_SIZE: break; } } } catch (::com::sun::star::beans::UnknownPropertyException) { msDescription.append ( OUString::createFromAscii("<unknown>")); } } void DescriptionGenerator::AddPropertyNames (void) { if (mxSet.is()) { uno::Reference<beans::XPropertySetInfo> xInfo (mxSet->getPropertySetInfo()); if (xInfo.is()) { uno::Sequence<beans::Property> aPropertyList (xInfo->getProperties ()); for (int i=0; i<aPropertyList.getLength(); i++) { msDescription.append (aPropertyList[i].Name); msDescription.append (sal_Unicode(',')); } } } } } // end of namespace accessibility <|endoftext|>
<commit_before>#ifndef __CPP_EVENTS__CONFIG__HPP #define __CPP_EVENTS__CONFIG__HPP //Platform detection #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) # define PLATFORM_DIR WinApi #elif defined(__GNUC__) # define PLATFORM_DIR POSIX #else # error "Unsupported target platform!" #endif // Platform-specific path #define PLATFORM_PATH_HELPER_0(Path) #Path #define PLATFORM_PATH_HELPER_1(Dir, Path) PLATFORM_PATH_HELPER_0(Dir ## / ## Path) #define PLATFORM_PATH_HELPER_2(Dir, Path) PLATFORM_PATH_HELPER_1(Dir, Path) #define PLATFORM_PATH(Path) PLATFORM_PATH_HELPER_2(PLATFORM_DIR, Path) #define DISABLE_COPY(Class) \ private: \ Class(Class const &); \ Class & operator=(Class const &); #endif //__CPP_EVENTS__CONFIG__HPP<commit_msg>-: Fixed: wrong usage of the concatenation preprocessor operator in <Cpp/Events/Config.hpp><commit_after>#ifndef __CPP_EVENTS__CONFIG__HPP #define __CPP_EVENTS__CONFIG__HPP //Platform detection #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) # define PLATFORM_DIR WinApi #elif defined(__GNUC__) # define PLATFORM_DIR POSIX #else # error "Unsupported target platform!" #endif // Platform-specific path #define PLATFORM_PATH_HELPER_0(Path) #Path #define PLATFORM_PATH_HELPER_1(Dir, Path) PLATFORM_PATH_HELPER_0(Dir/Path) #define PLATFORM_PATH_HELPER_2(Dir, Path) PLATFORM_PATH_HELPER_1(Dir, Path) #define PLATFORM_PATH(Path) PLATFORM_PATH_HELPER_2(PLATFORM_DIR, Path) #define DISABLE_COPY(Class) \ private: \ Class(Class const &); \ Class & operator=(Class const &); #endif //__CPP_EVENTS__CONFIG__HPP<|endoftext|>
<commit_before>//===--- Stmt.cpp - Swift Language Statement ASTs -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 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 // //===----------------------------------------------------------------------===// // // This file implements the Stmt class and subclasses. // //===----------------------------------------------------------------------===// #include "swift/AST/Stmt.h" #include "swift/AST/ASTContext.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "swift/AST/Pattern.h" #include "llvm/ADT/PointerUnion.h" using namespace swift; //===----------------------------------------------------------------------===// // Stmt methods. //===----------------------------------------------------------------------===// // Only allow allocation of Stmts using the allocator in ASTContext. void *Stmt::operator new(size_t Bytes, ASTContext &C, unsigned Alignment) { return C.Allocate(Bytes, Alignment); } StringRef Stmt::getKindName(StmtKind K) { switch (K) { #define STMT(Id, Parent) case StmtKind::Id: return #Id; #include "swift/AST/StmtNodes.def" } llvm_unreachable("bad StmtKind"); } // Helper functions to check statically whether a method has been // overridden from its implementation in Stmt. The sort of thing you // need when you're avoiding v-tables. namespace { template <typename ReturnType, typename Class> constexpr bool isOverriddenFromStmt(ReturnType (Class::*)() const) { return true; } template <typename ReturnType> constexpr bool isOverriddenFromStmt(ReturnType (Stmt::*)() const) { return false; } template <bool IsOverridden> struct Dispatch; /// Dispatch down to a concrete override. template <> struct Dispatch<true> { template <class T> static SourceLoc getStartLoc(const T *S) { return S->getStartLoc(); } template <class T> static SourceLoc getEndLoc(const T *S) { return S->getEndLoc(); } template <class T> static SourceRange getSourceRange(const T *S) { return S->getSourceRange(); } }; /// Default implementations for when a method isn't overridden. template <> struct Dispatch<false> { template <class T> static SourceLoc getStartLoc(const T *S) { return S->getSourceRange().Start; } template <class T> static SourceLoc getEndLoc(const T *S) { return S->getSourceRange().End; } template <class T> static SourceRange getSourceRange(const T *S) { return { S->getStartLoc(), S->getEndLoc() }; } }; } template <class T> static SourceRange getSourceRangeImpl(const T *S) { static_assert(isOverriddenFromStmt(&T::getSourceRange) || (isOverriddenFromStmt(&T::getStartLoc) && isOverriddenFromStmt(&T::getEndLoc)), "Stmt subclass must implement either getSourceRange() " "or getStartLoc()/getEndLoc()"); return Dispatch<isOverriddenFromStmt(&T::getSourceRange)>::getSourceRange(S); } SourceRange Stmt::getSourceRange() const { switch (getKind()) { #define STMT(ID, PARENT) \ case StmtKind::ID: return getSourceRangeImpl(cast<ID##Stmt>(this)); #include "swift/AST/StmtNodes.def" } llvm_unreachable("statement type not handled!"); } template <class T> static SourceLoc getStartLocImpl(const T *S) { return Dispatch<isOverriddenFromStmt(&T::getStartLoc)>::getStartLoc(S); } SourceLoc Stmt::getStartLoc() const { switch (getKind()) { #define STMT(ID, PARENT) \ case StmtKind::ID: return getStartLocImpl(cast<ID##Stmt>(this)); #include "swift/AST/StmtNodes.def" } llvm_unreachable("statement type not handled!"); } template <class T> static SourceLoc getEndLocImpl(const T *S) { return Dispatch<isOverriddenFromStmt(&T::getEndLoc)>::getEndLoc(S); } SourceLoc Stmt::getEndLoc() const { switch (getKind()) { #define STMT(ID, PARENT) \ case StmtKind::ID: return getEndLocImpl(cast<ID##Stmt>(this)); #include "swift/AST/StmtNodes.def" } llvm_unreachable("statement type not handled!"); } BraceStmt::BraceStmt(SourceLoc lbloc, ArrayRef<ASTNode> elts, SourceLoc rbloc, Optional<bool> implicit) : Stmt(StmtKind::Brace, getDefaultImplicitFlag(implicit, lbloc)), NumElements(elts.size()), LBLoc(lbloc), RBLoc(rbloc) { std::uninitialized_copy(elts.begin(), elts.end(), getTrailingObjects<ASTNode>()); } BraceStmt *BraceStmt::create(ASTContext &ctx, SourceLoc lbloc, ArrayRef<ASTNode> elts, SourceLoc rbloc, Optional<bool> implicit) { assert(std::none_of(elts.begin(), elts.end(), [](ASTNode node) -> bool { return node.isNull(); }) && "null element in BraceStmt"); void *Buffer = ctx.Allocate(totalSizeToAlloc<ASTNode>(elts.size()), alignof(BraceStmt)); return ::new(Buffer) BraceStmt(lbloc, elts, rbloc, implicit); } SourceLoc ReturnStmt::getStartLoc() const { if (ReturnLoc.isInvalid() && Result) return Result->getStartLoc(); return ReturnLoc; } SourceLoc ReturnStmt::getEndLoc() const { if (Result && Result->getEndLoc().isValid()) return Result->getEndLoc(); return ReturnLoc; } SourceLoc ThrowStmt::getEndLoc() const { return SubExpr->getEndLoc(); } SourceLoc DeferStmt::getEndLoc() const { return tempDecl->getBody()->getEndLoc(); } /// Dig the original user's body of the defer out for AST fidelity. BraceStmt *DeferStmt::getBodyAsWritten() const { return tempDecl->getBody(); } bool LabeledStmt::isPossibleContinueTarget() const { switch (getKind()) { #define LABELED_STMT(ID, PARENT) #define STMT(ID, PARENT) case StmtKind::ID: #include "swift/AST/StmtNodes.def" llvm_unreachable("not a labeled statement"); // Sema has diagnostics with hard-coded expectations about what // statements return false from this method. case StmtKind::If: case StmtKind::Guard: case StmtKind::Switch: return false; case StmtKind::Do: case StmtKind::DoCatch: case StmtKind::RepeatWhile: case StmtKind::For: case StmtKind::ForEach: case StmtKind::While: return true; } llvm_unreachable("statement kind unhandled!"); } bool LabeledStmt::requiresLabelOnJump() const { switch (getKind()) { #define LABELED_STMT(ID, PARENT) #define STMT(ID, PARENT) case StmtKind::ID: #include "swift/AST/StmtNodes.def" llvm_unreachable("not a labeled statement"); case StmtKind::If: case StmtKind::Do: case StmtKind::DoCatch: case StmtKind::Guard: // Guard doesn't allow labels, so no break/continue. return true; case StmtKind::RepeatWhile: case StmtKind::For: case StmtKind::ForEach: case StmtKind::Switch: case StmtKind::While: return false; } llvm_unreachable("statement kind unhandled!"); } void ForEachStmt::setPattern(Pattern *p) { Pat = p; Pat->markOwnedByStatement(this); } void CatchStmt::setErrorPattern(Pattern *pattern) { ErrorPattern = pattern; ErrorPattern->markOwnedByStatement(this); } DoCatchStmt *DoCatchStmt::create(ASTContext &ctx, LabeledStmtInfo labelInfo, SourceLoc doLoc, Stmt *body, ArrayRef<CatchStmt*> catches, Optional<bool> implicit) { void *mem = ctx.Allocate(totalSizeToAlloc<CatchStmt*>(catches.size()), alignof(DoCatchStmt)); return ::new (mem) DoCatchStmt(labelInfo, doLoc, body, catches, implicit); } bool DoCatchStmt::isSyntacticallyExhaustive() const { for (auto clause : getCatches()) { if (clause->isSyntacticallyExhaustive()) return true; } return false; } void LabeledConditionalStmt::setCond(StmtCondition e) { // When set a condition into a Conditional Statement, inform each of the // variables bound in any patterns that this is the owning statement for the // pattern. for (auto &elt : e) if (auto pat = elt.getPatternOrNull()) pat->markOwnedByStatement(this); Cond = e; } bool CatchStmt::isSyntacticallyExhaustive() const { // It cannot have a guard expression and the pattern cannot be refutable. return getGuardExpr() == nullptr && !getErrorPattern()->isRefutablePattern(); } PoundAvailableInfo *PoundAvailableInfo::create(ASTContext &ctx, SourceLoc PoundLoc, ArrayRef<AvailabilitySpec *> queries, SourceLoc RParenLoc) { unsigned size = totalSizeToAlloc<AvailabilitySpec *>(queries.size()); void *Buffer = ctx.Allocate(size, alignof(PoundAvailableInfo)); return ::new (Buffer) PoundAvailableInfo(PoundLoc, queries, RParenLoc); } SourceLoc PoundAvailableInfo::getEndLoc() const { if (RParenLoc.isInvalid()) { if (NumQueries == 0) { return PoundLoc; } return getQueries()[NumQueries - 1]->getSourceRange().End; } return RParenLoc; } void PoundAvailableInfo:: getPlatformKeywordLocs(SmallVectorImpl<SourceLoc> &PlatformLocs) { for (unsigned i = 0; i < NumQueries; i++) { auto *VersionSpec = dyn_cast<PlatformVersionConstraintAvailabilitySpec>(getQueries()[i]); if (!VersionSpec) continue; PlatformLocs.push_back(VersionSpec->getPlatformLoc()); } } SourceRange StmtConditionElement::getSourceRange() const { switch (getKind()) { case StmtConditionElement::CK_Boolean: return getBoolean()->getSourceRange(); case StmtConditionElement::CK_Availability: return getAvailability()->getSourceRange(); case StmtConditionElement::CK_PatternBinding: SourceLoc Start; if (IntroducerLoc.isValid()) Start = IntroducerLoc; else Start = getPattern()->getStartLoc(); SourceLoc End = getInitializer()->getEndLoc(); if (Start.isValid() && End.isValid()) { return SourceRange(Start, End); } else { return SourceRange(); } } } SourceLoc StmtConditionElement::getStartLoc() const { switch (getKind()) { case StmtConditionElement::CK_Boolean: return getBoolean()->getStartLoc(); case StmtConditionElement::CK_Availability: return getAvailability()->getStartLoc(); case StmtConditionElement::CK_PatternBinding: SourceLoc Start; if (IntroducerLoc.isValid()) Start = IntroducerLoc; else Start = getPattern()->getStartLoc(); SourceLoc End = getInitializer()->getEndLoc(); if (Start.isValid() && End.isValid()) { return Start; } else { return SourceLoc(); } } } SourceLoc StmtConditionElement::getEndLoc() const { switch (getKind()) { case StmtConditionElement::CK_Boolean: return getBoolean()->getEndLoc(); case StmtConditionElement::CK_Availability: return getAvailability()->getEndLoc(); case StmtConditionElement::CK_PatternBinding: SourceLoc Start; if (IntroducerLoc.isValid()) Start = IntroducerLoc; else Start = getPattern()->getStartLoc(); SourceLoc End = getInitializer()->getEndLoc(); if (Start.isValid() && End.isValid()) { return End; } else { return SourceLoc(); } } } static StmtCondition exprToCond(Expr *C, ASTContext &Ctx) { StmtConditionElement Arr[] = { StmtConditionElement(C) }; return Ctx.AllocateCopy(Arr); } IfStmt::IfStmt(SourceLoc IfLoc, Expr *Cond, Stmt *Then, SourceLoc ElseLoc, Stmt *Else, Optional<bool> implicit, ASTContext &Ctx) : IfStmt(LabeledStmtInfo(), IfLoc, exprToCond(Cond, Ctx), Then, ElseLoc, Else, implicit) { } GuardStmt::GuardStmt(SourceLoc GuardLoc, Expr *Cond, Stmt *Body, Optional<bool> implicit, ASTContext &Ctx) : GuardStmt(GuardLoc, exprToCond(Cond, Ctx), Body, implicit) { } SourceLoc RepeatWhileStmt::getEndLoc() const { return Cond->getEndLoc(); } SourceRange CaseLabelItem::getSourceRange() const { if (auto *E = getGuardExpr()) return { CasePattern->getStartLoc(), E->getEndLoc() }; return CasePattern->getSourceRange(); } SourceLoc CaseLabelItem::getStartLoc() const { return CasePattern->getStartLoc(); } SourceLoc CaseLabelItem::getEndLoc() const { if (auto *E = getGuardExpr()) return E->getEndLoc(); return CasePattern->getEndLoc(); } CaseStmt::CaseStmt(SourceLoc CaseLoc, ArrayRef<CaseLabelItem> CaseLabelItems, bool HasBoundDecls, SourceLoc ColonLoc, Stmt *Body, Optional<bool> Implicit) : Stmt(StmtKind::Case, getDefaultImplicitFlag(Implicit, CaseLoc)), CaseLoc(CaseLoc), ColonLoc(ColonLoc), BodyAndHasBoundDecls(Body, HasBoundDecls), NumPatterns(CaseLabelItems.size()) { assert(NumPatterns > 0 && "case block must have at least one pattern"); MutableArrayRef<CaseLabelItem> Items{ getTrailingObjects<CaseLabelItem>(), NumPatterns }; for (unsigned i = 0; i < NumPatterns; ++i) { new (&Items[i]) CaseLabelItem(CaseLabelItems[i]); Items[i].getPattern()->markOwnedByStatement(this); } } CaseStmt *CaseStmt::create(ASTContext &C, SourceLoc CaseLoc, ArrayRef<CaseLabelItem> CaseLabelItems, bool HasBoundDecls, SourceLoc ColonLoc, Stmt *Body, Optional<bool> Implicit) { void *Mem = C.Allocate(totalSizeToAlloc<CaseLabelItem>(CaseLabelItems.size()), alignof(CaseStmt)); return ::new (Mem) CaseStmt(CaseLoc, CaseLabelItems, HasBoundDecls, ColonLoc, Body, Implicit); } SwitchStmt *SwitchStmt::create(LabeledStmtInfo LabelInfo, SourceLoc SwitchLoc, Expr *SubjectExpr, SourceLoc LBraceLoc, ArrayRef<CaseStmt *> Cases, SourceLoc RBraceLoc, ASTContext &C) { void *p = C.Allocate(totalSizeToAlloc<CaseStmt *>(Cases.size()), alignof(SwitchStmt)); SwitchStmt *theSwitch = ::new (p) SwitchStmt(LabelInfo, SwitchLoc, SubjectExpr, LBraceLoc, Cases.size(), RBraceLoc); std::uninitialized_copy(Cases.begin(), Cases.end(), theSwitch->getTrailingObjects<CaseStmt *>()); return theSwitch; } <commit_msg>Changed the PatternBinding StmtConditionElement start/end loc to call getSourceRange instead<commit_after>//===--- Stmt.cpp - Swift Language Statement ASTs -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 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 // //===----------------------------------------------------------------------===// // // This file implements the Stmt class and subclasses. // //===----------------------------------------------------------------------===// #include "swift/AST/Stmt.h" #include "swift/AST/ASTContext.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "swift/AST/Pattern.h" #include "llvm/ADT/PointerUnion.h" using namespace swift; //===----------------------------------------------------------------------===// // Stmt methods. //===----------------------------------------------------------------------===// // Only allow allocation of Stmts using the allocator in ASTContext. void *Stmt::operator new(size_t Bytes, ASTContext &C, unsigned Alignment) { return C.Allocate(Bytes, Alignment); } StringRef Stmt::getKindName(StmtKind K) { switch (K) { #define STMT(Id, Parent) case StmtKind::Id: return #Id; #include "swift/AST/StmtNodes.def" } llvm_unreachable("bad StmtKind"); } // Helper functions to check statically whether a method has been // overridden from its implementation in Stmt. The sort of thing you // need when you're avoiding v-tables. namespace { template <typename ReturnType, typename Class> constexpr bool isOverriddenFromStmt(ReturnType (Class::*)() const) { return true; } template <typename ReturnType> constexpr bool isOverriddenFromStmt(ReturnType (Stmt::*)() const) { return false; } template <bool IsOverridden> struct Dispatch; /// Dispatch down to a concrete override. template <> struct Dispatch<true> { template <class T> static SourceLoc getStartLoc(const T *S) { return S->getStartLoc(); } template <class T> static SourceLoc getEndLoc(const T *S) { return S->getEndLoc(); } template <class T> static SourceRange getSourceRange(const T *S) { return S->getSourceRange(); } }; /// Default implementations for when a method isn't overridden. template <> struct Dispatch<false> { template <class T> static SourceLoc getStartLoc(const T *S) { return S->getSourceRange().Start; } template <class T> static SourceLoc getEndLoc(const T *S) { return S->getSourceRange().End; } template <class T> static SourceRange getSourceRange(const T *S) { return { S->getStartLoc(), S->getEndLoc() }; } }; } template <class T> static SourceRange getSourceRangeImpl(const T *S) { static_assert(isOverriddenFromStmt(&T::getSourceRange) || (isOverriddenFromStmt(&T::getStartLoc) && isOverriddenFromStmt(&T::getEndLoc)), "Stmt subclass must implement either getSourceRange() " "or getStartLoc()/getEndLoc()"); return Dispatch<isOverriddenFromStmt(&T::getSourceRange)>::getSourceRange(S); } SourceRange Stmt::getSourceRange() const { switch (getKind()) { #define STMT(ID, PARENT) \ case StmtKind::ID: return getSourceRangeImpl(cast<ID##Stmt>(this)); #include "swift/AST/StmtNodes.def" } llvm_unreachable("statement type not handled!"); } template <class T> static SourceLoc getStartLocImpl(const T *S) { return Dispatch<isOverriddenFromStmt(&T::getStartLoc)>::getStartLoc(S); } SourceLoc Stmt::getStartLoc() const { switch (getKind()) { #define STMT(ID, PARENT) \ case StmtKind::ID: return getStartLocImpl(cast<ID##Stmt>(this)); #include "swift/AST/StmtNodes.def" } llvm_unreachable("statement type not handled!"); } template <class T> static SourceLoc getEndLocImpl(const T *S) { return Dispatch<isOverriddenFromStmt(&T::getEndLoc)>::getEndLoc(S); } SourceLoc Stmt::getEndLoc() const { switch (getKind()) { #define STMT(ID, PARENT) \ case StmtKind::ID: return getEndLocImpl(cast<ID##Stmt>(this)); #include "swift/AST/StmtNodes.def" } llvm_unreachable("statement type not handled!"); } BraceStmt::BraceStmt(SourceLoc lbloc, ArrayRef<ASTNode> elts, SourceLoc rbloc, Optional<bool> implicit) : Stmt(StmtKind::Brace, getDefaultImplicitFlag(implicit, lbloc)), NumElements(elts.size()), LBLoc(lbloc), RBLoc(rbloc) { std::uninitialized_copy(elts.begin(), elts.end(), getTrailingObjects<ASTNode>()); } BraceStmt *BraceStmt::create(ASTContext &ctx, SourceLoc lbloc, ArrayRef<ASTNode> elts, SourceLoc rbloc, Optional<bool> implicit) { assert(std::none_of(elts.begin(), elts.end(), [](ASTNode node) -> bool { return node.isNull(); }) && "null element in BraceStmt"); void *Buffer = ctx.Allocate(totalSizeToAlloc<ASTNode>(elts.size()), alignof(BraceStmt)); return ::new(Buffer) BraceStmt(lbloc, elts, rbloc, implicit); } SourceLoc ReturnStmt::getStartLoc() const { if (ReturnLoc.isInvalid() && Result) return Result->getStartLoc(); return ReturnLoc; } SourceLoc ReturnStmt::getEndLoc() const { if (Result && Result->getEndLoc().isValid()) return Result->getEndLoc(); return ReturnLoc; } SourceLoc ThrowStmt::getEndLoc() const { return SubExpr->getEndLoc(); } SourceLoc DeferStmt::getEndLoc() const { return tempDecl->getBody()->getEndLoc(); } /// Dig the original user's body of the defer out for AST fidelity. BraceStmt *DeferStmt::getBodyAsWritten() const { return tempDecl->getBody(); } bool LabeledStmt::isPossibleContinueTarget() const { switch (getKind()) { #define LABELED_STMT(ID, PARENT) #define STMT(ID, PARENT) case StmtKind::ID: #include "swift/AST/StmtNodes.def" llvm_unreachable("not a labeled statement"); // Sema has diagnostics with hard-coded expectations about what // statements return false from this method. case StmtKind::If: case StmtKind::Guard: case StmtKind::Switch: return false; case StmtKind::Do: case StmtKind::DoCatch: case StmtKind::RepeatWhile: case StmtKind::For: case StmtKind::ForEach: case StmtKind::While: return true; } llvm_unreachable("statement kind unhandled!"); } bool LabeledStmt::requiresLabelOnJump() const { switch (getKind()) { #define LABELED_STMT(ID, PARENT) #define STMT(ID, PARENT) case StmtKind::ID: #include "swift/AST/StmtNodes.def" llvm_unreachable("not a labeled statement"); case StmtKind::If: case StmtKind::Do: case StmtKind::DoCatch: case StmtKind::Guard: // Guard doesn't allow labels, so no break/continue. return true; case StmtKind::RepeatWhile: case StmtKind::For: case StmtKind::ForEach: case StmtKind::Switch: case StmtKind::While: return false; } llvm_unreachable("statement kind unhandled!"); } void ForEachStmt::setPattern(Pattern *p) { Pat = p; Pat->markOwnedByStatement(this); } void CatchStmt::setErrorPattern(Pattern *pattern) { ErrorPattern = pattern; ErrorPattern->markOwnedByStatement(this); } DoCatchStmt *DoCatchStmt::create(ASTContext &ctx, LabeledStmtInfo labelInfo, SourceLoc doLoc, Stmt *body, ArrayRef<CatchStmt*> catches, Optional<bool> implicit) { void *mem = ctx.Allocate(totalSizeToAlloc<CatchStmt*>(catches.size()), alignof(DoCatchStmt)); return ::new (mem) DoCatchStmt(labelInfo, doLoc, body, catches, implicit); } bool DoCatchStmt::isSyntacticallyExhaustive() const { for (auto clause : getCatches()) { if (clause->isSyntacticallyExhaustive()) return true; } return false; } void LabeledConditionalStmt::setCond(StmtCondition e) { // When set a condition into a Conditional Statement, inform each of the // variables bound in any patterns that this is the owning statement for the // pattern. for (auto &elt : e) if (auto pat = elt.getPatternOrNull()) pat->markOwnedByStatement(this); Cond = e; } bool CatchStmt::isSyntacticallyExhaustive() const { // It cannot have a guard expression and the pattern cannot be refutable. return getGuardExpr() == nullptr && !getErrorPattern()->isRefutablePattern(); } PoundAvailableInfo *PoundAvailableInfo::create(ASTContext &ctx, SourceLoc PoundLoc, ArrayRef<AvailabilitySpec *> queries, SourceLoc RParenLoc) { unsigned size = totalSizeToAlloc<AvailabilitySpec *>(queries.size()); void *Buffer = ctx.Allocate(size, alignof(PoundAvailableInfo)); return ::new (Buffer) PoundAvailableInfo(PoundLoc, queries, RParenLoc); } SourceLoc PoundAvailableInfo::getEndLoc() const { if (RParenLoc.isInvalid()) { if (NumQueries == 0) { return PoundLoc; } return getQueries()[NumQueries - 1]->getSourceRange().End; } return RParenLoc; } void PoundAvailableInfo:: getPlatformKeywordLocs(SmallVectorImpl<SourceLoc> &PlatformLocs) { for (unsigned i = 0; i < NumQueries; i++) { auto *VersionSpec = dyn_cast<PlatformVersionConstraintAvailabilitySpec>(getQueries()[i]); if (!VersionSpec) continue; PlatformLocs.push_back(VersionSpec->getPlatformLoc()); } } SourceRange StmtConditionElement::getSourceRange() const { switch (getKind()) { case StmtConditionElement::CK_Boolean: return getBoolean()->getSourceRange(); case StmtConditionElement::CK_Availability: return getAvailability()->getSourceRange(); case StmtConditionElement::CK_PatternBinding: SourceLoc Start; if (IntroducerLoc.isValid()) Start = IntroducerLoc; else Start = getPattern()->getStartLoc(); SourceLoc End = getInitializer()->getEndLoc(); if (Start.isValid() && End.isValid()) { return SourceRange(Start, End); } else { return SourceRange(); } } } SourceLoc StmtConditionElement::getStartLoc() const { switch (getKind()) { case StmtConditionElement::CK_Boolean: return getBoolean()->getStartLoc(); case StmtConditionElement::CK_Availability: return getAvailability()->getStartLoc(); case StmtConditionElement::CK_PatternBinding: return getSourceRange().Start; } } SourceLoc StmtConditionElement::getEndLoc() const { switch (getKind()) { case StmtConditionElement::CK_Boolean: return getBoolean()->getEndLoc(); case StmtConditionElement::CK_Availability: return getAvailability()->getEndLoc(); case StmtConditionElement::CK_PatternBinding: return getSourceRange().End; } } static StmtCondition exprToCond(Expr *C, ASTContext &Ctx) { StmtConditionElement Arr[] = { StmtConditionElement(C) }; return Ctx.AllocateCopy(Arr); } IfStmt::IfStmt(SourceLoc IfLoc, Expr *Cond, Stmt *Then, SourceLoc ElseLoc, Stmt *Else, Optional<bool> implicit, ASTContext &Ctx) : IfStmt(LabeledStmtInfo(), IfLoc, exprToCond(Cond, Ctx), Then, ElseLoc, Else, implicit) { } GuardStmt::GuardStmt(SourceLoc GuardLoc, Expr *Cond, Stmt *Body, Optional<bool> implicit, ASTContext &Ctx) : GuardStmt(GuardLoc, exprToCond(Cond, Ctx), Body, implicit) { } SourceLoc RepeatWhileStmt::getEndLoc() const { return Cond->getEndLoc(); } SourceRange CaseLabelItem::getSourceRange() const { if (auto *E = getGuardExpr()) return { CasePattern->getStartLoc(), E->getEndLoc() }; return CasePattern->getSourceRange(); } SourceLoc CaseLabelItem::getStartLoc() const { return CasePattern->getStartLoc(); } SourceLoc CaseLabelItem::getEndLoc() const { if (auto *E = getGuardExpr()) return E->getEndLoc(); return CasePattern->getEndLoc(); } CaseStmt::CaseStmt(SourceLoc CaseLoc, ArrayRef<CaseLabelItem> CaseLabelItems, bool HasBoundDecls, SourceLoc ColonLoc, Stmt *Body, Optional<bool> Implicit) : Stmt(StmtKind::Case, getDefaultImplicitFlag(Implicit, CaseLoc)), CaseLoc(CaseLoc), ColonLoc(ColonLoc), BodyAndHasBoundDecls(Body, HasBoundDecls), NumPatterns(CaseLabelItems.size()) { assert(NumPatterns > 0 && "case block must have at least one pattern"); MutableArrayRef<CaseLabelItem> Items{ getTrailingObjects<CaseLabelItem>(), NumPatterns }; for (unsigned i = 0; i < NumPatterns; ++i) { new (&Items[i]) CaseLabelItem(CaseLabelItems[i]); Items[i].getPattern()->markOwnedByStatement(this); } } CaseStmt *CaseStmt::create(ASTContext &C, SourceLoc CaseLoc, ArrayRef<CaseLabelItem> CaseLabelItems, bool HasBoundDecls, SourceLoc ColonLoc, Stmt *Body, Optional<bool> Implicit) { void *Mem = C.Allocate(totalSizeToAlloc<CaseLabelItem>(CaseLabelItems.size()), alignof(CaseStmt)); return ::new (Mem) CaseStmt(CaseLoc, CaseLabelItems, HasBoundDecls, ColonLoc, Body, Implicit); } SwitchStmt *SwitchStmt::create(LabeledStmtInfo LabelInfo, SourceLoc SwitchLoc, Expr *SubjectExpr, SourceLoc LBraceLoc, ArrayRef<CaseStmt *> Cases, SourceLoc RBraceLoc, ASTContext &C) { void *p = C.Allocate(totalSizeToAlloc<CaseStmt *>(Cases.size()), alignof(SwitchStmt)); SwitchStmt *theSwitch = ::new (p) SwitchStmt(LabelInfo, SwitchLoc, SubjectExpr, LBraceLoc, Cases.size(), RBraceLoc); std::uninitialized_copy(Cases.begin(), Cases.end(), theSwitch->getTrailingObjects<CaseStmt *>()); return theSwitch; } <|endoftext|>
<commit_before>#include "CanGateway.h" //Output to a serial CAN adapter instead of directly to a CAN bus #define SERIALTEST 0 #define DEBUG 0 /****************************************************************** * CanGateway() * Constructor * * Initializes the queues and ports necessary for communication * with ROS. Does not initialize CAN communication. ******************************************************************/ CanGateway::CanGateway(const std::string& name): TaskContext(name){ this->upQueue = new queue<canMsg>(); this->downQueue = new queue<canMsg>(); this->inPort = new InputPort<hubomsg::CanMessage>("can_down"); this->outPort = new OutputPort<hubomsg::CanMessage>("can_up"); this->addEventPort(*inPort); this->addPort(*outPort); tempYaw = 0; rightHipEnabled = false; tempRoll = 0; } CanGateway::~CanGateway(){ } /****************************************************************** * strToSerial() * * Converts a std::string formatted CAN packet into a character * array for communication over USB. Adds a 0x0D (carriage return) * onto the end of the array as per the protocol. * * Protocol is tested for the EasySync USB2-F-7x01 adapter * * Paramters: * packet - a string representation of a CAN packet * * Returns a character array representation of the input string * with a trailing carriage return. ******************************************************************/ char* CanGateway::strToSerial(string packet){ char* data = new char[packet.length() + 1]; strcpy(data, packet.c_str()); data[packet.length()] = (char) 0x0D; return data; } /****************************************************************** * transmit() * * Sends a canmsg_t (can4linux) packet over a hardware channel. * * Parameters: * packet - a canmsg_t formatted packet to transmit to hardware * * Returns true if data was sent successfully, false otherwise. ******************************************************************/ bool CanGateway::transmit(canmsg_t* packet){ int sent = 0; //Make sure there's an outbound channel if (this->channel > 0){ //Amount to send is always 1 for canmsg_t (see can4linux.h) sent = write(this->channel, packet, 1); } if (sent < 1){ //Not all the data was sent std::cout << "Data transmission error" << std::endl; return false; } return true; } /****************************************************************** * transmit() * * Sends a char* packet over a hardware channel. * * Parameters: * packet - a char* formatted packet to transmit to hardware * * Returns true if data was sent successfully, false otherwise. ******************************************************************/ bool CanGateway::transmit(char* packet){ int sent = 0; //Make sure there's an outbound channel if (this->channel > 0){ sent = write(this->channel, packet, strlen(packet)); } if (sent < strlen(packet)){ //Not all the data was sent return false; } return true; } /****************************************************************** * openCanConnection() * * Opens a hardware channel file descriptor for communication. * * Parameters: * path - the path to a file descriptor (e.g. /dev/ttyUSB0) * * Returns the channel number to use for communication. ******************************************************************/ int CanGateway::openCanConnection(char* path){ //Read/Write and non-blocking. Should be the same for //serial or CAN hardware. int channel = open(path, O_RDWR | O_NONBLOCK); return channel; } /****************************************************************** * initConnection() * * Initializes a CAN connection. Sends the appropriate packets to * set channel speed and open a connection, if necessary. * * Paramters: * channel - the channel to initialize. obtained by a successful * call to openCanConnection() ******************************************************************/ void CanGateway::initConnection(int channel, int bitrate){ if (SERIALTEST){ //Send speed and open packet transmit(strToSerial("s8")); transmit(strToSerial("O")); } else{ Config_par_t cfg; volatile Command_par_t cmd; cmd.cmd = CMD_STOP; ioctl(channel, CAN_IOCTL_COMMAND, &cmd); cfg.target = CONF_TIMING; cfg.val1 = (unsigned int)bitrate; ioctl(channel, CAN_IOCTL_CONFIG, &cfg); cmd.cmd = CMD_START; ioctl(channel, CAN_IOCTL_COMMAND, &cmd); } } /****************************************************************** * closeCanConnection() * * Closes a CAN connection. Sends the appropriate packets to close * the connection if necessary. * * Parameters: * channel - the channel to close. obtained by a successful call * to openCanConnection() ******************************************************************/ void CanGateway::closeCanConnection(int channel){ if (SERIALTEST){ //Send close packet transmit(strToSerial("C")); } else{ volatile Command_par_t cmd; cmd.cmd = CMD_STOP; ioctl(channel, CAN_IOCTL_COMMAND, &cmd); } close(channel); } /****************************************************************** * recvFromRos() * * Attempts to receive new data from the subscribed ROS topic. Adds * new data (if available) to the hardware send queue. ******************************************************************/ void CanGateway::recvFromRos(){ hubomsg::CanMessage inMsg = hubomsg::CanMessage(); canMsg can_message; //If a new message has come in from ROS, grab the CAN information while (NewData==this->inPort->read(inMsg)){ can_message = canMsg((boardNum)inMsg.bno, (messageType)inMsg.mType, (cmdType)inMsg.cmdType, inMsg.r1, inMsg.r2, inMsg.r3, inMsg.r4, inMsg.r5, inMsg.r6, inMsg.r7, inMsg.r8); //Add message to queue //if (!this->downQueue->empty()) //this->downQueue->pop(); if (inMsg.bno == BNO_R_HIP_YAW_ROLL && inMsg.mType == TX_REF && inMsg.cmdType == 2) { tempYaw = inMsg.r1; tempRoll = inMsg.r2; } else if (inMsg.bno == BNO_R_HIP_YAW_ROLL && inMsg.mType == TX_MOTOR_CMD && inMsg.cmdType == CMD_CONTROLLER_ON){ this->downQueue->push(can_message); rightHipEnabled = true; } else if (inMsg.bno == BNO_R_HIP_YAW_ROLL && inMsg.mType == TX_MOTOR_CMD && inMsg.cmdType == CMD_CONTROLLER_OFF){ this->downQueue->push(can_message); rightHipEnabled = false; } else this->downQueue->push(can_message); //std::cout << this->downQueue->size() << std::endl; } } /****************************************************************** * transmitToRos() * * Transmits all queued messages from hardware back up to ROS. ******************************************************************/ void CanGateway::transmitToRos(){ //Flush our upstream queue out to the ROS bus canMsg out; for (int i = 0; i < upQueue->size(); i++){ hubomsg::CanMessage upstream = hubomsg::CanMessage(); out = upQueue->front(); upQueue->pop(); //Set up ROS message parameters upstream.bno = out.getBNO(); upstream.mType = out.getType(); upstream.cmdType = out.getCmd(); upstream.r1 = out.getR1(); upstream.r2 = out.getR2(); upstream.r3 = out.getR3(); upstream.r4 = out.getR4(); upstream.r5 = out.getR5(); upstream.r6 = out.getR6(); upstream.r7 = out.getR7(); upstream.r8 = out.getR8(); this->outPort->write(upstream); } } /****************************************************************** * getInputPort() * * Returns the InputPort used for ROS communication. ******************************************************************/ InputPort<hubomsg::CanMessage>* CanGateway::getInputPort(){ return this->inPort; } /****************************************************************** * getOutputPort() * * Returns the OutputPort used for ROS communication. ******************************************************************/ OutputPort<hubomsg::CanMessage>* CanGateway::getOutputPort(){ return this->outPort; } /****************************************************************** * runTick() * * Called each clock interval. Sends the next message in the queue * to the hardware. ******************************************************************/ void CanGateway::runTick(){ canmsg_t** rx = new canmsg_t*[5]; //At each clock interval (50 ms?) send a message out to the hardware. canMsg out_message = this->downQueue->front(); this->downQueue->pop(); if (SERIALTEST){ //Format message for serial output char* data = strToSerial(out_message.toSerial()); this->transmit(data); } else { //Format message for CAN output canmsg_t* data = out_message.toCAN(); this->transmit(data); } int messages_read = 0; //Also make an attempt to read in from hardware if (SERIALTEST){ } else { messages_read = read(this->channel, &rx, 5); if (messages_read > 0){ for (int i = 0; i < messages_read; i++){ //Rebuild a canMsg and add it to the upstream buffer this->upQueue->push(canMsg::fromLineType(rx[i])); //std::cout << "read in a message from CAN" << std::endl; } } } } /****************************************************************** * startHook() * * Called at start. ******************************************************************/ bool CanGateway::startHook(){ //@TODO: This should be some sort of parameter...not hardcoded this->channel = openCanConnection("/dev/can0"); std::cout << "Opened CAN connection on channel " << channel << std::endl; if (this->channel > -1){ initConnection(this->channel, 1000); canMsg name_info = canMsg(BNO_R_HIP_YAW_ROLL, TX_MOTOR_CMD, CMD_SETREQ_BOARD_INFO, 0x05, 0, 0, 0, 0, 0, 0, 0); canMsg hip_on = canMsg(BNO_R_HIP_YAW_ROLL, TX_MOTOR_CMD, CMD_HIP_ENABLE, 0x01, 0, 0, 0, 0, 0, 0, 0); canMsg run = canMsg(BNO_R_HIP_YAW_ROLL, TX_MOTOR_CMD, CMD_CONTROLLER_ON, 0, 0, 0, 0, 0, 0, 0, 0); name_info.printme(); hip_on.printme(); run.printme(); // transmit(name_info.toCAN()); // transmit(hip_on.toCAN()); // transmit(run.toCAN()); // write(channel, name_info.toCAN(), 1); // write(channel, hip_on.toCAN(), 1); // write(channel, run.toCAN(), 1); return 1; } return 0; } /****************************************************************** * updateHook() * * Called each iteration. ******************************************************************/ void CanGateway::updateHook(){ //runTick(); recvFromRos(); if (downQueue->empty() && rightHipEnabled){ downQueue->push(canMsg((boardNum)BNO_R_HIP_YAW_ROLL, (messageType)TX_REF, (cmdType)2, tempYaw, tempRoll, 0, 0, 0, 0, 0, 0)); } canmsg_t rx[5]; if (!this->downQueue->empty()){ transmit(this->downQueue->front().toCAN()); this->downQueue->pop(); } if (this->channel > 0){ int messages_read = read(this->channel, &rx, 5); if (messages_read > 0){ //std::cout << "read in a message from CAN" << std::endl; for (int i = 0; i < messages_read; i++){ //Rebuild a canMsg and add it to the upstream buffer this->upQueue->push(canMsg::fromLineType(&rx[i])); //std::cout << "read in a message from CAN" << std::endl; } } } transmitToRos(); } /****************************************************************** * startHook() * * Called at shutdown. ******************************************************************/ void CanGateway::stopHook(){ closeCanConnection(this->channel); } ORO_LIST_COMPONENT_TYPE(CanGateway) <commit_msg>Blah. don't ask me to commit message! THIS IS TOO IMPORTANT!<commit_after>#include "CanGateway.h" #include <fstream> //Output to a serial CAN adapter instead of directly to a CAN bus #define SERIALTEST 0 #define DEBUG 0 /****************************************************************** * CanGateway() * Constructor * * Initializes the queues and ports necessary for communication * with ROS. Does not initialize CAN communication. ******************************************************************/ CanGateway::CanGateway(const std::string& name): TaskContext(name){ this->upQueue = new queue<canMsg>(); this->downQueue = new queue<canMsg>(); this->inPort = new InputPort<hubomsg::CanMessage>("can_down"); this->outPort = new OutputPort<hubomsg::CanMessage>("can_up"); this->addEventPort(*inPort); this->addPort(*outPort); tempYaw = 0; rightHipEnabled = false; tempRoll = 0; } CanGateway::~CanGateway(){ } /****************************************************************** * strToSerial() * * Converts a std::string formatted CAN packet into a character * array for communication over USB. Adds a 0x0D (carriage return) * onto the end of the array as per the protocol. * * Protocol is tested for the EasySync USB2-F-7x01 adapter * * Paramters: * packet - a string representation of a CAN packet * * Returns a character array representation of the input string * with a trailing carriage return. ******************************************************************/ char* CanGateway::strToSerial(string packet){ char* data = new char[packet.length() + 1]; strcpy(data, packet.c_str()); data[packet.length()] = (char) 0x0D; return data; } /****************************************************************** * transmit() * * Sends a canmsg_t (can4linux) packet over a hardware channel. * * Parameters: * packet - a canmsg_t formatted packet to transmit to hardware * * Returns true if data was sent successfully, false otherwise. ******************************************************************/ bool CanGateway::transmit(canmsg_t* packet){ int sent = 0; //Make sure there's an outbound channel if (this->channel > 0){ //Amount to send is always 1 for canmsg_t (see can4linux.h) sent = write(this->channel, packet, 1); } if (sent < 1){ //Not all the data was sent std::cout << "Data transmission error" << std::endl; return false; } return true; } /****************************************************************** * transmit() * * Sends a char* packet over a hardware channel. * * Parameters: * packet - a char* formatted packet to transmit to hardware * * Returns true if data was sent successfully, false otherwise. ******************************************************************/ bool CanGateway::transmit(char* packet){ int sent = 0; //Make sure there's an outbound channel if (this->channel > 0){ sent = write(this->channel, packet, strlen(packet)); } if (sent < strlen(packet)){ //Not all the data was sent return false; } return true; } /****************************************************************** * openCanConnection() * * Opens a hardware channel file descriptor for communication. * * Parameters: * path - the path to a file descriptor (e.g. /dev/ttyUSB0) * * Returns the channel number to use for communication. ******************************************************************/ int CanGateway::openCanConnection(char* path){ //Read/Write and non-blocking. Should be the same for //serial or CAN hardware. int channel = open(path, O_RDWR | O_NONBLOCK); return channel; } /****************************************************************** * initConnection() * * Initializes a CAN connection. Sends the appropriate packets to * set channel speed and open a connection, if necessary. * * Paramters: * channel - the channel to initialize. obtained by a successful * call to openCanConnection() ******************************************************************/ void CanGateway::initConnection(int channel, int bitrate){ if (SERIALTEST){ //Send speed and open packet transmit(strToSerial("s8")); transmit(strToSerial("O")); } else{ Config_par_t cfg; volatile Command_par_t cmd; cmd.cmd = CMD_STOP; ioctl(channel, CAN_IOCTL_COMMAND, &cmd); cfg.target = CONF_TIMING; cfg.val1 = (unsigned int)bitrate; ioctl(channel, CAN_IOCTL_CONFIG, &cfg); cmd.cmd = CMD_START; ioctl(channel, CAN_IOCTL_COMMAND, &cmd); } } /****************************************************************** * closeCanConnection() * * Closes a CAN connection. Sends the appropriate packets to close * the connection if necessary. * * Parameters: * channel - the channel to close. obtained by a successful call * to openCanConnection() ******************************************************************/ void CanGateway::closeCanConnection(int channel){ if (SERIALTEST){ //Send close packet transmit(strToSerial("C")); } else{ volatile Command_par_t cmd; cmd.cmd = CMD_STOP; ioctl(channel, CAN_IOCTL_COMMAND, &cmd); } close(channel); } /****************************************************************** * recvFromRos() * * Attempts to receive new data from the subscribed ROS topic. Adds * new data (if available) to the hardware send queue. ******************************************************************/ void CanGateway::recvFromRos(){ hubomsg::CanMessage inMsg = hubomsg::CanMessage(); canMsg can_message; //If a new message has come in from ROS, grab the CAN information while (NewData==this->inPort->read(inMsg)){ can_message = canMsg((boardNum)inMsg.bno, (messageType)inMsg.mType, (cmdType)inMsg.cmdType, inMsg.r1, inMsg.r2, inMsg.r3, inMsg.r4, inMsg.r5, inMsg.r6, inMsg.r7, inMsg.r8); std::cout << "Message received! r1: " << inMsg.r1 << std::endl; //Add message to queue //if (!this->downQueue->empty()) //this->downQueue->pop(); if (inMsg.bno == BNO_R_HIP_YAW_ROLL && inMsg.mType == TX_REF && inMsg.cmdType == 2) { tempYaw = inMsg.r1; tempRoll = inMsg.r2; } else if (inMsg.bno == BNO_R_HIP_YAW_ROLL && inMsg.mType == TX_MOTOR_CMD && inMsg.cmdType == CMD_CONTROLLER_ON){ this->downQueue->push(can_message); rightHipEnabled = true; } else if (inMsg.bno == BNO_R_HIP_YAW_ROLL && inMsg.mType == TX_MOTOR_CMD && inMsg.cmdType == CMD_CONTROLLER_OFF){ this->downQueue->push(can_message); rightHipEnabled = false; } else this->downQueue->push(can_message); //std::cout << this->downQueue->size() << std::endl; } } /****************************************************************** * transmitToRos() * * Transmits all queued messages from hardware back up to ROS. ******************************************************************/ void CanGateway::transmitToRos(){ //Flush our upstream queue out to the ROS bus canMsg out; for (int i = 0; i < upQueue->size(); i++){ hubomsg::CanMessage upstream = hubomsg::CanMessage(); out = upQueue->front(); upQueue->pop(); //Set up ROS message parameters upstream.bno = out.getBNO(); upstream.mType = out.getType(); upstream.cmdType = out.getCmd(); upstream.r1 = out.getR1(); upstream.r2 = out.getR2(); upstream.r3 = out.getR3(); upstream.r4 = out.getR4(); upstream.r5 = out.getR5(); upstream.r6 = out.getR6(); upstream.r7 = out.getR7(); upstream.r8 = out.getR8(); this->outPort->write(upstream); } } /****************************************************************** * getInputPort() * * Returns the InputPort used for ROS communication. ******************************************************************/ InputPort<hubomsg::CanMessage>* CanGateway::getInputPort(){ return this->inPort; } /****************************************************************** * getOutputPort() * * Returns the OutputPort used for ROS communication. ******************************************************************/ OutputPort<hubomsg::CanMessage>* CanGateway::getOutputPort(){ return this->outPort; } /****************************************************************** * runTick() * * Called each clock interval. Sends the next message in the queue * to the hardware. ******************************************************************/ void CanGateway::runTick(){ canmsg_t** rx = new canmsg_t*[5]; //At each clock interval (50 ms?) send a message out to the hardware. canMsg out_message = this->downQueue->front(); this->downQueue->pop(); if (SERIALTEST){ //Format message for serial output char* data = strToSerial(out_message.toSerial()); this->transmit(data); } else { //Format message for CAN output canmsg_t* data = out_message.toCAN(); this->transmit(data); } int messages_read = 0; //Also make an attempt to read in from hardware if (SERIALTEST){ } else { messages_read = read(this->channel, &rx, 5); if (messages_read > 0){ for (int i = 0; i < messages_read; i++){ //Rebuild a canMsg and add it to the upstream buffer this->upQueue->push(canMsg::fromLineType(rx[i])); //std::cout << "read in a message from CAN" << std::endl; } } } } /****************************************************************** * startHook() * * Called at start. ******************************************************************/ bool CanGateway::startHook(){ //@TODO: This should be some sort of parameter...not hardcoded this->channel = openCanConnection("/dev/can0"); std::cout << "Opened CAN connection on channel " << channel << std::endl; if (this->channel > -1){ initConnection(this->channel, 1000); canMsg name_info = canMsg(BNO_R_HIP_YAW_ROLL, TX_MOTOR_CMD, CMD_SETREQ_BOARD_INFO, 0x05, 0, 0, 0, 0, 0, 0, 0); canMsg hip_on = canMsg(BNO_R_HIP_YAW_ROLL, TX_MOTOR_CMD, CMD_HIP_ENABLE, 0x01, 0, 0, 0, 0, 0, 0, 0); canMsg run = canMsg(BNO_R_HIP_YAW_ROLL, TX_MOTOR_CMD, CMD_CONTROLLER_ON, 0, 0, 0, 0, 0, 0, 0, 0); name_info.printme(); hip_on.printme(); run.printme(); // transmit(name_info.toCAN()); // transmit(hip_on.toCAN()); // transmit(run.toCAN()); // write(channel, name_info.toCAN(), 1); // write(channel, hip_on.toCAN(), 1); // write(channel, run.toCAN(), 1); return 1; } return 0; } /****************************************************************** * updateHook() * * Called each iteration. ******************************************************************/ void CanGateway::updateHook(){ //runTick(); recvFromRos(); if (downQueue->empty() && rightHipEnabled){ downQueue->push(canMsg((boardNum)BNO_R_HIP_YAW_ROLL, (messageType)TX_REF, (cmdType)2, tempYaw, tempRoll, 0, 0, 0, 0, 0, 0)); } canmsg_t rx[5]; if (!this->downQueue->empty()){ transmit(this->downQueue->front().toCAN()); std::cout << "Transmitting message! r1: " << this->downQueue->front().getR1() << std::endl; this->downQueue->pop(); } if (this->channel > 0){ int messages_read = read(this->channel, &rx, 5); if (messages_read > 0){ //std::cout << "read in a message from CAN" << std::endl; for (int i = 0; i < messages_read; i++){ //Rebuild a canMsg and add it to the upstream buffer this->upQueue->push(canMsg::fromLineType(&rx[i])); //std::cout << "read in a message from CAN" << std::endl; } } } transmitToRos(); } /****************************************************************** * startHook() * * Called at shutdown. ******************************************************************/ void CanGateway::stopHook(){ closeCanConnection(this->channel); } ORO_LIST_COMPONENT_TYPE(CanGateway) <|endoftext|>
<commit_before>#include "DepthSensor.h" #ifdef KinectAzure_Enabled #include "cinder/ImageIo.h" #include "cinder/Log.h" #include "cinder/app/App.h" #include "k4a/k4a.h" #pragma comment(lib, "k4a") using namespace ci; using namespace ci::app; using namespace std; namespace ds { struct DeviceKinectAzure : public Device { virtual bool isValid() const { return true; } ivec2 getDepthSize() const { return depthSize; } ivec2 getColorSize() const { return colorSize; } DeviceKinectAzure(Option option) { this->option = option; k4a_result_t openResult = k4a_device_open(option.deviceId, &device_handle); if (openResult != K4A_RESULT_SUCCEEDED) return; k4a_device_configuration_t conf = {}; if (option.enableColor) { conf.color_format = K4A_IMAGE_FORMAT_COLOR_BGRA32; conf.color_resolution = K4A_COLOR_RESOLUTION_1080P; } if (option.enableInfrared) { conf.depth_mode = K4A_DEPTH_MODE_PASSIVE_IR; } if (option.enableDepth) { conf.depth_mode = K4A_DEPTH_MODE_WFOV_2X2BINNED; } conf.camera_fps = K4A_FRAMES_PER_SECOND_30; conf.wired_sync_mode = K4A_WIRED_SYNC_MODE_STANDALONE; k4a_result_t startResult = k4a_device_start_cameras(device_handle, &conf); if (startResult != K4A_RESULT_SUCCEEDED) return; App::get()->getSignalUpdate().connect(std::bind(&DeviceKinectAzure::update, this)); } ~DeviceKinectAzure() { if (device_handle) { k4a_device_stop_cameras(device_handle); k4a_device_close(device_handle); } } void update() { if (device_handle == 0) return; const int32_t TIMEOUT_IN_MS = 1000; k4a_capture_t capture_handle; k4a_wait_result_t waiResult = k4a_device_get_capture(device_handle, &capture_handle, TIMEOUT_IN_MS); if (waiResult != K4A_WAIT_RESULT_SUCCEEDED) return; if (option.enableColor) { auto image = k4a_capture_get_color_image(capture_handle); if (image != 0) { if (colorSize.x == 0 || colorSize.y == 0) { colorSize.x = k4a_image_get_width_pixels(image); colorSize.y = k4a_image_get_height_pixels(image); colorSize.z = k4a_image_get_stride_bytes(image); } uint8_t* ptr = k4a_image_get_buffer(image); colorSurface = Surface8u(ptr, colorSize.x, colorSize.y, colorSize.z, SurfaceChannelOrder::BGRX); signalColorDirty.emit(); k4a_image_release(image); } } if (option.enableDepth) { auto image = k4a_capture_get_depth_image(capture_handle); if (image != 0) { if (depthSize.x == 0 || depthSize.y == 0) { depthSize.x = k4a_image_get_width_pixels(image); depthSize.y = k4a_image_get_height_pixels(image); depthSize.z = k4a_image_get_stride_bytes(image); } uint16_t* ptr = (uint16_t*)k4a_image_get_buffer(image); if (ptr != nullptr) { depthChannel = Channel16u(depthSize.x, depthSize.y, depthSize.z, 1, ptr); signalDepthDirty.emit(); } k4a_image_release(image); } } if (option.enableInfrared) { auto image = k4a_capture_get_ir_image(capture_handle); if (image != 0) { if (depthSize.x == 0 || depthSize.y == 0) { depthSize.x = k4a_image_get_width_pixels(image); depthSize.y = k4a_image_get_height_pixels(image); depthSize.z = k4a_image_get_stride_bytes(image); } uint16_t* ptr = (uint16_t*)k4a_image_get_buffer(image); infraredChannel = Channel16u(depthSize.x, depthSize.y, depthSize.z, 1, ptr); signalInfraredDirty.emit(); k4a_image_release(image); } } k4a_capture_release(capture_handle); } k4a_device_t device_handle = 0; ivec3 colorSize, depthSize; }; uint32_t getKinectAzureCount() { return k4a_device_get_installed_count(); } DeviceRef createKinectAzure(Option option) { return DeviceRef(new DeviceKinectAzure(option)); } } // namespace ds #endif <commit_msg>k4a - wip support of body tracking<commit_after>#include "DepthSensor.h" #ifdef KinectAzure_Enabled #include "cinder/ImageIo.h" #include "cinder/Log.h" #include "cinder/app/App.h" #include "k4a/k4a.h" #include "k4a/k4abt.h" #pragma comment(lib, "k4a") #pragma comment(lib, "k4abt") using namespace ci; using namespace ci::app; using namespace std; namespace ds { struct DeviceKinectAzure : public Device { virtual bool isValid() const { return true; } ivec2 getDepthSize() const { return depthSize; } ivec2 getColorSize() const { return colorSize; } DeviceKinectAzure(Option option) { this->option = option; k4a_result_t result = k4a_device_open(option.deviceId, &device_handle); if (result != K4A_RESULT_SUCCEEDED) return; k4a_device_configuration_t conf = K4A_DEVICE_CONFIG_INIT_DISABLE_ALL; if (option.enableColor) { conf.color_format = K4A_IMAGE_FORMAT_COLOR_BGRA32; conf.color_resolution = K4A_COLOR_RESOLUTION_1080P; } if (option.enableInfrared) { conf.depth_mode = K4A_DEPTH_MODE_PASSIVE_IR; } if (option.enableDepth) { conf.depth_mode = K4A_DEPTH_MODE_NFOV_UNBINNED; } if (option.enableBody || option.enableBodyIndex) { result = k4a_device_get_calibration(device_handle, conf.depth_mode, conf.color_resolution, &calibration); k4abt_tracker_configuration_t cfg = { K4ABT_SENSOR_ORIENTATION_DEFAULT, false }; result = k4abt_tracker_create(&calibration, cfg, &tracker); } conf.camera_fps = K4A_FRAMES_PER_SECOND_30; conf.wired_sync_mode = K4A_WIRED_SYNC_MODE_STANDALONE; k4a_result_t startResult = k4a_device_start_cameras(device_handle, &conf); if (startResult != K4A_RESULT_SUCCEEDED) return; App::get()->getSignalUpdate().connect(std::bind(&DeviceKinectAzure::update, this)); } ~DeviceKinectAzure() { if (device_handle) { k4a_device_stop_cameras(device_handle); k4a_device_close(device_handle); } if (tracker) { k4abt_tracker_destroy(tracker); } } void update() { if (device_handle == 0) return; const int32_t TIMEOUT_IN_MS = 1000; k4a_capture_t capture_handle; k4a_wait_result_t waiResult = k4a_device_get_capture(device_handle, &capture_handle, TIMEOUT_IN_MS); if (waiResult != K4A_WAIT_RESULT_SUCCEEDED) return; if (option.enableColor) { auto image = k4a_capture_get_color_image(capture_handle); if (image != 0) { if (colorSize.x == 0 || colorSize.y == 0) { colorSize.x = k4a_image_get_width_pixels(image); colorSize.y = k4a_image_get_height_pixels(image); colorSize.z = k4a_image_get_stride_bytes(image); } uint8_t* ptr = k4a_image_get_buffer(image); colorSurface = Surface8u(ptr, colorSize.x, colorSize.y, colorSize.z, SurfaceChannelOrder::BGRX); signalColorDirty.emit(); k4a_image_release(image); } } if (option.enableDepth) { auto image = k4a_capture_get_depth_image(capture_handle); if (image != 0) { if (depthSize.x == 0 || depthSize.y == 0) { depthSize.x = k4a_image_get_width_pixels(image); depthSize.y = k4a_image_get_height_pixels(image); depthSize.z = k4a_image_get_stride_bytes(image); } uint16_t* ptr = (uint16_t*)k4a_image_get_buffer(image); if (ptr != nullptr) { depthChannel = Channel16u(depthSize.x, depthSize.y, depthSize.z, 1, ptr); signalDepthDirty.emit(); } k4a_image_release(image); } } if (option.enableBody || option.enableBodyIndex) { k4a_wait_result_t result = k4abt_tracker_enqueue_capture(tracker, capture_handle, TIMEOUT_IN_MS); if (result == K4A_WAIT_RESULT_SUCCEEDED) { k4abt_frame_t body_frame_handle; result = k4abt_tracker_pop_result(tracker, &body_frame_handle, TIMEOUT_IN_MS); if (body_frame_handle != nullptr) { if (option.enableBody) { uint32_t num_bodies = k4abt_frame_get_num_bodies(body_frame_handle); CI_LOG_I(num_bodies << " bodies are detected"); vector<k4abt_skeleton_t> skeletons; for (int i = 0; i < num_bodies; i++) { k4abt_skeleton_t skeleton; auto result = k4abt_frame_get_body_skeleton(body_frame_handle, i, &skeleton); skeletons.emplace_back(skeleton); } } if (option.enableBodyIndex) { k4a_image_t body_index = k4abt_frame_get_body_index_map(body_frame_handle); } k4abt_frame_release(body_frame_handle); } } } if (option.enableInfrared) { auto image = k4a_capture_get_ir_image(capture_handle); if (image != 0) { if (depthSize.x == 0 || depthSize.y == 0) { depthSize.x = k4a_image_get_width_pixels(image); depthSize.y = k4a_image_get_height_pixels(image); depthSize.z = k4a_image_get_stride_bytes(image); } uint16_t* ptr = (uint16_t*)k4a_image_get_buffer(image); infraredChannel = Channel16u(depthSize.x, depthSize.y, depthSize.z, 1, ptr); signalInfraredDirty.emit(); k4a_image_release(image); } } k4a_capture_release(capture_handle); } k4a_device_t device_handle = 0; ivec3 colorSize, depthSize; k4a_calibration_t calibration; k4abt_tracker_t tracker; }; uint32_t getKinectAzureCount() { return k4a_device_get_installed_count(); } DeviceRef createKinectAzure(Option option) { return DeviceRef(new DeviceKinectAzure(option)); } } // namespace ds #endif <|endoftext|>
<commit_before>// Copyright (c) 2018 BiliBili, 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. // Authors: Jiashun Zhu([email protected]) #include <gflags/gflags.h> #include "butil/third_party/rapidjson/document.h" #include "butil/string_printf.h" #include "brpc/channel.h" #include "brpc/controller.h" #include "brpc/policy/discovery_naming_service.h" namespace brpc { namespace policy { #ifdef BILIBILI_INTERNAL DEFINE_string(discovery_api_addr, "http://api.bilibili.co/discovery/nodes", "The address of discovery api"); #else DEFINE_string(discovery_api_addr, "", "The address of discovery api"); #endif DEFINE_int32(discovery_timeout_ms, 3000, "Timeout for discovery requests"); DEFINE_string(discovery_env, "prod", "Environment of services"); DEFINE_string(discovery_status, "1", "Status of services. 1 for ready, 2 for not ready, 3 for all"); int DiscoveryNamingService::ParseNodesResult( const butil::IOBuf& buf, std::string* server_addr) { BUTIL_RAPIDJSON_NAMESPACE::Document nodes; const std::string response = buf.to_string(); nodes.Parse(response.c_str()); auto itr = nodes.FindMember("data"); if (itr == nodes.MemberEnd()) { LOG(ERROR) << "No data field in discovery nodes response"; return -1; } const BUTIL_RAPIDJSON_NAMESPACE::Value& data = itr->value; if (!data.IsArray()) { LOG(ERROR) << "data field is not an array"; return -1; } for (BUTIL_RAPIDJSON_NAMESPACE::SizeType i = 0; i < data.Size(); ++i) { const BUTIL_RAPIDJSON_NAMESPACE::Value& addr_item = data[i]; auto itr_addr = addr_item.FindMember("addr"); auto itr_status = addr_item.FindMember("status"); if (itr_addr == addr_item.MemberEnd() || !itr_addr->value.IsString() || itr_status == addr_item.MemberEnd() || !itr_status->value.IsUint() || itr_status->value.GetUint() != 0) { continue; } server_addr->assign(itr_addr->value.GetString(), itr_addr->value.GetStringLength()); // Currently, we just use the first successful result break; } return 0; } int DiscoveryNamingService::ParseFetchsResult( const butil::IOBuf& buf, const char* service_name, std::vector<ServerNode>* servers) { BUTIL_RAPIDJSON_NAMESPACE::Document d; const std::string response = buf.to_string(); d.Parse(response.c_str()); auto itr_data = d.FindMember("data"); if (itr_data == d.MemberEnd()) { LOG(ERROR) << "No data field in discovery fetchs response"; return -1; } const BUTIL_RAPIDJSON_NAMESPACE::Value& data = itr_data->value; auto itr_service = data.FindMember(service_name); if (itr_service == data.MemberEnd()) { LOG(ERROR) << "No " << service_name << " field in discovery response"; return -1; } const BUTIL_RAPIDJSON_NAMESPACE::Value& services = itr_service->value; auto itr_instances = services.FindMember("instances"); if (itr_instances == services.MemberEnd()) { LOG(ERROR) << "Fail to find instances"; return -1; } const BUTIL_RAPIDJSON_NAMESPACE::Value& instances = itr_instances->value; if (!instances.IsArray()) { LOG(ERROR) << "Fail to parse instances as an array"; return -1; } for (BUTIL_RAPIDJSON_NAMESPACE::SizeType i = 0; i < instances.Size(); ++i) { auto itr = instances[i].FindMember("addrs"); if (itr == instances[i].MemberEnd() || !itr->value.IsArray()) { LOG(ERROR) << "Fail to find addrs or addrs is not an array"; return -1; } const BUTIL_RAPIDJSON_NAMESPACE::Value& addrs = itr->value; for (BUTIL_RAPIDJSON_NAMESPACE::SizeType j = 0; j < addrs.Size(); ++j) { if (!addrs[j].IsString()) { continue; } // The result returned by discovery include protocol prefix, such as // http://172.22.35.68:6686, which should be removed. butil::StringPiece addr(addrs[j].GetString(), addrs[j].GetStringLength()); butil::StringPiece::size_type pos = addr.find("://"); if (pos != butil::StringPiece::npos) { addr.remove_prefix(pos + 3); } ServerNode node; if (str2endpoint(addr.data(), &node.addr) != 0) { LOG(ERROR) << "Invalid address=`" << addr << '\''; continue; } servers->push_back(node); } } return 0; } int DiscoveryNamingService::GetServers(const char* service_name, std::vector<ServerNode>* servers) { if (!_is_initialized) { Channel api_channel; ChannelOptions channel_options; channel_options.protocol = PROTOCOL_HTTP; channel_options.timeout_ms = FLAGS_discovery_timeout_ms; channel_options.connect_timeout_ms = FLAGS_discovery_timeout_ms / 3; if (api_channel.Init(FLAGS_discovery_api_addr.c_str(), "", &channel_options) != 0) { LOG(ERROR) << "Fail to init channel to " << FLAGS_discovery_api_addr; return -1; } Controller cntl; cntl.http_request().uri() = FLAGS_discovery_api_addr; api_channel.CallMethod(NULL, &cntl, NULL, NULL, NULL); if (cntl.Failed()) { LOG(ERROR) << "Fail to access " << cntl.http_request().uri() << ": " << cntl.ErrorText(); return -1; } std::string discovery_addr; if (ParseNodesResult(cntl.response_attachment(), &discovery_addr) != 0) { return -1; } if (_channel.Init(discovery_addr.c_str(), "", &channel_options) != 0) { LOG(ERROR) << "Fail to init channel to " << discovery_addr; return -1; } _is_initialized = true; } servers->clear(); Controller cntl; // TODO(zhujiashun): pass zone from service_name cntl.http_request().uri() = butil::string_printf( "/discovery/fetchs?appid=%s&env=%s&status=%s", service_name, FLAGS_discovery_env.c_str(), FLAGS_discovery_status.c_str()); _channel.CallMethod(NULL, &cntl, NULL, NULL, NULL); if (cntl.Failed()) { LOG(ERROR) << "Fail to make /discovery/fetchs request: " << cntl.ErrorText(); return -1; } return ParseFetchsResult(cntl.response_attachment(), service_name, servers); } void DiscoveryNamingService::Describe(std::ostream& os, const DescribeOptions&) const { os << "discovery"; return; } NamingService* DiscoveryNamingService::New() const { return new DiscoveryNamingService; } void DiscoveryNamingService::Destroy() { delete this; } } // namespace policy } // namespace brpc <commit_msg>remove todo<commit_after>// Copyright (c) 2018 BiliBili, 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. // Authors: Jiashun Zhu([email protected]) #include <gflags/gflags.h> #include "butil/third_party/rapidjson/document.h" #include "butil/string_printf.h" #include "brpc/channel.h" #include "brpc/controller.h" #include "brpc/policy/discovery_naming_service.h" namespace brpc { namespace policy { #ifdef BILIBILI_INTERNAL DEFINE_string(discovery_api_addr, "http://api.bilibili.co/discovery/nodes", "The address of discovery api"); #else DEFINE_string(discovery_api_addr, "", "The address of discovery api"); #endif DEFINE_int32(discovery_timeout_ms, 3000, "Timeout for discovery requests"); DEFINE_string(discovery_env, "prod", "Environment of services"); DEFINE_string(discovery_status, "1", "Status of services. 1 for ready, 2 for not ready, 3 for all"); int DiscoveryNamingService::ParseNodesResult( const butil::IOBuf& buf, std::string* server_addr) { BUTIL_RAPIDJSON_NAMESPACE::Document nodes; const std::string response = buf.to_string(); nodes.Parse(response.c_str()); auto itr = nodes.FindMember("data"); if (itr == nodes.MemberEnd()) { LOG(ERROR) << "No data field in discovery nodes response"; return -1; } const BUTIL_RAPIDJSON_NAMESPACE::Value& data = itr->value; if (!data.IsArray()) { LOG(ERROR) << "data field is not an array"; return -1; } for (BUTIL_RAPIDJSON_NAMESPACE::SizeType i = 0; i < data.Size(); ++i) { const BUTIL_RAPIDJSON_NAMESPACE::Value& addr_item = data[i]; auto itr_addr = addr_item.FindMember("addr"); auto itr_status = addr_item.FindMember("status"); if (itr_addr == addr_item.MemberEnd() || !itr_addr->value.IsString() || itr_status == addr_item.MemberEnd() || !itr_status->value.IsUint() || itr_status->value.GetUint() != 0) { continue; } server_addr->assign(itr_addr->value.GetString(), itr_addr->value.GetStringLength()); // Currently, we just use the first successful result break; } return 0; } int DiscoveryNamingService::ParseFetchsResult( const butil::IOBuf& buf, const char* service_name, std::vector<ServerNode>* servers) { BUTIL_RAPIDJSON_NAMESPACE::Document d; const std::string response = buf.to_string(); d.Parse(response.c_str()); auto itr_data = d.FindMember("data"); if (itr_data == d.MemberEnd()) { LOG(ERROR) << "No data field in discovery fetchs response"; return -1; } const BUTIL_RAPIDJSON_NAMESPACE::Value& data = itr_data->value; auto itr_service = data.FindMember(service_name); if (itr_service == data.MemberEnd()) { LOG(ERROR) << "No " << service_name << " field in discovery response"; return -1; } const BUTIL_RAPIDJSON_NAMESPACE::Value& services = itr_service->value; auto itr_instances = services.FindMember("instances"); if (itr_instances == services.MemberEnd()) { LOG(ERROR) << "Fail to find instances"; return -1; } const BUTIL_RAPIDJSON_NAMESPACE::Value& instances = itr_instances->value; if (!instances.IsArray()) { LOG(ERROR) << "Fail to parse instances as an array"; return -1; } for (BUTIL_RAPIDJSON_NAMESPACE::SizeType i = 0; i < instances.Size(); ++i) { auto itr = instances[i].FindMember("addrs"); if (itr == instances[i].MemberEnd() || !itr->value.IsArray()) { LOG(ERROR) << "Fail to find addrs or addrs is not an array"; return -1; } const BUTIL_RAPIDJSON_NAMESPACE::Value& addrs = itr->value; for (BUTIL_RAPIDJSON_NAMESPACE::SizeType j = 0; j < addrs.Size(); ++j) { if (!addrs[j].IsString()) { continue; } // The result returned by discovery include protocol prefix, such as // http://172.22.35.68:6686, which should be removed. butil::StringPiece addr(addrs[j].GetString(), addrs[j].GetStringLength()); butil::StringPiece::size_type pos = addr.find("://"); if (pos != butil::StringPiece::npos) { addr.remove_prefix(pos + 3); } ServerNode node; if (str2endpoint(addr.data(), &node.addr) != 0) { LOG(ERROR) << "Invalid address=`" << addr << '\''; continue; } servers->push_back(node); } } return 0; } int DiscoveryNamingService::GetServers(const char* service_name, std::vector<ServerNode>* servers) { if (!_is_initialized) { Channel api_channel; ChannelOptions channel_options; channel_options.protocol = PROTOCOL_HTTP; channel_options.timeout_ms = FLAGS_discovery_timeout_ms; channel_options.connect_timeout_ms = FLAGS_discovery_timeout_ms / 3; if (api_channel.Init(FLAGS_discovery_api_addr.c_str(), "", &channel_options) != 0) { LOG(ERROR) << "Fail to init channel to " << FLAGS_discovery_api_addr; return -1; } Controller cntl; cntl.http_request().uri() = FLAGS_discovery_api_addr; api_channel.CallMethod(NULL, &cntl, NULL, NULL, NULL); if (cntl.Failed()) { LOG(ERROR) << "Fail to access " << cntl.http_request().uri() << ": " << cntl.ErrorText(); return -1; } std::string discovery_addr; if (ParseNodesResult(cntl.response_attachment(), &discovery_addr) != 0) { return -1; } if (_channel.Init(discovery_addr.c_str(), "", &channel_options) != 0) { LOG(ERROR) << "Fail to init channel to " << discovery_addr; return -1; } _is_initialized = true; } servers->clear(); Controller cntl; cntl.http_request().uri() = butil::string_printf( "/discovery/fetchs?appid=%s&env=%s&status=%s", service_name, FLAGS_discovery_env.c_str(), FLAGS_discovery_status.c_str()); _channel.CallMethod(NULL, &cntl, NULL, NULL, NULL); if (cntl.Failed()) { LOG(ERROR) << "Fail to make /discovery/fetchs request: " << cntl.ErrorText(); return -1; } return ParseFetchsResult(cntl.response_attachment(), service_name, servers); } void DiscoveryNamingService::Describe(std::ostream& os, const DescribeOptions&) const { os << "discovery"; return; } NamingService* DiscoveryNamingService::New() const { return new DiscoveryNamingService; } void DiscoveryNamingService::Destroy() { delete this; } } // namespace policy } // namespace brpc <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 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 LICENSE 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. */ // Provide BZFS with a list server connection /* class header */ #include "ListServerConnection.h" /* system implementation headers */ #include <string.h> #include <string> #include <math.h> #include <errno.h> /* common implementation headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "Protocol.h" extern Address serverAddress; extern PingPacket getTeamCounts(); ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle) { // parse url std::string protocol, hostname, pathname; int port = 80; bool useDefault = false; // use default if it can't be parsed if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname)) useDefault = true; // use default if wrong protocol or invalid port if ((protocol != "http") || (port < 1) || (port > 65535)) useDefault = true; // use default if bad address Address address = Address::getHostAddress(hostname); if (address.isAny()) useDefault = true; // parse default list server URL if we need to; assume default works if (useDefault) { BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname); DEBUG1("Provided list server URL (%s) is invalid. Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL); } // add to list this->address = address; this->port = port; this->pathname = pathname; this->hostname = hostname; this->linkSocket = NotConnected; this->publicizeAddress = publicizedAddress; this->publicizeDescription = publicizedTitle; this->publicizeServer = true; //if this c'tor is called, it's safe to publicize // schedule initial ADD message queueMessage(ListServerLink::ADD); } ListServerLink::ListServerLink() { // does not create a usable link, so checks should be placed // in all public member functions to ensure that nothing tries // to happen if publicizeServer is false this->linkSocket = NotConnected; this->publicizeServer = false; } ListServerLink::~ListServerLink() { // now tell the list server that we're going away. this can // take some time but we don't want to wait too long. we do // our own multiplexing loop and wait for a maximum of 3 seconds // total. // if we aren't supposed to be publicizing, skip the whole thing // and don't waste 3 seconds. if (!publicizeServer) return; queueMessage(ListServerLink::REMOVE); TimeKeeper start = TimeKeeper::getCurrent(); do { // compute timeout float waitTime = 3.0f - (TimeKeeper::getCurrent() - start); if (waitTime <= 0.0f) break; if (!isConnected()) //queueMessage should have connected us break; // check for list server socket connection int fdMax = -1; fd_set write_set; fd_set read_set; FD_ZERO(&write_set); FD_ZERO(&read_set); if (phase == ListServerLink::CONNECTING) _FD_SET(linkSocket, &write_set); else _FD_SET(linkSocket, &read_set); fdMax = linkSocket; // wait for socket to connect or timeout struct timeval timeout; timeout.tv_sec = long(floorf(waitTime)); timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime))); int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set, 0, &timeout); if (nfound == 0) // Time has gone, close and go break; // check for connection to list server if (FD_ISSET(linkSocket, &write_set)) sendQueuedMessages(); else if (FD_ISSET(linkSocket, &read_set)) read(); } while (true); // stop list server communication closeLink(); } void ListServerLink::closeLink() { if (isConnected()) { close(linkSocket); DEBUG4("Closing List Server\n"); linkSocket = NotConnected; } } void ListServerLink::read() { if (isConnected()) { char buf[256]; recv(linkSocket, buf, sizeof(buf), 0); closeLink(); if (nextMessageType != ListServerLink::NONE) // There was a pending request arrived after we write: // we should redo all the stuff openLink(); } } void ListServerLink::openLink() { // start opening connection if not already doing so if (!isConnected()) { linkSocket = socket(AF_INET, SOCK_STREAM, 0); DEBUG4("Opening List Server\n"); if (!isConnected()) { return; } // set to non-blocking for connect if (BzfNetwork::setNonBlocking(linkSocket) < 0) { closeLink(); return; } // Make our connection come from our serverAddress in case we have // multiple/masked IPs so the list server can verify us. struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr = serverAddress; // assign the address to the socket if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) { closeLink(); return; } // connect. this should fail with EINPROGRESS but check for // success just in case. memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr = address; if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) { #if defined(_WIN32) #undef EINPROGRESS #define EINPROGRESS EWOULDBLOCK #endif if (getErrno() != EINPROGRESS) { nerror("connecting to list server"); // try to lookup dns name again in case it moved this->address = Address::getHostAddress(this->hostname); closeLink(); } else { phase = CONNECTING; } } else { // shouldn't arrive here. Just in case, clean closeLink(); } } } void ListServerLink::queueMessage(MessageType type) { // ignore if the server is not public if (!publicizeServer) return; // Open network connection only if closed if (!isConnected()) openLink(); // record next message to send. nextMessageType = type; } void ListServerLink::sendQueuedMessages() { if (!isConnected()) return; if (nextMessageType == ListServerLink::ADD) { DEBUG3("Queuing ADD message to list server\n"); addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription)); lastAddTime = TimeKeeper::getCurrent(); } else if (nextMessageType == ListServerLink::REMOVE) { DEBUG3("Queuing REMOVE message to list server\n"); removeMe(publicizeAddress); } } void ListServerLink::addMe(PingPacket pingInfo, std::string publicizedAddress, std::string publicizedTitle) { std::string msg; // encode ping reply as ascii hex digits plus NULL char gameInfo[PingPacketHexPackedSize + 1]; pingInfo.packHex(gameInfo); // TODO loop through and send any player tokens that need approval // TODO loop through groups we are interested and request those too // TODO we probably should convert to a POST instead. List server now allows either // send ADD message (must send blank line) msg = TextUtils::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s&title=%s HTTP/1.1\r\n" "Host: %s\r\nCache-Control: no-cache\r\n\r\n", pathname.c_str(), publicizedAddress.c_str(), getServerVersion(), gameInfo, getAppVersion(), publicizedTitle.c_str(), hostname.c_str()); // TODO need to listen for user info replies and setup callsign for isAllowedToEnter() sendMessage(msg); } void ListServerLink::removeMe(std::string publicizedAddress) { std::string msg; // send REMOVE (must send blank line) msg = TextUtils::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n" "Host: %s\r\nCache-Control: no-cache\r\n\r\n", pathname.c_str(), publicizedAddress.c_str(), hostname.c_str()); sendMessage(msg); } void ListServerLink::sendMessage(std::string message) { const int bufsize = 4096; char msg[bufsize]; strncpy(msg, message.c_str(), bufsize); msg[bufsize - 1] = 0; if (strlen(msg) > 0) { DEBUG3("%s\n", msg); if (send(linkSocket, msg, strlen(msg), 0) == -1) { perror("List server send failed"); DEBUG3("Unable to send to the list server!\n"); closeLink(); } else { nextMessageType = ListServerLink::NONE; phase = ListServerLink::WRITTEN; } } else { closeLink(); } } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>comments on next steps for authentication<commit_after>/* bzflag * Copyright (c) 1993 - 2004 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 LICENSE 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. */ // Provide BZFS with a list server connection /* class header */ #include "ListServerConnection.h" /* system implementation headers */ #include <string.h> #include <string> #include <math.h> #include <errno.h> /* common implementation headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "Protocol.h" extern Address serverAddress; extern PingPacket getTeamCounts(); ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle) { // parse url std::string protocol, hostname, pathname; int port = 80; bool useDefault = false; // use default if it can't be parsed if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname)) useDefault = true; // use default if wrong protocol or invalid port if ((protocol != "http") || (port < 1) || (port > 65535)) useDefault = true; // use default if bad address Address address = Address::getHostAddress(hostname); if (address.isAny()) useDefault = true; // parse default list server URL if we need to; assume default works if (useDefault) { BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname); DEBUG1("Provided list server URL (%s) is invalid. Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL); } // add to list this->address = address; this->port = port; this->pathname = pathname; this->hostname = hostname; this->linkSocket = NotConnected; this->publicizeAddress = publicizedAddress; this->publicizeDescription = publicizedTitle; this->publicizeServer = true; //if this c'tor is called, it's safe to publicize // schedule initial ADD message queueMessage(ListServerLink::ADD); } ListServerLink::ListServerLink() { // does not create a usable link, so checks should be placed // in all public member functions to ensure that nothing tries // to happen if publicizeServer is false this->linkSocket = NotConnected; this->publicizeServer = false; } ListServerLink::~ListServerLink() { // now tell the list server that we're going away. this can // take some time but we don't want to wait too long. we do // our own multiplexing loop and wait for a maximum of 3 seconds // total. // if we aren't supposed to be publicizing, skip the whole thing // and don't waste 3 seconds. if (!publicizeServer) return; queueMessage(ListServerLink::REMOVE); TimeKeeper start = TimeKeeper::getCurrent(); do { // compute timeout float waitTime = 3.0f - (TimeKeeper::getCurrent() - start); if (waitTime <= 0.0f) break; if (!isConnected()) //queueMessage should have connected us break; // check for list server socket connection int fdMax = -1; fd_set write_set; fd_set read_set; FD_ZERO(&write_set); FD_ZERO(&read_set); if (phase == ListServerLink::CONNECTING) _FD_SET(linkSocket, &write_set); else _FD_SET(linkSocket, &read_set); fdMax = linkSocket; // wait for socket to connect or timeout struct timeval timeout; timeout.tv_sec = long(floorf(waitTime)); timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime))); int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set, 0, &timeout); if (nfound == 0) // Time has gone, close and go break; // check for connection to list server if (FD_ISSET(linkSocket, &write_set)) sendQueuedMessages(); else if (FD_ISSET(linkSocket, &read_set)) read(); } while (true); // stop list server communication closeLink(); } void ListServerLink::closeLink() { if (isConnected()) { close(linkSocket); DEBUG4("Closing List Server\n"); linkSocket = NotConnected; } } void ListServerLink::read() { if (isConnected()) { char buf[256]; recv(linkSocket, buf, sizeof(buf), 0); closeLink(); if (nextMessageType != ListServerLink::NONE) // There was a pending request arrived after we write: // we should redo all the stuff openLink(); } } void ListServerLink::openLink() { // start opening connection if not already doing so if (!isConnected()) { linkSocket = socket(AF_INET, SOCK_STREAM, 0); DEBUG4("Opening List Server\n"); if (!isConnected()) { return; } // set to non-blocking for connect if (BzfNetwork::setNonBlocking(linkSocket) < 0) { closeLink(); return; } // Make our connection come from our serverAddress in case we have // multiple/masked IPs so the list server can verify us. struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr = serverAddress; // assign the address to the socket if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) { closeLink(); return; } // connect. this should fail with EINPROGRESS but check for // success just in case. memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr = address; if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) { #if defined(_WIN32) #undef EINPROGRESS #define EINPROGRESS EWOULDBLOCK #endif if (getErrno() != EINPROGRESS) { nerror("connecting to list server"); // try to lookup dns name again in case it moved this->address = Address::getHostAddress(this->hostname); closeLink(); } else { phase = CONNECTING; } } else { // shouldn't arrive here. Just in case, clean closeLink(); } } } void ListServerLink::queueMessage(MessageType type) { // ignore if the server is not public if (!publicizeServer) return; // Open network connection only if closed if (!isConnected()) openLink(); // record next message to send. nextMessageType = type; } void ListServerLink::sendQueuedMessages() { if (!isConnected()) return; if (nextMessageType == ListServerLink::ADD) { DEBUG3("Queuing ADD message to list server\n"); addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription)); lastAddTime = TimeKeeper::getCurrent(); } else if (nextMessageType == ListServerLink::REMOVE) { DEBUG3("Queuing REMOVE message to list server\n"); removeMe(publicizeAddress); } } void ListServerLink::addMe(PingPacket pingInfo, std::string publicizedAddress, std::string publicizedTitle) { std::string msg; // encode ping reply as ascii hex digits plus NULL char gameInfo[PingPacketHexPackedSize + 1]; pingInfo.packHex(gameInfo); // TODO loop through and send any player tokens that need approval // confirm=callsign0%3D1%3A123123123%0D%0Acallsign1%3D1%3A123123123%0D%0A // TODO loop through groups we are interested and request those too // TODO we probably should convert to a POST instead. List server now allows either // send ADD message (must send blank line) msg = TextUtils::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s&title=%s HTTP/1.1\r\n" "Host: %s\r\nCache-Control: no-cache\r\n\r\n", pathname.c_str(), publicizedAddress.c_str(), getServerVersion(), gameInfo, getAppVersion(), publicizedTitle.c_str(), hostname.c_str()); // TODO need to listen for user info replies and setup callsign for isAllowedToEnter() sendMessage(msg); } void ListServerLink::removeMe(std::string publicizedAddress) { std::string msg; // send REMOVE (must send blank line) msg = TextUtils::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n" "Host: %s\r\nCache-Control: no-cache\r\n\r\n", pathname.c_str(), publicizedAddress.c_str(), hostname.c_str()); sendMessage(msg); } void ListServerLink::sendMessage(std::string message) { const int bufsize = 4096; char msg[bufsize]; strncpy(msg, message.c_str(), bufsize); msg[bufsize - 1] = 0; if (strlen(msg) > 0) { DEBUG3("%s\n", msg); if (send(linkSocket, msg, strlen(msg), 0) == -1) { perror("List server send failed"); DEBUG3("Unable to send to the list server!\n"); closeLink(); } else { nextMessageType = ListServerLink::NONE; phase = ListServerLink::WRITTEN; } } else { closeLink(); } } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include "Mitos.h" std::vector<perf_event_sample> samples; char* cmd; void dump() { // Header std::cout << "variable,xidx,yidx,ip,time,latency,dataSource,hit,address,cpu" << std::endl; // Tuples for(size_t i=0; i<samples.size(); i++) { std::cout << samples[i].data_symbol; std::cout << ","; if(samples[i].access_index) { std::cout << std::dec << samples[i].access_index[0]; std::cout << ","; std::cout << std::dec << samples[i].access_index[1]; } else { std::cout << std::dec << -1; std::cout << ","; std::cout << std::dec << -1; } std::cout << ","; std::cout << std::hex << samples[i].ip ; std::cout << ","; std::cout << std::hex << samples[i].time ; std::cout << ","; std::cout << std::dec << samples[i].weight ; std::cout << ","; std::cout << std::hex << Mitos_data_source(&samples[i]) ; std::cout << ","; std::cout << std::hex << Mitos_hit_type(&samples[i]) ; std::cout << ","; std::cout << std::hex << samples[i].addr ; std::cout << ","; std::cout << std::dec << samples[i].cpu << std::endl; std::cout << std::endl; } } void sample_handler(perf_event_sample *sample, void *args) { Mitos_resolve_symbol(sample); samples.push_back(*sample); } void workit() { int N = 512; double *a; double *b; double *c; int i,j,k; a = (double*)malloc(sizeof(double)*N*N); b = (double*)malloc(sizeof(double)*N*N); c = (double*)malloc(sizeof(double)*N*N); size_t dims[2]; dims[0] = N; dims[1] = N; Mitos_add_symbol("a",a,sizeof(double),dims,2); Mitos_add_symbol("b",b,sizeof(double),dims,2); Mitos_add_symbol("c",c,sizeof(double),dims,2); for(i=0; i<N; ++i) for(j=0; j<N; ++j) c[i*N+j] = 0; for(i=0; i<N; ++i) for(j=0; j<N; ++j) for(k=0; k<N; ++k) c[i*N+j] += a[i*N+k] * b[k*N+j]; } int main(int argc, char **argv) { cmd = argv[0]; Mitos_set_sample_mode(SMPL_MEMORY); Mitos_set_handler_fn(&sample_handler,NULL); Mitos_prepare(0); Mitos_begin_sampler(); workit(); Mitos_end_sampler(); dump(); } <commit_msg>use funciton in test<commit_after>#include <iostream> #include <fstream> #include <vector> #include "Mitos.h" std::vector<perf_event_sample> samples; char* cmd; void dump() { // Header std::cout << "variable,xidx,yidx,ip,time,latency,dataSource,hit,address,cpu" << std::endl; // Tuples for(size_t i=0; i<samples.size(); i++) { std::cout << samples[i].data_symbol; std::cout << ","; std::cout << std::dec << Mitos_x_index(&samples[i]); std::cout << ","; std::cout << std::dec << Mitos_y_index(&samples[i]); std::cout << ","; std::cout << std::hex << samples[i].ip ; std::cout << ","; std::cout << std::hex << samples[i].time ; std::cout << ","; std::cout << std::dec << samples[i].weight ; std::cout << ","; std::cout << std::hex << Mitos_data_source(&samples[i]) ; std::cout << ","; std::cout << std::hex << Mitos_hit_type(&samples[i]) ; std::cout << ","; std::cout << std::hex << samples[i].addr ; std::cout << ","; std::cout << std::dec << samples[i].cpu << std::endl; std::cout << std::endl; } } void sample_handler(perf_event_sample *sample, void *args) { Mitos_resolve_symbol(sample); samples.push_back(*sample); } void workit() { int N = 512; double *a; double *b; double *c; int i,j,k; a = (double*)malloc(sizeof(double)*N*N); b = (double*)malloc(sizeof(double)*N*N); c = (double*)malloc(sizeof(double)*N*N); size_t dims[2]; dims[0] = N; dims[1] = N; Mitos_add_symbol("a",a,sizeof(double),dims,2); Mitos_add_symbol("b",b,sizeof(double),dims,2); Mitos_add_symbol("c",c,sizeof(double),dims,2); for(i=0; i<N; ++i) for(j=0; j<N; ++j) c[i*N+j] = 0; for(i=0; i<N; ++i) for(j=0; j<N; ++j) for(k=0; k<N; ++k) c[i*N+j] += a[i*N+k] * b[k*N+j]; } int main(int argc, char **argv) { cmd = argv[0]; Mitos_set_sample_mode(SMPL_MEMORY); Mitos_set_handler_fn(&sample_handler,NULL); Mitos_prepare(0); Mitos_begin_sampler(); workit(); Mitos_end_sampler(); dump(); } <|endoftext|>
<commit_before>#include "HexagonAlignLoads.h" #include "IRMutator.h" #include "IROperator.h" #include "Scope.h" #include "Bounds.h" #include "ModulusRemainder.h" #include "Simplify.h" namespace Halide { namespace Internal { using std::vector; class HexagonAlignLoads : public IRMutator { public: HexagonAlignLoads(Target t) : target(t) {} private: Target target; /** Alignment info for Int(32) variables in scope. */ Scope<ModulusRemainder> alignment_info; using IRMutator::visit; ModulusRemainder get_alignment_info(Expr e) { return modulus_remainder(e, alignment_info); } void visit(const Load *op) { debug(4) << "HexagonAlignLoads: Working on " << (Expr) op << "..\n"; Expr index = mutate(op->index); if (op->type.is_vector()) { bool external = op->image.defined(); if (external) { debug(4) << "HexagonAlignLoads: Not dealing with an external image\n"; debug(4) << (Expr) op << "\n"; expr = op; return; } else { const Ramp *ramp = index.as<Ramp>(); const IntImm *stride = ramp ? ramp->stride.as<IntImm>() : NULL; // We will work only on natural vectors supported by the target. if (ramp->lanes != target.natural_vector_size(op->type)) { expr = op; return; } if (ramp && stride && stride->value == 1) { int lanes = ramp->lanes; int vec_size = target.natural_vector_size(Int(8)); // If this is a parameter, the base_alignment should be host_alignment. // This cannot be an external image because we have already checked for // it. Otherwise, this is an internal buffers that is always aligned // to the natural vector width. int base_alignment = op->param.defined() ? op->param.host_alignment() : vec_size; int base_lanes_off = mod_imp(base_alignment, lanes); // We reason only in terms of lanes. Each lane is a vector element. // We want to know the following. // 1. if the base + ramp->base (i.e. the index) are aligned. // 2. if not, then how many lanes off an aligned address are they. // 3. if 2, then we create two loads and slice_vector them. // We know the base itself puts us off an aligned address by base_lanes_off // number of lanes. ModulusRemainder mod_rem = get_alignment_info(ramp->base); if (mod_rem.modulus == 1 && mod_rem.remainder == 0) { // We know nothing about alignment. Give up. // TODO: Fix this. debug(4) << "HexagonAlignLoads: Cannot reason about alignment.\n"; debug(4) << "HexagonAlignLoads: Type: " << op->type << "\n"; debug(4) << "HexagonAlignLoads: Index: " << index << "\n"; expr = op; return; } int base_mod = base_lanes_off + mod_imp(mod_rem.modulus, lanes); int rem_mod = mod_imp(mod_rem.remainder, lanes); if (!(base_mod + rem_mod)) { expr = op; debug(4) << "HexagonAlignLoads: Encountered a perfectly aligned load.\n"; debug(4) << "HexagonAlignLoads: Type: " << op->type << "\n"; debug(4) << "HexagonAlignLoads: Index: " << index << "\n"; return; } else { Expr base = ramp->base; const Add *add = base.as<Add>(); const IntImm *b = add->b.as<IntImm>(); if (!b) { // Should we be expecting the index to be in simplified // canonical form, i.e. expression + IntImm? debug(4) << "HexagonAlignLoads: add->b is not a constant\n"; debug(4) << "HexagonAlignLoads: Type: " << op->type << "\n"; debug(4) << "HexagonAlignLoads: Index: " << index << "\n"; expr = op; return; } Expr base_low = base - (base_mod + rem_mod); Expr ramp_low = Ramp::make(simplify(base_low), 1, lanes); Expr ramp_high = Ramp::make(simplify(base_low + lanes), 1, lanes); Expr load_low = Load::make(op->type, op->name, ramp_low, op->image, op->param); Expr load_high = Load::make(op->type, op->name, ramp_high, op->image, op->param); // slice_vector considers the vectors in it to be concatenated and the result // is a vector containing as many lanes as the last argument and the vector // begins at lane number specified by the penultimate arg. // So, slice_vector(2, a, b, 126, 128) gives a vector of 128 lanes starting // from lanes 126 through 253 of the concatenated vector a.b. debug(4) << "HexagonAlignLoads: Unaligned Load: Converting " << (Expr) op << " into ...\n"; expr = Call::make(op->type, Call::slice_vector, { make_two(Int(32)), load_low, load_high, make_const(Int(32), (base_mod + rem_mod)), make_const(Int(32), lanes) }, Call::PureIntrinsic); debug(4) << "... " << expr << "\n"; return; } } else { expr = op; return; } } } else { expr = op; return; } } template<typename NodeType, typename LetType> void visit_let(NodeType &result, const LetType *op) { if (op->value.type() == Int(32)) { alignment_info.push(op->name, modulus_remainder(op->value, alignment_info)); } NodeType body = mutate(op->body); if (op->value.type() == Int(32)) { alignment_info.pop(op->name); } result = LetType::make(op->name, op->value, body); } void visit(const Let *op) { visit_let(expr, op); } void visit(const LetStmt *op) { visit_let(stmt, op); } }; Stmt hexagon_align_loads(Stmt s, const Target &t) { return HexagonAlignLoads(t).mutate(s); } } } <commit_msg>Handle loads that may be values in Lets<commit_after>#include "HexagonAlignLoads.h" #include "IRMutator.h" #include "IROperator.h" #include "Scope.h" #include "Bounds.h" #include "ModulusRemainder.h" #include "Simplify.h" namespace Halide { namespace Internal { using std::vector; class HexagonAlignLoads : public IRMutator { public: HexagonAlignLoads(Target t) : target(t) {} private: Target target; /** Alignment info for Int(32) variables in scope. */ Scope<ModulusRemainder> alignment_info; using IRMutator::visit; ModulusRemainder get_alignment_info(Expr e) { return modulus_remainder(e, alignment_info); } void visit(const Load *op) { debug(4) << "HexagonAlignLoads: Working on " << (Expr) op << "..\n"; Expr index = mutate(op->index); if (op->type.is_vector()) { bool external = op->image.defined(); if (external) { debug(4) << "HexagonAlignLoads: Not dealing with an external image\n"; debug(4) << (Expr) op << "\n"; expr = op; return; } else { const Ramp *ramp = index.as<Ramp>(); const IntImm *stride = ramp ? ramp->stride.as<IntImm>() : NULL; // We will work only on natural vectors supported by the target. if (ramp->lanes != target.natural_vector_size(op->type)) { expr = op; return; } if (ramp && stride && stride->value == 1) { int lanes = ramp->lanes; int vec_size = target.natural_vector_size(Int(8)); // If this is a parameter, the base_alignment should be host_alignment. // This cannot be an external image because we have already checked for // it. Otherwise, this is an internal buffers that is always aligned // to the natural vector width. int base_alignment = op->param.defined() ? op->param.host_alignment() : vec_size; int base_lanes_off = mod_imp(base_alignment, lanes); // We reason only in terms of lanes. Each lane is a vector element. // We want to know the following. // 1. if the base + ramp->base (i.e. the index) are aligned. // 2. if not, then how many lanes off an aligned address are they. // 3. if 2, then we create two loads and slice_vector them. // We know the base itself puts us off an aligned address by base_lanes_off // number of lanes. ModulusRemainder mod_rem = get_alignment_info(ramp->base); if (mod_rem.modulus == 1 && mod_rem.remainder == 0) { // We know nothing about alignment. Give up. // TODO: Fix this. debug(4) << "HexagonAlignLoads: Cannot reason about alignment.\n"; debug(4) << "HexagonAlignLoads: Type: " << op->type << "\n"; debug(4) << "HexagonAlignLoads: Index: " << index << "\n"; expr = op; return; } int base_mod = base_lanes_off + mod_imp(mod_rem.modulus, lanes); int rem_mod = mod_imp(mod_rem.remainder, lanes); if (!(base_mod + rem_mod)) { expr = op; debug(4) << "HexagonAlignLoads: Encountered a perfectly aligned load.\n"; debug(4) << "HexagonAlignLoads: Type: " << op->type << "\n"; debug(4) << "HexagonAlignLoads: Index: " << index << "\n"; return; } else { Expr base = ramp->base; const Add *add = base.as<Add>(); const IntImm *b = add->b.as<IntImm>(); if (!b) { // Should we be expecting the index to be in simplified // canonical form, i.e. expression + IntImm? debug(4) << "HexagonAlignLoads: add->b is not a constant\n"; debug(4) << "HexagonAlignLoads: Type: " << op->type << "\n"; debug(4) << "HexagonAlignLoads: Index: " << index << "\n"; expr = op; return; } Expr base_low = base - (base_mod + rem_mod); Expr ramp_low = Ramp::make(simplify(base_low), 1, lanes); Expr ramp_high = Ramp::make(simplify(base_low + lanes), 1, lanes); Expr load_low = Load::make(op->type, op->name, ramp_low, op->image, op->param); Expr load_high = Load::make(op->type, op->name, ramp_high, op->image, op->param); // slice_vector considers the vectors in it to be concatenated and the result // is a vector containing as many lanes as the last argument and the vector // begins at lane number specified by the penultimate arg. // So, slice_vector(2, a, b, 126, 128) gives a vector of 128 lanes starting // from lanes 126 through 253 of the concatenated vector a.b. debug(4) << "HexagonAlignLoads: Unaligned Load: Converting " << (Expr) op << " into ...\n"; expr = Call::make(op->type, Call::slice_vector, { make_two(Int(32)), load_low, load_high, make_const(Int(32), (base_mod + rem_mod)), make_const(Int(32), lanes) }, Call::PureIntrinsic); debug(4) << "... " << expr << "\n"; return; } } else { expr = op; return; } } } else { expr = op; return; } } template<typename NodeType, typename LetType> void visit_let(NodeType &result, const LetType *op) { Expr value; if (op->value.type() == Int(32)) { alignment_info.push(op->name, modulus_remainder(op->value, alignment_info)); } else { const Load *ld = op->value.template as<Load>(); if (ld) value = mutate(op->value); else value = op->value; } NodeType body = mutate(op->body); if (op->value.type() == Int(32)) { alignment_info.pop(op->name); } result = LetType::make(op->name, value, body); } void visit(const Let *op) { visit_let(expr, op); } void visit(const LetStmt *op) { visit_let(stmt, op); } }; Stmt hexagon_align_loads(Stmt s, const Target &t) { return HexagonAlignLoads(t).mutate(s); } } } <|endoftext|>
<commit_before>#include <stdexcept> #include <sstream> #include <cmath> #include <boost/lexical_cast.hpp> #include <boost/timer/timer.hpp> #include "gtest/gtest.h" #include "HorizontalDiffusionSA.h" #include "HoriDiffReference.h" #include "Definitions.h" #include "UnittestEnvironment.h" #include "HaloUpdateManager.h" #include "Options.h" #include "mpi.h" #ifdef __CUDA_BACKEND__ #include "cuda_profiler_api.h" #endif // method parsing a string option int parseIntOption(int argc, char **argv, std::string option, int defaultValue) { int result = defaultValue; for(int i = 0; i < argc; ++i) { if(argv[i] == option && i+1 < argc) { result = boost::lexical_cast<int>(argv[i+1]); break; } } return result; } // method parsing a string option std::string parseStringOption(int argc, char **argv, std::string option, std::string defaultValue) { std::string result = defaultValue; for(int i = 0; i < argc; ++i) { if(argv[i] == option && i+1 < argc) { result = argv[i+1]; break; } } return result; } // method parsing a boolean option bool parseBoolOption(int argc, char **argv, std::string option) { bool result = false; for(int i = 0; i < argc; ++i) { if(argv[i] == option) { result = true; break; } } return result; } void readOptions(int argc, char** argv) { std::cout << "HP2CDycoreUnittest\n\n"; std::cout << "usage: HP2CDycoreUnittest -p <dataPath>" << "\n"; for(int i=0; i < argc; ++i) std::cout << std::string(argv[i]) << std::endl; // parse additional command options int iSize = parseIntOption(argc, argv, "--ie", 128); int jSize = parseIntOption(argc, argv, "--je", 128); int kSize = parseIntOption(argc, argv, "--ke", 60); bool sync = parseBoolOption(argc, argv, "--sync"); bool nocomm = parseBoolOption(argc, argv, "--nocomm"); bool nocomp = parseBoolOption(argc, argv, "--nocomp"); bool nostella = parseBoolOption(argc, argv, "--nostella"); bool nogcl = parseBoolOption(argc, argv, "--nogcl"); int nHaloUpdates = parseIntOption(argc, argv, "--nh", 2); int nRep = parseIntOption(argc, argv, "-n", cNumBenchmarkRepetitions); bool inOrder = parseBoolOption(argc, argv, "--inorder"); IJKSize domain; domain.Init(iSize, jSize, kSize); Options::getInstance().domain_ = domain; Options::getInstance().sync_ = sync; Options::getInstance().nocomm_ = nocomm; Options::getInstance().nocomp_ = nocomp; Options::getInstance().nostella_ = nostella; Options::getInstance().nogcl_ = nogcl; Options::getInstance().nHaloUpdates_ = nHaloUpdates; Options::getInstance().nRep_ = nRep; Options::getInstance().inOrder_ = inOrder; } void setupDevice() { #ifdef MVAPICH2 const char* env_p = std::getenv("SLURM_PROCID"); if(!env_p) { std::cout << "SLURM_PROCID not set" << std::endl; exit (EXIT_FAILURE); } #else const char* env_p = std::getenv("OMPI_COMM_WORLD_RANK"); if(!env_p) { std::cout << "OMPI_COMM_WORLD_RANK not set" << std::endl; exit (EXIT_FAILURE); } #endif int numGPU; cudaError_t error = cudaGetDeviceCount(&numGPU); if(error) { std::cout << "CUDA ERROR " << std::endl; exit(EXIT_FAILURE); } error = cudaSetDevice(atoi(env_p)%numGPU); if(error) { std::cout << "CUDA ERROR " << std::endl; exit(EXIT_FAILURE); } } int main(int argc, char** argv) { MPI_Init(&argc, &argv); int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); readOptions(argc, argv); setupDevice(); HoriDiffRepository* pRepository_ = &UnittestEnvironment::getInstance().repository(); IJKSize domain_ = UnittestEnvironment::getInstance().calculationDomain(); HoriDiffReference ref_; ref_.Init(*pRepository_); ref_.Generate(); std::cout << "CONFIGURATION " << std::endl; std::cout << "====================================" << std::endl; std::cout << "Domain : [" << Options::getInstance().domain_.iSize() << "," << Options::getInstance().domain_.jSize() << "," <<Options::getInstance().domain_.kSize() << "]" << std::endl; std::cout << "Sync? : " << Options::getInstance().sync_ << std::endl; std::cout << "NoComm? : " << Options::getInstance().nocomm_ << std::endl; std::cout << "NoComp? : " << Options::getInstance().nocomp_ << std::endl; std::cout << "NoStella? : " << Options::getInstance().nostella_ << std::endl; std::cout << "NoGCL? : " << Options::getInstance().nogcl_ << std::endl; std::cout << "Number Halo Exchanges : " << Options::getInstance().nHaloUpdates_ << std::endl; std::cout << "Number benchmark repetitions : " << Options::getInstance().nRep_ << std::endl; std::cout << "In Order halo exchanges? : " << Options::getInstance().inOrder_ << std::endl; int deviceId; if( cudaGetDevice(&deviceId) != cudaSuccess) { std::cerr << cudaGetErrorString(cudaGetLastError()) << std::endl; } std::cout << "Device ID :" << deviceId << std::endl; #ifdef MVAPICH2 const char* env_p = std::getenv("SLURM_PROCID"); std::cout << "SLURM_PROCID :" << env_p << std::endl; std::cout << "Compiled for mvapich2" << std::endl; #else const char* env_p = std::getenv("OMPI_COMM_WORLD_RANK"); std::cout << "OMPI_COMM_WORLD_RANK :" << env_p<< std::endl; std::cout << "Compiled for openmpi" << std::endl; #endif boost::timer::cpu_timer cpu_timer; // generate a reference field that contain the output of a horizontal diffusion operator HorizontalDiffusionSA horizontalDiffusionSA; horizontalDiffusionSA.Init(*pRepository_, UnittestEnvironment::getInstance().communicationConfiguration()); IJBoundary applyB; applyB.Init(-1,1,-1,1); horizontalDiffusionSA.Apply(applyB); // horizontalDiffusionSA.ApplyHalos(); pRepository_->Swap(); horizontalDiffusionSA.Apply(); IJKRealField& outField = pRepository_->u_out(0); IJKRealField& refField = pRepository_->refField(); // we only verify the stencil once (before starting the real benchmark) IJKBoundary checkBoundary; checkBoundary.Init(0, 0, 0, 0, 0, 0); horizontalDiffusionSA.Apply(); cudaDeviceSynchronize(); horizontalDiffusionSA.ResetMeters(); #ifdef __CUDA_BACKEND__ cudaProfilerStart(); #endif cpu_timer.start(); for(int i=0; i < Options::getInstance().nRep_; ++i) { int numGPU; cudaGetDeviceCount(&numGPU); // flush cache between calls to horizontal diffusion stencil if(i!=0 && !Options::getInstance().sync_ && !Options::getInstance().nocomm_ && !Options::getInstance().inOrder_) { for(int c=0; c < Options::getInstance().nHaloUpdates_ ; ++c) { horizontalDiffusionSA.WaitHalos(c); } } if(!Options::getInstance().nocomp_) { horizontalDiffusionSA.Apply(); } if(Options::getInstance().inOrder_) { for(int c=0; c < Options::getInstance().nHaloUpdates_ ; ++c) { if(!Options::getInstance().nocomm_){ if(!Options::getInstance().sync_) horizontalDiffusionSA.StartHalos(c); else horizontalDiffusionSA.ApplyHalos(c); } pRepository_->Swap(); if(!Options::getInstance().nocomp_) horizontalDiffusionSA.Apply(); if(!Options::getInstance().nocomm_){ if(!Options::getInstance().sync_) horizontalDiffusionSA.WaitHalos(c); } } } else { for(int c=0; c < Options::getInstance().nHaloUpdates_ ; ++c) { if(!Options::getInstance().nocomm_){ if(!Options::getInstance().sync_) horizontalDiffusionSA.StartHalos(c); else horizontalDiffusionSA.ApplyHalos(c); } pRepository_->Swap(); if(!Options::getInstance().nocomp_) horizontalDiffusionSA.Apply(); } } } if(!Options::getInstance().nocomm_ && !Options::getInstance().sync_ && !Options::getInstance().inOrder_){ for(int c=0; c < Options::getInstance().nHaloUpdates_ ; ++c) { horizontalDiffusionSA.WaitHalos(c); } } cudaDeviceSynchronize(); #ifdef __CUDA_BACKEND__ cudaProfilerStop(); #endif cpu_timer.stop(); boost::timer::cpu_times elapsed = cpu_timer.elapsed(); double total_time = ((double) elapsed.wall)/1000000000.0; int num_ranks; MPI_Comm_size(MPI_COMM_WORLD, &num_ranks); int rank_id; MPI_Comm_rank(MPI_COMM_WORLD, &rank_id); std::vector<double> total_time_g(num_ranks); MPI_Gather(&total_time, 1, MPI_DOUBLE, &(total_time_g[0]), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); if(rank_id==0) { double avg = 0.0; double rms = 0.0; total_time_g[3] = 5; for(int i=0; i < num_ranks; ++i) { avg += total_time_g[i]; } avg /= (double)num_ranks; for(int i=0; i < num_ranks; ++i) { rms += (total_time_g[i]-avg)*(total_time_g[i]-avg); } rms /= (double)num_ranks; rms = std::sqrt(rms); std::cout <<"ELAPSED TIME : " << avg << " +- + " << rms << std::endl; } MPI_Finalize(); } <commit_msg>Fix error in MPI_Finalize<commit_after>#include <stdexcept> #include <sstream> #include <cmath> #include <boost/lexical_cast.hpp> #include <boost/timer/timer.hpp> #include "gtest/gtest.h" #include "HorizontalDiffusionSA.h" #include "HoriDiffReference.h" #include "Definitions.h" #include "UnittestEnvironment.h" #include "HaloUpdateManager.h" #include "Options.h" #include "mpi.h" #ifdef __CUDA_BACKEND__ #include "cuda_profiler_api.h" #endif // method parsing a string option int parseIntOption(int argc, char **argv, std::string option, int defaultValue) { int result = defaultValue; for(int i = 0; i < argc; ++i) { if(argv[i] == option && i+1 < argc) { result = boost::lexical_cast<int>(argv[i+1]); break; } } return result; } // method parsing a string option std::string parseStringOption(int argc, char **argv, std::string option, std::string defaultValue) { std::string result = defaultValue; for(int i = 0; i < argc; ++i) { if(argv[i] == option && i+1 < argc) { result = argv[i+1]; break; } } return result; } // method parsing a boolean option bool parseBoolOption(int argc, char **argv, std::string option) { bool result = false; for(int i = 0; i < argc; ++i) { if(argv[i] == option) { result = true; break; } } return result; } void readOptions(int argc, char** argv) { std::cout << "HP2CDycoreUnittest\n\n"; std::cout << "usage: HP2CDycoreUnittest -p <dataPath>" << "\n"; for(int i=0; i < argc; ++i) std::cout << std::string(argv[i]) << std::endl; // parse additional command options int iSize = parseIntOption(argc, argv, "--ie", 128); int jSize = parseIntOption(argc, argv, "--je", 128); int kSize = parseIntOption(argc, argv, "--ke", 60); bool sync = parseBoolOption(argc, argv, "--sync"); bool nocomm = parseBoolOption(argc, argv, "--nocomm"); bool nocomp = parseBoolOption(argc, argv, "--nocomp"); bool nostella = parseBoolOption(argc, argv, "--nostella"); bool nogcl = parseBoolOption(argc, argv, "--nogcl"); int nHaloUpdates = parseIntOption(argc, argv, "--nh", 2); int nRep = parseIntOption(argc, argv, "-n", cNumBenchmarkRepetitions); bool inOrder = parseBoolOption(argc, argv, "--inorder"); IJKSize domain; domain.Init(iSize, jSize, kSize); Options::getInstance().domain_ = domain; Options::getInstance().sync_ = sync; Options::getInstance().nocomm_ = nocomm; Options::getInstance().nocomp_ = nocomp; Options::getInstance().nostella_ = nostella; Options::getInstance().nogcl_ = nogcl; Options::getInstance().nHaloUpdates_ = nHaloUpdates; Options::getInstance().nRep_ = nRep; Options::getInstance().inOrder_ = inOrder; } void setupDevice() { #ifdef MVAPICH2 const char* env_p = std::getenv("SLURM_PROCID"); if(!env_p) { std::cout << "SLURM_PROCID not set" << std::endl; exit (EXIT_FAILURE); } #else const char* env_p = std::getenv("OMPI_COMM_WORLD_RANK"); if(!env_p) { std::cout << "OMPI_COMM_WORLD_RANK not set" << std::endl; exit (EXIT_FAILURE); } #endif int numGPU; cudaError_t error = cudaGetDeviceCount(&numGPU); if(error) { std::cout << "CUDA ERROR " << std::endl; exit(EXIT_FAILURE); } error = cudaSetDevice(atoi(env_p)%numGPU); if(error) { std::cout << "CUDA ERROR " << std::endl; exit(EXIT_FAILURE); } } int main(int argc, char** argv) { MPI_Init(&argc, &argv); int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); readOptions(argc, argv); setupDevice(); HoriDiffRepository* pRepository_ = &UnittestEnvironment::getInstance().repository(); IJKSize domain_ = UnittestEnvironment::getInstance().calculationDomain(); HoriDiffReference ref_; ref_.Init(*pRepository_); ref_.Generate(); std::cout << "CONFIGURATION " << std::endl; std::cout << "====================================" << std::endl; std::cout << "Domain : [" << Options::getInstance().domain_.iSize() << "," << Options::getInstance().domain_.jSize() << "," <<Options::getInstance().domain_.kSize() << "]" << std::endl; std::cout << "Sync? : " << Options::getInstance().sync_ << std::endl; std::cout << "NoComm? : " << Options::getInstance().nocomm_ << std::endl; std::cout << "NoComp? : " << Options::getInstance().nocomp_ << std::endl; std::cout << "NoStella? : " << Options::getInstance().nostella_ << std::endl; std::cout << "NoGCL? : " << Options::getInstance().nogcl_ << std::endl; std::cout << "Number Halo Exchanges : " << Options::getInstance().nHaloUpdates_ << std::endl; std::cout << "Number benchmark repetitions : " << Options::getInstance().nRep_ << std::endl; std::cout << "In Order halo exchanges? : " << Options::getInstance().inOrder_ << std::endl; int deviceId; if( cudaGetDevice(&deviceId) != cudaSuccess) { std::cerr << cudaGetErrorString(cudaGetLastError()) << std::endl; } std::cout << "Device ID :" << deviceId << std::endl; #ifdef MVAPICH2 const char* env_p = std::getenv("SLURM_PROCID"); std::cout << "SLURM_PROCID :" << env_p << std::endl; std::cout << "Compiled for mvapich2" << std::endl; #else const char* env_p = std::getenv("OMPI_COMM_WORLD_RANK"); std::cout << "OMPI_COMM_WORLD_RANK :" << env_p<< std::endl; std::cout << "Compiled for openmpi" << std::endl; #endif boost::timer::cpu_timer cpu_timer; // generate a reference field that contain the output of a horizontal diffusion operator HorizontalDiffusionSA horizontalDiffusionSA; horizontalDiffusionSA.Init(*pRepository_, UnittestEnvironment::getInstance().communicationConfiguration()); IJBoundary applyB; applyB.Init(-1,1,-1,1); horizontalDiffusionSA.Apply(applyB); // horizontalDiffusionSA.ApplyHalos(); pRepository_->Swap(); horizontalDiffusionSA.Apply(); IJKRealField& outField = pRepository_->u_out(0); IJKRealField& refField = pRepository_->refField(); // we only verify the stencil once (before starting the real benchmark) IJKBoundary checkBoundary; checkBoundary.Init(0, 0, 0, 0, 0, 0); horizontalDiffusionSA.Apply(); cudaDeviceSynchronize(); horizontalDiffusionSA.ResetMeters(); #ifdef __CUDA_BACKEND__ cudaProfilerStart(); #endif cpu_timer.start(); for(int i=0; i < Options::getInstance().nRep_; ++i) { int numGPU; cudaGetDeviceCount(&numGPU); // flush cache between calls to horizontal diffusion stencil if(i!=0 && !Options::getInstance().sync_ && !Options::getInstance().nocomm_ && !Options::getInstance().inOrder_) { for(int c=0; c < Options::getInstance().nHaloUpdates_ ; ++c) { horizontalDiffusionSA.WaitHalos(c); } } if(!Options::getInstance().nocomp_) { horizontalDiffusionSA.Apply(); } if(Options::getInstance().inOrder_) { for(int c=0; c < Options::getInstance().nHaloUpdates_ ; ++c) { if(!Options::getInstance().nocomm_){ if(!Options::getInstance().sync_) horizontalDiffusionSA.StartHalos(c); else horizontalDiffusionSA.ApplyHalos(c); } pRepository_->Swap(); if(!Options::getInstance().nocomp_) horizontalDiffusionSA.Apply(); if(!Options::getInstance().nocomm_){ if(!Options::getInstance().sync_) horizontalDiffusionSA.WaitHalos(c); } } } else { for(int c=0; c < Options::getInstance().nHaloUpdates_ ; ++c) { if(!Options::getInstance().nocomm_){ if(!Options::getInstance().sync_) horizontalDiffusionSA.StartHalos(c); else horizontalDiffusionSA.ApplyHalos(c); } pRepository_->Swap(); if(!Options::getInstance().nocomp_) horizontalDiffusionSA.Apply(); } } } if(!Options::getInstance().nocomm_ && !Options::getInstance().sync_ && !Options::getInstance().inOrder_){ for(int c=0; c < Options::getInstance().nHaloUpdates_ ; ++c) { horizontalDiffusionSA.WaitHalos(c); } } cudaDeviceSynchronize(); #ifdef __CUDA_BACKEND__ cudaProfilerStop(); #endif cpu_timer.stop(); boost::timer::cpu_times elapsed = cpu_timer.elapsed(); double total_time = ((double) elapsed.wall)/1000000000.0; int num_ranks; MPI_Comm_size(MPI_COMM_WORLD, &num_ranks); int rank_id; MPI_Comm_rank(MPI_COMM_WORLD, &rank_id); std::vector<double> total_time_g(num_ranks); MPI_Gather(&total_time, 1, MPI_DOUBLE, &(total_time_g[0]), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); if(rank_id==0) { double avg = 0.0; double rms = 0.0; for(int i=0; i < num_ranks; ++i) { avg += total_time_g[i]; } avg /= (double)num_ranks; for(int i=0; i < num_ranks; ++i) { rms += (total_time_g[i]-avg)*(total_time_g[i]-avg); } rms /= (double)num_ranks; rms = std::sqrt(rms); std::cout <<"ELAPSED TIME : " << avg << " +- + " << rms << std::endl; } MPI_Finalize(); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/common/include/p9_mc_scom_addresses_fld_fixes.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mc_scom_addresses_fld_fixes.H /// @brief The *scom_addresses_fld.H files are generated form figtree, /// but the figree can be wrong. This file is included in /// *_scom_addresses_fld.H and allows incorrect constants to be /// fixed manually. /// // *HWP HWP Owner: Ben Gass <[email protected]> // *HWP FW Owner: ? <?> // *HWP Team: SAO // *HWP Level: 1 // *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE #ifndef __P9_MC_SCOM_ADDRESSES_FLD_FIXES_H #define __P9_MC_SCOM_ADDRESSES_FLD_FIXES_H //Example //Copy the whole line from the *scom_addresses_fld.H file. Then add FIX in front of REG //and add another paramter that is the new value you want. // //FIXREG64_FLD( PU_ALTD_CMD_REG_FBC_WITH_TM_QUIESCE, 24, SH_UNT, SH_ACS_SCOM, SH_FLD_FBC_WITH_TM_QUIESCE, // 12); const static uint64_t SH_FLD_COMMAND_LIST_TIMEOUT_SPEC = 99990000; REG64_FLD( MCS_MCFIR_COMMAND_LIST_TIMEOUT_SPEC , 9 , SH_UNT_MCS , SH_ACS_SCOM2_OR , SH_FLD_COMMAND_LIST_TIMEOUT_SPEC ); REG64_FLD( MCA_DDRPHY_DP16_SYSCLK_PR0_P0_0_01_ENABLE , 48 , SH_UNT_MCA , SH_ACS_SCOM_RW , 0 ); #endif <commit_msg>New scom addresses const headers for chip 9031<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/common/include/p9_mc_scom_addresses_fld_fixes.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mc_scom_addresses_fld_fixes.H /// @brief The *scom_addresses_fld.H files are generated form figtree, /// but the figree can be wrong. This file is included in /// *_scom_addresses_fld.H and allows incorrect constants to be /// fixed manually. /// // *HWP HWP Owner: Ben Gass <[email protected]> // *HWP FW Owner: ? <?> // *HWP Team: SAO // *HWP Level: 1 // *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE #ifndef __P9_MC_SCOM_ADDRESSES_FLD_FIXES_H #define __P9_MC_SCOM_ADDRESSES_FLD_FIXES_H //Example //Copy the whole line from the *scom_addresses_fld.H file. Then add FIX in front of REG //and add another paramter that is the new value you want. // //FIXREG64_FLD( PU_ALTD_CMD_REG_FBC_WITH_TM_QUIESCE, 24, SH_UNT, SH_ACS_SCOM, SH_FLD_FBC_WITH_TM_QUIESCE, // 12); static const uint64_t SH_FLD_COMMAND_LIST_TIMEOUT_SPEC = 99990000; REG64_FLD( MCS_MCFIR_COMMAND_LIST_TIMEOUT_SPEC , 9 , SH_UNT_MCS , SH_ACS_SCOM2_OR , SH_FLD_COMMAND_LIST_TIMEOUT_SPEC ); REG64_FLD( MCA_DDRPHY_DP16_SYSCLK_PR0_P0_0_01_ENABLE , 48 , SH_UNT_MCA , SH_ACS_SCOM_RW , 0 ); #endif <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_query_cache_access_state.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_query_cache_access_state.C /// @brief Check the stop level for the EX caches and sets boolean scomable parameters /// // *HWP HWP Owner: Christina Graves <[email protected]> // *HWP Backup HWP Owner: Greg Still <[email protected]> // *HWP FW Owner: Sangeetha T S <[email protected]> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS:SBE /// /// /// /// @verbatim /// High-level procedure flow: /// - For the quad target, read the Stop State History register in the PPM /// and use the actual stop level to determine if the quad has power and is being /// clocked. /// @endverbatim /// //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_quad_scom_addresses.H> #include <p9_query_cache_access_state.H> // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- const uint32_t eq_clk_l2_pos[] = {8, 9}; const uint32_t eq_clk_l3_pos[] = {6, 7}; const uint32_t SSH_REG_STOP_LEVEL = 8; const uint32_t SSH_REG_STOP_LEVEL_LEN = 4; // ---------------------------------------------------------------------- // Procedure Function // ---------------------------------------------------------------------- fapi2::ReturnCode p9_query_cache_access_state( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, bool& o_l2_is_scomable, bool& o_l2_is_scannable, bool& o_l3_is_scomable, bool& o_l3_is_scannable) { fapi2::buffer<uint64_t> l_qsshsrc; uint32_t l_quadStopLevel = 0; fapi2::buffer<uint64_t> l_data64; bool l_is_scomable = 1; uint8_t l_chpltNumber = 0; uint32_t l_exPos = 0; uint8_t l_execution_platform = 0; uint32_t l_stop_state_reg = 0; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_INF("> p9_query_cache_access_state..."); //Get the stop state from the SSHRC in the EQPPM //First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform) FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform), "Error: Failed to get platform"); if (l_execution_platform == 0x02) { l_stop_state_reg = EQ_PPM_SSHFSP; } else { l_stop_state_reg = EQ_PPM_SSHHYP; } FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), "Error reading data from QPPM SSHSRC"); //A unit is scommable if clocks are running //A unit is scannable if the unit is powered up //Extract the core stop state l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN); FAPI_DBG("EQ Stop State: EQ(%d)", l_quadStopLevel); //Set all attribtes to 1, then clear them based on the stop state o_l2_is_scomable = 1; o_l2_is_scannable = 1; o_l3_is_scomable = 1; o_l3_is_scannable = 1; // STOP8 - Half Quad Deep Sleep // VSU, ISU are powered off // IFU, LSU are powered off // PC, Core EPS are powered off // L20-EX0 is clocked off if both cores are >= 8 // L20-EX1 is clocked off if both cores are >= 8 if (l_quadStopLevel >= 8) { o_l2_is_scomable = 0; } // STOP9 - Fast Winkle (lab use only) // Both cores and cache are clocked off if (l_quadStopLevel >= 9) { o_l3_is_scomable = 0; } // STOP11 - Deep Winkle // Both cores and cache are powered off if (l_quadStopLevel >= 11) { o_l2_is_scannable = 0; o_l3_is_scannable = 0; } //Read clock status to confirm stop state history is accurate //If we trust the stop state history, this could be removed to save on code size //Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), "Error reading data from EQ_CLOCK_STAT_SL"); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber), "Error: Failed to get the position of the EX:0x%08X", i_target); l_exPos = l_chpltNumber % 2; l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]); if (o_l2_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l2_is_scomable = l_is_scomable; } l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]); if (o_l3_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l3_is_scomable = l_is_scomable; } fapi_try_exit: FAPI_INF("< p9_query_cache_access_state..."); return fapi2::current_err; } <commit_msg>Skip EQ_CLOCK_STAT_SL scom is we are in stop 11 or greater<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_query_cache_access_state.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_query_cache_access_state.C /// @brief Check the stop level for the EX caches and sets boolean scomable parameters /// // *HWP HWP Owner: Christina Graves <[email protected]> // *HWP Backup HWP Owner: Greg Still <[email protected]> // *HWP FW Owner: Sangeetha T S <[email protected]> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS:SBE /// /// /// /// @verbatim /// High-level procedure flow: /// - For the quad target, read the Stop State History register in the PPM /// and use the actual stop level to determine if the quad has power and is being /// clocked. /// @endverbatim /// //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_quad_scom_addresses.H> #include <p9_query_cache_access_state.H> // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- const uint32_t eq_clk_l2_pos[] = {8, 9}; const uint32_t eq_clk_l3_pos[] = {6, 7}; const uint32_t SSH_REG_STOP_LEVEL = 8; const uint32_t SSH_REG_STOP_LEVEL_LEN = 4; // ---------------------------------------------------------------------- // Procedure Function // ---------------------------------------------------------------------- fapi2::ReturnCode p9_query_cache_access_state( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, bool& o_l2_is_scomable, bool& o_l2_is_scannable, bool& o_l3_is_scomable, bool& o_l3_is_scannable) { fapi2::buffer<uint64_t> l_qsshsrc; uint32_t l_quadStopLevel = 0; fapi2::buffer<uint64_t> l_data64; bool l_is_scomable = 1; uint8_t l_chpltNumber = 0; uint32_t l_exPos = 0; uint8_t l_execution_platform = 0; uint32_t l_stop_state_reg = 0; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_INF("> p9_query_cache_access_state..."); //Get the stop state from the SSHRC in the EQPPM //First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform) FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform), "Error: Failed to get platform"); if (l_execution_platform == 0x02) { l_stop_state_reg = EQ_PPM_SSHFSP; } else { l_stop_state_reg = EQ_PPM_SSHHYP; } FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), "Error reading data from QPPM SSHSRC"); //A unit is scommable if clocks are running //A unit is scannable if the unit is powered up //Extract the core stop state l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN); FAPI_DBG("EQ Stop State: EQ(%d)", l_quadStopLevel); //Set all attribtes to 1, then clear them based on the stop state o_l2_is_scomable = 1; o_l2_is_scannable = 1; o_l3_is_scomable = 1; o_l3_is_scannable = 1; // STOP8 - Half Quad Deep Sleep // VSU, ISU are powered off // IFU, LSU are powered off // PC, Core EPS are powered off // L20-EX0 is clocked off if both cores are >= 8 // L20-EX1 is clocked off if both cores are >= 8 if (l_quadStopLevel >= 8) { o_l2_is_scomable = 0; } // STOP9 - Fast Winkle (lab use only) // Both cores and cache are clocked off if (l_quadStopLevel >= 9) { o_l3_is_scomable = 0; } // STOP11 - Deep Winkle // Both cores and cache are powered off if (l_quadStopLevel >= 11) { o_l2_is_scannable = 0; o_l3_is_scannable = 0; } else { //Read clock status to confirm stop state history is accurate //If we trust the stop state history, this could be removed to save on code size //Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), "Error reading data from EQ_CLOCK_STAT_SL"); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber), "Error: Failed to get the position of the EX:0x%08X", i_target); l_exPos = l_chpltNumber % 2; l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]); if (o_l2_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l2_is_scomable = l_is_scomable; } l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]); if (o_l3_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l3_is_scomable = l_is_scomable; } } fapi_try_exit: FAPI_INF("< p9_query_cache_access_state..."); return fapi2::current_err; } <|endoftext|>
<commit_before>#include "feedcontainer.h" #include <algorithm> // stable_sort #include <numeric> // accumulate #include <unordered_set> #include "rssfeed.h" #include "utils.h" namespace newsboat { void FeedContainer::sort_feeds(const FeedSortStrategy& sort_strategy) { std::lock_guard<std::mutex> feedslock(feeds_mutex); switch (sort_strategy.sm) { case FeedSortMethod::NONE: std::stable_sort( feeds.begin(), feeds.end(), [&](std::shared_ptr<RssFeed> a, std::shared_ptr<RssFeed> b) { bool result = a->get_order() < b->get_order(); if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; }); break; case FeedSortMethod::FIRST_TAG: std::stable_sort( feeds.begin(), feeds.end(), [&](std::shared_ptr<RssFeed> a, std::shared_ptr<RssFeed> b) { if (a->get_firsttag().length() == 0 || b->get_firsttag().length() == 0) { bool result = a->get_firsttag().length() > b->get_firsttag().length(); if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; } const auto left = a->get_firsttag(); const auto right = b->get_firsttag(); bool result = utils::strnaturalcmp(left, right) < 0; if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; }); break; case FeedSortMethod::TITLE: std::stable_sort( feeds.begin(), feeds.end(), [&](std::shared_ptr<RssFeed> a, std::shared_ptr<RssFeed> b) { const auto left = a->title(); const auto right = b->title(); bool result = utils::strnaturalcmp(left, right) < 0; if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; }); break; case FeedSortMethod::ARTICLE_COUNT: std::stable_sort( feeds.begin(), feeds.end(), [&](std::shared_ptr<RssFeed> a, std::shared_ptr<RssFeed> b) { bool result = a->total_item_count() < b->total_item_count(); if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; }); break; case FeedSortMethod::UNREAD_ARTICLE_COUNT: std::stable_sort( feeds.begin(), feeds.end(), [&](std::shared_ptr<RssFeed> a, std::shared_ptr<RssFeed> b) { int diff = a->unread_item_count() - b->unread_item_count(); bool result = false; if (diff != 0) { if (sort_strategy.sd == SortDirection::DESC) { diff *= -1; } result = diff > 0; } return result; }); break; case FeedSortMethod::LAST_UPDATED: std::stable_sort( feeds.begin(), feeds.end(), [&](std::shared_ptr<RssFeed> a, std::shared_ptr<RssFeed> b) { if (a->items().size() == 0 || b->items().size() == 0) { bool result = a->items().size() > b->items().size(); if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; } auto cmp = [](std::shared_ptr<RssItem> a, std::shared_ptr<RssItem> b) { return *a < *b; }; auto& a_item = *std::min_element(a->items().begin(), a->items().end(), cmp); auto& b_item = *std::min_element(b->items().begin(), b->items().end(), cmp); bool result = cmp(a_item, b_item); if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; }); break; } } std::shared_ptr<RssFeed> FeedContainer::get_feed(const unsigned int pos) { std::lock_guard<std::mutex> feedslock(feeds_mutex); if (pos < feeds.size()) { return feeds[pos]; } return nullptr; } void FeedContainer::mark_all_feed_items_read(std::shared_ptr<RssFeed> feed) { std::lock_guard<std::mutex> lock(feed->item_mutex); std::vector<std::shared_ptr<RssItem>>& items = feed->items(); if (items.size() > 0) { bool notify = items[0]->feedurl() != feed->rssurl(); LOG(Level::DEBUG, "FeedContainer::mark_all_read: notify = %s", notify ? "yes" : "no"); for (const auto& item : items) { item->set_unread_nowrite_notify(false, notify); } } } void FeedContainer::mark_all_feeds_read() { std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { feed->mark_all_items_read(); } } void FeedContainer::add_feed(const std::shared_ptr<RssFeed> feed) { std::lock_guard<std::mutex> feedslock(feeds_mutex); feeds.push_back(feed); } void FeedContainer::populate_query_feeds() { std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { if (feed->is_query_feed()) { feed->update_items(feeds); } } } unsigned int FeedContainer::get_feed_count_per_tag(const std::string& tag) { unsigned int count = 0; std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { if (feed->matches_tag(tag)) { count++; } } return count; } unsigned int FeedContainer::get_unread_feed_count_per_tag( const std::string& tag) { unsigned int count = 0; std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { if (feed->matches_tag(tag) && feed->unread_item_count() > 0) { count++; } } return count; } unsigned int FeedContainer::get_unread_item_count_per_tag( const std::string& tag) { unsigned int count = 0; std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { if (feed->matches_tag(tag)) { count += feed->unread_item_count(); } } return count; } std::shared_ptr<RssFeed> FeedContainer::get_feed_by_url( const std::string& feedurl) { std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { if (feedurl == feed->rssurl()) { return feed; } } LOG(Level::ERROR, "FeedContainer:get_feed_by_url failed for %s", feedurl); return std::shared_ptr<RssFeed>(); } unsigned int FeedContainer::get_pos_of_next_unread(unsigned int pos) { std::lock_guard<std::mutex> feedslock(feeds_mutex); for (pos++; pos < feeds.size(); pos++) { if (feeds[pos]->unread_item_count() > 0) { break; } } return pos; } unsigned int FeedContainer::feeds_size() { std::lock_guard<std::mutex> feedslock(feeds_mutex); return feeds.size(); } void FeedContainer::reset_feeds_status() { std::lock_guard<std::mutex> feedlock(feeds_mutex); for (const auto& feed : feeds) { feed->reset_status(); } } void FeedContainer::set_feeds( const std::vector<std::shared_ptr<RssFeed>> new_feeds) { std::lock_guard<std::mutex> feedslock(feeds_mutex); feeds = new_feeds; } std::vector<std::shared_ptr<RssFeed>> FeedContainer::get_all_feeds() const { std::lock_guard<std::mutex> feedslock(feeds_mutex); return feeds; } unsigned int FeedContainer::unread_feed_count() const { std::lock_guard<std::mutex> feedslock(feeds_mutex); return std::count_if(feeds.begin(), feeds.end(), [](const std::shared_ptr<RssFeed> feed) { return feed->unread_item_count() > 0; }); } unsigned int FeedContainer::unread_item_count() const { std::lock_guard<std::mutex> feedslock(feeds_mutex); using guid_set = std::unordered_set<std::string>; const auto unread_guids = std::accumulate(feeds.begin(), feeds.end(), guid_set(), [](guid_set guids, const std::shared_ptr<RssFeed> feed) { // Hidden feeds can't be viewed. The only way to read their articles is // via a query feed; items that aren't in query feeds are completely // inaccessible. Thus, we skip hidden feeds altogether to avoid // counting items that can't be accessed. if (feed->hidden()) { return guids; } std::lock_guard<std::mutex> itemslock(feed->item_mutex); for (const auto& item : feed->items()) { if (item->unread()) { guids.insert(item->guid()); } } return guids; }); return unread_guids.size(); } void FeedContainer::replace_feed(unsigned int pos, std::shared_ptr<RssFeed> feed) { std::lock_guard<std::mutex> feedslock(feeds_mutex); assert(pos < feeds.size()); feeds[pos] = feed; } } // namespace newsboat <commit_msg>simplify comparison for unread articles<commit_after>#include "feedcontainer.h" #include <algorithm> // stable_sort #include <numeric> // accumulate #include <unordered_set> #include "rssfeed.h" #include "utils.h" namespace newsboat { void FeedContainer::sort_feeds(const FeedSortStrategy& sort_strategy) { std::lock_guard<std::mutex> feedslock(feeds_mutex); switch (sort_strategy.sm) { case FeedSortMethod::NONE: std::stable_sort( feeds.begin(), feeds.end(), [&](std::shared_ptr<RssFeed> a, std::shared_ptr<RssFeed> b) { bool result = a->get_order() < b->get_order(); if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; }); break; case FeedSortMethod::FIRST_TAG: std::stable_sort( feeds.begin(), feeds.end(), [&](std::shared_ptr<RssFeed> a, std::shared_ptr<RssFeed> b) { if (a->get_firsttag().length() == 0 || b->get_firsttag().length() == 0) { bool result = a->get_firsttag().length() > b->get_firsttag().length(); if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; } const auto left = a->get_firsttag(); const auto right = b->get_firsttag(); bool result = utils::strnaturalcmp(left, right) < 0; if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; }); break; case FeedSortMethod::TITLE: std::stable_sort( feeds.begin(), feeds.end(), [&](std::shared_ptr<RssFeed> a, std::shared_ptr<RssFeed> b) { const auto left = a->title(); const auto right = b->title(); bool result = utils::strnaturalcmp(left, right) < 0; if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; }); break; case FeedSortMethod::ARTICLE_COUNT: std::stable_sort( feeds.begin(), feeds.end(), [&](std::shared_ptr<RssFeed> a, std::shared_ptr<RssFeed> b) { bool result = a->total_item_count() < b->total_item_count(); if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; }); break; case FeedSortMethod::UNREAD_ARTICLE_COUNT: std::stable_sort( feeds.begin(), feeds.end(), [&](std::shared_ptr<RssFeed> a, std::shared_ptr<RssFeed> b) { if (sort_strategy.sd == SortDirection::DESC) { return a->unread_item_count() < b->unread_item_count(); } else { return a->unread_item_count() > b->unread_item_count(); } }); break; case FeedSortMethod::LAST_UPDATED: std::stable_sort( feeds.begin(), feeds.end(), [&](std::shared_ptr<RssFeed> a, std::shared_ptr<RssFeed> b) { if (a->items().size() == 0 || b->items().size() == 0) { bool result = a->items().size() > b->items().size(); if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; } auto cmp = [](std::shared_ptr<RssItem> a, std::shared_ptr<RssItem> b) { return *a < *b; }; auto& a_item = *std::min_element(a->items().begin(), a->items().end(), cmp); auto& b_item = *std::min_element(b->items().begin(), b->items().end(), cmp); bool result = cmp(a_item, b_item); if (sort_strategy.sd == SortDirection::ASC) { result = !result; } return result; }); break; } } std::shared_ptr<RssFeed> FeedContainer::get_feed(const unsigned int pos) { std::lock_guard<std::mutex> feedslock(feeds_mutex); if (pos < feeds.size()) { return feeds[pos]; } return nullptr; } void FeedContainer::mark_all_feed_items_read(std::shared_ptr<RssFeed> feed) { std::lock_guard<std::mutex> lock(feed->item_mutex); std::vector<std::shared_ptr<RssItem>>& items = feed->items(); if (items.size() > 0) { bool notify = items[0]->feedurl() != feed->rssurl(); LOG(Level::DEBUG, "FeedContainer::mark_all_read: notify = %s", notify ? "yes" : "no"); for (const auto& item : items) { item->set_unread_nowrite_notify(false, notify); } } } void FeedContainer::mark_all_feeds_read() { std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { feed->mark_all_items_read(); } } void FeedContainer::add_feed(const std::shared_ptr<RssFeed> feed) { std::lock_guard<std::mutex> feedslock(feeds_mutex); feeds.push_back(feed); } void FeedContainer::populate_query_feeds() { std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { if (feed->is_query_feed()) { feed->update_items(feeds); } } } unsigned int FeedContainer::get_feed_count_per_tag(const std::string& tag) { unsigned int count = 0; std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { if (feed->matches_tag(tag)) { count++; } } return count; } unsigned int FeedContainer::get_unread_feed_count_per_tag( const std::string& tag) { unsigned int count = 0; std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { if (feed->matches_tag(tag) && feed->unread_item_count() > 0) { count++; } } return count; } unsigned int FeedContainer::get_unread_item_count_per_tag( const std::string& tag) { unsigned int count = 0; std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { if (feed->matches_tag(tag)) { count += feed->unread_item_count(); } } return count; } std::shared_ptr<RssFeed> FeedContainer::get_feed_by_url( const std::string& feedurl) { std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { if (feedurl == feed->rssurl()) { return feed; } } LOG(Level::ERROR, "FeedContainer:get_feed_by_url failed for %s", feedurl); return std::shared_ptr<RssFeed>(); } unsigned int FeedContainer::get_pos_of_next_unread(unsigned int pos) { std::lock_guard<std::mutex> feedslock(feeds_mutex); for (pos++; pos < feeds.size(); pos++) { if (feeds[pos]->unread_item_count() > 0) { break; } } return pos; } unsigned int FeedContainer::feeds_size() { std::lock_guard<std::mutex> feedslock(feeds_mutex); return feeds.size(); } void FeedContainer::reset_feeds_status() { std::lock_guard<std::mutex> feedlock(feeds_mutex); for (const auto& feed : feeds) { feed->reset_status(); } } void FeedContainer::set_feeds( const std::vector<std::shared_ptr<RssFeed>> new_feeds) { std::lock_guard<std::mutex> feedslock(feeds_mutex); feeds = new_feeds; } std::vector<std::shared_ptr<RssFeed>> FeedContainer::get_all_feeds() const { std::lock_guard<std::mutex> feedslock(feeds_mutex); return feeds; } unsigned int FeedContainer::unread_feed_count() const { std::lock_guard<std::mutex> feedslock(feeds_mutex); return std::count_if(feeds.begin(), feeds.end(), [](const std::shared_ptr<RssFeed> feed) { return feed->unread_item_count() > 0; }); } unsigned int FeedContainer::unread_item_count() const { std::lock_guard<std::mutex> feedslock(feeds_mutex); using guid_set = std::unordered_set<std::string>; const auto unread_guids = std::accumulate(feeds.begin(), feeds.end(), guid_set(), [](guid_set guids, const std::shared_ptr<RssFeed> feed) { // Hidden feeds can't be viewed. The only way to read their articles is // via a query feed; items that aren't in query feeds are completely // inaccessible. Thus, we skip hidden feeds altogether to avoid // counting items that can't be accessed. if (feed->hidden()) { return guids; } std::lock_guard<std::mutex> itemslock(feed->item_mutex); for (const auto& item : feed->items()) { if (item->unread()) { guids.insert(item->guid()); } } return guids; }); return unread_guids.size(); } void FeedContainer::replace_feed(unsigned int pos, std::shared_ptr<RssFeed> feed) { std::lock_guard<std::mutex> feedslock(feeds_mutex); assert(pos < feeds.size()); feeds[pos] = feed; } } // namespace newsboat <|endoftext|>
<commit_before> /************************************************************************* * * $RCSfile: filinpstr.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-11-17 09:55:57 $ * * 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): _______________________________________ * * ************************************************************************/ #ifndef _FILINPSTR_HXX_ #define _FILINPSTR_HXX_ #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _UCBHELPER_MACROS_HXX #include <ucbhelper/macros.hxx> #endif #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_ #include <com/sun/star/io/XSeekable.hpp> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_ #include <com/sun/star/ucb/XContentProvider.hpp> #endif namespace fileaccess { // forward declaration class shell; class XInputStream_impl : public cppu::OWeakObject, public com::sun::star::lang::XTypeProvider, public com::sun::star::lang::XServiceInfo, public com::sun::star::io::XInputStream, public com::sun::star::io::XSeekable { public: XInputStream_impl( shell* pMyShell,const rtl::OUString& aUncPath ); virtual ~XInputStream_impl(); /** * Returns an error code as given by filerror.hxx */ sal_Int32 SAL_CALL CtorSuccess(); sal_Int32 SAL_CALL getMinorError(); // XTypeProvider XTYPEPROVIDER_DECL() // XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName ) throw( com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type& rType ) throw( com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( void ) throw(); virtual void SAL_CALL release( void ) throw(); virtual sal_Int32 SAL_CALL readBytes( com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL readSomeBytes( com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException); virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL available( void ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL closeInput( void ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL seek( sal_Int64 location ) throw( com::sun::star::lang::IllegalArgumentException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual sal_Int64 SAL_CALL getPosition( void ) throw( com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual sal_Int64 SAL_CALL getLength( void ) throw( com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); private: shell* m_pMyShell; com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider > m_xProvider; sal_Bool m_nIsOpen; osl::File m_aFile; sal_Int32 m_nErrorCode; sal_Int32 m_nMinorErrorCode; }; } // end namespace XInputStream_impl #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.4.52); FILE MERGED 2005/09/05 18:45:01 rt 1.4.52.1: #i54170# Change license header: remove SISSL<commit_after> /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: filinpstr.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:25:07 $ * * 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 _FILINPSTR_HXX_ #define _FILINPSTR_HXX_ #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _UCBHELPER_MACROS_HXX #include <ucbhelper/macros.hxx> #endif #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_ #include <com/sun/star/io/XSeekable.hpp> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_ #include <com/sun/star/ucb/XContentProvider.hpp> #endif namespace fileaccess { // forward declaration class shell; class XInputStream_impl : public cppu::OWeakObject, public com::sun::star::lang::XTypeProvider, public com::sun::star::lang::XServiceInfo, public com::sun::star::io::XInputStream, public com::sun::star::io::XSeekable { public: XInputStream_impl( shell* pMyShell,const rtl::OUString& aUncPath ); virtual ~XInputStream_impl(); /** * Returns an error code as given by filerror.hxx */ sal_Int32 SAL_CALL CtorSuccess(); sal_Int32 SAL_CALL getMinorError(); // XTypeProvider XTYPEPROVIDER_DECL() // XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName ) throw( com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type& rType ) throw( com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( void ) throw(); virtual void SAL_CALL release( void ) throw(); virtual sal_Int32 SAL_CALL readBytes( com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL readSomeBytes( com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException); virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL available( void ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL closeInput( void ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL seek( sal_Int64 location ) throw( com::sun::star::lang::IllegalArgumentException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual sal_Int64 SAL_CALL getPosition( void ) throw( com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual sal_Int64 SAL_CALL getLength( void ) throw( com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); private: shell* m_pMyShell; com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider > m_xProvider; sal_Bool m_nIsOpen; osl::File m_aFile; sal_Int32 m_nErrorCode; sal_Int32 m_nMinorErrorCode; }; } // end namespace XInputStream_impl #endif <|endoftext|>
<commit_before>/* -*- mode:linux -*- */ /** * \file closed_list.cc * * * * \author Ethan Burns * \date 2008-10-09 */ #include <map> #include "state.h" #include "closed_list.h" void ClosedList::add(const State *s) { m[s->hash()] = s; } const State *ClosedList::lookup(const State *c) const { // this is stupid: apparently you can't do an assignment with // iterators, so instead we need to do two lookups. if (m.find(c->hash()) == m.end()) return NULL; return m.find(c->hash())->second; } /** * Delete (free up the memory for) all states in the closed list. */ void ClosedList::delete_all_states(void) { map<int, const State *>::iterator iter; for (iter = m.begin(); iter != m.end(); iter++) delete iter->second; } <commit_msg>Use a const_iterator in ClosedList::lookup.<commit_after>/* -*- mode:linux -*- */ /** * \file closed_list.cc * * * * \author Ethan Burns * \date 2008-10-09 */ #include <map> #include "state.h" #include "closed_list.h" void ClosedList::add(const State *s) { m[s->hash()] = s; } const State *ClosedList::lookup(const State *c) const { map<int, const State *>::const_iterator iter; iter = m.find(c->hash()); if (iter == m.end()) return NULL; return iter->second; } /** * Delete (free up the memory for) all states in the closed list. */ void ClosedList::delete_all_states(void) { map<int, const State *>::iterator iter; for (iter = m.begin(); iter != m.end(); iter++) delete iter->second; } <|endoftext|>
<commit_before>/* medViewContainerMulti.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Wed Mar 17 11:01:46 2010 (+0100) * Version: $Id$ * Last-Updated: Mon Dec 20 11:26:25 2010 (+0100) * By: Julien Wintz * Update #: 56 */ /* Commentary: * */ /* Change log: * */ #include "medViewContainer_p.h" #include "medViewContainerMulti.h" #include "medViewPool.h" #include <dtkCore/dtkAbstractView.h> #include <medCore/medAbstractView.h> #include <medCore/medViewManager.h> medViewContainerSingle2::~medViewContainerSingle2() { } void medViewContainerSingle2::setView (dtkAbstractView *view) { d->layout->setContentsMargins(1, 1, 1, 1); d->layout->addWidget(view->widget(), 0, 0); d->view = view; // d->pool->appendView (view); // only difference with medViewContainerSingle: do not add the view to the pool connect (view, SIGNAL (closing()), this, SLOT (onViewClosing())); } void medViewContainerSingle2::onViewClosing (void) { if (d->view) { d->layout->removeWidget(d->view->widget()); d->view->widget()->hide(); disconnect (d->view, SIGNAL (closing()), this, SLOT (onViewClosing())); // d->pool->removeView (d->view); // do not remove it from the pool d->view = NULL; } } class medViewContainerMultiPrivate { public: QList<dtkAbstractView *> views; }; medViewContainerMulti::medViewContainerMulti (QWidget *parent) : medViewContainer (parent), d2 (new medViewContainerMultiPrivate) { } medViewContainerMulti::~medViewContainerMulti() { medViewContainer::setView(0); delete d2; d2 = NULL; } void medViewContainerMulti::split(int rows, int cols) { Q_UNUSED(rows); Q_UNUSED(cols); // Don't split a multi view container return; } dtkAbstractView *medViewContainerMulti::view(void) const { return NULL; } QList<dtkAbstractView*> medViewContainerMulti::views (void) const { return d2->views; } void medViewContainerMulti::setView(dtkAbstractView *view) { if (!view) return; if (d2->views.contains (view)) return; QList<QWidget *> content; for(int i = 0; i < d->layout->rowCount() ; i++) { for(int j = 0; j < d->layout->columnCount() ; j++) { if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) { content << item->widget(); d->layout->removeItem(item); } } } medViewContainer *container = new medViewContainerSingle2(this); container->setAcceptDrops(false); container->setView(view); content << container; this->layout(content); medViewContainer::setView (view); d2->views << view; // d->view = view; // set in medViewContainer::setView(view) // d->view->reset(); if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view)) d->pool->appendView (medView); connect (view, SIGNAL (closing()), this, SLOT (onViewClosing())); connect (view, SIGNAL (becomeDaddy(bool)), this, SLOT (repaint())); connect (view, SIGNAL (fullScreen(bool)), this, SLOT (onViewFullScreen(bool))); this->setCurrent( container ); emit viewAdded (view); } void medViewContainerMulti::layout(QList<QWidget *> content) { int row = 0; int col = 0, colmax = 0; for(int i = 0; i < content.count()-1; i++) { if(((col+1)*(row+1)) <= content.count()-1) { qreal rratio = qMin(((qreal)this->height()/(qreal)(row+2)), ((qreal)this->width()/(qreal)(col+1))); qreal cratio = qMin(((qreal)this->height()/(qreal)(row+1)), ((qreal)this->width()/(qreal)(col+2))); if(rratio > cratio) { row++; col = 0; } else { col++; } colmax = qMax(col, colmax); } } int layout_row = 0; int layout_col = 0; for(int i = 0; i < content.size(); i++) { d->layout->addWidget(content.at(i), layout_row, layout_col); if(layout_col == colmax) { layout_row++; layout_col = 0; } else { layout_col++; } } d->layout->setContentsMargins(1, 1, 1, 1); } void medViewContainerMulti::onViewClosing (void) { if (dtkAbstractView *view = dynamic_cast<dtkAbstractView *>(this->sender())) { QList<QWidget *> content; for(int i = 0; i < d->layout->rowCount() ; i++) { for(int j = 0; j < d->layout->columnCount() ; j++) { if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) { if(item->widget()!=view->widget()->parent()) { content << item->widget(); item->widget()->show(); // in case view was hidden } else { item->widget()->hide(); } d->layout->removeItem(item); } } } disconnect (view, SIGNAL (closing()), this, SLOT (onViewClosing())); disconnect (view, SIGNAL (becomeDaddy(bool)), this, SLOT (repaint())); disconnect (view, SIGNAL (fullScreen(bool)), this, SLOT (onViewFullScreen(bool))); if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view)) d->pool->removeView (medView); d2->views.removeOne (view); emit viewRemoved (view); view->close(); this->layout (content); } } void medViewContainerMulti::onViewFullScreen (bool value) { if (dtkAbstractView *view = dynamic_cast<dtkAbstractView *>(this->sender())) { if (value) { QList<QWidget *> content; for(int i = 0; i < d->layout->rowCount() ; i++) { for(int j = 0; j < d->layout->columnCount() ; j++) { if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) { if(item->widget()!=view->widget()->parent()) item->widget()->hide(); } } } } else { QList<QWidget *> content; for(int i = 0; i < d->layout->rowCount() ; i++) { for(int j = 0; j < d->layout->columnCount() ; j++) { if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) { if(item->widget()!=view->widget()->parent()) item->widget()->show(); } } } } } } void medViewContainerMulti::dragEnterEvent(QDragEnterEvent *event) { medViewContainer::dragEnterEvent(event); } void medViewContainerMulti::dragMoveEvent(QDragMoveEvent *event) { medViewContainer::dragMoveEvent(event); } void medViewContainerMulti::dragLeaveEvent(QDragLeaveEvent *event) { medViewContainer::dragLeaveEvent(event); } void medViewContainerMulti::dropEvent(QDropEvent *event) { if(medViewContainerMulti *container = dynamic_cast<medViewContainerMulti *>(this->parentWidget())) { this->setCurrent(container); } else { this->setCurrent(this); } medViewContainer::dropEvent(event); } void medViewContainerMulti::focusInEvent(QFocusEvent *event) { Q_UNUSED(event); } void medViewContainerMulti::focusOutEvent(QFocusEvent *event) { Q_UNUSED(event); } <commit_msg>select another view container when closing one in multi view<commit_after>/* medViewContainerMulti.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Wed Mar 17 11:01:46 2010 (+0100) * Version: $Id$ * Last-Updated: Mon Dec 20 11:26:25 2010 (+0100) * By: Julien Wintz * Update #: 56 */ /* Commentary: * */ /* Change log: * */ #include "medViewContainer_p.h" #include "medViewContainerMulti.h" #include "medViewPool.h" #include <dtkCore/dtkAbstractView.h> #include <medCore/medAbstractView.h> #include <medCore/medViewManager.h> medViewContainerSingle2::~medViewContainerSingle2() { } void medViewContainerSingle2::setView (dtkAbstractView *view) { d->layout->setContentsMargins(1, 1, 1, 1); d->layout->addWidget(view->widget(), 0, 0); d->view = view; // d->pool->appendView (view); // only difference with medViewContainerSingle: do not add the view to the pool connect (view, SIGNAL (closing()), this, SLOT (onViewClosing())); } void medViewContainerSingle2::onViewClosing (void) { if (d->view) { d->layout->removeWidget(d->view->widget()); d->view->widget()->hide(); disconnect (d->view, SIGNAL (closing()), this, SLOT (onViewClosing())); // d->pool->removeView (d->view); // do not remove it from the pool d->view = NULL; } } class medViewContainerMultiPrivate { public: QList<dtkAbstractView *> views; }; medViewContainerMulti::medViewContainerMulti (QWidget *parent) : medViewContainer (parent), d2 (new medViewContainerMultiPrivate) { } medViewContainerMulti::~medViewContainerMulti() { medViewContainer::setView(0); delete d2; d2 = NULL; } void medViewContainerMulti::split(int rows, int cols) { Q_UNUSED(rows); Q_UNUSED(cols); // Don't split a multi view container return; } dtkAbstractView *medViewContainerMulti::view(void) const { return NULL; } QList<dtkAbstractView*> medViewContainerMulti::views (void) const { return d2->views; } void medViewContainerMulti::setView(dtkAbstractView *view) { if (!view) return; if (d2->views.contains (view)) return; QList<QWidget *> content; for(int i = 0; i < d->layout->rowCount() ; i++) { for(int j = 0; j < d->layout->columnCount() ; j++) { if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) { content << item->widget(); d->layout->removeItem(item); } } } medViewContainer *container = new medViewContainerSingle2(this); container->setAcceptDrops(false); container->setView(view); content << container; this->layout(content); medViewContainer::setView (view); d2->views << view; // d->view = view; // set in medViewContainer::setView(view) // d->view->reset(); if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view)) d->pool->appendView (medView); connect (view, SIGNAL (closing()), this, SLOT (onViewClosing())); connect (view, SIGNAL (becomeDaddy(bool)), this, SLOT (repaint())); connect (view, SIGNAL (fullScreen(bool)), this, SLOT (onViewFullScreen(bool))); this->setCurrent( container ); emit viewAdded (view); } void medViewContainerMulti::layout(QList<QWidget *> content) { int row = 0; int col = 0, colmax = 0; for(int i = 0; i < content.count()-1; i++) { if(((col+1)*(row+1)) <= content.count()-1) { qreal rratio = qMin(((qreal)this->height()/(qreal)(row+2)), ((qreal)this->width()/(qreal)(col+1))); qreal cratio = qMin(((qreal)this->height()/(qreal)(row+1)), ((qreal)this->width()/(qreal)(col+2))); if(rratio > cratio) { row++; col = 0; } else { col++; } colmax = qMax(col, colmax); } } int layout_row = 0; int layout_col = 0; for(int i = 0; i < content.size(); i++) { d->layout->addWidget(content.at(i), layout_row, layout_col); if(layout_col == colmax) { layout_row++; layout_col = 0; } else { layout_col++; } } d->layout->setContentsMargins(1, 1, 1, 1); } void medViewContainerMulti::onViewClosing (void) { if (dtkAbstractView *view = dynamic_cast<dtkAbstractView *>(this->sender())) { // needed for selecting another container as current afterwards QWidget * predContainer = NULL; QWidget * succContainer = NULL; bool closedItemFound = false; QWidget * closedContainer = dynamic_cast< QWidget * >( view->widget()->parent() ); QList<QWidget *> content; for (int i = 0; i < d->layout->rowCount(); i++) { for (int j = 0; j < d->layout->columnCount(); j++) { QLayoutItem * item = d->layout->itemAtPosition(i, j); if ( item != NULL ) { QWidget * container = item->widget(); if ( container != closedContainer ) { content << container; container->show(); // in case view was hidden // remember the predecessor resp. successor of // the closed container if ( closedItemFound ) { if ( succContainer == NULL ) succContainer = container; } else predContainer = container; } else { container->hide(); closedItemFound = true; } d->layout->removeItem(item); } } } disconnect (view, SIGNAL (closing()), this, SLOT (onViewClosing())); disconnect (view, SIGNAL (becomeDaddy(bool)), this, SLOT (repaint())); disconnect (view, SIGNAL (fullScreen(bool)), this, SLOT (onViewFullScreen(bool))); if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view)) d->pool->removeView (medView); d2->views.removeOne (view); emit viewRemoved (view); view->close(); this->layout (content); medViewContainer * current = dynamic_cast< medViewContainer * >( succContainer ); if ( current == NULL ) current = dynamic_cast< medViewContainer * >( predContainer ); if ( current != NULL ) this->setCurrent( current ); else this->setCurrent( this ); this->update(); } } void medViewContainerMulti::onViewFullScreen (bool value) { if (dtkAbstractView *view = dynamic_cast<dtkAbstractView *>(this->sender())) { if (value) { QList<QWidget *> content; for(int i = 0; i < d->layout->rowCount() ; i++) { for(int j = 0; j < d->layout->columnCount() ; j++) { if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) { if(item->widget()!=view->widget()->parent()) item->widget()->hide(); } } } } else { QList<QWidget *> content; for(int i = 0; i < d->layout->rowCount() ; i++) { for(int j = 0; j < d->layout->columnCount() ; j++) { if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) { if(item->widget()!=view->widget()->parent()) item->widget()->show(); } } } } } } void medViewContainerMulti::dragEnterEvent(QDragEnterEvent *event) { medViewContainer::dragEnterEvent(event); } void medViewContainerMulti::dragMoveEvent(QDragMoveEvent *event) { medViewContainer::dragMoveEvent(event); } void medViewContainerMulti::dragLeaveEvent(QDragLeaveEvent *event) { medViewContainer::dragLeaveEvent(event); } void medViewContainerMulti::dropEvent(QDropEvent *event) { if(medViewContainerMulti *container = dynamic_cast<medViewContainerMulti *>(this->parentWidget())) { this->setCurrent(container); } else { this->setCurrent(this); } medViewContainer::dropEvent(event); } void medViewContainerMulti::focusInEvent(QFocusEvent *event) { Q_UNUSED(event); } void medViewContainerMulti::focusOutEvent(QFocusEvent *event) { Q_UNUSED(event); } <|endoftext|>
<commit_before>// $Id: mesh_refinement_smoothing.C,v 1.13 2006-04-18 03:44:23 roystgnr Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "libmesh_config.h" // only compile these functions if the user requests AMR support #ifdef ENABLE_AMR #include "mesh_refinement.h" #include "mesh_base.h" #include "elem.h" //----------------------------------------------------------------- // Mesh refinement methods bool MeshRefinement::limit_level_mismatch_at_node (const unsigned int max_mismatch) { bool flags_changed = false; // Vector holding the maximum element level that touches a node. std::vector<unsigned char> max_level_at_node (_mesh.n_nodes(), 0); std::vector<unsigned char> max_p_level_at_node (_mesh.n_nodes(), 0); // Loop over all the active elements & fill the vector { // const_active_elem_iterator elem_it (_mesh.const_elements_begin()); // const const_active_elem_iterator elem_end(_mesh.const_elements_end()); MeshBase::element_iterator elem_it = _mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { const Elem* elem = *elem_it; const unsigned char elem_level = elem->level() + ((elem->refinement_flag() == Elem::REFINE) ? 1 : 0); const unsigned char elem_p_level = elem->p_level() + ((elem->p_refinement_flag() == Elem::REFINE) ? 1 : 0); // Set the max_level at each node for (unsigned int n=0; n<elem->n_nodes(); n++) { const unsigned int node_number = elem->node(n); assert (node_number < max_level_at_node.size()); max_level_at_node[node_number] = std::max (max_level_at_node[node_number], elem_level); max_p_level_at_node[node_number] = std::max (max_p_level_at_node[node_number], elem_p_level); } } } // Now loop over the active elements and flag the elements // who violate the requested level mismatch { // active_elem_iterator elem_it (_mesh.elements_begin()); // const active_elem_iterator elem_end(_mesh.elements_end()); MeshBase::element_iterator elem_it = _mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { Elem* elem = *elem_it; const unsigned int elem_level = elem->level(); const unsigned int elem_p_level = elem->p_level(); // Skip the element if it is already fully flagged if (elem->refinement_flag() == Elem::REFINE && elem->p_refinement_flag() == Elem::REFINE) continue; // Loop over the nodes, check for possible mismatch for (unsigned int n=0; n<elem->n_nodes(); n++) { const unsigned int node_number = elem->node(n); // Flag the element for refinement if it violates // the requested level mismatch if ( (elem_level + max_mismatch) < max_level_at_node[node_number] && elem->refinement_flag() != Elem::REFINE) { elem->set_refinement_flag (Elem::REFINE); flags_changed = true; } if ( (elem_p_level + max_mismatch) < max_p_level_at_node[node_number] && elem->p_refinement_flag() != Elem::REFINE) { elem->set_p_refinement_flag (Elem::REFINE); flags_changed = true; } } } } return flags_changed; } bool MeshRefinement::eliminate_unrefined_patches () { bool flags_changed = false; // active_elem_iterator elem_it (_mesh.elements_begin()); // const active_elem_iterator elem_end(_mesh.elements_end()); MeshBase::element_iterator elem_it = _mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { Elem* elem = *elem_it; bool h_flag_me = true, p_flag_me = true; // Skip the element if it is already fully flagged for refinement if (elem->p_refinement_flag() == Elem::REFINE) p_flag_me = false; if (elem->refinement_flag() == Elem::REFINE) { h_flag_me = false; if (!p_flag_me) continue; } // Test the parent if that is already flagged for coarsening else if (elem->refinement_flag() == Elem::COARSEN) { assert(elem->parent()); elem = elem->parent(); // FIXME - this doesn't seem right - RHS if (elem->refinement_flag() != Elem::COARSEN_INACTIVE) continue; p_flag_me = false; } const unsigned int my_level = elem->level(); int my_p_adjustment = 0; if (elem->p_refinement_flag() == Elem::REFINE) my_p_adjustment = 1; else if (elem->p_refinement_flag() == Elem::COARSEN) { assert(elem->p_level() > 0); my_p_adjustment = -1; } const unsigned int my_new_p_level = elem->p_level() + my_p_adjustment; // Check all the element neighbors for (unsigned int n=0; n<elem->n_neighbors(); n++) { const Elem *neighbor = elem->neighbor(n); // Quit if the element is on the boundary if (neighbor == NULL) { h_flag_me = false; p_flag_me = false; break; } // if the neighbor will be equally or less refined // than we are, then we do not need to h refine ourselves. if (h_flag_me && (neighbor->level() < my_level) || ((neighbor->active()) && (neighbor->refinement_flag() != Elem::REFINE)) || (neighbor->refinement_flag() == Elem::COARSEN_INACTIVE)) { h_flag_me = false; if (!p_flag_me) break; } if (p_flag_me) { // if active neighbors will have a p level // equal to or lower than ours, then we do not need to p refine // ourselves. if (neighbor->active()) { int p_adjustment = 0; if (neighbor->p_refinement_flag() == Elem::REFINE) p_adjustment = 1; else if (neighbor->p_refinement_flag() == Elem::COARSEN) { assert(neighbor->p_level() > 0); p_adjustment = -1; } if (my_new_p_level >= neighbor->p_level() + p_adjustment) { p_flag_me = false; if (!h_flag_me) break; } } // If we have inactive neighbors, we need to // test all their active descendants which neighbor us else { if (neighbor->min_new_p_level_by_neighbor(elem, my_new_p_level + 2) <= my_new_p_level) { p_flag_me = false; if (!h_flag_me) break; } } } } if (h_flag_me) { // Parents that would create islands should no longer // coarsen if (elem->refinement_flag() == Elem::COARSEN_INACTIVE) { for (unsigned int c=0; c<elem->n_children(); c++) { assert(elem->child(c)->refinement_flag() == Elem::COARSEN); elem->child(c)->set_refinement_flag(Elem::DO_NOTHING); } elem->set_refinement_flag(Elem::INACTIVE); } else elem->set_refinement_flag(Elem::REFINE); flags_changed = true; } if (p_flag_me) { elem->set_p_refinement_flag(Elem::REFINE); flags_changed = true; } } return flags_changed; } #endif <commit_msg>Fix "go directly from coarsening to refinement" bug<commit_after>// $Id: mesh_refinement_smoothing.C,v 1.14 2006-05-24 20:34:45 roystgnr Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "libmesh_config.h" // only compile these functions if the user requests AMR support #ifdef ENABLE_AMR #include "mesh_refinement.h" #include "mesh_base.h" #include "elem.h" //----------------------------------------------------------------- // Mesh refinement methods bool MeshRefinement::limit_level_mismatch_at_node (const unsigned int max_mismatch) { bool flags_changed = false; // Vector holding the maximum element level that touches a node. std::vector<unsigned char> max_level_at_node (_mesh.n_nodes(), 0); std::vector<unsigned char> max_p_level_at_node (_mesh.n_nodes(), 0); // Loop over all the active elements & fill the vector { // const_active_elem_iterator elem_it (_mesh.const_elements_begin()); // const const_active_elem_iterator elem_end(_mesh.const_elements_end()); MeshBase::element_iterator elem_it = _mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { const Elem* elem = *elem_it; const unsigned char elem_level = elem->level() + ((elem->refinement_flag() == Elem::REFINE) ? 1 : 0); const unsigned char elem_p_level = elem->p_level() + ((elem->p_refinement_flag() == Elem::REFINE) ? 1 : 0); // Set the max_level at each node for (unsigned int n=0; n<elem->n_nodes(); n++) { const unsigned int node_number = elem->node(n); assert (node_number < max_level_at_node.size()); max_level_at_node[node_number] = std::max (max_level_at_node[node_number], elem_level); max_p_level_at_node[node_number] = std::max (max_p_level_at_node[node_number], elem_p_level); } } } // Now loop over the active elements and flag the elements // who violate the requested level mismatch { // active_elem_iterator elem_it (_mesh.elements_begin()); // const active_elem_iterator elem_end(_mesh.elements_end()); MeshBase::element_iterator elem_it = _mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { Elem* elem = *elem_it; const unsigned int elem_level = elem->level(); const unsigned int elem_p_level = elem->p_level(); // Skip the element if it is already fully flagged if (elem->refinement_flag() == Elem::REFINE && elem->p_refinement_flag() == Elem::REFINE) continue; // Loop over the nodes, check for possible mismatch for (unsigned int n=0; n<elem->n_nodes(); n++) { const unsigned int node_number = elem->node(n); // Flag the element for refinement if it violates // the requested level mismatch if ( (elem_level + max_mismatch) < max_level_at_node[node_number] && elem->refinement_flag() != Elem::REFINE) { elem->set_refinement_flag (Elem::REFINE); flags_changed = true; } if ( (elem_p_level + max_mismatch) < max_p_level_at_node[node_number] && elem->p_refinement_flag() != Elem::REFINE) { elem->set_p_refinement_flag (Elem::REFINE); flags_changed = true; } } } } return flags_changed; } bool MeshRefinement::eliminate_unrefined_patches () { bool flags_changed = false; // active_elem_iterator elem_it (_mesh.elements_begin()); // const active_elem_iterator elem_end(_mesh.elements_end()); MeshBase::element_iterator elem_it = _mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { Elem* elem = *elem_it; // First assume that we'll have to flag this element for both h // and p refinement, then change our minds if we see any // neighbors that are as coarse or coarser than us. bool h_flag_me = true, p_flag_me = true; // Skip the element if it is already fully flagged for refinement if (elem->p_refinement_flag() == Elem::REFINE) p_flag_me = false; if (elem->refinement_flag() == Elem::REFINE) { h_flag_me = false; if (!p_flag_me) continue; } // Test the parent if that is already flagged for coarsening else if (elem->refinement_flag() == Elem::COARSEN) { assert(elem->parent()); elem = elem->parent(); // FIXME - this doesn't seem right - RHS if (elem->refinement_flag() != Elem::COARSEN_INACTIVE) continue; p_flag_me = false; } const unsigned int my_level = elem->level(); int my_p_adjustment = 0; if (elem->p_refinement_flag() == Elem::REFINE) my_p_adjustment = 1; else if (elem->p_refinement_flag() == Elem::COARSEN) { assert(elem->p_level() > 0); my_p_adjustment = -1; } const unsigned int my_new_p_level = elem->p_level() + my_p_adjustment; // Check all the element neighbors for (unsigned int n=0; n<elem->n_neighbors(); n++) { const Elem *neighbor = elem->neighbor(n); // Quit if the element is on the boundary if (neighbor == NULL) { h_flag_me = false; p_flag_me = false; break; } // if the neighbor will be equally or less refined // than we are, then we do not need to h refine ourselves. if (h_flag_me && (neighbor->level() < my_level) || ((neighbor->active()) && (neighbor->refinement_flag() != Elem::REFINE)) || (neighbor->refinement_flag() == Elem::COARSEN_INACTIVE)) { h_flag_me = false; if (!p_flag_me) break; } if (p_flag_me) { // if active neighbors will have a p level // equal to or lower than ours, then we do not need to p // refine ourselves. if (neighbor->active()) { int p_adjustment = 0; if (neighbor->p_refinement_flag() == Elem::REFINE) p_adjustment = 1; else if (neighbor->p_refinement_flag() == Elem::COARSEN) { assert(neighbor->p_level() > 0); p_adjustment = -1; } if (my_new_p_level >= neighbor->p_level() + p_adjustment) { p_flag_me = false; if (!h_flag_me) break; } } // If we have inactive neighbors, we need to // test all their active descendants which neighbor us else { if (neighbor->min_new_p_level_by_neighbor(elem, my_new_p_level + 2) <= my_new_p_level) { p_flag_me = false; if (!h_flag_me) break; } } } } if (h_flag_me) { // Parents that would create islands should no longer // coarsen if (elem->refinement_flag() == Elem::COARSEN_INACTIVE) { for (unsigned int c=0; c<elem->n_children(); c++) { assert(elem->child(c)->refinement_flag() == Elem::COARSEN); elem->child(c)->set_refinement_flag(Elem::DO_NOTHING); } elem->set_refinement_flag(Elem::INACTIVE); } else elem->set_refinement_flag(Elem::REFINE); flags_changed = true; } if (p_flag_me) { if (elem->p_refinement_flag() == Elem::COARSEN) elem->set_p_refinement_flag(Elem::DO_NOTHING); else elem->set_p_refinement_flag(Elem::REFINE); flags_changed = true; } } return flags_changed; } #endif <|endoftext|>
<commit_before>/* Copyright 2009, 2010 SPARTA, Inc., dba Cobham Analytic Solutions * * This file is part of WATCHER. * * WATCHER 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. * * WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>. */ /** * @file showClock.cpp * @author Geoff Lawler <[email protected]> * @date 2009-07-15 */ /** * @page showClock * * showClock is a test node command line program that "draws" a clock by arranging a set of nodes and edges into the shape of an * analog clock. The "clock" is updated once a second to move "the hands" of the clock around. This program is mostly * used to test the "TiVO" functionality built into the watcher system. * * Usage: * @{ * <b>showClock -s server [optional args]</b> * @} * @{ * Args: * @arg <b>-s, --server=address|name</b>, The address or name of the node running watcherd * @} * Optional args: * @arg <b>-r, --radius</b>, The radius of the clock face in some unknown unit * @arg <b>-S, --hideSecondRing</b> Don't send message to draw the outer, second hand ring. * @arg <b>-H, --hideHourRing</b> Don't send message to draw the inner, hour hand ring. * @arg <b>-p, --logProps=file</b>, log.properties file, which controls logging for this program * @arg <b>-h, --help</b>, Show help message */ #include <getopt.h> #include <string> #include <math.h> #include <boost/asio.hpp> #include <boost/lexical_cast.hpp> #include <libwatcher/client.h> #include <libwatcher/gpsMessage.h> #include <libwatcher/labelMessage.h> #include <libwatcher/edgeMessage.h> #include <libwatcher/watcherColors.h> #include <libwatcher/colors.h> #include "logger.h" #include <libwatcher/sendMessageHandler.h> #include <libwatcher/dataPointMessage.h> DECLARE_GLOBAL_LOGGER("showClock"); using namespace std; using namespace watcher; using namespace watcher::event; using namespace boost; #define PI (3.141592653589793) // Isn't this #DEFINEd somewhere? void usage(const char *progName) { fprintf(stderr, "Usage: %s [args]\n", basename(progName)); fprintf(stderr, "Args:\n"); fprintf(stderr, " -s, --server=address The addres of the node running watcherd\n"); fprintf(stderr, "\n"); fprintf(stderr, "Optional args:\n"); fprintf(stderr, " -p, --logProps log.properties file, which controls logging for this program\n"); fprintf(stderr, " -r, --radius The radius of the circle in some unknown unit\n"); fprintf(stderr, " -S, --hideSecondRing Don't send message to draw the outer, second hand ring\n"); fprintf(stderr, " -H, --hideHourRing Don't send message to draw the inner, hour hand ring\n"); fprintf(stderr, " -t, --latitude Place the clock at this latitude (def==0).\n"); fprintf(stderr, " -g, --longitude Place the clock at this longitude (def==0).\n"); fprintf(stderr, " -x, --gpsScale Factor the GPS positions by this much (def==1)\n"); fprintf(stderr, "\n"); fprintf(stderr, " -h, --help Show this message\n"); exit(1); } int main(int argc, char **argv) { TRACE_ENTER(); int c; string server; string logProps(string(basename(argv[0]))+string(".log.properties")); double radius=50.0; bool showSecondRing=true, showHourRing=true; double offsetLong=0, offsetLat=0; double gpsScale=1; // dataPoint values for each node int minuteDP[60] = {0,}; int secDP[60] = {0,}; while (true) { int option_index = 0; static struct option long_options[] = { {"server", required_argument, 0, 's'}, {"logProps", required_argument, 0, 'p'}, {"radius", no_argument, 0, 'r'}, {"hideSecondRing", no_argument, 0, 'S'}, {"hideHourRing", no_argument, 0, 'H'}, {"latitude", required_argument, 0, 't'}, {"longitude", required_argument, 0, 'g'}, {"gpsScale", required_argument, 0, 'x'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; c = getopt_long(argc, argv, "r:s:p:t:g:x:eSHh?", long_options, &option_index); if (c == -1) break; switch(c) { case 's': server=optarg; break; case 'p': logProps=optarg; break; case 'r': radius=lexical_cast<double>(optarg); break; case 'S': showSecondRing=false; break; case 'H': showHourRing=false; break; case 'g': offsetLong=lexical_cast<double>(optarg); break; case 't': offsetLat=lexical_cast<double>(optarg); break; case 'x': gpsScale=lexical_cast<double>(optarg); break; case 'h': case '?': default: usage(argv[0]); break; } } if (server=="") { usage(argv[0]); exit(1); } // // Now do some actual work. // LOAD_LOG_PROPS(logProps); Client client(server); LOG_INFO("Connecting to " << server << " and sending message."); // Do not add empty handler - default Client handler does not close connection. // client.addMessageHandler(SendMessageHandler::create()); unsigned int loopTime=1; // Create hour, min, sec, and center nodes. NodeIdentifier centerId=NodeIdentifier::from_string("192.168.1.100"); NodeIdentifier hourId=NodeIdentifier::from_string("192.168.1.101"); NodeIdentifier minId=NodeIdentifier::from_string("192.168.1.102"); NodeIdentifier secId=NodeIdentifier::from_string("192.168.1.103"); const GUILayer hourLayer("Hour"); const GUILayer minLayer("Min"); const GUILayer secLayer("Sec"); const GUILayer hourRingLayer("HourRing"); const GUILayer secRingLayer("SecondRing"); const double step=(2*PI)/60; struct { double theta; NodeIdentifier *id; const char *label; double length; const GUILayer layer; double dataPoint[2]; } nodeData[]= { { 0, &hourId, "hour", radius*0.7, hourLayer, { 0, 0 } }, { 0, &minId, "min", radius, minLayer, { 0, 0 } }, { 0, &secId, "sec", radius, secLayer, { 0, 0 } }, }; while (true) // draw everything all the time as we don't know when watcher will start { vector<MessagePtr> messages; // Draw center node GPSMessagePtr gpsMess(new GPSMessage(gpsScale*(offsetLong+radius), gpsScale*(offsetLat+radius), 0)); gpsMess->layer=hourLayer; // meh. gpsMess->fromNodeID=centerId; messages.push_back(gpsMess); for (unsigned int i=0; i<sizeof(nodeData)/sizeof(nodeData[0]); i++) { // update location offsets by current time. time_t nowInSecs=time(NULL); struct tm *now=localtime(&nowInSecs); if (*nodeData[i].id==hourId) nodeData[i].theta=step*((now->tm_hour*(60/12))+(now->tm_min/12)); else if(*nodeData[i].id==minId) nodeData[i].theta=step*now->tm_min; else if(*nodeData[i].id==secId) nodeData[i].theta=step*now->tm_sec; // Move hour. min, and sec nodes to appropriate locations. GPSMessagePtr gpsMess(new GPSMessage( gpsScale*(offsetLong+(sin(nodeData[i].theta)*nodeData[i].length)+radius), gpsScale*(offsetLat+(cos(nodeData[i].theta)*nodeData[i].length)+radius), (double)i)); gpsMess->layer=nodeData[i].layer; gpsMess->fromNodeID=*nodeData[i].id; messages.push_back(gpsMess); EdgeMessagePtr edge(new EdgeMessage(centerId, *nodeData[i].id, nodeData[i].layer, colors::blue, 2.0, false, loopTime*1500, true)); LabelMessagePtr labMess(new LabelMessage(nodeData[i].label)); labMess->layer=nodeData[i].layer; labMess->expiration=loopTime*1500; edge->middleLabel=labMess; LabelMessagePtr numLabMess(new LabelMessage); if (*nodeData[i].id==hourId) numLabMess->label=boost::lexical_cast<string>(now->tm_hour%12); else if(*nodeData[i].id==minId) numLabMess->label=boost::lexical_cast<string>(now->tm_min); else if(*nodeData[i].id==secId) numLabMess->label=boost::lexical_cast<string>(now->tm_sec); numLabMess->layer=nodeData[i].layer; numLabMess->expiration=loopTime*1500; edge->node2Label=numLabMess; messages.push_back(edge); int unit = (rand() <= RAND_MAX/2) ? -1 : +1; DataPointMessagePtr dataMess0(new DataPointMessage); nodeData[i].dataPoint[0] += unit; dataMess0->fromNodeID = *nodeData[i].id; dataMess0->dataPoints.push_back(nodeData[i].dataPoint[0]); dataMess0->dataName = "data0"; messages.push_back(dataMess0); unit = (rand() <= RAND_MAX/2) ? -1 : +1; nodeData[i].dataPoint[1] += unit; DataPointMessagePtr dataMess1(new DataPointMessage); dataMess1->fromNodeID = *nodeData[i].id; dataMess1->dataPoints.push_back(nodeData[i].dataPoint[1]); dataMess1->dataName = "data1"; messages.push_back(dataMess1); } if (showHourRing) { // add nodes at clock face number locations. double theta=(2*PI)/12; for (unsigned int i=0; i<12; i++, theta+=(2*PI)/12) { NodeIdentifier thisId=NodeIdentifier::from_string("192.168.2." + lexical_cast<string>(i+1)); GPSMessagePtr gpsMess(new GPSMessage( gpsScale*(offsetLong+((sin(theta)*radius)+radius)), gpsScale*(offsetLat+((cos(theta)*radius)+radius)), 0.0)); gpsMess->layer=hourRingLayer; gpsMess->fromNodeID=thisId; messages.push_back(gpsMess); } } if (showSecondRing) { // add nodes at clock face second locations. double theta=(2*PI)/60; for (unsigned int i=0; i<60; i++, theta+=(2*PI)/60) { NodeIdentifier thisId=NodeIdentifier::from_string("192.168.3." + lexical_cast<string>(i+1)); double faceRad=radius*1.15; GPSMessagePtr gpsMess(new GPSMessage( gpsScale*(offsetLong+((sin(theta)*faceRad)+radius)), gpsScale*(offsetLat+((cos(theta)*faceRad)+radius)), 0.0)); gpsMess->layer=secRingLayer; gpsMess->fromNodeID=thisId; messages.push_back(gpsMess); } } if (!messages.empty()) { if(!client.sendMessages(messages)) { LOG_ERROR("Error sending " << messages.size() << " messages."); TRACE_EXIT_RET(EXIT_FAILURE); return EXIT_FAILURE; } } sleep(loopTime); } client.wait(); TRACE_EXIT_RET(EXIT_SUCCESS); return EXIT_SUCCESS; } <commit_msg>have showClock use more realistic gps coordinates.<commit_after>/* Copyright 2009, 2010 SPARTA, Inc., dba Cobham Analytic Solutions * * This file is part of WATCHER. * * WATCHER 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. * * WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>. */ /** * @file showClock.cpp * @author Geoff Lawler <[email protected]> * @date 2009-07-15 */ /** * @page showClock * * showClock is a test node command line program that "draws" a clock by arranging a set of nodes and edges into the shape of an * analog clock. The "clock" is updated once a second to move "the hands" of the clock around. This program is mostly * used to test the "TiVO" functionality built into the watcher system. * * Usage: * @{ * <b>showClock -s server [optional args]</b> * @} * @{ * Args: * @arg <b>-s, --server=address|name</b>, The address or name of the node running watcherd * @} * Optional args: * @arg <b>-r, --radius</b>, The radius of the clock face in some unknown unit * @arg <b>-S, --hideSecondRing</b> Don't send message to draw the outer, second hand ring. * @arg <b>-H, --hideHourRing</b> Don't send message to draw the inner, hour hand ring. * @arg <b>-p, --logProps=file</b>, log.properties file, which controls logging for this program * @arg <b>-h, --help</b>, Show help message */ #include <getopt.h> #include <string> #include <math.h> #include <boost/asio.hpp> #include <boost/lexical_cast.hpp> #include <libwatcher/client.h> #include <libwatcher/gpsMessage.h> #include <libwatcher/labelMessage.h> #include <libwatcher/edgeMessage.h> #include <libwatcher/watcherColors.h> #include <libwatcher/colors.h> #include "logger.h" #include <libwatcher/sendMessageHandler.h> #include <libwatcher/dataPointMessage.h> DECLARE_GLOBAL_LOGGER("showClock"); using namespace std; using namespace watcher; using namespace watcher::event; using namespace boost; #define PI (3.141592653589793) // Isn't this #DEFINEd somewhere? void usage(const char *progName) { fprintf(stderr, "Usage: %s [args]\n", basename(progName)); fprintf(stderr, "Args:\n"); fprintf(stderr, " -s, --server=address The addres of the node running watcherd\n"); fprintf(stderr, "\n"); fprintf(stderr, "Optional args:\n"); fprintf(stderr, " -p, --logProps log.properties file, which controls logging for this program\n"); fprintf(stderr, " -r, --radius The radius of the circle in some unknown unit\n"); fprintf(stderr, " -S, --hideSecondRing Don't send message to draw the outer, second hand ring\n"); fprintf(stderr, " -H, --hideHourRing Don't send message to draw the inner, hour hand ring\n"); fprintf(stderr, " -t, --latitude Place the clock at this latitude (def==0).\n"); fprintf(stderr, " -g, --longitude Place the clock at this longitude (def==0).\n"); fprintf(stderr, " -x, --gpsScale Factor the GPS positions by this much (def==1)\n"); fprintf(stderr, "\n"); fprintf(stderr, " -h, --help Show this message\n"); exit(1); } int main(int argc, char **argv) { TRACE_ENTER(); int c; string server; string logProps(string(basename(argv[0]))+string(".log.properties")); double radius=50.0; bool showSecondRing=true, showHourRing=true; double offsetLong=0, offsetLat=0; double gpsScale=1; const double coordToGpsFactor=60000.0; // dataPoint values for each node int minuteDP[60] = {0,}; int secDP[60] = {0,}; while (true) { int option_index = 0; static struct option long_options[] = { {"server", required_argument, 0, 's'}, {"logProps", required_argument, 0, 'p'}, {"radius", no_argument, 0, 'r'}, {"hideSecondRing", no_argument, 0, 'S'}, {"hideHourRing", no_argument, 0, 'H'}, {"latitude", required_argument, 0, 't'}, {"longitude", required_argument, 0, 'g'}, {"gpsScale", required_argument, 0, 'x'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; c = getopt_long(argc, argv, "r:s:p:t:g:x:eSHh?", long_options, &option_index); if (c == -1) break; switch(c) { case 's': server=optarg; break; case 'p': logProps=optarg; break; case 'r': radius=lexical_cast<double>(optarg); break; case 'S': showSecondRing=false; break; case 'H': showHourRing=false; break; case 'g': offsetLong=lexical_cast<double>(optarg); break; case 't': offsetLat=lexical_cast<double>(optarg); break; case 'x': gpsScale=lexical_cast<double>(optarg); break; case 'h': case '?': default: usage(argv[0]); break; } } if (server=="") { usage(argv[0]); exit(1); } // // Now do some actual work. // LOAD_LOG_PROPS(logProps); Client client(server); LOG_INFO("Connecting to " << server << " and sending message."); // Do not add empty handler - default Client handler does not close connection. // client.addMessageHandler(SendMessageHandler::create()); unsigned int loopTime=1; // Create hour, min, sec, and center nodes. NodeIdentifier centerId=NodeIdentifier::from_string("192.168.1.100"); NodeIdentifier hourId=NodeIdentifier::from_string("192.168.1.101"); NodeIdentifier minId=NodeIdentifier::from_string("192.168.1.102"); NodeIdentifier secId=NodeIdentifier::from_string("192.168.1.103"); const GUILayer hourLayer("Hour"); const GUILayer minLayer("Min"); const GUILayer secLayer("Sec"); const GUILayer hourRingLayer("HourRing"); const GUILayer secRingLayer("SecondRing"); const double step=(2*PI)/60; struct { double theta; NodeIdentifier *id; const char *label; double length; const GUILayer layer; double dataPoint[2]; } nodeData[]= { { 0, &hourId, "hour", radius*0.7, hourLayer, { 0, 0 } }, { 0, &minId, "min", radius, minLayer, { 0, 0 } }, { 0, &secId, "sec", radius, secLayer, { 0, 0 } }, }; while (true) // draw everything all the time as we don't know when watcher will start { vector<MessagePtr> messages; // Draw center node GPSMessagePtr gpsMess(new GPSMessage((gpsScale*(offsetLong+radius))/coordToGpsFactor, (gpsScale*(offsetLat+radius))/coordToGpsFactor, 0)); gpsMess->layer=hourLayer; // meh. gpsMess->fromNodeID=centerId; messages.push_back(gpsMess); for (unsigned int i=0; i<sizeof(nodeData)/sizeof(nodeData[0]); i++) { // update location offsets by current time. time_t nowInSecs=time(NULL); struct tm *now=localtime(&nowInSecs); if (*nodeData[i].id==hourId) nodeData[i].theta=step*((now->tm_hour*(60/12))+(now->tm_min/12)); else if(*nodeData[i].id==minId) nodeData[i].theta=step*now->tm_min; else if(*nodeData[i].id==secId) nodeData[i].theta=step*now->tm_sec; // Move hour. min, and sec nodes to appropriate locations. GPSMessagePtr gpsMess(new GPSMessage( (gpsScale*(offsetLong+(sin(nodeData[i].theta)*nodeData[i].length)+radius))/coordToGpsFactor, (gpsScale*(offsetLat+(cos(nodeData[i].theta)*nodeData[i].length)+radius))/coordToGpsFactor, (double)i)); gpsMess->layer=nodeData[i].layer; gpsMess->fromNodeID=*nodeData[i].id; messages.push_back(gpsMess); EdgeMessagePtr edge(new EdgeMessage(centerId, *nodeData[i].id, nodeData[i].layer, colors::blue, 2.0, false, loopTime*1500, true)); LabelMessagePtr labMess(new LabelMessage(nodeData[i].label)); labMess->layer=nodeData[i].layer; labMess->expiration=loopTime*1500; edge->middleLabel=labMess; LabelMessagePtr numLabMess(new LabelMessage); if (*nodeData[i].id==hourId) numLabMess->label=boost::lexical_cast<string>(now->tm_hour%12); else if(*nodeData[i].id==minId) numLabMess->label=boost::lexical_cast<string>(now->tm_min); else if(*nodeData[i].id==secId) numLabMess->label=boost::lexical_cast<string>(now->tm_sec); numLabMess->layer=nodeData[i].layer; numLabMess->expiration=loopTime*1500; edge->node2Label=numLabMess; messages.push_back(edge); int unit = (rand() <= RAND_MAX/2) ? -1 : +1; DataPointMessagePtr dataMess0(new DataPointMessage); nodeData[i].dataPoint[0] += unit; dataMess0->fromNodeID = *nodeData[i].id; dataMess0->dataPoints.push_back(nodeData[i].dataPoint[0]); dataMess0->dataName = "data0"; messages.push_back(dataMess0); unit = (rand() <= RAND_MAX/2) ? -1 : +1; nodeData[i].dataPoint[1] += unit; DataPointMessagePtr dataMess1(new DataPointMessage); dataMess1->fromNodeID = *nodeData[i].id; dataMess1->dataPoints.push_back(nodeData[i].dataPoint[1]); dataMess1->dataName = "data1"; messages.push_back(dataMess1); } if (showHourRing) { // add nodes at clock face number locations. double theta=(2*PI)/12; for (unsigned int i=0; i<12; i++, theta+=(2*PI)/12) { NodeIdentifier thisId=NodeIdentifier::from_string("192.168.2." + lexical_cast<string>(i+1)); GPSMessagePtr gpsMess(new GPSMessage( (gpsScale*(offsetLong+((sin(theta)*radius)+radius)))/coordToGpsFactor, (gpsScale*(offsetLat+((cos(theta)*radius)+radius)))/coordToGpsFactor, 0.0)); gpsMess->layer=hourRingLayer; gpsMess->fromNodeID=thisId; messages.push_back(gpsMess); } } if (showSecondRing) { // add nodes at clock face second locations. double theta=(2*PI)/60; for (unsigned int i=0; i<60; i++, theta+=(2*PI)/60) { NodeIdentifier thisId=NodeIdentifier::from_string("192.168.3." + lexical_cast<string>(i+1)); double faceRad=radius*1.15; GPSMessagePtr gpsMess(new GPSMessage( (gpsScale*(offsetLong+((sin(theta)*faceRad)+radius)))/coordToGpsFactor, (gpsScale*(offsetLat+((cos(theta)*faceRad)+radius)))/coordToGpsFactor, 0.0)); gpsMess->layer=secRingLayer; gpsMess->fromNodeID=thisId; messages.push_back(gpsMess); } } if (!messages.empty()) { if(!client.sendMessages(messages)) { LOG_ERROR("Error sending " << messages.size() << " messages."); TRACE_EXIT_RET(EXIT_FAILURE); return EXIT_FAILURE; } } sleep(loopTime); } client.wait(); TRACE_EXIT_RET(EXIT_SUCCESS); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/lite/experimental/writer/writer_lib.h" #include <cstdlib> #include <cstring> #include <unordered_map> #include "tensorflow/lite/builtin_op_data.h" #include "tensorflow/lite/context_util.h" #include "tensorflow/lite/experimental/writer/enum_mapping.h" #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/schema/reflection/schema_generated.h" #include "tensorflow/lite/version.h" namespace tflite { template <class T> using Offset = flatbuffers::Offset<T>; template <class T> using Vector = flatbuffers::Vector<T>; using FlatBufferBuilder = flatbuffers::FlatBufferBuilder; std::pair<BuiltinOptions, Offset<void>> CreateBuiltinUnion( FlatBufferBuilder* fbb, enum BuiltinOperator op, void* builtin_op_data) { switch (op) { #include "tensorflow/lite/experimental/writer/option_writer_generated.h" } return std::make_pair(BuiltinOptions_NONE, Offset<void>()); } template <class T_OUTPUT, class T_INPUT> Offset<Vector<T_OUTPUT>> InterpreterWriter::ExportVector(FlatBufferBuilder* fbb, const T_INPUT& v) { std::vector<T_OUTPUT> inputs(v.begin(), v.end()); return fbb->template CreateVector<T_OUTPUT>(inputs); } Offset<Vector<Offset<Operator>>> InterpreterWriter::ExportOperators( FlatBufferBuilder* fbb) { std::vector<Offset<Operator>> operators; std::vector<int> operator_to_opcode; // TODO(aselle): Augment this once we put execution plan in schema. operator_to_opcode.resize(interpreter_->nodes_size(), -1); for (int op_index : interpreter_->execution_plan()) { const auto* node_and_registration = interpreter_->node_and_registration(op_index); const TfLiteRegistration* registration = &node_and_registration->second; if (!registration->custom_name) { operator_to_opcode[op_index] = GetOpCodeForBuiltin(registration->builtin_code); } else { operator_to_opcode[op_index] = GetOpCodeForCustom(registration->custom_name); } } // second pass serialize operators for (int op_index : interpreter_->execution_plan()) { const auto* node_and_registration = interpreter_->node_and_registration(op_index); const TfLiteNode& node = node_and_registration->first; const TfLiteRegistration& registration = node_and_registration->second; Offset<void> builtin_options; BuiltinOptions builtin_options_type = BuiltinOptions_NONE; // Custom data // TODO(aselle): Custom options format is not known by default. Just assume // for now. auto custom_options_format = CustomOptionsFormat_FLEXBUFFERS; Offset<Vector<uint8_t>> custom_options = 0; if (!registration.custom_name) { // builtin auto builtin_options_and_type = CreateBuiltinUnion( fbb, static_cast<enum BuiltinOperator>(registration.builtin_code), node.builtin_data); builtin_options = builtin_options_and_type.second; builtin_options_type = builtin_options_and_type.first; } else { auto custom_writer = custom_op_to_writer_.find(registration.custom_name); if (custom_writer != custom_op_to_writer_.end() && custom_writer->second) { // delegate to custom writer if it exists custom_writer->second(fbb, interpreter_, op_index, &custom_options, &custom_options_format); } else { // use the custom data as fact custom_options = fbb->CreateVector( reinterpret_cast<const uint8_t*>(node.custom_initial_data), node.custom_initial_data_size); } } int opcode_index = operator_to_opcode[op_index]; std::vector<int> written_inputs = RemapTensorIndicesToWritten(TfLiteIntArrayView(node.inputs)); std::vector<int> written_outputs = RemapTensorIndicesToWritten(TfLiteIntArrayView(node.outputs)); auto inputs = ExportVector<int32_t>(fbb, written_inputs); auto outputs = ExportVector<int32_t>(fbb, written_outputs); operators.push_back(CreateOperator(*fbb, opcode_index, inputs, outputs, builtin_options_type, builtin_options, custom_options, custom_options_format)); } return fbb->template CreateVector<Offset<Operator>>(operators); } Offset<Vector<Offset<Tensor>>> InterpreterWriter::ExportTensors( FlatBufferBuilder* fbb) { // Initialized to -1. // A value of -1 means this tensor will not be exported. tensor_to_written_tensor_.resize(interpreter_->tensors_size(), -1); std::vector<Offset<Tensor>> tensors; // Make a map from tensor index to whether the tensor is a temporary. std::vector<bool> tensor_is_temporary(interpreter_->tensors_size(), false); for (int op_index = 0; op_index < interpreter_->nodes_size(); ++op_index) { const auto* node_and_registration = interpreter_->node_and_registration(op_index); for (auto tensor_index : TfLiteIntArrayView(node_and_registration->first.temporaries)) tensor_is_temporary[tensor_index] = true; } // Now we need to remap all used tensor indices int curr_output_index = 0; for (int tensor_index = 0; tensor_index < interpreter_->tensors_size(); tensor_index++) { // Temporary tensors and unused tensors will not be written. if (!tensor_is_temporary[tensor_index] && unused_tensors_.find(tensor_index) == unused_tensors_.end()) { tensor_to_written_tensor_[tensor_index] = curr_output_index++; } } for (int tensor_index = 0; tensor_index < interpreter_->tensors_size(); ++tensor_index) { // Tensor not exported. if (tensor_to_written_tensor_[tensor_index] == -1) continue; if (TfLiteTensor* tensor = interpreter_->tensor(tensor_index)) { // We only need to convert non temporaries if (tensor->allocation_type != kTfLiteArenaRw && tensor->allocation_type != kTfLiteMmapRo && tensor->allocation_type != kTfLiteArenaRwPersistent) continue; // Allocate a buffer index int buffer_index = 0; // This is null if (tensor->allocation_type == kTfLiteMmapRo) { buffer_index = buffers_.size(); buffers_.push_back(std::make_pair( reinterpret_cast<const uint8_t*>(tensor->data.raw), tensor->bytes)); } // Primitive type. TensorType type = TfLiteTypeToSchemaType(tensor->type); // Handle quantization const Offset<Vector<float>> null_array; Offset<Vector<float>> scale_array; Offset<Vector<int64_t>> zero_point_array; if (tensor->params.scale != 0.f) { // We have quantization, make a single arugment array (multi channel // quant needs updating here). scale_array = fbb->CreateVector<float>({tensor->params.scale}); zero_point_array = fbb->CreateVector<int64_t>({tensor->params.zero_point}); } Offset<QuantizationParameters> quantization_params = CreateQuantizationParameters(*fbb, null_array, null_array, scale_array, zero_point_array); // Shape TfLiteIntArrayView shape_view(tensor->dims); std::vector<int> shape = std::vector<int>(shape_view.begin(), shape_view.end()); tensors.push_back(CreateTensor(*fbb, ExportVector<int32_t>(fbb, shape), type, buffer_index, fbb->CreateString(tensor->name), quantization_params, tensor->is_variable)); } } return fbb->template CreateVector<Offset<Tensor>>(tensors); } Offset<Vector<Offset<Buffer>>> InterpreterWriter::ExportBuffers( FlatBufferBuilder* fbb) { std::vector<Offset<Buffer>> buffer_vector; for (auto buffer : buffers_) { auto data_offset = fbb->CreateVector(buffer.first, buffer.second); buffer_vector.push_back(CreateBuffer(*fbb, data_offset)); } return fbb->template CreateVector<Offset<Buffer>>(buffer_vector); } Offset<Vector<Offset<OperatorCode>>> InterpreterWriter::CreateOpCodeTable( FlatBufferBuilder* fbb) { std::vector<Offset<OperatorCode>> codes; for (auto it : opcodes_) { const char* custom_name = it.custom.empty() ? nullptr : it.custom.c_str(); codes.push_back(CreateOperatorCodeDirect( *fbb, static_cast<BuiltinOperator>(it.builtin), custom_name)); } return fbb->template CreateVector<Offset<OperatorCode>>(codes); } template <class T> std::vector<int> InterpreterWriter::RemapTensorIndicesToWritten( const T& input) { std::vector<int> output; output.reserve(input.size()); for (int x : input) { // Special value representing an optional tensor which is not present. if (x == -1) { output.push_back(x); continue; } if (tensor_to_written_tensor_[x] != -1) { output.push_back(tensor_to_written_tensor_[x]); } } return output; } TfLiteStatus InterpreterWriter::GetBuffer(std::unique_ptr<uint8_t[]>* out, size_t* size) { if (!out || !size) return kTfLiteError; FlatBufferBuilder builder(/*initial_size=*/10240); std::vector<Offset<SubGraph>> subgraphs_as_vector; { // subgraph specific stuff auto tensors = ExportTensors(&builder); std::vector<int> written_inputs = RemapTensorIndicesToWritten(interpreter_->inputs()); std::vector<int> written_outputs = RemapTensorIndicesToWritten(interpreter_->outputs()); auto inputs = ExportVector<int32_t>(&builder, written_inputs); auto outputs = ExportVector<int32_t>(&builder, written_outputs); auto ops = ExportOperators(&builder); subgraphs_as_vector.push_back( CreateSubGraph(builder, tensors, inputs, outputs, ops, /* name */ 0)); } Offset<Vector<Offset<Buffer>>> buffers = ExportBuffers(&builder); auto description = builder.CreateString("Exported from Interpreter."); auto op_codes = CreateOpCodeTable(&builder); auto model = CreateModel(builder, TFLITE_SCHEMA_VERSION, op_codes, builder.CreateVector(subgraphs_as_vector), description, buffers); ::tflite::FinishModelBuffer(builder, model); const uint8_t* buffer = builder.GetBufferPointer(); *size = builder.GetSize(); (*out).reset(new uint8_t[*size]); memcpy(out->get(), buffer, *size); return kTfLiteOk; } TfLiteStatus InterpreterWriter::Write(const std::string& filename) { std::unique_ptr<uint8_t[]> buffer; size_t size; TF_LITE_ENSURE_STATUS(GetBuffer(&buffer, &size)); FILE* fp = fopen(filename.c_str(), "wb"); if (!fp) return kTfLiteError; if (fwrite(buffer.get(), 1, size, fp) != size) return kTfLiteError; if (fclose(fp)) return kTfLiteError; return kTfLiteOk; } TfLiteStatus InterpreterWriter::RegisterCustomWriter( const std::string& custom_name, CustomWriter custom_writer) { if (custom_op_to_writer_.find(custom_name) != custom_op_to_writer_.end()) { return kTfLiteError; } custom_op_to_writer_.insert(std::make_pair(custom_name, custom_writer)); return kTfLiteOk; } } // namespace tflite <commit_msg>Remove usings because they can clash with TFLite symbols.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/lite/experimental/writer/writer_lib.h" #include <cstdlib> #include <cstring> #include <unordered_map> #include "tensorflow/lite/builtin_op_data.h" #include "tensorflow/lite/context_util.h" #include "tensorflow/lite/experimental/writer/enum_mapping.h" #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/schema/reflection/schema_generated.h" #include "tensorflow/lite/version.h" namespace tflite { std::pair<BuiltinOptions, flatbuffers::Offset<void>> CreateBuiltinUnion( flatbuffers::FlatBufferBuilder* fbb, enum BuiltinOperator op, void* builtin_op_data) { switch (op) { #include "tensorflow/lite/experimental/writer/option_writer_generated.h" } return std::make_pair(BuiltinOptions_NONE, flatbuffers::Offset<void>()); } template <class T_OUTPUT, class T_INPUT> flatbuffers::Offset<flatbuffers::Vector<T_OUTPUT>> InterpreterWriter::ExportVector(flatbuffers::FlatBufferBuilder* fbb, const T_INPUT& v) { std::vector<T_OUTPUT> inputs(v.begin(), v.end()); return fbb->template CreateVector<T_OUTPUT>(inputs); } flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Operator>>> InterpreterWriter::ExportOperators(flatbuffers::FlatBufferBuilder* fbb) { std::vector<flatbuffers::Offset<Operator>> operators; std::vector<int> operator_to_opcode; // TODO(aselle): Augment this once we put execution plan in schema. operator_to_opcode.resize(interpreter_->nodes_size(), -1); for (int op_index : interpreter_->execution_plan()) { const auto* node_and_registration = interpreter_->node_and_registration(op_index); const TfLiteRegistration* registration = &node_and_registration->second; if (!registration->custom_name) { operator_to_opcode[op_index] = GetOpCodeForBuiltin(registration->builtin_code); } else { operator_to_opcode[op_index] = GetOpCodeForCustom(registration->custom_name); } } // second pass serialize operators for (int op_index : interpreter_->execution_plan()) { const auto* node_and_registration = interpreter_->node_and_registration(op_index); const TfLiteNode& node = node_and_registration->first; const TfLiteRegistration& registration = node_and_registration->second; flatbuffers::Offset<void> builtin_options; BuiltinOptions builtin_options_type = BuiltinOptions_NONE; // Custom data // TODO(aselle): Custom options format is not known by default. Just assume // for now. auto custom_options_format = CustomOptionsFormat_FLEXBUFFERS; flatbuffers::Offset<flatbuffers::Vector<uint8_t>> custom_options = 0; if (!registration.custom_name) { // builtin auto builtin_options_and_type = CreateBuiltinUnion( fbb, static_cast<enum BuiltinOperator>(registration.builtin_code), node.builtin_data); builtin_options = builtin_options_and_type.second; builtin_options_type = builtin_options_and_type.first; } else { auto custom_writer = custom_op_to_writer_.find(registration.custom_name); if (custom_writer != custom_op_to_writer_.end() && custom_writer->second) { // delegate to custom writer if it exists custom_writer->second(fbb, interpreter_, op_index, &custom_options, &custom_options_format); } else { // use the custom data as fact custom_options = fbb->CreateVector( reinterpret_cast<const uint8_t*>(node.custom_initial_data), node.custom_initial_data_size); } } int opcode_index = operator_to_opcode[op_index]; std::vector<int> written_inputs = RemapTensorIndicesToWritten(TfLiteIntArrayView(node.inputs)); std::vector<int> written_outputs = RemapTensorIndicesToWritten(TfLiteIntArrayView(node.outputs)); auto inputs = ExportVector<int32_t>(fbb, written_inputs); auto outputs = ExportVector<int32_t>(fbb, written_outputs); operators.push_back(CreateOperator(*fbb, opcode_index, inputs, outputs, builtin_options_type, builtin_options, custom_options, custom_options_format)); } return fbb->template CreateVector<flatbuffers::Offset<Operator>>(operators); } flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Tensor>>> InterpreterWriter::ExportTensors(flatbuffers::FlatBufferBuilder* fbb) { // Initialized to -1. // A value of -1 means this tensor will not be exported. tensor_to_written_tensor_.resize(interpreter_->tensors_size(), -1); std::vector<flatbuffers::Offset<Tensor>> tensors; // Make a map from tensor index to whether the tensor is a temporary. std::vector<bool> tensor_is_temporary(interpreter_->tensors_size(), false); for (int op_index = 0; op_index < interpreter_->nodes_size(); ++op_index) { const auto* node_and_registration = interpreter_->node_and_registration(op_index); for (auto tensor_index : TfLiteIntArrayView(node_and_registration->first.temporaries)) tensor_is_temporary[tensor_index] = true; } // Now we need to remap all used tensor indices int curr_output_index = 0; for (int tensor_index = 0; tensor_index < interpreter_->tensors_size(); tensor_index++) { // Temporary tensors and unused tensors will not be written. if (!tensor_is_temporary[tensor_index] && unused_tensors_.find(tensor_index) == unused_tensors_.end()) { tensor_to_written_tensor_[tensor_index] = curr_output_index++; } } for (int tensor_index = 0; tensor_index < interpreter_->tensors_size(); ++tensor_index) { // Tensor not exported. if (tensor_to_written_tensor_[tensor_index] == -1) continue; if (TfLiteTensor* tensor = interpreter_->tensor(tensor_index)) { // We only need to convert non temporaries if (tensor->allocation_type != kTfLiteArenaRw && tensor->allocation_type != kTfLiteMmapRo && tensor->allocation_type != kTfLiteArenaRwPersistent) continue; // Allocate a buffer index int buffer_index = 0; // This is null if (tensor->allocation_type == kTfLiteMmapRo) { buffer_index = buffers_.size(); buffers_.push_back(std::make_pair( reinterpret_cast<const uint8_t*>(tensor->data.raw), tensor->bytes)); } // Primitive type. TensorType type = TfLiteTypeToSchemaType(tensor->type); // Handle quantization const flatbuffers::Offset<flatbuffers::Vector<float>> null_array; flatbuffers::Offset<flatbuffers::Vector<float>> scale_array; flatbuffers::Offset<flatbuffers::Vector<int64_t>> zero_point_array; if (tensor->params.scale != 0.f) { // We have quantization, make a single arugment array (multi channel // quant needs updating here). scale_array = fbb->CreateVector<float>({tensor->params.scale}); zero_point_array = fbb->CreateVector<int64_t>({tensor->params.zero_point}); } flatbuffers::Offset<QuantizationParameters> quantization_params = CreateQuantizationParameters(*fbb, null_array, null_array, scale_array, zero_point_array); // Shape TfLiteIntArrayView shape_view(tensor->dims); std::vector<int> shape = std::vector<int>(shape_view.begin(), shape_view.end()); tensors.push_back(CreateTensor(*fbb, ExportVector<int32_t>(fbb, shape), type, buffer_index, fbb->CreateString(tensor->name), quantization_params, tensor->is_variable)); } } return fbb->template CreateVector<flatbuffers::Offset<Tensor>>(tensors); } flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Buffer>>> InterpreterWriter::ExportBuffers(flatbuffers::FlatBufferBuilder* fbb) { std::vector<flatbuffers::Offset<Buffer>> buffer_vector; for (auto buffer : buffers_) { auto data_offset = fbb->CreateVector(buffer.first, buffer.second); buffer_vector.push_back(CreateBuffer(*fbb, data_offset)); } return fbb->template CreateVector<flatbuffers::Offset<Buffer>>(buffer_vector); } flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<OperatorCode>>> InterpreterWriter::CreateOpCodeTable(flatbuffers::FlatBufferBuilder* fbb) { std::vector<flatbuffers::Offset<OperatorCode>> codes; for (auto it : opcodes_) { const char* custom_name = it.custom.empty() ? nullptr : it.custom.c_str(); codes.push_back(CreateOperatorCodeDirect( *fbb, static_cast<BuiltinOperator>(it.builtin), custom_name)); } return fbb->template CreateVector<flatbuffers::Offset<OperatorCode>>(codes); } template <class T> std::vector<int> InterpreterWriter::RemapTensorIndicesToWritten( const T& input) { std::vector<int> output; output.reserve(input.size()); for (int x : input) { // Special value representing an optional tensor which is not present. if (x == -1) { output.push_back(x); continue; } if (tensor_to_written_tensor_[x] != -1) { output.push_back(tensor_to_written_tensor_[x]); } } return output; } TfLiteStatus InterpreterWriter::GetBuffer(std::unique_ptr<uint8_t[]>* out, size_t* size) { if (!out || !size) return kTfLiteError; flatbuffers::FlatBufferBuilder builder(/*initial_size=*/10240); std::vector<flatbuffers::Offset<SubGraph>> subgraphs_as_vector; { // subgraph specific stuff auto tensors = ExportTensors(&builder); std::vector<int> written_inputs = RemapTensorIndicesToWritten(interpreter_->inputs()); std::vector<int> written_outputs = RemapTensorIndicesToWritten(interpreter_->outputs()); auto inputs = ExportVector<int32_t>(&builder, written_inputs); auto outputs = ExportVector<int32_t>(&builder, written_outputs); auto ops = ExportOperators(&builder); subgraphs_as_vector.push_back( CreateSubGraph(builder, tensors, inputs, outputs, ops, /* name */ 0)); } flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Buffer>>> buffers = ExportBuffers(&builder); auto description = builder.CreateString("Exported from Interpreter."); auto op_codes = CreateOpCodeTable(&builder); auto model = CreateModel(builder, TFLITE_SCHEMA_VERSION, op_codes, builder.CreateVector(subgraphs_as_vector), description, buffers); ::tflite::FinishModelBuffer(builder, model); const uint8_t* buffer = builder.GetBufferPointer(); *size = builder.GetSize(); (*out).reset(new uint8_t[*size]); memcpy(out->get(), buffer, *size); return kTfLiteOk; } TfLiteStatus InterpreterWriter::Write(const std::string& filename) { std::unique_ptr<uint8_t[]> buffer; size_t size; TF_LITE_ENSURE_STATUS(GetBuffer(&buffer, &size)); FILE* fp = fopen(filename.c_str(), "wb"); if (!fp) return kTfLiteError; if (fwrite(buffer.get(), 1, size, fp) != size) return kTfLiteError; if (fclose(fp)) return kTfLiteError; return kTfLiteOk; } TfLiteStatus InterpreterWriter::RegisterCustomWriter( const std::string& custom_name, CustomWriter custom_writer) { if (custom_op_to_writer_.find(custom_name) != custom_op_to_writer_.end()) { return kTfLiteError; } custom_op_to_writer_.insert(std::make_pair(custom_name, custom_writer)); return kTfLiteOk; } } // namespace tflite <|endoftext|>
<commit_before>#include "fmi/ValueInfo.hpp" namespace FMI { ValueInfo::ValueInfo() : ValueSwitch(), _valueReferenceToNamesMapping(4, std::map<size_type, vector<string_type> >()), _valueInputReferenceToNamesMapping(4, std::map<size_type, string_type>()), _valueReferenceToDescriptionMapping(4, std::map<size_type, vector<string_type> >()) { } ValueInfo::ValueInfo(const ValueInfo& obj) : ValueSwitch(), _valueReferenceToNamesMapping(obj._valueReferenceToNamesMapping) { } ValueInfo::~ValueInfo() { } size_type ValueInfo::size() const { size_t counter = 0; for (size_t i = 0; i < _valueReferenceToNamesMapping.size(); ++i) counter += _valueReferenceToNamesMapping[i].size(); return counter; } std::vector<string_type> ValueInfo::getAllValueNames() const { std::vector<string_type> valueNames; std::vector<string_type> valueNamesTmp; std::vector<string_type>::iterator it; valueNamesTmp = getValueNames<double>(); it = valueNames.end(); valueNames.insert(it, valueNamesTmp.begin(), valueNamesTmp.end()); valueNamesTmp = getValueNames<int_type>(); it = valueNames.end(); valueNames.insert(it, valueNamesTmp.begin(), valueNamesTmp.end()); valueNamesTmp = getValueNames<bool_type>(); it = valueNames.end(); valueNames.insert(it, valueNamesTmp.begin(), valueNamesTmp.end()); valueNamesTmp = getValueNames<string_type>(); it = valueNames.end(); valueNames.insert(it, valueNamesTmp.begin(), valueNamesTmp.end()); return valueNames; } list<std::pair<string_type , size_type> > ValueInfo::getAllReferences() const { list<std::pair<string_type , size_type> > res; for(const auto& maps : _valueReferenceToNamesMapping) for(const auto& p : maps) for(const string_type & str : p.second) res.push_back(std::pair<string_type ,size_type>(str,p.first)); return res; } void ValueInfo::getAllValueReferencesUnrolled(list<size_type>& realValueIndices, list<size_type>& bool_typeValueIndices, list<size_type>& intValueIndices, list<size_type>& stringValueIndices) const { list<size_type> valueReferencesTmp; list<size_type>::iterator it; valueReferencesTmp = getAllValueReferencesUnrolled<double>(); it = realValueIndices.end(); realValueIndices.insert(it, valueReferencesTmp.begin(), valueReferencesTmp.end()); valueReferencesTmp = getAllValueReferencesUnrolled<int_type>(); it = intValueIndices.end(); intValueIndices.insert(it, valueReferencesTmp.begin(), valueReferencesTmp.end()); valueReferencesTmp = getAllValueReferencesUnrolled<bool_type>(); it = bool_typeValueIndices.end(); bool_typeValueIndices.insert(it, valueReferencesTmp.begin(), valueReferencesTmp.end()); valueReferencesTmp = getAllValueReferencesUnrolled<string_type>(); it = stringValueIndices.end(); stringValueIndices.insert(it, valueReferencesTmp.begin(), valueReferencesTmp.end()); } } /* namespace FMI */ <commit_msg>Fix serial test by fixing the copy constructor for ValueInfo<commit_after>#include "fmi/ValueInfo.hpp" namespace FMI { ValueInfo::ValueInfo() : ValueSwitch(), _valueReferenceToNamesMapping(4, std::map<size_type, vector<string_type> >()), _valueInputReferenceToNamesMapping(4, std::map<size_type, string_type>()), _valueReferenceToDescriptionMapping(4, std::map<size_type, vector<string_type> >()) { } ValueInfo::ValueInfo(const ValueInfo& obj) : ValueSwitch(), _valueReferenceToNamesMapping(obj._valueReferenceToNamesMapping), _valueInputReferenceToNamesMapping(obj._valueInputReferenceToNamesMapping), _valueReferenceToDescriptionMapping(obj._valueReferenceToDescriptionMapping) { } ValueInfo::~ValueInfo() { } size_type ValueInfo::size() const { size_t counter = 0; for (size_t i = 0; i < _valueReferenceToNamesMapping.size(); ++i) counter += _valueReferenceToNamesMapping[i].size(); return counter; } std::vector<string_type> ValueInfo::getAllValueNames() const { std::vector<string_type> valueNames; std::vector<string_type> valueNamesTmp; std::vector<string_type>::iterator it; valueNamesTmp = getValueNames<double>(); it = valueNames.end(); valueNames.insert(it, valueNamesTmp.begin(), valueNamesTmp.end()); valueNamesTmp = getValueNames<int_type>(); it = valueNames.end(); valueNames.insert(it, valueNamesTmp.begin(), valueNamesTmp.end()); valueNamesTmp = getValueNames<bool_type>(); it = valueNames.end(); valueNames.insert(it, valueNamesTmp.begin(), valueNamesTmp.end()); valueNamesTmp = getValueNames<string_type>(); it = valueNames.end(); valueNames.insert(it, valueNamesTmp.begin(), valueNamesTmp.end()); return valueNames; } list<std::pair<string_type , size_type> > ValueInfo::getAllReferences() const { list<std::pair<string_type , size_type> > res; for(const auto& maps : _valueReferenceToNamesMapping) for(const auto& p : maps) for(const string_type & str : p.second) res.push_back(std::pair<string_type ,size_type>(str,p.first)); return res; } void ValueInfo::getAllValueReferencesUnrolled(list<size_type>& realValueIndices, list<size_type>& bool_typeValueIndices, list<size_type>& intValueIndices, list<size_type>& stringValueIndices) const { list<size_type> valueReferencesTmp; list<size_type>::iterator it; valueReferencesTmp = getAllValueReferencesUnrolled<double>(); it = realValueIndices.end(); realValueIndices.insert(it, valueReferencesTmp.begin(), valueReferencesTmp.end()); valueReferencesTmp = getAllValueReferencesUnrolled<int_type>(); it = intValueIndices.end(); intValueIndices.insert(it, valueReferencesTmp.begin(), valueReferencesTmp.end()); valueReferencesTmp = getAllValueReferencesUnrolled<bool_type>(); it = bool_typeValueIndices.end(); bool_typeValueIndices.insert(it, valueReferencesTmp.begin(), valueReferencesTmp.end()); valueReferencesTmp = getAllValueReferencesUnrolled<string_type>(); it = stringValueIndices.end(); stringValueIndices.insert(it, valueReferencesTmp.begin(), valueReferencesTmp.end()); } } /* namespace FMI */ <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkRandom.h" #include "SkTArray.h" class SkOnce : SkNoncopyable { public: SkOnce() { fDidOnce = false; } bool needToDo() const { return !fDidOnce; } bool alreadyDone() const { return fDidOnce; } void accomplished() { SkASSERT(!fDidOnce); fDidOnce = true; } private: bool fDidOnce; }; namespace skiagm { class ConvexPathsGM : public GM { SkOnce fOnce; public: ConvexPathsGM() { this->setBGColor(0xFF000000); } protected: virtual SkString onShortName() { return SkString("convexpaths"); } virtual SkISize onISize() { return make_isize(1200, 1100); } void makePaths() { if (fOnce.alreadyDone()) { return; } fOnce.accomplished(); fPaths.push_back().moveTo(0, 0); fPaths.back().quadTo(50 * SK_Scalar1, 100 * SK_Scalar1, 0, 100 * SK_Scalar1); fPaths.back().lineTo(0, 0); fPaths.push_back().moveTo(0, 50 * SK_Scalar1); fPaths.back().quadTo(50 * SK_Scalar1, 0, 100 * SK_Scalar1, 50 * SK_Scalar1); fPaths.back().quadTo(50 * SK_Scalar1, 100 * SK_Scalar1, 0, 50 * SK_Scalar1); fPaths.push_back().addRect(0, 0, 100 * SK_Scalar1, 100 * SK_Scalar1, SkPath::kCW_Direction); fPaths.push_back().addRect(0, 0, 100 * SK_Scalar1, 100 * SK_Scalar1, SkPath::kCCW_Direction); fPaths.push_back().addCircle(50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, SkPath::kCW_Direction); fPaths.push_back().addOval(SkRect::MakeXYWH(0, 0, 50 * SK_Scalar1, 100 * SK_Scalar1), SkPath::kCW_Direction); fPaths.push_back().addOval(SkRect::MakeXYWH(0, 0, 100 * SK_Scalar1, 5 * SK_Scalar1), SkPath::kCCW_Direction); fPaths.push_back().addOval(SkRect::MakeXYWH(0, 0, SK_Scalar1, 100 * SK_Scalar1), SkPath::kCCW_Direction); fPaths.push_back().addRoundRect(SkRect::MakeXYWH(0, 0, SK_Scalar1 * 100, SK_Scalar1 * 100), 40 * SK_Scalar1, 20 * SK_Scalar1, SkPath::kCW_Direction); // large number of points enum { kLength = 100, kPtsPerSide = (1 << 12), }; fPaths.push_back().moveTo(0, 0); for (int i = 1; i < kPtsPerSide; ++i) { // skip the first point due to moveTo. fPaths.back().lineTo(kLength * SkIntToScalar(i) / kPtsPerSide, 0); } for (int i = 0; i < kPtsPerSide; ++i) { fPaths.back().lineTo(kLength, kLength * SkIntToScalar(i) / kPtsPerSide); } for (int i = kPtsPerSide; i > 0; --i) { fPaths.back().lineTo(kLength * SkIntToScalar(i) / kPtsPerSide, kLength); } for (int i = kPtsPerSide; i > 0; --i) { fPaths.back().lineTo(0, kLength * SkIntToScalar(i) / kPtsPerSide); } // shallow diagonals fPaths.push_back().lineTo(100 * SK_Scalar1, SK_Scalar1); fPaths.back().lineTo(98 * SK_Scalar1, 100 * SK_Scalar1); fPaths.back().lineTo(3 * SK_Scalar1, 96 * SK_Scalar1); fPaths.push_back().arcTo(SkRect::MakeXYWH(0, 0, 50 * SK_Scalar1, 100 * SK_Scalar1), 25 * SK_Scalar1, 130 * SK_Scalar1, false); // cubics fPaths.push_back().cubicTo( 1 * SK_Scalar1, 1 * SK_Scalar1, 10 * SK_Scalar1, 90 * SK_Scalar1, 0 * SK_Scalar1, 100 * SK_Scalar1); fPaths.push_back().cubicTo(100 * SK_Scalar1, 50 * SK_Scalar1, 20 * SK_Scalar1, 100 * SK_Scalar1, 0 * SK_Scalar1, 0 * SK_Scalar1); // path that has a cubic with a repeated first control point and // a repeated last control point. fPaths.push_back().moveTo(SK_Scalar1 * 10, SK_Scalar1 * 10); fPaths.back().cubicTo(10 * SK_Scalar1, 10 * SK_Scalar1, 10 * SK_Scalar1, 0, 20 * SK_Scalar1, 0); fPaths.back().lineTo(40 * SK_Scalar1, 0); fPaths.back().cubicTo(40 * SK_Scalar1, 0, 50 * SK_Scalar1, 0, 50 * SK_Scalar1, 10 * SK_Scalar1); // path that has two cubics with repeated middle control points. fPaths.push_back().moveTo(SK_Scalar1 * 10, SK_Scalar1 * 10); fPaths.back().cubicTo(10 * SK_Scalar1, 0, 10 * SK_Scalar1, 0, 20 * SK_Scalar1, 0); fPaths.back().lineTo(40 * SK_Scalar1, 0); fPaths.back().cubicTo(50 * SK_Scalar1, 0, 50 * SK_Scalar1, 0, 50 * SK_Scalar1, 10 * SK_Scalar1); // cubic where last three points are almost a line fPaths.push_back().moveTo(0, 228 * SK_Scalar1 / 8); fPaths.back().cubicTo(628 * SK_Scalar1 / 8, 82 * SK_Scalar1 / 8, 1255 * SK_Scalar1 / 8, 141 * SK_Scalar1 / 8, 1883 * SK_Scalar1 / 8, 202 * SK_Scalar1 / 8); // flat cubic where the at end point tangents both point outward. fPaths.push_back().moveTo(10 * SK_Scalar1, 0); fPaths.back().cubicTo(0, SK_Scalar1, 30 * SK_Scalar1, SK_Scalar1, 20 * SK_Scalar1, 0); // flat cubic where initial tangent is in, end tangent out fPaths.push_back().moveTo(0, 0 * SK_Scalar1); fPaths.back().cubicTo(10 * SK_Scalar1, SK_Scalar1, 30 * SK_Scalar1, SK_Scalar1, 20 * SK_Scalar1, 0); // flat cubic where initial tangent is out, end tangent in fPaths.push_back().moveTo(10 * SK_Scalar1, 0); fPaths.back().cubicTo(0, SK_Scalar1, 20 * SK_Scalar1, SK_Scalar1, 30 * SK_Scalar1, 0); // triangle where one edge is a degenerate quad fPaths.push_back().moveTo(SkFloatToScalar(8.59375f), 45 * SK_Scalar1); fPaths.back().quadTo(SkFloatToScalar(16.9921875f), 45 * SK_Scalar1, SkFloatToScalar(31.25f), 45 * SK_Scalar1); fPaths.back().lineTo(100 * SK_Scalar1, 100 * SK_Scalar1); fPaths.back().lineTo(SkFloatToScalar(8.59375f), 45 * SK_Scalar1); // triangle where one edge is a quad with a repeated point fPaths.push_back().moveTo(0, 25 * SK_Scalar1); fPaths.back().lineTo(50 * SK_Scalar1, 0); fPaths.back().quadTo(50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1); // triangle where one edge is a cubic with a 2x repeated point fPaths.push_back().moveTo(0, 25 * SK_Scalar1); fPaths.back().lineTo(50 * SK_Scalar1, 0); fPaths.back().cubicTo(50 * SK_Scalar1, 0, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1); // triangle where one edge is a quad with a nearly repeated point fPaths.push_back().moveTo(0, 25 * SK_Scalar1); fPaths.back().lineTo(50 * SK_Scalar1, 0); fPaths.back().quadTo(50 * SK_Scalar1, SkFloatToScalar(49.95f), 50 * SK_Scalar1, 50 * SK_Scalar1); // triangle where one edge is a cubic with a 3x nearly repeated point fPaths.push_back().moveTo(0, 25 * SK_Scalar1); fPaths.back().lineTo(50 * SK_Scalar1, 0); fPaths.back().cubicTo(50 * SK_Scalar1, SkFloatToScalar(49.95f), 50 * SK_Scalar1, SkFloatToScalar(49.97f), 50 * SK_Scalar1, 50 * SK_Scalar1); // triangle where there is a point degenerate cubic at one corner fPaths.push_back().moveTo(0, 25 * SK_Scalar1); fPaths.back().lineTo(50 * SK_Scalar1, 0); fPaths.back().lineTo(50 * SK_Scalar1, 50 * SK_Scalar1); fPaths.back().cubicTo(50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1); // point line fPaths.push_back().moveTo(50 * SK_Scalar1, 50 * SK_Scalar1); fPaths.back().lineTo(50 * SK_Scalar1, 50 * SK_Scalar1); // point quad fPaths.push_back().moveTo(50 * SK_Scalar1, 50 * SK_Scalar1); fPaths.back().quadTo(50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1); // point cubic fPaths.push_back().moveTo(50 * SK_Scalar1, 50 * SK_Scalar1); fPaths.back().cubicTo(50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1); // moveTo only paths fPaths.push_back().moveTo(0, 0); fPaths.back().moveTo(0, 0); fPaths.back().moveTo(SK_Scalar1, SK_Scalar1); fPaths.back().moveTo(SK_Scalar1, SK_Scalar1); fPaths.back().moveTo(10 * SK_Scalar1, 10 * SK_Scalar1); fPaths.push_back().moveTo(0, 0); fPaths.back().moveTo(0, 0); // line degenerate fPaths.push_back().lineTo(100 * SK_Scalar1, 100 * SK_Scalar1); fPaths.push_back().quadTo(100 * SK_Scalar1, 100 * SK_Scalar1, 0, 0); fPaths.push_back().quadTo(100 * SK_Scalar1, 100 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1); fPaths.push_back().quadTo(50 * SK_Scalar1, 50 * SK_Scalar1, 100 * SK_Scalar1, 100 * SK_Scalar1); fPaths.push_back().cubicTo(0, 0, 0, 0, 100 * SK_Scalar1, 100 * SK_Scalar1); // small circle. This is listed last so that it has device coords far // from the origin (small area relative to x,y values). fPaths.push_back().addCircle(0, 0, SkFloatToScalar(1.2f)); } virtual void onDraw(SkCanvas* canvas) { this->makePaths(); SkPaint paint; paint.setAntiAlias(true); SkRandom rand; canvas->translate(20 * SK_Scalar1, 20 * SK_Scalar1); // As we've added more paths this has gotten pretty big. Scale the whole thing down. canvas->scale(2 * SK_Scalar1 / 3, 2 * SK_Scalar1 / 3); for (int i = 0; i < fPaths.count(); ++i) { canvas->save(); // position the path, and make it at off-integer coords. canvas->translate(SK_Scalar1 * 200 * (i % 5) + SK_Scalar1 / 10, SK_Scalar1 * 200 * (i / 5) + 9 * SK_Scalar1 / 10); SkColor color = rand.nextU(); color |= 0xff000000; paint.setColor(color); SkASSERT(fPaths[i].isConvex()); canvas->drawPath(fPaths[i], paint); canvas->restore(); } } private: typedef GM INHERITED; SkTArray<SkPath> fPaths; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new ConvexPathsGM; } static GMRegistry reg(MyFactory); } <commit_msg>temporarily disable assert in convexpaths GM while it is debugged<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkRandom.h" #include "SkTArray.h" class SkOnce : SkNoncopyable { public: SkOnce() { fDidOnce = false; } bool needToDo() const { return !fDidOnce; } bool alreadyDone() const { return fDidOnce; } void accomplished() { SkASSERT(!fDidOnce); fDidOnce = true; } private: bool fDidOnce; }; namespace skiagm { class ConvexPathsGM : public GM { SkOnce fOnce; public: ConvexPathsGM() { this->setBGColor(0xFF000000); } protected: virtual SkString onShortName() { return SkString("convexpaths"); } virtual SkISize onISize() { return make_isize(1200, 1100); } void makePaths() { if (fOnce.alreadyDone()) { return; } fOnce.accomplished(); fPaths.push_back().moveTo(0, 0); fPaths.back().quadTo(50 * SK_Scalar1, 100 * SK_Scalar1, 0, 100 * SK_Scalar1); fPaths.back().lineTo(0, 0); fPaths.push_back().moveTo(0, 50 * SK_Scalar1); fPaths.back().quadTo(50 * SK_Scalar1, 0, 100 * SK_Scalar1, 50 * SK_Scalar1); fPaths.back().quadTo(50 * SK_Scalar1, 100 * SK_Scalar1, 0, 50 * SK_Scalar1); fPaths.push_back().addRect(0, 0, 100 * SK_Scalar1, 100 * SK_Scalar1, SkPath::kCW_Direction); fPaths.push_back().addRect(0, 0, 100 * SK_Scalar1, 100 * SK_Scalar1, SkPath::kCCW_Direction); fPaths.push_back().addCircle(50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, SkPath::kCW_Direction); fPaths.push_back().addOval(SkRect::MakeXYWH(0, 0, 50 * SK_Scalar1, 100 * SK_Scalar1), SkPath::kCW_Direction); fPaths.push_back().addOval(SkRect::MakeXYWH(0, 0, 100 * SK_Scalar1, 5 * SK_Scalar1), SkPath::kCCW_Direction); fPaths.push_back().addOval(SkRect::MakeXYWH(0, 0, SK_Scalar1, 100 * SK_Scalar1), SkPath::kCCW_Direction); fPaths.push_back().addRoundRect(SkRect::MakeXYWH(0, 0, SK_Scalar1 * 100, SK_Scalar1 * 100), 40 * SK_Scalar1, 20 * SK_Scalar1, SkPath::kCW_Direction); // large number of points enum { kLength = 100, kPtsPerSide = (1 << 12), }; fPaths.push_back().moveTo(0, 0); for (int i = 1; i < kPtsPerSide; ++i) { // skip the first point due to moveTo. fPaths.back().lineTo(kLength * SkIntToScalar(i) / kPtsPerSide, 0); } for (int i = 0; i < kPtsPerSide; ++i) { fPaths.back().lineTo(kLength, kLength * SkIntToScalar(i) / kPtsPerSide); } for (int i = kPtsPerSide; i > 0; --i) { fPaths.back().lineTo(kLength * SkIntToScalar(i) / kPtsPerSide, kLength); } for (int i = kPtsPerSide; i > 0; --i) { fPaths.back().lineTo(0, kLength * SkIntToScalar(i) / kPtsPerSide); } // shallow diagonals fPaths.push_back().lineTo(100 * SK_Scalar1, SK_Scalar1); fPaths.back().lineTo(98 * SK_Scalar1, 100 * SK_Scalar1); fPaths.back().lineTo(3 * SK_Scalar1, 96 * SK_Scalar1); fPaths.push_back().arcTo(SkRect::MakeXYWH(0, 0, 50 * SK_Scalar1, 100 * SK_Scalar1), 25 * SK_Scalar1, 130 * SK_Scalar1, false); // cubics fPaths.push_back().cubicTo( 1 * SK_Scalar1, 1 * SK_Scalar1, 10 * SK_Scalar1, 90 * SK_Scalar1, 0 * SK_Scalar1, 100 * SK_Scalar1); fPaths.push_back().cubicTo(100 * SK_Scalar1, 50 * SK_Scalar1, 20 * SK_Scalar1, 100 * SK_Scalar1, 0 * SK_Scalar1, 0 * SK_Scalar1); // path that has a cubic with a repeated first control point and // a repeated last control point. fPaths.push_back().moveTo(SK_Scalar1 * 10, SK_Scalar1 * 10); fPaths.back().cubicTo(10 * SK_Scalar1, 10 * SK_Scalar1, 10 * SK_Scalar1, 0, 20 * SK_Scalar1, 0); fPaths.back().lineTo(40 * SK_Scalar1, 0); fPaths.back().cubicTo(40 * SK_Scalar1, 0, 50 * SK_Scalar1, 0, 50 * SK_Scalar1, 10 * SK_Scalar1); // path that has two cubics with repeated middle control points. fPaths.push_back().moveTo(SK_Scalar1 * 10, SK_Scalar1 * 10); fPaths.back().cubicTo(10 * SK_Scalar1, 0, 10 * SK_Scalar1, 0, 20 * SK_Scalar1, 0); fPaths.back().lineTo(40 * SK_Scalar1, 0); fPaths.back().cubicTo(50 * SK_Scalar1, 0, 50 * SK_Scalar1, 0, 50 * SK_Scalar1, 10 * SK_Scalar1); // cubic where last three points are almost a line fPaths.push_back().moveTo(0, 228 * SK_Scalar1 / 8); fPaths.back().cubicTo(628 * SK_Scalar1 / 8, 82 * SK_Scalar1 / 8, 1255 * SK_Scalar1 / 8, 141 * SK_Scalar1 / 8, 1883 * SK_Scalar1 / 8, 202 * SK_Scalar1 / 8); // flat cubic where the at end point tangents both point outward. fPaths.push_back().moveTo(10 * SK_Scalar1, 0); fPaths.back().cubicTo(0, SK_Scalar1, 30 * SK_Scalar1, SK_Scalar1, 20 * SK_Scalar1, 0); // flat cubic where initial tangent is in, end tangent out fPaths.push_back().moveTo(0, 0 * SK_Scalar1); fPaths.back().cubicTo(10 * SK_Scalar1, SK_Scalar1, 30 * SK_Scalar1, SK_Scalar1, 20 * SK_Scalar1, 0); // flat cubic where initial tangent is out, end tangent in fPaths.push_back().moveTo(10 * SK_Scalar1, 0); fPaths.back().cubicTo(0, SK_Scalar1, 20 * SK_Scalar1, SK_Scalar1, 30 * SK_Scalar1, 0); // triangle where one edge is a degenerate quad fPaths.push_back().moveTo(SkFloatToScalar(8.59375f), 45 * SK_Scalar1); fPaths.back().quadTo(SkFloatToScalar(16.9921875f), 45 * SK_Scalar1, SkFloatToScalar(31.25f), 45 * SK_Scalar1); fPaths.back().lineTo(100 * SK_Scalar1, 100 * SK_Scalar1); fPaths.back().lineTo(SkFloatToScalar(8.59375f), 45 * SK_Scalar1); // triangle where one edge is a quad with a repeated point fPaths.push_back().moveTo(0, 25 * SK_Scalar1); fPaths.back().lineTo(50 * SK_Scalar1, 0); fPaths.back().quadTo(50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1); // triangle where one edge is a cubic with a 2x repeated point fPaths.push_back().moveTo(0, 25 * SK_Scalar1); fPaths.back().lineTo(50 * SK_Scalar1, 0); fPaths.back().cubicTo(50 * SK_Scalar1, 0, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1); // triangle where one edge is a quad with a nearly repeated point fPaths.push_back().moveTo(0, 25 * SK_Scalar1); fPaths.back().lineTo(50 * SK_Scalar1, 0); fPaths.back().quadTo(50 * SK_Scalar1, SkFloatToScalar(49.95f), 50 * SK_Scalar1, 50 * SK_Scalar1); // triangle where one edge is a cubic with a 3x nearly repeated point fPaths.push_back().moveTo(0, 25 * SK_Scalar1); fPaths.back().lineTo(50 * SK_Scalar1, 0); fPaths.back().cubicTo(50 * SK_Scalar1, SkFloatToScalar(49.95f), 50 * SK_Scalar1, SkFloatToScalar(49.97f), 50 * SK_Scalar1, 50 * SK_Scalar1); // triangle where there is a point degenerate cubic at one corner fPaths.push_back().moveTo(0, 25 * SK_Scalar1); fPaths.back().lineTo(50 * SK_Scalar1, 0); fPaths.back().lineTo(50 * SK_Scalar1, 50 * SK_Scalar1); fPaths.back().cubicTo(50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1); // point line fPaths.push_back().moveTo(50 * SK_Scalar1, 50 * SK_Scalar1); fPaths.back().lineTo(50 * SK_Scalar1, 50 * SK_Scalar1); // point quad fPaths.push_back().moveTo(50 * SK_Scalar1, 50 * SK_Scalar1); fPaths.back().quadTo(50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1); // point cubic fPaths.push_back().moveTo(50 * SK_Scalar1, 50 * SK_Scalar1); fPaths.back().cubicTo(50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1); // moveTo only paths fPaths.push_back().moveTo(0, 0); fPaths.back().moveTo(0, 0); fPaths.back().moveTo(SK_Scalar1, SK_Scalar1); fPaths.back().moveTo(SK_Scalar1, SK_Scalar1); fPaths.back().moveTo(10 * SK_Scalar1, 10 * SK_Scalar1); fPaths.push_back().moveTo(0, 0); fPaths.back().moveTo(0, 0); // line degenerate fPaths.push_back().lineTo(100 * SK_Scalar1, 100 * SK_Scalar1); fPaths.push_back().quadTo(100 * SK_Scalar1, 100 * SK_Scalar1, 0, 0); fPaths.push_back().quadTo(100 * SK_Scalar1, 100 * SK_Scalar1, 50 * SK_Scalar1, 50 * SK_Scalar1); fPaths.push_back().quadTo(50 * SK_Scalar1, 50 * SK_Scalar1, 100 * SK_Scalar1, 100 * SK_Scalar1); fPaths.push_back().cubicTo(0, 0, 0, 0, 100 * SK_Scalar1, 100 * SK_Scalar1); // small circle. This is listed last so that it has device coords far // from the origin (small area relative to x,y values). fPaths.push_back().addCircle(0, 0, SkFloatToScalar(1.2f)); } virtual void onDraw(SkCanvas* canvas) { this->makePaths(); SkPaint paint; paint.setAntiAlias(true); SkRandom rand; canvas->translate(20 * SK_Scalar1, 20 * SK_Scalar1); // As we've added more paths this has gotten pretty big. Scale the whole thing down. canvas->scale(2 * SK_Scalar1 / 3, 2 * SK_Scalar1 / 3); for (int i = 0; i < fPaths.count(); ++i) { canvas->save(); // position the path, and make it at off-integer coords. canvas->translate(SK_Scalar1 * 200 * (i % 5) + SK_Scalar1 / 10, SK_Scalar1 * 200 * (i / 5) + 9 * SK_Scalar1 / 10); SkColor color = rand.nextU(); color |= 0xff000000; paint.setColor(color); #if 0 // This hitting on 32bit Linux builds for some paths. Temporarily disabling while it is // debugged. SkASSERT(fPaths[i].isConvex()); #endif canvas->drawPath(fPaths[i], paint); canvas->restore(); } } private: typedef GM INHERITED; SkTArray<SkPath> fPaths; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new ConvexPathsGM; } static GMRegistry reg(MyFactory); } <|endoftext|>
<commit_before>#include "AlertDialog.h" #include "../cocos-wheels/CWCommon.h" USING_NS_CC; static const Color3B C3B_BLUE_THEME = Color3B(51, 204, 255); AlertDialog *AlertDialog::Builder::create() const { return AlertDialog::createWithBuilder(*this); } AlertDialog *AlertDialog::createWithBuilder(const Builder &builder) { AlertDialog *ret = new (std::nothrow) AlertDialog(); if (ret != nullptr && ret->initWithBuilder(builder)) { ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; } bool AlertDialog::initWithBuilder(const Builder &builder) { if (UNLIKELY(!Layer::init())) { return false; } _scene = builder._scene; _positiveCallback = builder._positiveCallback; _negativeCallback = builder._negativeCallback; _isCancelable = builder._isCancelable; _isCloseOnTouchOutside = builder._isCloseOnTouchOutside; Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); // 监听返回键 EventListenerKeyboard *keyboardListener = EventListenerKeyboard::create(); keyboardListener->onKeyReleased = [this](EventKeyboard::KeyCode keyCode, Event *event) { if (keyCode == EventKeyboard::KeyCode::KEY_BACK) { if (_isCancelable) { event->stopPropagation(); onNegativeButton(nullptr); } } }; _eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this); // 遮罩 this->addChild(LayerColor::create(Color4B(0, 0, 0, 127))); const float maxWidth1 = AlertDialog::maxWidth(); const float totalWidth = maxWidth1 + 10.0f; // 背景 LayerColor *background = LayerColor::create(Color4B::WHITE); this->addChild(background); background->setIgnoreAnchorPointForPosition(false); background->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height * 0.5f)); float totalHeight = 0.0f; const std::string &positiveTitle = builder._positiveTitle; const std::string &negativeTitle = builder._negativeTitle; if (!positiveTitle.empty() || !negativeTitle.empty()) { if (!negativeTitle.empty() && !positiveTitle.empty()) { ui::Button *button = ui::Button::create("source_material/btn_square_disabled.png", "source_material/btn_square_selected.png"); background->addChild(button); button->setScale9Enabled(true); button->setContentSize(Size(totalWidth * 0.5f, 30.0f)); button->setTitleFontSize(14); button->setTitleText(negativeTitle); button->setPosition(Vec2(totalWidth * 0.25f, 15.0f)); button->addClickEventListener(std::bind(&AlertDialog::onNegativeButton, this, std::placeholders::_1)); button = ui::Button::create("source_material/btn_square_highlighted.png", "source_material/btn_square_selected.png"); background->addChild(button); button->setScale9Enabled(true); button->setContentSize(Size(totalWidth * 0.5f, 30.0f)); button->setTitleFontSize(14); button->setTitleText(positiveTitle); button->setPosition(Vec2(totalWidth * 0.75f, 15.0f)); button->addClickEventListener(std::bind(&AlertDialog::onPositiveButton, this, std::placeholders::_1)); totalHeight += 30.0f; } else if (!positiveTitle.empty()) { // 分隔线 LayerColor *line = LayerColor::create(Color4B(227, 227, 227, 255), totalWidth, 2.0f); background->addChild(line); line->setPosition(Vec2(0.0f, totalHeight + 28.0f)); ui::Button *button = ui::Button::create("source_material/btn_square_highlighted.png", "source_material/btn_square_selected.png"); background->addChild(button); button->setScale9Enabled(true); button->setContentSize(Size(55.0f, 20.0f)); button->setTitleFontSize(12); button->setTitleText(positiveTitle); button->setPosition(Vec2(totalWidth * 0.5f, 14.0f)); button->addClickEventListener(std::bind(&AlertDialog::onPositiveButton, this, std::placeholders::_1)); totalHeight += 30.0f; } else if (!negativeTitle.empty()) { // 分隔线 LayerColor *line = LayerColor::create(Color4B(227, 227, 227, 255), totalWidth, 2.0f); background->addChild(line); line->setPosition(Vec2(0.0f, totalHeight + 28.0f)); ui::Button *button = ui::Button::create("source_material/btn_square_highlighted.png", "source_material/btn_square_selected.png"); background->addChild(button); button->setScale9Enabled(true); button->setContentSize(Size(55.0f, 20.0f)); button->setTitleFontSize(12); button->setTitleText(negativeTitle); button->setPosition(Vec2(totalWidth * 0.5f, 14.0f)); button->addClickEventListener(std::bind(&AlertDialog::onNegativeButton, this, std::placeholders::_1)); totalHeight += 30.0f; } } Node *node = builder._contentNode; if (node != nullptr) { totalHeight += 10.0f; Size nodeSize = node->getContentSize(); if (nodeSize.width > maxWidth1) { float scale = maxWidth1 / nodeSize.width; node->setScale(scale); nodeSize.width = maxWidth1; nodeSize.height *= scale; } // 传入的node background->addChild(node); node->setIgnoreAnchorPointForPosition(false); node->setAnchorPoint(Vec2::ANCHOR_MIDDLE); node->setPosition(Vec2(totalWidth * 0.5f, totalHeight + nodeSize.height * 0.5f)); totalHeight += nodeSize.height; } if (!builder._message.empty()) { totalHeight += 10.0f; Label *label = Label::createWithSystemFont(builder._message, "Arail", 12); label->setColor(Color3B::BLACK); if (label->getContentSize().width > maxWidth1) { // 当宽度超过时,设置范围,使文本换行 label->setDimensions(maxWidth1, 0.0f); } Size labelSize = label->getContentSize(); background->addChild(label); label->setPosition(Vec2(totalWidth * 0.5f, totalHeight + labelSize.height * 0.5f)); totalHeight += labelSize.height; } if (!builder._title.empty()) { totalHeight += 10.0f; // 分隔线 LayerColor *line = LayerColor::create(Color4B(227, 227, 227, 255), totalWidth, 2.0f); background->addChild(line); line->setPosition(Vec2(0.0f, totalHeight)); totalHeight += 2.0f; // 标题 Label *label = Label::createWithSystemFont(builder._title, "Arail", 14); label->setColor(C3B_BLUE_THEME); background->addChild(label); label->setPosition(Vec2(totalWidth * 0.5f, totalHeight + 15.0f)); cw::trimLabelStringWithEllipsisToFitWidth(label, totalWidth - 4.0f); totalHeight += 20.0f; } totalHeight += 10.0f; background->setContentSize(Size(totalWidth, totalHeight)); // 触摸监听,点击background以外的部分按按下取消键处理 EventListenerTouchOneByOne *touchListener = EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(true); touchListener->onTouchBegan = [this, background](Touch *touch, Event *event) { if (_isCloseOnTouchOutside) { Vec2 pos = this->convertTouchToNodeSpace(touch); if (background->getBoundingBox().containsPoint(pos)) { return true; } event->stopPropagation(); onNegativeButton(nullptr); } return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); _touchListener = touchListener; return true; } void AlertDialog::onPositiveButton(cocos2d::Ref *) { bool shouldDismiss = true; if (_positiveCallback) { this->retain(); shouldDismiss = _positiveCallback(this, BUTTON_POSITIVE); this->release(); } if (shouldDismiss) { this->dismiss(); } } void AlertDialog::onNegativeButton(cocos2d::Ref *) { bool shouldDismiss = true; if (_negativeCallback) { this->retain(); shouldDismiss = _negativeCallback(this, BUTTON_NEGATIVE); this->release(); } if (shouldDismiss) { this->dismiss(); } } <commit_msg>优化执行效率<commit_after>#include "AlertDialog.h" #include "../cocos-wheels/CWCommon.h" USING_NS_CC; static const Color3B C3B_BLUE_THEME = Color3B(51, 204, 255); AlertDialog *AlertDialog::Builder::create() const { return AlertDialog::createWithBuilder(*this); } AlertDialog *AlertDialog::createWithBuilder(const Builder &builder) { AlertDialog *ret = new (std::nothrow) AlertDialog(); if (ret != nullptr && ret->initWithBuilder(builder)) { ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; } bool AlertDialog::initWithBuilder(const Builder &builder) { if (UNLIKELY(!Layer::init())) { return false; } _scene = builder._scene; _positiveCallback = builder._positiveCallback; _negativeCallback = builder._negativeCallback; _isCancelable = builder._isCancelable; _isCloseOnTouchOutside = builder._isCloseOnTouchOutside; Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); // 监听返回键 EventListenerKeyboard *keyboardListener = EventListenerKeyboard::create(); keyboardListener->onKeyReleased = [this](EventKeyboard::KeyCode keyCode, Event *event) { if (keyCode == EventKeyboard::KeyCode::KEY_BACK) { if (_isCancelable) { event->stopPropagation(); onNegativeButton(nullptr); } } }; _eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this); // 遮罩 this->addChild(LayerColor::create(Color4B(0, 0, 0, 127))); const float maxWidth1 = AlertDialog::maxWidth(); const float totalWidth = maxWidth1 + 10.0f; // 背景 LayerColor *background = LayerColor::create(Color4B::WHITE); this->addChild(background); background->setIgnoreAnchorPointForPosition(false); background->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height * 0.5f)); float totalHeight = 0.0f; const std::string &positiveTitle = builder._positiveTitle; const std::string &negativeTitle = builder._negativeTitle; const bool positiveTitleEmpty = positiveTitle.empty(); const bool negativeTitleEmpty = negativeTitle.empty(); if (!positiveTitleEmpty || !negativeTitleEmpty) { if (!negativeTitleEmpty && !positiveTitleEmpty) { ui::Button *button = ui::Button::create("source_material/btn_square_disabled.png", "source_material/btn_square_selected.png"); background->addChild(button); button->setScale9Enabled(true); button->setContentSize(Size(totalWidth * 0.5f, 30.0f)); button->setTitleFontSize(14); button->setTitleText(negativeTitle); button->setPosition(Vec2(totalWidth * 0.25f, 15.0f)); button->addClickEventListener(std::bind(&AlertDialog::onNegativeButton, this, std::placeholders::_1)); button = ui::Button::create("source_material/btn_square_highlighted.png", "source_material/btn_square_selected.png"); background->addChild(button); button->setScale9Enabled(true); button->setContentSize(Size(totalWidth * 0.5f, 30.0f)); button->setTitleFontSize(14); button->setTitleText(positiveTitle); button->setPosition(Vec2(totalWidth * 0.75f, 15.0f)); button->addClickEventListener(std::bind(&AlertDialog::onPositiveButton, this, std::placeholders::_1)); totalHeight += 30.0f; } else if (!positiveTitleEmpty) { // 分隔线 LayerColor *line = LayerColor::create(Color4B(227, 227, 227, 255), totalWidth, 2.0f); background->addChild(line); line->setPosition(Vec2(0.0f, totalHeight + 28.0f)); ui::Button *button = ui::Button::create("source_material/btn_square_highlighted.png", "source_material/btn_square_selected.png"); background->addChild(button); button->setScale9Enabled(true); button->setContentSize(Size(55.0f, 20.0f)); button->setTitleFontSize(12); button->setTitleText(positiveTitle); button->setPosition(Vec2(totalWidth * 0.5f, 14.0f)); button->addClickEventListener(std::bind(&AlertDialog::onPositiveButton, this, std::placeholders::_1)); totalHeight += 30.0f; } else if (!negativeTitleEmpty) { // 分隔线 LayerColor *line = LayerColor::create(Color4B(227, 227, 227, 255), totalWidth, 2.0f); background->addChild(line); line->setPosition(Vec2(0.0f, totalHeight + 28.0f)); ui::Button *button = ui::Button::create("source_material/btn_square_highlighted.png", "source_material/btn_square_selected.png"); background->addChild(button); button->setScale9Enabled(true); button->setContentSize(Size(55.0f, 20.0f)); button->setTitleFontSize(12); button->setTitleText(negativeTitle); button->setPosition(Vec2(totalWidth * 0.5f, 14.0f)); button->addClickEventListener(std::bind(&AlertDialog::onNegativeButton, this, std::placeholders::_1)); totalHeight += 30.0f; } } Node *node = builder._contentNode; if (node != nullptr) { totalHeight += 10.0f; Size nodeSize = node->getContentSize(); if (nodeSize.width > maxWidth1) { float scale = maxWidth1 / nodeSize.width; node->setScale(scale); nodeSize.width = maxWidth1; nodeSize.height *= scale; } // 传入的node background->addChild(node); node->setIgnoreAnchorPointForPosition(false); node->setAnchorPoint(Vec2::ANCHOR_MIDDLE); node->setPosition(Vec2(totalWidth * 0.5f, totalHeight + nodeSize.height * 0.5f)); totalHeight += nodeSize.height; } if (!builder._message.empty()) { totalHeight += 10.0f; Label *label = Label::createWithSystemFont(builder._message, "Arail", 12); label->setColor(Color3B::BLACK); if (label->getContentSize().width > maxWidth1) { // 当宽度超过时,设置范围,使文本换行 label->setDimensions(maxWidth1, 0.0f); } Size labelSize = label->getContentSize(); background->addChild(label); label->setPosition(Vec2(totalWidth * 0.5f, totalHeight + labelSize.height * 0.5f)); totalHeight += labelSize.height; } if (!builder._title.empty()) { totalHeight += 10.0f; // 分隔线 LayerColor *line = LayerColor::create(Color4B(227, 227, 227, 255), totalWidth, 2.0f); background->addChild(line); line->setPosition(Vec2(0.0f, totalHeight)); totalHeight += 2.0f; // 标题 Label *label = Label::createWithSystemFont(builder._title, "Arail", 14); label->setColor(C3B_BLUE_THEME); background->addChild(label); label->setPosition(Vec2(totalWidth * 0.5f, totalHeight + 15.0f)); cw::trimLabelStringWithEllipsisToFitWidth(label, totalWidth - 4.0f); totalHeight += 20.0f; } totalHeight += 10.0f; background->setContentSize(Size(totalWidth, totalHeight)); // 触摸监听,点击background以外的部分按按下取消键处理 EventListenerTouchOneByOne *touchListener = EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(true); touchListener->onTouchBegan = [this, background](Touch *touch, Event *event) { if (_isCloseOnTouchOutside) { Vec2 pos = this->convertTouchToNodeSpace(touch); if (background->getBoundingBox().containsPoint(pos)) { return true; } event->stopPropagation(); onNegativeButton(nullptr); } return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); _touchListener = touchListener; return true; } void AlertDialog::onPositiveButton(cocos2d::Ref *) { bool shouldDismiss = true; if (_positiveCallback) { this->retain(); shouldDismiss = _positiveCallback(this, BUTTON_POSITIVE); this->release(); } if (shouldDismiss) { this->dismiss(); } } void AlertDialog::onNegativeButton(cocos2d::Ref *) { bool shouldDismiss = true; if (_negativeCallback) { this->retain(); shouldDismiss = _negativeCallback(this, BUTTON_NEGATIVE); this->release(); } if (shouldDismiss) { this->dismiss(); } } <|endoftext|>
<commit_before>// @(#)root/graf:$Name: $:$Id: TCutG.cxx,v 1.12 2002/03/26 07:05:57 brun Exp $ // Author: Rene Brun 16/05/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TCutG // // // // A Graphical cut. // // A TCutG object defines a closed polygon in a x,y plot. // // It can be created via the graphics editor option "CutG" // // or directly by invoking its constructor. // // To create a TCutG via the graphics editor, use the left button // // to select the points building the contour of the cut. Click on // // the right button to close the TCutG. // // When it is created via the graphics editor, the TCutG object // // is named "CUTG". It is recommended to immediatly change the name // // by using the context menu item "SetName". // // // When the graphics editor is used, the names of the variables X,Y // // are automatically taken from the current pad title. // // Example: // // Assume a TTree object T and: // // Root > T.Draw("abs(fMomemtum)%fEtot") // // the TCutG members fVarX, fVary will be set to: // // fVarx = fEtot // // fVary = abs(fMomemtum) // // // // A graphical cut can be used in a TTree selection expression: // // Root > T.Draw("fEtot","cutg1") // // where "cutg1" is the name of an existing graphical cut. // // // // Note that, as shown in the example above, a graphical cut may be // // used in a selection expression when drawing TTrees expressions // // of 1-d, 2-d or 3-dimensions. // // The expressions used in TTree::Draw can reference the variables // // in the fVarX, fVarY of the graphical cut plus other variables. // // // // When the TCutG object is created, it is added to the list of special// // objects in the main TROOT object pointed by gROOT. To retrieve a // // pointer to this object from the code or command line, do: // // TCutG *mycutg; // // mycutg = (TCutG*)gROOT->GetListOfSpecials()->FindObject("CUTG") // // mycutg->SetName("mycutg"); // // // // Example of use of a TCutG in TTree::Draw: // // tree.Draw("x:y","mycutg && z>0 %% sqrt(x)>1") // // // // A Graphical cut may be drawn via TGraph::Draw. // // It can be edited like a normal TGraph. // // // // A Graphical cut may be saved to a file via TCutG::Write. // // // // ////////////////////////////////////////////////////////////////////////// #include <string.h> #include "Riostream.h" #include "TROOT.h" #include "TCutG.h" #include "TVirtualPad.h" #include "TPaveText.h" ClassImp(TCutG) //______________________________________________________________________________ TCutG::TCutG() : TGraph() { fObjectX = 0; fObjectY = 0; } //______________________________________________________________________________ TCutG::TCutG(const char *name, Int_t n) :TGraph(n) { fObjectX = 0; fObjectY = 0; SetName(name); delete gROOT->GetListOfSpecials()->FindObject(name); gROOT->GetListOfSpecials()->Add(this); // Take name of cut variables from pad title if title contains ":" if (gPad) { TPaveText *ptitle = (TPaveText*)gPad->FindObject("title"); if (!ptitle) return; TText *ttitle = ptitle->GetLineWith(":"); if (!ttitle) ttitle = ptitle->GetLineWith("{"); if (!ttitle) ttitle = ptitle->GetLine(0); if (!ttitle) return; const char *title = ttitle->GetTitle(); Int_t nch = strlen(title); char *vars = new char[nch+1]; strcpy(vars,title); char *col = strstr(vars,":"); if (col) { *col = 0; col++; char *brak = strstr(col," {"); if (brak) *brak = 0; fVarY = vars; fVarX = col; } else { char *brak = strstr(vars," {"); if (brak) *brak = 0; fVarX = vars; } delete [] vars; } } //______________________________________________________________________________ TCutG::TCutG(const char *name, Int_t n, const Float_t *x, const Float_t *y) :TGraph(n,x,y) { fObjectX = 0; fObjectY = 0; SetName(name); delete gROOT->GetListOfSpecials()->FindObject(name); gROOT->GetListOfSpecials()->Add(this); // Take name of cut variables from pad title if title contains ":" if (gPad) { TPaveText *ptitle = (TPaveText*)gPad->FindObject("title"); if (!ptitle) return; TText *ttitle = ptitle->GetLineWith(":"); if (!ttitle) ttitle = ptitle->GetLineWith("{"); if (!ttitle) ttitle = ptitle->GetLine(0); if (!ttitle) return; const char *title = ttitle->GetTitle(); Int_t nch = strlen(title); char *vars = new char[nch+1]; strcpy(vars,title); char *col = strstr(vars,":"); if (col) { *col = 0; col++; char *brak = strstr(col," {"); if (brak) *brak = 0; fVarY = vars; fVarX = col; } else { char *brak = strstr(vars," {"); if (brak) *brak = 0; fVarX = vars; } delete [] vars; } } //______________________________________________________________________________ TCutG::TCutG(const char *name, Int_t n, const Double_t *x, const Double_t *y) :TGraph(n,x,y) { fObjectX = 0; fObjectY = 0; SetName(name); delete gROOT->GetListOfSpecials()->FindObject(name); gROOT->GetListOfSpecials()->Add(this); // Take name of cut variables from pad title if title contains ":" if (gPad) { TPaveText *ptitle = (TPaveText*)gPad->FindObject("title"); if (!ptitle) return; TText *ttitle = ptitle->GetLineWith(":"); if (!ttitle) ttitle = ptitle->GetLineWith("{"); if (!ttitle) ttitle = ptitle->GetLine(0); if (!ttitle) return; const char *title = ttitle->GetTitle(); Int_t nch = strlen(title); char *vars = new char[nch+1]; strcpy(vars,title); char *col = strstr(vars,":"); if (col) { *col = 0; col++; char *brak = strstr(col," {"); if (brak) *brak = 0; fVarY = vars; fVarX = col; } else { char *brak = strstr(vars," {"); if (brak) *brak = 0; fVarX = vars; } delete [] vars; } } //______________________________________________________________________________ TCutG::~TCutG() { delete fObjectX; delete fObjectY; gROOT->GetListOfSpecials()->Remove(this); } //______________________________________________________________________________ Int_t TCutG::IsInside(Double_t x, Double_t y) const { //*. Function which returns 1 if point x,y lies inside the //*. polygon defined by the graph points //*. 0 otherwise //*. //*. The loop is executed with the end-point coordinates of a //*. line segment (X1,Y1)-(X2,Y2) and the Y-coordinate of a //*. horizontal line. //*. The counter inter is incremented if the line (X1,Y1)-(X2,Y2) //*. intersects the horizontal line. //*. In this case XINT is set to the X-coordinate of the //*. intersection point. //*. If inter is an odd number, then the point x,y is within //*. the polygon. //*. //*. This routine is based on an original algorithm //*. developed by R.Nierhaus. //*. Double_t xint; Int_t i; Int_t inter = 0; for (i=0;i<fNpoints-1;i++) { if (fY[i] == fY[i+1]) continue; if (y <= fY[i] && y <= fY[i+1]) continue; if (fY[i] < y && fY[i+1] < y) continue; xint = fX[i] + (y-fY[i])*(fX[i+1]-fX[i])/(fY[i+1]-fY[i]); if (x < xint) inter++; } if (inter%2) return 1; return 0; } //______________________________________________________________________________ void TCutG::SavePrimitive(ofstream &out, Option_t *option) { // Save primitive as a C++ statement(s) on output stream out char quote = '"'; out<<" "<<endl; if (gROOT->ClassSaved(TCutG::Class())) { out<<" "; } else { out<<" TCutG *"; } out<<"cutg = new TCutG("<<quote<<GetName()<<quote<<","<<fNpoints<<");"<<endl; out<<" cutg->SetVarX("<<quote<<GetVarX()<<quote<<");"<<endl; out<<" cutg->SetVarY("<<quote<<GetVarY()<<quote<<");"<<endl; out<<" cutg->SetTitle("<<quote<<GetTitle()<<quote<<");"<<endl; SaveFillAttributes(out,"cutg",0,1001); SaveLineAttributes(out,"cutg",1,1,1); SaveMarkerAttributes(out,"cutg",1,1,1); for (Int_t i=0;i<fNpoints;i++) { out<<" cutg->SetPoint("<<i<<","<<fX[i]<<","<<fY[i]<<");"<<endl; } out<<" cutg->Draw(" <<quote<<option<<quote<<");"<<endl; } //______________________________________________________________________________ void TCutG::SetVarX(const char *varx) { fVarX = varx; delete fObjectX; fObjectX = 0; } //______________________________________________________________________________ void TCutG::SetVarY(const char *vary) { fVarY = vary; delete fObjectY; fObjectY = 0; } //______________________________________________________________________________ void TCutG::Streamer(TBuffer &R__b) { // Stream an object of class TCutG. if (R__b.IsReading()) { TCutG::Class()->ReadBuffer(R__b, this); gROOT->GetListOfSpecials()->Add(this); } else { TCutG::Class()->WriteBuffer(R__b, this); } } <commit_msg>Use new function TMath::IsInside in TCutG::IsInside<commit_after>// @(#)root/graf:$Name: $:$Id: TCutG.cxx,v 1.13 2002/07/15 16:23:39 brun Exp $ // Author: Rene Brun 16/05/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TCutG // // // // A Graphical cut. // // A TCutG object defines a closed polygon in a x,y plot. // // It can be created via the graphics editor option "CutG" // // or directly by invoking its constructor. // // To create a TCutG via the graphics editor, use the left button // // to select the points building the contour of the cut. Click on // // the right button to close the TCutG. // // When it is created via the graphics editor, the TCutG object // // is named "CUTG". It is recommended to immediatly change the name // // by using the context menu item "SetName". // // // When the graphics editor is used, the names of the variables X,Y // // are automatically taken from the current pad title. // // Example: // // Assume a TTree object T and: // // Root > T.Draw("abs(fMomemtum)%fEtot") // // the TCutG members fVarX, fVary will be set to: // // fVarx = fEtot // // fVary = abs(fMomemtum) // // // // A graphical cut can be used in a TTree selection expression: // // Root > T.Draw("fEtot","cutg1") // // where "cutg1" is the name of an existing graphical cut. // // // // Note that, as shown in the example above, a graphical cut may be // // used in a selection expression when drawing TTrees expressions // // of 1-d, 2-d or 3-dimensions. // // The expressions used in TTree::Draw can reference the variables // // in the fVarX, fVarY of the graphical cut plus other variables. // // // // When the TCutG object is created, it is added to the list of special// // objects in the main TROOT object pointed by gROOT. To retrieve a // // pointer to this object from the code or command line, do: // // TCutG *mycutg; // // mycutg = (TCutG*)gROOT->GetListOfSpecials()->FindObject("CUTG") // // mycutg->SetName("mycutg"); // // // // Example of use of a TCutG in TTree::Draw: // // tree.Draw("x:y","mycutg && z>0 %% sqrt(x)>1") // // // // A Graphical cut may be drawn via TGraph::Draw. // // It can be edited like a normal TGraph. // // // // A Graphical cut may be saved to a file via TCutG::Write. // // // // ////////////////////////////////////////////////////////////////////////// #include <string.h> #include "Riostream.h" #include "TROOT.h" #include "TCutG.h" #include "TVirtualPad.h" #include "TPaveText.h" ClassImp(TCutG) //______________________________________________________________________________ TCutG::TCutG() : TGraph() { fObjectX = 0; fObjectY = 0; } //______________________________________________________________________________ TCutG::TCutG(const char *name, Int_t n) :TGraph(n) { fObjectX = 0; fObjectY = 0; SetName(name); delete gROOT->GetListOfSpecials()->FindObject(name); gROOT->GetListOfSpecials()->Add(this); // Take name of cut variables from pad title if title contains ":" if (gPad) { TPaveText *ptitle = (TPaveText*)gPad->FindObject("title"); if (!ptitle) return; TText *ttitle = ptitle->GetLineWith(":"); if (!ttitle) ttitle = ptitle->GetLineWith("{"); if (!ttitle) ttitle = ptitle->GetLine(0); if (!ttitle) return; const char *title = ttitle->GetTitle(); Int_t nch = strlen(title); char *vars = new char[nch+1]; strcpy(vars,title); char *col = strstr(vars,":"); if (col) { *col = 0; col++; char *brak = strstr(col," {"); if (brak) *brak = 0; fVarY = vars; fVarX = col; } else { char *brak = strstr(vars," {"); if (brak) *brak = 0; fVarX = vars; } delete [] vars; } } //______________________________________________________________________________ TCutG::TCutG(const char *name, Int_t n, const Float_t *x, const Float_t *y) :TGraph(n,x,y) { fObjectX = 0; fObjectY = 0; SetName(name); delete gROOT->GetListOfSpecials()->FindObject(name); gROOT->GetListOfSpecials()->Add(this); // Take name of cut variables from pad title if title contains ":" if (gPad) { TPaveText *ptitle = (TPaveText*)gPad->FindObject("title"); if (!ptitle) return; TText *ttitle = ptitle->GetLineWith(":"); if (!ttitle) ttitle = ptitle->GetLineWith("{"); if (!ttitle) ttitle = ptitle->GetLine(0); if (!ttitle) return; const char *title = ttitle->GetTitle(); Int_t nch = strlen(title); char *vars = new char[nch+1]; strcpy(vars,title); char *col = strstr(vars,":"); if (col) { *col = 0; col++; char *brak = strstr(col," {"); if (brak) *brak = 0; fVarY = vars; fVarX = col; } else { char *brak = strstr(vars," {"); if (brak) *brak = 0; fVarX = vars; } delete [] vars; } } //______________________________________________________________________________ TCutG::TCutG(const char *name, Int_t n, const Double_t *x, const Double_t *y) :TGraph(n,x,y) { fObjectX = 0; fObjectY = 0; SetName(name); delete gROOT->GetListOfSpecials()->FindObject(name); gROOT->GetListOfSpecials()->Add(this); // Take name of cut variables from pad title if title contains ":" if (gPad) { TPaveText *ptitle = (TPaveText*)gPad->FindObject("title"); if (!ptitle) return; TText *ttitle = ptitle->GetLineWith(":"); if (!ttitle) ttitle = ptitle->GetLineWith("{"); if (!ttitle) ttitle = ptitle->GetLine(0); if (!ttitle) return; const char *title = ttitle->GetTitle(); Int_t nch = strlen(title); char *vars = new char[nch+1]; strcpy(vars,title); char *col = strstr(vars,":"); if (col) { *col = 0; col++; char *brak = strstr(col," {"); if (brak) *brak = 0; fVarY = vars; fVarX = col; } else { char *brak = strstr(vars," {"); if (brak) *brak = 0; fVarX = vars; } delete [] vars; } } //______________________________________________________________________________ TCutG::~TCutG() { delete fObjectX; delete fObjectY; gROOT->GetListOfSpecials()->Remove(this); } //______________________________________________________________________________ Int_t TCutG::IsInside(Double_t x, Double_t y) const { //*. Function which returns 1 if point x,y lies inside the //*. polygon defined by the graph points //*. 0 otherwise //*. //*. The loop is executed with the end-point coordinates of a //*. line segment (X1,Y1)-(X2,Y2) and the Y-coordinate of a //*. horizontal line. //*. The counter inter is incremented if the line (X1,Y1)-(X2,Y2) //*. intersects the horizontal line. //*. In this case XINT is set to the X-coordinate of the //*. intersection point. //*. If inter is an odd number, then the point x,y is within //*. the polygon. //*. //*. This routine is based on an original algorithm //*. developed by R.Nierhaus. //*. return (Int_t)TMath::IsInside(x,y,fNpoints,fX,fY); } //______________________________________________________________________________ void TCutG::SavePrimitive(ofstream &out, Option_t *option) { // Save primitive as a C++ statement(s) on output stream out char quote = '"'; out<<" "<<endl; if (gROOT->ClassSaved(TCutG::Class())) { out<<" "; } else { out<<" TCutG *"; } out<<"cutg = new TCutG("<<quote<<GetName()<<quote<<","<<fNpoints<<");"<<endl; out<<" cutg->SetVarX("<<quote<<GetVarX()<<quote<<");"<<endl; out<<" cutg->SetVarY("<<quote<<GetVarY()<<quote<<");"<<endl; out<<" cutg->SetTitle("<<quote<<GetTitle()<<quote<<");"<<endl; SaveFillAttributes(out,"cutg",0,1001); SaveLineAttributes(out,"cutg",1,1,1); SaveMarkerAttributes(out,"cutg",1,1,1); for (Int_t i=0;i<fNpoints;i++) { out<<" cutg->SetPoint("<<i<<","<<fX[i]<<","<<fY[i]<<");"<<endl; } out<<" cutg->Draw(" <<quote<<option<<quote<<");"<<endl; } //______________________________________________________________________________ void TCutG::SetVarX(const char *varx) { fVarX = varx; delete fObjectX; fObjectX = 0; } //______________________________________________________________________________ void TCutG::SetVarY(const char *vary) { fVarY = vary; delete fObjectY; fObjectY = 0; } //______________________________________________________________________________ void TCutG::Streamer(TBuffer &R__b) { // Stream an object of class TCutG. if (R__b.IsReading()) { TCutG::Class()->ReadBuffer(R__b, this); gROOT->GetListOfSpecials()->Add(this); } else { TCutG::Class()->WriteBuffer(R__b, this); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkTransformIOBase.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkTransformIOBase.h" #include "itkTransformFactoryBase.h" #include <iostream> #include <fstream> #include <string> namespace itk { TransformIOBase:: TransformIOBase() { this->m_AppendMode = false; } TransformIOBase:: ~TransformIOBase() { } void TransformIOBase:: CreateTransform(TransformPointer &ptr, const std::string &ClassName) { // Instantiate the transform itkDebugMacro ( "About to call ObjectFactory" ); LightObject::Pointer i; i = ObjectFactoryBase::CreateInstance ( ClassName.c_str() ); itkDebugMacro ( "After call ObjectFactory"); ptr = dynamic_cast<TransformBase*> ( i.GetPointer() ); if ( ptr.IsNull() ) { OStringStream msg; msg << "Could not create an instance of " << ClassName << std::endl << "The usual cause of this error is not registering the " << "transform with TransformFactory" << std::endl; msg << "Currently registered Transforms: " << std::endl; std::list<std::string> names = TransformFactoryBase::GetFactory()->GetClassOverrideWithNames(); std::list<std::string>::iterator it; for ( it = names.begin(); it != names.end(); it++ ) { msg << "\t\"" << *it << "\"" << std::endl; } itkExceptionMacro ( << msg.str() ); } } void TransformIOBase ::OpenStream(std::ofstream &out, bool binary) { #ifdef __sgi // Create the file. This is required on some older sgi's if (this->m_AppendMode) { std::ofstream tFile(m_FileName.c_str(),std::ios::out | std::ios::app); tFile.close(); } else { std::ofstream tFile(m_FileName.c_str(),std::ios::out); tFile.close(); } #endif std::ios::openmode mode(std::ios::out); if(binary) { mode |= std::ios::binary; } if (this->m_AppendMode) { mode |= std::ios::app; } out.open(m_FileName.c_str(), mode); } void TransformIOBase::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "FileName: " << m_FileName << std::endl; os << indent << "AppendMode: " << (m_AppendMode ? "true" : "false") << std::endl; if(m_ReadTransformList.size() > 0) { os << indent << "ReadTransformList: " << std::endl; for(TransformListType::Iterator it = m_ReadTransformList.begin(); it != m_ReadTransformList.end(); it++) { os << (*it)->PrintSelf(os,indent.GetNextIndent()); } } if(m_WriteTransformList.size() > 0) { os << indent << "WriteTransformList: " << std::endl; for(ConstTransformListType::Iterator it = m_WriteTransformList.begin(); it != m_WriteTransformList.end(); it++) { os << (*it)->PrintSelf(os,indent.GetNextIndent()); } } } } // itk <commit_msg>COMP: type<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkTransformIOBase.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkTransformIOBase.h" #include "itkTransformFactoryBase.h" #include <iostream> #include <fstream> #include <string> namespace itk { TransformIOBase:: TransformIOBase() { this->m_AppendMode = false; } TransformIOBase:: ~TransformIOBase() { } void TransformIOBase:: CreateTransform(TransformPointer &ptr, const std::string &ClassName) { // Instantiate the transform itkDebugMacro ( "About to call ObjectFactory" ); LightObject::Pointer i; i = ObjectFactoryBase::CreateInstance ( ClassName.c_str() ); itkDebugMacro ( "After call ObjectFactory"); ptr = dynamic_cast<TransformBase*> ( i.GetPointer() ); if ( ptr.IsNull() ) { OStringStream msg; msg << "Could not create an instance of " << ClassName << std::endl << "The usual cause of this error is not registering the " << "transform with TransformFactory" << std::endl; msg << "Currently registered Transforms: " << std::endl; std::list<std::string> names = TransformFactoryBase::GetFactory()->GetClassOverrideWithNames(); std::list<std::string>::iterator it; for ( it = names.begin(); it != names.end(); it++ ) { msg << "\t\"" << *it << "\"" << std::endl; } itkExceptionMacro ( << msg.str() ); } } void TransformIOBase ::OpenStream(std::ofstream &out, bool binary) { #ifdef __sgi // Create the file. This is required on some older sgi's if (this->m_AppendMode) { std::ofstream tFile(m_FileName.c_str(),std::ios::out | std::ios::app); tFile.close(); } else { std::ofstream tFile(m_FileName.c_str(),std::ios::out); tFile.close(); } #endif std::ios::openmode mode(std::ios::out); if(binary) { mode |= std::ios::binary; } if (this->m_AppendMode) { mode |= std::ios::app; } out.open(m_FileName.c_str(), mode); } void TransformIOBase::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "FileName: " << m_FileName << std::endl; os << indent << "AppendMode: " << (m_AppendMode ? "true" : "false") << std::endl; if(m_ReadTransformList.size() > 0) { os << indent << "ReadTransformList: " << std::endl; for(TransformListType::iterator it = m_ReadTransformList.begin(); it != m_ReadTransformList.end(); it++) { os << (*it)->PrintSelf(os,indent.GetNextIndent()); } } if(m_WriteTransformList.size() > 0) { os << indent << "WriteTransformList: " << std::endl; for(ConstTransformListType::iterator it = m_WriteTransformList.begin(); it != m_WriteTransformList.end(); it++) { os << (*it)->PrintSelf(os,indent.GetNextIndent()); } } } } // itk <|endoftext|>
<commit_before>/* * * Copyright 2015 gRPC 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 <stdio.h> #include <string.h> #include <grpc/byte_buffer.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "test/core/end2end/cq_verifier.h" #include "test/core/end2end/end2end_tests.h" static void* tag(intptr_t t) { return reinterpret_cast<void*>(t); } static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config, const char* test_name, grpc_channel_args* client_args, grpc_channel_args* server_args) { grpc_end2end_test_fixture f; gpr_log(GPR_INFO, "Running test: %s/%s", test_name, config.name); f = config.create_fixture(client_args, server_args); config.init_server(&f, server_args); config.init_client(&f, client_args); return f; } static gpr_timespec n_seconds_from_now(int n) { return grpc_timeout_seconds_to_deadline(n); } static gpr_timespec five_seconds_from_now(void) { return n_seconds_from_now(5); } static void drain_cq(grpc_completion_queue* cq) { grpc_event ev; do { ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr); } while (ev.type != GRPC_QUEUE_SHUTDOWN); } static void shutdown_client(grpc_end2end_test_fixture* f) { if (!f->client) return; grpc_channel_destroy(f->client); f->client = nullptr; } static void end_test(grpc_end2end_test_fixture* f) { shutdown_client(f); grpc_completion_queue_shutdown(f->cq); drain_cq(f->cq); grpc_completion_queue_destroy(f->cq); } static void test_early_server_shutdown_finishes_tags( grpc_end2end_test_config config) { grpc_end2end_test_fixture f = begin_test( config, "test_early_server_shutdown_finishes_tags", nullptr, nullptr); cq_verifier* cqv = cq_verifier_create(f.cq); grpc_call* s = reinterpret_cast<grpc_call*>(1); grpc_call_details call_details; grpc_metadata_array request_metadata_recv; grpc_metadata_array_init(&request_metadata_recv); grpc_call_details_init(&call_details); /* upon shutdown, the server should finish all requested calls indicating no new call */ GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call( f.server, &s, &call_details, &request_metadata_recv, f.cq, f.cq, tag(101))); grpc_server_shutdown_and_notify(f.server, f.cq, tag(1000)); CQ_EXPECT_COMPLETION(cqv, tag(101), 0); CQ_EXPECT_COMPLETION(cqv, tag(1000), 1); cq_verify(cqv); GPR_ASSERT(s == nullptr); grpc_server_destroy(f.server); end_test(&f); config.tear_down_data(&f); cq_verifier_destroy(cqv); } void shutdown_finishes_tags(grpc_end2end_test_config config) { test_early_server_shutdown_finishes_tags(config); } void shutdown_finishes_tags_pre_init(void) {} <commit_msg>GracefulGoaway: Fix shutdown_finishes_tags test (#29091)<commit_after>/* * * Copyright 2015 gRPC 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 <stdio.h> #include <string.h> #include <grpc/byte_buffer.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "test/core/end2end/cq_verifier.h" #include "test/core/end2end/end2end_tests.h" static void* tag(intptr_t t) { return reinterpret_cast<void*>(t); } static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config, const char* test_name, grpc_channel_args* client_args, grpc_channel_args* server_args) { grpc_end2end_test_fixture f; gpr_log(GPR_INFO, "Running test: %s/%s", test_name, config.name); f = config.create_fixture(client_args, server_args); config.init_server(&f, server_args); config.init_client(&f, client_args); return f; } static gpr_timespec n_seconds_from_now(int n) { return grpc_timeout_seconds_to_deadline(n); } static gpr_timespec five_seconds_from_now(void) { return n_seconds_from_now(5); } static void drain_cq(grpc_completion_queue* cq) { grpc_event ev; do { ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr); } while (ev.type != GRPC_QUEUE_SHUTDOWN); } static void shutdown_client(grpc_end2end_test_fixture* f) { if (!f->client) return; grpc_channel_destroy(f->client); f->client = nullptr; } static void end_test(grpc_end2end_test_fixture* f) { grpc_completion_queue_shutdown(f->cq); drain_cq(f->cq); grpc_completion_queue_destroy(f->cq); } static void test_early_server_shutdown_finishes_tags( grpc_end2end_test_config config) { grpc_end2end_test_fixture f = begin_test( config, "test_early_server_shutdown_finishes_tags", nullptr, nullptr); cq_verifier* cqv = cq_verifier_create(f.cq); grpc_call* s = reinterpret_cast<grpc_call*>(1); grpc_call_details call_details; grpc_metadata_array request_metadata_recv; grpc_metadata_array_init(&request_metadata_recv); grpc_call_details_init(&call_details); /* upon shutdown, the server should finish all requested calls indicating no new call */ GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call( f.server, &s, &call_details, &request_metadata_recv, f.cq, f.cq, tag(101))); shutdown_client(&f); grpc_server_shutdown_and_notify(f.server, f.cq, tag(1000)); CQ_EXPECT_COMPLETION(cqv, tag(101), 0); CQ_EXPECT_COMPLETION(cqv, tag(1000), 1); cq_verify(cqv); GPR_ASSERT(s == nullptr); grpc_server_destroy(f.server); end_test(&f); config.tear_down_data(&f); cq_verifier_destroy(cqv); } void shutdown_finishes_tags(grpc_end2end_test_config config) { test_early_server_shutdown_finishes_tags(config); } void shutdown_finishes_tags_pre_init(void) {} <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 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 "CodeUnitPart.h" #include "CodeUnit.h" #include "Export/src/tree/CompositeFragment.h" #include "OOModel/src/allOOModelNodes.h" #include "OOModel/src/types/ClassType.h" #include "OOModel/src/types/PointerType.h" #include "OOModel/src/types/ReferenceType.h" namespace CppExport { CodeUnitPart::CodeUnitPart(CodeUnit* parent) : parent_{parent} {} bool CodeUnitPart::isSourceFragmentEmpty() const { if (!fragment_) return true; QList<Export::SourceFragment*> workList{fragment_}; while (!workList.empty()) { auto current = workList.takeLast(); if (dynamic_cast<Export::TextFragment*>(current)) return false; else if (auto compositeFragment = dynamic_cast<Export::CompositeFragment*>(current)) workList << compositeFragment->fragments(); } return true; } void CodeUnitPart::setFragment(Export::SourceFragment* sourceFragment) { fragment_ = sourceFragment; // calculate name and reference nodes nameNodes_.clear(); referenceNodes_.clear(); QList<Export::SourceFragment*> workStack{sourceFragment}; while (!workStack.empty()) { auto fragment = workStack.takeLast(); auto node = fragment->node(); if (node->definesSymbol()) nameNodes_.insert(node); else if (auto reference = DCast<OOModel::ReferenceExpression>(node)) referenceNodes_.insert(reference); if (auto compositeFragment = dynamic_cast<Export::CompositeFragment*>(fragment)) workStack << compositeFragment->fragments(); } // calculate targets softTargets_.clear(); hardTargets_.clear(); for (auto reference : referenceNodes_) if (auto target = fixedTarget(reference)) { if (isNameOnlyDependency(reference)) softTargets_.insert(target); else { auto parentMethodCall = DCast<OOModel::MethodCallExpression>(reference->parent()); auto prefixReference = DCast<OOModel::ReferenceExpression>(reference->prefix()); if (!parentMethodCall || !prefixReference || prefixReference->typeArguments()->isEmpty()) hardTargets_.insert(target); // member access if (parentMethodCall || DCast<OOModel::ReferenceExpression>(reference->parent())) { const OOModel::Type* baseType{}; if (parentMethodCall && parentMethodCall->callee()->isAncestorOf(reference)) baseType = parentMethodCall->type(); else baseType = reference->type(); auto finalType = baseType; if (auto pointerType = dynamic_cast<const OOModel::PointerType*>(baseType)) finalType = pointerType->baseType(); else if (auto referenceType = dynamic_cast<const OOModel::ReferenceType*>(baseType)) finalType = referenceType->baseType(); if (auto classType = dynamic_cast<const OOModel::ClassType*>(finalType)) hardTargets_.insert(classType->classDefinition()); SAFE_DELETE(baseType); } } } } bool CodeUnitPart::isNameOnlyDependency(OOModel::ReferenceExpression* reference) { auto parent = reference->parent(); Q_ASSERT(parent); if (DCast<OOModel::ExplicitTemplateInstantiation>(parent)) return false; else if (reference->firstAncestorOfType<OOModel::ExplicitTemplateInstantiation>()) return true; auto parentClass = reference->firstAncestorOfType<OOModel::Class>(); if (reference->firstAncestorOfType<OOModel::MethodCallExpression>() && !reference->typeArguments()->isEmpty() && parentClass && !parentClass->typeArguments()->isEmpty()) return true; if (reference->firstAncestorOfType<OOModel::MethodCallExpression>()) return false; if (DCast<OOModel::TypeQualifierExpression>(parent)) parent = parent->parent(); if (!DCast<OOModel::PointerTypeExpression>(parent) && !DCast<OOModel::ReferenceTypeExpression>(parent)) return false; if (auto tryCatchFinally = reference->firstAncestorOfType<OOModel::TryCatchFinallyStatement>()) if (tryCatchFinally->catchClauses()->isAncestorOf(reference)) return false; return true; } Model::Node* CodeUnitPart::fixedTarget(OOModel::ReferenceExpression* referenceExpression) { if (auto target = referenceExpression->target()) return target; // insert custom resolution adjustments here return nullptr; } void CodeUnitPart::calculateDependencies(QList<CodeUnit*>& allUnits) { if (DCast<OOModel::MetaDefinition>(parent_->node())) return; dependencies_.clear(); if (this == parent()->sourcePart()) dependencies_.insert(parent()->headerPart()); for (auto target : hardTargets_) for (auto unit : allUnits) if (unit->headerPart() != this && unit->headerPart()->nameNodes().contains(target)) dependencies_.insert(unit->headerPart()); } QSet<CodeUnitPart*> CodeUnitPart::sourceDependencies(QList<CodeUnit*> units) { QSet<CodeUnitPart*> result; for (auto referenceNode : referenceNodes_) if (auto target = referenceNode->target()) for (auto unit : units) if (unit->sourcePart() != this && unit->sourcePart()->nameNodes().contains(target)) result.insert(unit->sourcePart()); return result; } } <commit_msg>make explicit template instantiation ignore file internal order<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 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 "CodeUnitPart.h" #include "CodeUnit.h" #include "Export/src/tree/CompositeFragment.h" #include "OOModel/src/allOOModelNodes.h" #include "OOModel/src/types/ClassType.h" #include "OOModel/src/types/PointerType.h" #include "OOModel/src/types/ReferenceType.h" namespace CppExport { CodeUnitPart::CodeUnitPart(CodeUnit* parent) : parent_{parent} {} bool CodeUnitPart::isSourceFragmentEmpty() const { if (!fragment_) return true; QList<Export::SourceFragment*> workList{fragment_}; while (!workList.empty()) { auto current = workList.takeLast(); if (dynamic_cast<Export::TextFragment*>(current)) return false; else if (auto compositeFragment = dynamic_cast<Export::CompositeFragment*>(current)) workList << compositeFragment->fragments(); } return true; } void CodeUnitPart::setFragment(Export::SourceFragment* sourceFragment) { fragment_ = sourceFragment; // calculate name and reference nodes nameNodes_.clear(); referenceNodes_.clear(); QList<Export::SourceFragment*> workStack{sourceFragment}; while (!workStack.empty()) { auto fragment = workStack.takeLast(); auto node = fragment->node(); if (node->definesSymbol()) nameNodes_.insert(node); else if (auto reference = DCast<OOModel::ReferenceExpression>(node)) referenceNodes_.insert(reference); if (auto compositeFragment = dynamic_cast<Export::CompositeFragment*>(fragment)) workStack << compositeFragment->fragments(); } // calculate targets softTargets_.clear(); hardTargets_.clear(); for (auto reference : referenceNodes_) if (auto target = fixedTarget(reference)) { if (isNameOnlyDependency(reference)) softTargets_.insert(target); else { auto parentMethodCall = DCast<OOModel::MethodCallExpression>(reference->parent()); auto prefixReference = DCast<OOModel::ReferenceExpression>(reference->prefix()); if (!parentMethodCall || !prefixReference || prefixReference->typeArguments()->isEmpty()) hardTargets_.insert(target); // member access if (parentMethodCall || DCast<OOModel::ReferenceExpression>(reference->parent())) { const OOModel::Type* baseType{}; if (parentMethodCall && parentMethodCall->callee()->isAncestorOf(reference)) baseType = parentMethodCall->type(); else baseType = reference->type(); auto finalType = baseType; if (auto pointerType = dynamic_cast<const OOModel::PointerType*>(baseType)) finalType = pointerType->baseType(); else if (auto referenceType = dynamic_cast<const OOModel::ReferenceType*>(baseType)) finalType = referenceType->baseType(); if (auto classType = dynamic_cast<const OOModel::ClassType*>(finalType)) hardTargets_.insert(classType->classDefinition()); SAFE_DELETE(baseType); } } } } bool CodeUnitPart::isNameOnlyDependency(OOModel::ReferenceExpression* reference) { auto parent = reference->parent(); Q_ASSERT(parent); if (DCast<OOModel::ExplicitTemplateInstantiation>(parent)) return false; else if (reference->firstAncestorOfType<OOModel::ExplicitTemplateInstantiation>()) return true; auto parentClass = reference->firstAncestorOfType<OOModel::Class>(); if (reference->firstAncestorOfType<OOModel::MethodCallExpression>() && !reference->typeArguments()->isEmpty() && parentClass && !parentClass->typeArguments()->isEmpty()) return true; if (reference->firstAncestorOfType<OOModel::MethodCallExpression>()) return false; if (DCast<OOModel::TypeQualifierExpression>(parent)) parent = parent->parent(); if (!DCast<OOModel::PointerTypeExpression>(parent) && !DCast<OOModel::ReferenceTypeExpression>(parent)) return false; if (auto tryCatchFinally = reference->firstAncestorOfType<OOModel::TryCatchFinallyStatement>()) if (tryCatchFinally->catchClauses()->isAncestorOf(reference)) return false; return true; } Model::Node* CodeUnitPart::fixedTarget(OOModel::ReferenceExpression* referenceExpression) { if (auto target = referenceExpression->target()) return target; // insert custom resolution adjustments here return nullptr; } void CodeUnitPart::calculateDependencies(QList<CodeUnit*>& allUnits) { if (DCast<OOModel::MetaDefinition>(parent_->node())) return; dependencies_.clear(); if (this == parent()->sourcePart()) dependencies_.insert(parent()->headerPart()); for (auto target : hardTargets_) for (auto unit : allUnits) if (unit->headerPart() != this && unit->headerPart()->nameNodes().contains(target)) dependencies_.insert(unit->headerPart()); } QSet<CodeUnitPart*> CodeUnitPart::sourceDependencies(QList<CodeUnit*> units) { QSet<CodeUnitPart*> result; for (auto referenceNode : referenceNodes_) if (!referenceNode->firstAncestorOfType<OOModel::ExplicitTemplateInstantiation>()) if (auto target = referenceNode->target()) for (auto unit : units) if (unit->sourcePart() != this && unit->sourcePart()->nameNodes().contains(target)) result.insert(unit->sourcePart()); return result; } } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // bootstrap.cpp // // Identification: src/backend/bridge/ddl/bootstrap.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <iostream> #include "backend/bridge/ddl/bootstrap.h" #include "backend/storage/database.h" #include "backend/common/logger.h" namespace peloton { namespace bridge { /** * @brief This function constructs all the user-defined tables and indices in * all databases * @return true or false, depending on whether we could bootstrap. */ bool Bootstrap::BootstrapPeloton(void) { raw_database_info raw_database(MyDatabaseId); raw_database.CollectRawTableAndIndex(); raw_database.CollectRawForeignKeys(); // create the database with current database id elog(DEBUG5, "Initializing database %s(%u) in Peloton", raw_database.GetDbName().c_str(), raw_database.GetDbOid()); bool status = raw_database.CreateDatabase(); // skip if we already initialize current database if (status == false) return false; // Create objects in Peloton raw_database.CreateTables(); raw_database.CreateIndexes(); raw_database.CreateForeignkeys(); //auto &manager = catalog::Manager::GetInstance(); // TODO: Update stats //auto db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid()); //db->UpdateStats(peloton_status, false); // Verbose mode //std::cout << "Print db :: \n"<<*db << std::endl; elog(DEBUG5, "Finished initializing Peloton"); return true; } } // namespace bridge } // namespace peloton <commit_msg>Minor fix<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // bootstrap.cpp // // Identification: src/backend/bridge/ddl/bootstrap.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <iostream> #include "backend/bridge/ddl/bootstrap.h" #include "backend/storage/database.h" #include "backend/common/logger.h" namespace peloton { namespace bridge { /** * @brief This function constructs all the user-defined tables and indices in * all databases * @return true or false, depending on whether we could bootstrap. */ bool Bootstrap::BootstrapPeloton(void) { raw_database_info raw_database(MyDatabaseId); raw_database.CollectRawTableAndIndex(); raw_database.CollectRawForeignKeys(); // create the database with current database id elog(DEBUG5, "Initializing database %s(%lu) in Peloton", raw_database.GetDbName().c_str(), raw_database.GetDbOid()); bool status = raw_database.CreateDatabase(); // skip if we already initialize current database if (status == false) return false; // Create objects in Peloton raw_database.CreateTables(); raw_database.CreateIndexes(); raw_database.CreateForeignkeys(); //auto &manager = catalog::Manager::GetInstance(); // TODO: Update stats //auto db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid()); //db->UpdateStats(peloton_status, false); // Verbose mode //std::cout << "Print db :: \n"<<*db << std::endl; elog(DEBUG5, "Finished initializing Peloton"); return true; } } // namespace bridge } // namespace peloton <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * * ddl_table.cpp * file description * * Copyright(c) 2015, CMU * * /peloton/src/backend/bridge/ddl_table.cpp * *------------------------------------------------------------------------- */ #include <cassert> #include <iostream> #include <vector> #include "backend/bridge/ddl/ddl.h" #include "backend/bridge/ddl/ddl_table.h" #include "backend/bridge/ddl/ddl_database.h" #include "backend/bridge/ddl/ddl_utils.h" #include "backend/common/logger.h" #include "backend/storage/backend_vm.h" #include "backend/storage/table_factory.h" #include "backend/storage/database.h" #include "commands/dbcommands.h" #include "nodes/pg_list.h" #include "parser/parse_utilcmd.h" namespace peloton { namespace bridge { //===--------------------------------------------------------------------===// // Table DDL //===--------------------------------------------------------------------===// /** * @brief Execute the create stmt. * @param the parse tree * @param query string * @return true if we handled it correctly, false otherwise */ bool DDLTable::ExecCreateStmt(Node* parsetree, std::vector<Node*>& parsetree_stack, Peloton_Status* status, TransactionId txn_id) { List* stmts = ((CreateStmt*)parsetree)->stmts; /* ... and do it */ ListCell* l; foreach (l, stmts) { Node* stmt = (Node*)lfirst(l); if (IsA(stmt, CreateStmt)) { CreateStmt* Cstmt = (CreateStmt*)stmt; List* schema = (List*)(Cstmt->tableElts); // Relation name and oid char* relation_name = Cstmt->relation->relname; Oid relation_oid = ((CreateStmt*)parsetree)->relation_id; assert(relation_oid); std::vector<catalog::Column> column_infos; std::vector<catalog::ForeignKey> foreign_keys; bool status; //===--------------------------------------------------------------------===// // CreateStmt --> ColumnInfo --> CreateTable //===--------------------------------------------------------------------===// if (schema != NULL) { DDLUtils::ParsingCreateStmt(Cstmt, column_infos, foreign_keys); DDLTable::CreateTable(relation_oid, relation_name, column_infos); } //===--------------------------------------------------------------------===// // Set Reference Tables //===--------------------------------------------------------------------===// status = DDLTable::SetReferenceTables(foreign_keys, relation_oid); if (status == false) { LOG_WARN("Failed to set reference tables"); } } } //===--------------------------------------------------------------------===// // Rerun query //===--------------------------------------------------------------------===// for( auto parsetree : parsetree_stack ){ DDL::ProcessUtility(parsetree,"rerun", status, txn_id); } parsetree_stack.clear(); return true; } /** * @brief Execute the alter stmt. * @param the parsetree * @param the parsetree_stack store parsetree if the table is not created yet * @return true if we handled it correctly, false otherwise */ bool DDLTable::ExecAlterTableStmt(Node* parsetree, std::vector<Node*>& parsetree_stack) { AlterTableStmt* atstmt = (AlterTableStmt*)parsetree; Oid relation_oid = atstmt->relation_id; List* stmts = atstmt->stmts; // If table has not been created yet, store it into the parsetree stack auto& manager = catalog::Manager::GetInstance(); storage::Database* db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid()); if (nullptr == db->GetTableWithOid(relation_oid)){ parsetree_stack.push_back(parsetree); return true; } ListCell* l; foreach (l, stmts) { Node* stmt = (Node*)lfirst(l); if (IsA(stmt, AlterTableStmt)) { DDLTable::AlterTable(relation_oid, (AlterTableStmt*)stmt); } } return true; } /** * @brief Execute the drop stmt. * @param the parse tree * @return true if we handled it correctly, false otherwise */ bool DDLTable::ExecDropStmt(Node* parsetree) { DropStmt* drop = (DropStmt*)parsetree; // TODO drop->behavior; /* RESTRICT or CASCADE behavior */ ListCell* cell; foreach (cell, drop->objects) { List* names = ((List*)lfirst(cell)); switch (drop->removeType) { case OBJECT_DATABASE: { char* database_name = strVal(linitial(names)); Oid database_oid = get_database_oid(database_name, true); DDLDatabase::DropDatabase(database_oid); } break; case OBJECT_TABLE: { char* table_name = strVal(linitial(names)); auto& manager = catalog::Manager::GetInstance(); storage::Database* db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid()); auto table = db->GetTableWithName(table_name); // skip if no table if( table == nullptr) break; Oid table_oid = table->GetOid(); DDLTable::DropTable(table_oid); } break; default: { LOG_WARN("Unsupported drop object %d ", drop->removeType); } break; } } return true; } /** * @brief Create table. * @param table_name Table name * @param column_infos Information about the columns * @param schema Schema for the table * @return true if we created a table, false otherwise */ bool DDLTable::CreateTable(Oid relation_oid, std::string table_name, std::vector<catalog::Column> column_infos, catalog::Schema* schema) { assert(!table_name.empty()); Oid database_oid = Bridge::GetCurrentDatabaseOid(); if (database_oid == INVALID_OID || relation_oid == INVALID_OID) return false; // Get db oid auto& manager = catalog::Manager::GetInstance(); storage::Database* db = manager.GetDatabaseWithOid(database_oid); // Construct our schema from vector of ColumnInfo if (schema == NULL) schema = new catalog::Schema(column_infos); // Build a table from schema storage::DataTable* table = storage::TableFactory::GetDataTable( database_oid, relation_oid, schema, table_name); db->AddTable(table); if(table != nullptr) { LOG_INFO("Created table(%u)%s in database(%u) ", relation_oid, table_name.c_str(), database_oid); return true; } return false; } /** * @brief AlterTable with given AlterTableStmt * @param relation_oid relation oid * @param Astmt AlterTableStmt * @return true if we alter the table successfully, false otherwise */ bool DDLTable::AlterTable(Oid relation_oid, AlterTableStmt* Astmt) { ListCell* lcmd; foreach (lcmd, Astmt->cmds) { AlterTableCmd* cmd = (AlterTableCmd*)lfirst(lcmd); switch (cmd->subtype) { // case AT_AddColumn: /* add column */ // case AT_DropColumn: /* drop column */ case AT_AddConstraint: /* ADD CONSTRAINT */ { bool status = AddConstraint(relation_oid, (Constraint*)cmd->def); if (status == false) { LOG_WARN("Failed to add constraint"); } break; } default: break; } } LOG_INFO("Alter the table (%u)\n", relation_oid); return true; } /** * @brief Drop table. * @param table_oid Table id. * @return true if we dropped the table, false otherwise */ // FIXME :: Dependencies btw indexes and tables bool DDLTable::DropTable(Oid table_oid) { oid_t database_oid = Bridge::GetCurrentDatabaseOid(); if (database_oid == InvalidOid || table_oid == InvalidOid) { LOG_WARN("Could not drop table :: db oid : %u table oid : %u", database_oid, table_oid); return false; } // Get db with current database oid auto& manager = catalog::Manager::GetInstance(); storage::Database* db = manager.GetDatabaseWithOid(database_oid); db->DropTableWithOid(table_oid); LOG_INFO("Dropped table with oid : %u\n", table_oid); return true; } /** * @brief Add new constraint to the table * @param relation_oid relation oid * @param constraint constraint * @return true if we add the constraint, false otherwise */ bool DDLTable::AddConstraint(Oid relation_oid, Constraint* constraint) { ConstraintType contype = PostgresConstraintTypeToPelotonConstraintType( (PostgresConstraintType)constraint->contype); std::vector<catalog::ForeignKey> foreign_keys; std::string conname; if (constraint->conname != NULL) { conname = constraint->conname; } else { conname = ""; } // FIXME // Create a new constraint switch(contype){ std::cout << "const type : " << ConstraintTypeToString(contype) << std::endl; case CONSTRAINT_TYPE_FOREIGN: { oid_t database_oid = Bridge::GetCurrentDatabaseOid(); assert(database_oid); auto& manager = catalog::Manager::GetInstance(); storage::Database* db = manager.GetDatabaseWithOid(database_oid); // PrimaryKey Table oid_t PrimaryKeyTableId = db->GetTableWithName(constraint->pktable->relname)->GetOid(); // Each table column names std::vector<std::string> pk_column_names; std::vector<std::string> fk_column_names; ListCell* column; if (constraint->pk_attrs != NULL && constraint->pk_attrs->length > 0) { foreach (column, constraint->pk_attrs) { char* attname = strVal(lfirst(column)); pk_column_names.push_back(attname); } } if (constraint->fk_attrs != NULL && constraint->fk_attrs->length > 0) { foreach (column, constraint->fk_attrs) { char* attname = strVal(lfirst(column)); fk_column_names.push_back(attname); } } catalog::ForeignKey* foreign_key = new catalog::ForeignKey( PrimaryKeyTableId, pk_column_names, fk_column_names, constraint->fk_upd_action, constraint->fk_del_action, conname); // new_constraint = new catalog::Constraint(contype, conname); foreign_keys.push_back(*foreign_key); } break; default: LOG_WARN("Unrecognized constraint type %d\n", (int)contype); break; } // FIXME : bool status = SetReferenceTables(foreign_keys, relation_oid); if (status == false) { LOG_WARN("Failed to set reference tables"); } return true; } /** * @brief Set Reference Tables * @param reference table namees reference table names * @param relation_oid relation oid * @return true if we set the reference tables, false otherwise */ bool DDLTable::SetReferenceTables( std::vector<catalog::ForeignKey>& foreign_keys, oid_t relation_oid) { assert(relation_oid); oid_t database_oid = Bridge::GetCurrentDatabaseOid(); assert(database_oid); storage::DataTable* current_table = (storage::DataTable*)catalog::Manager::GetInstance().GetTableWithOid( database_oid, relation_oid); for (auto foreign_key : foreign_keys) { current_table->AddForeignKey(&foreign_key); } return true; } } // namespace bridge } // namespace peloton <commit_msg>Minor fix<commit_after>/*------------------------------------------------------------------------- * * ddl_table.cpp * file description * * Copyright(c) 2015, CMU * * /peloton/src/backend/bridge/ddl_table.cpp * *------------------------------------------------------------------------- */ #include <cassert> #include <iostream> #include <vector> #include "backend/bridge/ddl/ddl.h" #include "backend/bridge/ddl/ddl_table.h" #include "backend/bridge/ddl/ddl_database.h" #include "backend/bridge/ddl/ddl_utils.h" #include "backend/common/logger.h" #include "backend/storage/backend_vm.h" #include "backend/storage/table_factory.h" #include "backend/storage/database.h" #include "commands/dbcommands.h" #include "nodes/pg_list.h" #include "parser/parse_utilcmd.h" namespace peloton { namespace bridge { //===--------------------------------------------------------------------===// // Table DDL //===--------------------------------------------------------------------===// /** * @brief Execute the create stmt. * @param the parse tree * @param query string * @return true if we handled it correctly, false otherwise */ bool DDLTable::ExecCreateStmt(Node* parsetree, std::vector<Node*>& parsetree_stack, Peloton_Status* status, TransactionId txn_id) { List* stmts = ((CreateStmt*)parsetree)->stmts; /* ... and do it */ ListCell* l; foreach (l, stmts) { Node* stmt = (Node*)lfirst(l); if (IsA(stmt, CreateStmt)) { CreateStmt* Cstmt = (CreateStmt*)stmt; List* schema = (List*)(Cstmt->tableElts); // Relation name and oid char* relation_name = Cstmt->relation->relname; Oid relation_oid = ((CreateStmt*)parsetree)->relation_id; assert(relation_oid); std::vector<catalog::Column> column_infos; std::vector<catalog::ForeignKey> foreign_keys; bool status; //===--------------------------------------------------------------------===// // CreateStmt --> ColumnInfo --> CreateTable //===--------------------------------------------------------------------===// if (schema != NULL) { DDLUtils::ParsingCreateStmt(Cstmt, column_infos, foreign_keys); DDLTable::CreateTable(relation_oid, relation_name, column_infos); } //===--------------------------------------------------------------------===// // Set Reference Tables //===--------------------------------------------------------------------===// status = DDLTable::SetReferenceTables(foreign_keys, relation_oid); if (status == false) { LOG_WARN("Failed to set reference tables"); } } } //===--------------------------------------------------------------------===// // Rerun query //===--------------------------------------------------------------------===// for( auto parsetree : parsetree_stack ){ DDL::ProcessUtility(parsetree,"rerun", status, txn_id); } parsetree_stack.clear(); return true; } /** * @brief Execute the alter stmt. * @param the parsetree * @param the parsetree_stack store parsetree if the table is not created yet * @return true if we handled it correctly, false otherwise */ bool DDLTable::ExecAlterTableStmt(Node* parsetree, std::vector<Node*>& parsetree_stack) { AlterTableStmt* atstmt = (AlterTableStmt*)parsetree; Oid relation_oid = atstmt->relation_id; List* stmts = atstmt->stmts; // If table has not been created yet, store it into the parsetree stack auto& manager = catalog::Manager::GetInstance(); storage::Database* db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid()); if (nullptr == db->GetTableWithOid(relation_oid)){ parsetree_stack.push_back(parsetree); return true; } ListCell* l; foreach (l, stmts) { Node* stmt = (Node*)lfirst(l); if (IsA(stmt, AlterTableStmt)) { DDLTable::AlterTable(relation_oid, (AlterTableStmt*)stmt); } } return true; } /** * @brief Execute the drop stmt. * @param the parse tree * @return true if we handled it correctly, false otherwise */ bool DDLTable::ExecDropStmt(Node* parsetree) { DropStmt* drop = (DropStmt*)parsetree; // TODO drop->behavior; /* RESTRICT or CASCADE behavior */ ListCell* cell; foreach (cell, drop->objects) { List* names = ((List*)lfirst(cell)); switch (drop->removeType) { case OBJECT_DATABASE: { char* database_name = strVal(linitial(names)); Oid database_oid = get_database_oid(database_name, true); DDLDatabase::DropDatabase(database_oid); } break; case OBJECT_TABLE: { char* table_name = strVal(linitial(names)); auto& manager = catalog::Manager::GetInstance(); storage::Database* db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid()); auto table = db->GetTableWithName(table_name); // skip if no table if( table == nullptr) break; Oid table_oid = table->GetOid(); DDLTable::DropTable(table_oid); } break; default: { LOG_WARN("Unsupported drop object %d ", drop->removeType); } break; } } return true; } /** * @brief Create table. * @param table_name Table name * @param column_infos Information about the columns * @param schema Schema for the table * @return true if we created a table, false otherwise */ bool DDLTable::CreateTable(Oid relation_oid, std::string table_name, std::vector<catalog::Column> column_infos, catalog::Schema* schema) { assert(!table_name.empty()); Oid database_oid = Bridge::GetCurrentDatabaseOid(); if (database_oid == INVALID_OID || relation_oid == INVALID_OID) return false; // Get db oid auto& manager = catalog::Manager::GetInstance(); storage::Database* db = manager.GetDatabaseWithOid(database_oid); // Construct our schema from vector of ColumnInfo if (schema == NULL) schema = new catalog::Schema(column_infos); // Build a table from schema storage::DataTable* table = storage::TableFactory::GetDataTable( database_oid, relation_oid, schema, table_name); db->AddTable(table); if(table != nullptr) { LOG_INFO("Created table(%u)%s in database(%u) ", relation_oid, table_name.c_str(), database_oid); return true; } return false; } /** * @brief AlterTable with given AlterTableStmt * @param relation_oid relation oid * @param Astmt AlterTableStmt * @return true if we alter the table successfully, false otherwise */ bool DDLTable::AlterTable(Oid relation_oid, AlterTableStmt* Astmt) { ListCell* lcmd; foreach (lcmd, Astmt->cmds) { AlterTableCmd* cmd = (AlterTableCmd*)lfirst(lcmd); switch (cmd->subtype) { // case AT_AddColumn: /* add column */ // case AT_DropColumn: /* drop column */ case AT_AddConstraint: /* ADD CONSTRAINT */ { bool status = AddConstraint(relation_oid, (Constraint*)cmd->def); if (status == false) { LOG_WARN("Failed to add constraint"); } break; } default: break; } } LOG_INFO("Alter the table (%u)\n", relation_oid); return true; } /** * @brief Drop table. * @param table_oid Table id. * @return true if we dropped the table, false otherwise */ // FIXME :: Dependencies btw indexes and tables bool DDLTable::DropTable(Oid table_oid) { oid_t database_oid = Bridge::GetCurrentDatabaseOid(); if (database_oid == InvalidOid || table_oid == InvalidOid) { LOG_WARN("Could not drop table :: db oid : %u table oid : %u", database_oid, table_oid); return false; } // Get db with current database oid auto& manager = catalog::Manager::GetInstance(); storage::Database* db = manager.GetDatabaseWithOid(database_oid); db->DropTableWithOid(table_oid); LOG_INFO("Dropped table with oid : %u\n", table_oid); return true; } /** * @brief Add new constraint to the table * @param relation_oid relation oid * @param constraint constraint * @return true if we add the constraint, false otherwise */ bool DDLTable::AddConstraint(Oid relation_oid, Constraint* constraint) { ConstraintType contype = PostgresConstraintTypeToPelotonConstraintType( (PostgresConstraintType)constraint->contype); std::vector<catalog::ForeignKey> foreign_keys; std::string conname; if (constraint->conname != NULL) { conname = constraint->conname; } else { conname = ""; } switch(contype){ case CONSTRAINT_TYPE_FOREIGN: { oid_t database_oid = Bridge::GetCurrentDatabaseOid(); assert(database_oid); auto& manager = catalog::Manager::GetInstance(); storage::Database* db = manager.GetDatabaseWithOid(database_oid); // PrimaryKey Table oid_t PrimaryKeyTableId = db->GetTableWithName(constraint->pktable->relname)->GetOid(); // Each table column names std::vector<std::string> pk_column_names; std::vector<std::string> fk_column_names; ListCell* column; if (constraint->pk_attrs != NULL && constraint->pk_attrs->length > 0) { foreach (column, constraint->pk_attrs) { char* attname = strVal(lfirst(column)); pk_column_names.push_back(attname); } } if (constraint->fk_attrs != NULL && constraint->fk_attrs->length > 0) { foreach (column, constraint->fk_attrs) { char* attname = strVal(lfirst(column)); fk_column_names.push_back(attname); } } catalog::ForeignKey* foreign_key = new catalog::ForeignKey( PrimaryKeyTableId, pk_column_names, fk_column_names, constraint->fk_upd_action, constraint->fk_del_action, conname); foreign_keys.push_back(*foreign_key); } break; default: LOG_WARN("Unrecognized constraint type %d\n", (int)contype); break; } // FIXME : bool status = SetReferenceTables(foreign_keys, relation_oid); if (status == false) { LOG_WARN("Failed to set reference tables"); } return true; } /** * @brief Set Reference Tables * @param reference table namees reference table names * @param relation_oid relation oid * @return true if we set the reference tables, false otherwise */ bool DDLTable::SetReferenceTables( std::vector<catalog::ForeignKey>& foreign_keys, oid_t relation_oid) { assert(relation_oid); oid_t database_oid = Bridge::GetCurrentDatabaseOid(); assert(database_oid); storage::DataTable* current_table = (storage::DataTable*)catalog::Manager::GetInstance().GetTableWithOid( database_oid, relation_oid); for (auto foreign_key : foreign_keys) { current_table->AddForeignKey(&foreign_key); } return true; } } // namespace bridge } // namespace peloton <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2019, 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 ********************************************************/ #pragma once namespace common { /// Deletes a handle. /// /// This function deletes a handle. Handle are usually typedefed pointers /// which are created by a C API of a library. /// /// \param[in] handle the handle that will deleted by the destroy function /// \note This function will need to be specialized for each type of handle template<typename T> void handle_deleter(T handle) noexcept; /// Creates a handle /// This function creates a handle. Handle are usually typedefed pointers /// which are created by a C API of a library. /// /// \param[in] handle the handle that will be initialzed by the create function /// \note This function will need to be specialized for each type of handle template<typename T> void handle_creator(T *handle) noexcept; /// \brief A generic class to manage basic RAII lifetimes for C handles /// /// This class manages the lifetimes of C handles found in many types of /// libraries. This class is non-copiable but can be moved. /// /// You can use this class with a new handle by using the CREATE_HANDLE macro in /// the src/backend/*/handle.cpp file. This macro instantiates the /// handle_createor and handle_deleter functions used by this class. /// /// \code{.cpp} /// CREATE_HANDLE(cusparseHandle_t, cusparseCreate, cusparseDestroy); /// \code{.cpp} template<typename T> class unique_handle { T handle_; public: /// Default constructor. Initializes the handle to zero. Does not call the /// create function constexpr unique_handle() noexcept : handle_(0) {} void create() { if (!handle_) handle_creator(&handle_); } /// \brief Takes ownership of a previously created handle /// /// \param[in] handle The handle to manage by this object explicit constexpr unique_handle(T handle) noexcept : handle_(handle){}; /// \brief Deletes the handle if created. ~unique_handle() noexcept { if (handle_) handle_deleter(handle_); }; /// \brief Implicit converter for the handle constexpr operator const T &() const noexcept { return handle_; } unique_handle(const unique_handle &other) noexcept = delete; constexpr unique_handle(unique_handle &&other) noexcept : handle_(other.handle_) { other.handle_ = 0; } unique_handle &operator=(unique_handle &other) noexcept = delete; unique_handle &operator=(unique_handle &&other) noexcept { handle_ = other.handle_; other.handle_ = 0; } // Returns true if the \p other unique_handle is the same as this handle constexpr bool operator==(unique_handle &other) const noexcept { return handle_ == other.handle_; } // Returns true if the \p other handle is the same as this handle constexpr bool operator==(T &other) const noexcept { return handle_ == other; } // Returns true if the \p other handle is the same as this handle constexpr bool operator==(T other) const noexcept { return handle_ == other; } }; /// \brief Returns an initialized handle object. The create function on this /// object is already called template<typename T> unique_handle<T> make_handle() { unique_handle<T> h; h.create(); return h; } } // namespace common /// specializes the handle_creater and handle_deleter functions for a specific /// handle /// /// \param[in] HANDLE The type of the handle /// \param[in] CREATE The create function for the handle /// \param[in] DESTROY The destroy function for the handle /// \note Do not add this macro to another namespace, The macro provides a /// namespace for the functions. #define CREATE_HANDLE(HANDLE, CREATE, DESTROY) \ namespace common { \ template<> \ void handle_deleter<HANDLE>(HANDLE handle) noexcept { \ DESTROY(handle); \ } \ template<> \ void handle_creator<HANDLE>(HANDLE * handle) noexcept { \ CREATE(handle); \ } \ } // namespace common <commit_msg>Return error codes from the unique_handle's create function<commit_after>/******************************************************* * Copyright (c) 2019, 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 ********************************************************/ #pragma once namespace common { /// Deletes a handle. /// /// This function deletes a handle. Handle are usually typedefed pointers /// which are created by a C API of a library. /// /// \param[in] handle the handle that will deleted by the destroy function /// \note This function will need to be specialized for each type of handle template<typename T> void handle_deleter(T handle) noexcept; /// Creates a handle /// This function creates a handle. Handle are usually typedefed pointers /// which are created by a C API of a library. /// /// \param[in] handle the handle that will be initialzed by the create function /// \note This function will need to be specialized for each type of handle template<typename T> int handle_creator(T *handle) noexcept; /// \brief A generic class to manage basic RAII lifetimes for C handles /// /// This class manages the lifetimes of C handles found in many types of /// libraries. This class is non-copiable but can be moved. /// /// You can use this class with a new handle by using the CREATE_HANDLE macro in /// the src/backend/*/handle.cpp file. This macro instantiates the /// handle_createor and handle_deleter functions used by this class. /// /// \code{.cpp} /// CREATE_HANDLE(cusparseHandle_t, cusparseCreate, cusparseDestroy); /// \code{.cpp} template<typename T> class unique_handle { T handle_; public: /// Default constructor. Initializes the handle to zero. Does not call the /// create function constexpr unique_handle() noexcept : handle_(0) {} int create() { if (!handle_) { int error = handle_creator(&handle_); if (error) { handle_ = 0; } return error; } return 0; } /// \brief Takes ownership of a previously created handle /// /// \param[in] handle The handle to manage by this object explicit constexpr unique_handle(T handle) noexcept : handle_(handle){}; /// \brief Deletes the handle if created. ~unique_handle() noexcept { if (handle_) handle_deleter(handle_); }; /// \brief Implicit converter for the handle constexpr operator const T &() const noexcept { return handle_; } unique_handle(const unique_handle &other) noexcept = delete; constexpr unique_handle(unique_handle &&other) noexcept : handle_(other.handle_) { other.handle_ = 0; } unique_handle &operator=(unique_handle &other) noexcept = delete; unique_handle &operator=(unique_handle &&other) noexcept { handle_ = other.handle_; other.handle_ = 0; } // Returns true if the \p other unique_handle is the same as this handle constexpr bool operator==(unique_handle &other) const noexcept { return handle_ == other.handle_; } // Returns true if the \p other handle is the same as this handle constexpr bool operator==(T &other) const noexcept { return handle_ == other; } // Returns true if the \p other handle is the same as this handle constexpr bool operator==(T other) const noexcept { return handle_ == other; } // Returns true if the handle was initialized correctly constexpr operator bool() { return handle_ != 0; } }; /// \brief Returns an initialized handle object. The create function on this /// object is already called template<typename T> unique_handle<T> make_handle() { unique_handle<T> h; h.create(); return h; } } // namespace common /// specializes the handle_creater and handle_deleter functions for a specific /// handle /// /// \param[in] HANDLE The type of the handle /// \param[in] CREATE The create function for the handle /// \param[in] DESTROY The destroy function for the handle /// \note Do not add this macro to another namespace, The macro provides a /// namespace for the functions. #define CREATE_HANDLE(HANDLE, CREATE, DESTROY) \ namespace common { \ template<> \ void handle_deleter<HANDLE>(HANDLE handle) noexcept { \ DESTROY(handle); \ } \ template<> \ int handle_creator<HANDLE>(HANDLE * handle) noexcept { \ return CREATE(handle); \ } \ } // namespace common <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Embedded Framework 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 "include/cef.h" #include "testing/gtest/include/gtest/gtest.h" TEST(URLTest, CreateURL) { // Create the URL using the spec. { CefURLParts parts; CefString url; CefString(&parts.spec).FromASCII( "http://user:[email protected]:88/path/to.html?foo=test&bar=test2"); ASSERT_TRUE(CefCreateURL(parts, url)); ASSERT_EQ(url, "http://user:[email protected]:88/path/to.html?foo=test&bar=test2"); } // Test that scheme and host are required. { CefURLParts parts; CefString url; CefString(&parts.scheme).FromASCII("http"); ASSERT_FALSE(CefCreateURL(parts, url)); } { CefURLParts parts; CefString url; CefString(&parts.host).FromASCII("www.example.com"); ASSERT_FALSE(CefCreateURL(parts, url)); } // Create the URL using scheme and host. { CefURLParts parts; CefString url; CefString(&parts.scheme).FromASCII("http"); CefString(&parts.host).FromASCII("www.example.com"); ASSERT_TRUE(CefCreateURL(parts, url)); ASSERT_EQ(url, "http://www.example.com/"); } // Create the URL using scheme, host and path. { CefURLParts parts; CefString url; CefString(&parts.scheme).FromASCII("http"); CefString(&parts.host).FromASCII("www.example.com"); CefString(&parts.path).FromASCII("/path/to.html"); ASSERT_TRUE(CefCreateURL(parts, url)); ASSERT_EQ(url, "http://www.example.com/path/to.html"); } // Create the URL using scheme, host, path and query. { CefURLParts parts; CefString url; CefString(&parts.scheme).FromASCII("http"); CefString(&parts.host).FromASCII("www.example.com"); CefString(&parts.path).FromASCII("/path/to.html"); CefString(&parts.query).FromASCII("foo=test&bar=test2"); ASSERT_TRUE(CefCreateURL(parts, url)); ASSERT_EQ(url, "http://www.example.com/path/to.html?foo=test&bar=test2"); } // Create the URL using all the various components. { CefURLParts parts; CefString url; CefString(&parts.scheme).FromASCII("http"); CefString(&parts.username).FromASCII("user"); CefString(&parts.password).FromASCII("pass"); CefString(&parts.host).FromASCII("www.example.com"); CefString(&parts.port).FromASCII("88"); CefString(&parts.path).FromASCII("/path/to.html"); CefString(&parts.query).FromASCII("foo=test&bar=test2"); ASSERT_TRUE(CefCreateURL(parts, url)); ASSERT_EQ(url, "http://user:[email protected]:88/path/to.html?foo=test&bar=test2"); } } TEST(URLTest, ParseURL) { // Parse the URL using scheme and host. { CefURLParts parts; CefString url; url.FromASCII("http://www.example.com"); ASSERT_TRUE(CefParseURL(url, parts)); CefString spec(&parts.spec); ASSERT_EQ(spec, "http://www.example.com/"); ASSERT_EQ(parts.username.length, 0); ASSERT_EQ(parts.password.length, 0); CefString scheme(&parts.scheme); ASSERT_EQ(scheme, "http"); CefString host(&parts.host); ASSERT_EQ(host, "www.example.com"); ASSERT_EQ(parts.port.length, 0); CefString path(&parts.path); ASSERT_EQ(path, "/"); ASSERT_EQ(parts.query.length, 0); } // Parse the URL using scheme, host and path. { CefURLParts parts; CefString url; url.FromASCII("http://www.example.com/path/to.html"); ASSERT_TRUE(CefParseURL(url, parts)); CefString spec(&parts.spec); ASSERT_EQ(spec, "http://www.example.com/path/to.html"); ASSERT_EQ(parts.username.length, 0); ASSERT_EQ(parts.password.length, 0); CefString scheme(&parts.scheme); ASSERT_EQ(scheme, "http"); CefString host(&parts.host); ASSERT_EQ(host, "www.example.com"); ASSERT_EQ(parts.port.length, 0); CefString path(&parts.path); ASSERT_EQ(path, "/path/to.html"); ASSERT_EQ(parts.query.length, 0); } // Parse the URL using scheme, host, path and query. { CefURLParts parts; CefString url; url.FromASCII("http://www.example.com/path/to.html?foo=test&bar=test2"); ASSERT_TRUE(CefParseURL(url, parts)); CefString spec(&parts.spec); ASSERT_EQ(spec, "http://www.example.com/path/to.html?foo=test&bar=test2"); ASSERT_EQ(parts.username.length, 0); ASSERT_EQ(parts.password.length, 0); CefString scheme(&parts.scheme); ASSERT_EQ(scheme, "http"); CefString host(&parts.host); ASSERT_EQ(host, "www.example.com"); ASSERT_EQ(parts.port.length, 0); CefString path(&parts.path); ASSERT_EQ(path, "/path/to.html"); CefString query(&parts.query); ASSERT_EQ(query, "foo=test&bar=test2"); } // Parse the URL using all the various components. { CefURLParts parts; CefString url; url.FromASCII( "http://user:[email protected]:88/path/to.html?foo=test&bar=test2"); ASSERT_TRUE(CefParseURL(url, parts)); CefString spec(&parts.spec); ASSERT_EQ(spec, "http://user:[email protected]:88/path/to.html?foo=test&bar=test2"); CefString scheme(&parts.scheme); ASSERT_EQ(scheme, "http"); CefString username(&parts.username); ASSERT_EQ(username, "user"); CefString password(&parts.password); ASSERT_EQ(password, "pass"); CefString host(&parts.host); ASSERT_EQ(host, "www.example.com"); CefString port(&parts.port); ASSERT_EQ(port, "88"); CefString path(&parts.path); ASSERT_EQ(path, "/path/to.html"); CefString query(&parts.query); ASSERT_EQ(query, "foo=test&bar=test2"); } // Parse an invalid URL. { CefURLParts parts; CefString url; url.FromASCII("www.example.com"); ASSERT_FALSE(CefParseURL(url, parts)); } } <commit_msg>Fix Mac compile errors.<commit_after>// Copyright (c) 2011 The Chromium Embedded Framework 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 "include/cef.h" #include "testing/gtest/include/gtest/gtest.h" TEST(URLTest, CreateURL) { // Create the URL using the spec. { CefURLParts parts; CefString url; CefString(&parts.spec).FromASCII( "http://user:[email protected]:88/path/to.html?foo=test&bar=test2"); ASSERT_TRUE(CefCreateURL(parts, url)); ASSERT_EQ(url, "http://user:[email protected]:88/path/to.html?foo=test&bar=test2"); } // Test that scheme and host are required. { CefURLParts parts; CefString url; CefString(&parts.scheme).FromASCII("http"); ASSERT_FALSE(CefCreateURL(parts, url)); } { CefURLParts parts; CefString url; CefString(&parts.host).FromASCII("www.example.com"); ASSERT_FALSE(CefCreateURL(parts, url)); } // Create the URL using scheme and host. { CefURLParts parts; CefString url; CefString(&parts.scheme).FromASCII("http"); CefString(&parts.host).FromASCII("www.example.com"); ASSERT_TRUE(CefCreateURL(parts, url)); ASSERT_EQ(url, "http://www.example.com/"); } // Create the URL using scheme, host and path. { CefURLParts parts; CefString url; CefString(&parts.scheme).FromASCII("http"); CefString(&parts.host).FromASCII("www.example.com"); CefString(&parts.path).FromASCII("/path/to.html"); ASSERT_TRUE(CefCreateURL(parts, url)); ASSERT_EQ(url, "http://www.example.com/path/to.html"); } // Create the URL using scheme, host, path and query. { CefURLParts parts; CefString url; CefString(&parts.scheme).FromASCII("http"); CefString(&parts.host).FromASCII("www.example.com"); CefString(&parts.path).FromASCII("/path/to.html"); CefString(&parts.query).FromASCII("foo=test&bar=test2"); ASSERT_TRUE(CefCreateURL(parts, url)); ASSERT_EQ(url, "http://www.example.com/path/to.html?foo=test&bar=test2"); } // Create the URL using all the various components. { CefURLParts parts; CefString url; CefString(&parts.scheme).FromASCII("http"); CefString(&parts.username).FromASCII("user"); CefString(&parts.password).FromASCII("pass"); CefString(&parts.host).FromASCII("www.example.com"); CefString(&parts.port).FromASCII("88"); CefString(&parts.path).FromASCII("/path/to.html"); CefString(&parts.query).FromASCII("foo=test&bar=test2"); ASSERT_TRUE(CefCreateURL(parts, url)); ASSERT_EQ(url, "http://user:[email protected]:88/path/to.html?foo=test&bar=test2"); } } TEST(URLTest, ParseURL) { // Parse the URL using scheme and host. { CefURLParts parts; CefString url; url.FromASCII("http://www.example.com"); ASSERT_TRUE(CefParseURL(url, parts)); CefString spec(&parts.spec); ASSERT_EQ(spec, "http://www.example.com/"); ASSERT_EQ(parts.username.length, (size_t)0); ASSERT_EQ(parts.password.length, (size_t)0); CefString scheme(&parts.scheme); ASSERT_EQ(scheme, "http"); CefString host(&parts.host); ASSERT_EQ(host, "www.example.com"); ASSERT_EQ(parts.port.length, (size_t)0); CefString path(&parts.path); ASSERT_EQ(path, "/"); ASSERT_EQ(parts.query.length, (size_t)0); } // Parse the URL using scheme, host and path. { CefURLParts parts; CefString url; url.FromASCII("http://www.example.com/path/to.html"); ASSERT_TRUE(CefParseURL(url, parts)); CefString spec(&parts.spec); ASSERT_EQ(spec, "http://www.example.com/path/to.html"); ASSERT_EQ(parts.username.length, (size_t)0); ASSERT_EQ(parts.password.length, (size_t)0); CefString scheme(&parts.scheme); ASSERT_EQ(scheme, "http"); CefString host(&parts.host); ASSERT_EQ(host, "www.example.com"); ASSERT_EQ(parts.port.length, (size_t)0); CefString path(&parts.path); ASSERT_EQ(path, "/path/to.html"); ASSERT_EQ(parts.query.length, (size_t)0); } // Parse the URL using scheme, host, path and query. { CefURLParts parts; CefString url; url.FromASCII("http://www.example.com/path/to.html?foo=test&bar=test2"); ASSERT_TRUE(CefParseURL(url, parts)); CefString spec(&parts.spec); ASSERT_EQ(spec, "http://www.example.com/path/to.html?foo=test&bar=test2"); ASSERT_EQ(parts.username.length, (size_t)0); ASSERT_EQ(parts.password.length, (size_t)0); CefString scheme(&parts.scheme); ASSERT_EQ(scheme, "http"); CefString host(&parts.host); ASSERT_EQ(host, "www.example.com"); ASSERT_EQ(parts.port.length, (size_t)0); CefString path(&parts.path); ASSERT_EQ(path, "/path/to.html"); CefString query(&parts.query); ASSERT_EQ(query, "foo=test&bar=test2"); } // Parse the URL using all the various components. { CefURLParts parts; CefString url; url.FromASCII( "http://user:[email protected]:88/path/to.html?foo=test&bar=test2"); ASSERT_TRUE(CefParseURL(url, parts)); CefString spec(&parts.spec); ASSERT_EQ(spec, "http://user:[email protected]:88/path/to.html?foo=test&bar=test2"); CefString scheme(&parts.scheme); ASSERT_EQ(scheme, "http"); CefString username(&parts.username); ASSERT_EQ(username, "user"); CefString password(&parts.password); ASSERT_EQ(password, "pass"); CefString host(&parts.host); ASSERT_EQ(host, "www.example.com"); CefString port(&parts.port); ASSERT_EQ(port, "88"); CefString path(&parts.path); ASSERT_EQ(path, "/path/to.html"); CefString query(&parts.query); ASSERT_EQ(query, "foo=test&bar=test2"); } // Parse an invalid URL. { CefURLParts parts; CefString url; url.FromASCII("www.example.com"); ASSERT_FALSE(CefParseURL(url, parts)); } } <|endoftext|>
<commit_before>/* TODO: - load file in a separate thread ("prefetch") - can be smarter about the memcpy call instead of doing it row-by-row :: use util functions caffe_copy, and Blob->offset() :: don't forget to update hdf5_daa_layer.cu accordingly - add ability to shuffle filenames if flag is set */ #include <fstream> // NOLINT(readability/streams) #include <string> #include <vector> #include "hdf5.h" #include "hdf5_hl.h" #include "stdint.h" #include "caffe/data_layers.hpp" #include "caffe/layer.hpp" #include "caffe/util/io.hpp" namespace caffe { template <typename Dtype> HDF5DataLayer<Dtype>::~HDF5DataLayer<Dtype>() { } // Load data and label from HDF5 filename into the class property blobs. template <typename Dtype> void HDF5DataLayer<Dtype>::LoadHDF5FileData(const char* filename) { DLOG(INFO) << "Loading HDF5 file: " << filename; hid_t file_id = H5Fopen(filename, H5F_ACC_RDONLY, H5P_DEFAULT); if (file_id < 0) { LOG(FATAL) << "Failed opening HDF5 file: " << filename; } int top_size = this->layer_param_.top_size(); hdf_blobs_.resize(top_size); const int MIN_DATA_DIM = 1; const int MAX_DATA_DIM = INT_MAX; for (int i = 0; i < top_size; ++i) { hdf_blobs_[i] = shared_ptr<Blob<Dtype> >(new Blob<Dtype>()); hdf5_load_nd_dataset(file_id, this->layer_param_.top(i).c_str(), MIN_DATA_DIM, MAX_DATA_DIM, hdf_blobs_[i].get()); } herr_t status = H5Fclose(file_id); CHECK_GE(status, 0) << "Failed to close HDF5 file: " << filename; // MinTopBlobs==1 guarantees at least one top blob CHECK_GE(hdf_blobs_[0]->num_axes(), 1) << "Input must have at least 1 axis."; const int num = hdf_blobs_[0]->shape(0); for (int i = 1; i < top_size; ++i) { CHECK_EQ(hdf_blobs_[i]->shape(0), num); } // Default to identity permutation. data_permutation_.clear(); data_permutation_.resize(hdf_blobs_[0]->shape(0)); for (int i = 0; i < hdf_blobs_[0]->shape(0); i++) data_permutation_[i] = i; // Shuffle if needed. if (this->layer_param_.hdf5_data_param().shuffle()) { std::random_shuffle(data_permutation_.begin(), data_permutation_.end()); DLOG(INFO) << "Successully loaded " << hdf_blobs_[0]->shape(0) << " rows (shuffled)"; } else { DLOG(INFO) << "Successully loaded " << hdf_blobs_[0]->shape(0) << " rows"; } } template <typename Dtype> void HDF5DataLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { // Refuse transformation parameters since HDF5 is totally generic. CHECK(!this->layer_param_.has_transform_param()) << this->type() << " does not transform data."; // Read the source to parse the filenames. const string& source = this->layer_param_.hdf5_data_param().source(); LOG(INFO) << "Loading list of HDF5 filenames from: " << source; hdf_filenames_.clear(); std::ifstream source_file(source.c_str()); if (source_file.is_open()) { std::string line; while (source_file >> line) { hdf_filenames_.push_back(line); } } else { LOG(FATAL) << "Failed to open source file: " << source; } source_file.close(); num_files_ = hdf_filenames_.size(); current_file_ = 0; LOG(INFO) << "Number of HDF5 files: " << num_files_; CHECK_GE(num_files_, 1) << "Must have at least 1 HDF5 filename listed in " << source; file_permutation_.clear(); file_permutation_.resize(num_files_); // Default to identity permutation. for (int i = 0; i < num_files_; i++) { file_permutation_[i] = i; } // Shuffle if needed. if (this->layer_param_.hdf5_data_param().shuffle()) { std::random_shuffle(file_permutation_.begin(), file_permutation_.end()); } // Load the first HDF5 file and initialize the line counter. LoadHDF5FileData(hdf_filenames_[file_permutation_[current_file_]].c_str()); current_row_ = 0; if (this->layer_param_.hdf5_data_param().shuffle()) { std::random_shuffle(file_permutation_.begin(), file_permutation_.end()); } // Reshape blobs. const int batch_size = this->layer_param_.hdf5_data_param().batch_size(); const int top_size = this->layer_param_.top_size(); vector<int> top_shape; for (int i = 0; i < top_size; ++i) { top_shape.resize(hdf_blobs_[i]->num_axes()); top_shape[0] = batch_size; for (int j = 1; j < top_shape.size(); ++j) { top_shape[j] = hdf_blobs_[i]->shape(j); } top[i]->Reshape(top_shape); } } template <typename Dtype> void HDF5DataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const int batch_size = this->layer_param_.hdf5_data_param().batch_size(); for (int i = 0; i < batch_size; ++i, ++current_row_) { if (current_row_ == hdf_blobs_[0]->shape(0)) { if (num_files_ > 1) { ++current_file_; if (current_file_ == num_files_) { current_file_ = 0; if (this->layer_param_.hdf5_data_param().shuffle()) { std::random_shuffle(file_permutation_.begin(), file_permutation_.end()); } DLOG(INFO) << "Looping around to first file."; } LoadHDF5FileData( hdf_filenames_[file_permutation_[current_file_]].c_str()); } current_row_ = 0; if (this->layer_param_.hdf5_data_param().shuffle()) std::random_shuffle(data_permutation_.begin(), data_permutation_.end()); } for (int j = 0; j < this->layer_param_.top_size(); ++j) { int data_dim = top[j]->count() / top[j]->shape(0); caffe_copy(data_dim, &hdf_blobs_[j]->cpu_data()[data_permutation_[current_row_] * data_dim], &top[j]->mutable_cpu_data()[i * data_dim]); } } } #ifdef CPU_ONLY STUB_GPU_FORWARD(HDF5DataLayer, Forward); #endif INSTANTIATE_CLASS(HDF5DataLayer); REGISTER_LAYER_CLASS(HDF5Data); } // namespace caffe <commit_msg>HDF5DataLayer: remove redundant shuffle<commit_after>/* TODO: - load file in a separate thread ("prefetch") - can be smarter about the memcpy call instead of doing it row-by-row :: use util functions caffe_copy, and Blob->offset() :: don't forget to update hdf5_daa_layer.cu accordingly - add ability to shuffle filenames if flag is set */ #include <fstream> // NOLINT(readability/streams) #include <string> #include <vector> #include "hdf5.h" #include "hdf5_hl.h" #include "stdint.h" #include "caffe/data_layers.hpp" #include "caffe/layer.hpp" #include "caffe/util/io.hpp" namespace caffe { template <typename Dtype> HDF5DataLayer<Dtype>::~HDF5DataLayer<Dtype>() { } // Load data and label from HDF5 filename into the class property blobs. template <typename Dtype> void HDF5DataLayer<Dtype>::LoadHDF5FileData(const char* filename) { DLOG(INFO) << "Loading HDF5 file: " << filename; hid_t file_id = H5Fopen(filename, H5F_ACC_RDONLY, H5P_DEFAULT); if (file_id < 0) { LOG(FATAL) << "Failed opening HDF5 file: " << filename; } int top_size = this->layer_param_.top_size(); hdf_blobs_.resize(top_size); const int MIN_DATA_DIM = 1; const int MAX_DATA_DIM = INT_MAX; for (int i = 0; i < top_size; ++i) { hdf_blobs_[i] = shared_ptr<Blob<Dtype> >(new Blob<Dtype>()); hdf5_load_nd_dataset(file_id, this->layer_param_.top(i).c_str(), MIN_DATA_DIM, MAX_DATA_DIM, hdf_blobs_[i].get()); } herr_t status = H5Fclose(file_id); CHECK_GE(status, 0) << "Failed to close HDF5 file: " << filename; // MinTopBlobs==1 guarantees at least one top blob CHECK_GE(hdf_blobs_[0]->num_axes(), 1) << "Input must have at least 1 axis."; const int num = hdf_blobs_[0]->shape(0); for (int i = 1; i < top_size; ++i) { CHECK_EQ(hdf_blobs_[i]->shape(0), num); } // Default to identity permutation. data_permutation_.clear(); data_permutation_.resize(hdf_blobs_[0]->shape(0)); for (int i = 0; i < hdf_blobs_[0]->shape(0); i++) data_permutation_[i] = i; // Shuffle if needed. if (this->layer_param_.hdf5_data_param().shuffle()) { std::random_shuffle(data_permutation_.begin(), data_permutation_.end()); DLOG(INFO) << "Successully loaded " << hdf_blobs_[0]->shape(0) << " rows (shuffled)"; } else { DLOG(INFO) << "Successully loaded " << hdf_blobs_[0]->shape(0) << " rows"; } } template <typename Dtype> void HDF5DataLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { // Refuse transformation parameters since HDF5 is totally generic. CHECK(!this->layer_param_.has_transform_param()) << this->type() << " does not transform data."; // Read the source to parse the filenames. const string& source = this->layer_param_.hdf5_data_param().source(); LOG(INFO) << "Loading list of HDF5 filenames from: " << source; hdf_filenames_.clear(); std::ifstream source_file(source.c_str()); if (source_file.is_open()) { std::string line; while (source_file >> line) { hdf_filenames_.push_back(line); } } else { LOG(FATAL) << "Failed to open source file: " << source; } source_file.close(); num_files_ = hdf_filenames_.size(); current_file_ = 0; LOG(INFO) << "Number of HDF5 files: " << num_files_; CHECK_GE(num_files_, 1) << "Must have at least 1 HDF5 filename listed in " << source; file_permutation_.clear(); file_permutation_.resize(num_files_); // Default to identity permutation. for (int i = 0; i < num_files_; i++) { file_permutation_[i] = i; } // Shuffle if needed. if (this->layer_param_.hdf5_data_param().shuffle()) { std::random_shuffle(file_permutation_.begin(), file_permutation_.end()); } // Load the first HDF5 file and initialize the line counter. LoadHDF5FileData(hdf_filenames_[file_permutation_[current_file_]].c_str()); current_row_ = 0; // Reshape blobs. const int batch_size = this->layer_param_.hdf5_data_param().batch_size(); const int top_size = this->layer_param_.top_size(); vector<int> top_shape; for (int i = 0; i < top_size; ++i) { top_shape.resize(hdf_blobs_[i]->num_axes()); top_shape[0] = batch_size; for (int j = 1; j < top_shape.size(); ++j) { top_shape[j] = hdf_blobs_[i]->shape(j); } top[i]->Reshape(top_shape); } } template <typename Dtype> void HDF5DataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const int batch_size = this->layer_param_.hdf5_data_param().batch_size(); for (int i = 0; i < batch_size; ++i, ++current_row_) { if (current_row_ == hdf_blobs_[0]->shape(0)) { if (num_files_ > 1) { ++current_file_; if (current_file_ == num_files_) { current_file_ = 0; if (this->layer_param_.hdf5_data_param().shuffle()) { std::random_shuffle(file_permutation_.begin(), file_permutation_.end()); } DLOG(INFO) << "Looping around to first file."; } LoadHDF5FileData( hdf_filenames_[file_permutation_[current_file_]].c_str()); } current_row_ = 0; if (this->layer_param_.hdf5_data_param().shuffle()) std::random_shuffle(data_permutation_.begin(), data_permutation_.end()); } for (int j = 0; j < this->layer_param_.top_size(); ++j) { int data_dim = top[j]->count() / top[j]->shape(0); caffe_copy(data_dim, &hdf_blobs_[j]->cpu_data()[data_permutation_[current_row_] * data_dim], &top[j]->mutable_cpu_data()[i * data_dim]); } } } #ifdef CPU_ONLY STUB_GPU_FORWARD(HDF5DataLayer, Forward); #endif INSTANTIATE_CLASS(HDF5DataLayer); REGISTER_LAYER_CLASS(HDF5Data); } // namespace caffe <|endoftext|>
<commit_before>#include <utility> #include <vector> #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/vision_layers.hpp" #include "caffe/test/test_caffe_main.hpp" namespace caffe { template <typename Dtype> class ArgMaxLayerTest : public CPUDeviceTest<Dtype> { protected: ArgMaxLayerTest() : blob_bottom_(new Blob<Dtype>(10, 20, 1, 1)), blob_top_(new Blob<Dtype>()), top_k_(5) { Caffe::set_random_seed(1701); // fill the values FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); blob_bottom_vec_.push_back(blob_bottom_); blob_top_vec_.push_back(blob_top_); } virtual ~ArgMaxLayerTest() { delete blob_bottom_; delete blob_top_; } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; size_t top_k_; }; TYPED_TEST_CASE(ArgMaxLayerTest, TestDtypes); TYPED_TEST(ArgMaxLayerTest, TestSetup) { LayerParameter layer_param; ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num()); EXPECT_EQ(this->blob_top_->channels(), 1); } TYPED_TEST(ArgMaxLayerTest, TestSetupMaxVal) { LayerParameter layer_param; ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param(); argmax_param->set_out_max_val(true); ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num()); EXPECT_EQ(this->blob_top_->channels(), 2); } TYPED_TEST(ArgMaxLayerTest, TestCPU) { LayerParameter layer_param; ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Now, check values const TypeParam* bottom_data = this->blob_bottom_->cpu_data(); const TypeParam* top_data = this->blob_top_->cpu_data(); int max_ind; TypeParam max_val; int num = this->blob_bottom_->num(); int dim = this->blob_bottom_->count() / num; for (int i = 0; i < num; ++i) { EXPECT_GE(top_data[i], 0); EXPECT_LE(top_data[i], dim); max_ind = top_data[i]; max_val = bottom_data[i * dim + max_ind]; for (int j = 0; j < dim; ++j) { EXPECT_LE(bottom_data[i * dim + j], max_val); } } } TYPED_TEST(ArgMaxLayerTest, TestCPUMaxVal) { LayerParameter layer_param; ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param(); argmax_param->set_out_max_val(true); ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Now, check values const TypeParam* bottom_data = this->blob_bottom_->cpu_data(); const TypeParam* top_data = this->blob_top_->cpu_data(); int max_ind; TypeParam max_val; int num = this->blob_bottom_->num(); int dim = this->blob_bottom_->count() / num; for (int i = 0; i < num; ++i) { EXPECT_GE(top_data[i], 0); EXPECT_LE(top_data[i], dim); max_ind = top_data[i * 2]; max_val = top_data[i * 2 + 1]; EXPECT_EQ(bottom_data[i * dim + max_ind], max_val); for (int j = 0; j < dim; ++j) { EXPECT_LE(bottom_data[i * dim + j], max_val); } } } TYPED_TEST(ArgMaxLayerTest, TestCPUTopK) { LayerParameter layer_param; ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param(); argmax_param->set_top_k(this->top_k_); ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Now, check values int max_ind; TypeParam max_val; int num = this->blob_bottom_->num(); int dim = this->blob_bottom_->count() / num; for (int i = 0; i < num; ++i) { EXPECT_GE(this->blob_top_->data_at(i, 0, 0, 0), 0); EXPECT_LE(this->blob_top_->data_at(i, 0, 0, 0), dim); for (int j = 0; j < this->top_k_; ++j) { max_ind = this->blob_top_->data_at(i, 0, j, 0); max_val = this->blob_bottom_->data_at(i, max_ind, 0, 0); int count = 0; for (int k = 0; k < dim; ++k) { if (this->blob_bottom_->data_at(i, k, 0, 0) > max_val) { ++count; } } EXPECT_EQ(j, count); } } } TYPED_TEST(ArgMaxLayerTest, TestCPUMaxValTopK) { LayerParameter layer_param; ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param(); argmax_param->set_out_max_val(true); argmax_param->set_top_k(this->top_k_); ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Now, check values int max_ind; TypeParam max_val; int num = this->blob_bottom_->num(); int dim = this->blob_bottom_->count() / num; for (int i = 0; i < num; ++i) { EXPECT_GE(this->blob_top_->data_at(i, 0, 0, 0), 0); EXPECT_LE(this->blob_top_->data_at(i, 0, 0, 0), dim); for (int j = 0; j < this->top_k_; ++j) { max_ind = this->blob_top_->data_at(i, 0, j, 0); max_val = this->blob_top_->data_at(i, 1, j, 0); EXPECT_EQ(this->blob_bottom_->data_at(i, max_ind, 0, 0), max_val); int count = 0; for (int k = 0; k < dim; ++k) { if (this->blob_bottom_->data_at(i, k, 0, 0) > max_val) { ++count; } } EXPECT_EQ(j, count); } } } } // namespace caffe <commit_msg>Generalise ArgMaxLayerTest bottom blob shape<commit_after>#include <utility> #include <vector> #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/vision_layers.hpp" #include "caffe/test/test_caffe_main.hpp" namespace caffe { template <typename Dtype> class ArgMaxLayerTest : public CPUDeviceTest<Dtype> { protected: ArgMaxLayerTest() : blob_bottom_(new Blob<Dtype>(10, 10, 20, 20)), blob_top_(new Blob<Dtype>()), top_k_(5) { Caffe::set_random_seed(1701); // fill the values FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); blob_bottom_vec_.push_back(blob_bottom_); blob_top_vec_.push_back(blob_top_); } virtual ~ArgMaxLayerTest() { delete blob_bottom_; delete blob_top_; } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; size_t top_k_; }; TYPED_TEST_CASE(ArgMaxLayerTest, TestDtypes); TYPED_TEST(ArgMaxLayerTest, TestSetup) { LayerParameter layer_param; ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num()); EXPECT_EQ(this->blob_top_->channels(), 1); } TYPED_TEST(ArgMaxLayerTest, TestSetupMaxVal) { LayerParameter layer_param; ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param(); argmax_param->set_out_max_val(true); ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num()); EXPECT_EQ(this->blob_top_->channels(), 2); } TYPED_TEST(ArgMaxLayerTest, TestCPU) { LayerParameter layer_param; ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Now, check values const TypeParam* bottom_data = this->blob_bottom_->cpu_data(); const TypeParam* top_data = this->blob_top_->cpu_data(); int max_ind; TypeParam max_val; int num = this->blob_bottom_->num(); int dim = this->blob_bottom_->count() / num; for (int i = 0; i < num; ++i) { EXPECT_GE(top_data[i], 0); EXPECT_LE(top_data[i], dim); max_ind = top_data[i]; max_val = bottom_data[i * dim + max_ind]; for (int j = 0; j < dim; ++j) { EXPECT_LE(bottom_data[i * dim + j], max_val); } } } TYPED_TEST(ArgMaxLayerTest, TestCPUMaxVal) { LayerParameter layer_param; ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param(); argmax_param->set_out_max_val(true); ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Now, check values const TypeParam* bottom_data = this->blob_bottom_->cpu_data(); const TypeParam* top_data = this->blob_top_->cpu_data(); int max_ind; TypeParam max_val; int num = this->blob_bottom_->num(); int dim = this->blob_bottom_->count() / num; for (int i = 0; i < num; ++i) { EXPECT_GE(top_data[i], 0); EXPECT_LE(top_data[i], dim); max_ind = top_data[i * 2]; max_val = top_data[i * 2 + 1]; EXPECT_EQ(bottom_data[i * dim + max_ind], max_val); for (int j = 0; j < dim; ++j) { EXPECT_LE(bottom_data[i * dim + j], max_val); } } } TYPED_TEST(ArgMaxLayerTest, TestCPUTopK) { LayerParameter layer_param; ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param(); argmax_param->set_top_k(this->top_k_); ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Now, check values const TypeParam* bottom_data = this->blob_bottom_->cpu_data(); int max_ind; TypeParam max_val; int num = this->blob_bottom_->num(); int dim = this->blob_bottom_->count() / num; for (int i = 0; i < num; ++i) { EXPECT_GE(this->blob_top_->data_at(i, 0, 0, 0), 0); EXPECT_LE(this->blob_top_->data_at(i, 0, 0, 0), dim); for (int j = 0; j < this->top_k_; ++j) { max_ind = this->blob_top_->data_at(i, 0, j, 0); max_val = bottom_data[i * dim + max_ind]; int count = 0; for (int k = 0; k < dim; ++k) { if (bottom_data[i * dim + k] > max_val) { ++count; } } EXPECT_EQ(j, count); } } } TYPED_TEST(ArgMaxLayerTest, TestCPUMaxValTopK) { LayerParameter layer_param; ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param(); argmax_param->set_out_max_val(true); argmax_param->set_top_k(this->top_k_); ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Now, check values const TypeParam* bottom_data = this->blob_bottom_->cpu_data(); int max_ind; TypeParam max_val; int num = this->blob_bottom_->num(); int dim = this->blob_bottom_->count() / num; for (int i = 0; i < num; ++i) { EXPECT_GE(this->blob_top_->data_at(i, 0, 0, 0), 0); EXPECT_LE(this->blob_top_->data_at(i, 0, 0, 0), dim); for (int j = 0; j < this->top_k_; ++j) { max_ind = this->blob_top_->data_at(i, 0, j, 0); max_val = this->blob_top_->data_at(i, 1, j, 0); EXPECT_EQ(bottom_data[i * dim + max_ind], max_val); int count = 0; for (int k = 0; k < dim; ++k) { if (bottom_data[i * dim + k] > max_val) { ++count; } } EXPECT_EQ(j, count); } } } } // namespace caffe <|endoftext|>
<commit_before>/*MIT License Copyright (c) 2017 TU Ilmenau, Systems and Software Engineering Group 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. */ /* * Simple C++UML Example. In this example simple UML-Elements (Class, Model, Operation,...) will be created. Some model contet will be printed out followed by the informations of metamodel and meta-metamodel. */ #include <iostream> #include "abstractDataTypes/SubsetUnion.hpp" #include "uml/UmlFactory.hpp" #include "uml/UmlPackage.hpp" #include "uml/Class.hpp" #include "uml/Model.hpp" #include "uml/Operation.hpp" #include "uml/InstanceSpecification.hpp" #include "ecore/EClass.hpp" #include "ecore/EOperation.hpp" #include "umlReflection/UMLPackage.hpp" using namespace std; int main() { //############# Create simple UML model ############# std::shared_ptr<uml::UmlFactory> factory = uml::UmlFactory::eInstance(); std::shared_ptr<uml::UmlPackage> package = uml::UmlPackage::eInstance(); std::shared_ptr<uml::Model> p = factory->createModel(); p->setName("Model"); // std::shared_ptr<uml::Class> c = factory->createClass_in_Package(p); c->setName("Class1"); // //use a string to create a class std::shared_ptr<ecore::EObject> a = factory->create("Class", p, package->TYPE_ATTRIBUTE_PACKAGE); c = std::dynamic_pointer_cast<uml::Class>(a); c->setName("Class2"); //use a Package::MetaClass-ID to create a class std::shared_ptr<ecore::EObject> a = factory->create(uml::UmlPackage::CLASS_CLASS, p, package->TYPE_ATTRIBUTE_PACKAGE); c = std::dynamic_pointer_cast<uml::Class>(a); c->setName("Class4"); //use a MetaClass to create a class std::shared_ptr<ecore::EObject> a = factory->create(c->getMetaClass(), p, package->TYPE_ATTRIBUTE_PACKAGE); c = std::dynamic_pointer_cast<uml::Class>(a); c->setName("Class3"); c->setPackage(p); //use a UmkPackage MetaClass to create a class std::shared_ptr<ecore::EObject> a = factory->create(package->getClass_Class(), p, package->TYPE_ATTRIBUTE_PACKAGE); c = std::dynamic_pointer_cast<uml::Class>(a); c->setName("Class5"); // //create an operation std::shared_ptr<uml::Operation> o = factory->createOperation_in_Class(c); o->setName("do"); //create an UML-Objekt (InstanceSpecification) of Class2 std::shared_ptr<uml::InstanceSpecification> i = factory->createInstanceSpecification_in_Owner(p); i->setName("o"); std::shared_ptr<Bag<uml::Classifier>> t = i->getClassifier(); t->push_back(c); //set Type to Class2 //############# Print model content ############# cout << "______________ Model ____________" << endl; std::shared_ptr<Bag<uml::PackageableElement>> elements = p->getPackagedElement(); for(std::shared_ptr<uml::PackageableElement>it : *elements) { // optional type check using UML Metamodel std::shared_ptr<ecore::EClass> uc = uml::UmlPackage::eInstance()->getClass_Class(); if(it->eClass() == uc->eClass()) { cout << it->getName() << " is a Class"<< endl; std::shared_ptr<uml::Class> itC = std::dynamic_pointer_cast<uml::Class>(it); // It is certainly an uml::Class std::shared_ptr<Bag<uml::Operation>> opList = itC->getOwnedOperation(); for(std::shared_ptr<uml::Operation>it : *opList) { cout << it->getName() << endl; } } else { cout << it->getName() << " is a " << it->eClass()->getName() << endl; } } cout << "______________ Ecore MetaModel ____________" << endl; std::shared_ptr<ecore::EClass> mc = c->eClass(); // UML is defined with ecore cout << mc->getName() << " :" << endl; std::shared_ptr<Bag<ecore::EOperation>> opList = mc->getEAllOperations(); for(std::shared_ptr<ecore::EOperation> it : *opList) { cout << it->getName() << endl; } cout << "___________ Ecore MetaMetaModel _______________" << endl; std::shared_ptr<ecore::EClass> mmc = mc->eClass(); cout << mmc->getName() << " :" << endl; std::shared_ptr<Bag<ecore::EOperation>> opList2 = mmc->getEAllOperations(); for(std::shared_ptr<ecore::EOperation> it : *opList2) { cout << it->getName() << endl; } return 0; } <commit_msg>bugfix...<commit_after>/*MIT License Copyright (c) 2017 TU Ilmenau, Systems and Software Engineering Group 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. */ /* * Simple C++UML Example. In this example simple UML-Elements (Class, Model, Operation,...) will be created. Some model contet will be printed out followed by the informations of metamodel and meta-metamodel. */ #include <iostream> #include "abstractDataTypes/SubsetUnion.hpp" #include "uml/UmlFactory.hpp" #include "uml/UmlPackage.hpp" #include "uml/Class.hpp" #include "uml/Model.hpp" #include "uml/Operation.hpp" #include "uml/InstanceSpecification.hpp" #include "ecore/EClass.hpp" #include "ecore/EOperation.hpp" #include "umlReflection/UMLPackage.hpp" using namespace std; int main() { //############# Create simple UML model ############# std::shared_ptr<uml::UmlFactory> factory = uml::UmlFactory::eInstance(); std::shared_ptr<uml::UmlPackage> package = uml::UmlPackage::eInstance(); std::shared_ptr<uml::Model> p = factory->createModel(); p->setName("Model"); std::shared_ptr<uml::Class> c = factory->createClass_in_Package(p); c->setName("Class1"); //use a string to create a class std::shared_ptr<ecore::EObject> a = factory->create("Class", p, package->TYPE_ATTRIBUTE_PACKAGE); c = std::dynamic_pointer_cast<uml::Class>(a); c->setName("Class2"); //use a Package::MetaClass-ID to create a class std::shared_ptr<ecore::EObject> a = factory->create(uml::UmlPackage::CLASS_CLASS, p, package->TYPE_ATTRIBUTE_PACKAGE); c = std::dynamic_pointer_cast<uml::Class>(a); c->setName("Class43"); //use a MetaClass to create a class std::shared_ptr<ecore::EObject> a = factory->create(c->eClass(), p, package->TYPE_ATTRIBUTE_PACKAGE); c = std::dynamic_pointer_cast<uml::Class>(a); c->setName("Class4"); c->setPackage(p); //use a UmkPackage MetaClass to create a class std::shared_ptr<ecore::EObject> a = factory->create(package->getClass_Class(), p, package->TYPE_ATTRIBUTE_PACKAGE); c = std::dynamic_pointer_cast<uml::Class>(a); c->setName("Class5"); // //create an operation std::shared_ptr<uml::Operation> o = factory->createOperation_in_Class(c); o->setName("do"); //create an UML-Objekt (InstanceSpecification) of Class2 std::shared_ptr<uml::InstanceSpecification> i = factory->createInstanceSpecification_in_Owner(p); i->setName("o"); std::shared_ptr<Bag<uml::Classifier>> t = i->getClassifier(); t->push_back(c); //set Type to Class2 //############# Print model content ############# cout << "______________ Model ____________" << endl; std::shared_ptr<Bag<uml::PackageableElement>> elements = p->getPackagedElement(); for(std::shared_ptr<uml::PackageableElement>it : *elements) { // optional type check using UML Metamodel std::shared_ptr<ecore::EClass> uc = uml::UmlPackage::eInstance()->getClass_Class(); if(it->eClass() == uc->eClass()) { cout << it->getName() << " is a Class"<< endl; std::shared_ptr<uml::Class> itC = std::dynamic_pointer_cast<uml::Class>(it); // It is certainly an uml::Class std::shared_ptr<Bag<uml::Operation>> opList = itC->getOwnedOperation(); for(std::shared_ptr<uml::Operation>it : *opList) { cout << it->getName() << endl; } } else { cout << it->getName() << " is a " << it->eClass()->getName() << endl; } } cout << "______________ Ecore MetaModel ____________" << endl; std::shared_ptr<ecore::EClass> mc = c->eClass(); // UML is defined with ecore cout << mc->getName() << " :" << endl; std::shared_ptr<Bag<ecore::EOperation>> opList = mc->getEAllOperations(); for(std::shared_ptr<ecore::EOperation> it : *opList) { cout << it->getName() << endl; } cout << "___________ Ecore MetaMetaModel _______________" << endl; std::shared_ptr<ecore::EClass> mmc = mc->eClass(); cout << mmc->getName() << " :" << endl; std::shared_ptr<Bag<ecore::EOperation>> opList2 = mmc->getEAllOperations(); for(std::shared_ptr<ecore::EOperation> it : *opList2) { cout << it->getName() << endl; } return 0; } <|endoftext|>
<commit_before>#include<stdio.h> #include<string.h> #include<errno.h> #include<assert.h> #include"Logger.h" #include"../SimpleFS/CSimpleFS.h" #include"../SimpleFS/CDirectory.h" #include"fuseoper.h" //http://fuse.sourceforge.net/doxygen/fusexmp__fh_8c.html //https://www.cs.hmc.edu/~geoff/classes/hmc.cs135.201001/homework/fuse/fuse_doc.html #define FUSE_USE_VERSION 26 extern "C" { #include <fuse.h> } static SimpleFilesystem *fs; std::string mountpoint; struct fuse *fusectx = NULL; struct fuse_chan *fuse_chan = NULL; static int fuse_getattr(const char *path, struct stat *stbuf) { LOG(LogLevel::INFO) << "FUSE: getattr '" << path << "'"; memset(stbuf, 0, sizeof(struct stat)); if (strcmp(path, "/") == 0) { stbuf->st_mode = S_IFDIR | 0755; stbuf->st_nlink = 2; return 0; } try { INODEPTR node = fs->OpenNode(path); node->Lock(); stbuf->st_size = node->size; stbuf->st_blocks = node->size/512; stbuf->st_nlink = 1; if (node->type == INODETYPE::dir) { stbuf->st_mode = S_IFDIR | 0755; } else { stbuf->st_mode = S_IFREG | 0666; } node->Unlock(); } catch(const int &err) { return -err; } return 0; } static int fuse_utimens(const char *path, const struct timespec tv[2]) { LOG(LogLevel::INFO) << "FUSE: utimens '" << path << "'"; return 0; } static int fuse_chmod(const char *path, mode_t mode) { LOG(LogLevel::INFO) << "FUSE: chmod '" << path << "'"; return 0; } static int fuse_chown(const char *path, uid_t uid, gid_t gid) { LOG(LogLevel::INFO) << "FUSE: chown '" << path << "'"; return 0; } static int fuse_truncate(const char *path, off_t size) { LOG(LogLevel::INFO) << "FUSE: truncate '" << path << "' size=" << size; try { INODEPTR node = fs->OpenFile(path); node->Truncate(size); } catch(const int &err) { return -err; } return 0; } static int fuse_opendir(const char *path, struct fuse_file_info *fi) { LOG(LogLevel::INFO) << "FUSE: opendir '" << path << "'"; try { CDirectory dir = fs->OpenDir(path); fi->fh = dir.dirnode->id; } catch(const int &err) { return -err; } return 0; } static int fuse_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { (void) offset; LOG(LogLevel::INFO) << "FUSE: readdir '" << path << "'"; try { CDirectory dir = fs->OpenDir(fi->fh); filler(buf, ".", NULL, 0); filler(buf, "..", NULL, 0); dir.ForEachEntry([&](DIRENTRY &de) { if (de.id == CFragmentDesc::INVALIDID) return FOREACHENTRYRET::OK; filler(buf, de.name, NULL, 0); return FOREACHENTRYRET::OK; }); } catch(const int &err) { return -err; } return 0; } static int fuse_open(const char *path, struct fuse_file_info *fi) { LOG(LogLevel::INFO) << "FUSE: open '" << path << "'"; try { INODEPTR node = fs->OpenFile(path); fi->fh = node->id; } catch(const int &err) { return -err; } /* if ((fi->flags & 3) != O_RDONLY) return -EACCES; */ return 0; } static int fuse_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { LOG(LogLevel::INFO) << "FUSE: read '" << path << "' ofs=" << offset << " size=" << size; try { INODEPTR node = fs->OpenFile(fi->fh); size = node->Read((int8_t*)buf, offset, size); } catch(const int &err) { return -err; } return size; } static int fuse_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { LOG(LogLevel::INFO) << "FUSE: write '" << path << "' ofs=" << offset << " size=" << size; try { INODEPTR node = fs->OpenFile(fi->fh); node->Write((int8_t*)buf, offset, size); } catch(const int &err) { return -err; } return size; } static int fuse_mkdir(const char *path, mode_t mode) { LOG(LogLevel::INFO) << "FUSE: mkdir '" << path << "'"; // test if dir is empty? Looks like this is tested already std::vector<std::string> splitpath; splitpath = SplitPath(std::string(path)); assert(splitpath.size() >= 1); std::string dirname = splitpath.back(); splitpath.pop_back(); try { CDirectory dir = fs->OpenDir(splitpath); dir.CreateDirectory(dirname); } catch(const int &err) { return -err; } return 0; } static int fuse_rmdir(const char *path) { LOG(LogLevel::INFO) << "FUSE: rmdir '" << path << "'"; try { CDirectory dir = fs->OpenDir(path); if (!dir.IsEmpty()) return -ENOTEMPTY; dir.dirnode->Remove(); } catch(const int &err) { return -err; } return 0; } static int fuse_unlink(const char *path) { LOG(LogLevel::INFO) << "FUSE: unlink '" << path << "'"; try { INODEPTR node = fs->OpenNode(path); node->Remove(); } catch(const int &err) { return -err; } return 0; } static int fuse_create(const char *path, mode_t mode, struct fuse_file_info *fi) { LOG(LogLevel::INFO) << "FUSE: create '" << path << "'"; std::vector<std::string> splitpath; splitpath = SplitPath(std::string(path)); assert(splitpath.size() >= 1); std::string filename = splitpath.back(); splitpath.pop_back(); try { CDirectory dir = fs->OpenDir(splitpath); fi->fh = dir.CreateFile(filename); } catch(const int &err) { return -err; } return 0; } static int fuse_access(const char *path, int mask) { LOG(LogLevel::INFO) << "FUSE: access '" << path << "'"; try { INODEPTR node = fs->OpenNode(path); } catch(const int &err) { return -err; } return 0; } static int fuse_rename(const char *oldpath, const char *newpath) { LOG(LogLevel::INFO) << "FUSE: create '" << oldpath << "' to '" << newpath << "'"; std::vector<std::string> splitpath; splitpath = SplitPath(std::string(newpath)); assert(splitpath.size() >= 1); try { INODEPTR newnode = fs->OpenNode(splitpath); return -EEXIST; } catch(...){} try { INODEPTR node = fs->OpenNode(oldpath); std::string filename = splitpath.back(); splitpath.pop_back(); CDirectory dir = fs->OpenDir(splitpath); fs->Rename(node, dir, filename); // TODO: check if rename overwrites an already existing file. } catch(const int &err) { return -err; } return 0; } static int fuse_statfs(const char *path, struct statvfs *buf) { LOG(LogLevel::INFO) << "FUSE: statfs '" << path << "'"; CStatFS stat; fs->StatFS(&stat); buf->f_avail = stat.f_bavail; buf->f_bfree = stat.f_bfree; buf->f_blocks = stat.f_blocks; buf->f_bsize = stat.f_bsize; buf->f_files = stat.f_files; buf->f_frsize = stat.f_frsize; buf->f_namemax = stat.f_namemax; return 0; } int StopFuse() { if (fs == NULL) return EXIT_SUCCESS; if (fusectx == NULL) return EXIT_SUCCESS; LOG(LogLevel::INFO) << "Unmount FUSE mountpoint: " << mountpoint; fuse_unmount(mountpoint.c_str(), fuse_chan); return EXIT_SUCCESS; } int StartFuse(int argc, char *argv[], const char* _mountpoint, SimpleFilesystem &_fs) { fs = &_fs; mountpoint = std::string(_mountpoint); LOG(LogLevel::INFO) << "FUSE Version: " << fuse_version(); struct fuse_args args = FUSE_ARGS_INIT(0, NULL); fuse_opt_add_arg(&args, "-odirect_io"); fuse_opt_add_arg(&args, "-obig_writes"); fuse_opt_add_arg(&args, "-oasync_read"); // fuse_opt_add_arg(&args, "-f"); // fuse_opt_add_arg(&args, _mountpoint); struct fuse_operations fuse_oper; memset(&fuse_oper, 0, sizeof(struct fuse_operations)); fuse_oper.getattr = fuse_getattr; fuse_oper.opendir = fuse_opendir; fuse_oper.readdir = fuse_readdir; fuse_oper.open = fuse_open; fuse_oper.read = fuse_read; fuse_oper.write = fuse_write; fuse_oper.mkdir = fuse_mkdir; fuse_oper.create = fuse_create; fuse_oper.rmdir = fuse_rmdir; fuse_oper.unlink = fuse_unlink; fuse_oper.truncate = fuse_truncate; fuse_oper.access = fuse_access; fuse_oper.rename = fuse_rename; fuse_oper.chmod = fuse_chmod; fuse_oper.chown = fuse_chown; fuse_oper.statfs = fuse_statfs; fuse_oper.utimens = fuse_utimens; //fuse_oper.flag_nullpath_ok = 1; fuse_chan = fuse_mount(_mountpoint, &args); fusectx = fuse_new(fuse_chan, &args, &fuse_oper, sizeof(fuse_oper), NULL); int ret = fuse_loop_mt(fusectx); fuse_destroy(fusectx); return ret; // return fuse_loop(fusectx); // return fuse_main(args.argc, args.argv, &fuse_oper, NULL); } <commit_msg>Fix statfs<commit_after>#include<stdio.h> #include<string.h> #include<errno.h> #include<assert.h> #include"Logger.h" #include"../SimpleFS/CSimpleFS.h" #include"../SimpleFS/CDirectory.h" #include"fuseoper.h" //http://fuse.sourceforge.net/doxygen/fusexmp__fh_8c.html //https://www.cs.hmc.edu/~geoff/classes/hmc.cs135.201001/homework/fuse/fuse_doc.html #define FUSE_USE_VERSION 26 extern "C" { #include <fuse.h> } static SimpleFilesystem *fs; std::string mountpoint; struct fuse *fusectx = NULL; struct fuse_chan *fuse_chan = NULL; static int fuse_getattr(const char *path, struct stat *stbuf) { LOG(LogLevel::INFO) << "FUSE: getattr '" << path << "'"; memset(stbuf, 0, sizeof(struct stat)); if (strcmp(path, "/") == 0) { stbuf->st_mode = S_IFDIR | 0755; stbuf->st_nlink = 2; return 0; } try { INODEPTR node = fs->OpenNode(path); node->Lock(); stbuf->st_size = node->size; stbuf->st_blocks = node->size/512; stbuf->st_nlink = 1; if (node->type == INODETYPE::dir) { stbuf->st_mode = S_IFDIR | 0755; } else { stbuf->st_mode = S_IFREG | 0666; } node->Unlock(); } catch(const int &err) { return -err; } return 0; } static int fuse_utimens(const char *path, const struct timespec tv[2]) { LOG(LogLevel::INFO) << "FUSE: utimens '" << path << "'"; return 0; } static int fuse_chmod(const char *path, mode_t mode) { LOG(LogLevel::INFO) << "FUSE: chmod '" << path << "'"; return 0; } static int fuse_chown(const char *path, uid_t uid, gid_t gid) { LOG(LogLevel::INFO) << "FUSE: chown '" << path << "'"; return 0; } static int fuse_truncate(const char *path, off_t size) { LOG(LogLevel::INFO) << "FUSE: truncate '" << path << "' size=" << size; try { INODEPTR node = fs->OpenFile(path); node->Truncate(size); } catch(const int &err) { return -err; } return 0; } static int fuse_opendir(const char *path, struct fuse_file_info *fi) { LOG(LogLevel::INFO) << "FUSE: opendir '" << path << "'"; try { CDirectory dir = fs->OpenDir(path); fi->fh = dir.dirnode->id; } catch(const int &err) { return -err; } return 0; } static int fuse_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { (void) offset; LOG(LogLevel::INFO) << "FUSE: readdir '" << path << "'"; try { CDirectory dir = fs->OpenDir(fi->fh); filler(buf, ".", NULL, 0); filler(buf, "..", NULL, 0); dir.ForEachEntry([&](DIRENTRY &de) { if (de.id == CFragmentDesc::INVALIDID) return FOREACHENTRYRET::OK; filler(buf, de.name, NULL, 0); return FOREACHENTRYRET::OK; }); } catch(const int &err) { return -err; } return 0; } static int fuse_open(const char *path, struct fuse_file_info *fi) { LOG(LogLevel::INFO) << "FUSE: open '" << path << "'"; try { INODEPTR node = fs->OpenFile(path); fi->fh = node->id; } catch(const int &err) { return -err; } /* if ((fi->flags & 3) != O_RDONLY) return -EACCES; */ return 0; } static int fuse_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { LOG(LogLevel::INFO) << "FUSE: read '" << path << "' ofs=" << offset << " size=" << size; try { INODEPTR node = fs->OpenFile(fi->fh); size = node->Read((int8_t*)buf, offset, size); } catch(const int &err) { return -err; } return size; } static int fuse_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { LOG(LogLevel::INFO) << "FUSE: write '" << path << "' ofs=" << offset << " size=" << size; try { INODEPTR node = fs->OpenFile(fi->fh); node->Write((int8_t*)buf, offset, size); } catch(const int &err) { return -err; } return size; } static int fuse_mkdir(const char *path, mode_t mode) { LOG(LogLevel::INFO) << "FUSE: mkdir '" << path << "'"; // test if dir is empty? Looks like this is tested already std::vector<std::string> splitpath; splitpath = SplitPath(std::string(path)); assert(splitpath.size() >= 1); std::string dirname = splitpath.back(); splitpath.pop_back(); try { CDirectory dir = fs->OpenDir(splitpath); dir.CreateDirectory(dirname); } catch(const int &err) { return -err; } return 0; } static int fuse_rmdir(const char *path) { LOG(LogLevel::INFO) << "FUSE: rmdir '" << path << "'"; try { CDirectory dir = fs->OpenDir(path); if (!dir.IsEmpty()) return -ENOTEMPTY; dir.dirnode->Remove(); } catch(const int &err) { return -err; } return 0; } static int fuse_unlink(const char *path) { LOG(LogLevel::INFO) << "FUSE: unlink '" << path << "'"; try { INODEPTR node = fs->OpenNode(path); node->Remove(); } catch(const int &err) { return -err; } return 0; } static int fuse_create(const char *path, mode_t mode, struct fuse_file_info *fi) { LOG(LogLevel::INFO) << "FUSE: create '" << path << "'"; std::vector<std::string> splitpath; splitpath = SplitPath(std::string(path)); assert(splitpath.size() >= 1); std::string filename = splitpath.back(); splitpath.pop_back(); try { CDirectory dir = fs->OpenDir(splitpath); fi->fh = dir.CreateFile(filename); } catch(const int &err) { return -err; } return 0; } static int fuse_access(const char *path, int mask) { LOG(LogLevel::INFO) << "FUSE: access '" << path << "'"; try { INODEPTR node = fs->OpenNode(path); } catch(const int &err) { return -err; } return 0; } static int fuse_rename(const char *oldpath, const char *newpath) { LOG(LogLevel::INFO) << "FUSE: create '" << oldpath << "' to '" << newpath << "'"; std::vector<std::string> splitpath; splitpath = SplitPath(std::string(newpath)); assert(splitpath.size() >= 1); try { INODEPTR newnode = fs->OpenNode(splitpath); return -EEXIST; } catch(...){} try { INODEPTR node = fs->OpenNode(oldpath); std::string filename = splitpath.back(); splitpath.pop_back(); CDirectory dir = fs->OpenDir(splitpath); fs->Rename(node, dir, filename); // TODO: check if rename overwrites an already existing file. } catch(const int &err) { return -err; } return 0; } static int fuse_statfs(const char *path, struct statvfs *buf) { LOG(LogLevel::INFO) << "FUSE: statfs '" << path << "'"; CStatFS stat; fs->StatFS(&stat); buf->f_bavail = stat.f_bavail; buf->f_bfree = stat.f_bfree; buf->f_blocks = stat.f_blocks; buf->f_bsize = stat.f_bsize; buf->f_files = stat.f_files; buf->f_frsize = stat.f_frsize; buf->f_namemax = stat.f_namemax; return 0; } int StopFuse() { if (fs == NULL) return EXIT_SUCCESS; if (fusectx == NULL) return EXIT_SUCCESS; LOG(LogLevel::INFO) << "Unmount FUSE mountpoint: " << mountpoint; fuse_unmount(mountpoint.c_str(), fuse_chan); return EXIT_SUCCESS; } int StartFuse(int argc, char *argv[], const char* _mountpoint, SimpleFilesystem &_fs) { fs = &_fs; mountpoint = std::string(_mountpoint); LOG(LogLevel::INFO) << "FUSE Version: " << fuse_version(); struct fuse_args args = FUSE_ARGS_INIT(0, NULL); fuse_opt_add_arg(&args, "-odirect_io"); fuse_opt_add_arg(&args, "-obig_writes"); fuse_opt_add_arg(&args, "-oasync_read"); // fuse_opt_add_arg(&args, "-f"); // fuse_opt_add_arg(&args, _mountpoint); struct fuse_operations fuse_oper; memset(&fuse_oper, 0, sizeof(struct fuse_operations)); fuse_oper.getattr = fuse_getattr; fuse_oper.opendir = fuse_opendir; fuse_oper.readdir = fuse_readdir; fuse_oper.open = fuse_open; fuse_oper.read = fuse_read; fuse_oper.write = fuse_write; fuse_oper.mkdir = fuse_mkdir; fuse_oper.create = fuse_create; fuse_oper.rmdir = fuse_rmdir; fuse_oper.unlink = fuse_unlink; fuse_oper.truncate = fuse_truncate; fuse_oper.access = fuse_access; fuse_oper.rename = fuse_rename; fuse_oper.chmod = fuse_chmod; fuse_oper.chown = fuse_chown; fuse_oper.statfs = fuse_statfs; fuse_oper.utimens = fuse_utimens; //fuse_oper.flag_nullpath_ok = 1; fuse_chan = fuse_mount(_mountpoint, &args); fusectx = fuse_new(fuse_chan, &args, &fuse_oper, sizeof(fuse_oper), NULL); int ret = fuse_loop_mt(fusectx); fuse_destroy(fusectx); return ret; // return fuse_loop(fusectx); // return fuse_main(args.argc, args.argv, &fuse_oper, NULL); } <|endoftext|>
<commit_before>// // Copyright 2017 Shivansh Rai // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. // // $FreeBSD$ #include <array> #include <boost/filesystem.hpp> #include <boost/chrono.hpp> #include <boost/thread.hpp> #include <cstdlib> #include <dirent.h> #include <fstream> #include <iostream> #include <memory> #include <stdexcept> #include <sys/stat.h> #include <sys/wait.h> #include <unordered_set> #include "add_testcase.h" #include "generate_license.h" #include "generate_test.h" #include "read_annotations.h" #define TIMEOUT 2 // threshold (seconds) for a function call to return. std::string license; // license file generated during runtime. // Executes the passed argument "cmd" in a shell // and returns its output and the exit status. std::pair<std::string, int> generate_test::exec(const char* cmd) { const int bufsize = 128; std::array<char, bufsize> buffer; std::string usage_output; FILE* pipe = popen(cmd, "r"); if (!pipe) throw std::runtime_error("popen() failed!"); try { while (!feof(pipe)) if (std::fgets(buffer.data(), bufsize, pipe) != NULL) usage_output += buffer.data(); } catch(...) { pclose(pipe); throw "Unable to execute the command: " + std::string(cmd); } return std::make_pair<std::string, int> ((std::string)usage_output, WEXITSTATUS(pclose(pipe))); } // Generate a test for the given utility. void generate_test::generate_test(std::string utility, std::string section) { std::list<utils::opt_rel*> ident_opt_list; // List of identified option relations. std::vector<std::string> usage_messages; // Vector to store usage messages for comparison. std::string command; // Command to be executed in shell. std::string descr; // Testcase description. std::string testcase_list; // List of testcases. std::string testcase_buffer; // Buffer for (temporarily) holding testcase data. std::string test_file; // atf-sh test name. std::string util_with_section; // Section number appended to utility. std::ofstream test_ofs; // Output stream for the atf-sh test. std::pair<std::string, int> output; // Return value type for `exec()`. std::unordered_set<std::string> annot; // Hashset of utility specific annotations. int temp; // Read annotations and populate hash set "annot". annotations::read_annotations(utility, annot); util_with_section = utility + '(' + section + ')'; utils::opt_def f_opts; ident_opt_list = f_opts.check_opts(utility); test_file = "generated_tests/" + utility + "_test.sh"; // Add license in the generated test scripts. test_ofs.open(test_file, std::ios::out); test_ofs << license; // If a known option was encountered (i.e. `ident_opt_list` is // populated), produce a testcase to check the validity of the // result of that option. If no known option was encountered, // produce testcases to verify the correct (generated) usage // message when using the supported options incorrectly. // Add testcases for known options. if (!ident_opt_list.empty()) { for (const auto &i : ident_opt_list) { command = utility + " -" + i->value + " 2>&1 </dev/null"; output = generate_test::exec(command.c_str()); if (!output.first.compare(0, 6, "usage:")) { add_testcase::add_known_testcase(i->value, util_with_section, descr, output.first, test_ofs); } else { // A usage message was produced, i.e. we // failed to guess the correct usage. add_testcase::add_unknown_testcase(i->value, util_with_section, output.first, output.second, testcase_buffer); } testcase_list.append("\tatf_add_test_case " + i->value + "_flag\n"); } } // Add testcases for the options whose usage is not known (yet). if (!f_opts.opt_list.empty()) { // For the purpose of adding a "$usage_output" variable, // we choose the option which produces one. // TODO Avoid double executions of an option, i.e. one while // selecting usage message and another while generating testcase. if (f_opts.opt_list.size() == 1) { // Utility supports a single option, check if it produces a usage message. command = utility + " -" + f_opts.opt_list.front() + " 2>&1 </dev/null"; output = generate_test::exec(command.c_str()); if (output.second) test_ofs << "usage_output=\'" + output.first + "\'\n\n"; } else { // Utility supports multiple options. In case the usage message // is consistent for atleast "two" options, we reduce duplication // by assigning a variable "usage_output" in the test script. for (const auto &i : f_opts.opt_list) { command = utility + " -" + i + " 2>&1 </dev/null"; output = generate_test::exec(command.c_str()); if (output.second && usage_messages.size() < 3) usage_messages.push_back(output.first); } temp = usage_messages.size(); for (int j = 0; j < temp; j++) { if (!(usage_messages.at(j)).compare(usage_messages.at((j+1) % temp))) { test_ofs << "usage_output=\'" + output.first.substr(0, 7 + utility.size()) + "\'\n\n"; break; } } } // Execute the utility with supported options // and add (+ve)/(-ve) testcases accordingly. for (const auto &i : f_opts.opt_list) { // If the option is annotated, skip it. if (annot.find(i) != annot.end()) continue; command = utility + " -" + i + " 2>&1 </dev/null"; output = generate_test::exec(command.c_str()); if (output.second) { // Non-zero exit status was encountered. add_testcase::add_unknown_testcase(i, util_with_section, output.first, output.second, testcase_buffer); } else { // EXIT_SUCCESS was encountered. Hence, // the guessed usage was correct. add_testcase::add_known_testcase(i, util_with_section, "", output.first, test_ofs); testcase_list.append(std::string("\tatf_add_test_case ") + i + "_flag\n"); } } testcase_list.append("\tatf_add_test_case invalid_usage\n"); test_ofs << std::string("atf_test_case invalid_usage\ninvalid_usage_head()\n") + "{\n\tatf_set \"descr\" \"Verify that an invalid usage " + "with a supported option produces a valid error message" + "\"\n}\n\ninvalid_usage_body()\n{"; test_ofs << testcase_buffer + "\n}\n\n"; } // Add a testcase under "no_arguments" for // running the utility without any arguments. if (annot.find("*") == annot.end()) { command = utility + " 2>&1 </dev/null"; output = generate_test::exec(command.c_str()); add_testcase::add_noargs_testcase(util_with_section, output, test_ofs); testcase_list.append("\tatf_add_test_case no_arguments\n"); } test_ofs << "atf_init_test_cases()\n{\n" + testcase_list + "}\n"; test_ofs.close(); } int main() { std::ifstream groff_list; std::list<std::pair<std::string, std::string>> utility_list; std::string test_file; // atf-sh test name. std::string util_name; // Utility name. const char *tests_dir = "generated_tests/"; struct stat sb; struct dirent *ent; DIR *groff_dir; char answer; // User input to determine overwriting of test files. // For testing (or generating tests for only selected utilities), // the utility_list can be populated above during declaration. if (utility_list.empty()) { if ((groff_dir = opendir("groff"))) { readdir(groff_dir); // Skip directory entry for "." readdir(groff_dir); // Skip directory entry for ".." while ((ent = readdir(groff_dir))) { util_name = ent->d_name; utility_list.push_back(std::make_pair<std::string, std::string> (util_name.substr(0, util_name.length() - 2), util_name.substr(util_name.length() - 1, 1))); } closedir(groff_dir); } else { fprintf(stderr, "Could not open the directory: ./groff\nRefer to the " "section \"Populating groff scripts\" in README!\n"); return EXIT_FAILURE; } } // Check if the directory 'generated_tests' exists. if (stat(tests_dir, &sb) || !S_ISDIR(sb.st_mode)) { boost::filesystem::path dir(tests_dir); if (boost::filesystem::create_directory(dir)) std::cout << "Directory created: " << tests_dir << std::endl; } // Generate a license to be added in the generated scripts. license = add_license::generate_license(); for (const auto &util : utility_list) { test_file = tests_dir + util.first + "_test.sh"; // TODO Check before overwriting existing test scripts. // Enable line-buffering on stdout. setlinebuf(stdout); std::cout << "Generating test for: " + util.first + '('+ util.second + ')' << " ..."; boost::thread api_caller(generate_test::generate_test, util.first, util.second); if (api_caller.try_join_for(boost::chrono::seconds(TIMEOUT))) { // API call successfully returned within TIMEOUT (seconds). std::cout << "Successful\n"; } else { // API call timed out. std::cout << "Failed!\n"; // Remove the incomplete test file. remove(("generated_tests/" + util.first + "_test.sh").c_str()); } } return EXIT_SUCCESS; } <commit_msg>Avoid adding variable "usage_output" in case of an empty output<commit_after>// // Copyright 2017 Shivansh Rai // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. // // $FreeBSD$ #include <array> #include <boost/filesystem.hpp> #include <boost/chrono.hpp> #include <boost/thread.hpp> #include <cstdlib> #include <dirent.h> #include <fstream> #include <iostream> #include <memory> #include <stdexcept> #include <sys/stat.h> #include <sys/wait.h> #include <unordered_set> #include "add_testcase.h" #include "generate_license.h" #include "generate_test.h" #include "read_annotations.h" #define TIMEOUT 2 // threshold (seconds) for a function call to return. std::string license; // license file generated during runtime. // Executes the passed argument "cmd" in a shell // and returns its output and the exit status. std::pair<std::string, int> generate_test::exec(const char* cmd) { const int bufsize = 128; std::array<char, bufsize> buffer; std::string usage_output; FILE* pipe = popen(cmd, "r"); if (!pipe) throw std::runtime_error("popen() failed!"); try { while (!feof(pipe)) if (std::fgets(buffer.data(), bufsize, pipe) != NULL) usage_output += buffer.data(); } catch(...) { pclose(pipe); throw "Unable to execute the command: " + std::string(cmd); } return std::make_pair<std::string, int> ((std::string)usage_output, WEXITSTATUS(pclose(pipe))); } // Generate a test for the given utility. void generate_test::generate_test(std::string utility, std::string section) { std::list<utils::opt_rel*> ident_opt_list; // List of identified option relations. std::vector<std::string> usage_messages; // Vector to store usage messages for comparison. std::string command; // Command to be executed in shell. std::string descr; // Testcase description. std::string testcase_list; // List of testcases. std::string testcase_buffer; // Buffer for (temporarily) holding testcase data. std::string test_file; // atf-sh test name. std::string util_with_section; // Section number appended to utility. std::ofstream test_ofs; // Output stream for the atf-sh test. std::pair<std::string, int> output; // Return value type for `exec()`. std::unordered_set<std::string> annot; // Hashset of utility specific annotations. int temp; // Read annotations and populate hash set "annot". annotations::read_annotations(utility, annot); util_with_section = utility + '(' + section + ')'; utils::opt_def f_opts; ident_opt_list = f_opts.check_opts(utility); test_file = "generated_tests/" + utility + "_test.sh"; // Add license in the generated test scripts. test_ofs.open(test_file, std::ios::out); test_ofs << license; // If a known option was encountered (i.e. `ident_opt_list` is // populated), produce a testcase to check the validity of the // result of that option. If no known option was encountered, // produce testcases to verify the correct (generated) usage // message when using the supported options incorrectly. // Add testcases for known options. if (!ident_opt_list.empty()) { for (const auto &i : ident_opt_list) { command = utility + " -" + i->value + " 2>&1 </dev/null"; output = generate_test::exec(command.c_str()); if (!output.first.compare(0, 6, "usage:")) { add_testcase::add_known_testcase(i->value, util_with_section, descr, output.first, test_ofs); } else { // A usage message was produced, i.e. we // failed to guess the correct usage. add_testcase::add_unknown_testcase(i->value, util_with_section, output.first, output.second, testcase_buffer); } testcase_list.append("\tatf_add_test_case " + i->value + "_flag\n"); } } // Add testcases for the options whose usage is not known (yet). if (!f_opts.opt_list.empty()) { // For the purpose of adding a "$usage_output" variable, // we choose the option which produces one. // TODO Avoid double executions of an option, i.e. one while // selecting usage message and another while generating testcase. if (f_opts.opt_list.size() == 1) { // Utility supports a single option, check if it produces a usage message. command = utility + " -" + f_opts.opt_list.front() + " 2>&1 </dev/null"; output = generate_test::exec(command.c_str()); if (output.second && !output.first.empty()) test_ofs << "usage_output=\'" + output.first + "\'\n\n"; } else { // Utility supports multiple options. In case the usage message // is consistent for atleast "two" options, we reduce duplication // by assigning a variable "usage_output" in the test script. for (const auto &i : f_opts.opt_list) { command = utility + " -" + i + " 2>&1 </dev/null"; output = generate_test::exec(command.c_str()); if (output.second && usage_messages.size() < 3) usage_messages.push_back(output.first); } temp = usage_messages.size(); for (int j = 0; j < temp; j++) { if (!(usage_messages.at(j)).compare(usage_messages.at((j+1) % temp)) && !output.first.empty()) { test_ofs << "usage_output=\'" + output.first.substr(0, 7 + utility.size()) + "\'\n\n"; break; } } } // Execute the utility with supported options // and add (+ve)/(-ve) testcases accordingly. for (const auto &i : f_opts.opt_list) { // If the option is annotated, skip it. if (annot.find(i) != annot.end()) continue; command = utility + " -" + i + " 2>&1 </dev/null"; output = generate_test::exec(command.c_str()); if (output.second) { // Non-zero exit status was encountered. add_testcase::add_unknown_testcase(i, util_with_section, output.first, output.second, testcase_buffer); } else { // EXIT_SUCCESS was encountered. Hence, // the guessed usage was correct. add_testcase::add_known_testcase(i, util_with_section, "", output.first, test_ofs); testcase_list.append(std::string("\tatf_add_test_case ") + i + "_flag\n"); } } testcase_list.append("\tatf_add_test_case invalid_usage\n"); test_ofs << std::string("atf_test_case invalid_usage\ninvalid_usage_head()\n") + "{\n\tatf_set \"descr\" \"Verify that an invalid usage " + "with a supported option produces a valid error message" + "\"\n}\n\ninvalid_usage_body()\n{"; test_ofs << testcase_buffer + "\n}\n\n"; } // Add a testcase under "no_arguments" for // running the utility without any arguments. if (annot.find("*") == annot.end()) { command = utility + " 2>&1 </dev/null"; output = generate_test::exec(command.c_str()); add_testcase::add_noargs_testcase(util_with_section, output, test_ofs); testcase_list.append("\tatf_add_test_case no_arguments\n"); } test_ofs << "atf_init_test_cases()\n{\n" + testcase_list + "}\n"; test_ofs.close(); } int main() { std::ifstream groff_list; std::list<std::pair<std::string, std::string>> utility_list; std::string test_file; // atf-sh test name. std::string util_name; // Utility name. const char *tests_dir = "generated_tests/"; struct stat sb; struct dirent *ent; DIR *groff_dir; char answer; // User input to determine overwriting of test files. // For testing (or generating tests for only selected utilities), // the utility_list can be populated above during declaration. if (utility_list.empty()) { if ((groff_dir = opendir("groff"))) { readdir(groff_dir); // Skip directory entry for "." readdir(groff_dir); // Skip directory entry for ".." while ((ent = readdir(groff_dir))) { util_name = ent->d_name; utility_list.push_back(std::make_pair<std::string, std::string> (util_name.substr(0, util_name.length() - 2), util_name.substr(util_name.length() - 1, 1))); } closedir(groff_dir); } else { fprintf(stderr, "Could not open the directory: ./groff\nRefer to the " "section \"Populating groff scripts\" in README!\n"); return EXIT_FAILURE; } } // Check if the directory 'generated_tests' exists. if (stat(tests_dir, &sb) || !S_ISDIR(sb.st_mode)) { boost::filesystem::path dir(tests_dir); if (boost::filesystem::create_directory(dir)) std::cout << "Directory created: " << tests_dir << std::endl; } // Generate a license to be added in the generated scripts. license = add_license::generate_license(); for (const auto &util : utility_list) { test_file = tests_dir + util.first + "_test.sh"; // TODO Check before overwriting existing test scripts. // Enable line-buffering on stdout. setlinebuf(stdout); std::cout << "Generating test for: " + util.first + '('+ util.second + ')' << " ..."; boost::thread api_caller(generate_test::generate_test, util.first, util.second); if (api_caller.try_join_for(boost::chrono::seconds(TIMEOUT))) { // API call successfully returned within TIMEOUT (seconds). std::cout << "Successful\n"; } else { // API call timed out. std::cout << "Failed!\n"; // Remove the incomplete test file. remove(("generated_tests/" + util.first + "_test.sh").c_str()); } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jni_compiler.h" #include "class_linker.h" #include "compilation_unit.h" #include "compiled_method.h" #include "compiler.h" #include "compiler_llvm.h" #include "ir_builder.h" #include "logging.h" #include "oat_compilation_unit.h" #include "object.h" #include "runtime.h" #include "runtime_support_func.h" #include "shadow_frame.h" #include "utils_llvm.h" #include <llvm/BasicBlock.h> #include <llvm/DerivedTypes.h> #include <llvm/Function.h> #include <llvm/Type.h> namespace art { namespace compiler_llvm { using namespace runtime_support; JniCompiler::JniCompiler(CompilationUnit* cunit, Compiler const& compiler, OatCompilationUnit* oat_compilation_unit) : cunit_(cunit), compiler_(&compiler), module_(cunit_->GetModule()), context_(cunit_->GetLLVMContext()), irb_(*cunit_->GetIRBuilder()), oat_compilation_unit_(oat_compilation_unit), access_flags_(oat_compilation_unit->access_flags_), method_idx_(oat_compilation_unit->method_idx_), class_linker_(oat_compilation_unit->class_linker_), class_loader_(oat_compilation_unit->class_loader_), dex_cache_(oat_compilation_unit->dex_cache_), dex_file_(oat_compilation_unit->dex_file_), method_(dex_cache_->GetResolvedMethod(method_idx_)), elf_func_idx_(cunit_->AcquireUniqueElfFuncIndex()) { // Check: Ensure that the method is resolved CHECK_NE(method_, static_cast<art::Method*>(NULL)); // Check: Ensure that JNI compiler will only get "native" method CHECK((access_flags_ & kAccNative) != 0); } CompiledMethod* JniCompiler::Compile() { const bool is_static = (access_flags_ & kAccStatic) != 0; const bool is_synchronized = (access_flags_ & kAccSynchronized) != 0; DexFile::MethodId const& method_id = dex_file_->GetMethodId(method_idx_); char const return_shorty = dex_file_->GetMethodShorty(method_id)[0]; llvm::Value* this_object_or_class_object; CreateFunction(); // Set argument name llvm::Function::arg_iterator arg_begin(func_->arg_begin()); llvm::Function::arg_iterator arg_end(func_->arg_end()); llvm::Function::arg_iterator arg_iter(arg_begin); DCHECK_NE(arg_iter, arg_end); arg_iter->setName("method"); llvm::Value* method_object_addr = arg_iter++; if (!is_static) { // Non-static, the second argument is "this object" this_object_or_class_object = arg_iter++; } else { // Load class object this_object_or_class_object = irb_.LoadFromObjectOffset(method_object_addr, Method::DeclaringClassOffset().Int32Value(), irb_.getJObjectTy()); } // Actual argument (ignore method and this object) arg_begin = arg_iter; // Count the number of Object* arguments uint32_t sirt_size = 1; // "this" object pointer for non-static // "class" object pointer for static for (unsigned i = 0; arg_iter != arg_end; ++i, ++arg_iter) { arg_iter->setName(StringPrintf("a%u", i)); if (arg_iter->getType() == irb_.getJObjectTy()) { ++sirt_size; } } // Get thread object llvm::Value* thread_object_addr = irb_.CreateCall(irb_.GetRuntime(GetCurrentThread)); // Shadow stack llvm::StructType* shadow_frame_type = irb_.getShadowFrameTy(sirt_size); llvm::AllocaInst* shadow_frame_ = irb_.CreateAlloca(shadow_frame_type); // Zero-initialization of the shadow frame llvm::ConstantAggregateZero* zero_initializer = llvm::ConstantAggregateZero::get(shadow_frame_type); irb_.CreateStore(zero_initializer, shadow_frame_); // Store the method pointer llvm::Value* method_field_addr = irb_.CreatePtrDisp(shadow_frame_, irb_.getPtrEquivInt(ShadowFrame::MethodOffset()), irb_.getJObjectTy()->getPointerTo()); irb_.CreateStore(method_object_addr, method_field_addr); // Store the dex pc irb_.StoreToObjectOffset(shadow_frame_, ShadowFrame::DexPCOffset(), irb_.getInt32(0)); // Store the number of the pointer slots irb_.StoreToObjectOffset(shadow_frame_, ShadowFrame::NumberOfReferencesOffset(), irb_.getInt32(sirt_size)); // Push the shadow frame llvm::Value* shadow_frame_upcast = irb_.CreateConstGEP2_32(shadow_frame_, 0, 0); irb_.CreateCall(irb_.GetRuntime(PushShadowFrame), shadow_frame_upcast); // Get JNIEnv llvm::Value* jni_env_object_addr = irb_.LoadFromObjectOffset(thread_object_addr, Thread::JniEnvOffset().Int32Value(), irb_.getJObjectTy()); // Set thread state to kNative irb_.StoreToObjectOffset(thread_object_addr, Thread::StateOffset().Int32Value(), irb_.getInt32(kNative)); // Get callee code_addr llvm::Value* code_addr = irb_.LoadFromObjectOffset(method_object_addr, Method::NativeMethodOffset().Int32Value(), GetFunctionType(method_idx_, is_static, true)->getPointerTo()); // Load actual parameters std::vector<llvm::Value*> args; // The 1st parameter: JNIEnv* args.push_back(jni_env_object_addr); // Variables for GetElementPtr llvm::Value* gep_index[] = { irb_.getInt32(0), // No displacement for shadow frame pointer irb_.getInt32(1), // SIRT NULL, }; size_t sirt_member_index = 0; // Store the "this object or class object" to SIRT gep_index[2] = irb_.getInt32(sirt_member_index++); llvm::Value* sirt_field_addr = irb_.CreateGEP(shadow_frame_, gep_index); irb_.CreateStore(this_object_or_class_object, sirt_field_addr); // Push the "this object or class object" to out args args.push_back(irb_.CreateBitCast(sirt_field_addr, irb_.getJObjectTy())); // Store arguments to SIRT, and push back to args for (arg_iter = arg_begin; arg_iter != arg_end; ++arg_iter) { if (arg_iter->getType() == irb_.getJObjectTy()) { // Store the reference type arguments to SIRT gep_index[2] = irb_.getInt32(sirt_member_index++); llvm::Value* sirt_field_addr = irb_.CreateGEP(shadow_frame_, gep_index); irb_.CreateStore(arg_iter, sirt_field_addr); // Note null is placed in the SIRT but the jobject passed to the native code must be null // (not a pointer into the SIRT as with regular references). llvm::Value* equal_null = irb_.CreateICmpEQ(arg_iter, irb_.getJNull()); llvm::Value* arg = irb_.CreateSelect(equal_null, irb_.getJNull(), irb_.CreateBitCast(sirt_field_addr, irb_.getJObjectTy())); args.push_back(arg); } else { args.push_back(arg_iter); } } // Acquire lock for synchronized methods. if (is_synchronized) { // Acquire lock irb_.CreateCall2(irb_.GetRuntime(LockObject), this_object_or_class_object, thread_object_addr); // Check exception pending llvm::Value* exception_pending = irb_.CreateCall(irb_.GetRuntime(IsExceptionPending)); // Create two basic block for branch llvm::BasicBlock* block_cont = llvm::BasicBlock::Create(*context_, "B.cont", func_); llvm::BasicBlock* block_exception_ = llvm::BasicBlock::Create(*context_, "B.exception", func_); // Branch by exception_pending irb_.CreateCondBr(exception_pending, block_exception_, block_cont); // If exception pending irb_.SetInsertPoint(block_exception_); // TODO: Set thread state? // Pop the shadow frame irb_.CreateCall(irb_.GetRuntime(PopShadowFrame)); // Unwind if (return_shorty != 'V') { irb_.CreateRet(irb_.getJZero(return_shorty)); } else { irb_.CreateRetVoid(); } // If no exception pending irb_.SetInsertPoint(block_cont); } // saved_local_ref_cookie = env->local_ref_cookie llvm::Value* saved_local_ref_cookie = irb_.LoadFromObjectOffset(jni_env_object_addr, JNIEnvExt::LocalRefCookieOffset().Int32Value(), irb_.getInt32Ty()); // env->local_ref_cookie = env->locals.segment_state llvm::Value* segment_state = irb_.LoadFromObjectOffset(jni_env_object_addr, JNIEnvExt::SegmentStateOffset().Int32Value(), irb_.getInt32Ty()); irb_.StoreToObjectOffset(jni_env_object_addr, JNIEnvExt::LocalRefCookieOffset().Int32Value(), segment_state); // Call!!! llvm::Value* retval = irb_.CreateCall(code_addr, args); // Release lock for synchronized methods. if (is_synchronized) { irb_.CreateCall2(irb_.GetRuntime(UnlockObject), this_object_or_class_object, thread_object_addr); } // Set thread state to kRunnable irb_.StoreToObjectOffset(thread_object_addr, Thread::StateOffset().Int32Value(), irb_.getInt32(kRunnable)); // Do a suspend check irb_.CreateCall(irb_.GetRuntime(TestSuspend), thread_object_addr); if (return_shorty == 'L') { // If the return value is reference, it may point to SIRT, we should decode it. retval = irb_.CreateCall2(irb_.GetRuntime(DecodeJObjectInThread), thread_object_addr, retval); } // env->locals.segment_state = env->local_ref_cookie llvm::Value* local_ref_cookie = irb_.LoadFromObjectOffset(jni_env_object_addr, JNIEnvExt::LocalRefCookieOffset().Int32Value(), irb_.getInt32Ty()); irb_.StoreToObjectOffset(jni_env_object_addr, JNIEnvExt::SegmentStateOffset().Int32Value(), local_ref_cookie); // env->local_ref_cookie = saved_local_ref_cookie irb_.StoreToObjectOffset(jni_env_object_addr, JNIEnvExt::LocalRefCookieOffset().Int32Value(), saved_local_ref_cookie); // Pop the shadow frame irb_.CreateCall(irb_.GetRuntime(PopShadowFrame)); // Return! if (return_shorty != 'V') { irb_.CreateRet(retval); } else { irb_.CreateRetVoid(); } // Verify the generated bitcode VERIFY_LLVM_FUNCTION(*func_); // Add the memory usage approximation of the compilation unit cunit_->AddMemUsageApproximation((sirt_size * 4 + 50) * 50); // NOTE: We will emit 4 LLVM instructions per object argument, // And about 50 instructions for other operations. (Some runtime support will be inlined.) // Beside, we guess that we have to use 50 bytes to represent one LLVM instruction. CompiledMethod* compiled_method = new CompiledMethod(cunit_->GetInstructionSet(), cunit_->GetElfIndex(), elf_func_idx_); cunit_->RegisterCompiledMethod(func_, compiled_method); return compiled_method; } void JniCompiler::CreateFunction() { // LLVM function name std::string func_name(ElfFuncName(elf_func_idx_)); // Get function type llvm::FunctionType* func_type = GetFunctionType(method_idx_, method_->IsStatic(), false); // Create function func_ = llvm::Function::Create(func_type, llvm::Function::ExternalLinkage, func_name, module_); // Create basic block llvm::BasicBlock* basic_block = llvm::BasicBlock::Create(*context_, "B0", func_); // Set insert point irb_.SetInsertPoint(basic_block); } llvm::FunctionType* JniCompiler::GetFunctionType(uint32_t method_idx, bool is_static, bool is_native_function) { // Get method signature DexFile::MethodId const& method_id = dex_file_->GetMethodId(method_idx); uint32_t shorty_size; char const* shorty = dex_file_->GetMethodShorty(method_id, &shorty_size); CHECK_GE(shorty_size, 1u); // Get return type llvm::Type* ret_type = irb_.getJType(shorty[0], kAccurate); // Get argument type std::vector<llvm::Type*> args_type; args_type.push_back(irb_.getJObjectTy()); // method object pointer if (!is_static || is_native_function) { // "this" object pointer for non-static // "class" object pointer for static naitve args_type.push_back(irb_.getJType('L', kAccurate)); } for (uint32_t i = 1; i < shorty_size; ++i) { args_type.push_back(irb_.getJType(shorty[i], kAccurate)); } return llvm::FunctionType::get(ret_type, args_type, false); } } // namespace compiler_llvm } // namespace art <commit_msg>No need zero initialize jni shadow frame.<commit_after>/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jni_compiler.h" #include "class_linker.h" #include "compilation_unit.h" #include "compiled_method.h" #include "compiler.h" #include "compiler_llvm.h" #include "ir_builder.h" #include "logging.h" #include "oat_compilation_unit.h" #include "object.h" #include "runtime.h" #include "runtime_support_func.h" #include "shadow_frame.h" #include "utils_llvm.h" #include <llvm/BasicBlock.h> #include <llvm/DerivedTypes.h> #include <llvm/Function.h> #include <llvm/Type.h> namespace art { namespace compiler_llvm { using namespace runtime_support; JniCompiler::JniCompiler(CompilationUnit* cunit, Compiler const& compiler, OatCompilationUnit* oat_compilation_unit) : cunit_(cunit), compiler_(&compiler), module_(cunit_->GetModule()), context_(cunit_->GetLLVMContext()), irb_(*cunit_->GetIRBuilder()), oat_compilation_unit_(oat_compilation_unit), access_flags_(oat_compilation_unit->access_flags_), method_idx_(oat_compilation_unit->method_idx_), class_linker_(oat_compilation_unit->class_linker_), class_loader_(oat_compilation_unit->class_loader_), dex_cache_(oat_compilation_unit->dex_cache_), dex_file_(oat_compilation_unit->dex_file_), method_(dex_cache_->GetResolvedMethod(method_idx_)), elf_func_idx_(cunit_->AcquireUniqueElfFuncIndex()) { // Check: Ensure that the method is resolved CHECK_NE(method_, static_cast<art::Method*>(NULL)); // Check: Ensure that JNI compiler will only get "native" method CHECK((access_flags_ & kAccNative) != 0); } CompiledMethod* JniCompiler::Compile() { const bool is_static = (access_flags_ & kAccStatic) != 0; const bool is_synchronized = (access_flags_ & kAccSynchronized) != 0; DexFile::MethodId const& method_id = dex_file_->GetMethodId(method_idx_); char const return_shorty = dex_file_->GetMethodShorty(method_id)[0]; llvm::Value* this_object_or_class_object; CreateFunction(); // Set argument name llvm::Function::arg_iterator arg_begin(func_->arg_begin()); llvm::Function::arg_iterator arg_end(func_->arg_end()); llvm::Function::arg_iterator arg_iter(arg_begin); DCHECK_NE(arg_iter, arg_end); arg_iter->setName("method"); llvm::Value* method_object_addr = arg_iter++; if (!is_static) { // Non-static, the second argument is "this object" this_object_or_class_object = arg_iter++; } else { // Load class object this_object_or_class_object = irb_.LoadFromObjectOffset(method_object_addr, Method::DeclaringClassOffset().Int32Value(), irb_.getJObjectTy()); } // Actual argument (ignore method and this object) arg_begin = arg_iter; // Count the number of Object* arguments uint32_t sirt_size = 1; // "this" object pointer for non-static // "class" object pointer for static for (unsigned i = 0; arg_iter != arg_end; ++i, ++arg_iter) { arg_iter->setName(StringPrintf("a%u", i)); if (arg_iter->getType() == irb_.getJObjectTy()) { ++sirt_size; } } // Get thread object llvm::Value* thread_object_addr = irb_.CreateCall(irb_.GetRuntime(GetCurrentThread)); // Shadow stack llvm::StructType* shadow_frame_type = irb_.getShadowFrameTy(sirt_size); llvm::AllocaInst* shadow_frame_ = irb_.CreateAlloca(shadow_frame_type); // Store the method pointer llvm::Value* method_field_addr = irb_.CreatePtrDisp(shadow_frame_, irb_.getPtrEquivInt(ShadowFrame::MethodOffset()), irb_.getJObjectTy()->getPointerTo()); irb_.CreateStore(method_object_addr, method_field_addr); // Store the dex pc irb_.StoreToObjectOffset(shadow_frame_, ShadowFrame::DexPCOffset(), irb_.getInt32(0)); // Store the number of the pointer slots irb_.StoreToObjectOffset(shadow_frame_, ShadowFrame::NumberOfReferencesOffset(), irb_.getInt32(sirt_size)); // Push the shadow frame llvm::Value* shadow_frame_upcast = irb_.CreateConstGEP2_32(shadow_frame_, 0, 0); irb_.CreateCall(irb_.GetRuntime(PushShadowFrame), shadow_frame_upcast); // Get JNIEnv llvm::Value* jni_env_object_addr = irb_.LoadFromObjectOffset(thread_object_addr, Thread::JniEnvOffset().Int32Value(), irb_.getJObjectTy()); // Set thread state to kNative irb_.StoreToObjectOffset(thread_object_addr, Thread::StateOffset().Int32Value(), irb_.getInt32(kNative)); // Get callee code_addr llvm::Value* code_addr = irb_.LoadFromObjectOffset(method_object_addr, Method::NativeMethodOffset().Int32Value(), GetFunctionType(method_idx_, is_static, true)->getPointerTo()); // Load actual parameters std::vector<llvm::Value*> args; // The 1st parameter: JNIEnv* args.push_back(jni_env_object_addr); // Variables for GetElementPtr llvm::Value* gep_index[] = { irb_.getInt32(0), // No displacement for shadow frame pointer irb_.getInt32(1), // SIRT NULL, }; size_t sirt_member_index = 0; // Store the "this object or class object" to SIRT gep_index[2] = irb_.getInt32(sirt_member_index++); llvm::Value* sirt_field_addr = irb_.CreateGEP(shadow_frame_, gep_index); irb_.CreateStore(this_object_or_class_object, sirt_field_addr); // Push the "this object or class object" to out args args.push_back(irb_.CreateBitCast(sirt_field_addr, irb_.getJObjectTy())); // Store arguments to SIRT, and push back to args for (arg_iter = arg_begin; arg_iter != arg_end; ++arg_iter) { if (arg_iter->getType() == irb_.getJObjectTy()) { // Store the reference type arguments to SIRT gep_index[2] = irb_.getInt32(sirt_member_index++); llvm::Value* sirt_field_addr = irb_.CreateGEP(shadow_frame_, gep_index); irb_.CreateStore(arg_iter, sirt_field_addr); // Note null is placed in the SIRT but the jobject passed to the native code must be null // (not a pointer into the SIRT as with regular references). llvm::Value* equal_null = irb_.CreateICmpEQ(arg_iter, irb_.getJNull()); llvm::Value* arg = irb_.CreateSelect(equal_null, irb_.getJNull(), irb_.CreateBitCast(sirt_field_addr, irb_.getJObjectTy())); args.push_back(arg); } else { args.push_back(arg_iter); } } // Acquire lock for synchronized methods. if (is_synchronized) { // Acquire lock irb_.CreateCall2(irb_.GetRuntime(LockObject), this_object_or_class_object, thread_object_addr); // Check exception pending llvm::Value* exception_pending = irb_.CreateCall(irb_.GetRuntime(IsExceptionPending)); // Create two basic block for branch llvm::BasicBlock* block_cont = llvm::BasicBlock::Create(*context_, "B.cont", func_); llvm::BasicBlock* block_exception_ = llvm::BasicBlock::Create(*context_, "B.exception", func_); // Branch by exception_pending irb_.CreateCondBr(exception_pending, block_exception_, block_cont); // If exception pending irb_.SetInsertPoint(block_exception_); // TODO: Set thread state? // Pop the shadow frame irb_.CreateCall(irb_.GetRuntime(PopShadowFrame)); // Unwind if (return_shorty != 'V') { irb_.CreateRet(irb_.getJZero(return_shorty)); } else { irb_.CreateRetVoid(); } // If no exception pending irb_.SetInsertPoint(block_cont); } // saved_local_ref_cookie = env->local_ref_cookie llvm::Value* saved_local_ref_cookie = irb_.LoadFromObjectOffset(jni_env_object_addr, JNIEnvExt::LocalRefCookieOffset().Int32Value(), irb_.getInt32Ty()); // env->local_ref_cookie = env->locals.segment_state llvm::Value* segment_state = irb_.LoadFromObjectOffset(jni_env_object_addr, JNIEnvExt::SegmentStateOffset().Int32Value(), irb_.getInt32Ty()); irb_.StoreToObjectOffset(jni_env_object_addr, JNIEnvExt::LocalRefCookieOffset().Int32Value(), segment_state); // Call!!! llvm::Value* retval = irb_.CreateCall(code_addr, args); // Release lock for synchronized methods. if (is_synchronized) { irb_.CreateCall2(irb_.GetRuntime(UnlockObject), this_object_or_class_object, thread_object_addr); } // Set thread state to kRunnable irb_.StoreToObjectOffset(thread_object_addr, Thread::StateOffset().Int32Value(), irb_.getInt32(kRunnable)); // Do a suspend check irb_.CreateCall(irb_.GetRuntime(TestSuspend), thread_object_addr); if (return_shorty == 'L') { // If the return value is reference, it may point to SIRT, we should decode it. retval = irb_.CreateCall2(irb_.GetRuntime(DecodeJObjectInThread), thread_object_addr, retval); } // env->locals.segment_state = env->local_ref_cookie llvm::Value* local_ref_cookie = irb_.LoadFromObjectOffset(jni_env_object_addr, JNIEnvExt::LocalRefCookieOffset().Int32Value(), irb_.getInt32Ty()); irb_.StoreToObjectOffset(jni_env_object_addr, JNIEnvExt::SegmentStateOffset().Int32Value(), local_ref_cookie); // env->local_ref_cookie = saved_local_ref_cookie irb_.StoreToObjectOffset(jni_env_object_addr, JNIEnvExt::LocalRefCookieOffset().Int32Value(), saved_local_ref_cookie); // Pop the shadow frame irb_.CreateCall(irb_.GetRuntime(PopShadowFrame)); // Return! if (return_shorty != 'V') { irb_.CreateRet(retval); } else { irb_.CreateRetVoid(); } // Verify the generated bitcode VERIFY_LLVM_FUNCTION(*func_); // Add the memory usage approximation of the compilation unit cunit_->AddMemUsageApproximation((sirt_size * 4 + 50) * 50); // NOTE: We will emit 4 LLVM instructions per object argument, // And about 50 instructions for other operations. (Some runtime support will be inlined.) // Beside, we guess that we have to use 50 bytes to represent one LLVM instruction. CompiledMethod* compiled_method = new CompiledMethod(cunit_->GetInstructionSet(), cunit_->GetElfIndex(), elf_func_idx_); cunit_->RegisterCompiledMethod(func_, compiled_method); return compiled_method; } void JniCompiler::CreateFunction() { // LLVM function name std::string func_name(ElfFuncName(elf_func_idx_)); // Get function type llvm::FunctionType* func_type = GetFunctionType(method_idx_, method_->IsStatic(), false); // Create function func_ = llvm::Function::Create(func_type, llvm::Function::ExternalLinkage, func_name, module_); // Create basic block llvm::BasicBlock* basic_block = llvm::BasicBlock::Create(*context_, "B0", func_); // Set insert point irb_.SetInsertPoint(basic_block); } llvm::FunctionType* JniCompiler::GetFunctionType(uint32_t method_idx, bool is_static, bool is_native_function) { // Get method signature DexFile::MethodId const& method_id = dex_file_->GetMethodId(method_idx); uint32_t shorty_size; char const* shorty = dex_file_->GetMethodShorty(method_id, &shorty_size); CHECK_GE(shorty_size, 1u); // Get return type llvm::Type* ret_type = irb_.getJType(shorty[0], kAccurate); // Get argument type std::vector<llvm::Type*> args_type; args_type.push_back(irb_.getJObjectTy()); // method object pointer if (!is_static || is_native_function) { // "this" object pointer for non-static // "class" object pointer for static naitve args_type.push_back(irb_.getJType('L', kAccurate)); } for (uint32_t i = 1; i < shorty_size; ++i) { args_type.push_back(irb_.getJType(shorty[i], kAccurate)); } return llvm::FunctionType::get(ret_type, args_type, false); } } // namespace compiler_llvm } // namespace art <|endoftext|>
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* This WRM evaluator evaluates saturation of gas, liquid, and ice from capillary pressures for the ice-liquid and liquid-gas pairs. Authors: Ethan Coon ([email protected]) */ #include "wrm_permafrost_evaluator.hh" #include "wrm_partition.hh" namespace Amanzi { namespace Flow { namespace FlowRelations { /* -------------------------------------------------------------------------------- Constructor from just a ParameterList, reads WRMs and permafrost models from list. -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist) : SecondaryVariablesFieldEvaluator(plist) { // get the WRMs ASSERT(plist_.isSublist("WRM parameters")); Teuchos::ParameterList wrm_plist = plist_.sublist("WRM parameters"); wrms_ = createWRMPartition(wrm_plist); // and the permafrost models ASSERT(plist_.isSublist("permafrost model parameters")); Teuchos::ParameterList perm_plist = plist_.sublist("permafrost model parameters"); permafrost_models_ = createWRMPermafrostModelPartition(perm_plist, wrms_); InitializeFromPlist_(); } /* -------------------------------------------------------------------------------- Constructor with WRMs. -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist, const Teuchos::RCP<WRMPartition>& wrms) : SecondaryVariablesFieldEvaluator(plist), wrms_(wrms) { // and the permafrost models ASSERT(plist_.isSublist("permafrost model parameters")); Teuchos::ParameterList perm_plist = plist_.sublist("permafrost model parameters"); permafrost_models_ = createWRMPermafrostModelPartition(perm_plist, wrms_); InitializeFromPlist_(); } /* -------------------------------------------------------------------------------- Constructor with Permafrost models. -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist, const Teuchos::RCP<WRMPermafrostModelPartition>& models) : SecondaryVariablesFieldEvaluator(plist), permafrost_models_(models) { InitializeFromPlist_(); } /* -------------------------------------------------------------------------------- Copy constructor -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(const WRMPermafrostEvaluator& other) : SecondaryVariablesFieldEvaluator(other), pc_liq_key_(other.pc_liq_key_), pc_ice_key_(other.pc_ice_key_), s_l_key_(other.s_l_key_), permafrost_models_(other.permafrost_models_) {} /* -------------------------------------------------------------------------------- Virtual opy constructor as a FieldEvaluator. -------------------------------------------------------------------------------- */ Teuchos::RCP<FieldEvaluator> WRMPermafrostEvaluator::Clone() const { return Teuchos::rcp(new WRMPermafrostEvaluator(*this)); } /* -------------------------------------------------------------------------------- Initialization of keys. -------------------------------------------------------------------------------- */ void WRMPermafrostEvaluator::InitializeFromPlist_() { // my keys are for saturation -- order matters... gas -> liq -> ice my_keys_.push_back(plist_.get<string>("gas saturation key", "saturation_gas")); s_l_key_ = plist_.get<string>("liquid saturation key", "saturation_liquid"); my_keys_.push_back(s_l_key_); my_keys_.push_back(plist_.get<string>("ice saturation key", "saturation_ice")); // liquid-gas capillary pressure pc_liq_key_ = plist_.get<string>("gas-liquid capillary pressure key", "capillary_pressure_gas_liq"); dependencies_.insert(pc_liq_key_); // liquid-gas capillary pressure pc_ice_key_ = plist_.get<string>("liquid-ice capillary pressure key", "capillary_pressure_liq_ice"); dependencies_.insert(pc_ice_key_); } void WRMPermafrostEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S, const std::vector<Teuchos::Ptr<CompositeVector> >& results) { // Initialize the MeshPartition if (!permafrost_models_->first->initialized()) permafrost_models_->first->Initialize(results[0]->Mesh()); // Cell values Epetra_MultiVector& satg_c = *results[0]->ViewComponent("cell",false); Epetra_MultiVector& satl_c = *results[1]->ViewComponent("cell",false); Epetra_MultiVector& sati_c = *results[2]->ViewComponent("cell",false); const Epetra_MultiVector& pc_liq_c = *S->GetFieldData(pc_liq_key_) ->ViewComponent("cell",false); const Epetra_MultiVector& pc_ice_c = *S->GetFieldData(pc_ice_key_) ->ViewComponent("cell",false); double sats[3]; int ncells = satg_c.MyLength(); for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) { int i = (*permafrost_models_->first)[c]; permafrost_models_->second[i]->saturations(pc_liq_c[0][c], pc_ice_c[0][c], sats); satg_c[0][c] = sats[0]; satl_c[0][c] = sats[1]; sati_c[0][c] = sats[2]; } // Potentially do face values as well, though only for saturation_liquid? if (results[0]->HasComponent("boundary_face")) { Epetra_MultiVector& satg_bf = *results[0]->ViewComponent("boundary_face",false); Epetra_MultiVector& satl_bf = *results[1]->ViewComponent("boundary_face",false); Epetra_MultiVector& sati_bf = *results[2]->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_liq_bf = *S->GetFieldData(pc_liq_key_) ->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_ice_bf = *S->GetFieldData(pc_ice_key_) ->ViewComponent("boundary_face",false); // Need to get boundary face's inner cell to specify the WRM. Teuchos::RCP<const AmanziMesh::Mesh> mesh = results[0]->Mesh(); const Epetra_Map& vandelay_map = mesh->exterior_face_epetra_map(); const Epetra_Map& face_map = mesh->face_epetra_map(false); AmanziMesh::Entity_ID_List cells; // calculate boundary face values int nbfaces = satg_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { // given a boundary face, we need the internal cell to choose the right WRM AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf)); mesh->face_get_cells(f, AmanziMesh::USED, &cells); ASSERT(cells.size() == 1); int i = (*permafrost_models_->first)[cells[0]]; permafrost_models_->second[i] ->saturations(pc_liq_bf[0][bf], pc_ice_bf[0][bf], sats); satg_bf[0][bf] = sats[0]; satl_bf[0][bf] = sats[1]; sati_bf[0][bf] = sats[2]; } } } void WRMPermafrostEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S, Key wrt_key, const std::vector<Teuchos::Ptr<CompositeVector> > & results) { // Cell values Epetra_MultiVector& satg_c = *results[0]->ViewComponent("cell",false); Epetra_MultiVector& satl_c = *results[1]->ViewComponent("cell",false); Epetra_MultiVector& sati_c = *results[2]->ViewComponent("cell",false); const Epetra_MultiVector& pc_liq_c = *S->GetFieldData(pc_liq_key_) ->ViewComponent("cell",false); const Epetra_MultiVector& pc_ice_c = *S->GetFieldData(pc_ice_key_) ->ViewComponent("cell",false); double dsats[3]; if (wrt_key == pc_liq_key_) { int ncells = satg_c.MyLength(); for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) { int i = (*permafrost_models_->first)[c]; permafrost_models_->second[i]->dsaturations_dpc_liq( pc_liq_c[0][c], pc_ice_c[0][c], dsats); satg_c[0][c] = dsats[0]; satl_c[0][c] = dsats[1]; sati_c[0][c] = dsats[2]; } } else if (wrt_key == pc_ice_key_) { int ncells = satg_c.MyLength(); for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) { int i = (*permafrost_models_->first)[c]; permafrost_models_->second[i]->dsaturations_dpc_ice( pc_liq_c[0][c], pc_ice_c[0][c], dsats); satg_c[0][c] = dsats[0]; satl_c[0][c] = dsats[1]; sati_c[0][c] = dsats[2]; } } else { ASSERT(0); } // Potentially do face values as well, though only for saturation_liquid? if (results[1]->HasComponent("boundary_face")) { ASSERT(!results[0]->HasComponent("boundary_face")); ASSERT(!results[2]->HasComponent("boundary_face")); Epetra_MultiVector& sat_bf = *results[1]->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_liq_bf = *S->GetFieldData(pc_liq_key_) ->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_ice_bf = *S->GetFieldData(pc_ice_key_) ->ViewComponent("boundary_face",false); // Need to get boundary face's inner cell to specify the WRM. Teuchos::RCP<const AmanziMesh::Mesh> mesh = results[0]->Mesh(); const Epetra_Map& face_map = mesh->face_epetra_map(false); const Epetra_Map& vandelay_map = mesh->exterior_face_epetra_map(); AmanziMesh::Entity_ID_List cells; if (wrt_key == pc_liq_key_) { // calculate boundary face values int nbfaces = sat_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { // given a boundary face, we need the internal cell to choose the right WRM AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf)); mesh->face_get_cells(f, AmanziMesh::USED, &cells); ASSERT(cells.size() == 1); int i = (*permafrost_models_->first)[cells[0]]; permafrost_models_->second[i]->dsaturations_dpc_liq( pc_liq_bf[0][bf], pc_ice_bf[0][bf], dsats); sat_bf[0][bf] = dsats[1]; } } else if (wrt_key == pc_ice_key_) { // calculate boundary face values int nbfaces = sat_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { // given a boundary face, we need the internal cell to choose the right WRM AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf)); mesh->face_get_cells(f, AmanziMesh::USED, &cells); ASSERT(cells.size() == 1); int i = (*permafrost_models_->first)[cells[0]]; permafrost_models_->second[i]->dsaturations_dpc_ice( pc_liq_bf[0][bf], pc_ice_bf[0][bf], dsats); sat_bf[0][bf] = dsats[1]; } } else { ASSERT(0); } } } } // namespace } // namespace } // namespace <commit_msg>repeat of previous change, for derivatives too this time...<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* This WRM evaluator evaluates saturation of gas, liquid, and ice from capillary pressures for the ice-liquid and liquid-gas pairs. Authors: Ethan Coon ([email protected]) */ #include "wrm_permafrost_evaluator.hh" #include "wrm_partition.hh" namespace Amanzi { namespace Flow { namespace FlowRelations { /* -------------------------------------------------------------------------------- Constructor from just a ParameterList, reads WRMs and permafrost models from list. -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist) : SecondaryVariablesFieldEvaluator(plist) { // get the WRMs ASSERT(plist_.isSublist("WRM parameters")); Teuchos::ParameterList wrm_plist = plist_.sublist("WRM parameters"); wrms_ = createWRMPartition(wrm_plist); // and the permafrost models ASSERT(plist_.isSublist("permafrost model parameters")); Teuchos::ParameterList perm_plist = plist_.sublist("permafrost model parameters"); permafrost_models_ = createWRMPermafrostModelPartition(perm_plist, wrms_); InitializeFromPlist_(); } /* -------------------------------------------------------------------------------- Constructor with WRMs. -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist, const Teuchos::RCP<WRMPartition>& wrms) : SecondaryVariablesFieldEvaluator(plist), wrms_(wrms) { // and the permafrost models ASSERT(plist_.isSublist("permafrost model parameters")); Teuchos::ParameterList perm_plist = plist_.sublist("permafrost model parameters"); permafrost_models_ = createWRMPermafrostModelPartition(perm_plist, wrms_); InitializeFromPlist_(); } /* -------------------------------------------------------------------------------- Constructor with Permafrost models. -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist, const Teuchos::RCP<WRMPermafrostModelPartition>& models) : SecondaryVariablesFieldEvaluator(plist), permafrost_models_(models) { InitializeFromPlist_(); } /* -------------------------------------------------------------------------------- Copy constructor -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(const WRMPermafrostEvaluator& other) : SecondaryVariablesFieldEvaluator(other), pc_liq_key_(other.pc_liq_key_), pc_ice_key_(other.pc_ice_key_), s_l_key_(other.s_l_key_), permafrost_models_(other.permafrost_models_) {} /* -------------------------------------------------------------------------------- Virtual opy constructor as a FieldEvaluator. -------------------------------------------------------------------------------- */ Teuchos::RCP<FieldEvaluator> WRMPermafrostEvaluator::Clone() const { return Teuchos::rcp(new WRMPermafrostEvaluator(*this)); } /* -------------------------------------------------------------------------------- Initialization of keys. -------------------------------------------------------------------------------- */ void WRMPermafrostEvaluator::InitializeFromPlist_() { // my keys are for saturation -- order matters... gas -> liq -> ice my_keys_.push_back(plist_.get<string>("gas saturation key", "saturation_gas")); s_l_key_ = plist_.get<string>("liquid saturation key", "saturation_liquid"); my_keys_.push_back(s_l_key_); my_keys_.push_back(plist_.get<string>("ice saturation key", "saturation_ice")); // liquid-gas capillary pressure pc_liq_key_ = plist_.get<string>("gas-liquid capillary pressure key", "capillary_pressure_gas_liq"); dependencies_.insert(pc_liq_key_); // liquid-gas capillary pressure pc_ice_key_ = plist_.get<string>("liquid-ice capillary pressure key", "capillary_pressure_liq_ice"); dependencies_.insert(pc_ice_key_); } void WRMPermafrostEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S, const std::vector<Teuchos::Ptr<CompositeVector> >& results) { // Initialize the MeshPartition if (!permafrost_models_->first->initialized()) permafrost_models_->first->Initialize(results[0]->Mesh()); // Cell values Epetra_MultiVector& satg_c = *results[0]->ViewComponent("cell",false); Epetra_MultiVector& satl_c = *results[1]->ViewComponent("cell",false); Epetra_MultiVector& sati_c = *results[2]->ViewComponent("cell",false); const Epetra_MultiVector& pc_liq_c = *S->GetFieldData(pc_liq_key_) ->ViewComponent("cell",false); const Epetra_MultiVector& pc_ice_c = *S->GetFieldData(pc_ice_key_) ->ViewComponent("cell",false); double sats[3]; int ncells = satg_c.MyLength(); for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) { int i = (*permafrost_models_->first)[c]; permafrost_models_->second[i]->saturations(pc_liq_c[0][c], pc_ice_c[0][c], sats); satg_c[0][c] = sats[0]; satl_c[0][c] = sats[1]; sati_c[0][c] = sats[2]; } // Potentially do face values as well, though only for saturation_liquid? if (results[0]->HasComponent("boundary_face")) { Epetra_MultiVector& satg_bf = *results[0]->ViewComponent("boundary_face",false); Epetra_MultiVector& satl_bf = *results[1]->ViewComponent("boundary_face",false); Epetra_MultiVector& sati_bf = *results[2]->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_liq_bf = *S->GetFieldData(pc_liq_key_) ->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_ice_bf = *S->GetFieldData(pc_ice_key_) ->ViewComponent("boundary_face",false); // Need to get boundary face's inner cell to specify the WRM. Teuchos::RCP<const AmanziMesh::Mesh> mesh = results[0]->Mesh(); const Epetra_Map& vandelay_map = mesh->exterior_face_epetra_map(); const Epetra_Map& face_map = mesh->face_epetra_map(false); AmanziMesh::Entity_ID_List cells; // calculate boundary face values int nbfaces = satg_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { // given a boundary face, we need the internal cell to choose the right WRM AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf)); mesh->face_get_cells(f, AmanziMesh::USED, &cells); ASSERT(cells.size() == 1); int i = (*permafrost_models_->first)[cells[0]]; permafrost_models_->second[i] ->saturations(pc_liq_bf[0][bf], pc_ice_bf[0][bf], sats); satg_bf[0][bf] = sats[0]; satl_bf[0][bf] = sats[1]; sati_bf[0][bf] = sats[2]; } } } void WRMPermafrostEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S, Key wrt_key, const std::vector<Teuchos::Ptr<CompositeVector> > & results) { // Cell values Epetra_MultiVector& satg_c = *results[0]->ViewComponent("cell",false); Epetra_MultiVector& satl_c = *results[1]->ViewComponent("cell",false); Epetra_MultiVector& sati_c = *results[2]->ViewComponent("cell",false); const Epetra_MultiVector& pc_liq_c = *S->GetFieldData(pc_liq_key_) ->ViewComponent("cell",false); const Epetra_MultiVector& pc_ice_c = *S->GetFieldData(pc_ice_key_) ->ViewComponent("cell",false); double dsats[3]; if (wrt_key == pc_liq_key_) { int ncells = satg_c.MyLength(); for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) { int i = (*permafrost_models_->first)[c]; permafrost_models_->second[i]->dsaturations_dpc_liq( pc_liq_c[0][c], pc_ice_c[0][c], dsats); satg_c[0][c] = dsats[0]; satl_c[0][c] = dsats[1]; sati_c[0][c] = dsats[2]; } } else if (wrt_key == pc_ice_key_) { int ncells = satg_c.MyLength(); for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) { int i = (*permafrost_models_->first)[c]; permafrost_models_->second[i]->dsaturations_dpc_ice( pc_liq_c[0][c], pc_ice_c[0][c], dsats); satg_c[0][c] = dsats[0]; satl_c[0][c] = dsats[1]; sati_c[0][c] = dsats[2]; } } else { ASSERT(0); } // Potentially do face values as well, though only for saturation_liquid? if (results[0]->HasComponent("boundary_face")) { Epetra_MultiVector& satg_bf = *results[0]->ViewComponent("boundary_face",false); Epetra_MultiVector& satl_bf = *results[1]->ViewComponent("boundary_face",false); Epetra_MultiVector& sati_bf = *results[2]->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_liq_bf = *S->GetFieldData(pc_liq_key_) ->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_ice_bf = *S->GetFieldData(pc_ice_key_) ->ViewComponent("boundary_face",false); // Need to get boundary face's inner cell to specify the WRM. Teuchos::RCP<const AmanziMesh::Mesh> mesh = results[0]->Mesh(); const Epetra_Map& face_map = mesh->face_epetra_map(false); const Epetra_Map& vandelay_map = mesh->exterior_face_epetra_map(); AmanziMesh::Entity_ID_List cells; if (wrt_key == pc_liq_key_) { // calculate boundary face values int nbfaces = satl_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { // given a boundary face, we need the internal cell to choose the right WRM AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf)); mesh->face_get_cells(f, AmanziMesh::USED, &cells); ASSERT(cells.size() == 1); int i = (*permafrost_models_->first)[cells[0]]; permafrost_models_->second[i]->dsaturations_dpc_liq( pc_liq_bf[0][bf], pc_ice_bf[0][bf], dsats); satg_bf[0][bf] = dsats[0]; satl_bf[0][bf] = dsats[1]; sati_bf[0][bf] = dsats[2]; } } else if (wrt_key == pc_ice_key_) { // calculate boundary face values int nbfaces = satl_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { // given a boundary face, we need the internal cell to choose the right WRM AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf)); mesh->face_get_cells(f, AmanziMesh::USED, &cells); ASSERT(cells.size() == 1); int i = (*permafrost_models_->first)[cells[0]]; permafrost_models_->second[i]->dsaturations_dpc_ice( pc_liq_bf[0][bf], pc_ice_bf[0][bf], dsats); satg_bf[0][bf] = dsats[0]; satl_bf[0][bf] = dsats[1]; sati_bf[0][bf] = dsats[2]; } } else { ASSERT(0); } } } } // namespace } // namespace } // namespace <|endoftext|>
<commit_before> #include <stdlib.h> /* srand, rand */ #include <chrono> #include <iostream> #include <fstream> #include <string> #include <algorithm> #include "bpmf.h" using namespace std; using namespace Eigen; typedef SparseMatrix<double> SparseMatrixD; const int num_feat = 32; unsigned num_p = 0; unsigned num_m = 0; const int alpha = 2; const int nsims = 20; const int burnin = 5; double mean_rating = .0; SparseMatrixD M; typedef Eigen::Triplet<double> T; vector<T> probe_vec; VectorXd mu_u(num_feat); VectorXd mu_m(num_feat); MatrixXd Lambda_u(num_feat, num_feat); MatrixXd Lambda_m(num_feat, num_feat); MatrixXd sample_u; MatrixXd sample_m; // parameters of Inv-Whishart distribution (see paper for details) MatrixXd WI_u(num_feat, num_feat); const int b0_u = 2; const int df_u = num_feat; VectorXd mu0_u(num_feat); MatrixXd WI_m(num_feat, num_feat); const int b0_m = 2; const int df_m = num_feat; VectorXd mu0_m(num_feat); void loadChemo(const char* fname) { std::vector<T> lst; lst.reserve(100000); FILE *f = fopen(fname, "r"); assert(f && "Could not open file"); // skip header char buf[2048]; fscanf(f, "%s\n", buf); // data unsigned i, j; double v; while (!feof(f)) { if (!fscanf(f, "%d,%d,%lg\n", &i, &j, &v)) continue; i--; j--; if ((rand() % 5) == 0) { probe_vec.push_back(T(i,j,log10(v))); } #ifndef TEST_SAMPLE else // if not in test case -> remove probe_vec from lst #endif { num_p = std::max(num_p, i); num_m = std::max(num_m, j); mean_rating += v; lst.push_back(T(i,j,log10(v))); } } num_p++; num_m++; mean_rating /= lst.size(); fclose(f); M = SparseMatrix<double>(num_p, num_m); M.setFromTriplets(lst.begin(), lst.end()); } void init() { mean_rating = M.sum() / M.nonZeros(); Lambda_u.setIdentity(); Lambda_m.setIdentity(); sample_u = MatrixXd(num_feat, num_p); sample_m = MatrixXd(num_feat, num_m); sample_u.setZero(); sample_m.setZero(); // parameters of Inv-Whishart distribution (see paper for details) WI_u.setIdentity(); mu0_u.setZero(); WI_m.setIdentity(); mu0_m.setZero(); } pair<double,double> eval_probe_vec(const vector<T> &probe_vec, const MatrixXd &sample_m, const MatrixXd &sample_u, double mean_rating) { unsigned n = probe_vec.size(); unsigned correct = 0; double diff = .0; for(auto t : probe_vec) { double prediction = sample_m.col(t.col()).dot(sample_u.col(t.row())) + mean_rating; //cout << "prediction: " << prediction - mean_rating << " + " << mean_rating << " = " << prediction << endl; //cout << "actual: " << t.value() << endl; correct += (t.value() < log10(200)) == (prediction < log10(200)); diff += abs(t.value() - prediction); } return std::make_pair((double)correct / n, diff / n); } void sample_movie(MatrixXd &s, int mm, const SparseMatrixD &mat, double mean_rating, const MatrixXd &samples, int alpha, const MatrixXd &mu_u, const MatrixXd &Lambda_u) { int i = 0; MatrixXd E(num_feat,mat.col(mm).nonZeros()); VectorXd rr(mat.col(mm).nonZeros()); //cout << "movie " << endl; for (SparseMatrixD::InnerIterator it(mat,mm); it; ++it, ++i) { // cout << "M[" << it.row() << "," << it.col() << "] = " << it.value() << endl; E.col(i) = samples.col(it.row()); rr(i) = it.value() - mean_rating; } auto MM = E * E.transpose(); MatrixXd MMs = alpha * MM.array(); assert(MMs.cols() == num_feat && MMs.rows() == num_feat); MatrixXd covar = (Lambda_u + MMs).inverse(); MatrixXd MMrr = (E * rr) * alpha; auto U = Lambda_u * mu_u; auto mu = covar * (MMrr + U); MatrixXd chol = covar.llt().matrixL(); #ifdef TEST_SAMPLE auto r(num_feat); r.setConstant(0.25); #else auto r = nrandn(num_feat); #endif s.col(mm) = chol * r + mu; #ifdef TEST_SAMPLE cout << "movie " << mm << ":" << result.cols() << " x" << result.rows() << endl; cout << "mean rating " << mean_rating << endl; cout << "E = [" << E << "]" << endl; cout << "rr = [" << rr << "]" << endl; cout << "MM = [" << MM << "]" << endl; cout << "Lambda_u = [" << Lambda_u << "]" << endl; cout << "covar = [" << covar << "]" << endl; cout << "mu = [" << mu << "]" << endl; cout << "chol = [" << chol << "]" << endl; cout << "rand = [" << r <<"]" << endl; cout << "result = [" << result << "]" << endl; #endif } #ifdef TEST_SAMPLE void test() { MatrixXd sample_u(num_feat, num_p); MatrixXd sample_m(num_feat, num_m); mu_m.setZero(); Lambda_m.setIdentity(); sample_u.setConstant(2.0); Lambda_m *= 0.5; sample_m.col(0) = sample_movie(0, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } #else void run() { auto start = std::chrono::steady_clock::now(); SparseMatrixD Mt = M.transpose(); std::cout << "Sampling" << endl; for(int i=0; i<nsims; ++i) { // Sample from movie hyperparams tie(mu_m, Lambda_m) = CondNormalWishart(sample_m, mu0_m, b0_m, WI_m, df_m); // Sample from user hyperparams tie(mu_u, Lambda_u) = CondNormalWishart(sample_u, mu0_u, b0_u, WI_u, df_u); #pragma omp parallel for for(int mm = 0; mm < num_m; ++mm) { sample_movie(sample_m, mm, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } #pragma omp parallel for for(int uu = 0; uu < num_p; ++uu) { sample_movie(sample_u, uu, Mt, mean_rating, sample_m, alpha, mu_u, Lambda_u); } auto eval = eval_probe_vec(probe_vec, sample_m, sample_u, mean_rating); double norm_u = sample_u.norm(); double norm_m = sample_m.norm(); auto end = std::chrono::steady_clock::now(); auto elapsed = std::chrono::duration<double>(end - start); double samples_per_sec = (i + 1) * (num_p + num_m) / elapsed.count(); printf("Iteration %d:\t num_correct: %3.2f%%\tavg_diff: %3.2f\tFU(%6.2f)\tFM(%6.2f)\tSamples/sec: %6.2f\n", i, 100*eval.first, eval.second, norm_u, norm_m, samples_per_sec); } } #endif int main(int argc, char *argv[]) { const char *fname = argv[1]; assert(fname && "filename missing"); Eigen::initParallel(); Eigen::setNbThreads(1); loadChemo(fname); init(); #ifdef TEST_SAMPLE test(); #else run(); #endif return 0; } <commit_msg>c++: static sizes<commit_after> #include <stdlib.h> /* srand, rand */ #include <chrono> #include <iostream> #include <fstream> #include <string> #include <algorithm> #include "bpmf.h" using namespace std; using namespace Eigen; typedef SparseMatrix<double> SparseMatrixD; const int num_feat = 32; unsigned num_p = 0; unsigned num_m = 0; const int alpha = 2; const int nsims = 20; const int burnin = 5; double mean_rating = .0; SparseMatrixD M; typedef Eigen::Triplet<double> T; vector<T> probe_vec; typedef Matrix<double, num_feat, 1> VectorNd; typedef Matrix<double, num_feat, num_feat> MatrixNNd; typedef Matrix<double, num_feat, Dynamic> MatrixNXd; VectorNd mu_u; VectorNd mu_m; MatrixNNd Lambda_u; MatrixNNd Lambda_m; MatrixNXd sample_u; MatrixNXd sample_m; // parameters of Inv-Whishart distribution (see paper for details) MatrixNNd WI_u; const int b0_u = 2; const int df_u = num_feat; VectorNd mu0_u; MatrixNNd WI_m; const int b0_m = 2; const int df_m = num_feat; VectorNd mu0_m; void loadChemo(const char* fname) { std::vector<T> lst; lst.reserve(100000); FILE *f = fopen(fname, "r"); assert(f && "Could not open file"); // skip header char buf[2048]; fscanf(f, "%s\n", buf); // data unsigned i, j; double v; while (!feof(f)) { if (!fscanf(f, "%d,%d,%lg\n", &i, &j, &v)) continue; i--; j--; if ((rand() % 5) == 0) { probe_vec.push_back(T(i,j,log10(v))); } #ifndef TEST_SAMPLE else // if not in test case -> remove probe_vec from lst #endif { num_p = std::max(num_p, i); num_m = std::max(num_m, j); mean_rating += v; lst.push_back(T(i,j,log10(v))); } } num_p++; num_m++; mean_rating /= lst.size(); fclose(f); M = SparseMatrix<double>(num_p, num_m); M.setFromTriplets(lst.begin(), lst.end()); } void init() { mean_rating = M.sum() / M.nonZeros(); Lambda_u.setIdentity(); Lambda_m.setIdentity(); sample_u = MatrixNXd(num_feat,num_p); sample_m = MatrixNXd(num_feat,num_m); sample_u.setZero(); sample_m.setZero(); // parameters of Inv-Whishart distribution (see paper for details) WI_u.setIdentity(); mu0_u.setZero(); WI_m.setIdentity(); mu0_m.setZero(); } pair<double,double> eval_probe_vec(const vector<T> &probe_vec, const MatrixNXd &sample_m, const MatrixNXd &sample_u, double mean_rating) { unsigned n = probe_vec.size(); unsigned correct = 0; double diff = .0; for(auto t : probe_vec) { double prediction = sample_m.col(t.col()).dot(sample_u.col(t.row())) + mean_rating; //cout << "prediction: " << prediction - mean_rating << " + " << mean_rating << " = " << prediction << endl; //cout << "actual: " << t.value() << endl; correct += (t.value() < log10(200)) == (prediction < log10(200)); diff += abs(t.value() - prediction); } return std::make_pair((double)correct / n, diff / n); } void sample_movie(MatrixNXd &s, int mm, const SparseMatrixD &mat, double mean_rating, const MatrixNXd &samples, int alpha, const VectorNd &mu_u, const MatrixNNd &Lambda_u) { int i = 0; MatrixNXd E(num_feat,mat.col(mm).nonZeros()); VectorXd rr(mat.col(mm).nonZeros()); //cout << "movie " << endl; for (SparseMatrixD::InnerIterator it(mat,mm); it; ++it, ++i) { // cout << "M[" << it.row() << "," << it.col() << "] = " << it.value() << endl; E.col(i) = samples.col(it.row()); rr(i) = it.value() - mean_rating; } auto MM = E * E.transpose(); auto MMs = alpha * MM; MatrixNNd covar = (Lambda_u + MMs).inverse(); VectorNd MMrr = (E * rr) * alpha; auto U = Lambda_u * mu_u; auto mu = covar * (MMrr + U); MatrixNNd chol = covar.llt().matrixL(); #ifdef TEST_SAMPLE auto r(num_feat); r.setConstant(0.25); #else auto r = nrandn(num_feat); #endif s.col(mm) = chol * r + mu; #ifdef TEST_SAMPLE cout << "movie " << mm << ":" << result.cols() << " x" << result.rows() << endl; cout << "mean rating " << mean_rating << endl; cout << "E = [" << E << "]" << endl; cout << "rr = [" << rr << "]" << endl; cout << "MM = [" << MM << "]" << endl; cout << "Lambda_u = [" << Lambda_u << "]" << endl; cout << "covar = [" << covar << "]" << endl; cout << "mu = [" << mu << "]" << endl; cout << "chol = [" << chol << "]" << endl; cout << "rand = [" << r <<"]" << endl; cout << "result = [" << result << "]" << endl; #endif } #ifdef TEST_SAMPLE void test() { MatrixNXd sample_u(num_p); MatrixNXd sample_m(num_m); mu_m.setZero(); Lambda_m.setIdentity(); sample_u.setConstant(2.0); Lambda_m *= 0.5; sample_m.col(0) = sample_movie(0, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } #else void run() { auto start = std::chrono::steady_clock::now(); SparseMatrixD Mt = M.transpose(); std::cout << "Sampling" << endl; for(int i=0; i<nsims; ++i) { // Sample from movie hyperparams tie(mu_m, Lambda_m) = CondNormalWishart(sample_m, mu0_m, b0_m, WI_m, df_m); // Sample from user hyperparams tie(mu_u, Lambda_u) = CondNormalWishart(sample_u, mu0_u, b0_u, WI_u, df_u); #pragma omp parallel for for(int mm = 0; mm < num_m; ++mm) { sample_movie(sample_m, mm, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } #pragma omp parallel for for(int uu = 0; uu < num_p; ++uu) { sample_movie(sample_u, uu, Mt, mean_rating, sample_m, alpha, mu_u, Lambda_u); } auto eval = eval_probe_vec(probe_vec, sample_m, sample_u, mean_rating); double norm_u = sample_u.norm(); double norm_m = sample_m.norm(); auto end = std::chrono::steady_clock::now(); auto elapsed = std::chrono::duration<double>(end - start); double samples_per_sec = (i + 1) * (num_p + num_m) / elapsed.count(); printf("Iteration %d:\t num_correct: %3.2f%%\tavg_diff: %3.2f\tFU(%6.2f)\tFM(%6.2f)\tSamples/sec: %6.2f\n", i, 100*eval.first, eval.second, norm_u, norm_m, samples_per_sec); } } #endif int main(int argc, char *argv[]) { const char *fname = argv[1]; assert(fname && "filename missing"); Eigen::initParallel(); Eigen::setNbThreads(1); loadChemo(fname); init(); #ifdef TEST_SAMPLE test(); #else run(); #endif return 0; } <|endoftext|>
<commit_before>#include "tcp_server.h" #include "utility.h" #include <thread> #include <atomic> #include <unistd.h> #include <boost/function.hpp> #include <boost/exception/diagnostic_information.hpp> namespace Akumuli { // // // Tcp Session // // // std::string make_unique_session_name() { static std::atomic<int> counter = {0}; std::stringstream str; str << "tcp-session-" << counter.fetch_add(1); return str.str(); } TcpSession::TcpSession(IOServiceT *io, std::shared_ptr<DbSession> spout, bool parallel) : parallel_(parallel) , io_(io) , socket_(*io) , strand_(*io) , spout_(spout) , parser_(spout) , logger_(make_unique_session_name(), 10) { logger_.info() << "Session created"; parser_.start(); } TcpSession::~TcpSession() { logger_.info() << "Session destroyed"; } SocketT& TcpSession::socket() { return socket_; } std::tuple<TcpSession::BufferT, size_t> TcpSession::get_next_buffer() { Byte *buffer = parser_.get_next_buffer(); return std::make_tuple(buffer, BUFFER_SIZE); } void TcpSession::start() { BufferT buf; size_t buf_size; std::tie(buf, buf_size) = get_next_buffer(); if (parallel_) { socket_.async_read_some( boost::asio::buffer(buf, buf_size), strand_.wrap( boost::bind(&TcpSession::handle_read, shared_from_this(), buf, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } else { // Strand is not used here socket_.async_read_some( boost::asio::buffer(buf, buf_size), boost::bind(&TcpSession::handle_read, shared_from_this(), buf, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } ErrorCallback TcpSession::get_error_cb() { logger_.info() << "Creating error handler for session"; auto self = shared_from_this(); auto weak = std::weak_ptr<TcpSession>(self); auto fn = [weak](aku_Status status, u64) { auto session = weak.lock(); if (session) { const char* msg = aku_error_message(status); session->logger_.trace() << msg; boost::asio::streambuf stream; std::ostream os(&stream); os << "-DB " << msg << "\r\n"; boost::asio::async_write(session->socket_, stream, boost::bind(&TcpSession::handle_write_error, session, boost::asio::placeholders::error)); } }; return ErrorCallback(fn); } void TcpSession::handle_read(BufferT buffer, boost::system::error_code error, size_t nbytes) { if (error) { logger_.error() << error.message(); parser_.close(); } else { try { parser_.parse_next(buffer, static_cast<u32>(nbytes)); start(); } catch (StreamError const& resp_err) { // This error is related to client so we need to send it back logger_.error() << resp_err.what(); boost::asio::streambuf stream; std::ostream os(&stream); os << "-PARSER " << resp_err.what() << "\r\n"; boost::asio::async_write(socket_, stream, boost::bind(&TcpSession::handle_write_error, shared_from_this(), boost::asio::placeholders::error) ); } catch (DatabaseError const& dberr) { // Database error logger_.error() << boost::current_exception_diagnostic_information(); boost::asio::streambuf stream; std::ostream os(&stream); os << "-DB " << dberr.what() << "\r\n"; boost::asio::async_write(socket_, stream, boost::bind(&TcpSession::handle_write_error, shared_from_this(), boost::asio::placeholders::error) ); } catch (...) { // Unexpected error logger_.error() << boost::current_exception_diagnostic_information(); boost::asio::streambuf stream; std::ostream os(&stream); os << "-ERR " << boost::current_exception_diagnostic_information() << "\r\n"; boost::asio::async_write(socket_, stream, boost::bind(&TcpSession::handle_write_error, shared_from_this(), boost::asio::placeholders::error) ); } } } void TcpSession::handle_write_error(boost::system::error_code error) { if (!error) { logger_.info() << "Clean shutdown"; socket_.shutdown(SocketT::shutdown_both); } else { logger_.error() << "Error sending error message to client"; logger_.error() << error.message(); parser_.close(); } } // // // Tcp Acceptor // // // TcpAcceptor::TcpAcceptor(// Server parameters std::vector<IOServiceT *> io, int port, // Storage & pipeline std::shared_ptr<DbConnection> connection , bool parallel) : parallel_(parallel) , acceptor_(own_io_, EndpointT(boost::asio::ip::tcp::v4(), static_cast<u16>(port))) , sessions_io_(io) , connection_(connection) , io_index_{0} , start_barrier_(2) , stop_barrier_(2) , logger_("tcp-acceptor", 10) { logger_.info() << "Server created!"; logger_.info() << "Port: " << port; // Blocking I/O services for (auto io: sessions_io_) { sessions_work_.emplace_back(*io); } } TcpAcceptor::~TcpAcceptor() { logger_.info() << "TCP acceptor destroyed"; } void TcpAcceptor::start() { WorkT work(own_io_); // Run detached thread for accepts auto self = shared_from_this(); std::thread accept_thread([self]() { #ifdef __gnu_linux__ // Name the thread auto thread = pthread_self(); pthread_setname_np(thread, "TCP-accept"); #endif self->logger_.info() << "Starting acceptor worker thread"; self->start_barrier_.wait(); self->logger_.info() << "Acceptor worker thread have started"; try { self->own_io_.run(); } catch (...) { self->logger_.error() << "Error in acceptor worker thread: " << boost::current_exception_diagnostic_information(); throw; } self->logger_.info() << "Stopping acceptor worker thread"; self->stop_barrier_.wait(); self->logger_.info() << "Acceptor worker thread have stopped"; }); accept_thread.detach(); start_barrier_.wait(); logger_.info() << "Start listening"; _start(); } void TcpAcceptor::_run_one() { own_io_.run_one(); } void TcpAcceptor::_start() { std::shared_ptr<TcpSession> session; auto con = connection_.lock(); if (con) { auto spout = con->create_session(); session = std::make_shared<TcpSession>(sessions_io_.at(io_index_++ % sessions_io_.size()), std::move(spout), parallel_); } else { logger_.error() << "Database was already closed"; } // attach session to spout // run session acceptor_.async_accept( session->socket(), boost::bind(&TcpAcceptor::handle_accept, shared_from_this(), session, boost::asio::placeholders::error) ); } void TcpAcceptor::stop() { logger_.info() << "Stopping acceptor"; acceptor_.cancel(); own_io_.stop(); sessions_work_.clear(); logger_.info() << "Trying to stop acceptor"; stop_barrier_.wait(); logger_.info() << "Acceptor successfully stopped"; } void TcpAcceptor::_stop() { logger_.info() << "Stopping acceptor (test runner)"; acceptor_.close(); own_io_.stop(); sessions_work_.clear(); } void TcpAcceptor::handle_accept(std::shared_ptr<TcpSession> session, boost::system::error_code err) { if (AKU_LIKELY(!err)) { session->start(); _start(); } else { logger_.error() << "Acceptor error " << err.message(); } } // // // Tcp Server // // // TcpServer::TcpServer(std::shared_ptr<DbConnection> connection, int concurrency, int port, TcpServer::Mode mode) : connection_(connection) , barrier(static_cast<u32>(concurrency) + 1) , stopped{0} , logger_("tcp-server", 32) { logger_.info() << "TCP server created, concurrency: " << concurrency; if (mode == Mode::EVENT_LOOP_PER_THREAD) { for(int i = 0; i < concurrency; i++) { IOPtr ptr = IOPtr(new IOServiceT(1)); iovec.push_back(ptr.get()); ios_.push_back(std::move(ptr)); } } else { IOPtr ptr = IOPtr(new IOServiceT(static_cast<size_t>(concurrency))); iovec.push_back(ptr.get()); ios_.push_back(std::move(ptr)); } bool parallel = mode == Mode::SHARED_EVENT_LOOP; auto con = connection_.lock(); if (con) { serv = std::make_shared<TcpAcceptor>(iovec, port, con, parallel); serv->start(); } else { logger_.error() << "Can't start TCP server, database closed"; std::runtime_error err("DB connection closed"); BOOST_THROW_EXCEPTION(err); } } TcpServer::~TcpServer() { logger_.info() << "TCP server destroyed"; } void TcpServer::start(SignalHandler* sig, int id) { auto self = shared_from_this(); sig->add_handler(boost::bind(&TcpServer::stop, self), id); auto iorun = [self](IOServiceT& io, int cnt) { auto fn = [self, &io, cnt]() { #ifdef __gnu_linux__ // Name the thread auto thread = pthread_self(); pthread_setname_np(thread, "TCP-worker"); #endif Logger logger("tcp-server-worker", 10); try { logger.info() << "Event loop " << cnt << " started"; io.run(); logger.info() << "Event loop " << cnt << " stopped"; self->barrier.wait(); } catch (RESPError const& e) { logger.error() << e.what(); throw; } catch (...) { logger.error() << "Error in event loop " << cnt << ": " << boost::current_exception_diagnostic_information(); throw; } logger.info() << "Worker thread " << cnt << " stopped"; }; return fn; }; int cnt = 0; for (auto io: iovec) { std::thread iothread(iorun(*io, cnt++)); iothread.detach(); } } void TcpServer::stop() { if (stopped++ == 0) { serv->stop(); logger_.info() << "TcpServer stopped"; for(auto& svc: ios_) { svc->stop(); logger_.info() << "I/O service stopped"; } barrier.wait(); logger_.info() << "I/O threads stopped"; } } struct TcpServerBuilder { TcpServerBuilder() { ServerFactory::instance().register_type("TCP", *this); } std::shared_ptr<Server> operator () (std::shared_ptr<DbConnection> con, std::shared_ptr<ReadOperationBuilder>, const ServerSettings& settings) { if (sysconf(_SC_NPROCESSORS_ONLN <= 4)) settings.nworkers = 1; else settings.nworkers = std::thread::hardwared_concurrency() * 0.75; return std::make_shared<TcpServer>(con, settings.nworkers, settings.port); } }; static TcpServerBuilder reg_type; } <commit_msg>bugfix<commit_after>#include "tcp_server.h" #include "utility.h" #include <thread> #include <atomic> #include <unistd.h> #include <boost/function.hpp> #include <boost/exception/diagnostic_information.hpp> namespace Akumuli { // // // Tcp Session // // // std::string make_unique_session_name() { static std::atomic<int> counter = {0}; std::stringstream str; str << "tcp-session-" << counter.fetch_add(1); return str.str(); } TcpSession::TcpSession(IOServiceT *io, std::shared_ptr<DbSession> spout, bool parallel) : parallel_(parallel) , io_(io) , socket_(*io) , strand_(*io) , spout_(spout) , parser_(spout) , logger_(make_unique_session_name(), 10) { logger_.info() << "Session created"; parser_.start(); } TcpSession::~TcpSession() { logger_.info() << "Session destroyed"; } SocketT& TcpSession::socket() { return socket_; } std::tuple<TcpSession::BufferT, size_t> TcpSession::get_next_buffer() { Byte *buffer = parser_.get_next_buffer(); return std::make_tuple(buffer, BUFFER_SIZE); } void TcpSession::start() { BufferT buf; size_t buf_size; std::tie(buf, buf_size) = get_next_buffer(); if (parallel_) { socket_.async_read_some( boost::asio::buffer(buf, buf_size), strand_.wrap( boost::bind(&TcpSession::handle_read, shared_from_this(), buf, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } else { // Strand is not used here socket_.async_read_some( boost::asio::buffer(buf, buf_size), boost::bind(&TcpSession::handle_read, shared_from_this(), buf, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } ErrorCallback TcpSession::get_error_cb() { logger_.info() << "Creating error handler for session"; auto self = shared_from_this(); auto weak = std::weak_ptr<TcpSession>(self); auto fn = [weak](aku_Status status, u64) { auto session = weak.lock(); if (session) { const char* msg = aku_error_message(status); session->logger_.trace() << msg; boost::asio::streambuf stream; std::ostream os(&stream); os << "-DB " << msg << "\r\n"; boost::asio::async_write(session->socket_, stream, boost::bind(&TcpSession::handle_write_error, session, boost::asio::placeholders::error)); } }; return ErrorCallback(fn); } void TcpSession::handle_read(BufferT buffer, boost::system::error_code error, size_t nbytes) { if (error) { logger_.error() << error.message(); parser_.close(); } else { try { parser_.parse_next(buffer, static_cast<u32>(nbytes)); start(); } catch (StreamError const& resp_err) { // This error is related to client so we need to send it back logger_.error() << resp_err.what(); boost::asio::streambuf stream; std::ostream os(&stream); os << "-PARSER " << resp_err.what() << "\r\n"; boost::asio::async_write(socket_, stream, boost::bind(&TcpSession::handle_write_error, shared_from_this(), boost::asio::placeholders::error) ); } catch (DatabaseError const& dberr) { // Database error logger_.error() << boost::current_exception_diagnostic_information(); boost::asio::streambuf stream; std::ostream os(&stream); os << "-DB " << dberr.what() << "\r\n"; boost::asio::async_write(socket_, stream, boost::bind(&TcpSession::handle_write_error, shared_from_this(), boost::asio::placeholders::error) ); } catch (...) { // Unexpected error logger_.error() << boost::current_exception_diagnostic_information(); boost::asio::streambuf stream; std::ostream os(&stream); os << "-ERR " << boost::current_exception_diagnostic_information() << "\r\n"; boost::asio::async_write(socket_, stream, boost::bind(&TcpSession::handle_write_error, shared_from_this(), boost::asio::placeholders::error) ); } } } void TcpSession::handle_write_error(boost::system::error_code error) { if (!error) { logger_.info() << "Clean shutdown"; socket_.shutdown(SocketT::shutdown_both); } else { logger_.error() << "Error sending error message to client"; logger_.error() << error.message(); parser_.close(); } } // // // Tcp Acceptor // // // TcpAcceptor::TcpAcceptor(// Server parameters std::vector<IOServiceT *> io, int port, // Storage & pipeline std::shared_ptr<DbConnection> connection , bool parallel) : parallel_(parallel) , acceptor_(own_io_, EndpointT(boost::asio::ip::tcp::v4(), static_cast<u16>(port))) , sessions_io_(io) , connection_(connection) , io_index_{0} , start_barrier_(2) , stop_barrier_(2) , logger_("tcp-acceptor", 10) { logger_.info() << "Server created!"; logger_.info() << "Port: " << port; // Blocking I/O services for (auto io: sessions_io_) { sessions_work_.emplace_back(*io); } } TcpAcceptor::~TcpAcceptor() { logger_.info() << "TCP acceptor destroyed"; } void TcpAcceptor::start() { WorkT work(own_io_); // Run detached thread for accepts auto self = shared_from_this(); std::thread accept_thread([self]() { #ifdef __gnu_linux__ // Name the thread auto thread = pthread_self(); pthread_setname_np(thread, "TCP-accept"); #endif self->logger_.info() << "Starting acceptor worker thread"; self->start_barrier_.wait(); self->logger_.info() << "Acceptor worker thread have started"; try { self->own_io_.run(); } catch (...) { self->logger_.error() << "Error in acceptor worker thread: " << boost::current_exception_diagnostic_information(); throw; } self->logger_.info() << "Stopping acceptor worker thread"; self->stop_barrier_.wait(); self->logger_.info() << "Acceptor worker thread have stopped"; }); accept_thread.detach(); start_barrier_.wait(); logger_.info() << "Start listening"; _start(); } void TcpAcceptor::_run_one() { own_io_.run_one(); } void TcpAcceptor::_start() { std::shared_ptr<TcpSession> session; auto con = connection_.lock(); if (con) { auto spout = con->create_session(); session = std::make_shared<TcpSession>(sessions_io_.at(io_index_++ % sessions_io_.size()), std::move(spout), parallel_); } else { logger_.error() << "Database was already closed"; } // attach session to spout // run session acceptor_.async_accept( session->socket(), boost::bind(&TcpAcceptor::handle_accept, shared_from_this(), session, boost::asio::placeholders::error) ); } void TcpAcceptor::stop() { logger_.info() << "Stopping acceptor"; acceptor_.cancel(); own_io_.stop(); sessions_work_.clear(); logger_.info() << "Trying to stop acceptor"; stop_barrier_.wait(); logger_.info() << "Acceptor successfully stopped"; } void TcpAcceptor::_stop() { logger_.info() << "Stopping acceptor (test runner)"; acceptor_.close(); own_io_.stop(); sessions_work_.clear(); } void TcpAcceptor::handle_accept(std::shared_ptr<TcpSession> session, boost::system::error_code err) { if (AKU_LIKELY(!err)) { session->start(); _start(); } else { logger_.error() << "Acceptor error " << err.message(); } } // // // Tcp Server // // // TcpServer::TcpServer(std::shared_ptr<DbConnection> connection, int concurrency, int port, TcpServer::Mode mode) : connection_(connection) , barrier(static_cast<u32>(concurrency) + 1) , stopped{0} , logger_("tcp-server", 32) { logger_.info() << "TCP server created, concurrency: " << concurrency; if (mode == Mode::EVENT_LOOP_PER_THREAD) { for(int i = 0; i < concurrency; i++) { IOPtr ptr = IOPtr(new IOServiceT(1)); iovec.push_back(ptr.get()); ios_.push_back(std::move(ptr)); } } else { IOPtr ptr = IOPtr(new IOServiceT(static_cast<size_t>(concurrency))); iovec.push_back(ptr.get()); ios_.push_back(std::move(ptr)); } bool parallel = mode == Mode::SHARED_EVENT_LOOP; auto con = connection_.lock(); if (con) { serv = std::make_shared<TcpAcceptor>(iovec, port, con, parallel); serv->start(); } else { logger_.error() << "Can't start TCP server, database closed"; std::runtime_error err("DB connection closed"); BOOST_THROW_EXCEPTION(err); } } TcpServer::~TcpServer() { logger_.info() << "TCP server destroyed"; } void TcpServer::start(SignalHandler* sig, int id) { auto self = shared_from_this(); sig->add_handler(boost::bind(&TcpServer::stop, self), id); auto iorun = [self](IOServiceT& io, int cnt) { auto fn = [self, &io, cnt]() { #ifdef __gnu_linux__ // Name the thread auto thread = pthread_self(); pthread_setname_np(thread, "TCP-worker"); #endif Logger logger("tcp-server-worker", 10); try { logger.info() << "Event loop " << cnt << " started"; io.run(); logger.info() << "Event loop " << cnt << " stopped"; self->barrier.wait(); } catch (RESPError const& e) { logger.error() << e.what(); throw; } catch (...) { logger.error() << "Error in event loop " << cnt << ": " << boost::current_exception_diagnostic_information(); throw; } logger.info() << "Worker thread " << cnt << " stopped"; }; return fn; }; int cnt = 0; for (auto io: iovec) { std::thread iothread(iorun(*io, cnt++)); iothread.detach(); } } void TcpServer::stop() { if (stopped++ == 0) { serv->stop(); logger_.info() << "TcpServer stopped"; for(auto& svc: ios_) { svc->stop(); logger_.info() << "I/O service stopped"; } barrier.wait(); logger_.info() << "I/O threads stopped"; } } struct TcpServerBuilder { TcpServerBuilder() { ServerFactory::instance().register_type("TCP", *this); } std::shared_ptr<Server> operator () (std::shared_ptr<DbConnection> con, std::shared_ptr<ReadOperationBuilder>, const ServerSettings& settings) { if (sysconf(_SC_NPROCESSORS_ONLN) <= 4) settings.nworkers = 1; else settings.nworkers = std::thread::hardwared_concurrency() * 0.75; return std::make_shared<TcpServer>(con, settings.nworkers, settings.port); } }; static TcpServerBuilder reg_type; } <|endoftext|>
<commit_before>#include "cast.h" #include "assert.h" int main() { uint8_t num15[] = {0x00, 0x0a}; assert(0x0a == qingpei::toolkit::cast::bytes_to_uint16(num15)); return 0; }<commit_msg>one more test case for cast<commit_after>#include "cast.h" #include "assert.h" int main() { uint8_t bytes[] = {0x00, 0x0a, 0x01, 0x02}; assert(0x0a == qingpei::toolkit::cast::bytes_to_uint16(bytes)); assert(0x0a0102 == qingpei::toolkit::cast::bytes_to_uint32(bytes)); return 0; }<|endoftext|>
<commit_before>// common.cpp // nativeGraphics #include "common.h" #include <string> #ifdef ANDROID_NDK #include "importgl.h" #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <jni.h> #elif __APPLE__ #include <stdlib.h> #include <OpenGLES/ES2/gl.h> #else // linux #include <GL/glew.h> #include <stdio.h> #endif #include "Eigen/Core" #include "Eigen/Eigenvalues" #include "transform.h" #include "RenderObject.h" #include "PhysicsObject.h" #include "Character.h" #include "RenderLight.h" #include "Timer.h" #include "glsl_helper.h" #include "log.h" using namespace std; using Eigen::Matrix4f; using Eigen::Vector4f; int displayWidth = 0; int displayHeight = 0; GLuint defaultFrameBuffer = 0; RenderPipeline *pipeline = NULL; RenderObject *cave = NULL; Character *character = NULL; Character *jellyfish = NULL; PhysicsObject *bomb = NULL; RenderLight *smallLight = NULL; RenderLight *bigLight = NULL; RenderLight *spotLight = NULL; unsigned int frameNum = 0; #define PI 3.14f // Callback function to load resources. void*(*resourceCallback)(const char *) = NULL; void SetResourceCallback(void*(*cb)(const char *)) { resourceCallback = cb; } // Initialize the application, loading all of the settings that // we will be accessing later in our fragment shaders. void Setup(int w, int h) { if(!resourceCallback) { LOGE("Resource callback not set."); exit(-1); } displayWidth = w; displayHeight = h; pipeline = new RenderPipeline(); cave = new RenderObject("cave2.obj", NULL, "albedo_f.glsl"); cave->AddTexture("cave_albedo.jpg", false); character = new Character("submarine.obj", NULL, "albedo_f.glsl"); character->AddTexture("submarine_albedo.jpg", false); jellyfish = new Character("jellyfish.obj", "jellyfish_v.glsl", "albedo_f.glsl"); jellyfish->AddTexture("jellyfish_albedo.jpg", false); jellyfish->MaxAcceleration = 200.0f; jellyfish->Drag = 100.0f; jellyfish->MaxVelocity = 100.0f; bomb = new PhysicsObject("icosphere.obj", NULL, "solid_color_f.glsl"); smallLight = new RenderLight("icosphere.obj", "dr_standard_v.glsl", "dr_pointlight_sat_f.glsl"); bigLight = new RenderLight("square.obj", "dr_square_v.glsl", "dr_pointlight_f.glsl"); spotLight = new RenderLight("cone.obj", "dr_standard_v.glsl", "dr_spotlight_f.glsl"); } void setFrameBuffer(int handle) { defaultFrameBuffer = handle; } float cameraPos[3] = {0,180,100}; float cameraPan[3] = {0,200,0}; float orientation[3] = {0,0,0}; #define PAN_LERP_FACTOR .04 bool touchDown = false; bool shootBomb = false; float lastTouch[2] = {0,0}; // Clamps input to (-max, max) according to curve. inline float tanClamp(float input, float max) { return max * atan(input / max); } // Rotate around the subject based on orientation void rotatePerspective() { float rot0 = tanClamp( orientation[2], PI / 10.0f); float rot2 = tanClamp(-orientation[1], PI / 10.0f); translatef(cameraPan[0], cameraPan[1], cameraPan[2]); rotate(rot0, 0, rot2); translatef(-cameraPan[0], -cameraPan[1], -cameraPan[2]); } void RenderFrame() { pipeline->ClearBuffers(); // Setup perspective matrices pLoadIdentity(); perspective(90, (float) displayWidth / (float) displayHeight, 60, 800); mvLoadIdentity(); lookAt(cameraPos[0]+cameraPan[0], cameraPos[1]+cameraPan[1], cameraPos[2]+cameraPan[2], cameraPan[0], cameraPan[1], cameraPan[2], 0, 1, 0); rotatePerspective(); ////////////////////////////////// // Render to g buffer. /** Any geometry that will be collision detected should be rendered here, before user input. **/ mvPushMatrix(); scalef(40); cave->Render(); mvPopMatrix(); // Process user input if(touchDown) { uint8_t * geometry = pipeline->RayTracePixel(lastTouch[0], 1.0f - lastTouch[1], true); if(geometry[3] != 255) { float depth = geometry[3] / 128.0f - 1.0f; Matrix4f mvp = projection.top()*model_view.top(); Vector4f pos = mvp.inverse() * Vector4f((lastTouch[0]) * 2.0f - 1.0f, (1.0 - lastTouch[1]) * 2.0f - 1.0f, depth, 1.0); character->targetPosition = Vector3f(pos(0) / pos(3), pos(1) / pos(3), pos(2) / pos(3)); } delete[] geometry; } for(int i = 0; i < 3; i++) cameraPan[i] = (1.0 - PAN_LERP_FACTOR) * cameraPan[i] + PAN_LERP_FACTOR * character->position[i]; if(shootBomb) { bomb->position = Eigen::Vector3f(character->position[0], character->position[1], character->position[2]); bomb->velocity = 200.0f * Eigen::Vector3f(-cos(character->rot[0]), 1.0f, sin(character->rot[0])); shootBomb = false; } // Run physics. bomb->Update(); character->Update(); jellyfish->targetPosition = Vector3f(character->position[0], character->position[1], character->position[2]);// character->position; jellyfish->Update(); mvPushMatrix(); translatef(character->position[0], character->position[1], character->position[2]); rotate(0.0, character->rot[0], character->rot[1]); scalef(.15); character->Render(); mvPopMatrix(); mvPushMatrix(); translatef(jellyfish->position[0], jellyfish->position[1], jellyfish->position[2]); rotate(0.0, jellyfish->rot[0], jellyfish->rot[1]); rotate(0.0, 0.0, PI / 2); scalef(3.00); jellyfish->Render(); mvPopMatrix(); mvPushMatrix(); translatef(bomb->position[0], bomb->position[1], bomb->position[2]); scalef(10); bomb->Render(); mvPopMatrix(); //////////////////////////////////////////////////// // Using g buffer, render lights mvPushMatrix(); translatef(character->position[0], character->position[1], character->position[2]); bigLight->color[0] = 1.0; bigLight->color[1] = 1.0; bigLight->color[2] = 0.8; bigLight->brightness = 16000.0; bigLight->Render(); mvPopMatrix(); mvPushMatrix(); translatef(bomb->position[0], bomb->position[1], bomb->position[2]); scalef(100); smallLight->color[0] = 1.00f; smallLight->color[1] = 0.33f; smallLight->color[2] = 0.07f; smallLight->brightness = 1500 + 1500 * sin(frameNum / 6.0f); smallLight->Render(); mvPopMatrix(); mvPushMatrix(); translatef(character->position[0], character->position[1], character->position[2]); rotate(0.0, character->rot[0], character->rot[1]); rotate(0.0,0,-PI / 2); scalef(300.0f); spotLight->color[0] = 0.4f; spotLight->color[1] = 0.6f; spotLight->color[2] = 1.0f; spotLight->brightness = 16000.0; spotLight->Render(); mvPopMatrix(); frameNum++; fpsMeter(); } void PointerDown(float x, float y, int pointerIndex) { lastTouch[0] = x; lastTouch[1] = y; touchDown = true; shootBomb = true; } void PointerMove(float x, float y, int pointerIndex) { lastTouch[0] = x; lastTouch[1] = y; touchDown = true; } void PointerUp(float x, float y, int pointerIndex) { touchDown = false; } void UpdateOrientation(float roll, float pitch, float yaw) { orientation[0] = roll; orientation[1] = pitch; orientation[2] = yaw; } <commit_msg>Wrote an explosion for the bomb.<commit_after>// common.cpp // nativeGraphics #include "common.h" #include <string> #ifdef ANDROID_NDK #include "importgl.h" #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <jni.h> #elif __APPLE__ #include <stdlib.h> #include <OpenGLES/ES2/gl.h> #else // linux #include <GL/glew.h> #include <stdio.h> #endif #include "Eigen/Core" #include "Eigen/Eigenvalues" #include "transform.h" #include "RenderObject.h" #include "PhysicsObject.h" #include "Character.h" #include "RenderLight.h" #include "Timer.h" #include "glsl_helper.h" #include "log.h" using namespace std; using Eigen::Matrix4f; using Eigen::Vector4f; int displayWidth = 0; int displayHeight = 0; GLuint defaultFrameBuffer = 0; RenderPipeline *pipeline = NULL; RenderObject *cave = NULL; Character *character = NULL; Character *jellyfish = NULL; PhysicsObject *bomb = NULL; Timer bombTimer; #define BOMB_TIMER_LENGTH 2.0f #define BOMB_EXPLOSION_LENGTH .3f RenderLight *smallLight = NULL; RenderLight *bigLight = NULL; RenderLight *explosiveLight = NULL; RenderLight *spotLight = NULL; #define PI 3.1415f // Callback function to load resources. void*(*resourceCallback)(const char *) = NULL; void SetResourceCallback(void*(*cb)(const char *)) { resourceCallback = cb; } // Initialize the application, loading all of the settings that // we will be accessing later in our fragment shaders. void Setup(int w, int h) { if(!resourceCallback) { LOGE("Resource callback not set."); exit(-1); } displayWidth = w; displayHeight = h; pipeline = new RenderPipeline(); cave = new RenderObject("cave2.obj", NULL, "albedo_f.glsl"); cave->AddTexture("cave_albedo.jpg", false); character = new Character("submarine.obj", NULL, "albedo_f.glsl"); character->AddTexture("submarine_albedo.jpg", false); jellyfish = new Character("jellyfish.obj", "jellyfish_v.glsl", "albedo_f.glsl"); jellyfish->AddTexture("jellyfish_albedo.jpg", false); jellyfish->position = Vector3f(200, 300, 400); jellyfish->MaxAcceleration = 200.0f; jellyfish->Drag = 100.0f; jellyfish->MaxVelocity = 100.0f; bomb = new PhysicsObject("icosphere.obj", NULL, "solid_color_f.glsl"); smallLight = new RenderLight("icosphere.obj", "dr_standard_v.glsl", "dr_pointlight_sat_f.glsl"); bigLight = new RenderLight("square.obj", "dr_square_v.glsl", "dr_pointlight_f.glsl"); explosiveLight = new RenderLight("icosphere.obj", "dr_standard_v.glsl", "dr_explosive_pointlight_f.glsl"); spotLight = new RenderLight("cone.obj", "dr_standard_v.glsl", "dr_spotlight_f.glsl"); } void setFrameBuffer(int handle) { defaultFrameBuffer = handle; } float cameraPos[3] = {0,180,100}; float cameraPan[3] = {0,200,0}; float orientation[3] = {0,0,0}; #define PAN_LERP_FACTOR .04 bool touchDown = false; bool shootBomb = false; float lastTouch[2] = {0,0}; // Clamps input to (-max, max) according to curve. inline float tanClamp(float input, float max) { return max * atan(input / max); } // Rotate around the subject based on orientation void rotatePerspective() { float rot0 = tanClamp( orientation[2], PI / 10.0f); float rot2 = tanClamp(-orientation[1], PI / 10.0f); translatef(cameraPan[0], cameraPan[1], cameraPan[2]); rotate(rot0, 0, rot2); translatef(-cameraPan[0], -cameraPan[1], -cameraPan[2]); } void RenderFrame() { pipeline->ClearBuffers(); // Setup perspective matrices pLoadIdentity(); perspective(90, (float) displayWidth / (float) displayHeight, 60, 800); mvLoadIdentity(); lookAt(cameraPos[0]+cameraPan[0], cameraPos[1]+cameraPan[1], cameraPos[2]+cameraPan[2], cameraPan[0], cameraPan[1], cameraPan[2], 0, 1, 0); rotatePerspective(); ////////////////////////////////// // Render to g buffer. /** Any geometry that will be collision detected should be rendered here, before user input. **/ mvPushMatrix(); scalef(40); cave->Render(); mvPopMatrix(); // Process user input if(touchDown) { uint8_t * geometry = pipeline->RayTracePixel(lastTouch[0], 1.0f - lastTouch[1], true); if(geometry[3] != 255) { float depth = geometry[3] / 128.0f - 1.0f; Matrix4f mvp = projection.top()*model_view.top(); Vector4f pos = mvp.inverse() * Vector4f((lastTouch[0]) * 2.0f - 1.0f, (1.0 - lastTouch[1]) * 2.0f - 1.0f, depth, 1.0); character->targetPosition = Vector3f(pos(0) / pos(3), pos(1) / pos(3), pos(2) / pos(3)); } delete[] geometry; } for(int i = 0; i < 3; i++) cameraPan[i] = (1.0 - PAN_LERP_FACTOR) * cameraPan[i] + PAN_LERP_FACTOR * character->position[i]; if(shootBomb) { bomb->position = Eigen::Vector3f(character->position[0], character->position[1], character->position[2]); bomb->velocity = 200.0f * Eigen::Vector3f(-cos(character->rot[0]), 1.0f, sin(character->rot[0])); shootBomb = false; bombTimer.reset(); } // Run physics. bomb->Update(); character->Update(); jellyfish->targetPosition = character->position; jellyfish->Update(); mvPushMatrix(); translatef(character->position[0], character->position[1], character->position[2]); rotate(0.0, character->rot[0], character->rot[1]); scalef(.15); character->Render(); mvPopMatrix(); mvPushMatrix(); translatef(jellyfish->position[0], jellyfish->position[1], jellyfish->position[2]); rotate(0.0, jellyfish->rot[0], jellyfish->rot[1]); rotate(0.0, 0.0, PI / 2); scalef(2.00); jellyfish->Render(); mvPopMatrix(); if(bombTimer.getSeconds() <= BOMB_TIMER_LENGTH) { mvPushMatrix(); translatef(bomb->position[0], bomb->position[1], bomb->position[2]); scalef(10); bomb->Render(); mvPopMatrix(); } //////////////////////////////////////////////////// // Using g buffer, render lights mvPushMatrix(); translatef(character->position[0], character->position[1], character->position[2]); bigLight->color[0] = 1.0; bigLight->color[1] = 1.0; bigLight->color[2] = 0.8; bigLight->brightness = 16000.0; bigLight->Render(); mvPopMatrix(); if(bombTimer.getSeconds() <= BOMB_TIMER_LENGTH) { mvPushMatrix(); translatef(bomb->position[0], bomb->position[1], bomb->position[2]); scalef(100); smallLight->color[0] = 1.00f; smallLight->color[1] = 0.33f; smallLight->color[2] = 0.07f; smallLight->brightness = 1500 + 1500 * sin(bombTimer.getSeconds() * 4.0f * PI); smallLight->Render(); mvPopMatrix(); } else if(bombTimer.getSeconds() <= BOMB_TIMER_LENGTH + BOMB_EXPLOSION_LENGTH) { mvPushMatrix(); translatef(bomb->position[0], bomb->position[1], bomb->position[2]); scalef(250); explosiveLight->color[0] = 1.00f; explosiveLight->color[1] = 1.00f; explosiveLight->color[2] = 1.00f; float explosionTime = (bombTimer.getSeconds() - BOMB_TIMER_LENGTH) / BOMB_EXPLOSION_LENGTH; explosiveLight->brightness = 10000000.0f * sin(PI * sqrt(explosionTime)); explosiveLight->Render(); mvPopMatrix(); } mvPushMatrix(); translatef(character->position[0], character->position[1], character->position[2]); rotate(0.0, character->rot[0], character->rot[1]); rotate(0.0,0,-PI / 2); scalef(300.0f); spotLight->color[0] = 0.4f; spotLight->color[1] = 0.6f; spotLight->color[2] = 1.0f; spotLight->brightness = 16000.0; spotLight->Render(); mvPopMatrix(); fpsMeter(); } void PointerDown(float x, float y, int pointerIndex) { lastTouch[0] = x; lastTouch[1] = y; touchDown = true; shootBomb = true; } void PointerMove(float x, float y, int pointerIndex) { lastTouch[0] = x; lastTouch[1] = y; touchDown = true; } void PointerUp(float x, float y, int pointerIndex) { touchDown = false; } void UpdateOrientation(float roll, float pitch, float yaw) { orientation[0] = roll; orientation[1] = pitch; orientation[2] = yaw; } <|endoftext|>
<commit_before>#ifndef tut_polymorphism_hpp #define tut_polymorphism_hpp #include <cstddef> #include <functional> #include "../xtd/castable.hpp" namespace tut { // This tutorial gives an introduction to the data abstraction-style in C++ (DAS). // // DAS is a simple, powerful, composable, and efficient style of C++ programming. It is the // combination of four major implementation techniques - // // 1) data abstractions rather than OOP objects // 2) stand-alone functions rather than member functions // 3) opaque mixins rather than OOP inheritance // 4) the following types of polymorphism rather than OOP polymorphism - // a) ad-hoc polymorphism (function overloading) // b) structural polymorphism (function templates without specialization) // c) static polymorphisms (function template with specialization) // // Subtype polymorphism should be used only when necessary, such as in mixins and plugins. // // In these tutorial and with the library code provided in this repository, I hope to // demonstrate the validity of DAS programming in C++ as an alternative to OOP. // // So let's get started! // Here we have a data abstraction, or 'DA'. You can tell it is different from an OOP object as // it has no public functions (save for ctors, dtors, and operators). Its has better generic // usage (especially with respect to the above preferred forms of polymorphism) and exposes a // much simpler and more extensible interface. Adding a new function to a DA is as easy as // opening up its containing namespace and plopping one in. // // Also unlike objects, DA's do only what they must in order to implement a localized // semantics rather than doing as much as possible for the wider system. // // For example, if you have a simulant DA in a simulation, it won't be that simulant's role to // hold on to a shader and texture handle to in order to render itself. Instead, the DA will be // a bag of data properties with consistency invariants. To perform specialized tasks like // rendering or physics, the simulant DA sends data messages that describe the desired // rendering or physics results to a renderer or physics system. It is up to these // specialized systems to manage resources and perform the tasks that the data messages // describe. // // The downside to DAs is that they are considered novel in some C++ shops, and may therfore // pose adoption difficulties in practice. class data_abstraction { private: // A private field. Note that having a single, const private field is rarely a good enough // reason to use a DA, but we're just giving a toy example to keeps things simple. const int value; protected: // Here we have a friend declaration that allows us to implement our interface. I make it // protected because that seems to gel with the ordering in more involved DA types, but you // can make them private if your prefer. friend int func(const data_abstraction&); public: // A public constructor that initializes the private value. data_abstraction(int value) : value(value) { } }; // Here we expose our DA's interface with stand-alone functions. For more on why stand-alone // functions are considered superior to OO-style member functions, see - // http://www.gotw.ca/gotw/084.htm and - // http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197 int func(const data_abstraction& da) { return da.value * 5; } // Unlike with OO interfaces, extending a DA is easy; even if you're in a different file or // code base, just open up the DA's namespace and add functions to you heart's content! int func_ex(const data_abstraction& da) { return func(da) + 5; } // Structural, or 'static duck-type', polymorphism is easy, useful, and usually politically // viable in C++ shops. However, it's not the most powerful form of static polymorphism in // C++, and its applicability is therefore limited. template<typename T> int pow(const T& t) { return func(t) * func(t); } // An extended pow function. template<typename T> int pow_ex(const T& t) { return func_ex(t) * func_ex(t); } // Template specialization provides a powerful form of static polymorphism in C++. On the plus // side, it's generally efficient, and in simpler forms, is easy to understand. On the minus, // once this approach starts invoking multiple different functions on the generalized type, it // starts becoming more like a limited form of type classes. That, in itself is quite a good // thing, but considering that C++ Concepts still haven't made it into the language, code that // leverages this form of polymorphism in complicated ways can be increasingly difficult for // many devs to deal with. template<typename T> T op(const T& a, const T& b) { return a + b; } // Int specialization of op. template<> int op(const int& a, const int& b) { return a * b; } // Float specialization of op. template<> float op(const float& a, const float& b) { return a / b; } // Note that function templates shadow rather than overload, so if you want to have the same // generic function with a different number of parameters, you do as the standard library does // and suffix the name with the number parameters. This is the same approach as taken in most // functional languages. Usually the original function remains un-numbered, so you can apply // this after-the-fact. template<typename T> T op3(const T& a, const T& b, const T& c) { return a + b + c; } // As you can see, a great variety of computation and program characteristics can be cleanly, // efficiently, and most importantly _generically_ expressed using just the above concepts. // However, we will still need late-binding to achieve certain types of abstractions. This // is where DAS mixins come in. // // What is a mixin in the context of data-abstraction style? // // Mixins in this context are a bit different than what most C++ articles about mixins present. // Rather than being programming components that allow the injection of capabilities into a // class a posteriori via template arguments, our mixins are simple data abstractions that each // provide a single orthogonal capability to another data abstraction (itself possibly another // mixin) via inheritance. // // A good example of a mixin is implemented in '../hpp/xtd/castable.hpp'. By inheriting from // this mixin, you get dynamic castability capabilities via - // 1) A common base type xtd::castable. // 2) Virtual try_cast functions, with default template impl functions to ease overriding. // 3) A complete public interface, including usage with smart ptrs. // // The following is a type that leverages the castable mixin - // A mixin for making a type addressable. // // The policy hard-wired into this mixin is that an addressable's name cannot change. If an // addressable needs a different name, the policy is to copy it with a different name, then // discard the original. This actually works best in simulators because trying to implement // mutable identities is overly complicating in practice. class widget : public virtual xtd::castable { private: const int upc; const float age; const bool replacable; protected: // Override xtd::castable::try_cast_const. void const* try_cast_const(const char* type_name) const override { return try_cast_const_impl<castable>(this, type_name); } // Override xtd::castable::try_cast. void* try_cast(const char* type_name) override { return try_cast_impl<castable>(this, type_name); } // Our interface functions. friend int get_upc(const widget& widget); friend bool should_replace(const widget& widget, float age_max); public: widget(int upc, float age, bool replacable) : upc(upc), age(age), replacable(replacable) { } }; int get_upc(const widget& widget) { return widget.upc; } bool should_replace(const widget& widget, float age_max) { return widget.replacable && widget.age > age_max; } bool should_replace_with(const widget& widget, float age_max, int upc) { return should_replace(widget, age_max) && get_upc(widget) == upc; } } #endif <commit_msg>Cleaned up mixin docs.<commit_after>#ifndef tut_polymorphism_hpp #define tut_polymorphism_hpp #include <cstddef> #include <functional> #include "../xtd/castable.hpp" namespace tut { // This tutorial gives an introduction to the data abstraction-style in C++ (DAS). // // DAS is a simple, powerful, composable, and efficient style of C++ programming. It is the // combination of four major implementation techniques - // // 1) data abstractions rather than OOP objects // 2) stand-alone functions rather than member functions // 3) composable mixins rather than OOP inheritance // 4) the following types of polymorphism rather than OOP polymorphism - // a) ad-hoc polymorphism (function overloading) // b) structural polymorphism (function templates without specialization) // c) static polymorphisms (function template with specialization) // // Subtype polymorphism should be used only when necessary, such as in mixins and plugins. // // In these tutorial and with the library code provided in this repository, I hope to // demonstrate the validity of DAS programming in C++ as an alternative to OOP. // // So let's get started! // Here we have a data abstraction, or 'DA'. You can tell it is different from an OOP object as // it has no public functions (save for ctors, dtors, and operators). Its has better generic // usage (especially with respect to the above preferred forms of polymorphism) and exposes a // much simpler and more extensible interface. Adding a new function to a DA is as easy as // opening up its containing namespace and plopping one in. // // Also unlike objects, DA's do only what they must in order to implement a localized // semantics rather than doing as much as possible for the wider system. // // For example, if you have a simulant DA in a simulation, it won't be that simulant's role to // hold on to a shader and texture handle to in order to render itself. Instead, the DA will be // a bag of data properties with consistency invariants. To perform specialized tasks like // rendering or physics, the simulant DA sends data messages that describe the desired // rendering or physics results to a renderer or physics system. It is up to these // specialized systems to manage resources and perform the tasks that the data messages // describe. // // The downside to DAs is that they are considered novel in some C++ shops, and may therfore // pose adoption difficulties in practice. class data_abstraction { private: // A private field. Note that having a single, const private field is rarely a good enough // reason to use a DA, but we're just giving a toy example to keeps things simple. const int value; protected: // Here we have a friend declaration that allows us to implement our interface. I make it // protected because that seems to gel with the ordering in more involved DA types, but you // can make them private if your prefer. friend int func(const data_abstraction&); public: // A public constructor that initializes the private value. data_abstraction(int value) : value(value) { } }; // Here we expose our DA's interface with stand-alone functions. For more on why stand-alone // functions are considered superior to OO-style member functions, see - // http://www.gotw.ca/gotw/084.htm and - // http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197 int func(const data_abstraction& da) { return da.value * 5; } // Unlike with OO interfaces, extending a DA is easy; even if you're in a different file or // code base, just open up the DA's namespace and add functions to you heart's content! int func_ex(const data_abstraction& da) { return func(da) + 5; } // Structural, or 'static duck-type', polymorphism is easy, useful, and usually politically // viable in C++ shops. However, it's not the most powerful form of static polymorphism in // C++, and its applicability is therefore limited. template<typename T> int pow(const T& t) { return func(t) * func(t); } // An extended pow function. template<typename T> int pow_ex(const T& t) { return func_ex(t) * func_ex(t); } // Template specialization provides a powerful form of static polymorphism in C++. On the plus // side, it's generally efficient, and in simpler forms, is easy to understand. On the minus, // once this approach starts invoking multiple different functions on the generalized type, it // starts becoming more like a limited form of type classes. That, in itself is quite a good // thing, but considering that C++ Concepts still haven't made it into the language, code that // leverages this form of polymorphism in complicated ways can be increasingly difficult for // many devs to deal with. template<typename T> T op(const T& a, const T& b) { return a + b; } // Int specialization of op. template<> int op(const int& a, const int& b) { return a * b; } // Float specialization of op. template<> float op(const float& a, const float& b) { return a / b; } // Note that function templates shadow rather than overload, so if you want to have the same // generic function with a different number of parameters, you do as the standard library does // and suffix the name with the number parameters. This is the same approach as taken in most // functional languages. Usually the original function remains un-numbered, so you can apply // this after-the-fact. template<typename T> T op3(const T& a, const T& b, const T& c) { return a + b + c; } // As you can see, a great variety of computation and program characteristics can be cleanly, // efficiently, and most importantly _generically_ expressed using just the above concepts. // However, we will still need late-binding to achieve certain types of abstractions. This // is where DAS mixins come in. // // What is a mixin in the context of data-abstraction style? // // Mixins in this context are a bit different than what most C++ articles about mixins present. // Rather than being programming components that allow the injection of capabilities into a // class a posteriori via template arguments, our mixins are simple data abstractions that each // provide a single orthogonal capability to another data abstraction via inheritance. // // A good example of a mixin is implemented in '../hpp/xtd/castable.hpp'. By inheriting from // this mixin, you get dynamic castability capabilities via - // 1) A common base type xtd::castable. // 2) Virtual try_cast functions, with default template impl functions to ease overriding. // 3) A completely general public interface, including casting with smart ptrs. // // The following is a type that leverages the castable mixin - class widget : public xtd::castable { private: const int upc; const float age; const bool replacable; protected: // Override xtd::castable::try_cast_const from mixin. void const* try_cast_const(const char* type_name) const override { return try_cast_const_impl<castable>(this, type_name); } // Override xtd::castable::try_cast from mixin. void* try_cast(const char* type_name) override { return try_cast_impl<castable>(this, type_name); } friend int get_upc(const widget& widget); friend bool should_replace(const widget& widget, float age_max); public: // Construct our widget. widget(int upc, float age, bool replacable) : upc(upc), age(age), replacable(replacable) { } }; // Get the upc of a widget. int get_upc(const widget& widget) { return widget.upc; } // Query that a widget should be replaced. bool should_replace(const widget& widget, float age_max) { return widget.replacable && widget.age > age_max; } // Query that a widget should be replaced with a give product. bool should_replace_with(const widget& widget, float age_max, int upc) { return should_replace(widget, age_max) && get_upc(widget) == upc; } } #endif <|endoftext|>
<commit_before>// This file is part of Poseidon. // Copyleft 2022, LH_Mouse. All wrongs reserved. #include "../precompiled.ipp" #include "udp_socket.hpp" #include "../static/async_logger.hpp" #include "../utils.hpp" namespace poseidon { UDP_Socket:: UDP_Socket(int family) : Abstract_Socket(family, SOCK_DGRAM, IPPROTO_UDP) { } UDP_Socket:: ~UDP_Socket() { } IO_Result UDP_Socket:: do_abstract_socket_on_readable() { const recursive_mutex::unique_lock io_lock(this->m_io_mutex); // Try getting a packet from this socket. this->m_io_read_queue.clear(); this->m_io_read_queue.reserve(0xFFFFU); size_t datalen = this->m_io_read_queue.capacity(); Socket_Address addr; ::socklen_t addrlen = (::socklen_t) addr.capacity(); ::ssize_t nread; int err; do { nread = ::recvfrom(this->fd(), this->m_io_read_queue.mut_end(), datalen, 0, addr.mut_addr(), &addrlen); err = (nread < 0) ? errno : 0; } while(err == EINTR); if((err == EAGAIN) || (err == EWOULDBLOCK)) return io_result_would_block; else if(err != 0) POSEIDON_THROW(( "Error reading UDP socket", "[`recvfrom()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(err)); // Accept this packet. this->m_io_read_queue.accept((size_t) nread); addr.set_size(addrlen); this->do_on_udp_packet(::std::move(addr), ::std::move(this->m_io_read_queue)); return io_result_partial; } IO_Result UDP_Socket:: do_abstract_socket_on_writable() { const recursive_mutex::unique_lock io_lock(this->m_io_mutex); if(this->m_io_write_queue.empty()) return io_result_partial; Socket_Address addr; ::socklen_t addrlen; size_t datalen; // Get a packet from the send queue. // This piece of code must match `udp_send()`. size_t ngot = this->m_io_write_queue.getn((char*) &addrlen, sizeof(addrlen)); ROCKET_ASSERT(ngot == sizeof(addrlen)); ngot = this->m_io_write_queue.getn((char*) &datalen, sizeof(datalen)); ROCKET_ASSERT(ngot == sizeof(datalen)); ngot = this->m_io_write_queue.getn((char*) addr.mut_data(), addrlen); ROCKET_ASSERT(ngot == (uint32_t) addrlen); ::ssize_t nwritten; int err; do { nwritten = ::sendto(this->fd(), this->m_io_write_queue.begin(), datalen, 0, addr.addr(), addrlen); err = (nwritten < 0) ? errno : 0; } while(err == EINTR); // Remove data from the send queue, no matter whether the operation has // succeeded or not. this->m_io_write_queue.discard(datalen); if((err == EAGAIN) || (err == EWOULDBLOCK)) return io_result_would_block; else if(err != 0) POSEIDON_THROW(( "Error writing UDP socket", "[`sendto()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(err)); // Report that some data have been written anyway. return io_result_partial; } void UDP_Socket:: do_abstract_socket_on_exception(exception& stdex) { POSEIDON_LOG_WARN(( "Ignoring exception: $3", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), stdex); } void UDP_Socket:: join_multicast_group(const Socket_Address& maddr, uint8_t ttl, bool loopback) { if(maddr.classify() != socket_address_class_multicast) POSEIDON_THROW(( "Invalid multicast address `$1`"), maddr); if(maddr.family() == AF_INET) { // IPv4 struct ::ip_mreqn mreq; mreq.imr_multiaddr = maddr.addr4()->sin_addr; mreq.imr_address.s_addr = INADDR_ANY; mreq.imr_ifindex = 0; if(::setsockopt(this->fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) != 0) POSEIDON_THROW(( "Failed to join multicast group `$4`", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(), maddr); int ival = ttl; if(::setsockopt(this->fd(), IPPROTO_IP, IP_MULTICAST_TTL, &ival, sizeof(ival)) != 0) POSEIDON_THROW(( "Failed to set TTL of multicast packets", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); ival = loopback; if(::setsockopt(this->fd(), IPPROTO_IP, IP_MULTICAST_LOOP, &ival, sizeof(ival)) != 0) POSEIDON_THROW(( "Failed to set loopback of multicast packets", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); } else if(maddr.family() == AF_INET6) { // IPv6 struct ::ipv6_mreq mreq; mreq.ipv6mr_multiaddr = maddr.addr6()->sin6_addr; mreq.ipv6mr_interface = 0; if(::setsockopt(this->fd(), IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) != 0) POSEIDON_THROW(( "Failed to join multicast group `$4`", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(), maddr); int ival = ttl; if(::setsockopt(this->fd(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ival, sizeof(ival)) != 0) POSEIDON_THROW(( "Failed to set TTL of multicast packets", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); ival = loopback; if(::setsockopt(this->fd(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &ival, sizeof(ival)) != 0) POSEIDON_THROW(( "Failed to set loopback of multicast packets", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); } else POSEIDON_THROW(( "Socket address family `$3` not supported", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), maddr.family()); } void UDP_Socket:: leave_multicast_group(const Socket_Address& maddr) { if(maddr.classify() != socket_address_class_multicast) POSEIDON_THROW(( "Invalid multicast address `$1`"), maddr); if(maddr.family() == AF_INET) { // IPv4 struct ::ip_mreqn mreq; mreq.imr_multiaddr = maddr.addr4()->sin_addr; mreq.imr_address.s_addr = INADDR_ANY; mreq.imr_ifindex = 0; if(::setsockopt(this->fd(), IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) != 0) POSEIDON_THROW(( "Failed to leave multicast group `$4`", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(), maddr); } else if(maddr.family() == AF_INET6) { // IPv6 struct ::ipv6_mreq mreq; mreq.ipv6mr_multiaddr = maddr.addr6()->sin6_addr; mreq.ipv6mr_interface = 0; if(::setsockopt(this->fd(), IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) != 0) POSEIDON_THROW(( "Failed to leave multicast group `$4`", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(), maddr); } else POSEIDON_THROW(( "Socket address family `$3` not supported", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), maddr.family()); } bool UDP_Socket:: udp_send(const Socket_Address& addr, const char* data, size_t size) { size_t datalen = size & 0xFFFFU; if(datalen != size) POSEIDON_THROW(( "`$3` bytes is too large for a UDP packet", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), size); if(datalen && !data) POSEIDON_THROW(( "Null data pointer", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this)); // If this socket has been marked closed, fail immediately. if(this->socket_state() == socket_state_closed) return false; const recursive_mutex::unique_lock io_lock(this->m_io_mutex); // Encode this packet. // This piece of code must match `do_abstract_socket_on_writable()`. ::socklen_t addrlen = addr.ssize(); size_t queue_size = sizeof(addrlen) + sizeof(datalen) + (uint32_t) addrlen + datalen; this->m_io_write_queue.reserve(queue_size); ::memcpy(this->m_io_write_queue.mut_end(), &addrlen, sizeof(addrlen)); this->m_io_write_queue.accept(sizeof(addrlen)); ::memcpy(this->m_io_write_queue.mut_end(), &datalen, sizeof(datalen)); this->m_io_write_queue.accept(sizeof(datalen)); ::memcpy(this->m_io_write_queue.mut_end(), addr.data(), (uint32_t) addrlen); this->m_io_write_queue.accept((uint32_t) addrlen); ::memcpy(this->m_io_write_queue.mut_end(), data, datalen); this->m_io_write_queue.accept(datalen); // Try writing once. This is essential for the edge-triggered epoll to work // reliably, because the level-triggered epoll does not check for `EPOLLOUT` by // default. If the packet has been sent anyway, discard it from the send queue. this->do_abstract_socket_on_writable(); return true; } bool UDP_Socket:: udp_send(const Socket_Address& addr, const cow_string& data) { return this->udp_send(addr, data.data(), data.size()); } bool UDP_Socket:: udp_send(const Socket_Address& addr, const string& data) { return this->udp_send(addr, data.data(), data.size()); } } // namespace poseidon <commit_msg>udp_socket: Minor<commit_after>// This file is part of Poseidon. // Copyleft 2022, LH_Mouse. All wrongs reserved. #include "../precompiled.ipp" #include "udp_socket.hpp" #include "../static/async_logger.hpp" #include "../utils.hpp" namespace poseidon { UDP_Socket:: UDP_Socket(int family) : Abstract_Socket(family, SOCK_DGRAM, IPPROTO_UDP) { } UDP_Socket:: ~UDP_Socket() { } IO_Result UDP_Socket:: do_abstract_socket_on_readable() { const recursive_mutex::unique_lock io_lock(this->m_io_mutex); // Try getting a packet from this socket. this->m_io_read_queue.clear(); this->m_io_read_queue.reserve(0xFFFFU); size_t datalen = this->m_io_read_queue.capacity(); Socket_Address addr; ::socklen_t addrlen = (::socklen_t) addr.capacity(); ::ssize_t nread; int err; do { nread = ::recvfrom(this->fd(), this->m_io_read_queue.mut_end(), datalen, 0, addr.mut_addr(), &addrlen); datalen = (size_t) nread; err = (nread < 0) ? errno : 0; } while(err == EINTR); if((err == EAGAIN) || (err == EWOULDBLOCK)) return io_result_would_block; else if(err != 0) POSEIDON_THROW(( "Error reading UDP socket", "[`recvfrom()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(err)); // Accept this packet. this->m_io_read_queue.accept(datalen); addr.set_size(addrlen); this->do_on_udp_packet(::std::move(addr), ::std::move(this->m_io_read_queue)); return io_result_partial; } IO_Result UDP_Socket:: do_abstract_socket_on_writable() { const recursive_mutex::unique_lock io_lock(this->m_io_mutex); if(this->m_io_write_queue.empty()) return io_result_partial; Socket_Address addr; ::socklen_t addrlen; size_t datalen; // Get a packet from the send queue. // This piece of code must match `udp_send()`. size_t ngot = this->m_io_write_queue.getn((char*) &addrlen, sizeof(addrlen)); ROCKET_ASSERT(ngot == sizeof(addrlen)); ngot = this->m_io_write_queue.getn((char*) &datalen, sizeof(datalen)); ROCKET_ASSERT(ngot == sizeof(datalen)); ngot = this->m_io_write_queue.getn((char*) addr.mut_data(), addrlen); ROCKET_ASSERT(ngot == (uint32_t) addrlen); ::ssize_t nwritten; int err; do { nwritten = ::sendto(this->fd(), this->m_io_write_queue.begin(), datalen, 0, addr.addr(), addrlen); err = (nwritten < 0) ? errno : 0; } while(err == EINTR); // Remove data from the send queue, no matter whether the operation has // succeeded or not. this->m_io_write_queue.discard(datalen); if((err == EAGAIN) || (err == EWOULDBLOCK)) return io_result_would_block; else if(err != 0) POSEIDON_THROW(( "Error writing UDP socket", "[`sendto()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(err)); // Report that some data have been written anyway. return io_result_partial; } void UDP_Socket:: do_abstract_socket_on_exception(exception& stdex) { POSEIDON_LOG_WARN(( "Ignoring exception: $3", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), stdex); } void UDP_Socket:: join_multicast_group(const Socket_Address& maddr, uint8_t ttl, bool loopback) { if(maddr.classify() != socket_address_class_multicast) POSEIDON_THROW(( "Invalid multicast address `$1`"), maddr); if(maddr.family() == AF_INET) { // IPv4 struct ::ip_mreqn mreq; mreq.imr_multiaddr = maddr.addr4()->sin_addr; mreq.imr_address.s_addr = INADDR_ANY; mreq.imr_ifindex = 0; if(::setsockopt(this->fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) != 0) POSEIDON_THROW(( "Failed to join multicast group `$4`", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(), maddr); int ival = ttl; if(::setsockopt(this->fd(), IPPROTO_IP, IP_MULTICAST_TTL, &ival, sizeof(ival)) != 0) POSEIDON_THROW(( "Failed to set TTL of multicast packets", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); ival = loopback; if(::setsockopt(this->fd(), IPPROTO_IP, IP_MULTICAST_LOOP, &ival, sizeof(ival)) != 0) POSEIDON_THROW(( "Failed to set loopback of multicast packets", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); } else if(maddr.family() == AF_INET6) { // IPv6 struct ::ipv6_mreq mreq; mreq.ipv6mr_multiaddr = maddr.addr6()->sin6_addr; mreq.ipv6mr_interface = 0; if(::setsockopt(this->fd(), IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) != 0) POSEIDON_THROW(( "Failed to join multicast group `$4`", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(), maddr); int ival = ttl; if(::setsockopt(this->fd(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ival, sizeof(ival)) != 0) POSEIDON_THROW(( "Failed to set TTL of multicast packets", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); ival = loopback; if(::setsockopt(this->fd(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &ival, sizeof(ival)) != 0) POSEIDON_THROW(( "Failed to set loopback of multicast packets", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); } else POSEIDON_THROW(( "Socket address family `$3` not supported", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), maddr.family()); } void UDP_Socket:: leave_multicast_group(const Socket_Address& maddr) { if(maddr.classify() != socket_address_class_multicast) POSEIDON_THROW(( "Invalid multicast address `$1`"), maddr); if(maddr.family() == AF_INET) { // IPv4 struct ::ip_mreqn mreq; mreq.imr_multiaddr = maddr.addr4()->sin_addr; mreq.imr_address.s_addr = INADDR_ANY; mreq.imr_ifindex = 0; if(::setsockopt(this->fd(), IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) != 0) POSEIDON_THROW(( "Failed to leave multicast group `$4`", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(), maddr); } else if(maddr.family() == AF_INET6) { // IPv6 struct ::ipv6_mreq mreq; mreq.ipv6mr_multiaddr = maddr.addr6()->sin6_addr; mreq.ipv6mr_interface = 0; if(::setsockopt(this->fd(), IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) != 0) POSEIDON_THROW(( "Failed to leave multicast group `$4`", "[`setsockopt()` failed: $3]", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(), maddr); } else POSEIDON_THROW(( "Socket address family `$3` not supported", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), maddr.family()); } bool UDP_Socket:: udp_send(const Socket_Address& addr, const char* data, size_t size) { if(size && !data) POSEIDON_THROW(( "Null data pointer", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this)); size_t datalen = size & 0xFFFFU; if(datalen != size) POSEIDON_THROW(( "`$3` bytes is too large for a UDP packet", "[UDP socket `$1` (class `$2`)]"), this, typeid(*this), size); // If this socket has been marked closed, fail immediately. if(this->socket_state() == socket_state_closed) return false; const recursive_mutex::unique_lock io_lock(this->m_io_mutex); // Encode this packet. // This piece of code must match `do_abstract_socket_on_writable()`. ::socklen_t addrlen = addr.ssize(); size_t queue_size = sizeof(addrlen) + sizeof(datalen) + (uint32_t) addrlen + datalen; this->m_io_write_queue.reserve(queue_size); ::memcpy(this->m_io_write_queue.mut_end(), &addrlen, sizeof(addrlen)); this->m_io_write_queue.accept(sizeof(addrlen)); ::memcpy(this->m_io_write_queue.mut_end(), &datalen, sizeof(datalen)); this->m_io_write_queue.accept(sizeof(datalen)); ::memcpy(this->m_io_write_queue.mut_end(), addr.data(), (uint32_t) addrlen); this->m_io_write_queue.accept((uint32_t) addrlen); ::memcpy(this->m_io_write_queue.mut_end(), data, datalen); this->m_io_write_queue.accept(datalen); // Try writing once. This is essential for the edge-triggered epoll to work // reliably, because the level-triggered epoll does not check for `EPOLLOUT` by // default. If the packet has been sent anyway, discard it from the send queue. this->do_abstract_socket_on_writable(); return true; } bool UDP_Socket:: udp_send(const Socket_Address& addr, const cow_string& data) { return this->udp_send(addr, data.data(), data.size()); } bool UDP_Socket:: udp_send(const Socket_Address& addr, const string& data) { return this->udp_send(addr, data.data(), data.size()); } } // namespace poseidon <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX グループ MTU 制御 @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #if defined(SIG_RX24T) #include "RX24T/mtu_io.hpp" #endif <commit_msg>update<commit_after>#pragma once //=====================================================================// /*! @file @brief RX グループ MTU3 制御 @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "common/renesas.hpp" /// F_PCKA は変換パラメーター計算で必要で、設定が無いとエラーにします。 #ifndef F_PCKA # error "mtu_io.hpp requires F_PCKA to be defined" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief MTU 制御クラス @param[in] MTU MTU ユニット @param[in] TASK 割り込みタスク */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class MTU, class TASK> class mtu_io { public: //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 機能タイプ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class functions : uint8_t { PWM, ///< PWM }; private: static TASK task_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// mtu_io() { } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] func 機能選択 @param[in] level 割り込みレベル */ //-----------------------------------------------------------------// bool start(functions func, uint8_t level) { power_cfg::turn(MTU::get_peripheral()); return true; } //-----------------------------------------------------------------// /*! @brief TASK クラスの参照 @return TASK クラス */ //-----------------------------------------------------------------// static TASK& at_task() { return task_; } }; template <class MTU, class TASK> TASK mtu_io<MTU, TASK>::task_; } <|endoftext|>
<commit_before>#include <vector> #include <cstring> #include <stdint.h> // uint32_t etc. // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #include <glm/gtc/matrix_transform.hpp> #include "shader.hpp" #include "texture.hpp" #include "text2D.hpp" GLuint Text2DTextureID; // Texture containing the font GLuint Text2DVertexBufferID; // Buffer containing the vertices GLuint Text2DUVBufferID; // UVs GLuint Text2DShaderID; // Program used to disaply the text GLuint vertexPosition_screenspaceID; // Location of the program's "vertexPosition_screenspace" attribute GLuint vertexUVID; // Location of the program's "vertexUV" attribute GLuint Text2DUniformID; // Location of the program's texture attribute GLuint screen_width_uniform_ID; // Location of the program's window width uniform. GLuint screen_height_uniform_ID; // Location of the program's window height uniform. namespace text2D { void initText2D( GLuint screen_width, GLuint screen_height, const char *texturePath, const char *char_font_texture_file_format) { // Initialize texture if ((strcmp(char_font_texture_file_format, "bmp") == 0) || (strcmp(char_font_texture_file_format, "BMP") == 0)) { Text2DTextureID = texture::load_BMP_texture(texturePath); } else if ((strcmp(char_font_texture_file_format, "dds") == 0) || (strcmp(char_font_texture_file_format, "DDS") == 0)) { Text2DTextureID = texture::load_DDS_texture(texturePath); } // Initialize VBO glGenBuffers(1, &Text2DVertexBufferID); glGenBuffers(1, &Text2DUVBufferID); // Initialize Shader Text2DShaderID = LoadShaders("TextVertexShader.vertexshader", "TextVertexShader.fragmentshader"); // Get a handle for our buffers vertexPosition_screenspaceID = glGetAttribLocation(Text2DShaderID, "vertexPosition_screenspace"); vertexUVID = glGetAttribLocation(Text2DShaderID, "vertexUV"); // Initialize uniforms' IDs Text2DUniformID = glGetUniformLocation(Text2DShaderID, "myTextureSampler"); // Initialize uniform window width. screen_width_uniform_ID = glGetUniformLocation(Text2DShaderID, "screen_width"); glUniform1i(screen_width_uniform_ID, screen_width); // Initialize uniform window height. screen_height_uniform_ID = glGetUniformLocation(Text2DShaderID, "screen_height"); glUniform1i(screen_height_uniform_ID, screen_height); } void printText2D( GLuint screen_width, GLuint screen_height, GLuint x, GLuint y, GLuint text_size, GLuint font_size, const char *text, const char *char_font_texture_file_format, const char *horizontal_alignment, const char *vertical_alignment) { uint32_t length = strlen(text); // Fill buffers std::vector<glm::vec2> vertices; std::vector<glm::vec2> UVs; for (uint32_t i = 0; i < length; i++) { // Print to the right side of X (so far there is no check for input length). // Print up of Y. GLfloat vertex_up_left_x; GLfloat vertex_up_left_y; GLfloat vertex_up_right_x; GLfloat vertex_up_right_y; GLfloat vertex_down_left_x; GLfloat vertex_down_left_y; GLfloat vertex_down_right_x; GLfloat vertex_down_right_y; if (strcmp(horizontal_alignment, "left") == 0) { vertex_up_left_x = vertex_down_left_x = x + (i * text_size); vertex_up_right_x = vertex_down_right_x = x + (i * text_size) + text_size; } else if (strcmp(horizontal_alignment, "right") == 0) { vertex_up_left_x = vertex_down_left_x = x - (length * text_size) + (i * text_size); vertex_up_right_x = vertex_down_right_x = x - (length * text_size) + (i * text_size + text_size); } else if (strcmp(horizontal_alignment, "center") == 0) { vertex_up_left_x = vertex_down_left_x = x - (0.5f * length * text_size) + (i * text_size); vertex_up_right_x = vertex_down_right_x = x - (0.5f * length * text_size) + (i * text_size + text_size); } if (strcmp(vertical_alignment, "bottom") == 0) { vertex_down_left_y = vertex_down_right_y = y; vertex_up_left_y = vertex_up_right_y = y + text_size; } else if (strcmp(vertical_alignment, "top") == 0) { vertex_down_left_y = vertex_down_right_y = y - text_size; vertex_up_left_y = vertex_up_right_y = y; } else if (strcmp(vertical_alignment, "center") == 0) { vertex_down_left_y = vertex_down_right_y = y - 0.5f * text_size; vertex_up_left_y = vertex_up_right_y = y + 0.5f * text_size; } glm::vec2 vertex_up_left = glm::vec2(vertex_up_left_x, vertex_up_left_y); glm::vec2 vertex_up_right = glm::vec2(vertex_up_right_x, vertex_up_right_y); glm::vec2 vertex_down_left = glm::vec2(vertex_down_left_x, vertex_down_left_y); glm::vec2 vertex_down_right = glm::vec2(vertex_down_right_x, vertex_down_right_y); vertices.push_back(vertex_up_left); vertices.push_back(vertex_down_left); vertices.push_back(vertex_up_right); vertices.push_back(vertex_down_right); vertices.push_back(vertex_up_right); vertices.push_back(vertex_down_left); char character = text[i]; float uv_x = (character % font_size) / (GLfloat) font_size; float uv_y; if ((strcmp(char_font_texture_file_format, "dds") == 0) || (strcmp(char_font_texture_file_format, "DDS") == 0)) { uv_y = (character / font_size) / (GLfloat) font_size; } else if ((strcmp(char_font_texture_file_format, "bmp") == 0) || (strcmp(char_font_texture_file_format, "BMP") == 0)) { // BMP is stored in the file beginning from the bottom line. uv_y = 1 - (character / font_size) / (GLfloat) font_size; } glm::vec2 uv_up_left = glm::vec2(uv_x , uv_y); glm::vec2 uv_up_right = glm::vec2(uv_x + (1.0f / (GLfloat) font_size), uv_y); glm::vec2 uv_down_right; glm::vec2 uv_down_left; if ((strcmp(char_font_texture_file_format, "dds") == 0) || (strcmp(char_font_texture_file_format, "DDS") == 0)) { uv_down_right = glm::vec2(uv_x + (1.0f / (GLfloat) font_size), (uv_y + 1.0f / (GLfloat) font_size)); uv_down_left = glm::vec2(uv_x , (uv_y + 1.0f / (GLfloat) font_size)); } else if ((strcmp(char_font_texture_file_format, "bmp") == 0) || (strcmp(char_font_texture_file_format, "BMP") == 0)) { // BMP is stored in the file beginning from the bottom line. uv_down_right = glm::vec2(uv_x + (1.0f / (GLfloat) font_size), (uv_y - 1.0f / (GLfloat) font_size)); uv_down_left = glm::vec2(uv_x , (uv_y - 1.0f / (GLfloat) font_size)); } UVs.push_back(uv_up_left); UVs.push_back(uv_down_left); UVs.push_back(uv_up_right); UVs.push_back(uv_down_right); UVs.push_back(uv_up_right); UVs.push_back(uv_down_left); } glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec2), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID); glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs[0], GL_STATIC_DRAW); // Bind shader glUseProgram(Text2DShaderID); // Bind texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Text2DTextureID); // Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(Text2DUniformID, 0); // Set screen width. glUniform1i(screen_width_uniform_ID, screen_width); // Set screen height. glUniform1i(screen_height_uniform_ID, screen_height); // 1rst attribute buffer : vertices glEnableVertexAttribArray(vertexPosition_screenspaceID); glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID); glVertexAttribPointer(vertexPosition_screenspaceID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0); // 2nd attribute buffer : UVs glEnableVertexAttribArray(vertexUVID); glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID); glVertexAttribPointer(vertexUVID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Draw call glDrawArrays(GL_TRIANGLES, 0, vertices.size()); glDisable(GL_BLEND); glDisableVertexAttribArray(vertexPosition_screenspaceID); glDisableVertexAttribArray(vertexUVID); } void printText2D(PrintingStruct printing_struct) { printText2D( printing_struct.screen_width, printing_struct.screen_height, printing_struct.x, printing_struct.y, printing_struct.text_size, printing_struct.font_size, printing_struct.text, printing_struct.char_font_texture_file_format, printing_struct.horizontal_alignment, printing_struct.vertical_alignment); } void printText2D( GLuint screen_width, GLuint screen_height, GLuint x, GLuint y, GLuint text_size, GLuint font_size, const char *text, const char *char_font_texture_file_format) { printText2D(screen_width, screen_height, x, y, text_size, font_size, text, char_font_texture_file_format, "left", "bottom"); } void cleanupText2D() { // Delete buffers glDeleteBuffers(1, &Text2DVertexBufferID); glDeleteBuffers(1, &Text2DUVBufferID); // Delete texture glDeleteTextures(1, &Text2DTextureID); // Delete shader glDeleteProgram(Text2DShaderID); } } <commit_msg>Muokattu kommentteja.<commit_after>#include <vector> #include <cstring> #include <stdint.h> // uint32_t etc. // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #include <glm/gtc/matrix_transform.hpp> #include "shader.hpp" #include "texture.hpp" #include "text2D.hpp" GLuint Text2DTextureID; // Texture containing the font GLuint Text2DVertexBufferID; // Buffer containing the vertices GLuint Text2DUVBufferID; // Buffer containing the UVs GLuint Text2DShaderID; // Shader program used to display the text GLuint vertexPosition_screenspaceID; // Location of the program's "vertexPosition_screenspace" attribute GLuint vertexUVID; // Location of the program's "vertexUV" attribute GLuint Text2DUniformID; // Location of the program's texture attribute GLuint screen_width_uniform_ID; // Location of the program's window width uniform. GLuint screen_height_uniform_ID; // Location of the program's window height uniform. namespace text2D { void initText2D( GLuint screen_width, GLuint screen_height, const char *texturePath, const char *char_font_texture_file_format) { // Initialize texture if ((strcmp(char_font_texture_file_format, "bmp") == 0) || (strcmp(char_font_texture_file_format, "BMP") == 0)) { Text2DTextureID = texture::load_BMP_texture(texturePath); } else if ((strcmp(char_font_texture_file_format, "dds") == 0) || (strcmp(char_font_texture_file_format, "DDS") == 0)) { Text2DTextureID = texture::load_DDS_texture(texturePath); } // Initialize VBO glGenBuffers(1, &Text2DVertexBufferID); glGenBuffers(1, &Text2DUVBufferID); // Initialize Shader Text2DShaderID = LoadShaders("TextVertexShader.vertexshader", "TextVertexShader.fragmentshader"); // Get a handle for our buffers vertexPosition_screenspaceID = glGetAttribLocation(Text2DShaderID, "vertexPosition_screenspace"); vertexUVID = glGetAttribLocation(Text2DShaderID, "vertexUV"); // Initialize uniforms' IDs Text2DUniformID = glGetUniformLocation(Text2DShaderID, "myTextureSampler"); // Initialize uniform window width. screen_width_uniform_ID = glGetUniformLocation(Text2DShaderID, "screen_width"); glUniform1i(screen_width_uniform_ID, screen_width); // Initialize uniform window height. screen_height_uniform_ID = glGetUniformLocation(Text2DShaderID, "screen_height"); glUniform1i(screen_height_uniform_ID, screen_height); } void printText2D( GLuint screen_width, GLuint screen_height, GLuint x, GLuint y, GLuint text_size, GLuint font_size, const char *text, const char *char_font_texture_file_format, const char *horizontal_alignment, const char *vertical_alignment) { uint32_t length = strlen(text); // Fill buffers std::vector<glm::vec2> vertices; std::vector<glm::vec2> UVs; for (uint32_t i = 0; i < length; i++) { // Print to the right side of X (so far there is no check for input length). // Print up of Y. GLfloat vertex_up_left_x; GLfloat vertex_up_left_y; GLfloat vertex_up_right_x; GLfloat vertex_up_right_y; GLfloat vertex_down_left_x; GLfloat vertex_down_left_y; GLfloat vertex_down_right_x; GLfloat vertex_down_right_y; if (strcmp(horizontal_alignment, "left") == 0) { vertex_up_left_x = vertex_down_left_x = x + (i * text_size); vertex_up_right_x = vertex_down_right_x = x + (i * text_size) + text_size; } else if (strcmp(horizontal_alignment, "right") == 0) { vertex_up_left_x = vertex_down_left_x = x - (length * text_size) + (i * text_size); vertex_up_right_x = vertex_down_right_x = x - (length * text_size) + (i * text_size + text_size); } else if (strcmp(horizontal_alignment, "center") == 0) { vertex_up_left_x = vertex_down_left_x = x - (0.5f * length * text_size) + (i * text_size); vertex_up_right_x = vertex_down_right_x = x - (0.5f * length * text_size) + (i * text_size + text_size); } if (strcmp(vertical_alignment, "bottom") == 0) { vertex_down_left_y = vertex_down_right_y = y; vertex_up_left_y = vertex_up_right_y = y + text_size; } else if (strcmp(vertical_alignment, "top") == 0) { vertex_down_left_y = vertex_down_right_y = y - text_size; vertex_up_left_y = vertex_up_right_y = y; } else if (strcmp(vertical_alignment, "center") == 0) { vertex_down_left_y = vertex_down_right_y = y - 0.5f * text_size; vertex_up_left_y = vertex_up_right_y = y + 0.5f * text_size; } glm::vec2 vertex_up_left = glm::vec2(vertex_up_left_x, vertex_up_left_y); glm::vec2 vertex_up_right = glm::vec2(vertex_up_right_x, vertex_up_right_y); glm::vec2 vertex_down_left = glm::vec2(vertex_down_left_x, vertex_down_left_y); glm::vec2 vertex_down_right = glm::vec2(vertex_down_right_x, vertex_down_right_y); vertices.push_back(vertex_up_left); vertices.push_back(vertex_down_left); vertices.push_back(vertex_up_right); vertices.push_back(vertex_down_right); vertices.push_back(vertex_up_right); vertices.push_back(vertex_down_left); char character = text[i]; float uv_x = (character % font_size) / (GLfloat) font_size; float uv_y; if ((strcmp(char_font_texture_file_format, "dds") == 0) || (strcmp(char_font_texture_file_format, "DDS") == 0)) { uv_y = (character / font_size) / (GLfloat) font_size; } else if ((strcmp(char_font_texture_file_format, "bmp") == 0) || (strcmp(char_font_texture_file_format, "BMP") == 0)) { // BMP is stored in the file beginning from the bottom line. uv_y = 1 - (character / font_size) / (GLfloat) font_size; } glm::vec2 uv_up_left = glm::vec2(uv_x , uv_y); glm::vec2 uv_up_right = glm::vec2(uv_x + (1.0f / (GLfloat) font_size), uv_y); glm::vec2 uv_down_right; glm::vec2 uv_down_left; if ((strcmp(char_font_texture_file_format, "dds") == 0) || (strcmp(char_font_texture_file_format, "DDS") == 0)) { uv_down_right = glm::vec2(uv_x + (1.0f / (GLfloat) font_size), (uv_y + 1.0f / (GLfloat) font_size)); uv_down_left = glm::vec2(uv_x , (uv_y + 1.0f / (GLfloat) font_size)); } else if ((strcmp(char_font_texture_file_format, "bmp") == 0) || (strcmp(char_font_texture_file_format, "BMP") == 0)) { // BMP is stored in the file beginning from the bottom line. uv_down_right = glm::vec2(uv_x + (1.0f / (GLfloat) font_size), (uv_y - 1.0f / (GLfloat) font_size)); uv_down_left = glm::vec2(uv_x , (uv_y - 1.0f / (GLfloat) font_size)); } UVs.push_back(uv_up_left); UVs.push_back(uv_down_left); UVs.push_back(uv_up_right); UVs.push_back(uv_down_right); UVs.push_back(uv_up_right); UVs.push_back(uv_down_left); } glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec2), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID); glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs[0], GL_STATIC_DRAW); // Bind shader glUseProgram(Text2DShaderID); // Bind texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Text2DTextureID); // Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(Text2DUniformID, 0); // Set screen width. glUniform1i(screen_width_uniform_ID, screen_width); // Set screen height. glUniform1i(screen_height_uniform_ID, screen_height); // 1rst attribute buffer : vertices glEnableVertexAttribArray(vertexPosition_screenspaceID); glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID); glVertexAttribPointer(vertexPosition_screenspaceID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0); // 2nd attribute buffer : UVs glEnableVertexAttribArray(vertexUVID); glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID); glVertexAttribPointer(vertexUVID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Draw call glDrawArrays(GL_TRIANGLES, 0, vertices.size()); glDisable(GL_BLEND); glDisableVertexAttribArray(vertexPosition_screenspaceID); glDisableVertexAttribArray(vertexUVID); } void printText2D(PrintingStruct printing_struct) { printText2D( printing_struct.screen_width, printing_struct.screen_height, printing_struct.x, printing_struct.y, printing_struct.text_size, printing_struct.font_size, printing_struct.text, printing_struct.char_font_texture_file_format, printing_struct.horizontal_alignment, printing_struct.vertical_alignment); } void printText2D( GLuint screen_width, GLuint screen_height, GLuint x, GLuint y, GLuint text_size, GLuint font_size, const char *text, const char *char_font_texture_file_format) { printText2D(screen_width, screen_height, x, y, text_size, font_size, text, char_font_texture_file_format, "left", "bottom"); } void cleanupText2D() { // Delete buffers glDeleteBuffers(1, &Text2DVertexBufferID); glDeleteBuffers(1, &Text2DUVBufferID); // Delete texture glDeleteTextures(1, &Text2DTextureID); // Delete shader glDeleteProgram(Text2DShaderID); } } <|endoftext|>
<commit_before>/*! \mainpage The QtSparql library \brief <center>unstable</center> \section Introduction <b>Description</b> QtSparql is a client-side library for accessing RDF stores. The query language for RDF stores is <a href="http://www.w3.org/TR/rdf-sparql-query/">SPARQL</a>. QtSparql takes in SPARQL queries, forwards them to the selected backend, and gives back the results of the query. It can return the results asynchronously if the backend supports asynchronous operations. QtSparql can connect to different backends. Currently the following backends exist: - QTRACKER for accessing <a href="http://projects.gnome.org/tracker/">Tracker</a> over D-Bus - QTRACKER_DIRECT for accessing <a href="http://projects.gnome.org/tracker/">Tracker</a> via direct database access and D-Bus - QSPARQL_ENDPOINT for accessing online RDF stores, e.g., <a href="http://dbpedia.org">DBpedia</a> - QVIRTUOSO backend for accessing <a href="http://docs.openlinksw.com/virtuoso/">Virtuoso</a> <b>List of classes QtSparql API provides:</b> <p><table width="100%"> <tr valign="top" bgcolor="#ffffff"><td><i>Class</i></td><td><i>Description</i></td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlConnection</b></td> <td>Interface for accessing an RDF store.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlConnectionOptions</b></td> <td>Encapsulates options given to QSparqlConnection. Some options are used only by some drivers.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlError</b></td><td>SPARQL error information.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlBinding</b></td><td>Handles a binding between a SPARQL query variable name and the value of the RDF node.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlQuery</b></td><td>Means of executing and manipulating SPARQL statements.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlQueryModel</b></td><td>Read-only data model for SPARQL result sets.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlResultRow</b></td><td>Encapsulates a row in the results of a query.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlResult</b></td><td>Abstract interface for accessing the results of an executed QSparqlQuery.</td></tr> </table></p> \attention The QtSparql library is not yet stable; we make no promises about API / ABI compatibility! \section gettingstarted Getting started The following code snippets demonstrate how to retrieve data from a RDF database using QtSparql. - Create a QSparqlConnection object specifiying the backend you want to use. If necessary, specify the parameters by using QSparqlConnectionOptions and passing it to QSparqlConnection. E.g. to use tracker: \dontinclude simple/main.cpp \skipline QSparqlConnection E.g. to use DBpedia: \dontinclude dbpedia/main.cpp \skip QSparqlConnectionOptions \until QSPARQL_ENDPOINT - Construct a QSparqlQuery with the SPARQL query string. Specify the query type, if needed. E.g. \dontinclude simple/main.cpp \skipline QSparqlQuery or \dontinclude iteration/main.cpp \skip QSparqlQuery insert \until InsertStatement - Use QSparqlConnection::exec() to execute the query. It returns a pointer to QSparqlResult. E.g. \dontinclude simple/main.cpp \skipline QSparqlResult - You can then connect to the QSparqlResult::finished() and QSparqlResult::dataReady signals. - The QSparqlResult can be iterated over by using the following functions: QSparqlResult::first(), QSparqlResult::last(), QSparqlResult::next(), QSparqlResult::previous(), QSparqlResult::setPos(). The caller is responsible for deleting the QSparqlResult. E.g. \dontinclude simple/main.cpp \skip result->next \until toString - Data can be retrieved by using QSparqlResult::value(). The following classes are the most relevant for getting started with QSparql: - QSparqlConnection - QSparqlQuery - QSparqlResult - QSparqlQueryModel \section querymodels Query models The QSparqlQueryModel class provides a convienient, read-only, data model for SPARQL results which can be used to provide data to view classes such as QTableView. After creating the model, use QSparqlQueryModel::setQuery() to set the query for the connection, header data for the model can also be set using QSparqlQueryModel::setHeaderData(). E.g. \dontinclude querymodel/main.cpp \skip model; \until setHeaderData You can then use this in an a view class by using it's setModel() function. E.g. \dontinclude querymodel/main.cpp \skip *view \until model \section connectionoptions Connection options supported by drivers QTRACKER driver supports the following connection options: - custom: "batch" (bool), use BatchUpdate when writing data to Tracker. BatchUpdate will schedule the data to be written at a suitable moment, so it is not necessarity written when the query is finished. QTRACKER_DIRECT driver supports the following connection options: - dataReadyInterval (int, default 1), controls the interval for emitting the dataReady signal. - maxThread (int), sets the maximum number of threads for the thread pool to use. If not set a default of number of cores * 2 will be used. - threadExpiry (int, default 2000), controls the expiry time (in milliseconds) of the threads created by the thread pool. QENDPOINT driver supports the following connection options: - hostName (QString) - path (QString) - port (int) - userName (QString) - password (QString) - networkAccessManager (QNetworkAccessManager*) - proxy (const QNetworkProxy&) - custom: "timeout" (int) (for virtuoso endpoints) - custom: "maxrows" (int) (for virtuoso endpoints) QVIRTUOSO driver supports the following connection options: - hostName (QString) - port (int) - userName (QString) - password (QString) - databaseName (QString) For setting custom options, use QSparqlConnectionOptions::setOption() and give the option name as a string, followed by the value. Other options can be set using QSparqlConnectionOptions::setOption(), however it is preferable to use the convinence functions in QSparqlConnectionOptions, as these provide additional error checking. \section connectionfeatures Connection features The following table describes the features supported by each driver. The features can be queried with QSparqlConnection::hasFeature(). <table> <tr> <td></td> <th>QuerySize</th> <th>DefaultGraph</th> <th>AskQueries</th> <th>ConstructQueries</th> <th>UpdateQueries</th> <th>SyncExec</th> <th>AsyncExec</th> </tr> <tr> <th>QTRACKER</th> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> <td>No</td> <td>Yes</td> </tr> <tr> <th>QTRACKER_DIRECT</th> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> <td>Yes</td> <td>No</td> </tr> <tr> <th>QSPARQL_ENDPOINT</th> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> </tr> <tr> <th>QVIRTUOSO</th> <td>Yes</td> <td>No</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No (*)</td> <td>No</td> </tr> </table> (*) The QVIRTUOSO driver is natively synchronous, but support for syncExec directly is not currently implemented. \section backendspecific Accessing backend-specific functionalities QtSparql doesn't offer backend-specific functionalities. For that purpose, there are separate add-on libraries, e.g., libqtsparql-tracker-extensions. */ <commit_msg>minor fixes<commit_after>/*! \mainpage The QtSparql library \brief <center>unstable</center> \section Introduction <b>Description</b> QtSparql is a client-side library for accessing RDF stores. The query language for RDF stores is <a href="http://www.w3.org/TR/rdf-sparql-query/">SPARQL</a>. QtSparql takes in SPARQL queries, forwards them to the selected backend, and gives back the results of the query. It can return the results asynchronously if the backend supports asynchronous operations. QtSparql can connect to different backends. Currently the following backends exist: - QTRACKER for accessing <a href="http://projects.gnome.org/tracker/">Tracker</a> over D-Bus - QTRACKER_DIRECT for accessing <a href="http://projects.gnome.org/tracker/">Tracker</a> via direct database access and D-Bus - QSPARQL_ENDPOINT for accessing online RDF stores, e.g., <a href="http://dbpedia.org">DBpedia</a> - QVIRTUOSO backend for accessing <a href="http://docs.openlinksw.com/virtuoso/">Virtuoso</a> <b>List of classes QtSparql API provides:</b> <p><table width="100%"> <tr valign="top" bgcolor="#ffffff"><td><i>Class</i></td><td><i>Description</i></td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlConnection</b></td> <td>Interface for accessing an RDF store.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlConnectionOptions</b></td> <td>Encapsulates options given to QSparqlConnection. Some options are used only by some drivers.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlError</b></td><td>SPARQL error information.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlBinding</b></td><td>Handles a binding between a SPARQL query variable name and the value of the RDF node.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlQuery</b></td><td>Means of executing and manipulating SPARQL statements.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlQueryModel</b></td><td>Read-only data model for SPARQL result sets.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlResultRow</b></td><td>Encapsulates a row in the results of a query.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlResult</b></td><td>Abstract interface for accessing the results of an executed QSparqlQuery.</td></tr> </table></p> \attention The QtSparql library is not yet stable; we make no promises about API / ABI compatibility! \section gettingstarted Getting started The following code snippets demonstrate how to retrieve data from a RDF database using QtSparql. - Create a QSparqlConnection object specifiying the backend you want to use. If necessary, specify the parameters by using QSparqlConnectionOptions and passing it to QSparqlConnection. E.g. to use tracker: \dontinclude simple/main.cpp \skipline QSparqlConnection E.g. to use DBpedia: \dontinclude dbpedia/main.cpp \skip QSparqlConnectionOptions \until QSPARQL_ENDPOINT - Construct a QSparqlQuery with the SPARQL query string. Specify the query type, if needed. E.g. \dontinclude simple/main.cpp \skipline QSparqlQuery or \dontinclude iteration/main.cpp \skip QSparqlQuery insert \until InsertStatement - Use QSparqlConnection::exec() to execute the query. It returns a pointer to QSparqlResult. E.g. \dontinclude simple/main.cpp \skipline QSparqlResult - You can then connect to the QSparqlResult::finished() and QSparqlResult::dataReady signals. - The QSparqlResult can be iterated over by using the following functions: QSparqlResult::first(), QSparqlResult::last(), QSparqlResult::next(), QSparqlResult::previous(), QSparqlResult::setPos(). The caller is responsible for deleting the QSparqlResult. E.g. \dontinclude simple/main.cpp \skip result->next \until toString - Data can be retrieved by using QSparqlResult::value(). The following classes are the most relevant for getting started with QSparql: - QSparqlConnection - QSparqlQuery - QSparqlResult - QSparqlQueryModel \section querymodels Query models The QSparqlQueryModel class provides a convienient, read-only, data model for SPARQL results which can be used to provide data to view classes such as QTableView. After creating the model, use QSparqlQueryModel::setQuery() to set the query for the connection, header data for the model can also be set using QSparqlQueryModel::setHeaderData(). E.g. \dontinclude querymodel/main.cpp \skip model; \until setHeaderData You can then use this in an a view class by using it's setModel() function. E.g. \dontinclude querymodel/main.cpp \skip *view \until model It is also easy to implement custom query models by reimplementing QSparqlQueryModel::data(), see the querymodel example for an example of this. \section connectionoptions Connection options supported by drivers QTRACKER driver supports the following connection options: - custom: "batch" (bool), use BatchUpdate when writing data to Tracker. BatchUpdate will schedule the data to be written at a suitable moment, so it is not necessarity written when the query is finished. QTRACKER_DIRECT driver supports the following connection options: - dataReadyInterval (int, default 1), controls the interval for emitting the dataReady signal. - maxThread (int), sets the maximum number of threads for the thread pool to use. If not set a default of number of cores * 2 will be used. - threadExpiry (int, default 2000), controls the expiry time (in milliseconds) of the threads created by the thread pool. QENDPOINT driver supports the following connection options: - hostName (QString) - path (QString) - port (int) - userName (QString) - password (QString) - networkAccessManager (QNetworkAccessManager*) - proxy (const QNetworkProxy&) - custom: "timeout" (int) (for virtuoso endpoints) - custom: "maxrows" (int) (for virtuoso endpoints) QVIRTUOSO driver supports the following connection options: - hostName (QString) - port (int) - userName (QString) - password (QString) - databaseName (QString) For setting custom options, use QSparqlConnectionOptions::setOption() and give the option name as a string, followed by the value. Other options can be set using QSparqlConnectionOptions::setOption(), however it is preferable to use the convinence functions in QSparqlConnectionOptions, as these provide additional error checking. \section connectionfeatures Connection features The following table describes the features supported by each driver. The features can be queried with QSparqlConnection::hasFeature(). <table> <tr> <td></td> <th>QuerySize</th> <th>DefaultGraph</th> <th>AskQueries</th> <th>ConstructQueries</th> <th>UpdateQueries</th> <th>SyncExec</th> <th>AsyncExec</th> </tr> <tr> <th>QTRACKER</th> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> <td>No</td> <td>Yes</td> </tr> <tr> <th>QTRACKER_DIRECT</th> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> <td>Yes</td> <td>No</td> </tr> <tr> <th>QSPARQL_ENDPOINT</th> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> </tr> <tr> <th>QVIRTUOSO</th> <td>Yes</td> <td>No</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No (*)</td> <td>No</td> </tr> </table> (*) The QVIRTUOSO driver is natively synchronous, but support for syncExec directly is not currently implemented. \section backendspecific Accessing backend-specific functionalities QtSparql doesn't offer backend-specific functionalities. For that purpose, there are separate add-on libraries, e.g., libqtsparql-tracker-extensions. */ <|endoftext|>
<commit_before> /************************************************** * Source Code for the Original Compiler for the * Programming Language Wake * * EarlyBailoutMethodInvecation.cpp * * Licensed under the MIT license * See LICENSE.TXT for details * * Author: Michael Fairhurst * Revised By: * **************************************************/ #include "ast/EarlyBailoutMethodInvocation.h" #include "TypeError.h" using namespace wake; PureType<QUALIFIED>* ast::EarlyBailoutMethodInvocation::typeCheck(bool forceArrayIdentifier) { PureType<QUALIFIED> subject = *auto_ptr<PureType<QUALIFIED> >(subjectExpr->typeCheck(false)); if(subject.type == TYPE_MATCHALL) { return new PureType<QUALIFIED>(subject); } else if(subject.type != TYPE_OPTIONAL) { errors->addError(new SemanticError(OPTIONAL_USE_OF_NONOPTIONAL_TYPE, "using .? on a nonoptional", node)); return new PureType<QUALIFIED>(TYPE_MATCHALL); } else { PureType<QUALIFIED>* ret = new PureType<QUALIFIED>(TYPE_OPTIONAL); PureType<QUALIFIED>* nonoptional = subject.typedata.optional.contained; while(nonoptional->type == TYPE_OPTIONAL) { nonoptional = nonoptional->typedata.optional.contained; } ret->typedata.optional.contained = typeCheckMethodInvocation(*nonoptional); return ret; } } <commit_msg>Add type hint for java codegen<commit_after> /************************************************** * Source Code for the Original Compiler for the * Programming Language Wake * * EarlyBailoutMethodInvecation.cpp * * Licensed under the MIT license * See LICENSE.TXT for details * * Author: Michael Fairhurst * Revised By: * **************************************************/ #include "ast/EarlyBailoutMethodInvocation.h" #include "TypeError.h" using namespace wake; PureType<QUALIFIED>* ast::EarlyBailoutMethodInvocation::typeCheck(bool forceArrayIdentifier) { PureType<QUALIFIED> subject = *auto_ptr<PureType<QUALIFIED> >(subjectExpr->typeCheck(false)); addSubNode(node, makeNodeFromPureType((PureType<UNQUALIFIED>*) new PureType<QUALIFIED>(subject), node->loc)); if(subject.type == TYPE_MATCHALL) { return new PureType<QUALIFIED>(subject); } else if(subject.type != TYPE_OPTIONAL) { errors->addError(new SemanticError(OPTIONAL_USE_OF_NONOPTIONAL_TYPE, "using .? on a nonoptional", node)); return new PureType<QUALIFIED>(TYPE_MATCHALL); } else { PureType<QUALIFIED>* ret = new PureType<QUALIFIED>(TYPE_OPTIONAL); PureType<QUALIFIED>* nonoptional = subject.typedata.optional.contained; while(nonoptional->type == TYPE_OPTIONAL) { nonoptional = nonoptional->typedata.optional.contained; } ret->typedata.optional.contained = typeCheckMethodInvocation(*nonoptional); return ret; } } <|endoftext|>
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or [email protected]. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or [email protected]. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "condor_common.h" #include "condor_debug.h" static char *_FileName_ = __FILE__; static struct hostent *host_ptr = NULL; static char hostname[MAXHOSTNAMELEN]; static char full_hostname[MAXHOSTNAMELEN]; static unsigned int ip_addr; static int hostnames_initialized = 0; static void init_hostnames(); // Return our hostname in a static data buffer. char * my_hostname() { if( ! hostnames_initialized ) { init_hostnames(); } return hostname; } // Return our full hostname (with domain) in a static data buffer. char* my_full_hostname() { if( ! hostnames_initialized ) { init_hostnames(); } return full_hostname; } // Return the host-ordered, unsigned int version of our hostname. unsigned int my_ip_addr() { if( ! hostnames_initialized ) { init_hostnames(); } return ip_addr; } void init_hostnames() { char* tmp; // Get our local hostname, and strip off the domain if // gethostname returns it. if( gethostname(hostname, sizeof(hostname)) == 0 ) { tmp = strchr( hostname, '.' ); if( tmp ) { *tmp = '\0'; } } else { EXCEPT( "gethostname failed, errno = %d", errno ); } // Look up our official host information if( (host_ptr = gethostbyname(hostname)) == NULL ) { EXCEPT( "gethostbyname(%s) failed, errno = %d", hostname, errno ); } // Grab our ip_addr and fully qualified hostname memcpy( &ip_addr, host_ptr->h_addr, (size_t)host_ptr->h_length ); ip_addr = ntohl( ip_addr ); strcpy( full_hostname, host_ptr->h_name ); hostnames_initialized = TRUE; } <commit_msg>print out errno correctly on Win32<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or [email protected]. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or [email protected]. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "condor_common.h" #include "condor_debug.h" static char *_FileName_ = __FILE__; static struct hostent *host_ptr = NULL; static char hostname[MAXHOSTNAMELEN]; static char full_hostname[MAXHOSTNAMELEN]; static unsigned int ip_addr; static int hostnames_initialized = 0; static void init_hostnames(); // Return our hostname in a static data buffer. char * my_hostname() { if( ! hostnames_initialized ) { init_hostnames(); } return hostname; } // Return our full hostname (with domain) in a static data buffer. char* my_full_hostname() { if( ! hostnames_initialized ) { init_hostnames(); } return full_hostname; } // Return the host-ordered, unsigned int version of our hostname. unsigned int my_ip_addr() { if( ! hostnames_initialized ) { init_hostnames(); } return ip_addr; } void init_hostnames() { char* tmp; // Get our local hostname, and strip off the domain if // gethostname returns it. if( gethostname(hostname, sizeof(hostname)) == 0 ) { tmp = strchr( hostname, '.' ); if( tmp ) { *tmp = '\0'; } } else { EXCEPT( "gethostname failed, errno = %d", #ifndef WIN32 errno ); #else WSAGetLastError() ); #endif } // Look up our official host information if( (host_ptr = gethostbyname(hostname)) == NULL ) { EXCEPT( "gethostbyname(%s) failed, errno = %d", hostname, errno ); } // Grab our ip_addr and fully qualified hostname memcpy( &ip_addr, host_ptr->h_addr, (size_t)host_ptr->h_length ); ip_addr = ntohl( ip_addr ); strcpy( full_hostname, host_ptr->h_name ); hostnames_initialized = TRUE; } <|endoftext|>
<commit_before>#include "hibike_message.h" uint8_t checksum(uint8_t data[], int length) { uint8_t chk = data[0]; for (int i=1; i<length; i++) { chk ^= data[i]; } return chk; } int send_message(message_t *msg) { uint8_t data[msg->payload_length+ MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES+CHECKSUM_BYTES]; message_to_byte(data, msg); data[msg->payload_length+MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES] = checksum(data, msg->payload_length+MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES); uint8_t written = Serial.write(data, msg->payload_length+ MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES+CHECKSUM_BYTES); if (written != msg->payload_length+ MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES+CHECKSUM_BYTES) { return -1; } return 0; } // Returns 0 on success, -1 on error (ex. no message) // If checksum does not match, empties the incoming buffer. int read_message(message_t *msg) { if (!Serial.available()) { return -1; } uint8_t data[MAX_PAYLOAD_SIZE+MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES]; Serial.readBytes((char*) data, MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES); uint8_t length = data[MESSAGEID_BYTES]; Serial.readBytes((char*) data+MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES, length); uint8_t chk = checksum(data, length+ MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES+CHECKSUM_BYTES); int expected_chk_ind = MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES+length; Serial.readBytes((char*) data+expected_chk_ind, 1); if (chk != data[expected_chk_ind]) { // Empty incoming buffer while (Serial.available() > 0) { Serial.read(); } return -1; } msg->messageID = data[0]; msg->payload_length = data[MESSAGEID_BYTES]; for (int i = 0; i < length; i++){ msg->payload[i] = data[i+MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES]; } return 0; } void message_to_byte(uint8_t *data, message_t *msg) { data[0] = msg->messageID; data[1] = msg->payload_length; for (int i = 0; i < msg->payload_length; i++){ data[i+MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES] = msg->payload[i]; } } <commit_msg>fix merge conflict<commit_after>#include "hibike_message.h" uint8_t checksum(uint8_t data[], int length) { uint8_t chk = data[0]; for (int i=1; i<length; i++) { chk ^= data[i]; } return chk; } int send_message(message_t *msg) { uint8_t data[msg->payload_length+ MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES+CHECKSUM_BYTES]; message_to_byte(data, msg); data[msg->payload_length+MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES] = checksum(data, msg->payload_length+MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES); uint8_t written = Serial.write(data, msg->payload_length+ MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES+CHECKSUM_BYTES); if (written != msg->payload_length+ MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES+CHECKSUM_BYTES) { return -1; } return 0; } // Returns 0 on success, -1 on error (ex. no message) // If checksum does not match, empties the incoming buffer. int read_message(message_t *msg) { if (!Serial.available()) { return -1; } uint8_t data[MAX_PAYLOAD_SIZE+MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES]; Serial.readBytes((char*) data, MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES); uint8_t length = data[MESSAGEID_BYTES]; Serial.readBytes((char*) data+MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES, length); uint8_t chk = checksum(data, length+ MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES); int expected_chk_ind = MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES+length; Serial.readBytes((char*) data+expected_chk_ind, 1); if (chk != data[expected_chk_ind]) { // Empty incoming buffer while (Serial.available() > 0) { Serial.read(); } return -1; } msg->messageID = data[0]; msg->payload_length = data[MESSAGEID_BYTES]; for (int i = 0; i < length; i++){ msg->payload[i] = data[i+MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES]; } return 0; } void message_to_byte(uint8_t *data, message_t *msg) { data[0] = msg->messageID; data[1] = msg->payload_length; for (int i = 0; i < msg->payload_length; i++){ data[i+MESSAGEID_BYTES+PAYLOAD_SIZE_BYTES] = msg->payload[i]; } } <|endoftext|>
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/application/common/manifest_handlers/csp_handler.h" #include "xwalk/application/common/application_manifest_constants.h" #include "testing/gtest/include/gtest/gtest.h" namespace xwalk { namespace keys = application_manifest_keys; namespace application { class CSPHandlerTest: public testing::Test { public: virtual void SetUp() OVERRIDE { manifest.SetString(keys::kNameKey, "no name"); manifest.SetString(keys::kVersionKey, "0"); } scoped_refptr<ApplicationData> CreateApplication() { std::string error; scoped_refptr<ApplicationData> application = ApplicationData::Create( base::FilePath(), Manifest::INVALID_TYPE, manifest, "", &error); return application; } const CSPInfo* GetCSPInfo( scoped_refptr<ApplicationData> application) { const CSPInfo* info = static_cast<CSPInfo*>( application->GetManifestData(keys::kCSPKey)); DCHECK(info); return info; } base::DictionaryValue manifest; }; TEST_F(CSPHandlerTest, NoCSP) { scoped_refptr<ApplicationData> application = CreateApplication(); EXPECT_TRUE(application.get()); EXPECT_EQ(GetCSPInfo(application)->GetDirectives().size(), 2); } TEST_F(CSPHandlerTest, EmptyCSP) { manifest.SetString(keys::kCSPKey, ""); scoped_refptr<ApplicationData> application = CreateApplication(); EXPECT_TRUE(application.get()); EXPECT_EQ(GetCSPInfo(application)->GetDirectives().size(), 0); } TEST_F(CSPHandlerTest, CSP) { manifest.SetString(keys::kCSPKey, "default-src 'self' "); scoped_refptr<ApplicationData> application = CreateApplication(); EXPECT_TRUE(application.get()); const std::map<std::string, std::vector<std::string> >& policies = GetCSPInfo(application)->GetDirectives(); EXPECT_EQ(policies.size(), 1); std::map<std::string, std::vector<std::string> >::const_iterator it = policies.find("default-src"); ASSERT_NE(it, policies.end()); EXPECT_EQ(it->second.size(), 1); EXPECT_STREQ((it->second)[0].c_str(), "'self'"); } } // namespace application } // namespace xwalk <commit_msg>Disable NoCSP unit test<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/application/common/manifest_handlers/csp_handler.h" #include "xwalk/application/common/application_manifest_constants.h" #include "testing/gtest/include/gtest/gtest.h" namespace xwalk { namespace keys = application_manifest_keys; namespace application { class CSPHandlerTest: public testing::Test { public: virtual void SetUp() OVERRIDE { manifest.SetString(keys::kNameKey, "no name"); manifest.SetString(keys::kVersionKey, "0"); } scoped_refptr<ApplicationData> CreateApplication() { std::string error; scoped_refptr<ApplicationData> application = ApplicationData::Create( base::FilePath(), Manifest::INVALID_TYPE, manifest, "", &error); return application; } const CSPInfo* GetCSPInfo( scoped_refptr<ApplicationData> application) { const CSPInfo* info = static_cast<CSPInfo*>( application->GetManifestData(keys::kCSPKey)); DCHECK(info); return info; } base::DictionaryValue manifest; }; // FIXME: the default CSP policy settings in CSP manifest handler // are temporally removed, since they had affected some tests and legacy apps. TEST_F(CSPHandlerTest, DISABLED_NoCSP) { scoped_refptr<ApplicationData> application = CreateApplication(); EXPECT_TRUE(application.get()); EXPECT_EQ(GetCSPInfo(application)->GetDirectives().size(), 2); } TEST_F(CSPHandlerTest, EmptyCSP) { manifest.SetString(keys::kCSPKey, ""); scoped_refptr<ApplicationData> application = CreateApplication(); EXPECT_TRUE(application.get()); EXPECT_EQ(GetCSPInfo(application)->GetDirectives().size(), 0); } TEST_F(CSPHandlerTest, CSP) { manifest.SetString(keys::kCSPKey, "default-src 'self' "); scoped_refptr<ApplicationData> application = CreateApplication(); EXPECT_TRUE(application.get()); const std::map<std::string, std::vector<std::string> >& policies = GetCSPInfo(application)->GetDirectives(); EXPECT_EQ(policies.size(), 1); std::map<std::string, std::vector<std::string> >::const_iterator it = policies.find("default-src"); ASSERT_NE(it, policies.end()); EXPECT_EQ(it->second.size(), 1); EXPECT_STREQ((it->second)[0].c_str(), "'self'"); } } // namespace application } // namespace xwalk <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_attributes.h" #include "dagman_classad.h" #include "dc_schedd.h" #include "condor_qmgr.h" #include "debug.h" //--------------------------------------------------------------------------- DagmanClassad::DagmanClassad( const CondorID &DAGManJobId ) { _valid = false; _schedd = NULL; CondorID defaultCondorId; if ( DAGManJobId == defaultCondorId ) { debug_printf( DEBUG_QUIET, "No Condor ID available for DAGMan (running on command line?); DAG status will not be reported to classad\n" ); return; } _dagmanId = DAGManJobId; _schedd = new DCSchedd( NULL, NULL ); if ( !_schedd || !_schedd->locate() ) { const char *errMsg = _schedd ? _schedd->error() : "?"; debug_printf( DEBUG_QUIET, "WARNING: can't find address of local schedd for classad updates (%s)\n", errMsg ); check_warning_strictness( DAG_STRICT_3 ); return; } _valid = true; } //--------------------------------------------------------------------------- DagmanClassad::~DagmanClassad() { _valid = false; delete _schedd; } //--------------------------------------------------------------------------- void DagmanClassad::Update( int total, int done, int pre, int submitted, int post, int ready, int failed, int unready, Dag::dag_status dagStatus, bool recovery ) { if ( !_valid ) { debug_printf( DEBUG_VERBOSE, "Skipping classad update -- DagmanClassad object is invalid\n" ); return; } // Open job queue CondorError errstack; Qmgr_connection *queue = ConnectQ( _schedd->addr(), 0, false, &errstack, NULL, _schedd->version() ); if ( !queue ) { debug_printf( DEBUG_QUIET, "WARNING: failed to connect to queue manager (%s)\n", errstack.getFullText().c_str() ); check_warning_strictness( DAG_STRICT_3 ); return; } SetDagAttribute( ATTR_DAG_NODES_TOTAL, total ); SetDagAttribute( ATTR_DAG_NODES_DONE, done ); SetDagAttribute( ATTR_DAG_NODES_PRERUN, pre ); SetDagAttribute( ATTR_DAG_NODES_QUEUED, submitted ); SetDagAttribute( ATTR_DAG_NODES_POSTRUN, post ); SetDagAttribute( ATTR_DAG_NODES_READY, ready ); SetDagAttribute( ATTR_DAG_NODES_FAILED, failed ); SetDagAttribute( ATTR_DAG_NODES_UNREADY, unready ); SetDagAttribute( ATTR_DAG_STATUS, (int)dagStatus ); SetDagAttribute( ATTR_DAG_IN_RECOVERY, recovery ); if ( !DisconnectQ( queue ) ) { debug_printf( DEBUG_QUIET, "WARNING: queue transaction failed. No attributes were set.\n" ); check_warning_strictness( DAG_STRICT_3 ); } } //--------------------------------------------------------------------------- void DagmanClassad::SetDagAttribute( const char *attrName, int attrVal ) { if ( SetAttributeInt( _dagmanId._cluster, _dagmanId._proc, attrName, attrVal, SETDIRTY|SHOULDLOG ) != 0 ) { // Try again without SETDIRTY|SHOULDLOG. if ( SetAttributeInt( _dagmanId._cluster, _dagmanId._proc, attrName, attrVal ) != 0 ) { debug_printf( DEBUG_QUIET, "WARNING: failed to set attribute %s\n", attrName ); check_warning_strictness( DAG_STRICT_3 ); } } } <commit_msg>DAGMan shouldn't set logging flags when updating its job ad. #3863<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_attributes.h" #include "dagman_classad.h" #include "dc_schedd.h" #include "condor_qmgr.h" #include "debug.h" //--------------------------------------------------------------------------- DagmanClassad::DagmanClassad( const CondorID &DAGManJobId ) { _valid = false; _schedd = NULL; CondorID defaultCondorId; if ( DAGManJobId == defaultCondorId ) { debug_printf( DEBUG_QUIET, "No Condor ID available for DAGMan (running on command line?); DAG status will not be reported to classad\n" ); return; } _dagmanId = DAGManJobId; _schedd = new DCSchedd( NULL, NULL ); if ( !_schedd || !_schedd->locate() ) { const char *errMsg = _schedd ? _schedd->error() : "?"; debug_printf( DEBUG_QUIET, "WARNING: can't find address of local schedd for classad updates (%s)\n", errMsg ); check_warning_strictness( DAG_STRICT_3 ); return; } _valid = true; } //--------------------------------------------------------------------------- DagmanClassad::~DagmanClassad() { _valid = false; delete _schedd; } //--------------------------------------------------------------------------- void DagmanClassad::Update( int total, int done, int pre, int submitted, int post, int ready, int failed, int unready, Dag::dag_status dagStatus, bool recovery ) { if ( !_valid ) { debug_printf( DEBUG_VERBOSE, "Skipping classad update -- DagmanClassad object is invalid\n" ); return; } // Open job queue CondorError errstack; Qmgr_connection *queue = ConnectQ( _schedd->addr(), 0, false, &errstack, NULL, _schedd->version() ); if ( !queue ) { debug_printf( DEBUG_QUIET, "WARNING: failed to connect to queue manager (%s)\n", errstack.getFullText().c_str() ); check_warning_strictness( DAG_STRICT_3 ); return; } SetDagAttribute( ATTR_DAG_NODES_TOTAL, total ); SetDagAttribute( ATTR_DAG_NODES_DONE, done ); SetDagAttribute( ATTR_DAG_NODES_PRERUN, pre ); SetDagAttribute( ATTR_DAG_NODES_QUEUED, submitted ); SetDagAttribute( ATTR_DAG_NODES_POSTRUN, post ); SetDagAttribute( ATTR_DAG_NODES_READY, ready ); SetDagAttribute( ATTR_DAG_NODES_FAILED, failed ); SetDagAttribute( ATTR_DAG_NODES_UNREADY, unready ); SetDagAttribute( ATTR_DAG_STATUS, (int)dagStatus ); SetDagAttribute( ATTR_DAG_IN_RECOVERY, recovery ); if ( !DisconnectQ( queue ) ) { debug_printf( DEBUG_QUIET, "WARNING: queue transaction failed. No attributes were set.\n" ); check_warning_strictness( DAG_STRICT_3 ); } } //--------------------------------------------------------------------------- void DagmanClassad::SetDagAttribute( const char *attrName, int attrVal ) { if ( SetAttributeInt( _dagmanId._cluster, _dagmanId._proc, attrName, attrVal ) != 0 ) { debug_printf( DEBUG_QUIET, "WARNING: failed to set attribute %s\n", attrName ); check_warning_strictness( DAG_STRICT_3 ); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSparseFrequencyContainer.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkSparseFrequencyContainer.h" namespace itk{ namespace Statistics{ SparseFrequencyContainer ::SparseFrequencyContainer() { m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero; } void SparseFrequencyContainer ::Initialize(unsigned long) { this->SetToZero(); } void SparseFrequencyContainer ::SetToZero() { typedef FrequencyContainerType::iterator IteratorType; IteratorType iter = m_FrequencyContainer.begin(); IteratorType end = m_FrequencyContainer.end(); while ( iter != end ) { iter->second = NumericTraits< FrequencyType >::Zero; ++iter; } m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero; } bool SparseFrequencyContainer ::SetFrequency(const InstanceIdentifier id, const FrequencyType value) { // No need to test for bounds because in a map container the // element is allocated if the key doesn't exist yet FrequencyType frequency = this->GetFrequency(id); m_FrequencyContainer[id] = value; m_TotalFrequency += (value - frequency); return true; } SparseFrequencyContainer::FrequencyType SparseFrequencyContainer ::GetFrequency(const InstanceIdentifier id) const { FrequencyContainerType::const_iterator iter = m_FrequencyContainer.find(id); if ( iter != m_FrequencyContainer.end() ) { return iter->second; } else { return 0; } } bool SparseFrequencyContainer ::IncreaseFrequency(const InstanceIdentifier id, const FrequencyType value) { // No need to test for bounds because in a map container the // element is allocated if the key doesn't exist yet FrequencyType frequency = this->GetFrequency(id); if( NumericTraits< FrequencyType >::max() - frequency < value ) { itkExceptionMacro("Frequency container saturated for Instance " << id ); } else { (*m_FrequencyContainer)[id] = frequency + value; } if( NumericTraits< TotalFrequencyType >::max() - m_TotalFrequency < value ) { itkExceptionMacro("Total Frequency container saturated for Instance " << id ); } else { m_TotalFrequency += value; } return true; } void SparseFrequencyContainer ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); } } // end of namespace Statistics } // end of namespace itk <commit_msg>COMP: Copy pasting is Evil !, Evil I tell you...<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSparseFrequencyContainer.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkSparseFrequencyContainer.h" namespace itk{ namespace Statistics{ SparseFrequencyContainer ::SparseFrequencyContainer() { m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero; } void SparseFrequencyContainer ::Initialize(unsigned long) { this->SetToZero(); } void SparseFrequencyContainer ::SetToZero() { typedef FrequencyContainerType::iterator IteratorType; IteratorType iter = m_FrequencyContainer.begin(); IteratorType end = m_FrequencyContainer.end(); while ( iter != end ) { iter->second = NumericTraits< FrequencyType >::Zero; ++iter; } m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero; } bool SparseFrequencyContainer ::SetFrequency(const InstanceIdentifier id, const FrequencyType value) { // No need to test for bounds because in a map container the // element is allocated if the key doesn't exist yet FrequencyType frequency = this->GetFrequency(id); m_FrequencyContainer[id] = value; m_TotalFrequency += (value - frequency); return true; } SparseFrequencyContainer::FrequencyType SparseFrequencyContainer ::GetFrequency(const InstanceIdentifier id) const { FrequencyContainerType::const_iterator iter = m_FrequencyContainer.find(id); if ( iter != m_FrequencyContainer.end() ) { return iter->second; } else { return 0; } } bool SparseFrequencyContainer ::IncreaseFrequency(const InstanceIdentifier id, const FrequencyType value) { // No need to test for bounds because in a map container the // element is allocated if the key doesn't exist yet FrequencyType frequency = this->GetFrequency(id); if( NumericTraits< FrequencyType >::max() - frequency < value ) { itkExceptionMacro("Frequency container saturated for Instance " << id ); } else { m_FrequencyContainer[id] = frequency + value; } if( NumericTraits< TotalFrequencyType >::max() - m_TotalFrequency < value ) { itkExceptionMacro("Total Frequency container saturated for Instance " << id ); } else { m_TotalFrequency += value; } return true; } void SparseFrequencyContainer ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); } } // end of namespace Statistics } // end of namespace itk <|endoftext|>
<commit_before>#include "direction.hpp" <commit_msg>Unused file<commit_after><|endoftext|>
<commit_before>#include "CommonData.hpp" #include "EventOutputQueue.hpp" #include "KeyboardRepeat.hpp" #include "ToEvent.hpp" #include "VirtualKey.hpp" namespace org_pqrs_KeyRemap4MacBook { bool ToEvent::isEventLikeModifier(void) const { switch (type_) { case Type::NONE: return false; case Type::KEY: return VirtualKey::isKeyLikeModifier(key_); case Type::CONSUMER_KEY: return false; case Type::POINTING_BUTTON: return true; } } void ToEvent::fire_downup(Flags flags, bool add_to_keyrepeat) { switch (type_) { case Type::NONE: break; case Type::KEY: { KeyboardType keyboardType = CommonData::getcurrent_keyboardType(); EventOutputQueue::FireKey::fire_downup(flags, key_, keyboardType); if (add_to_keyrepeat) { KeyboardRepeat::primitive_add_downup(flags, key_, keyboardType); } break; } case Type::CONSUMER_KEY: { { Params_KeyboardSpecialEventCallback::auto_ptr ptr(Params_KeyboardSpecialEventCallback::alloc(EventType::DOWN, flags, consumer_, false)); if (ptr) { EventOutputQueue::FireConsumer::fire(*ptr); } } { Params_KeyboardSpecialEventCallback::auto_ptr ptr(Params_KeyboardSpecialEventCallback::alloc(EventType::UP, flags, consumer_, false)); if (ptr) { EventOutputQueue::FireConsumer::fire(*ptr); } } if (add_to_keyrepeat) { KeyboardRepeat::primitive_add(EventType::DOWN, flags, consumer_); KeyboardRepeat::primitive_add(EventType::UP, flags, consumer_); } break; } case Type::POINTING_BUTTON: { FlagStatus::ScopedTemporaryFlagsChanger stfc(flags); ButtonStatus::increase(button_); EventOutputQueue::FireRelativePointer::fire(ButtonStatus::makeButtons()); ButtonStatus::decrease(button_); EventOutputQueue::FireRelativePointer::fire(ButtonStatus::makeButtons()); // XXX: handle add_to_keyrepeat break; } } } } <commit_msg>use EventOutputQueue::FireConsumer::fire_downup<commit_after>#include "CommonData.hpp" #include "EventOutputQueue.hpp" #include "KeyboardRepeat.hpp" #include "ToEvent.hpp" #include "VirtualKey.hpp" namespace org_pqrs_KeyRemap4MacBook { bool ToEvent::isEventLikeModifier(void) const { switch (type_) { case Type::NONE: return false; case Type::KEY: return VirtualKey::isKeyLikeModifier(key_); case Type::CONSUMER_KEY: return false; case Type::POINTING_BUTTON: return true; } } void ToEvent::fire_downup(Flags flags, bool add_to_keyrepeat) { switch (type_) { case Type::NONE: break; case Type::KEY: { KeyboardType keyboardType = CommonData::getcurrent_keyboardType(); EventOutputQueue::FireKey::fire_downup(flags, key_, keyboardType); if (add_to_keyrepeat) { KeyboardRepeat::primitive_add_downup(flags, key_, keyboardType); } break; } case Type::CONSUMER_KEY: { EventOutputQueue::FireConsumer::fire_downup(flags, consumer_); if (add_to_keyrepeat) { KeyboardRepeat::primitive_add(EventType::DOWN, flags, consumer_); KeyboardRepeat::primitive_add(EventType::UP, flags, consumer_); } break; } case Type::POINTING_BUTTON: { FlagStatus::ScopedTemporaryFlagsChanger stfc(flags); ButtonStatus::increase(button_); EventOutputQueue::FireRelativePointer::fire(ButtonStatus::makeButtons()); ButtonStatus::decrease(button_); EventOutputQueue::FireRelativePointer::fire(ButtonStatus::makeButtons()); // XXX: handle add_to_keyrepeat break; } } } } <|endoftext|>
<commit_before>/* * TexLogParser.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/tex/TexLogParser.hpp> #include <boost/foreach.hpp> #include <boost/regex.hpp> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <core/Error.hpp> #include <core/FilePath.hpp> #include <core/FileSerializer.hpp> #include <core/SafeConvert.hpp> #include <core/system/System.hpp> namespace core { namespace tex { namespace { // Helper function, returns true if str begins with any of these values bool beginsWith(const std::string& str, const std::string& test1, const std::string& test2=std::string(), const std::string& test3=std::string(), const std::string& test4=std::string()) { using namespace boost::algorithm; if (starts_with(str, test1)) return true; if (test2.empty()) return false; else if (starts_with(str, test2)) return true; if (test3.empty()) return false; else if (starts_with(str, test3)) return true; if (test4.empty()) return false; else if (starts_with(str, test4)) return true; return false; } // Finds unmatched parens in `line` and puts them in pParens. Can be either // ( or ). Logically the result can only be [zero or more ')'] followed by // [zero or more '(']. void findUnmatchedParens(const std::string& line, std::vector<std::string::const_iterator>* pParens) { // We need to ignore close parens unless they are at the start of a line, // preceded by nothing but whitespace and/or other close parens. Without // this, sample.Rnw has some false positives due to some math errors, e.g.: // // l.204 (x + (y^ // 2)) // // The first line is ignored because it's part of an error message. The rest // gets parsed and underflows the file stack. bool ignoreCloseParens = false; // NOTE: I don't know if it's possible for (<filename> to appear anywhere // but the beginning of the line (preceded only by whitespace(?) and close // parens). But the Sublime Text 2 plugin code seemed to imply that it is // possible. for (std::string::const_iterator it = line.begin(); it != line.end(); it++) { switch (*it) { case '(': pParens->push_back(it); ignoreCloseParens = true; break; case ')': if (pParens->empty() || *(pParens->back()) == ')') { if (!ignoreCloseParens) pParens->push_back(it); } else pParens->pop_back(); break; case ' ': case '\t': break; default: ignoreCloseParens = true; break; } } } // TeX wraps lines hard at 79 characters. We use heuristics as described in // Sublime Text's TeX plugin to determine where these breaks are. void unwrapLines(std::vector<std::string>* pLines) { static boost::regex regexLine("^l\\.(\\d+)\\s"); static boost::regex regexAssignment("^\\\\.*?="); std::vector<std::string>::iterator pos = pLines->begin(); for ( ; pos != pLines->end(); pos++) { // The first line is always long, and not artificially wrapped if (pos == pLines->begin()) continue; if (pos->length() != 79) continue; // The **<filename> line may be long, but we don't care about it if (beginsWith(*pos, "**")) continue; while (true) { std::vector<std::string>::iterator nextPos = pos + 1; // No more lines to add if (nextPos == pLines->end()) break; if (nextPos->empty()) break; // Underfull/Overfull terminator if (*nextPos == " []") break; // Common prefixes if (beginsWith(*nextPos, "File:", "Package:", "Document Class:")) break; // More prefixes if (beginsWith(*nextPos, "LaTeX Warning:", "LaTeX Info:", "LaTeX2e <")) break; if (boost::regex_search(*nextPos, regexAssignment)) break; if (boost::regex_search(*nextPos, regexLine)) break; bool breakAfterAppend = nextPos->length() != 79; pos->append(*nextPos); // NOTE: Erase is a simple but inefficient way of handling this. Would // be way faster to maintain an output iterator that points to the // correct point in pLines, and when finished, truncate whatever // elements come after the final position of the output iterator. pLines->erase(nextPos, nextPos+1); if (breakAfterAppend) break; } } } // Given the value of the line, push and pop files from the stack as needed. void maintainFileStack(const std::string line, std::vector<std::string>* pFileStack) { std::vector<std::string::const_iterator> parens; findUnmatchedParens(line, &parens); BOOST_FOREACH(std::string::const_iterator it, parens) { if (*it == ')') { if (pFileStack->size() > 1) pFileStack->pop_back(); else { LOG_WARNING_MESSAGE("File context stack underflow while parsing " "TeX log"); } } else if (*it == '(') { std::string filename; std::copy(it + 1, line.end(), std::back_inserter(filename)); // Remove quotes if present if (filename.size() >= 2 && filename[0] == '"' && filename[filename.size()-1] == '"') { filename = filename.substr(1, filename.size()-2); } pFileStack->push_back(filename); } else BOOST_ASSERT(false); } } Error parseLog( const FilePath& logFilePath, const boost::regex& re, const boost::function<LogEntry(const boost::smatch& match, const FilePath&)> matchToEntry, LogEntries* pLogEntries) { // get the lines std::vector<std::string> lines; Error error = core::readStringVectorFromFile(logFilePath, &lines); if (error) return error; // look for error messages BOOST_FOREACH(std::string line, lines) { boost::smatch match; if (regex_match(line, match, re)) { pLogEntries->push_back(matchToEntry(match, logFilePath.parent())); } } return Success(); } FilePath texFilePath(const std::string& logPath, const FilePath& compileDir) { // some tex compilers report file names with absolute paths and some // report them relative to the compilation directory -- on Posix use // realPath to get a clean full path back -- note the fact that we // don't do this on Windows is a tacit assumption that Windows TeX logs // are either absolute or don't require interpretation of .., etc. FilePath path = compileDir.complete(logPath); #ifdef _WIN32 return path; #else FilePath realPath; Error error = core::system::realPath(path.absolutePath(), &realPath); if (error) { LOG_ERROR(error); return path; } else { return realPath; } #endif } LogEntry fromLatexMatch(const boost::smatch& match, const FilePath& compileDir) { return LogEntry(LogEntry::Error, texFilePath(match[1], compileDir), boost::lexical_cast<int>(match[2]), match[3]); } LogEntry fromBibtexMatch(const boost::smatch& match, const FilePath& compileDir) { return LogEntry(LogEntry::Error, texFilePath(match[3], compileDir), boost::lexical_cast<int>(match[2]), match[1]); } } // anonymous namespace Error parseLatexLog(const FilePath& logFilePath, LogEntries* pLogEntries) { static boost::regex regexOverUnderfullLines(" at lines (\\d+)--(\\d+)\\s*(?:\\[])?$"); static boost::regex regexWarning("^(?:.*?) Warning: (.+)"); static boost::regex regexWarningEnd(" input line (\\d+)\\.$"); static boost::regex regexLnn("^l\\.(\\d+)\\s"); std::vector<std::string> lines; Error error = readStringVectorFromFile(logFilePath, &lines, false); if (error) return error; unwrapLines(&lines); std::vector<std::string> fileStack; fileStack.push_back(""); // The "null" file context for (std::vector<std::string>::const_iterator it = lines.begin(); it != lines.end(); it++) { const std::string& line = *it; // We slurp overfull/underfull messages with no further processing // (i.e. not manipulating the file stack) if (beginsWith(line, "Overfull ", "Underfull ")) { std::string msg = line; FilePath filePath = fileStack.back().empty() ? FilePath() : FilePath(fileStack.back()); int lineNum = -1; // Parse lines, if present boost::smatch overUnderfullLinesMatch; if (boost::regex_search(line, overUnderfullLinesMatch, regexOverUnderfullLines)) { lineNum = safe_convert::stringTo<int>(overUnderfullLinesMatch[1], -1); } // Single line case bool singleLine = boost::algorithm::ends_with(line, "[]"); if (singleLine) { msg.erase(line.size()-2, 2); boost::algorithm::trim_right(msg); } pLogEntries->push_back(LogEntry(LogEntry::Box, filePath, lineNum, msg)); if (singleLine) continue; for (; it != lines.end(); it++) { // For multi-line case, we're looking for " []" on a line by itself if (*it == " []") break; } // The iterator would be incremented by the outer for loop, must not // let it go past the end! (If we did get to the end, it would // mean the log file was malformed, but we still can't crash in this // situation.) if (it == lines.end()) break; else continue; } maintainFileStack(line, &fileStack); // Now see if it's an error or warning if (beginsWith(line, "! ")) { std::string errorMsg = line.substr(2); FilePath filePath = fileStack.back().empty() ? FilePath() : FilePath(fileStack.back()); int lineNum = -1; boost::smatch match; for (it++; it != lines.end(); it++) { if (boost::regex_search(*it, match, regexLnn)) { lineNum = safe_convert::stringTo<int>(match[1], -1); break; } } pLogEntries->push_back(LogEntry(LogEntry::Error, filePath, lineNum, errorMsg)); // The iterator would be incremented by the outer for loop, must not // let it go past the end! (If we did get to the end, it would // mean the log file was malformed, but we still can't crash in this // situation.) if (it == lines.end()) break; else continue; } boost::smatch warningMatch; if (boost::regex_search(line, warningMatch, regexWarning)) { std::string warningMsg = warningMatch[1]; FilePath filePath = fileStack.back().empty() ? FilePath() : FilePath(fileStack.back()); int lineNum = -1; while (true) { if (boost::algorithm::ends_with(warningMsg, ".")) { boost::smatch warningEndMatch; if (boost::regex_search(*it, warningEndMatch, regexWarningEnd)) { lineNum = safe_convert::stringTo<int>(warningEndMatch[1], -1); } break; } if (++it == lines.end()) break; warningMsg.append(*it); } pLogEntries->push_back(LogEntry(LogEntry::Warning, filePath, lineNum, warningMsg)); // The iterator would be incremented by the outer for loop, must not // let it go past the end! (If we did get to the end, it would // mean the log file was malformed, but we still can't crash in this // situation.) if (it == lines.end()) break; else continue; } } return Success(); } Error parseBibtexLog(const FilePath& logFilePath, LogEntries* pLogEntries) { return parseLog(logFilePath, boost::regex("^(.*)---line ([0-9]+) of file (.*)$"), fromBibtexMatch, pLogEntries); ; } } // namespace tex } // namespace core <commit_msg>TeX log parsing: Check if files actually exist before treating them as in-scope<commit_after>/* * TexLogParser.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/tex/TexLogParser.hpp> #include <boost/foreach.hpp> #include <boost/regex.hpp> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <core/Error.hpp> #include <core/FilePath.hpp> #include <core/FileSerializer.hpp> #include <core/SafeConvert.hpp> #include <core/system/System.hpp> namespace core { namespace tex { namespace { // Helper function, returns true if str begins with any of these values bool beginsWith(const std::string& str, const std::string& test1, const std::string& test2=std::string(), const std::string& test3=std::string(), const std::string& test4=std::string()) { using namespace boost::algorithm; if (starts_with(str, test1)) return true; if (test2.empty()) return false; else if (starts_with(str, test2)) return true; if (test3.empty()) return false; else if (starts_with(str, test3)) return true; if (test4.empty()) return false; else if (starts_with(str, test4)) return true; return false; } // Finds unmatched parens in `line` and puts them in pParens. Can be either // ( or ). Logically the result can only be [zero or more ')'] followed by // [zero or more '(']. void findUnmatchedParens(const std::string& line, std::vector<std::string::const_iterator>* pParens) { // We need to ignore close parens unless they are at the start of a line, // preceded by nothing but whitespace and/or other close parens. Without // this, sample.Rnw has some false positives due to some math errors, e.g.: // // l.204 (x + (y^ // 2)) // // The first line is ignored because it's part of an error message. The rest // gets parsed and underflows the file stack. bool ignoreCloseParens = false; // NOTE: I don't know if it's possible for (<filename> to appear anywhere // but the beginning of the line (preceded only by whitespace(?) and close // parens). But the Sublime Text 2 plugin code seemed to imply that it is // possible. for (std::string::const_iterator it = line.begin(); it != line.end(); it++) { switch (*it) { case '(': pParens->push_back(it); ignoreCloseParens = true; break; case ')': if (pParens->empty() || *(pParens->back()) == ')') { if (!ignoreCloseParens) pParens->push_back(it); } else pParens->pop_back(); break; case ' ': case '\t': break; default: ignoreCloseParens = true; break; } } } // TeX wraps lines hard at 79 characters. We use heuristics as described in // Sublime Text's TeX plugin to determine where these breaks are. void unwrapLines(std::vector<std::string>* pLines) { static boost::regex regexLine("^l\\.(\\d+)\\s"); static boost::regex regexAssignment("^\\\\.*?="); std::vector<std::string>::iterator pos = pLines->begin(); for ( ; pos != pLines->end(); pos++) { // The first line is always long, and not artificially wrapped if (pos == pLines->begin()) continue; if (pos->length() != 79) continue; // The **<filename> line may be long, but we don't care about it if (beginsWith(*pos, "**")) continue; while (true) { std::vector<std::string>::iterator nextPos = pos + 1; // No more lines to add if (nextPos == pLines->end()) break; if (nextPos->empty()) break; // Underfull/Overfull terminator if (*nextPos == " []") break; // Common prefixes if (beginsWith(*nextPos, "File:", "Package:", "Document Class:")) break; // More prefixes if (beginsWith(*nextPos, "LaTeX Warning:", "LaTeX Info:", "LaTeX2e <")) break; if (boost::regex_search(*nextPos, regexAssignment)) break; if (boost::regex_search(*nextPos, regexLine)) break; bool breakAfterAppend = nextPos->length() != 79; pos->append(*nextPos); // NOTE: Erase is a simple but inefficient way of handling this. Would // be way faster to maintain an output iterator that points to the // correct point in pLines, and when finished, truncate whatever // elements come after the final position of the output iterator. pLines->erase(nextPos, nextPos+1); if (breakAfterAppend) break; } } } class FileStack : public boost::noncopyable { public: FileStack(FilePath rootDir) : rootDir_(rootDir) { } FilePath currentFile() { return currentFile_; } void processLine(const std::string& line) { std::vector<std::string::const_iterator> parens; findUnmatchedParens(line, &parens); BOOST_FOREACH(std::string::const_iterator it, parens) { if (*it == ')') { if (!fileStack_.empty()) { fileStack_.pop_back(); updateCurrentFile(); } else { LOG_WARNING_MESSAGE("File context stack underflow while parsing " "TeX log"); } } else if (*it == '(') { std::string filename; std::copy(it + 1, line.end(), std::back_inserter(filename)); // Remove quotes if present if (filename.size() >= 2 && filename[0] == '"' && filename[filename.size()-1] == '"') { filename = filename.substr(1, filename.size()-2); } if (beginsWith(filename, "./")) filename = filename.substr(2); bool fileExists = !filename.empty() && rootDir_.complete(filename).exists(); if (!fileExists) filename = ""; fileStack_.push_back(filename.empty() ? FilePath() : rootDir_.complete(filename)); updateCurrentFile(); } else BOOST_ASSERT(false); } } private: void updateCurrentFile() { for (std::vector<FilePath>::reverse_iterator it = fileStack_.rbegin(); it != fileStack_.rend(); it++) { if (!it->empty()) { currentFile_ = *it; return; } } currentFile_ = FilePath(); } FilePath rootDir_; FilePath currentFile_; std::vector<FilePath> fileStack_; }; Error parseLog( const FilePath& logFilePath, const boost::regex& re, const boost::function<LogEntry(const boost::smatch& match, const FilePath&)> matchToEntry, LogEntries* pLogEntries) { // get the lines std::vector<std::string> lines; Error error = core::readStringVectorFromFile(logFilePath, &lines); if (error) return error; // look for error messages BOOST_FOREACH(std::string line, lines) { boost::smatch match; if (regex_match(line, match, re)) { pLogEntries->push_back(matchToEntry(match, logFilePath.parent())); } } return Success(); } FilePath texFilePath(const std::string& logPath, const FilePath& compileDir) { // some tex compilers report file names with absolute paths and some // report them relative to the compilation directory -- on Posix use // realPath to get a clean full path back -- note the fact that we // don't do this on Windows is a tacit assumption that Windows TeX logs // are either absolute or don't require interpretation of .., etc. FilePath path = compileDir.complete(logPath); #ifdef _WIN32 return path; #else FilePath realPath; Error error = core::system::realPath(path.absolutePath(), &realPath); if (error) { LOG_ERROR(error); return path; } else { return realPath; } #endif } LogEntry fromLatexMatch(const boost::smatch& match, const FilePath& compileDir) { return LogEntry(LogEntry::Error, texFilePath(match[1], compileDir), boost::lexical_cast<int>(match[2]), match[3]); } LogEntry fromBibtexMatch(const boost::smatch& match, const FilePath& compileDir) { return LogEntry(LogEntry::Error, texFilePath(match[3], compileDir), boost::lexical_cast<int>(match[2]), match[1]); } } // anonymous namespace Error parseLatexLog(const FilePath& logFilePath, LogEntries* pLogEntries) { static boost::regex regexOverUnderfullLines(" at lines (\\d+)--(\\d+)\\s*(?:\\[])?$"); static boost::regex regexWarning("^(?:.*?) Warning: (.+)"); static boost::regex regexWarningEnd(" input line (\\d+)\\.$"); static boost::regex regexLnn("^l\\.(\\d+)\\s"); std::vector<std::string> lines; Error error = readStringVectorFromFile(logFilePath, &lines, false); if (error) return error; unwrapLines(&lines); FileStack fileStack(logFilePath.parent()); for (std::vector<std::string>::const_iterator it = lines.begin(); it != lines.end(); it++) { const std::string& line = *it; // We slurp overfull/underfull messages with no further processing // (i.e. not manipulating the file stack) if (beginsWith(line, "Overfull ", "Underfull ")) { std::string msg = line; int lineNum = -1; // Parse lines, if present boost::smatch overUnderfullLinesMatch; if (boost::regex_search(line, overUnderfullLinesMatch, regexOverUnderfullLines)) { lineNum = safe_convert::stringTo<int>(overUnderfullLinesMatch[1], -1); } // Single line case bool singleLine = boost::algorithm::ends_with(line, "[]"); if (singleLine) { msg.erase(line.size()-2, 2); boost::algorithm::trim_right(msg); } pLogEntries->push_back(LogEntry(LogEntry::Box, fileStack.currentFile(), lineNum, msg)); if (singleLine) continue; for (; it != lines.end(); it++) { // For multi-line case, we're looking for " []" on a line by itself if (*it == " []") break; } // The iterator would be incremented by the outer for loop, must not // let it go past the end! (If we did get to the end, it would // mean the log file was malformed, but we still can't crash in this // situation.) if (it == lines.end()) break; else continue; } fileStack.processLine(line); // Now see if it's an error or warning if (beginsWith(line, "! ")) { std::string errorMsg = line.substr(2); int lineNum = -1; boost::smatch match; for (it++; it != lines.end(); it++) { if (boost::regex_search(*it, match, regexLnn)) { lineNum = safe_convert::stringTo<int>(match[1], -1); break; } } pLogEntries->push_back(LogEntry(LogEntry::Error, fileStack.currentFile(), lineNum, errorMsg)); // The iterator would be incremented by the outer for loop, must not // let it go past the end! (If we did get to the end, it would // mean the log file was malformed, but we still can't crash in this // situation.) if (it == lines.end()) break; else continue; } boost::smatch warningMatch; if (boost::regex_search(line, warningMatch, regexWarning)) { std::string warningMsg = warningMatch[1]; int lineNum = -1; while (true) { if (boost::algorithm::ends_with(warningMsg, ".")) { boost::smatch warningEndMatch; if (boost::regex_search(*it, warningEndMatch, regexWarningEnd)) { lineNum = safe_convert::stringTo<int>(warningEndMatch[1], -1); } break; } if (++it == lines.end()) break; warningMsg.append(*it); } pLogEntries->push_back(LogEntry(LogEntry::Warning, fileStack.currentFile(), lineNum, warningMsg)); // The iterator would be incremented by the outer for loop, must not // let it go past the end! (If we did get to the end, it would // mean the log file was malformed, but we still can't crash in this // situation.) if (it == lines.end()) break; else continue; } } return Success(); } Error parseBibtexLog(const FilePath& logFilePath, LogEntries* pLogEntries) { return parseLog(logFilePath, boost::regex("^(.*)---line ([0-9]+) of file (.*)$"), fromBibtexMatch, pLogEntries); ; } } // namespace tex } // namespace core <|endoftext|>
<commit_before>/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2018, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License version 3 as * published by the Free Software Foundation. * * 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 Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * * Author: @chhenning, 2018 * --------------------------------------------------------------------- */ /** @file PyBind11 bindings for SpatialPooler class */ // the use of 'register' keyword is removed in C++17 // Python2.7 uses 'register' in unicodeobject.h #ifdef _WIN32 #pragma warning( disable : 5033) // MSVC #else #pragma GCC diagnostic ignored "-Wregister" // for GCC and CLang #endif #include <pybind11/pybind11.h> #include <pybind11/iostream.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> #include <nupic/algorithms/SpatialPooler.hpp> #include "bindings/engine/py_utils.hpp" namespace py = pybind11; using namespace nupic; using namespace nupic::algorithms::spatial_pooler; namespace nupic_ext { void init_Spatial_Pooler(py::module& m) { py::class_<SpatialPooler> py_SpatialPooler(m, "SpatialPooler"); py_SpatialPooler.def( py::init<vector<UInt> , vector<UInt> , UInt , Real , bool , Real , UInt , UInt , Real , Real , Real , Real , UInt , Real , Int , UInt , bool>() , py::arg("inputDimensions") = vector<UInt>({ 32, 32 }) , py::arg("columnDimensions") = vector<UInt>({ 64, 64 }) , py::arg("potentialRadius") = 16 , py::arg("potentialPct") = 0.5 , py::arg("globalInhibition") = false , py::arg("localAreaDensity") = -1.0 , py::arg("numActiveColumnsPerInhArea") = 10 , py::arg("stimulusThreshold") = 0 , py::arg("synPermInactiveDec") = 0.01 , py::arg("synPermActiveInc") = 0.1 , py::arg("synPermConnected") = 0.1 , py::arg("minPctOverlapDutyCycle") = 0.001 , py::arg("dutyCyclePeriod") = 1000 , py::arg("boostStrength") = 0.0 , py::arg("seed") = -1 , py::arg("spVerbosity") = 0 , py::arg("wrapAround") = true ); py_SpatialPooler.def("initialize", &SpatialPooler::initialize , py::arg("inputDimensions") = vector<UInt>({ 32, 32 }) , py::arg("columnDimensions") = vector<UInt>({ 64, 64 }) , py::arg("potentialRadius") = 16 , py::arg("potentialPct") = 0.5 , py::arg("globalInhibition") = false , py::arg("localAreaDensity") = -1.0 , py::arg("numActiveColumnsPerInhArea") = 10 , py::arg("stimulusThreshold") = 0 , py::arg("synPermInactiveDec") = 0.01 , py::arg("synPermActiveInc") = 0.1 , py::arg("synPermConnected") = 0.1 , py::arg("minPctOverlapDutyCycle") = 0.001 , py::arg("dutyCyclePeriod") = 1000 , py::arg("boostStrength") = 0.0 , py::arg("seed") = -1 , py::arg("spVerbosity") = 0 , py::arg("wrapAround") = true); py_SpatialPooler.def("getColumnDimensions", &SpatialPooler::getColumnDimensions); py_SpatialPooler.def("getInputDimensions", &SpatialPooler::getInputDimensions); py_SpatialPooler.def("getNumColumns", &SpatialPooler::getNumColumns); py_SpatialPooler.def("getNumInputs", &SpatialPooler::getNumInputs); py_SpatialPooler.def("getPotentialRadius", &SpatialPooler::getPotentialRadius); py_SpatialPooler.def("setPotentialRadius", &SpatialPooler::setPotentialRadius); py_SpatialPooler.def("getPotentialPct", &SpatialPooler::getPotentialPct); py_SpatialPooler.def("setPotentialPct", &SpatialPooler::setPotentialPct); py_SpatialPooler.def("getGlobalInhibition", &SpatialPooler::getGlobalInhibition); py_SpatialPooler.def("setGlobalInhibition", &SpatialPooler::setGlobalInhibition); py_SpatialPooler.def("getNumActiveColumnsPerInhArea", &SpatialPooler::getNumActiveColumnsPerInhArea); py_SpatialPooler.def("setNumActiveColumnsPerInhArea", &SpatialPooler::setNumActiveColumnsPerInhArea); py_SpatialPooler.def("getLocalAreaDensity", &SpatialPooler::getLocalAreaDensity); py_SpatialPooler.def("setLocalAreaDensity", &SpatialPooler::setLocalAreaDensity); py_SpatialPooler.def("getStimulusThreshold", &SpatialPooler::getStimulusThreshold); py_SpatialPooler.def("setStimulusThreshold", &SpatialPooler::setStimulusThreshold); py_SpatialPooler.def("getInhibitionRadius", &SpatialPooler::getInhibitionRadius); py_SpatialPooler.def("setInhibitionRadius", &SpatialPooler::setInhibitionRadius); py_SpatialPooler.def("getDutyCyclePeriod", &SpatialPooler::getDutyCyclePeriod); py_SpatialPooler.def("setDutyCyclePeriod", &SpatialPooler::setDutyCyclePeriod); py_SpatialPooler.def("getBoostStrength", &SpatialPooler::getBoostStrength); py_SpatialPooler.def("setBoostStrength", &SpatialPooler::setBoostStrength); py_SpatialPooler.def("getIterationNum", &SpatialPooler::getIterationNum); py_SpatialPooler.def("setIterationNum", &SpatialPooler::setIterationNum); py_SpatialPooler.def("getIterationLearnNum", &SpatialPooler::getIterationLearnNum); py_SpatialPooler.def("setIterationLearnNum", &SpatialPooler::setIterationLearnNum); py_SpatialPooler.def("getSpVerbosity", &SpatialPooler::getSpVerbosity); py_SpatialPooler.def("setSpVerbosity", &SpatialPooler::setSpVerbosity); py_SpatialPooler.def("getWrapAround", &SpatialPooler::getWrapAround); py_SpatialPooler.def("setWrapAround", &SpatialPooler::setWrapAround); py_SpatialPooler.def("getUpdatePeriod", &SpatialPooler::getUpdatePeriod); py_SpatialPooler.def("setUpdatePeriod", &SpatialPooler::setUpdatePeriod); py_SpatialPooler.def("getSynPermActiveInc", &SpatialPooler::getSynPermActiveInc); py_SpatialPooler.def("setSynPermActiveInc", &SpatialPooler::setSynPermActiveInc); py_SpatialPooler.def("getSynPermInactiveDec", &SpatialPooler::getSynPermInactiveDec); py_SpatialPooler.def("setSynPermInactiveDec", &SpatialPooler::setSynPermInactiveDec); py_SpatialPooler.def("getSynPermBelowStimulusInc", &SpatialPooler::getSynPermBelowStimulusInc); py_SpatialPooler.def("setSynPermBelowStimulusInc", &SpatialPooler::setSynPermBelowStimulusInc); py_SpatialPooler.def("getSynPermConnected", &SpatialPooler::getSynPermConnected); py_SpatialPooler.def("setSynPermConnected", &SpatialPooler::setSynPermConnected); py_SpatialPooler.def("getSynPermMax", &SpatialPooler::getSynPermMax); py_SpatialPooler.def("setSynPermMax", &SpatialPooler::setSynPermMax); py_SpatialPooler.def("getMinPctOverlapDutyCycles", &SpatialPooler::getMinPctOverlapDutyCycles); py_SpatialPooler.def("setMinPctOverlapDutyCycles", &SpatialPooler::setMinPctOverlapDutyCycles); // loadFromString py_SpatialPooler.def("loadFromString", [](SpatialPooler& self, const std::string& inString) { std::istringstream inStream(inString); self.load(inStream); }); // writeToString py_SpatialPooler.def("writeToString", [](const SpatialPooler& self) { std::ostringstream os; os.flags(ios::scientific); os.precision(numeric_limits<double>::digits10 + 1); self.save(os); return os.str(); }); // compute py_SpatialPooler.def("compute", [](SpatialPooler& self, py::array& x, bool learn, py::array& y) { if (py::isinstance<py::array_t<std::uint32_t>>(x) == false) { throw runtime_error("Incompatible format. Expect uint32"); } if (py::isinstance<py::array_t<std::uint32_t>>(y) == false) { throw runtime_error("Incompatible format. Expect uint32"); } self.compute(get_it<UInt>(x), learn, get_it<UInt>(y)); }); // stripUnlearnedColumns py_SpatialPooler.def("stripUnlearnedColumns", [](SpatialPooler& self, py::array_t<UInt>& x) { self.stripUnlearnedColumns(get_it(x)); }); // setBoostFactors py_SpatialPooler.def("setBoostFactors", [](SpatialPooler& self, py::array_t<Real>& x) { self.setBoostFactors(get_it(x)); }); // getBoostFactors py_SpatialPooler.def("getBoostFactors", [](const SpatialPooler& self, py::array_t<Real>& x) { self.getBoostFactors(get_it(x)); }); // setOverlapDutyCycles py_SpatialPooler.def("setOverlapDutyCycles", [](SpatialPooler& self, py::array_t<Real>& x) { self.setOverlapDutyCycles(get_it(x)); }); // getOverlapDutyCycles py_SpatialPooler.def("getOverlapDutyCycles", [](const SpatialPooler& self, py::array_t<Real>& x) { self.getOverlapDutyCycles(get_it(x)); }); // setActiveDutyCycles py_SpatialPooler.def("setActiveDutyCycles", [](SpatialPooler& self, py::array_t<Real>& x) { self.setActiveDutyCycles(get_it(x)); }); // getActiveDutyCycles py_SpatialPooler.def("getActiveDutyCycles", [](const SpatialPooler& self, py::array_t<Real>& x) { self.getActiveDutyCycles(get_it(x)); }); // setMinOverlapDutyCycles py_SpatialPooler.def("setMinOverlapDutyCycles", [](SpatialPooler& self, py::array_t<Real>& x) { self.setMinOverlapDutyCycles(get_it(x)); }); // getMinOverlapDutyCycles py_SpatialPooler.def("getMinOverlapDutyCycles", [](const SpatialPooler& self, py::array_t<Real>& x) { self.getMinOverlapDutyCycles(get_it(x)); }); // setPotential py_SpatialPooler.def("setPotential", [](SpatialPooler& self, UInt column, py::array_t<UInt>& x) { self.setPotential(column, get_it(x)); }); // getPotential py_SpatialPooler.def("getPotential", [](const SpatialPooler& self, UInt column, py::array_t<UInt>& x) { self.getPotential(column, get_it(x)); }); // setPermanence py_SpatialPooler.def("setPermanence", [](SpatialPooler& self, UInt column, py::array_t<Real>& x) { self.setPermanence(column, get_it(x)); }); // getPermanence py_SpatialPooler.def("getPermanence", [](const SpatialPooler& self, UInt column, py::array_t<Real>& x) { self.getPermanence(column, get_it(x)); }); // getConnectedSynapses py_SpatialPooler.def("getConnectedSynapses", [](const SpatialPooler& self, UInt column, py::array_t<UInt>& x) { self.getConnectedSynapses(column, get_it(x)); }); // getConnectedCounts py_SpatialPooler.def("getConnectedCounts", [](const SpatialPooler& self, py::array_t<UInt>& x) { self.getConnectedCounts(get_it(x)); }); // getOverlaps py_SpatialPooler.def("getOverlaps", [](SpatialPooler& self) { auto overlaps = self.getOverlaps(); return py::array_t<UInt>({ overlaps.size() }, overlaps.data()); }); // getBoostedOverlaps py_SpatialPooler.def("getBoostedOverlaps", [](SpatialPooler& self) { auto overlaps = self.getBoostedOverlaps(); return py::array_t<Real>({ overlaps.size() }, overlaps.data()); }); //////////////////// // inhibitColumns auto inhibitColumns_func = [](SpatialPooler& self, py::array_t<Real>& overlaps) { std::vector<nupic::Real> overlapsVector(get_it(overlaps), get_end(overlaps)); std::vector<nupic::UInt> activeColumnsVector; self.inhibitColumns_(overlapsVector, activeColumnsVector); return py::array_t<UInt>({ activeColumnsVector.size() }, activeColumnsVector.data()); }; py_SpatialPooler.def("_inhibitColumns", inhibitColumns_func); py_SpatialPooler.def("inhibitColumns_", inhibitColumns_func); ////////////////////////////// // updatePermanencesForColumn auto updatePermanencesForColumn_func = [](SpatialPooler& self, py::array_t<Real>& perm, UInt column, bool raisePerm) { std::vector<nupic::Real> permVector(get_it(perm), get_end(perm)); self.updatePermanencesForColumn_(permVector, column, raisePerm); }; py_SpatialPooler.def("_updatePermanencesForColumn", updatePermanencesForColumn_func); py_SpatialPooler.def("updatePermanencesForColumn_", updatePermanencesForColumn_func); ////////////////////// // getIterationLearnNum py_SpatialPooler.def("getIterationLearnNum", &SpatialPooler::getIterationLearnNum); // pickle py_SpatialPooler.def(py::pickle( [](const SpatialPooler& sp) { std::stringstream ss; sp.save(ss); return ss.str(); }, [](std::string& s) { std::istringstream ss(s); SpatialPooler sp; sp.load(ss); return sp; })); } } // namespace nupic_ext <commit_msg>py_SpatialPooler: fix method removed in SP, remove in bindings too<commit_after>/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2018, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License version 3 as * published by the Free Software Foundation. * * 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 Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * * Author: @chhenning, 2018 * --------------------------------------------------------------------- */ /** @file PyBind11 bindings for SpatialPooler class */ // the use of 'register' keyword is removed in C++17 // Python2.7 uses 'register' in unicodeobject.h #ifdef _WIN32 #pragma warning( disable : 5033) // MSVC #else #pragma GCC diagnostic ignored "-Wregister" // for GCC and CLang #endif #include <pybind11/pybind11.h> #include <pybind11/iostream.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> #include <nupic/algorithms/SpatialPooler.hpp> #include "bindings/engine/py_utils.hpp" namespace py = pybind11; using namespace nupic; using namespace nupic::algorithms::spatial_pooler; namespace nupic_ext { void init_Spatial_Pooler(py::module& m) { py::class_<SpatialPooler> py_SpatialPooler(m, "SpatialPooler"); py_SpatialPooler.def( py::init<vector<UInt> , vector<UInt> , UInt , Real , bool , Real , UInt , UInt , Real , Real , Real , Real , UInt , Real , Int , UInt , bool>() , py::arg("inputDimensions") = vector<UInt>({ 32, 32 }) , py::arg("columnDimensions") = vector<UInt>({ 64, 64 }) , py::arg("potentialRadius") = 16 , py::arg("potentialPct") = 0.5 , py::arg("globalInhibition") = false , py::arg("localAreaDensity") = -1.0 , py::arg("numActiveColumnsPerInhArea") = 10 , py::arg("stimulusThreshold") = 0 , py::arg("synPermInactiveDec") = 0.01 , py::arg("synPermActiveInc") = 0.1 , py::arg("synPermConnected") = 0.1 , py::arg("minPctOverlapDutyCycle") = 0.001 , py::arg("dutyCyclePeriod") = 1000 , py::arg("boostStrength") = 0.0 , py::arg("seed") = -1 , py::arg("spVerbosity") = 0 , py::arg("wrapAround") = true ); py_SpatialPooler.def("initialize", &SpatialPooler::initialize , py::arg("inputDimensions") = vector<UInt>({ 32, 32 }) , py::arg("columnDimensions") = vector<UInt>({ 64, 64 }) , py::arg("potentialRadius") = 16 , py::arg("potentialPct") = 0.5 , py::arg("globalInhibition") = false , py::arg("localAreaDensity") = -1.0 , py::arg("numActiveColumnsPerInhArea") = 10 , py::arg("stimulusThreshold") = 0 , py::arg("synPermInactiveDec") = 0.01 , py::arg("synPermActiveInc") = 0.1 , py::arg("synPermConnected") = 0.1 , py::arg("minPctOverlapDutyCycle") = 0.001 , py::arg("dutyCyclePeriod") = 1000 , py::arg("boostStrength") = 0.0 , py::arg("seed") = -1 , py::arg("spVerbosity") = 0 , py::arg("wrapAround") = true); py_SpatialPooler.def("getColumnDimensions", &SpatialPooler::getColumnDimensions); py_SpatialPooler.def("getInputDimensions", &SpatialPooler::getInputDimensions); py_SpatialPooler.def("getNumColumns", &SpatialPooler::getNumColumns); py_SpatialPooler.def("getNumInputs", &SpatialPooler::getNumInputs); py_SpatialPooler.def("getPotentialRadius", &SpatialPooler::getPotentialRadius); py_SpatialPooler.def("setPotentialRadius", &SpatialPooler::setPotentialRadius); py_SpatialPooler.def("getPotentialPct", &SpatialPooler::getPotentialPct); py_SpatialPooler.def("setPotentialPct", &SpatialPooler::setPotentialPct); py_SpatialPooler.def("getGlobalInhibition", &SpatialPooler::getGlobalInhibition); py_SpatialPooler.def("setGlobalInhibition", &SpatialPooler::setGlobalInhibition); py_SpatialPooler.def("getNumActiveColumnsPerInhArea", &SpatialPooler::getNumActiveColumnsPerInhArea); py_SpatialPooler.def("setNumActiveColumnsPerInhArea", &SpatialPooler::setNumActiveColumnsPerInhArea); py_SpatialPooler.def("getLocalAreaDensity", &SpatialPooler::getLocalAreaDensity); py_SpatialPooler.def("setLocalAreaDensity", &SpatialPooler::setLocalAreaDensity); py_SpatialPooler.def("getStimulusThreshold", &SpatialPooler::getStimulusThreshold); py_SpatialPooler.def("setStimulusThreshold", &SpatialPooler::setStimulusThreshold); py_SpatialPooler.def("getInhibitionRadius", &SpatialPooler::getInhibitionRadius); py_SpatialPooler.def("setInhibitionRadius", &SpatialPooler::setInhibitionRadius); py_SpatialPooler.def("getDutyCyclePeriod", &SpatialPooler::getDutyCyclePeriod); py_SpatialPooler.def("setDutyCyclePeriod", &SpatialPooler::setDutyCyclePeriod); py_SpatialPooler.def("getBoostStrength", &SpatialPooler::getBoostStrength); py_SpatialPooler.def("setBoostStrength", &SpatialPooler::setBoostStrength); py_SpatialPooler.def("getIterationNum", &SpatialPooler::getIterationNum); py_SpatialPooler.def("setIterationNum", &SpatialPooler::setIterationNum); py_SpatialPooler.def("getIterationLearnNum", &SpatialPooler::getIterationLearnNum); py_SpatialPooler.def("setIterationLearnNum", &SpatialPooler::setIterationLearnNum); py_SpatialPooler.def("getSpVerbosity", &SpatialPooler::getSpVerbosity); py_SpatialPooler.def("setSpVerbosity", &SpatialPooler::setSpVerbosity); py_SpatialPooler.def("getWrapAround", &SpatialPooler::getWrapAround); py_SpatialPooler.def("setWrapAround", &SpatialPooler::setWrapAround); py_SpatialPooler.def("getUpdatePeriod", &SpatialPooler::getUpdatePeriod); py_SpatialPooler.def("setUpdatePeriod", &SpatialPooler::setUpdatePeriod); py_SpatialPooler.def("getSynPermActiveInc", &SpatialPooler::getSynPermActiveInc); py_SpatialPooler.def("setSynPermActiveInc", &SpatialPooler::setSynPermActiveInc); py_SpatialPooler.def("getSynPermInactiveDec", &SpatialPooler::getSynPermInactiveDec); py_SpatialPooler.def("setSynPermInactiveDec", &SpatialPooler::setSynPermInactiveDec); py_SpatialPooler.def("getSynPermBelowStimulusInc", &SpatialPooler::getSynPermBelowStimulusInc); py_SpatialPooler.def("setSynPermBelowStimulusInc", &SpatialPooler::setSynPermBelowStimulusInc); py_SpatialPooler.def("getSynPermConnected", &SpatialPooler::getSynPermConnected); py_SpatialPooler.def("setSynPermConnected", &SpatialPooler::setSynPermConnected); py_SpatialPooler.def("getSynPermMax", &SpatialPooler::getSynPermMax); py_SpatialPooler.def("getMinPctOverlapDutyCycles", &SpatialPooler::getMinPctOverlapDutyCycles); py_SpatialPooler.def("setMinPctOverlapDutyCycles", &SpatialPooler::setMinPctOverlapDutyCycles); // loadFromString py_SpatialPooler.def("loadFromString", [](SpatialPooler& self, const std::string& inString) { std::istringstream inStream(inString); self.load(inStream); }); // writeToString py_SpatialPooler.def("writeToString", [](const SpatialPooler& self) { std::ostringstream os; os.flags(ios::scientific); os.precision(numeric_limits<double>::digits10 + 1); self.save(os); return os.str(); }); // compute py_SpatialPooler.def("compute", [](SpatialPooler& self, py::array& x, bool learn, py::array& y) { if (py::isinstance<py::array_t<std::uint32_t>>(x) == false) { throw runtime_error("Incompatible format. Expect uint32"); } if (py::isinstance<py::array_t<std::uint32_t>>(y) == false) { throw runtime_error("Incompatible format. Expect uint32"); } self.compute(get_it<UInt>(x), learn, get_it<UInt>(y)); }); // stripUnlearnedColumns py_SpatialPooler.def("stripUnlearnedColumns", [](SpatialPooler& self, py::array_t<UInt>& x) { self.stripUnlearnedColumns(get_it(x)); }); // setBoostFactors py_SpatialPooler.def("setBoostFactors", [](SpatialPooler& self, py::array_t<Real>& x) { self.setBoostFactors(get_it(x)); }); // getBoostFactors py_SpatialPooler.def("getBoostFactors", [](const SpatialPooler& self, py::array_t<Real>& x) { self.getBoostFactors(get_it(x)); }); // setOverlapDutyCycles py_SpatialPooler.def("setOverlapDutyCycles", [](SpatialPooler& self, py::array_t<Real>& x) { self.setOverlapDutyCycles(get_it(x)); }); // getOverlapDutyCycles py_SpatialPooler.def("getOverlapDutyCycles", [](const SpatialPooler& self, py::array_t<Real>& x) { self.getOverlapDutyCycles(get_it(x)); }); // setActiveDutyCycles py_SpatialPooler.def("setActiveDutyCycles", [](SpatialPooler& self, py::array_t<Real>& x) { self.setActiveDutyCycles(get_it(x)); }); // getActiveDutyCycles py_SpatialPooler.def("getActiveDutyCycles", [](const SpatialPooler& self, py::array_t<Real>& x) { self.getActiveDutyCycles(get_it(x)); }); // setMinOverlapDutyCycles py_SpatialPooler.def("setMinOverlapDutyCycles", [](SpatialPooler& self, py::array_t<Real>& x) { self.setMinOverlapDutyCycles(get_it(x)); }); // getMinOverlapDutyCycles py_SpatialPooler.def("getMinOverlapDutyCycles", [](const SpatialPooler& self, py::array_t<Real>& x) { self.getMinOverlapDutyCycles(get_it(x)); }); // setPotential py_SpatialPooler.def("setPotential", [](SpatialPooler& self, UInt column, py::array_t<UInt>& x) { self.setPotential(column, get_it(x)); }); // getPotential py_SpatialPooler.def("getPotential", [](const SpatialPooler& self, UInt column, py::array_t<UInt>& x) { self.getPotential(column, get_it(x)); }); // setPermanence py_SpatialPooler.def("setPermanence", [](SpatialPooler& self, UInt column, py::array_t<Real>& x) { self.setPermanence(column, get_it(x)); }); // getPermanence py_SpatialPooler.def("getPermanence", [](const SpatialPooler& self, UInt column, py::array_t<Real>& x) { self.getPermanence(column, get_it(x)); }); // getConnectedSynapses py_SpatialPooler.def("getConnectedSynapses", [](const SpatialPooler& self, UInt column, py::array_t<UInt>& x) { self.getConnectedSynapses(column, get_it(x)); }); // getConnectedCounts py_SpatialPooler.def("getConnectedCounts", [](const SpatialPooler& self, py::array_t<UInt>& x) { self.getConnectedCounts(get_it(x)); }); // getOverlaps py_SpatialPooler.def("getOverlaps", [](SpatialPooler& self) { auto overlaps = self.getOverlaps(); return py::array_t<UInt>({ overlaps.size() }, overlaps.data()); }); // getBoostedOverlaps py_SpatialPooler.def("getBoostedOverlaps", [](SpatialPooler& self) { auto overlaps = self.getBoostedOverlaps(); return py::array_t<Real>({ overlaps.size() }, overlaps.data()); }); //////////////////// // inhibitColumns auto inhibitColumns_func = [](SpatialPooler& self, py::array_t<Real>& overlaps) { std::vector<nupic::Real> overlapsVector(get_it(overlaps), get_end(overlaps)); std::vector<nupic::UInt> activeColumnsVector; self.inhibitColumns_(overlapsVector, activeColumnsVector); return py::array_t<UInt>({ activeColumnsVector.size() }, activeColumnsVector.data()); }; py_SpatialPooler.def("_inhibitColumns", inhibitColumns_func); py_SpatialPooler.def("inhibitColumns_", inhibitColumns_func); ////////////////////////////// // updatePermanencesForColumn auto updatePermanencesForColumn_func = [](SpatialPooler& self, py::array_t<Real>& perm, UInt column, bool raisePerm) { std::vector<nupic::Real> permVector(get_it(perm), get_end(perm)); self.updatePermanencesForColumn_(permVector, column, raisePerm); }; py_SpatialPooler.def("_updatePermanencesForColumn", updatePermanencesForColumn_func); py_SpatialPooler.def("updatePermanencesForColumn_", updatePermanencesForColumn_func); ////////////////////// // getIterationLearnNum py_SpatialPooler.def("getIterationLearnNum", &SpatialPooler::getIterationLearnNum); // pickle py_SpatialPooler.def(py::pickle( [](const SpatialPooler& sp) { std::stringstream ss; sp.save(ss); return ss.str(); }, [](std::string& s) { std::istringstream ss(s); SpatialPooler sp; sp.load(ss); return sp; })); } } // namespace nupic_ext <|endoftext|>
<commit_before>/********************************************************************* * * Copyright 2012 the original author or authors. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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 "transcoders.h" #include<ros/ros.h> #include<sensor_msgs/CompressedImage.h> extern "C" { #include <libavcodec/avcodec.h> #include <libavutil/common.h> } bool SoftwareH264Encoder::encodeInPlace(sensor_msgs::CompressedImage *image, bool *keyFrame) { if (image->format != "yuv420p") { ROS_ERROR("Image is not in yuv420p format"); return false; } sourceFrame->data[0] = image->data.data(); sourceFrame->data[1] = sourceFrame->data[0] + width * height; sourceFrame->data[2] = sourceFrame->data[1] + width * height / 4; sourceFrame->linesize[0] = width; sourceFrame->linesize[1] = width / 2; sourceFrame->linesize[2] = width / 2; sourceFrame->pts = (1.0 / 30) * 90 * frameCounter; frameCounter++; // Data is going to be compressed, so this is a safe upper bound on the size uint8_t *outputBuffer = new uint8_t[image->data.size()]; int outputSize = avcodec_encode_video(context, outputBuffer, image->data.size(), sourceFrame); if (context->coded_frame->key_frame) { *keyFrame = true; } // XXX: Do we need to output the delayed frames here? by passing null as the // frame while the output buffer is getting populated image->data.clear(); image->format = "h264"; for (int i = 0; i < outputSize; i++) { image->data.push_back(outputBuffer[i]); } delete[] outputBuffer; *keyFrame = context->coded_frame->key_frame; return true; } AVFrame *SoftwareH264Encoder::allocFrame() { AVFrame *frame; uint8_t *buf; int size; frame = avcodec_alloc_frame(); size = avpicture_get_size(pixelFormat, width, height); buf = (uint8_t*) av_malloc(size); avpicture_fill((AVPicture *)frame, buf, pixelFormat, width, height); return frame; } SoftwareH264Encoder::SoftwareH264Encoder(int width, int height, PixelFormat pixelFormat) { avcodec_register_all(); this->width = width; this->height = height; this->pixelFormat = pixelFormat; encoder = avcodec_find_encoder(CODEC_ID_H264); if (!encoder) { ROS_ERROR("Could not find H264 encoder"); } context = avcodec_alloc_context3(encoder); avcodec_get_context_defaults3(context, encoder); sourceFrame = allocFrame(); context->codec_id = encoder->id; context->width = width; context->height = height; context->pix_fmt = pixelFormat; context->codec_type = AVMEDIA_TYPE_VIDEO; context->bit_rate = 400000; context->time_base = (AVRational){1, 25}; context->gop_size = 12; context->flags |= CODEC_FLAG_GLOBAL_HEADER; if (avcodec_open2(context, encoder, nullptr) < 0) { ROS_ERROR("Could not open h264 encoder"); } } <commit_msg>Replace usage of deprecated function<commit_after>/********************************************************************* * * Copyright 2012 the original author or authors. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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 "transcoders.h" #include<ros/ros.h> #include<sensor_msgs/CompressedImage.h> extern "C" { #include <libavcodec/avcodec.h> #include <libavutil/common.h> } bool SoftwareH264Encoder::encodeInPlace(sensor_msgs::CompressedImage *image, bool *keyFrame) { if (image->format != "yuv420p") { ROS_ERROR("Image is not in yuv420p format"); return false; } sourceFrame->data[0] = image->data.data(); sourceFrame->data[1] = sourceFrame->data[0] + width * height; sourceFrame->data[2] = sourceFrame->data[1] + width * height / 4; sourceFrame->linesize[0] = width; sourceFrame->linesize[1] = width / 2; sourceFrame->linesize[2] = width / 2; sourceFrame->pts = (1.0 / 30) * 90 * frameCounter; frameCounter++; // Data is going to be compressed, so this is a safe upper bound on the size uint8_t *outputBuffer = new uint8_t[image->data.size()]; AVPacket packet; av_init_packet(&packet); packet.size = image->data.size(); packet.data = outputBuffer; int gotPacket; int outputSize = avcodec_encode_video2(context, &packet, sourceFrame, &gotPacket); if (context->coded_frame->key_frame) { *keyFrame = true; } // XXX: Do we need to output the delayed frames here? by passing null as the // frame while the output buffer is getting populated image->data.clear(); image->format = "h264"; for (int i = 0; i < outputSize; i++) { image->data.push_back(outputBuffer[i]); } delete[] outputBuffer; *keyFrame = context->coded_frame->key_frame; return true; } AVFrame *SoftwareH264Encoder::allocFrame() { AVFrame *frame; uint8_t *buf; int size; frame = avcodec_alloc_frame(); size = avpicture_get_size(pixelFormat, width, height); buf = (uint8_t*) av_malloc(size); avpicture_fill((AVPicture *)frame, buf, pixelFormat, width, height); return frame; } SoftwareH264Encoder::SoftwareH264Encoder(int width, int height, PixelFormat pixelFormat) { avcodec_register_all(); this->width = width; this->height = height; this->pixelFormat = pixelFormat; encoder = avcodec_find_encoder(CODEC_ID_H264); if (!encoder) { ROS_ERROR("Could not find H264 encoder"); } context = avcodec_alloc_context3(encoder); avcodec_get_context_defaults3(context, encoder); sourceFrame = allocFrame(); context->codec_id = encoder->id; context->width = width; context->height = height; context->pix_fmt = pixelFormat; context->codec_type = AVMEDIA_TYPE_VIDEO; context->bit_rate = 400000; context->time_base = (AVRational){1, 25}; context->gop_size = 12; context->flags |= CODEC_FLAG_GLOBAL_HEADER; if (avcodec_open2(context, encoder, nullptr) < 0) { ROS_ERROR("Could not open h264 encoder"); } } <|endoftext|>
<commit_before>#include "CommonData.hpp" #include "EventOutputQueue.hpp" #include "KeyToKey.hpp" #include "KeyboardRepeat.hpp" #include "VirtualKey.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace RemapFunc { KeyToKey::KeyToKey(void) : index_(0), keyboardRepeatID_(-1), isRepeatEnabled_(true) { toKeys_ = new Vector_PairKeyFlags(); } KeyToKey::~KeyToKey(void) { if (toKeys_) { delete toKeys_; } } void KeyToKey::add(unsigned int datatype, unsigned int newval) { if (! toKeys_) return; switch (datatype) { case BRIDGE_DATATYPE_KEYCODE: { switch (index_) { case 0: fromKey_.key = newval; break; default: toKeys_->push_back(PairKeyFlags(newval)); break; } ++index_; break; } case BRIDGE_DATATYPE_FLAGS: { switch (index_) { case 0: IOLOG_ERROR("Invalid KeyToKey::add\n"); break; case 1: fromKey_.flags = newval; break; default: if (! toKeys_->empty()) { (toKeys_->back()).flags = newval; } break; } break; } case BRIDGE_DATATYPE_OPTION: { if (Option::NOREPEAT == newval) { isRepeatEnabled_ = false; } else { IOLOG_ERROR("KeyToKey::add unknown option:%d\n", newval); } break; } default: IOLOG_ERROR("KeyToKey::add invalid datatype:%d\n", datatype); break; } } bool KeyToKey::remap(RemapParams& remapParams) { if (! toKeys_) return false; if (remapParams.isremapped) return false; if (! fromkeychecker_.isFromKey(remapParams.params.ex_iskeydown, remapParams.params.key, FlagStatus::makeFlags(), fromKey_.key, fromKey_.flags)) return false; remapParams.isremapped = true; // ------------------------------------------------------------ // handle EventType & Modifiers // Let's consider the following setting. // --KeyToKey-- KeyCode::SHIFT_R, ModifierFlag::SHIFT_R | ModifierFlag::NONE, KeyCode::A, ModifierFlag::SHIFT_R // In this setting, we need decrease SHIFT_R only once. // So, we transform values of fromKey_. // // [before] // fromKey_.key : KeyCode::SHIFT_R // fromKey_.flags : ModifierFlag::SHIFT_R | ModifierFlag::NONE // // [after] // fromKey_.key : KeyCode::SHIFT_R // fromKey_.flags : ModifierFlag::NONE // // Note: we need to apply this transformation after calling fromkeychecker_.isFromKey. Flags fromFlags = fromKey_.flags; fromFlags.remove(fromKey_.key.getModifierFlag()); if (remapParams.params.ex_iskeydown) { FlagStatus::decrease(fromKey_.key.getModifierFlag()); } else { FlagStatus::increase(fromKey_.key.getModifierFlag()); } switch (toKeys_->size()) { case 0: break; case 1: { EventType newEventType = remapParams.params.ex_iskeydown ? EventType::DOWN : EventType::UP; ModifierFlag toModifierFlag = (*toKeys_)[0].key.getModifierFlag(); if (toModifierFlag == ModifierFlag::NONE && ! Handle_VK_CONFIG::is_VK_CONFIG_SYNC_KEYDOWNUP((*toKeys_)[0].key)) { // toKey FlagStatus::temporary_decrease(fromFlags); FlagStatus::temporary_increase((*toKeys_)[0].flags); } else { // toModifier or VK_CONFIG_SYNC_KEYDOWNUP_* if (toModifierFlag != ModifierFlag::NONE) { newEventType = EventType::MODIFY; } if (remapParams.params.ex_iskeydown) { FlagStatus::increase((*toKeys_)[0].flags | toModifierFlag); FlagStatus::decrease(fromFlags); } else { FlagStatus::decrease((*toKeys_)[0].flags | toModifierFlag); FlagStatus::increase(fromFlags); } } // ---------------------------------------- Params_KeyboardEventCallBack::auto_ptr ptr(Params_KeyboardEventCallBack::alloc(newEventType, FlagStatus::makeFlags(), (*toKeys_)[0].key, remapParams.params.keyboardType, remapParams.params.repeat)); if (! ptr) return false; Params_KeyboardEventCallBack& params = *ptr; if (remapParams.params.ex_iskeydown && ! isRepeatEnabled_) { KeyboardRepeat::cancel(); } else { KeyboardRepeat::set(params); } EventOutputQueue::FireKey::fire(params); break; } default: KeyCode lastKey = (*toKeys_)[toKeys_->size() - 1].key; Flags lastKeyFlags = (*toKeys_)[toKeys_->size() - 1].flags; ModifierFlag lastKeyModifierFlag = lastKey.getModifierFlag(); bool isLastKeyModifier = (lastKeyModifierFlag != ModifierFlag::NONE); bool isLastKeyLikeModifier = (Handle_VK_CONFIG::is_VK_CONFIG_SYNC_KEYDOWNUP(lastKey) || (Handle_VK_LAZY::getModifierFlag(lastKey) != ModifierFlag::NONE)); if (remapParams.params.ex_iskeydown) { KeyboardRepeat::cancel(); FlagStatus::temporary_decrease(fromFlags); size_t size = toKeys_->size(); // If the last key is modifier, we give it special treatment. // - Don't fire key repeat. // - Synchronous the key press status and the last modifier status. if (isLastKeyModifier || isLastKeyLikeModifier) { --size; } for (size_t i = 0; i < size; ++i) { FlagStatus::temporary_increase((*toKeys_)[i].flags); Flags f = FlagStatus::makeFlags(); KeyboardType keyboardType = remapParams.params.keyboardType; EventOutputQueue::FireKey::fire_downup(f, (*toKeys_)[i].key, keyboardType); KeyboardRepeat::primitive_add_downup(f, (*toKeys_)[i].key, keyboardType); FlagStatus::temporary_decrease((*toKeys_)[i].flags); } if (isLastKeyModifier || isLastKeyLikeModifier) { // restore temporary flag. FlagStatus::temporary_increase(fromFlags); FlagStatus::increase(lastKeyFlags | lastKeyModifierFlag); FlagStatus::decrease(fromFlags); EventOutputQueue::FireModifiers::fire(); if (isLastKeyLikeModifier) { Params_KeyboardEventCallBack::auto_ptr ptr(Params_KeyboardEventCallBack::alloc(EventType::DOWN, FlagStatus::makeFlags(), lastKey, remapParams.params.keyboardType, false)); if (ptr) { EventOutputQueue::FireKey::fire(*ptr); } } } if (isLastKeyModifier || isLastKeyLikeModifier) { KeyboardRepeat::cancel(); } else { if (isRepeatEnabled_) { keyboardRepeatID_ = KeyboardRepeat::primitive_start(); } else { keyboardRepeatID_ = -1; } } } else { if (isLastKeyModifier || isLastKeyLikeModifier) { FlagStatus::decrease(lastKeyFlags | lastKeyModifierFlag); FlagStatus::increase(fromFlags); EventOutputQueue::FireModifiers::fire(); if (isLastKeyLikeModifier) { Params_KeyboardEventCallBack::auto_ptr ptr(Params_KeyboardEventCallBack::alloc(EventType::UP, FlagStatus::makeFlags(), lastKey, remapParams.params.keyboardType, false)); if (ptr) { EventOutputQueue::FireKey::fire(*ptr); } } } else { if (KeyboardRepeat::getID() == keyboardRepeatID_) { KeyboardRepeat::cancel(); } } } break; } return true; } bool KeyToKey::call_remap_with_VK_PSEUDO_KEY(EventType eventType) { Params_KeyboardEventCallBack::auto_ptr ptr(Params_KeyboardEventCallBack::alloc(eventType, FlagStatus::makeFlags(), KeyCode::VK_PSEUDO_KEY, CommonData::getcurrent_keyboardType(), false)); if (! ptr) return false; Params_KeyboardEventCallBack& params = *ptr; RemapParams rp(params); return remap(rp); } } } <commit_msg>Improved KeyToKey around VK_LAZY<commit_after>#include "CommonData.hpp" #include "EventOutputQueue.hpp" #include "KeyToKey.hpp" #include "KeyboardRepeat.hpp" #include "VirtualKey.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace RemapFunc { KeyToKey::KeyToKey(void) : index_(0), keyboardRepeatID_(-1), isRepeatEnabled_(true) { toKeys_ = new Vector_PairKeyFlags(); } KeyToKey::~KeyToKey(void) { if (toKeys_) { delete toKeys_; } } void KeyToKey::add(unsigned int datatype, unsigned int newval) { if (! toKeys_) return; switch (datatype) { case BRIDGE_DATATYPE_KEYCODE: { switch (index_) { case 0: fromKey_.key = newval; break; default: toKeys_->push_back(PairKeyFlags(newval)); break; } ++index_; break; } case BRIDGE_DATATYPE_FLAGS: { switch (index_) { case 0: IOLOG_ERROR("Invalid KeyToKey::add\n"); break; case 1: fromKey_.flags = newval; break; default: if (! toKeys_->empty()) { (toKeys_->back()).flags = newval; } break; } break; } case BRIDGE_DATATYPE_OPTION: { if (Option::NOREPEAT == newval) { isRepeatEnabled_ = false; } else { IOLOG_ERROR("KeyToKey::add unknown option:%d\n", newval); } break; } default: IOLOG_ERROR("KeyToKey::add invalid datatype:%d\n", datatype); break; } } bool KeyToKey::remap(RemapParams& remapParams) { if (! toKeys_) return false; if (remapParams.isremapped) return false; if (! fromkeychecker_.isFromKey(remapParams.params.ex_iskeydown, remapParams.params.key, FlagStatus::makeFlags(), fromKey_.key, fromKey_.flags)) return false; remapParams.isremapped = true; // ------------------------------------------------------------ // handle EventType & Modifiers // Let's consider the following setting. // --KeyToKey-- KeyCode::SHIFT_R, ModifierFlag::SHIFT_R | ModifierFlag::NONE, KeyCode::A, ModifierFlag::SHIFT_R // In this setting, we need decrease SHIFT_R only once. // So, we transform values of fromKey_. // // [before] // fromKey_.key : KeyCode::SHIFT_R // fromKey_.flags : ModifierFlag::SHIFT_R | ModifierFlag::NONE // // [after] // fromKey_.key : KeyCode::SHIFT_R // fromKey_.flags : ModifierFlag::NONE // // Note: we need to apply this transformation after calling fromkeychecker_.isFromKey. Flags fromFlags = fromKey_.flags; fromFlags.remove(fromKey_.key.getModifierFlag()); if (remapParams.params.ex_iskeydown) { FlagStatus::decrease(fromKey_.key.getModifierFlag()); } else { FlagStatus::increase(fromKey_.key.getModifierFlag()); } switch (toKeys_->size()) { case 0: break; case 1: { EventType newEventType = remapParams.params.ex_iskeydown ? EventType::DOWN : EventType::UP; ModifierFlag toModifierFlag = (*toKeys_)[0].key.getModifierFlag(); if (toModifierFlag == ModifierFlag::NONE && ! Handle_VK_CONFIG::is_VK_CONFIG_SYNC_KEYDOWNUP((*toKeys_)[0].key)) { // toKey FlagStatus::temporary_decrease(fromFlags); FlagStatus::temporary_increase((*toKeys_)[0].flags); } else { // toModifier or VK_CONFIG_SYNC_KEYDOWNUP_* if (toModifierFlag != ModifierFlag::NONE) { newEventType = EventType::MODIFY; } if (remapParams.params.ex_iskeydown) { FlagStatus::increase((*toKeys_)[0].flags | toModifierFlag); FlagStatus::decrease(fromFlags); } else { FlagStatus::decrease((*toKeys_)[0].flags | toModifierFlag); FlagStatus::increase(fromFlags); } } // ---------------------------------------- Params_KeyboardEventCallBack::auto_ptr ptr(Params_KeyboardEventCallBack::alloc(newEventType, FlagStatus::makeFlags(), (*toKeys_)[0].key, remapParams.params.keyboardType, remapParams.params.repeat)); if (! ptr) return false; Params_KeyboardEventCallBack& params = *ptr; if (remapParams.params.ex_iskeydown && ! isRepeatEnabled_) { KeyboardRepeat::cancel(); } else { KeyboardRepeat::set(params); } EventOutputQueue::FireKey::fire(params); break; } default: KeyCode lastKey = (*toKeys_)[toKeys_->size() - 1].key; Flags lastKeyFlags = (*toKeys_)[toKeys_->size() - 1].flags; ModifierFlag lastKeyModifierFlag = lastKey.getModifierFlag(); bool isLastKeyModifier = (lastKeyModifierFlag != ModifierFlag::NONE); bool isLastKeyLikeModifier = (Handle_VK_CONFIG::is_VK_CONFIG_SYNC_KEYDOWNUP(lastKey) || (Handle_VK_LAZY::getModifierFlag(lastKey) != ModifierFlag::NONE)); if (remapParams.params.ex_iskeydown) { KeyboardRepeat::cancel(); FlagStatus::temporary_decrease(fromFlags); size_t size = toKeys_->size(); // If the last key is modifier, we give it special treatment. // - Don't fire key repeat. // - Synchronous the key press status and the last modifier status. if (isLastKeyModifier || isLastKeyLikeModifier) { --size; } for (size_t i = 0; i < size; ++i) { FlagStatus::temporary_increase((*toKeys_)[i].flags); Flags f = FlagStatus::makeFlags(); KeyboardType keyboardType = remapParams.params.keyboardType; EventOutputQueue::FireKey::fire_downup(f, (*toKeys_)[i].key, keyboardType); KeyboardRepeat::primitive_add_downup(f, (*toKeys_)[i].key, keyboardType); FlagStatus::temporary_decrease((*toKeys_)[i].flags); } if (isLastKeyModifier || isLastKeyLikeModifier) { // restore temporary flag. FlagStatus::temporary_increase(fromFlags); FlagStatus::increase(lastKeyFlags | lastKeyModifierFlag); FlagStatus::decrease(fromFlags); EventOutputQueue::FireModifiers::fire(); if (isLastKeyLikeModifier) { Params_KeyboardEventCallBack::auto_ptr ptr(Params_KeyboardEventCallBack::alloc(EventType::DOWN, FlagStatus::makeFlags(), lastKey, remapParams.params.keyboardType, false)); if (ptr) { EventOutputQueue::FireKey::fire(*ptr); } } } if (isLastKeyModifier || isLastKeyLikeModifier) { KeyboardRepeat::cancel(); } else { if (isRepeatEnabled_) { keyboardRepeatID_ = KeyboardRepeat::primitive_start(); } else { keyboardRepeatID_ = -1; } } } else { if (isLastKeyModifier || isLastKeyLikeModifier) { // For Lazy-Modifiers (KeyCode::VK_LAZY_*), // we need to handle these keys before restoring fromFlags, lastKeyFlags and lastKeyModifierFlag. // The unnecessary modifier events occur unless we do it. if (isLastKeyLikeModifier) { Params_KeyboardEventCallBack::auto_ptr ptr(Params_KeyboardEventCallBack::alloc(EventType::UP, FlagStatus::makeFlags(), lastKey, remapParams.params.keyboardType, false)); if (ptr) { EventOutputQueue::FireKey::fire(*ptr); } } FlagStatus::decrease(lastKeyFlags | lastKeyModifierFlag); FlagStatus::increase(fromFlags); EventOutputQueue::FireModifiers::fire(); } else { if (KeyboardRepeat::getID() == keyboardRepeatID_) { KeyboardRepeat::cancel(); } } } break; } return true; } bool KeyToKey::call_remap_with_VK_PSEUDO_KEY(EventType eventType) { Params_KeyboardEventCallBack::auto_ptr ptr(Params_KeyboardEventCallBack::alloc(eventType, FlagStatus::makeFlags(), KeyCode::VK_PSEUDO_KEY, CommonData::getcurrent_keyboardType(), false)); if (! ptr) return false; Params_KeyboardEventCallBack& params = *ptr; RemapParams rp(params); return remap(rp); } } } <|endoftext|>
<commit_before>/* * * Copyright 2019 gRPC 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 <grpc/support/port_platform.h> #include "src/core/lib/iomgr/logical_thread.h" namespace grpc_core { DebugOnlyTraceFlag grpc_logical_thread_trace(false, "logical_thread"); struct CallbackWrapper { CallbackWrapper(std::function<void()> cb, const grpc_core::DebugLocation& loc) : callback(std::move(cb)), location(loc) {} MultiProducerSingleConsumerQueue::Node mpscq_node; const std::function<void()> callback; const DebugLocation location; }; void LogicalThread::Run(std::function<void()> callback, const grpc_core::DebugLocation& location) { if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, "LogicalThread::Run() %p Scheduling callback [%s:%d]", this, location.file(), location.line()); } const size_t prev_size = size_.FetchAdd(1); if (prev_size == 0) { // There is no other closure executing right now on this logical thread. // Execute this closure immediately. if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, " Executing immediately"); } callback(); // Loan this thread to the logical thread and drain the queue. DrainQueue(); } else { CallbackWrapper* cb_wrapper = new CallbackWrapper(std::move(callback), location); // There already are closures executing on this logical thread. Simply add // this closure to the queue. if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, " Scheduling on queue : item %p", cb_wrapper); } queue_.Push(&cb_wrapper->mpscq_node); } } // The thread that calls this loans itself to the logical thread so as to // execute all the scheduled callback. This is called from within // LogicalThread::Run() after executing a callback immediately, and hence size_ // is atleast 1. void LogicalThread::DrainQueue() { while (true) { if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, "LogicalThread::DrainQueue() %p", this); } size_t prev_size = size_.FetchSub(1); // prev_size should be atleast 1 since GPR_DEBUG_ASSERT(prev_size >= 1); if (prev_size == 1) { if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, " Queue Drained"); } break; } // There is atleast one callback on the queue. Pop the callback from the // queue and execute it. CallbackWrapper* cb_wrapper = nullptr; bool empty_unused; while ((cb_wrapper = reinterpret_cast<CallbackWrapper*>( queue_.PopAndCheckEnd(&empty_unused))) == nullptr) { // This can happen either due to a race condition within the mpscq // implementation or because of a race with Run() if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, " Queue returned nullptr, trying again"); } } #ifndef NDEBUG if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, " Running item %p : callback scheduled at [%s:%d]", cb_wrapper, cb_wrapper->location.file(), cb_wrapper->location.line()); } #endif cb_wrapper->callback(); delete cb_wrapper; } } } // namespace grpc_core <commit_msg>Clang format<commit_after>/* * * Copyright 2019 gRPC 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 <grpc/support/port_platform.h> #include "src/core/lib/iomgr/logical_thread.h" namespace grpc_core { DebugOnlyTraceFlag grpc_logical_thread_trace(false, "logical_thread"); struct CallbackWrapper { CallbackWrapper(std::function<void()> cb, const grpc_core::DebugLocation& loc) : callback(std::move(cb)), location(loc) {} MultiProducerSingleConsumerQueue::Node mpscq_node; const std::function<void()> callback; const DebugLocation location; }; void LogicalThread::Run(std::function<void()> callback, const grpc_core::DebugLocation& location) { if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, "LogicalThread::Run() %p Scheduling callback [%s:%d]", this, location.file(), location.line()); } const size_t prev_size = size_.FetchAdd(1); if (prev_size == 0) { // There is no other closure executing right now on this logical thread. // Execute this closure immediately. if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, " Executing immediately"); } callback(); // Loan this thread to the logical thread and drain the queue. DrainQueue(); } else { CallbackWrapper* cb_wrapper = new CallbackWrapper(std::move(callback), location); // There already are closures executing on this logical thread. Simply add // this closure to the queue. if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, " Scheduling on queue : item %p", cb_wrapper); } queue_.Push(&cb_wrapper->mpscq_node); } } // The thread that calls this loans itself to the logical thread so as to // execute all the scheduled callback. This is called from within // LogicalThread::Run() after executing a callback immediately, and hence size_ // is atleast 1. void LogicalThread::DrainQueue() { while (true) { if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, "LogicalThread::DrainQueue() %p", this); } size_t prev_size = size_.FetchSub(1); // prev_size should be atleast 1 since GPR_DEBUG_ASSERT(prev_size >= 1); if (prev_size == 1) { if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, " Queue Drained"); } break; } // There is atleast one callback on the queue. Pop the callback from the // queue and execute it. CallbackWrapper* cb_wrapper = nullptr; bool empty_unused; while ((cb_wrapper = reinterpret_cast<CallbackWrapper*>( queue_.PopAndCheckEnd(&empty_unused))) == nullptr) { // This can happen either due to a race condition within the mpscq // implementation or because of a race with Run() if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, " Queue returned nullptr, trying again"); } } #ifndef NDEBUG if (GRPC_TRACE_FLAG_ENABLED(grpc_logical_thread_trace)) { gpr_log(GPR_INFO, " Running item %p : callback scheduled at [%s:%d]", cb_wrapper, cb_wrapper->location.file(), cb_wrapper->location.line()); } #endif cb_wrapper->callback(); delete cb_wrapper; } } } // namespace grpc_core <|endoftext|>
<commit_before>#include "benchmarks/symplectic_partitioned_runge_kutta_integrator.hpp" // .\Release\benchmarks_tests.exe --benchmark_repetitions=5 --benchmark_min_time=300 // NOLINT(whitespace/line_length) // Benchmarking on 1 X 3310 MHz CPU // 2014/05/30-20:51:41 // Benchmark Time(ns) CPU(ns) Iterations // ------------------------------------------------------------------ // BM_SolveHarmonicOscillator 1388241978 1227819635 51 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) // BM_SolveHarmonicOscillator 1220045434 1215559792 50 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) // BM_SolveHarmonicOscillator 1214497281 1212439772 50 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) // BM_SolveHarmonicOscillator 1226465770 1223047840 50 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) // BM_SolveHarmonicOscillator 1231751867 1225231854 50 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) // BM_SolveHarmonicOscillator_mean 1256726528 1220847667 251 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) // BM_SolveHarmonicOscillator_stddev 66665752 5858502 251 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) #define GLOG_NO_ABBREVIATED_SEVERITIES #include <algorithm> // Must come last to avoid conflicts when defining the CHECK macros. #include "benchmark/benchmark.h" using principia::integrators::SPRKIntegrator; namespace principia { namespace benchmarks { void SolveHarmonicOscillatorAndComputeError(benchmark::State* state, double* q_error, double* p_error) { SPRKIntegrator::Solution solution; SolveHarmonicOscillator(&solution); state->PauseTiming(); *q_error = 0; *p_error = 0; for (size_t i = 0; i < solution.time.quantities.size(); ++i) { *q_error = std::max(*q_error, std::abs(solution.position[0].quantities[i] - std::cos(solution.time.quantities[i]))); *p_error = std::max(*p_error, std::abs(solution.momentum[0].quantities[i] + std::sin(solution.time.quantities[i]))); } state->ResumeTiming(); } static void BM_SolveHarmonicOscillator( benchmark::State& state) { // NOLINT(runtime/references) double q_error; double p_error; while (state.KeepRunning()) { SolveHarmonicOscillatorAndComputeError(&state, &q_error, &p_error); } std::stringstream ss; ss << q_error << ", " << p_error; state.SetLabel(ss.str()); } BENCHMARK(BM_SolveHarmonicOscillator); } // namespace benchmarks } // namespace principia <commit_msg>Benchmark results.<commit_after>#include "benchmarks/symplectic_partitioned_runge_kutta_integrator.hpp" // .\Release\benchmarks.exe --benchmark_repetitions=5 --benchmark_min_time=300 // NOLINT(whitespace/line_length) // Benchmarking on 1 X 3310 MHz CPU // 2014/06/01-10:56:16 // Benchmark Time(ns) CPU(ns) Iterations // ------------------------------------------------------------------ // BM_SolveHarmonicOscillator 1158462428 1157407419 52 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) // BM_SolveHarmonicOscillator 1164918290 1163707460 52 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) // BM_SolveHarmonicOscillator 1161977190 1163107456 52 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) // BM_SolveHarmonicOscillator 1161909218 1160707440 52 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) // BM_SolveHarmonicOscillator 1163742772 1162207450 52 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) // BM_SolveHarmonicOscillator_mean 1162201980 1161427445 260 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) // BM_SolveHarmonicOscillator_stddev 2185080 2249814 260 1.37019e-013, 1.37057e-013 // NOLINT(whitespace/line_length) #define GLOG_NO_ABBREVIATED_SEVERITIES #include <algorithm> // Must come last to avoid conflicts when defining the CHECK macros. #include "benchmark/benchmark.h" using principia::integrators::SPRKIntegrator; namespace principia { namespace benchmarks { void SolveHarmonicOscillatorAndComputeError(benchmark::State* state, double* q_error, double* p_error) { SPRKIntegrator::Solution solution; SolveHarmonicOscillator(&solution); state->PauseTiming(); *q_error = 0; *p_error = 0; for (size_t i = 0; i < solution.time.quantities.size(); ++i) { *q_error = std::max(*q_error, std::abs(solution.position[0].quantities[i] - std::cos(solution.time.quantities[i]))); *p_error = std::max(*p_error, std::abs(solution.momentum[0].quantities[i] + std::sin(solution.time.quantities[i]))); } state->ResumeTiming(); } static void BM_SolveHarmonicOscillator( benchmark::State& state) { // NOLINT(runtime/references) double q_error; double p_error; while (state.KeepRunning()) { SolveHarmonicOscillatorAndComputeError(&state, &q_error, &p_error); } std::stringstream ss; ss << q_error << ", " << p_error; state.SetLabel(ss.str()); } BENCHMARK(BM_SolveHarmonicOscillator); } // namespace benchmarks } // namespace principia <|endoftext|>
<commit_before> #include "DateAndTimeHandler.h" #include "instantsearch/DateTime.h" #include <iostream> #include <boost/regex.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <cstdlib> #include <util/Assert.h> namespace srch2 { namespace instantsearch { /* * Example: * timeString = 02/03/2000 * output will be the number of seconds from 01/01/1970 to timeString. * The format of this string must match one of the followings : * "%H:%M:%S", "%m/%d/%Y", "%Y-%m-%d %H:%M:%S", "%Y%m%d%H%M%S", "%Y%m%d%H%M", "%Y%m%d" * or * "NOW" >> which will be interpreted as the current time. */ time_t DateAndTimeHandler::convertDateTimeStringToSecondsFromEpoch(const string & timeString) { // 1. first check with the known point of time formats we have bt::ptime pt; for(size_t i=0; i<localeFormatsPointOfTime; ++i) { boost::regex regexEngine(regexInputsPointOfTime[i]); boost::smatch whatIsMatched; if(boost::regex_match(timeString, whatIsMatched, regexEngine, boost::match_extra)) { // This piece of code is taken from : // http://stackoverflow.com/questions/2612343/basic-boost-date-time-input-format-question std::istringstream is(timeString); is.imbue(localeInputsPointOfTime[i]); is >> pt; if(pt != bt::not_a_date_time){ return convertPtimeToSecondsFromEpoch(pt); } } } // 4. check to see if it is a time relative to NOW (right now we only support now) if(timeString.compare("NOW") == 0){ // it's NOW return convertPtimeToSecondsFromEpoch(boost::posix_time::second_clock::local_time()); } return -1; } /* * this function prints the date determined by secondsFromEpoch seconds from 1/1/1970 * in a proper human readable format. */ string DateAndTimeHandler::convertSecondsFromEpochToDateTimeString(register const time_t * secondsFromEpoch){ ostringstream oss; boost::posix_time::ptime pTime = boost::posix_time::from_time_t(*secondsFromEpoch); oss << pTime; return oss.str() ; } /* * This functions verifies whether the input string is compatible with time formats that we have or not. */ bool DateAndTimeHandler::verifyDateTimeString(const string & timeStringInput, DateTimeType dateTimeType){ string timeString = boost::to_upper_copy(timeStringInput); switch (dateTimeType) { // timeString == NOW case DateTimeTypeNow: if(timeString.compare("NOW") == 0){ return true; }else{ return false; } // timeString exmaple : 02/03/2001 12:23:34 case DateTimeTypePointOfTime:{ for(size_t i=0; i<localeFormatsPointOfTime; ++i){ boost::regex regexEngine(regexInputsPointOfTime[i]); boost::smatch whatIsMatched; if(boost::regex_match(timeString, whatIsMatched, regexEngine, boost::match_extra)){ return true; } } return false; } // timeString example : 2YEARS or 12:01:01 (12 hours and 1 minutes and 1 seconds) case DateTimeTypeDurationOfTime:{ // 1. first see if it's a known duration format for(size_t i=0; i<localeFormatsDurationOfTime; ++i){ boost::regex regexEngine(regexInputsDurationOfTime[i]); boost::smatch whatIsMatched; if(boost::regex_match(timeString, whatIsMatched, regexEngine, boost::match_extra)){ return true; } } // 2. second check to see if it is a constant if(std::find(DURATION_OF_TIME_CONSTANTS.begin() , DURATION_OF_TIME_CONSTANTS.end() , timeString) != DURATION_OF_TIME_CONSTANTS.end()){ return true; } // 3. third, check to see if it's a combination of number and constant // first make the regex string // The regex will be like "^(\\d*SECOND|\\d*SECONDS|\\d*MINUTE|\d*MINUTES)$" // which will be matched with any string like 23DAYS string format = "^("; for(vector<string>::const_iterator cons = DURATION_OF_TIME_CONSTANTS.begin() ; cons != DURATION_OF_TIME_CONSTANTS.end() ; ++cons){ format+= "\\d*"+*cons + "|"; } format += ")$"; boost::regex regexEngine2(format); boost::smatch whatIsMatched2; if(boost::regex_match(timeString, whatIsMatched2, regexEngine2, boost::match_extra)){ // string matches this pattern return true; } return false; } default: return false; } } /* * This function converts a ptime (boost date/time object) to the number of seconds * from 01/01/1970. */ time_t DateAndTimeHandler::convertPtimeToSecondsFromEpoch(boost::posix_time::ptime t){ static boost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1)); return (t-epoch).ticks() / boost::posix_time::time_duration::ticks_per_second(); } /* * This function converts the number of seconds from 01/01/1970 to a ptime * (boost library date/time object) object. */ boost::posix_time::ptime DateAndTimeHandler::convertSecondsFromEpochToPTime(time_t t){ return boost::posix_time::from_time_t(t); } /* * In this function the string should be parsed and TimeDuration object must be built */ TimeDuration DateAndTimeHandler::convertDurationTimeStringToTimeDurationObject(const string & timeStringInput){ string timeString = boost::to_upper_copy(timeStringInput); // 1. if it is a constant, parse and save as a TimeDuration object vector<string>::const_iterator constantIter = std::find(DURATION_OF_TIME_CONSTANTS.begin() , DURATION_OF_TIME_CONSTANTS.end() , timeString); if(constantIter != DURATION_OF_TIME_CONSTANTS.end()){ timeString = "1"+timeStringInput; } // 2. if it's a combination of number and constant // first make the regex string string format = "^("; for(vector<string>::const_iterator cons = DURATION_OF_TIME_CONSTANTS.begin() ; cons != DURATION_OF_TIME_CONSTANTS.end() ; ++cons){ format+= "\\d*"+*cons + "|"; } format += ")$"; boost::regex regexEngine2(format); boost::smatch whatIsMatched2; if(boost::regex_match(timeString, whatIsMatched2, regexEngine2, boost::match_extra)){ // string matches this pattern for(vector<string>::const_iterator cons = DURATION_OF_TIME_CONSTANTS.begin() ; cons != DURATION_OF_TIME_CONSTANTS.end() ; ++cons){ string constant = *cons; /* * Example : 12WEEKS or 1SECOND */ if(timeString.find(constant) != std::string::npos){ int numberOfThisUnit = boost::lexical_cast<int>(timeString.substr(0,timeString.size() - constant.size())); if(constant.compare("SECOND") == 0 || constant.compare("SECONDS") == 0 ){ TimeDuration td; td.secondMinuteHourDuration = boost::posix_time::seconds(numberOfThisUnit); return td; } if(constant.compare("MINUTE") == 0 || constant.compare("MINUTES") == 0 ){ TimeDuration td; td.secondMinuteHourDuration = boost::posix_time::minutes(numberOfThisUnit); return td; } if(constant.compare("HOUR") == 0 || constant.compare("HOURS") == 0 ){ TimeDuration td; td.secondMinuteHourDuration = boost::posix_time::hours(numberOfThisUnit); return td; } if(constant.compare("DAY") == 0 || constant.compare("DAYS") == 0 ){ TimeDuration td; td.dayWeekDuration = boost::gregorian::days(numberOfThisUnit); return td; } if(constant.compare("WEEK") == 0 || constant.compare("WEEKS") == 0 ){ TimeDuration td; td.dayWeekDuration = boost::gregorian::weeks(numberOfThisUnit); return td; } if(constant.compare("MONTH") == 0 || constant.compare("MONTHS") == 0 ){ TimeDuration td; td.monthDuration = boost::gregorian::months(numberOfThisUnit); return td; } if(constant.compare("YEAR") == 0 || constant.compare("YEARS") == 0 ){ TimeDuration td; td.yearDuration = boost::gregorian::years(numberOfThisUnit); return td; } } } } // 3. if it's a known duration format // Example : 12:13:14 meaning a gap of 12 hours and 13 minutes and 14 seconds for(size_t i=0; i<localeFormatsDurationOfTime; ++i){ boost::regex regexEngine(regexInputsDurationOfTime[i]); boost::smatch whatIsMatched; if(boost::regex_match(timeString, whatIsMatched, regexEngine, boost::match_extra)){ TimeDuration td; td.secondMinuteHourDuration = boost::posix_time::duration_from_string(timeString); return td; } } TimeDuration td; return td; } vector<string> DateAndTimeHandler::initializeConstants(){ vector<string> constants; constants.push_back("SECOND"); constants.push_back("MINUTE"); constants.push_back("HOUR"); constants.push_back("DAY"); constants.push_back("WEEK"); constants.push_back("MONTH"); constants.push_back("YEAR"); constants.push_back("SECONDS"); constants.push_back("MINUTES"); constants.push_back("HOURS"); constants.push_back("DAYS"); constants.push_back("WEEKS"); constants.push_back("MONTHS"); constants.push_back("YEARS"); return constants; } // This regex array is parallel to localeInputsDurationOfTime and that variable is a good // explanation for this array const string DateAndTimeHandler::regexInputsDurationOfTime[] = { "^\\d{2}:\\d{2}:\\d{2}$" }; const locale DateAndTimeHandler::localeInputsDurationOfTime[] ={ locale(locale::classic(), new time_input_facet("%H:%M:%S")) }; const size_t DateAndTimeHandler::localeFormatsDurationOfTime = sizeof(DateAndTimeHandler::localeInputsDurationOfTime)/sizeof(DateAndTimeHandler::localeInputsDurationOfTime[0]); // This regex array is parallel to localeInputsPointOfTime and that variable is a good // explanation for this array const string DateAndTimeHandler::regexInputsPointOfTime[] = { "^\\d{2}:\\d{2}:\\d{2}$", "^\\d{2}/\\d{2}/\\d{4}$", "^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}$", "^\\d{4}\\d{2}\\d{2}\\s\\d{2}\\d{2}\\d{2}$", "^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}$", "^\\d{4}-\\d{2}-\\d{2}$" }; const locale DateAndTimeHandler::localeInputsPointOfTime[] ={ locale(locale::classic(), new time_input_facet("%H:%M:%S")), locale(locale::classic(), new time_input_facet("%m/%d/%Y")), locale(locale::classic(), new time_input_facet("%Y-%m-%d %H:%M:%S")), locale(locale::classic(), new time_input_facet("%Y%m%d%H%M%S")), locale(locale::classic(), new time_input_facet("%Y%m%d%H%M")), locale(locale::classic(), new time_input_facet("%Y%m%d")) }; const size_t DateAndTimeHandler::localeFormatsPointOfTime = sizeof(DateAndTimeHandler::localeInputsPointOfTime)/sizeof(DateAndTimeHandler::localeInputsPointOfTime[0]); const vector<string> DateAndTimeHandler::DURATION_OF_TIME_CONSTANTS = DateAndTimeHandler::initializeConstants(); /* * This function implements operator + for (TimeDuration + ptime) * This means if TimeDuration is on left and ptime is on right this function * returns a ptime which is equal to input + TimeDuration */ boost::posix_time::ptime TimeDuration::operator+(const boost::posix_time::ptime & pTime) const{ boost::posix_time::ptime timeResult; timeResult = pTime; timeResult = timeResult + secondMinuteHourDuration; timeResult = timeResult + dayWeekDuration; timeResult = timeResult + monthDuration; timeResult = timeResult + yearDuration; return timeResult; } /* * This function implements operator + for (TimeDuration + long) * This means if TimeDuration is on left and ling (number of seconds from epoch) is on right this function * returns a ptime which is equal to input + TimeDuration */ long TimeDuration::operator+(const long pTime) const{ boost::posix_time::ptime pTimeObj = DateAndTimeHandler::convertSecondsFromEpochToPTime(pTime); return DateAndTimeHandler::convertPtimeToSecondsFromEpoch(*this + pTimeObj); // it uses the other implementation for operator + } /* * This function adds two TimeDuration objects to make a larger interval. */ TimeDuration TimeDuration::operator+(const TimeDuration & timeDuration) const{ TimeDuration result; result.secondMinuteHourDuration = this->secondMinuteHourDuration + timeDuration.secondMinuteHourDuration; result.dayWeekDuration = this->dayWeekDuration + timeDuration.dayWeekDuration; result.monthDuration = this->monthDuration + timeDuration.monthDuration; result.yearDuration = this->yearDuration + timeDuration.yearDuration; return result; } string TimeDuration::toString() const{ ASSERT(false); return "WARNING!!!!"; } } } <commit_msg>A bug related to faceted search gap is fixed. String comparison was not precise which resulted in segmentation fault.<commit_after> #include "DateAndTimeHandler.h" #include "instantsearch/DateTime.h" #include <iostream> #include <boost/regex.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <cstdlib> #include <util/Assert.h> namespace srch2 { namespace instantsearch { /* * Example: * timeString = 02/03/2000 * output will be the number of seconds from 01/01/1970 to timeString. * The format of this string must match one of the followings : * "%H:%M:%S", "%m/%d/%Y", "%Y-%m-%d %H:%M:%S", "%Y%m%d%H%M%S", "%Y%m%d%H%M", "%Y%m%d" * or * "NOW" >> which will be interpreted as the current time. */ time_t DateAndTimeHandler::convertDateTimeStringToSecondsFromEpoch(const string & timeString) { // 1. first check with the known point of time formats we have bt::ptime pt; for(size_t i=0; i<localeFormatsPointOfTime; ++i) { boost::regex regexEngine(regexInputsPointOfTime[i]); boost::smatch whatIsMatched; if(boost::regex_match(timeString, whatIsMatched, regexEngine, boost::match_extra)) { // This piece of code is taken from : // http://stackoverflow.com/questions/2612343/basic-boost-date-time-input-format-question std::istringstream is(timeString); is.imbue(localeInputsPointOfTime[i]); is >> pt; if(pt != bt::not_a_date_time){ return convertPtimeToSecondsFromEpoch(pt); } } } // 4. check to see if it is a time relative to NOW (right now we only support now) if(timeString.compare("NOW") == 0){ // it's NOW return convertPtimeToSecondsFromEpoch(boost::posix_time::second_clock::local_time()); } return -1; } /* * this function prints the date determined by secondsFromEpoch seconds from 1/1/1970 * in a proper human readable format. */ string DateAndTimeHandler::convertSecondsFromEpochToDateTimeString(register const time_t * secondsFromEpoch){ ostringstream oss; boost::posix_time::ptime pTime = boost::posix_time::from_time_t(*secondsFromEpoch); oss << pTime; return oss.str() ; } /* * This functions verifies whether the input string is compatible with time formats that we have or not. */ bool DateAndTimeHandler::verifyDateTimeString(const string & timeStringInput, DateTimeType dateTimeType){ string timeString = boost::to_upper_copy(timeStringInput); switch (dateTimeType) { // timeString == NOW case DateTimeTypeNow: if(timeString.compare("NOW") == 0){ return true; }else{ return false; } // timeString exmaple : 02/03/2001 12:23:34 case DateTimeTypePointOfTime:{ for(size_t i=0; i<localeFormatsPointOfTime; ++i){ boost::regex regexEngine(regexInputsPointOfTime[i]); boost::smatch whatIsMatched; if(boost::regex_match(timeString, whatIsMatched, regexEngine, boost::match_extra)){ return true; } } return false; } // timeString example : 2YEARS or 12:01:01 (12 hours and 1 minutes and 1 seconds) case DateTimeTypeDurationOfTime:{ // 1. first see if it's a known duration format for(size_t i=0; i<localeFormatsDurationOfTime; ++i){ boost::regex regexEngine(regexInputsDurationOfTime[i]); boost::smatch whatIsMatched; if(boost::regex_match(timeString, whatIsMatched, regexEngine, boost::match_extra)){ return true; } } // 2. second check to see if it is a constant if(std::find(DURATION_OF_TIME_CONSTANTS.begin() , DURATION_OF_TIME_CONSTANTS.end() , timeString) != DURATION_OF_TIME_CONSTANTS.end()){ return true; } // 3. third, check to see if it's a combination of number and constant // first make the regex string // The regex will be like "^(\\d*SECOND|\\d*SECONDS|\\d*MINUTE|\d*MINUTES)$" // which will be matched with any string like 23DAYS string format = "^("; for(vector<string>::const_iterator cons = DURATION_OF_TIME_CONSTANTS.begin() ; cons != DURATION_OF_TIME_CONSTANTS.end() ; ++cons){ format+= "\\d*"+*cons + "|"; } format += ")$"; boost::regex regexEngine2(format); boost::smatch whatIsMatched2; if(boost::regex_match(timeString, whatIsMatched2, regexEngine2, boost::match_extra)){ // string matches this pattern return true; } return false; } default: return false; } } /* * This function converts a ptime (boost date/time object) to the number of seconds * from 01/01/1970. */ time_t DateAndTimeHandler::convertPtimeToSecondsFromEpoch(boost::posix_time::ptime t){ static boost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1)); return (t-epoch).ticks() / boost::posix_time::time_duration::ticks_per_second(); } /* * This function converts the number of seconds from 01/01/1970 to a ptime * (boost library date/time object) object. */ boost::posix_time::ptime DateAndTimeHandler::convertSecondsFromEpochToPTime(time_t t){ return boost::posix_time::from_time_t(t); } /* * In this function the string should be parsed and TimeDuration object must be built */ TimeDuration DateAndTimeHandler::convertDurationTimeStringToTimeDurationObject(const string & timeStringInput){ string timeString = boost::to_upper_copy(timeStringInput); // 1. if it is a constant, parse and save as a TimeDuration object vector<string>::const_iterator constantIter = std::find(DURATION_OF_TIME_CONSTANTS.begin() , DURATION_OF_TIME_CONSTANTS.end() , timeString); if(constantIter != DURATION_OF_TIME_CONSTANTS.end()){ timeString = "1"+timeStringInput; } // 2. if it's a combination of number and constant // first make the regex string string format = "^("; for(vector<string>::const_iterator cons = DURATION_OF_TIME_CONSTANTS.begin() ; cons != DURATION_OF_TIME_CONSTANTS.end() ; ++cons){ format+= "\\d*"+*cons + "|"; } format += ")$"; boost::regex regexEngine2(format); boost::smatch whatIsMatched2; if(boost::regex_match(timeString, whatIsMatched2, regexEngine2, boost::match_extra)){ // string matches this pattern for(vector<string>::const_iterator cons = DURATION_OF_TIME_CONSTANTS.begin() ; cons != DURATION_OF_TIME_CONSTANTS.end() ; ++cons){ string constant = *cons; /* * Example : 12WEEKS or 1SECOND */ if(timeString.length() > constant.length() && 0 == timeString.compare (timeString.length() - constant.length(), constant.length(), constant)){ int numberOfThisUnit = boost::lexical_cast<int>(timeString.substr(0,timeString.size() - constant.size())); if(constant.compare("SECOND") == 0 || constant.compare("SECONDS") == 0 ){ TimeDuration td; td.secondMinuteHourDuration = boost::posix_time::seconds(numberOfThisUnit); return td; } if(constant.compare("MINUTE") == 0 || constant.compare("MINUTES") == 0 ){ TimeDuration td; td.secondMinuteHourDuration = boost::posix_time::minutes(numberOfThisUnit); return td; } if(constant.compare("HOUR") == 0 || constant.compare("HOURS") == 0 ){ TimeDuration td; td.secondMinuteHourDuration = boost::posix_time::hours(numberOfThisUnit); return td; } if(constant.compare("DAY") == 0 || constant.compare("DAYS") == 0 ){ TimeDuration td; td.dayWeekDuration = boost::gregorian::days(numberOfThisUnit); return td; } if(constant.compare("WEEK") == 0 || constant.compare("WEEKS") == 0 ){ TimeDuration td; td.dayWeekDuration = boost::gregorian::weeks(numberOfThisUnit); return td; } if(constant.compare("MONTH") == 0 || constant.compare("MONTHS") == 0 ){ TimeDuration td; td.monthDuration = boost::gregorian::months(numberOfThisUnit); return td; } if(constant.compare("YEAR") == 0 || constant.compare("YEARS") == 0 ){ TimeDuration td; td.yearDuration = boost::gregorian::years(numberOfThisUnit); return td; } } } } // 3. if it's a known duration format // Example : 12:13:14 meaning a gap of 12 hours and 13 minutes and 14 seconds for(size_t i=0; i<localeFormatsDurationOfTime; ++i){ boost::regex regexEngine(regexInputsDurationOfTime[i]); boost::smatch whatIsMatched; if(boost::regex_match(timeString, whatIsMatched, regexEngine, boost::match_extra)){ TimeDuration td; td.secondMinuteHourDuration = boost::posix_time::duration_from_string(timeString); return td; } } TimeDuration td; return td; } vector<string> DateAndTimeHandler::initializeConstants(){ vector<string> constants; constants.push_back("SECOND"); constants.push_back("MINUTE"); constants.push_back("HOUR"); constants.push_back("DAY"); constants.push_back("WEEK"); constants.push_back("MONTH"); constants.push_back("YEAR"); constants.push_back("SECONDS"); constants.push_back("MINUTES"); constants.push_back("HOURS"); constants.push_back("DAYS"); constants.push_back("WEEKS"); constants.push_back("MONTHS"); constants.push_back("YEARS"); return constants; } // This regex array is parallel to localeInputsDurationOfTime and that variable is a good // explanation for this array const string DateAndTimeHandler::regexInputsDurationOfTime[] = { "^\\d{2}:\\d{2}:\\d{2}$" }; const locale DateAndTimeHandler::localeInputsDurationOfTime[] ={ locale(locale::classic(), new time_input_facet("%H:%M:%S")) }; const size_t DateAndTimeHandler::localeFormatsDurationOfTime = sizeof(DateAndTimeHandler::localeInputsDurationOfTime)/sizeof(DateAndTimeHandler::localeInputsDurationOfTime[0]); // This regex array is parallel to localeInputsPointOfTime and that variable is a good // explanation for this array const string DateAndTimeHandler::regexInputsPointOfTime[] = { "^\\d{2}:\\d{2}:\\d{2}$", "^\\d{2}/\\d{2}/\\d{4}$", "^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}$", "^\\d{4}\\d{2}\\d{2}\\s\\d{2}\\d{2}\\d{2}$", "^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}$", "^\\d{4}-\\d{2}-\\d{2}$" }; const locale DateAndTimeHandler::localeInputsPointOfTime[] ={ locale(locale::classic(), new time_input_facet("%H:%M:%S")), locale(locale::classic(), new time_input_facet("%m/%d/%Y")), locale(locale::classic(), new time_input_facet("%Y-%m-%d %H:%M:%S")), locale(locale::classic(), new time_input_facet("%Y%m%d%H%M%S")), locale(locale::classic(), new time_input_facet("%Y%m%d%H%M")), locale(locale::classic(), new time_input_facet("%Y%m%d")) }; const size_t DateAndTimeHandler::localeFormatsPointOfTime = sizeof(DateAndTimeHandler::localeInputsPointOfTime)/sizeof(DateAndTimeHandler::localeInputsPointOfTime[0]); const vector<string> DateAndTimeHandler::DURATION_OF_TIME_CONSTANTS = DateAndTimeHandler::initializeConstants(); /* * This function implements operator + for (TimeDuration + ptime) * This means if TimeDuration is on left and ptime is on right this function * returns a ptime which is equal to input + TimeDuration */ boost::posix_time::ptime TimeDuration::operator+(const boost::posix_time::ptime & pTime) const{ boost::posix_time::ptime timeResult; timeResult = pTime; timeResult = timeResult + secondMinuteHourDuration; timeResult = timeResult + dayWeekDuration; timeResult = timeResult + monthDuration; timeResult = timeResult + yearDuration; return timeResult; } /* * This function implements operator + for (TimeDuration + long) * This means if TimeDuration is on left and ling (number of seconds from epoch) is on right this function * returns a ptime which is equal to input + TimeDuration */ long TimeDuration::operator+(const long pTime) const{ boost::posix_time::ptime pTimeObj = DateAndTimeHandler::convertSecondsFromEpochToPTime(pTime); return DateAndTimeHandler::convertPtimeToSecondsFromEpoch(*this + pTimeObj); // it uses the other implementation for operator + } /* * This function adds two TimeDuration objects to make a larger interval. */ TimeDuration TimeDuration::operator+(const TimeDuration & timeDuration) const{ TimeDuration result; result.secondMinuteHourDuration = this->secondMinuteHourDuration + timeDuration.secondMinuteHourDuration; result.dayWeekDuration = this->dayWeekDuration + timeDuration.dayWeekDuration; result.monthDuration = this->monthDuration + timeDuration.monthDuration; result.yearDuration = this->yearDuration + timeDuration.yearDuration; return result; } string TimeDuration::toString() const{ ASSERT(false); return "WARNING!!!!"; } } } <|endoftext|>
<commit_before>/* * FastMETISParser.cpp * * Created on: 04.10.2013 * Author: cls */ #include "FastMETISParserDouble.h" #include <fstream> namespace NetworKit { FastMETISParserDouble::FastMETISParserDouble() { // TODO Auto-generated constructor stub } FastMETISParserDouble::~FastMETISParserDouble() { // TODO Auto-generated destructor stub } static inline uint64_t fast_string_to_integer(std::string::iterator it, const std::string::iterator& end) { uint64_t val = *it - '0'; // works on ASCII code points ++it; while (it != end) { val *= 10; val += *it - '0'; ++it; } return val; } static inline double fast_string_to_double(std::string::iterator it, const std::string::iterator& end) { double val = 0.0; bool negative = false; if (*it == '-') { negative = true; ++it; } while (*it >= '0' && *it <= '9' && it != end) { //it != end val = (val*10.0) + (*it - '0'); ++it; } if (*it == '.' && it != end) { double afterComma = 0.0; int exp = 0; ++it; while (*it >= '0' && *it <= '9' && it != end) { //it != end afterComma = (afterComma*10.0) + (*it - '0'); ++exp; ++it; } val += afterComma / std::pow(10.0, exp); } if (negative) { val = -val; } return val; } static inline std::tuple<count, count, int> parseHeader(const std::string& header) { count n; count m; int flag; std::vector<std::string> parts = Aux::StringTools::split(header); n = std::stoi(parts[0]); m = std::stoi(parts[1]); if (parts.size() > 2) { flag = std::stoi(parts[2]); } else { flag = 0; } return std::make_tuple(n, m, flag); } NetworKit::Graph FastMETISParserDouble::parse(const std::string& path) { std::ifstream stream(path); std::string line; std::getline(stream, line); // get header count n; count m; int flag; // weight flag std::tie(n, m, flag) = parseHeader(line); bool weighted = flag % 10; Graph G(n, weighted); node u = 0; // TODO: handle comment lines if (flag == 0) { DEBUG("reading unweighted graph"); // unweighted edges while (std::getline(stream, line)) { if (line.empty()) { continue; } auto it1 = line.begin(); auto end = line.end(); auto it2 = std::find(it1, end, ' '); if (line.back() == ' ') { // if line ends with one white space, do this trick... --end; } while (true) { node v = (fast_string_to_integer(it1, it2) - 1); if (u < v) { G.addEdge(u, v); } if (it2 == end) { break; } ++it2; it1 = it2; it2 = std::find(it1, end, ' '); } ++u; // next node } } else if (flag == 1) { DEBUG("reading weighted graph"); // weighted edges - WARNING: supports only non-negative integer weights while (std::getline(stream, line)) { if (line.empty()) { continue; } std::stringstream linestream(line); node v; double weight; while (linestream >> v >> weight) { G.addEdge(u,v-1, (edgeweight) weight); } /* auto it1 = line.begin(); auto end = line.end(); auto it2 = std::find(it1, end, ' '); if (line.back() == ' ') { // if line ends with one white space, do this trick... --end; } while (true) { TRACE("try to read new node"); node v = (fast_string_to_integer(it1, it2) - 1); TRACE("read node " , v); // advance ++it2; it1 = it2; it2 = std::find(it1, end, ' '); TRACE("char at it1: ",*it1," and at it2: ",*it2," and their difference: ",&*it2-&*it1); // get weight double weight = (fast_string_to_double(it1, it2)); //double weight = std::stod(line.sub); TRACE("read weight " , weight); ++it2; it1 = it2; TRACE("find new it2"); it2 = std::find(it1, end, ' '); TRACE("found new it2"); TRACE("char at it1: ",*it1," and at it2: ",*it2," and their difference: ",&*it2-&*it1); if (u < v) { G.addEdge(u, v, (edgeweight) weight); } TRACE("new node added"); if (it2 == end) { break; } }*/ ++u; // next node } } else if (flag == 11) { ERROR("weighted nodes are not supported"); throw std::runtime_error("weighted nodes are not supported"); } else { ERROR("invalid weight flag in header of METIS file: " , flag); throw std::runtime_error("invalid weight flag in header of METIS file"); } return G; } } /* namespace NetworKit */ <commit_msg>fixed bug in METIS reader for double weights<commit_after>/* * FastMETISParser.cpp * * Created on: 04.10.2013 * Author: cls */ #include "FastMETISParserDouble.h" #include <fstream> namespace NetworKit { FastMETISParserDouble::FastMETISParserDouble() { // TODO Auto-generated constructor stub } FastMETISParserDouble::~FastMETISParserDouble() { // TODO Auto-generated destructor stub } static inline uint64_t fast_string_to_integer(std::string::iterator it, const std::string::iterator& end) { uint64_t val = *it - '0'; // works on ASCII code points ++it; while (it != end) { val *= 10; val += *it - '0'; ++it; } return val; } static inline double fast_string_to_double(std::string::iterator it, const std::string::iterator& end) { double val = 0.0; bool negative = false; if (*it == '-') { negative = true; ++it; } while (*it >= '0' && *it <= '9' && it != end) { //it != end val = (val*10.0) + (*it - '0'); ++it; } if (*it == '.' && it != end) { double afterComma = 0.0; int exp = 0; ++it; while (*it >= '0' && *it <= '9' && it != end) { //it != end afterComma = (afterComma*10.0) + (*it - '0'); ++exp; ++it; } val += afterComma / std::pow(10.0, exp); } if (negative) { val = -val; } return val; } static inline std::tuple<count, count, int> parseHeader(const std::string& header) { count n; count m; int flag; std::vector<std::string> parts = Aux::StringTools::split(header); n = std::stoi(parts[0]); m = std::stoi(parts[1]); if (parts.size() > 2) { flag = std::stoi(parts[2]); } else { flag = 0; } return std::make_tuple(n, m, flag); } NetworKit::Graph FastMETISParserDouble::parse(const std::string& path) { std::ifstream stream(path); std::string line; std::getline(stream, line); // get header count n; count m; int flag; // weight flag std::tie(n, m, flag) = parseHeader(line); bool weighted = flag % 10; Graph G(n, weighted); node u = 0; // TODO: handle comment lines if (flag == 0) { DEBUG("reading unweighted graph"); // unweighted edges while (std::getline(stream, line)) { if (line.empty()) { continue; } auto it1 = line.begin(); auto end = line.end(); auto it2 = std::find(it1, end, ' '); if (line.back() == ' ') { // if line ends with one white space, do this trick... --end; } while (true) { node v = (fast_string_to_integer(it1, it2) - 1); if (u < v) { G.addEdge(u, v); } if (it2 == end) { break; } ++it2; it1 = it2; it2 = std::find(it1, end, ' '); } ++u; // next node } } else if (flag == 1) { DEBUG("reading weighted graph"); // weighted edges - WARNING: supports only non-negative integer weights while (std::getline(stream, line)) { if (line.empty()) { continue; } std::stringstream linestream(line); node v; double weight; while (linestream >> v >> weight) { if (u < v) { G.addEdge(u,v-1, (edgeweight) weight); } } /* auto it1 = line.begin(); auto end = line.end(); auto it2 = std::find(it1, end, ' '); if (line.back() == ' ') { // if line ends with one white space, do this trick... --end; } while (true) { TRACE("try to read new node"); node v = (fast_string_to_integer(it1, it2) - 1); TRACE("read node " , v); // advance ++it2; it1 = it2; it2 = std::find(it1, end, ' '); TRACE("char at it1: ",*it1," and at it2: ",*it2," and their difference: ",&*it2-&*it1); // get weight double weight = (fast_string_to_double(it1, it2)); //double weight = std::stod(line.sub); TRACE("read weight " , weight); ++it2; it1 = it2; TRACE("find new it2"); it2 = std::find(it1, end, ' '); TRACE("found new it2"); TRACE("char at it1: ",*it1," and at it2: ",*it2," and their difference: ",&*it2-&*it1); if (u < v) { G.addEdge(u, v, (edgeweight) weight); } TRACE("new node added"); if (it2 == end) { break; } }*/ ++u; // next node } } else if (flag == 11) { ERROR("weighted nodes are not supported"); throw std::runtime_error("weighted nodes are not supported"); } else { ERROR("invalid weight flag in header of METIS file: " , flag); throw std::runtime_error("invalid weight flag in header of METIS file"); } return G; } } /* namespace NetworKit */ <|endoftext|>
<commit_before>/************************************************************************* * Copyright (c) 2014 eProsima. All rights reserved. * * This copy of eProsima RTPS is licensed to you under the terms described in the * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution. * *************************************************************************/ /** * @file ListenResource.cpp * */ #include "eprosimartps/resources/ListenResource.h" #include "eprosimartps/writer/RTPSWriter.h" #include "eprosimartps/reader/RTPSReader.h" #include "eprosimartps/Endpoint.h" #include "eprosimartps/Participant.h" #include "eprosimartps/utils/IPFinder.h" #include "eprosimartps/utils/RTPSLog.h" using boost::asio::ip::udp; namespace eprosima { namespace rtps { typedef std::vector<RTPSWriter*>::iterator Wit; typedef std::vector<RTPSReader*>::iterator Rit; ListenResource::ListenResource(ParticipantImpl*p): mp_participantImpl(p), mp_thread(NULL), m_listen_socket(m_io_service) { m_MessageReceiver.mp_threadListen = this; } ListenResource::~ListenResource() { pWarning("Removing listening thread " << mp_thread->get_id() << std::endl); m_listen_socket.close(); m_io_service.stop(); pInfo("Joining with thread"<<endl); mp_thread->join(); delete(mp_thread); } bool ListenResource::removeAssociatedEndpoint(Endpoint* endp) { if(endp->getEndpointKind() == WRITER) { for(Wit wit = m_assocWriters.begin(); wit!=m_assocWriters.end();++wit) { if((*wit)->getGuid().entityId == endp->getGuid().entityId) { m_assocWriters.erase(wit); return true; } } } else if(endp->getEndpointKind() == READER) { for(Rit rit = m_assocReaders.begin();rit!=m_assocReaders.end();++rit) { if((*rit)->getGuid().entityId == endp->getGuid().entityId) { m_assocReaders.erase(rit); return true; } } } return false; } bool ListenResource::addAssociatedEndpoint(Endpoint* endp) { bool found = false; if(endp->getEndpointKind() == WRITER) { for(std::vector<RTPSWriter*>::iterator wit = m_assocWriters.begin(); wit!=m_assocWriters.end();++wit) { if((*wit)->getGuid().entityId == endp->getGuid().entityId) { found = true; break; } } if(!found) { m_assocWriters.push_back((RTPSWriter*)endp); pInfo("ResourceListen: Endpoint (" << endp->getGuid().entityId << ") added to listen Resource: "<< m_listenLoc.printIP4Port() << endl); return true; } } else if(endp->getEndpointKind() == READER) { for(std::vector<RTPSReader*>::iterator rit = m_assocReaders.begin();rit!=m_assocReaders.end();++rit) { if((*rit)->getGuid().entityId == endp->getGuid().entityId) { found = true; break; } } if(!found) { m_assocReaders.push_back((RTPSReader*)endp); pInfo("ResourceListen: Endpoint (" << endp->getGuid().entityId << ") added to listen Resource: "<< m_listenLoc.printIP4Port() << endl); return true; } } return false; } bool ListenResource::isListeningTo(const Locator_t& loc) { if(m_listenLoc == loc) return true; else return false; } void ListenResource::newCDRMessage(const boost::system::error_code& err, std::size_t msg_size) { if(err == boost::system::errc::success) { m_MessageReceiver.m_rec_msg.length = msg_size; if(m_MessageReceiver.m_rec_msg.length == 0) { return; } pInfo (RTPS_BLUE << "ResourceListen, msg of length: " << m_MessageReceiver.m_rec_msg.length << " FROM: " << m_sender_endpoint << " TO: " << m_listenLoc.printIP4Port()<< RTPS_DEF << endl); //Get address into Locator m_senderLocator.port = m_sender_endpoint.port(); LOCATOR_ADDRESS_INVALID(m_senderLocator.address); for(int i=0;i<4;i++) { m_senderLocator.address[i+12] = m_sender_endpoint.address().to_v4().to_bytes()[i]; } try { m_MessageReceiver.processCDRMsg(mp_participantImpl->getGuid().guidPrefix,&m_senderLocator,&m_MessageReceiver.m_rec_msg); } catch(int e) { pError( "Error processing message of type: " << e << std::endl); } //CDRMessage_t msg; // pInfo(BLUE<< "Socket async receive put again to listen "<<DEF<< endl); CDRMessage::initCDRMsg(&m_MessageReceiver.m_rec_msg); m_listen_socket.async_receive_from( boost::asio::buffer((void*)m_MessageReceiver.m_rec_msg.buffer, m_MessageReceiver.m_rec_msg.max_size), m_sender_endpoint, boost::bind(&ListenResource::newCDRMessage, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else if(err == boost::asio::error::operation_aborted) { pInfo("Operation in listening socket aborted..."<<endl); return; } else { //CDRMessage_t msg; pInfo(RTPS_BLUE<< "Msg processed, Socket async receive put again to listen "<<RTPS_DEF<< endl); CDRMessage::initCDRMsg(&m_MessageReceiver.m_rec_msg); m_listen_socket.async_receive_from( boost::asio::buffer((void*)m_MessageReceiver.m_rec_msg.buffer, m_MessageReceiver.m_rec_msg.max_size), m_sender_endpoint, boost::bind(&ListenResource::newCDRMessage, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } Locator_t ListenResource::init_thread(Locator_t& loc, bool isMulti, bool isFixed) { pInfo(RTPS_BLUE<<"Listen Resource initializing in : "<<loc.printIP4Port()<<RTPS_DEF<< endl); m_listenLoc = loc; boost::asio::ip::address address = boost::asio::ip::address::from_string(m_listenLoc.to_IP4_string()); if(isMulti) { m_listen_endpoint = udp::endpoint(boost::asio::ip::udp::v4(),m_listenLoc.port); } else { m_listen_endpoint = udp::endpoint(address,m_listenLoc.port); } //OPEN THE SOCKET: m_listen_socket.open(m_listen_endpoint.protocol()); m_listen_socket.set_option(boost::asio::socket_base::receive_buffer_size(this->mp_participantImpl->getListenSocketBufferSize())); if(isMulti) { m_listen_socket.set_option( boost::asio::ip::udp::socket::reuse_address( true ) ); m_listen_socket.set_option( boost::asio::ip::multicast::enable_loopback( true ) ); } if(isFixed) { try { m_listen_socket.bind(m_listen_endpoint); } catch (boost::system::system_error const& e) { pError(e.what() << " : " << m_listen_endpoint <<endl); m_listenLoc.kind = -1; return m_listenLoc; } } else { bool binded = false; for(uint8_t i =0;i<100;++i) { m_listen_endpoint.port(m_listen_endpoint.port()+i); try { m_listen_socket.bind(m_listen_endpoint); binded = true; m_listenLoc.port = m_listen_endpoint.port(); break; } catch(boost::system::system_error const& ) { pDebugInfo("Tried port "<< m_listen_endpoint.port() << ", trying next..."<<endl); } } if(!binded) { pError("Tried 100 ports and none was working" <<endl); m_listenLoc.kind = -1; return m_listenLoc; } } boost::asio::socket_base::receive_buffer_size option; m_listen_socket.get_option(option); pInfo("Listen endpoint: " << m_listen_endpoint<< " || Listen buffer size: " << option.value() <<endl); if(isMulti) { pDebugInfo("Joining group: "<<m_listenLoc.to_IP4_string()<<endl); LocatorList_t loclist; IPFinder::getIPAddress(&loclist); for(LocatorListIterator it=loclist.begin();it!=loclist.end();++it) m_listen_socket.set_option( boost::asio::ip::multicast::join_group(address.to_v4(),boost::asio::ip::address_v4::from_string(it->to_IP4_string())) ); } CDRMessage::initCDRMsg(&m_MessageReceiver.m_rec_msg); m_listen_socket.async_receive_from( boost::asio::buffer((void*)m_MessageReceiver.m_rec_msg.buffer, m_MessageReceiver.m_rec_msg.max_size), m_sender_endpoint, boost::bind(&ListenResource::newCDRMessage, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); mp_thread = new boost::thread(&ListenResource::run_io_service,this); mp_participantImpl->ResourceSemaphoreWait(); return m_listenLoc; } void ListenResource::run_io_service() { pInfo (RTPS_BLUE << "Thread: " << mp_thread->get_id() << " listening in IP: " << m_listen_socket.local_endpoint() << RTPS_DEF << endl) ; mp_participantImpl->ResourceSemaphorePost(); this->m_io_service.run(); } } /* namespace rtps */ } /* namespace eprosima */ <commit_msg>Changed endpoint to 0.0.0.0 in listen resource to enable loopback<commit_after>/************************************************************************* * Copyright (c) 2014 eProsima. All rights reserved. * * This copy of eProsima RTPS is licensed to you under the terms described in the * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution. * *************************************************************************/ /** * @file ListenResource.cpp * */ #include "eprosimartps/resources/ListenResource.h" #include "eprosimartps/writer/RTPSWriter.h" #include "eprosimartps/reader/RTPSReader.h" #include "eprosimartps/Endpoint.h" #include "eprosimartps/Participant.h" #include "eprosimartps/utils/IPFinder.h" #include "eprosimartps/utils/RTPSLog.h" using boost::asio::ip::udp; namespace eprosima { namespace rtps { typedef std::vector<RTPSWriter*>::iterator Wit; typedef std::vector<RTPSReader*>::iterator Rit; ListenResource::ListenResource(ParticipantImpl*p): mp_participantImpl(p), mp_thread(NULL), m_listen_socket(m_io_service) { m_MessageReceiver.mp_threadListen = this; } ListenResource::~ListenResource() { pWarning("Removing listening thread " << mp_thread->get_id() << std::endl); m_listen_socket.close(); m_io_service.stop(); pInfo("Joining with thread"<<endl); mp_thread->join(); delete(mp_thread); } bool ListenResource::removeAssociatedEndpoint(Endpoint* endp) { if(endp->getEndpointKind() == WRITER) { for(Wit wit = m_assocWriters.begin(); wit!=m_assocWriters.end();++wit) { if((*wit)->getGuid().entityId == endp->getGuid().entityId) { m_assocWriters.erase(wit); return true; } } } else if(endp->getEndpointKind() == READER) { for(Rit rit = m_assocReaders.begin();rit!=m_assocReaders.end();++rit) { if((*rit)->getGuid().entityId == endp->getGuid().entityId) { m_assocReaders.erase(rit); return true; } } } return false; } bool ListenResource::addAssociatedEndpoint(Endpoint* endp) { bool found = false; if(endp->getEndpointKind() == WRITER) { for(std::vector<RTPSWriter*>::iterator wit = m_assocWriters.begin(); wit!=m_assocWriters.end();++wit) { if((*wit)->getGuid().entityId == endp->getGuid().entityId) { found = true; break; } } if(!found) { m_assocWriters.push_back((RTPSWriter*)endp); pInfo("ResourceListen: Endpoint (" << endp->getGuid().entityId << ") added to listen Resource: "<< m_listenLoc.printIP4Port() << endl); return true; } } else if(endp->getEndpointKind() == READER) { for(std::vector<RTPSReader*>::iterator rit = m_assocReaders.begin();rit!=m_assocReaders.end();++rit) { if((*rit)->getGuid().entityId == endp->getGuid().entityId) { found = true; break; } } if(!found) { m_assocReaders.push_back((RTPSReader*)endp); pInfo("ResourceListen: Endpoint (" << endp->getGuid().entityId << ") added to listen Resource: "<< m_listenLoc.printIP4Port() << endl); return true; } } return false; } bool ListenResource::isListeningTo(const Locator_t& loc) { if(m_listenLoc == loc) return true; else return false; } void ListenResource::newCDRMessage(const boost::system::error_code& err, std::size_t msg_size) { if(err == boost::system::errc::success) { m_MessageReceiver.m_rec_msg.length = msg_size; if(m_MessageReceiver.m_rec_msg.length == 0) { return; } pInfo (RTPS_BLUE << "ResourceListen, msg of length: " << m_MessageReceiver.m_rec_msg.length << " FROM: " << m_sender_endpoint << " TO: " << m_listenLoc.printIP4Port()<< RTPS_DEF << endl); //Get address into Locator m_senderLocator.port = m_sender_endpoint.port(); LOCATOR_ADDRESS_INVALID(m_senderLocator.address); for(int i=0;i<4;i++) { m_senderLocator.address[i+12] = m_sender_endpoint.address().to_v4().to_bytes()[i]; } try { m_MessageReceiver.processCDRMsg(mp_participantImpl->getGuid().guidPrefix,&m_senderLocator,&m_MessageReceiver.m_rec_msg); } catch(int e) { pError( "Error processing message of type: " << e << std::endl); } //CDRMessage_t msg; // pInfo(BLUE<< "Socket async receive put again to listen "<<DEF<< endl); CDRMessage::initCDRMsg(&m_MessageReceiver.m_rec_msg); m_listen_socket.async_receive_from( boost::asio::buffer((void*)m_MessageReceiver.m_rec_msg.buffer, m_MessageReceiver.m_rec_msg.max_size), m_sender_endpoint, boost::bind(&ListenResource::newCDRMessage, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else if(err == boost::asio::error::operation_aborted) { pInfo("Operation in listening socket aborted..."<<endl); return; } else { //CDRMessage_t msg; pInfo(RTPS_BLUE<< "Msg processed, Socket async receive put again to listen "<<RTPS_DEF<< endl); CDRMessage::initCDRMsg(&m_MessageReceiver.m_rec_msg); m_listen_socket.async_receive_from( boost::asio::buffer((void*)m_MessageReceiver.m_rec_msg.buffer, m_MessageReceiver.m_rec_msg.max_size), m_sender_endpoint, boost::bind(&ListenResource::newCDRMessage, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } Locator_t ListenResource::init_thread(Locator_t& loc, bool isMulti, bool isFixed) { pInfo(RTPS_BLUE<<"Listen Resource initializing in : "<<loc.printIP4Port()<<RTPS_DEF<< endl); m_listenLoc = loc; boost::asio::ip::address address = boost::asio::ip::address::from_string(m_listenLoc.to_IP4_string()); if(isMulti) { m_listen_endpoint = udp::endpoint(boost::asio::ip::udp::v4(),m_listenLoc.port); } else { //m_listen_endpoint = udp::endpoint(address,m_listenLoc.port); m_listen_endpoint = udp::endpoint(boost::asio::ip::udp::v4(),m_listenLoc.port); } //OPEN THE SOCKET: m_listen_socket.open(m_listen_endpoint.protocol()); m_listen_socket.set_option(boost::asio::socket_base::receive_buffer_size(this->mp_participantImpl->getListenSocketBufferSize())); if(isMulti) { m_listen_socket.set_option( boost::asio::ip::udp::socket::reuse_address( true ) ); m_listen_socket.set_option( boost::asio::ip::multicast::enable_loopback( true ) ); } if(isFixed) { try { m_listen_socket.bind(m_listen_endpoint); } catch (boost::system::system_error const& e) { pError(e.what() << " : " << m_listen_endpoint <<endl); m_listenLoc.kind = -1; return m_listenLoc; } } else { bool binded = false; for(uint8_t i =0;i<100;++i) { m_listen_endpoint.port(m_listen_endpoint.port()+i); try { m_listen_socket.bind(m_listen_endpoint); binded = true; m_listenLoc.port = m_listen_endpoint.port(); break; } catch(boost::system::system_error const& ) { pDebugInfo("Tried port "<< m_listen_endpoint.port() << ", trying next..."<<endl); } } if(!binded) { pError("Tried 100 ports and none was working" <<endl); m_listenLoc.kind = -1; return m_listenLoc; } } boost::asio::socket_base::receive_buffer_size option; m_listen_socket.get_option(option); pInfo("Listen endpoint: " << m_listen_endpoint<< " || Listen buffer size: " << option.value() <<endl); if(isMulti) { pDebugInfo("Joining group: "<<m_listenLoc.to_IP4_string()<<endl); LocatorList_t loclist; IPFinder::getIPAddress(&loclist); for(LocatorListIterator it=loclist.begin();it!=loclist.end();++it) m_listen_socket.set_option( boost::asio::ip::multicast::join_group(address.to_v4(),boost::asio::ip::address_v4::from_string(it->to_IP4_string())) ); } CDRMessage::initCDRMsg(&m_MessageReceiver.m_rec_msg); m_listen_socket.async_receive_from( boost::asio::buffer((void*)m_MessageReceiver.m_rec_msg.buffer, m_MessageReceiver.m_rec_msg.max_size), m_sender_endpoint, boost::bind(&ListenResource::newCDRMessage, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); mp_thread = new boost::thread(&ListenResource::run_io_service,this); mp_participantImpl->ResourceSemaphoreWait(); return m_listenLoc; } void ListenResource::run_io_service() { pInfo (RTPS_BLUE << "Thread: " << mp_thread->get_id() << " listening in IP: " << m_listen_socket.local_endpoint() << RTPS_DEF << endl) ; mp_participantImpl->ResourceSemaphorePost(); this->m_io_service.run(); } } /* namespace rtps */ } /* namespace eprosima */ <|endoftext|>
<commit_before>/// HEADER #include <csapex/model/node_runner.h> /// PROJECT #include <csapex/model/node_handle.h> #include <csapex/model/node_worker.h> #include <csapex/model/tickable_node.h> #include <csapex/scheduling/scheduler.h> #include <csapex/scheduling/task.h> #include <csapex/utility/assert.h> #include <csapex/model/node_state.h> #include <csapex/utility/thread.h> /// SYSTEM #include <memory> #include <iostream> using namespace csapex; NodeRunner::NodeRunner(NodeWorkerPtr worker) : worker_(worker), scheduler_(nullptr), paused_(false), ticking_(false), is_source_(false), stepping_(false), can_step_(false), tick_thread_running_(false) { NodeHandlePtr handle = worker_->getNodeHandle(); NodePtr node = handle->getNode().lock(); is_source_ = handle->isSource(); ticking_ = node && std::dynamic_pointer_cast<TickableNode>(node); check_parameters_ = std::make_shared<Task>(std::string("check parameters for ") + handle->getUUID().getFullName(), std::bind(&NodeWorker::checkParameters, worker), 0, this); check_transitions_ = std::make_shared<Task>(std::string("check ") + handle->getUUID().getFullName(), std::bind(&NodeWorker::tryProcess, worker), 0, this); if(ticking_) { tick_ = std::make_shared<Task>(std::string("tick ") + handle->getUUID().getFullName(), [this]() { tick(); }, 0, this); } } NodeRunner::~NodeRunner() { for(csapex::slim_signal::Connection& c : connections_) { c.disconnect(); } connections_.clear(); if(scheduler_) { // detach(); } if(tick_thread_running_) { tick_thread_stop_ = true; ticking_thread_.join(); } } void NodeRunner::reset() { worker_->reset(); } void NodeRunner::assignToScheduler(Scheduler *scheduler) { std::unique_lock<std::recursive_mutex> lock(mutex_); apex_assert_hard(scheduler_ == nullptr); scheduler_ = scheduler; scheduler_->add(shared_from_this(), remaining_tasks_); worker_->getNodeHandle()->getNodeState()->setThread(scheduler->name(), scheduler->id()); remaining_tasks_.clear(); for(csapex::slim_signal::Connection& c : connections_) { c.disconnect(); } connections_.clear(); // node tasks auto ctr = worker_->tryProcessRequested.connect([this]() { check_transitions_->setPriority(worker_->getSequenceNumber()); schedule(check_transitions_); }); connections_.push_back(ctr); // parameter change auto check = worker_->getNodeHandle()->parametersChanged.connect([this]() { schedule(check_parameters_); }); connections_.push_back(check); schedule(check_parameters_); // generic task auto cg = worker_->getNodeHandle()->executionRequested.connect([this](std::function<void()> cb) { schedule(std::make_shared<Task>("anonymous", cb, 0, this)); }); connections_.push_back(cg); if(ticking_ && !tick_thread_running_) { // TODO: get rid of this! ticking_thread_ = std::thread([this]() { csapex::thread::set_name((std::string("T") + worker_->getUUID().getShortName()).c_str()); tick_thread_running_ = true; tick_thread_stop_ = false; tickLoop(); tick_thread_running_ = false; }); } } void NodeRunner::scheduleTick() { if(!paused_) { if(!stepping_ || can_step_) { can_step_ = false; schedule(tick_); } } } void NodeRunner::tick() { bool success = worker_->tick(); if(stepping_) { if(!success) { can_step_ = true; } else { end_step(); } } NodeHandlePtr handle = worker_->getNodeHandle(); NodePtr node = handle->getNode().lock(); auto ticker = std::dynamic_pointer_cast<TickableNode>(node); if(ticker->isImmediate()) { scheduleTick(); } } void NodeRunner::tickLoop() { NodePtr node = worker_->getNode(); auto ticker = std::dynamic_pointer_cast<TickableNode>(node); while(!tick_thread_stop_) { if(!ticker->isImmediate() || !tick_->isScheduled()) { scheduleTick(); } ticker->keepUpRate(); } } void NodeRunner::schedule(TaskPtr task) { std::unique_lock<std::recursive_mutex> lock(mutex_); remaining_tasks_.push_back(task); if(scheduler_) { for(TaskPtr t : remaining_tasks_) { scheduler_->schedule(t); } remaining_tasks_.clear(); } } void NodeRunner::detach() { std::unique_lock<std::recursive_mutex> lock(mutex_); if(scheduler_) { auto t = scheduler_->remove(this); remaining_tasks_.insert(remaining_tasks_.end(), t.begin(), t.end()); scheduler_ = nullptr; } } bool NodeRunner::isPaused() const { return paused_; } void NodeRunner::setPause(bool pause) { paused_ = pause; } void NodeRunner::setSteppingMode(bool stepping) { stepping_ = stepping; can_step_ = false; } void NodeRunner::step() { if(is_source_ && worker_->isProcessingEnabled()) { begin_step(); can_step_ = true; } else { can_step_ = false; end_step(); } } bool NodeRunner::isStepping() const { return stepping_; } bool NodeRunner::isStepDone() const { if(!ticking_) { return true; } return !can_step_; } UUID NodeRunner::getUUID() const { return worker_->getUUID(); } void NodeRunner::setError(const std::string &msg) { std::cerr << "error happened: " << msg << std::endl; worker_->setError(true, msg); } <commit_msg>immediate ticking no longer starves other nodes<commit_after>/// HEADER #include <csapex/model/node_runner.h> /// PROJECT #include <csapex/model/node_handle.h> #include <csapex/model/node_worker.h> #include <csapex/model/tickable_node.h> #include <csapex/scheduling/scheduler.h> #include <csapex/scheduling/task.h> #include <csapex/utility/assert.h> #include <csapex/model/node_state.h> #include <csapex/utility/thread.h> /// SYSTEM #include <memory> #include <iostream> using namespace csapex; NodeRunner::NodeRunner(NodeWorkerPtr worker) : worker_(worker), scheduler_(nullptr), paused_(false), ticking_(false), is_source_(false), stepping_(false), can_step_(false), tick_thread_running_(false) { NodeHandlePtr handle = worker_->getNodeHandle(); NodePtr node = handle->getNode().lock(); is_source_ = handle->isSource(); ticking_ = node && std::dynamic_pointer_cast<TickableNode>(node); check_parameters_ = std::make_shared<Task>(std::string("check parameters for ") + handle->getUUID().getFullName(), std::bind(&NodeWorker::checkParameters, worker), 0, this); check_transitions_ = std::make_shared<Task>(std::string("check ") + handle->getUUID().getFullName(), std::bind(&NodeWorker::tryProcess, worker), 0, this); if(ticking_) { tick_ = std::make_shared<Task>(std::string("tick ") + handle->getUUID().getFullName(), [this]() { tick(); }, 0, this); } } NodeRunner::~NodeRunner() { for(csapex::slim_signal::Connection& c : connections_) { c.disconnect(); } connections_.clear(); if(scheduler_) { // detach(); } if(tick_thread_running_) { tick_thread_stop_ = true; ticking_thread_.join(); } } void NodeRunner::reset() { worker_->reset(); } void NodeRunner::assignToScheduler(Scheduler *scheduler) { std::unique_lock<std::recursive_mutex> lock(mutex_); apex_assert_hard(scheduler_ == nullptr); scheduler_ = scheduler; scheduler_->add(shared_from_this(), remaining_tasks_); worker_->getNodeHandle()->getNodeState()->setThread(scheduler->name(), scheduler->id()); remaining_tasks_.clear(); for(csapex::slim_signal::Connection& c : connections_) { c.disconnect(); } connections_.clear(); // node tasks auto ctr = worker_->tryProcessRequested.connect([this]() { check_transitions_->setPriority(worker_->getSequenceNumber()); schedule(check_transitions_); }); connections_.push_back(ctr); // parameter change auto check = worker_->getNodeHandle()->parametersChanged.connect([this]() { schedule(check_parameters_); }); connections_.push_back(check); schedule(check_parameters_); // generic task auto cg = worker_->getNodeHandle()->executionRequested.connect([this](std::function<void()> cb) { schedule(std::make_shared<Task>("anonymous", cb, 0, this)); }); connections_.push_back(cg); if(ticking_ && !tick_thread_running_) { // TODO: get rid of this! ticking_thread_ = std::thread([this]() { csapex::thread::set_name((std::string("T") + worker_->getUUID().getShortName()).c_str()); tick_thread_running_ = true; tick_thread_stop_ = false; tickLoop(); tick_thread_running_ = false; }); } } void NodeRunner::scheduleTick() { if(!paused_) { if(!stepping_ || can_step_) { can_step_ = false; schedule(tick_); } } } void NodeRunner::tick() { bool success = worker_->tick(); if(stepping_) { if(!success) { can_step_ = true; } else { end_step(); } } if(success) { NodeHandlePtr handle = worker_->getNodeHandle(); NodePtr node = handle->getNode().lock(); auto ticker = std::dynamic_pointer_cast<TickableNode>(node); if(ticker->isImmediate()) { scheduleTick(); } } } void NodeRunner::tickLoop() { NodePtr node = worker_->getNode(); auto ticker = std::dynamic_pointer_cast<TickableNode>(node); while(!tick_thread_stop_) { if(!ticker->isImmediate() || !tick_->isScheduled()) { scheduleTick(); } ticker->keepUpRate(); } } void NodeRunner::schedule(TaskPtr task) { std::unique_lock<std::recursive_mutex> lock(mutex_); remaining_tasks_.push_back(task); if(scheduler_) { for(TaskPtr t : remaining_tasks_) { scheduler_->schedule(t); } remaining_tasks_.clear(); } } void NodeRunner::detach() { std::unique_lock<std::recursive_mutex> lock(mutex_); if(scheduler_) { auto t = scheduler_->remove(this); remaining_tasks_.insert(remaining_tasks_.end(), t.begin(), t.end()); scheduler_ = nullptr; } } bool NodeRunner::isPaused() const { return paused_; } void NodeRunner::setPause(bool pause) { paused_ = pause; } void NodeRunner::setSteppingMode(bool stepping) { stepping_ = stepping; can_step_ = false; } void NodeRunner::step() { if(is_source_ && worker_->isProcessingEnabled()) { begin_step(); can_step_ = true; } else { can_step_ = false; end_step(); } } bool NodeRunner::isStepping() const { return stepping_; } bool NodeRunner::isStepDone() const { if(!ticking_) { return true; } return !can_step_; } UUID NodeRunner::getUUID() const { return worker_->getUUID(); } void NodeRunner::setError(const std::string &msg) { std::cerr << "error happened: " << msg << std::endl; worker_->setError(true, msg); } <|endoftext|>
<commit_before>#include "factory.h" #include <chrono> #include <thread> void synopsis() { std::cout << "save_frames" << " [ " << std::endl << " " << " help " << std::endl << " " << " epiphan xvid | h265 sdi | dvi " << " [ <framerate> [ <x> <y> <width> <height> ] ]" << " # optimal: 20 600 185 678 688" << std::endl << " " << " file </file/path> xvid | h265 " << std::endl << " " << " chess xvid | h265 <width> <height> " << std::endl << " " << " ]" << std::endl; } enum TestMode { Epiphan, File, Chessboard }; enum TestMode test_mode; enum gg::Target codec; std::string codec_string, filetype; int width, height, square_size; float fps; int duration; // min int num_frames; int i = 0; VideoFrame_BGRA frame; cv::Mat image; cv::VideoCapture cap; enum gg::Device port; std::string port_string; int sleep_duration; IVideoSource * epiphan = NULL; int roi_x, roi_y; inline void timer_start(std::chrono::high_resolution_clock::time_point & start) { start = std::chrono::high_resolution_clock::now(); } inline float timer_end(const std::chrono::high_resolution_clock::time_point & start) { return std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - start ).count(); } void init(int argc, char ** argv) { std::vector<std::string> args; for (int i = 0; i < argc; i++) args.push_back(std::string(argv[i])); if (args[1]=="help") { synopsis(); exit(0); } if (args[1]=="epiphan") { test_mode = TestMode::Epiphan; if (argc < 4) { synopsis(); exit(-1); } codec_string = args[2]; port_string = args[3]; if (port_string == "sdi") port = gg::Device::DVI2PCIeDuo_SDI; else if (port_string == "dvi") port = gg::Device::DVI2PCIeDuo_DVI; else { std::cerr << "Port " << port_string << " not recognised" << std::endl; synopsis(); exit(-1); } epiphan = gg::Factory::connect(port); fps = 60; duration = 1; // min // optimal for Storz 27020 AA straight if (argc >= 5) { fps = atof(argv[4]); if (argc >= 9) { roi_x = atoi(argv[5]); roi_y = atoi(argv[6]); width = atoi(argv[7]); height = atoi(argv[8]); epiphan->set_sub_frame(roi_x, roi_y, width, height); } } num_frames = duration * 60 * fps; sleep_duration = (int)(1000/fps); // ms } else if (args[1]=="file") { test_mode = TestMode::File; if (argc < 4) { synopsis(); exit(-1); } cap.open(args[2]); if (not cap.isOpened()) { std::cerr << "File " << args[2] << " could not be opened" << std::endl; exit(-1); } codec_string = args[3]; num_frames = cap.get(CV_CAP_PROP_FRAME_COUNT); fps = cap.get(CV_CAP_PROP_FPS); duration = (num_frames / fps) / 60; } else if (args[1]=="chess") { test_mode = TestMode::Chessboard; if (argc < 5) { synopsis(); exit(-1); } codec_string = args[2]; width = atoi(argv[3]); height = atoi(argv[4]); /* square size purposefully odd, * to test robustness when odd frame * width and/or height provided, whereas * H265 requires even */ square_size = 61; image = cv::Mat(height * square_size, width * square_size, CV_8UC4); fps = 60; duration = 1; // min num_frames = duration * 60 * fps; } else { synopsis(); exit(-1); } // health checks if (codec_string == "xvid") { codec = gg::Target::File_XviD; filetype = "avi"; } else if (codec_string == "h265") { codec = gg::Target::File_H265; filetype = "mp4"; } else { std::cerr << "Codec " << codec_string << " not recognised" << std::endl; synopsis(); exit(-1); } } std::string which_file() { std::string filename; filename.append(std::to_string(duration)) .append("min_"); switch(test_mode) { case TestMode::Epiphan: filename.append("epiphan"); break; case TestMode::File: filename.append("from_file"); break; case TestMode::Chessboard: filename.append("colour_chessboard"); break; default: std::cerr << "Test mode not set" << std::endl; exit(-1); } filename.append("_") .append(codec_string) .append(".") .append(filetype); return filename; } void get_frame(VideoFrame_BGRA & frame) { // Chessboard params float elapsed, remaining; int red, green, blue, alpha, min_intensity; switch(test_mode) { case TestMode::Chessboard: elapsed = (((float) i) / num_frames); remaining = 1 - elapsed; red = 0, green = 0, blue = 0, alpha = 0; min_intensity = 50; // don't want black for (int row = 0; row < height; row++) { green = min_intensity + elapsed * (((float) row) / height) * (255 - min_intensity); for (int col = 0; col < width; col++) { red = min_intensity + elapsed * (((float) col) / width) * (255 - min_intensity); blue = min_intensity + remaining * sqrt( ((float)(row*row + col*col)) / (height*height+width*width) ) * (255 - min_intensity); cv::Mat square(square_size, square_size, CV_8UC4, cv::Scalar(blue, green, red, alpha)); square.copyTo(image(cv::Rect(col * square_size , row * square_size, square.cols, square.rows))); } } frame.init_from_opencv_mat(image); break; case TestMode::Epiphan: epiphan->get_frame(frame); break; case TestMode::File: cap >> image; cv::cvtColor(image, image, CV_BGR2BGRA); frame.init_from_opencv_mat(image); break; default: std::cerr << "Test mode not set" << std::endl; exit(-1); } } auto start = std::chrono::high_resolution_clock::now(); float elapsed; void time_left() { if (i % 5 == 0) { std::cout << "Saving frame " << i+1 << " of " << num_frames; elapsed = timer_end(start); int left = ((float) num_frames - i + 1) * elapsed / (i+1); std::cout << " (" << left << " sec. left)" << "\r"; } } void wait_for_next(const float elapsed = 0) { float real_sleep_duration; switch(test_mode) { case TestMode::File: case TestMode::Chessboard: // nop break; case TestMode::Epiphan: real_sleep_duration = sleep_duration - elapsed; if (real_sleep_duration < 0) std::cerr << std::endl << "Elapsed duration longer " << "than sleep duration by " << real_sleep_duration << " msec." << std::endl; else std::this_thread::sleep_for( std::chrono::milliseconds( (int)real_sleep_duration )); break; default: std::cerr << "Test mode not set" << std::endl; exit(-1); } } void finalise() { switch(test_mode) { case TestMode::File: case TestMode::Chessboard: // nop break; case TestMode::Epiphan: gg::Factory::disconnect(port); break; default: std::cerr << "Test mode not set" << std::endl; exit(-1); } } int main(int argc, char ** argv) { try { init(argc, argv); gg::IVideoTarget * file = gg::Factory::create(codec); std::string filename = which_file(); file->init(filename, fps); std::cout << "Saving to file " << filename << std::endl; timer_start(start); std::chrono::high_resolution_clock::time_point current_start, analysis; for (i = 0; i < num_frames; i++) { time_left(); timer_start(current_start); get_frame(frame); std::cout << "Frame:\t" << timer_end(current_start) << "\tmsec." << "\t"; timer_start(analysis); file->append(frame); std::cout << "Write:\t" << timer_end(analysis) << "\tmsec." << std::endl; float current_elapsed = timer_end(current_start); wait_for_next(current_elapsed); } auto total = timer_end(start); std::cout << std::endl << "Total time was " << total << " msec." << std::endl; file->finalise(); finalise(); } catch (gg::VideoTargetError & e) { std::cerr << e.what() << std::endl; return -1; } catch (gg::DeviceOffline & e) { std::cerr << e.what() << std::endl; return -1; } return 0; } <commit_msg>Issue #21: time_left outputs to cerr now (e.g. when cout used for redir to file)<commit_after>#include "factory.h" #include <chrono> #include <thread> void synopsis() { std::cout << "save_frames" << " [ " << std::endl << " " << " help " << std::endl << " " << " epiphan xvid | h265 sdi | dvi " << " [ <framerate> [ <x> <y> <width> <height> ] ]" << " # optimal: 20 600 185 678 688" << std::endl << " " << " file </file/path> xvid | h265 " << std::endl << " " << " chess xvid | h265 <width> <height> " << std::endl << " " << " ]" << std::endl; } enum TestMode { Epiphan, File, Chessboard }; enum TestMode test_mode; enum gg::Target codec; std::string codec_string, filetype; int width, height, square_size; float fps; int duration; // min int num_frames; int i = 0; VideoFrame_BGRA frame; cv::Mat image; cv::VideoCapture cap; enum gg::Device port; std::string port_string; int sleep_duration; IVideoSource * epiphan = NULL; int roi_x, roi_y; inline void timer_start(std::chrono::high_resolution_clock::time_point & start) { start = std::chrono::high_resolution_clock::now(); } inline float timer_end(const std::chrono::high_resolution_clock::time_point & start) { return std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - start ).count(); } void init(int argc, char ** argv) { std::vector<std::string> args; for (int i = 0; i < argc; i++) args.push_back(std::string(argv[i])); if (args[1]=="help") { synopsis(); exit(0); } if (args[1]=="epiphan") { test_mode = TestMode::Epiphan; if (argc < 4) { synopsis(); exit(-1); } codec_string = args[2]; port_string = args[3]; if (port_string == "sdi") port = gg::Device::DVI2PCIeDuo_SDI; else if (port_string == "dvi") port = gg::Device::DVI2PCIeDuo_DVI; else { std::cerr << "Port " << port_string << " not recognised" << std::endl; synopsis(); exit(-1); } epiphan = gg::Factory::connect(port); fps = 60; duration = 1; // min // optimal for Storz 27020 AA straight if (argc >= 5) { fps = atof(argv[4]); if (argc >= 9) { roi_x = atoi(argv[5]); roi_y = atoi(argv[6]); width = atoi(argv[7]); height = atoi(argv[8]); epiphan->set_sub_frame(roi_x, roi_y, width, height); } } num_frames = duration * 60 * fps; sleep_duration = (int)(1000/fps); // ms } else if (args[1]=="file") { test_mode = TestMode::File; if (argc < 4) { synopsis(); exit(-1); } cap.open(args[2]); if (not cap.isOpened()) { std::cerr << "File " << args[2] << " could not be opened" << std::endl; exit(-1); } codec_string = args[3]; num_frames = cap.get(CV_CAP_PROP_FRAME_COUNT); fps = cap.get(CV_CAP_PROP_FPS); duration = (num_frames / fps) / 60; } else if (args[1]=="chess") { test_mode = TestMode::Chessboard; if (argc < 5) { synopsis(); exit(-1); } codec_string = args[2]; width = atoi(argv[3]); height = atoi(argv[4]); /* square size purposefully odd, * to test robustness when odd frame * width and/or height provided, whereas * H265 requires even */ square_size = 61; image = cv::Mat(height * square_size, width * square_size, CV_8UC4); fps = 60; duration = 1; // min num_frames = duration * 60 * fps; } else { synopsis(); exit(-1); } // health checks if (codec_string == "xvid") { codec = gg::Target::File_XviD; filetype = "avi"; } else if (codec_string == "h265") { codec = gg::Target::File_H265; filetype = "mp4"; } else { std::cerr << "Codec " << codec_string << " not recognised" << std::endl; synopsis(); exit(-1); } } std::string which_file() { std::string filename; filename.append(std::to_string(duration)) .append("min_"); switch(test_mode) { case TestMode::Epiphan: filename.append("epiphan"); break; case TestMode::File: filename.append("from_file"); break; case TestMode::Chessboard: filename.append("colour_chessboard"); break; default: std::cerr << "Test mode not set" << std::endl; exit(-1); } filename.append("_") .append(codec_string) .append(".") .append(filetype); return filename; } void get_frame(VideoFrame_BGRA & frame) { // Chessboard params float elapsed, remaining; int red, green, blue, alpha, min_intensity; switch(test_mode) { case TestMode::Chessboard: elapsed = (((float) i) / num_frames); remaining = 1 - elapsed; red = 0, green = 0, blue = 0, alpha = 0; min_intensity = 50; // don't want black for (int row = 0; row < height; row++) { green = min_intensity + elapsed * (((float) row) / height) * (255 - min_intensity); for (int col = 0; col < width; col++) { red = min_intensity + elapsed * (((float) col) / width) * (255 - min_intensity); blue = min_intensity + remaining * sqrt( ((float)(row*row + col*col)) / (height*height+width*width) ) * (255 - min_intensity); cv::Mat square(square_size, square_size, CV_8UC4, cv::Scalar(blue, green, red, alpha)); square.copyTo(image(cv::Rect(col * square_size , row * square_size, square.cols, square.rows))); } } frame.init_from_opencv_mat(image); break; case TestMode::Epiphan: epiphan->get_frame(frame); break; case TestMode::File: cap >> image; cv::cvtColor(image, image, CV_BGR2BGRA); frame.init_from_opencv_mat(image); break; default: std::cerr << "Test mode not set" << std::endl; exit(-1); } } auto start = std::chrono::high_resolution_clock::now(); float elapsed; void time_left() { if (i % 5 == 0) { std::cerr << "Saving frame " << i+1 << " of " << num_frames; elapsed = timer_end(start); int left = ((float) num_frames - i + 1) * elapsed / (i+1); std::cerr << " (" << left << " sec. left)" << "\r"; } } void wait_for_next(const float elapsed = 0) { float real_sleep_duration; switch(test_mode) { case TestMode::File: case TestMode::Chessboard: // nop break; case TestMode::Epiphan: real_sleep_duration = sleep_duration - elapsed; if (real_sleep_duration < 0) std::cerr << std::endl << "Elapsed duration longer " << "than sleep duration by " << real_sleep_duration << " msec." << std::endl; else std::this_thread::sleep_for( std::chrono::milliseconds( (int)real_sleep_duration )); break; default: std::cerr << "Test mode not set" << std::endl; exit(-1); } } void finalise() { switch(test_mode) { case TestMode::File: case TestMode::Chessboard: // nop break; case TestMode::Epiphan: gg::Factory::disconnect(port); break; default: std::cerr << "Test mode not set" << std::endl; exit(-1); } } int main(int argc, char ** argv) { try { init(argc, argv); gg::IVideoTarget * file = gg::Factory::create(codec); std::string filename = which_file(); file->init(filename, fps); std::cout << "Saving to file " << filename << std::endl; timer_start(start); std::chrono::high_resolution_clock::time_point current_start, analysis; for (i = 0; i < num_frames; i++) { time_left(); timer_start(current_start); get_frame(frame); std::cout << "Frame:\t" << timer_end(current_start) << "\tmsec." << "\t"; timer_start(analysis); file->append(frame); std::cout << "Write:\t" << timer_end(analysis) << "\tmsec." << std::endl; float current_elapsed = timer_end(current_start); wait_for_next(current_elapsed); } auto total = timer_end(start); std::cout << std::endl << "Total time was " << total << " msec." << std::endl; file->finalise(); finalise(); } catch (gg::VideoTargetError & e) { std::cerr << e.what() << std::endl; return -1; } catch (gg::DeviceOffline & e) { std::cerr << e.what() << std::endl; return -1; } return 0; } <|endoftext|>
<commit_before>/** * @file */ #include "libbirch/Counted.hpp" bi::Counted::Counted() : sharedCount(0), weakCount(1), memoCount(0), size(0), frozen(false) { // } bi::Counted::Counted(const Counted& o) : sharedCount(0), weakCount(1), memoCount(0), size(o.size), frozen(false) { // } bi::Counted::~Counted() { assert(sharedCount == 0); } void bi::Counted::deallocate() { assert(sharedCount == 0); assert(weakCount == 0); bi::deallocate(this, size); } unsigned bi::Counted::getSize() const { return size; } bi::Counted* bi::Counted::lock() { unsigned count = sharedCount; while (count > 0 && !sharedCount.compare_exchange_weak(count, count + 1)) { // } return count > 0 ? this : nullptr; } void bi::Counted::incShared() { ++sharedCount; } void bi::Counted::decShared() { assert(sharedCount > 0); if (--sharedCount == 0 && size > 0) { // ^ size == 0 during construction, never destroy in that case destroy(); decWeak(); // release weak self-reference } } unsigned bi::Counted::numShared() const { return sharedCount; } void bi::Counted::incWeak() { ++weakCount; } void bi::Counted::decWeak() { assert(weakCount > 0); if (--weakCount == 0) { assert(sharedCount == 0); // ^ because of weak self-reference, the weak count should not expire // before the shared count deallocate(); } } unsigned bi::Counted::numWeak() const { return weakCount; } void bi::Counted::incMemo() { /* the order of operations here is important, as the weak count should * never be less than the memo count */ incWeak(); ++memoCount; } void bi::Counted::decMemo() { /* the order of operations here is important, as the weak count should * never be less than the memo count */ assert(memoCount > 0); --memoCount; decWeak(); } bool bi::Counted::isReachable() const { return sharedCount > 0 || weakCount > memoCount; } bool bi::Counted::isFrozen() const { return frozen; } void bi::Counted::freeze() { frozen = true; } <commit_msg>Fixed cross-copies putting new unfrozen objects in frozen memos. These objects should be frozen from the outset (they are only used for dependency tracking between clones).<commit_after>/** * @file */ #include "libbirch/Counted.hpp" bi::Counted::Counted() : sharedCount(0), weakCount(1), memoCount(0), size(0), frozen(false) { // } bi::Counted::Counted(const Counted& o) : sharedCount(0), weakCount(1), memoCount(0), size(o.size), frozen(currentContext->isFrozen()) { // } bi::Counted::~Counted() { assert(sharedCount == 0); } void bi::Counted::deallocate() { assert(sharedCount == 0); assert(weakCount == 0); bi::deallocate(this, size); } unsigned bi::Counted::getSize() const { return size; } bi::Counted* bi::Counted::lock() { unsigned count = sharedCount; while (count > 0 && !sharedCount.compare_exchange_weak(count, count + 1)) { // } return count > 0 ? this : nullptr; } void bi::Counted::incShared() { ++sharedCount; } void bi::Counted::decShared() { assert(sharedCount > 0); if (--sharedCount == 0 && size > 0) { // ^ size == 0 during construction, never destroy in that case destroy(); decWeak(); // release weak self-reference } } unsigned bi::Counted::numShared() const { return sharedCount; } void bi::Counted::incWeak() { ++weakCount; } void bi::Counted::decWeak() { assert(weakCount > 0); if (--weakCount == 0) { assert(sharedCount == 0); // ^ because of weak self-reference, the weak count should not expire // before the shared count deallocate(); } } unsigned bi::Counted::numWeak() const { return weakCount; } void bi::Counted::incMemo() { /* the order of operations here is important, as the weak count should * never be less than the memo count */ incWeak(); ++memoCount; } void bi::Counted::decMemo() { /* the order of operations here is important, as the weak count should * never be less than the memo count */ assert(memoCount > 0); --memoCount; decWeak(); } bool bi::Counted::isReachable() const { return sharedCount > 0 || weakCount > memoCount; } bool bi::Counted::isFrozen() const { return frozen; } void bi::Counted::freeze() { frozen = true; } <|endoftext|>
<commit_before>/* * libcpu: interface.cpp * * This is the interface to the client. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include <memory> #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/LinkAllPasses.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Transforms/Utils/Cloning.h" /* project global headers */ #include "libcpu.h" #include "libcpu_llvm.h" #include "tag.h" #include "translate_all.h" #include "translate_singlestep.h" #include "translate_singlestep_bb.h" #include "function.h" #include "optimize.h" #include "stat.h" /* architecture descriptors */ extern arch_func_t arch_func_6502; extern arch_func_t arch_func_m68k; extern arch_func_t arch_func_mips; extern arch_func_t arch_func_m88k; extern arch_func_t arch_func_arm; extern arch_func_t arch_func_8086; extern arch_func_t arch_func_fapra; #define IS_LITTLE_ENDIAN(cpu) (((cpu)->info.common_flags & CPU_FLAG_ENDIAN_MASK) == CPU_FLAG_ENDIAN_LITTLE) static inline bool is_valid_gpr_size(size_t size) { switch (size) { case 0: case 1: case 8: case 16: case 32: case 64: return true; default: return false; } } static inline bool is_valid_fpr_size(size_t size) { switch (size) { case 0: case 32: case 64: case 80: case 128: return true; default: return false; } } static inline bool is_valid_vr_size(size_t size) { switch (size) { case 0: case 64: case 128: return true; default: return false; } } ////////////////////////////////////////////////////////////////////// // cpu_t ////////////////////////////////////////////////////////////////////// cpu_t * cpu_new(cpu_arch_t arch, uint32_t flags, uint32_t arch_flags) { cpu_t *cpu; llvm::InitializeNativeTarget(); cpu = new cpu_t; assert(cpu != NULL); memset(&cpu->info, 0, sizeof(cpu->info)); memset(&cpu->rf, 0, sizeof(cpu->rf)); cpu->ctx = new LLVMContext(); cpu->info.type = arch; cpu->info.name = "noname"; cpu->info.common_flags = flags; cpu->info.arch_flags = arch_flags; switch (arch) { case CPU_ARCH_6502: cpu->f = arch_func_6502; break; case CPU_ARCH_M68K: cpu->f = arch_func_m68k; break; case CPU_ARCH_MIPS: cpu->f = arch_func_mips; break; case CPU_ARCH_M88K: cpu->f = arch_func_m88k; break; case CPU_ARCH_ARM: cpu->f = arch_func_arm; break; case CPU_ARCH_8086: cpu->f = arch_func_8086; break; case CPU_ARCH_FAPRA: cpu->f = arch_func_fapra; break; default: printf("illegal arch: %d\n", arch); exit(1); } cpu->code_start = 0; cpu->code_end = 0; cpu->code_entry = 0; cpu->tag = NULL; uint32_t i; for (i = 0; i < sizeof(cpu->func)/sizeof(*cpu->func); i++) cpu->func[i] = NULL; for (i = 0; i < sizeof(cpu->fp)/sizeof(*cpu->fp); i++) cpu->fp[i] = NULL; cpu->functions = 0; cpu->flags_codegen = CPU_CODEGEN_OPTIMIZE; cpu->flags_debug = CPU_DEBUG_NONE; cpu->flags_hint = CPU_HINT_NONE; cpu->flags = 0; // init the frontend cpu->f.init(cpu, &cpu->info, &cpu->rf); assert(is_valid_gpr_size(cpu->info.register_size[CPU_REG_GPR]) && "the specified GPR size is not guaranteed to work"); assert(is_valid_fpr_size(cpu->info.register_size[CPU_REG_FPR]) && "the specified FPR size is not guaranteed to work"); assert(is_valid_vr_size(cpu->info.register_size[CPU_REG_VR]) && "the specified VR size is not guaranteed to work"); assert(is_valid_gpr_size(cpu->info.register_size[CPU_REG_XR]) && "the specified XR size is not guaranteed to work"); uint32_t count = cpu->info.register_count[CPU_REG_GPR]; if (count != 0) { cpu->ptr_gpr = (Value **)calloc(count, sizeof(Value *)); cpu->in_ptr_gpr = (Value **)calloc(count, sizeof(Value *)); } else { cpu->ptr_gpr = NULL; cpu->in_ptr_gpr = NULL; } count = cpu->info.register_count[CPU_REG_XR]; if (count != 0) { cpu->ptr_xr = (Value **)calloc(count, sizeof(Value *)); cpu->in_ptr_xr = (Value **)calloc(count, sizeof(Value *)); } else { cpu->ptr_xr = NULL; cpu->in_ptr_xr = NULL; } count = cpu->info.register_count[CPU_REG_FPR]; if (count != 0) { cpu->ptr_fpr = (Value **)calloc(count, sizeof(Value *)); cpu->in_ptr_fpr = (Value **)calloc(count, sizeof(Value *)); } else { cpu->ptr_fpr = NULL; cpu->in_ptr_fpr = NULL; } if (cpu->info.psr_size != 0) { cpu->ptr_FLAG = (Value **)calloc(cpu->info.flags_count, sizeof(Value*)); assert(cpu->ptr_FLAG != NULL); } // init LLVM cpu->mod = new Module(cpu->info.name, _CTX()); assert(cpu->mod != NULL); std::unique_ptr<llvm::Module> module_ptr(llvm::CloneModule(*cpu->mod)); EngineBuilder builder{std::move(module_ptr)}; builder.setEngineKind(EngineKind::Kind::JIT); cpu->exec_engine = builder.create(); assert(cpu->exec_engine != NULL); // check if FP80 and FP128 are supported by this architecture. // XXX there is a better way to do this? std::string data_layout = cpu->exec_engine->getDataLayout().getStringRepresentation(); if (data_layout.find("f80") != std::string::npos) { LOG("INFO: FP80 supported.\n"); cpu->flags |= CPU_FLAG_FP80; } if (data_layout.find("f128") != std::string::npos) { LOG("INFO: FP128 supported.\n"); cpu->flags |= CPU_FLAG_FP128; } // check if we need to swap guest memory. if (cpu->exec_engine->getDataLayout().isLittleEndian() ^ IS_LITTLE_ENDIAN(cpu)) cpu->flags |= CPU_FLAG_SWAPMEM; cpu->timer_total[TIMER_TAG] = 0; cpu->timer_total[TIMER_FE] = 0; cpu->timer_total[TIMER_BE] = 0; cpu->timer_total[TIMER_RUN] = 0; return cpu; } void cpu_free(cpu_t *cpu) { if (cpu->f.done != NULL) cpu->f.done(cpu); if (cpu->exec_engine != NULL) { if (cpu->cur_func != NULL) { cpu->cur_func->eraseFromParent(); } delete cpu->exec_engine; } if (cpu->ctx != NULL) delete cpu->ctx; if (cpu->ptr_FLAG != NULL) free(cpu->ptr_FLAG); if (cpu->in_ptr_fpr != NULL) free(cpu->in_ptr_fpr); if (cpu->ptr_fpr != NULL) free(cpu->ptr_fpr); if (cpu->in_ptr_xr != NULL) free(cpu->in_ptr_xr); if (cpu->ptr_xr != NULL) free(cpu->ptr_xr); if (cpu->in_ptr_gpr != NULL) free(cpu->in_ptr_gpr); if (cpu->ptr_gpr != NULL) free(cpu->ptr_gpr); delete cpu; } void cpu_set_ram(cpu_t*cpu, uint8_t *r) { cpu->RAM = r; } void cpu_set_flags_codegen(cpu_t *cpu, uint32_t f) { cpu->flags_codegen = f; } void cpu_set_flags_debug(cpu_t *cpu, uint32_t f) { cpu->flags_debug = f; } void cpu_set_flags_hint(cpu_t *cpu, uint32_t f) { cpu->flags_hint = f; } void cpu_tag(cpu_t *cpu, addr_t pc) { update_timing(cpu, TIMER_TAG, true); tag_start(cpu, pc); update_timing(cpu, TIMER_TAG, false); } static void cpu_translate_function(cpu_t *cpu) { BasicBlock *bb_ret, *bb_trap, *label_entry, *bb_start; /* create function and fill it with std basic blocks */ cpu->cur_func = cpu_create_function(cpu, "jitmain", &bb_ret, &bb_trap, &label_entry); cpu->func[cpu->functions] = cpu->cur_func; /* TRANSLATE! */ update_timing(cpu, TIMER_FE, true); if (cpu->flags_debug & CPU_DEBUG_SINGLESTEP) { bb_start = cpu_translate_singlestep(cpu, bb_ret, bb_trap); } else if (cpu->flags_debug & CPU_DEBUG_SINGLESTEP_BB) { bb_start = cpu_translate_singlestep_bb(cpu, bb_ret, bb_trap); } else { bb_start = cpu_translate_all(cpu, bb_ret, bb_trap); } update_timing(cpu, TIMER_FE, false); /* finish entry basicblock */ BranchInst::Create(bb_start, label_entry); /* make sure everything is OK */ verifyFunction(*cpu->cur_func, &llvm::errs()); if (cpu->flags_debug & CPU_DEBUG_PRINT_IR) cpu->mod->print(llvm::errs(), nullptr); if (cpu->flags_codegen & CPU_CODEGEN_OPTIMIZE) { LOG("*** Optimizing..."); optimize(cpu); LOG("done.\n"); if (cpu->flags_debug & CPU_DEBUG_PRINT_IR_OPTIMIZED) cpu->mod->print(llvm::errs(), nullptr); } LOG("*** Translating..."); update_timing(cpu, TIMER_BE, true); cpu->fp[cpu->functions] = cpu->exec_engine->getPointerToFunction(cpu->cur_func); assert(cpu->fp[cpu->functions] != NULL); update_timing(cpu, TIMER_BE, false); LOG("done.\n"); cpu->functions++; } /* forces ahead of time translation (e.g. for benchmarking the run) */ void cpu_translate(cpu_t *cpu) { /* on demand translation */ if (cpu->tags_dirty) cpu_translate_function(cpu); cpu->tags_dirty = false; } typedef int (*fp_t)(uint8_t *RAM, void *grf, void *frf, debug_function_t fp); #ifdef __GNUC__ void __attribute__((noinline)) breakpoint() { asm("nop"); } #else void breakpoint() {} #endif int cpu_run(cpu_t *cpu, debug_function_t debug_function) { addr_t pc = 0, orig_pc = 0; uint32_t i; int ret; bool success; bool do_translate = true; /* try to find the entry in all functions */ while(true) { if (do_translate) { cpu_translate(cpu); pc = cpu->f.get_pc(cpu, cpu->rf.grf); } orig_pc = pc; success = false; for (i = 0; i < cpu->functions; i++) { fp_t FP = (fp_t)cpu->fp[i]; update_timing(cpu, TIMER_RUN, true); breakpoint(); ret = FP(cpu->RAM, cpu->rf.grf, cpu->rf.frf, debug_function); update_timing(cpu, TIMER_RUN, false); pc = cpu->f.get_pc(cpu, cpu->rf.grf); if (ret != JIT_RETURN_FUNCNOTFOUND) return ret; if (!is_inside_code_area(cpu, pc)) return ret; if (pc != orig_pc) { success = true; break; } } if (!success) { LOG("{%" PRIx64 "}", pc); cpu_tag(cpu, pc); do_translate = true; } } } //printf("%d\n", __LINE__); void cpu_flush(cpu_t *cpu) { cpu->cur_func->eraseFromParent(); cpu->functions = 0; // reset bb caching mapping cpu->func_bb.clear(); // delete cpu->mod; // cpu->mod = NULL; } void cpu_print_statistics(cpu_t *cpu) { printf("tag = %8" PRId64 "\n", cpu->timer_total[TIMER_TAG]); printf("fe = %8" PRId64 "\n", cpu->timer_total[TIMER_FE]); printf("be = %8" PRId64 "\n", cpu->timer_total[TIMER_BE]); printf("run = %8" PRId64 "\n", cpu->timer_total[TIMER_RUN]); } //printf("%s:%d\n", __func__, __LINE__); <commit_msg>llvm: Fix Module object lifetime<commit_after>/* * libcpu: interface.cpp * * This is the interface to the client. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include <memory> #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/LinkAllPasses.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Transforms/Utils/Cloning.h" /* project global headers */ #include "libcpu.h" #include "libcpu_llvm.h" #include "tag.h" #include "translate_all.h" #include "translate_singlestep.h" #include "translate_singlestep_bb.h" #include "function.h" #include "optimize.h" #include "stat.h" /* architecture descriptors */ extern arch_func_t arch_func_6502; extern arch_func_t arch_func_m68k; extern arch_func_t arch_func_mips; extern arch_func_t arch_func_m88k; extern arch_func_t arch_func_arm; extern arch_func_t arch_func_8086; extern arch_func_t arch_func_fapra; #define IS_LITTLE_ENDIAN(cpu) (((cpu)->info.common_flags & CPU_FLAG_ENDIAN_MASK) == CPU_FLAG_ENDIAN_LITTLE) static inline bool is_valid_gpr_size(size_t size) { switch (size) { case 0: case 1: case 8: case 16: case 32: case 64: return true; default: return false; } } static inline bool is_valid_fpr_size(size_t size) { switch (size) { case 0: case 32: case 64: case 80: case 128: return true; default: return false; } } static inline bool is_valid_vr_size(size_t size) { switch (size) { case 0: case 64: case 128: return true; default: return false; } } ////////////////////////////////////////////////////////////////////// // cpu_t ////////////////////////////////////////////////////////////////////// cpu_t * cpu_new(cpu_arch_t arch, uint32_t flags, uint32_t arch_flags) { cpu_t *cpu; llvm::InitializeNativeTarget(); cpu = new cpu_t; assert(cpu != NULL); memset(&cpu->info, 0, sizeof(cpu->info)); memset(&cpu->rf, 0, sizeof(cpu->rf)); cpu->ctx = new LLVMContext(); cpu->info.type = arch; cpu->info.name = "noname"; cpu->info.common_flags = flags; cpu->info.arch_flags = arch_flags; switch (arch) { case CPU_ARCH_6502: cpu->f = arch_func_6502; break; case CPU_ARCH_M68K: cpu->f = arch_func_m68k; break; case CPU_ARCH_MIPS: cpu->f = arch_func_mips; break; case CPU_ARCH_M88K: cpu->f = arch_func_m88k; break; case CPU_ARCH_ARM: cpu->f = arch_func_arm; break; case CPU_ARCH_8086: cpu->f = arch_func_8086; break; case CPU_ARCH_FAPRA: cpu->f = arch_func_fapra; break; default: printf("illegal arch: %d\n", arch); exit(1); } cpu->code_start = 0; cpu->code_end = 0; cpu->code_entry = 0; cpu->tag = NULL; uint32_t i; for (i = 0; i < sizeof(cpu->func)/sizeof(*cpu->func); i++) cpu->func[i] = NULL; for (i = 0; i < sizeof(cpu->fp)/sizeof(*cpu->fp); i++) cpu->fp[i] = NULL; cpu->functions = 0; cpu->flags_codegen = CPU_CODEGEN_OPTIMIZE; cpu->flags_debug = CPU_DEBUG_NONE; cpu->flags_hint = CPU_HINT_NONE; cpu->flags = 0; // init the frontend cpu->f.init(cpu, &cpu->info, &cpu->rf); assert(is_valid_gpr_size(cpu->info.register_size[CPU_REG_GPR]) && "the specified GPR size is not guaranteed to work"); assert(is_valid_fpr_size(cpu->info.register_size[CPU_REG_FPR]) && "the specified FPR size is not guaranteed to work"); assert(is_valid_vr_size(cpu->info.register_size[CPU_REG_VR]) && "the specified VR size is not guaranteed to work"); assert(is_valid_gpr_size(cpu->info.register_size[CPU_REG_XR]) && "the specified XR size is not guaranteed to work"); uint32_t count = cpu->info.register_count[CPU_REG_GPR]; if (count != 0) { cpu->ptr_gpr = (Value **)calloc(count, sizeof(Value *)); cpu->in_ptr_gpr = (Value **)calloc(count, sizeof(Value *)); } else { cpu->ptr_gpr = NULL; cpu->in_ptr_gpr = NULL; } count = cpu->info.register_count[CPU_REG_XR]; if (count != 0) { cpu->ptr_xr = (Value **)calloc(count, sizeof(Value *)); cpu->in_ptr_xr = (Value **)calloc(count, sizeof(Value *)); } else { cpu->ptr_xr = NULL; cpu->in_ptr_xr = NULL; } count = cpu->info.register_count[CPU_REG_FPR]; if (count != 0) { cpu->ptr_fpr = (Value **)calloc(count, sizeof(Value *)); cpu->in_ptr_fpr = (Value **)calloc(count, sizeof(Value *)); } else { cpu->ptr_fpr = NULL; cpu->in_ptr_fpr = NULL; } if (cpu->info.psr_size != 0) { cpu->ptr_FLAG = (Value **)calloc(cpu->info.flags_count, sizeof(Value*)); assert(cpu->ptr_FLAG != NULL); } // init LLVM std::unique_ptr<llvm::Module> module_ptr(new Module(cpu->info.name, _CTX())); cpu->mod = module_ptr.get(); assert(cpu->mod != NULL); EngineBuilder builder{std::move(module_ptr)}; builder.setEngineKind(EngineKind::Kind::JIT); cpu->exec_engine = builder.create(); assert(cpu->exec_engine != NULL); // check if FP80 and FP128 are supported by this architecture. // XXX there is a better way to do this? std::string data_layout = cpu->exec_engine->getDataLayout().getStringRepresentation(); if (data_layout.find("f80") != std::string::npos) { LOG("INFO: FP80 supported.\n"); cpu->flags |= CPU_FLAG_FP80; } if (data_layout.find("f128") != std::string::npos) { LOG("INFO: FP128 supported.\n"); cpu->flags |= CPU_FLAG_FP128; } // check if we need to swap guest memory. if (cpu->exec_engine->getDataLayout().isLittleEndian() ^ IS_LITTLE_ENDIAN(cpu)) cpu->flags |= CPU_FLAG_SWAPMEM; cpu->timer_total[TIMER_TAG] = 0; cpu->timer_total[TIMER_FE] = 0; cpu->timer_total[TIMER_BE] = 0; cpu->timer_total[TIMER_RUN] = 0; return cpu; } void cpu_free(cpu_t *cpu) { if (cpu->f.done != NULL) cpu->f.done(cpu); if (cpu->exec_engine != NULL) { if (cpu->cur_func != NULL) { cpu->cur_func->eraseFromParent(); } delete cpu->exec_engine; } if (cpu->ctx != NULL) delete cpu->ctx; if (cpu->ptr_FLAG != NULL) free(cpu->ptr_FLAG); if (cpu->in_ptr_fpr != NULL) free(cpu->in_ptr_fpr); if (cpu->ptr_fpr != NULL) free(cpu->ptr_fpr); if (cpu->in_ptr_xr != NULL) free(cpu->in_ptr_xr); if (cpu->ptr_xr != NULL) free(cpu->ptr_xr); if (cpu->in_ptr_gpr != NULL) free(cpu->in_ptr_gpr); if (cpu->ptr_gpr != NULL) free(cpu->ptr_gpr); delete cpu; } void cpu_set_ram(cpu_t*cpu, uint8_t *r) { cpu->RAM = r; } void cpu_set_flags_codegen(cpu_t *cpu, uint32_t f) { cpu->flags_codegen = f; } void cpu_set_flags_debug(cpu_t *cpu, uint32_t f) { cpu->flags_debug = f; } void cpu_set_flags_hint(cpu_t *cpu, uint32_t f) { cpu->flags_hint = f; } void cpu_tag(cpu_t *cpu, addr_t pc) { update_timing(cpu, TIMER_TAG, true); tag_start(cpu, pc); update_timing(cpu, TIMER_TAG, false); } static void cpu_translate_function(cpu_t *cpu) { BasicBlock *bb_ret, *bb_trap, *label_entry, *bb_start; /* create function and fill it with std basic blocks */ cpu->cur_func = cpu_create_function(cpu, "jitmain", &bb_ret, &bb_trap, &label_entry); cpu->func[cpu->functions] = cpu->cur_func; /* TRANSLATE! */ update_timing(cpu, TIMER_FE, true); if (cpu->flags_debug & CPU_DEBUG_SINGLESTEP) { bb_start = cpu_translate_singlestep(cpu, bb_ret, bb_trap); } else if (cpu->flags_debug & CPU_DEBUG_SINGLESTEP_BB) { bb_start = cpu_translate_singlestep_bb(cpu, bb_ret, bb_trap); } else { bb_start = cpu_translate_all(cpu, bb_ret, bb_trap); } update_timing(cpu, TIMER_FE, false); /* finish entry basicblock */ BranchInst::Create(bb_start, label_entry); /* make sure everything is OK */ verifyFunction(*cpu->cur_func, &llvm::errs()); if (cpu->flags_debug & CPU_DEBUG_PRINT_IR) cpu->mod->print(llvm::errs(), nullptr); if (cpu->flags_codegen & CPU_CODEGEN_OPTIMIZE) { LOG("*** Optimizing..."); optimize(cpu); LOG("done.\n"); if (cpu->flags_debug & CPU_DEBUG_PRINT_IR_OPTIMIZED) cpu->mod->print(llvm::errs(), nullptr); } LOG("*** Translating..."); update_timing(cpu, TIMER_BE, true); cpu->fp[cpu->functions] = cpu->exec_engine->getPointerToFunction(cpu->cur_func); assert(cpu->fp[cpu->functions] != NULL); update_timing(cpu, TIMER_BE, false); LOG("done.\n"); cpu->functions++; } /* forces ahead of time translation (e.g. for benchmarking the run) */ void cpu_translate(cpu_t *cpu) { /* on demand translation */ if (cpu->tags_dirty) cpu_translate_function(cpu); cpu->tags_dirty = false; } typedef int (*fp_t)(uint8_t *RAM, void *grf, void *frf, debug_function_t fp); #ifdef __GNUC__ void __attribute__((noinline)) breakpoint() { asm("nop"); } #else void breakpoint() {} #endif int cpu_run(cpu_t *cpu, debug_function_t debug_function) { addr_t pc = 0, orig_pc = 0; uint32_t i; int ret; bool success; bool do_translate = true; /* try to find the entry in all functions */ while(true) { if (do_translate) { cpu_translate(cpu); pc = cpu->f.get_pc(cpu, cpu->rf.grf); } orig_pc = pc; success = false; for (i = 0; i < cpu->functions; i++) { fp_t FP = (fp_t)cpu->fp[i]; update_timing(cpu, TIMER_RUN, true); breakpoint(); ret = FP(cpu->RAM, cpu->rf.grf, cpu->rf.frf, debug_function); update_timing(cpu, TIMER_RUN, false); pc = cpu->f.get_pc(cpu, cpu->rf.grf); if (ret != JIT_RETURN_FUNCNOTFOUND) return ret; if (!is_inside_code_area(cpu, pc)) return ret; if (pc != orig_pc) { success = true; break; } } if (!success) { LOG("{%" PRIx64 "}", pc); cpu_tag(cpu, pc); do_translate = true; } } } //printf("%d\n", __LINE__); void cpu_flush(cpu_t *cpu) { cpu->cur_func->eraseFromParent(); cpu->functions = 0; // reset bb caching mapping cpu->func_bb.clear(); // delete cpu->mod; // cpu->mod = NULL; } void cpu_print_statistics(cpu_t *cpu) { printf("tag = %8" PRId64 "\n", cpu->timer_total[TIMER_TAG]); printf("fe = %8" PRId64 "\n", cpu->timer_total[TIMER_FE]); printf("be = %8" PRId64 "\n", cpu->timer_total[TIMER_BE]); printf("run = %8" PRId64 "\n", cpu->timer_total[TIMER_RUN]); } //printf("%s:%d\n", __func__, __LINE__); <|endoftext|>
<commit_before>#include <ctime> #include <functional> #include <boost/assert.hpp> #include <boost/range.hpp> #include "global.hpp" struct context_t { std::ostringstream& stream; std::tm tm; }; namespace aux { inline uint digits(int value) { if (value == 0) { return 1; } uint digits = 0; while (value) { value /= 10; digits++; } return digits; } } // namespace aux inline void fill(std::ostringstream& stream, int value, int length, char filler = '0') { const int digits = aux::digits(value); const int gap = length - digits; BOOST_ASSERT(gap >= 0); for (int i = 0; i < gap; ++i) { stream << filler; } stream << value; } namespace visit { namespace year { inline void full(context_t& context) { fill(context.stream, context.tm.tm_year, 4); } inline void normal(context_t& context) { fill(context.stream, context.tm.tm_year % 100, 2); } } // namespace year namespace month { inline void numeric(context_t& context) { fill(context.stream, context.tm.tm_mon, 2); } } // namespace month namespace day { namespace month { template<char Filler = '0'> inline void numeric(context_t& context) { fill(context.stream, context.tm.tm_mday, 2, Filler); } } // namespace month } // namespace day namespace hour { inline void h24(context_t& context) { fill(context.stream, context.tm.tm_hour, 2); } inline void h12(context_t& context) { const uint mod = context.tm.tm_hour % 12; fill(context.stream, mod == 0 ? 12 : mod, 2); } } // namespace hour namespace time { namespace minute { inline void normal(context_t& context) { fill(context.stream, context.tm.tm_min, 2); } } // namespace minute namespace second { inline void normal(context_t& context) { fill(context.stream, context.tm.tm_sec, 2); } } // namespace second } // namespace time } // namespace visit struct literal_generator_t { std::string literal; void operator()(context_t& context) const { context.stream << literal; } }; namespace datetime { typedef std::function<void(context_t&)> generator_action_t; //!@note: copyable, movable. class generator_t { std::vector<generator_action_t> actions; public: generator_t(std::vector<generator_action_t>&& actions) : actions(std::move(actions)) {} template<class Stream> void operator()(Stream& stream, const std::tm& tm) const { context_t context { stream, tm }; for (auto it = actions.begin(); it != actions.end(); ++it) { const generator_action_t& action = *it; action(context); } } }; class generator_handler_t { typedef std::string::const_iterator iterator_type; std::vector<generator_action_t>& actions; std::string m_literal; public: generator_handler_t(std::vector<generator_action_t>& actions) : actions(actions) {} virtual void partial_literal(iterator_type begin, iterator_type end) { m_literal.append(begin, end); } virtual void end_partial_literal() { if (!m_literal.empty()) { literal(boost::make_iterator_range(m_literal)); m_literal.clear(); } } virtual void literal(const boost::iterator_range<iterator_type>& range) { actions.push_back(literal_generator_t { boost::copy_range<std::string>(range) }); } virtual void placeholder(const boost::iterator_range<iterator_type>& range) { literal(range); } virtual void full_year() { end_partial_literal(); actions.push_back(&visit::year::full); } virtual void short_year() { end_partial_literal(); actions.push_back(&visit::year::normal); } virtual void numeric_month() { end_partial_literal(); actions.push_back(&visit::month::numeric); } virtual void month_day(bool has_leading_zero = true) { end_partial_literal(); if (has_leading_zero) { actions.push_back(&visit::day::month::numeric<'0'>); } else { actions.push_back(&visit::day::month::numeric<' '>); } } virtual void hours() { end_partial_literal(); actions.push_back(&visit::hour::h24); } virtual void hours12() { end_partial_literal(); actions.push_back(&visit::hour::h12); } virtual void minute() { end_partial_literal(); actions.push_back(&visit::time::minute::normal); } virtual void second() { end_partial_literal(); actions.push_back(&visit::time::second::normal); } }; namespace parser { class through_t { public: typedef std::string::const_iterator iterator_type; static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) { BOOST_ASSERT(it != end && it + 1 != end); handler.placeholder(boost::make_iterator_range(it, it + 2)); return it + 2; } }; template<class Decorate = through_t> class common { public: typedef typename Decorate::iterator_type iterator_type; }; template<class Decorate> class time { public: typedef typename Decorate::iterator_type iterator_type; static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) { BOOST_ASSERT(it != end && it + 1 != end); switch (*(it + 1)) { case 'H': handler.hours(); break; case 'I': handler.hours12(); break; case 'M': handler.minute(); break; case 'S': handler.second(); break; default: return Decorate::parse(it, end, handler); } return it + 2; } }; template<class Decorate> class date { public: typedef typename Decorate::iterator_type iterator_type; static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) { BOOST_ASSERT(it != end && it + 1 != end); switch (*(it + 1)) { case 'Y': handler.full_year(); break; case 'y': handler.short_year(); break; case 'm': handler.numeric_month(); break; case 'd': handler.month_day(); break; case 'e': handler.month_day(false); break; default: return Decorate::parse(it, end, handler); } return it + 2; } }; } // namespace parser template<class Decorate> class parser_t { typedef typename Decorate::iterator_type iterator_type; public: static void parse(const std::string& format, generator_handler_t& handler) { iterator_type it = format.begin(); iterator_type end = format.end(); while (it != end) { iterator_type p = std::find(it, end, '%'); handler.partial_literal(it, p); if (std::distance(p, end) >= 2) { it = Decorate::parse(p, end, handler); } else { if (p != end) { handler.partial_literal(p, end); } break; } } handler.end_partial_literal(); } }; class generator_factory_t { public: static generator_t make(const std::string& pattern) { std::vector<generator_action_t> actions; generator_handler_t handler(actions); parser_t<parser::date<parser::time<parser::through_t>>>::parse(pattern, handler); return generator_t(std::move(actions)); } }; } // namespace datetime using namespace datetime; class generator_test_case_t : public Test { protected: std::tm tm; void SetUp() { tm = std::tm(); } std::string generate(const std::string& pattern) { std::ostringstream stream; generator_t generator = generator_factory_t::make(pattern); generator(stream, tm); return stream.str(); } }; TEST_F(generator_test_case_t, FullYear) { tm.tm_year = 2014; EXPECT_EQ("2014", generate("%Y")); } TEST_F(generator_test_case_t, ShortYear) { tm.tm_year = 2014; EXPECT_EQ("14", generate("%y")); } TEST_F(generator_test_case_t, ShortYearWithZeroPrefix) { tm.tm_year = 2004; EXPECT_EQ("04", generate("%y")); } TEST_F(generator_test_case_t, ShortYearMinValue) { tm.tm_year = 2000; EXPECT_EQ("00", generate("%y")); } TEST_F(generator_test_case_t, FullYearWithSuffixLiteral) { tm.tm_year = 2014; EXPECT_EQ("2014-", generate("%Y-")); } TEST_F(generator_test_case_t, FullYearWithPrefixLiteral) { tm.tm_year = 2014; EXPECT_EQ("-2014", generate("-%Y")); } TEST_F(generator_test_case_t, FullYearWithPrefixAndSuffixLiteral) { tm.tm_year = 2014; EXPECT_EQ("-2014-", generate("-%Y-")); } TEST_F(generator_test_case_t, NumericMonth) { tm.tm_mon = 2; EXPECT_EQ("02", generate("%m")); } TEST_F(generator_test_case_t, NumericDayOfMonth) { tm.tm_mday = 23; EXPECT_EQ("23", generate("%d")); } TEST_F(generator_test_case_t, NumericDayOfMonthWithSingleDigit) { tm.tm_mday = 6; EXPECT_EQ("06", generate("%d")); } TEST_F(generator_test_case_t, ShortNumericDayOfMonth) { tm.tm_mday = 23; EXPECT_EQ("23", generate("%e")); } TEST_F(generator_test_case_t, FullDayHour) { tm.tm_hour = 11; EXPECT_EQ("11", generate("%H")); } TEST_F(generator_test_case_t, FullDayHourWithSingleDigit) { tm.tm_hour = 0; EXPECT_EQ("00", generate("%H")); } TEST_F(generator_test_case_t, HalfDayHour) { //!@note: tm_hour is treated as [0; 23], so 00:30 will be 12:30. tm.tm_hour = 11; EXPECT_EQ("11", generate("%I")); } TEST_F(generator_test_case_t, HalfDayHourWithSingleDigit) { tm.tm_hour = 6; EXPECT_EQ("06", generate("%I")); } TEST_F(generator_test_case_t, HalfDayHourWithOverflow) { tm.tm_hour = 13; EXPECT_EQ("01", generate("%I")); } TEST_F(generator_test_case_t, HalfDayHourLowerBorderCase) { tm.tm_hour = 0; EXPECT_EQ("12", generate("%I")); } TEST_F(generator_test_case_t, HalfDayHourUpperBorderCase) { tm.tm_hour = 12; EXPECT_EQ("12", generate("%I")); } TEST_F(generator_test_case_t, Minute) { tm.tm_min = 30; EXPECT_EQ("30", generate("%M")); } TEST_F(generator_test_case_t, MinuteLowerBound) { tm.tm_min = 00; EXPECT_EQ("00", generate("%M")); } TEST_F(generator_test_case_t, MinuteUpperBound) { tm.tm_min = 59; EXPECT_EQ("59", generate("%M")); } TEST_F(generator_test_case_t, Second) { tm.tm_sec = 30; EXPECT_EQ("30", generate("%S")); } TEST_F(generator_test_case_t, SecondLowerBound) { tm.tm_sec = 0; EXPECT_EQ("00", generate("%S")); } TEST_F(generator_test_case_t, SecondUpperBound) { tm.tm_sec = 60; EXPECT_EQ("60", generate("%S")); } <commit_msg>Additional test case added.<commit_after>#include <ctime> #include <functional> #include <boost/assert.hpp> #include <boost/range.hpp> #include "global.hpp" struct context_t { std::ostringstream& stream; std::tm tm; }; namespace aux { inline uint digits(int value) { if (value == 0) { return 1; } uint digits = 0; while (value) { value /= 10; digits++; } return digits; } } // namespace aux inline void fill(std::ostringstream& stream, int value, int length, char filler = '0') { const int digits = aux::digits(value); const int gap = length - digits; BOOST_ASSERT(gap >= 0); for (int i = 0; i < gap; ++i) { stream << filler; } stream << value; } namespace visit { namespace year { inline void full(context_t& context) { fill(context.stream, context.tm.tm_year, 4); } inline void normal(context_t& context) { fill(context.stream, context.tm.tm_year % 100, 2); } } // namespace year namespace month { inline void numeric(context_t& context) { fill(context.stream, context.tm.tm_mon, 2); } } // namespace month namespace day { namespace month { template<char Filler = '0'> inline void numeric(context_t& context) { fill(context.stream, context.tm.tm_mday, 2, Filler); } } // namespace month } // namespace day namespace hour { inline void h24(context_t& context) { fill(context.stream, context.tm.tm_hour, 2); } inline void h12(context_t& context) { const uint mod = context.tm.tm_hour % 12; fill(context.stream, mod == 0 ? 12 : mod, 2); } } // namespace hour namespace time { namespace minute { inline void normal(context_t& context) { fill(context.stream, context.tm.tm_min, 2); } } // namespace minute namespace second { inline void normal(context_t& context) { fill(context.stream, context.tm.tm_sec, 2); } } // namespace second } // namespace time } // namespace visit struct literal_generator_t { std::string literal; void operator()(context_t& context) const { context.stream << literal; } }; namespace datetime { typedef std::function<void(context_t&)> generator_action_t; //!@note: copyable, movable. class generator_t { std::vector<generator_action_t> actions; public: generator_t(std::vector<generator_action_t>&& actions) : actions(std::move(actions)) {} template<class Stream> void operator()(Stream& stream, const std::tm& tm) const { context_t context { stream, tm }; for (auto it = actions.begin(); it != actions.end(); ++it) { const generator_action_t& action = *it; action(context); } } }; class generator_handler_t { typedef std::string::const_iterator iterator_type; std::vector<generator_action_t>& actions; std::string m_literal; public: generator_handler_t(std::vector<generator_action_t>& actions) : actions(actions) {} virtual void partial_literal(iterator_type begin, iterator_type end) { m_literal.append(begin, end); } virtual void end_partial_literal() { if (!m_literal.empty()) { literal(boost::make_iterator_range(m_literal)); m_literal.clear(); } } virtual void literal(const boost::iterator_range<iterator_type>& range) { actions.push_back(literal_generator_t { boost::copy_range<std::string>(range) }); } virtual void placeholder(const boost::iterator_range<iterator_type>& range) { literal(range); } virtual void full_year() { end_partial_literal(); actions.push_back(&visit::year::full); } virtual void short_year() { end_partial_literal(); actions.push_back(&visit::year::normal); } virtual void numeric_month() { end_partial_literal(); actions.push_back(&visit::month::numeric); } virtual void month_day(bool has_leading_zero = true) { end_partial_literal(); if (has_leading_zero) { actions.push_back(&visit::day::month::numeric<'0'>); } else { actions.push_back(&visit::day::month::numeric<' '>); } } virtual void hours() { end_partial_literal(); actions.push_back(&visit::hour::h24); } virtual void hours12() { end_partial_literal(); actions.push_back(&visit::hour::h12); } virtual void minute() { end_partial_literal(); actions.push_back(&visit::time::minute::normal); } virtual void second() { end_partial_literal(); actions.push_back(&visit::time::second::normal); } }; namespace parser { class through_t { public: typedef std::string::const_iterator iterator_type; static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) { BOOST_ASSERT(it != end && it + 1 != end); handler.placeholder(boost::make_iterator_range(it, it + 2)); return it + 2; } }; template<class Decorate = through_t> class common { public: typedef typename Decorate::iterator_type iterator_type; }; template<class Decorate> class time { public: typedef typename Decorate::iterator_type iterator_type; static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) { BOOST_ASSERT(it != end && it + 1 != end); switch (*(it + 1)) { case 'H': handler.hours(); break; case 'I': handler.hours12(); break; case 'M': handler.minute(); break; case 'S': handler.second(); break; default: return Decorate::parse(it, end, handler); } return it + 2; } }; template<class Decorate> class date { public: typedef typename Decorate::iterator_type iterator_type; static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) { BOOST_ASSERT(it != end && it + 1 != end); switch (*(it + 1)) { case 'Y': handler.full_year(); break; case 'y': handler.short_year(); break; case 'm': handler.numeric_month(); break; case 'd': handler.month_day(); break; case 'e': handler.month_day(false); break; default: return Decorate::parse(it, end, handler); } return it + 2; } }; } // namespace parser template<class Decorate> class parser_t { typedef typename Decorate::iterator_type iterator_type; public: static void parse(const std::string& format, generator_handler_t& handler) { iterator_type it = format.begin(); iterator_type end = format.end(); while (it != end) { iterator_type p = std::find(it, end, '%'); handler.partial_literal(it, p); if (std::distance(p, end) >= 2) { it = Decorate::parse(p, end, handler); } else { if (p != end) { handler.partial_literal(p, end); } break; } } handler.end_partial_literal(); } }; class generator_factory_t { public: static generator_t make(const std::string& pattern) { std::vector<generator_action_t> actions; generator_handler_t handler(actions); parser_t<parser::date<parser::time<parser::through_t>>>::parse(pattern, handler); return generator_t(std::move(actions)); } }; } // namespace datetime using namespace datetime; class generator_test_case_t : public Test { protected: std::tm tm; void SetUp() { tm = std::tm(); } std::string generate(const std::string& pattern) { std::ostringstream stream; generator_t generator = generator_factory_t::make(pattern); generator(stream, tm); return stream.str(); } }; TEST_F(generator_test_case_t, FullYear) { tm.tm_year = 2014; EXPECT_EQ("2014", generate("%Y")); } TEST_F(generator_test_case_t, ShortYear) { tm.tm_year = 2014; EXPECT_EQ("14", generate("%y")); } TEST_F(generator_test_case_t, ShortYearWithZeroPrefix) { tm.tm_year = 2004; EXPECT_EQ("04", generate("%y")); } TEST_F(generator_test_case_t, ShortYearMinValue) { tm.tm_year = 2000; EXPECT_EQ("00", generate("%y")); } TEST_F(generator_test_case_t, FullYearWithSuffixLiteral) { tm.tm_year = 2014; EXPECT_EQ("2014-", generate("%Y-")); } TEST_F(generator_test_case_t, FullYearWithPrefixLiteral) { tm.tm_year = 2014; EXPECT_EQ("-2014", generate("-%Y")); } TEST_F(generator_test_case_t, FullYearWithPrefixAndSuffixLiteral) { tm.tm_year = 2014; EXPECT_EQ("-2014-", generate("-%Y-")); } TEST_F(generator_test_case_t, NumericMonth) { tm.tm_mon = 2; EXPECT_EQ("02", generate("%m")); } TEST_F(generator_test_case_t, NumericDayOfMonth) { tm.tm_mday = 23; EXPECT_EQ("23", generate("%d")); } TEST_F(generator_test_case_t, NumericDayOfMonthWithSingleDigit) { tm.tm_mday = 6; EXPECT_EQ("06", generate("%d")); } TEST_F(generator_test_case_t, ShortNumericDayOfMonth) { tm.tm_mday = 23; EXPECT_EQ("23", generate("%e")); } TEST_F(generator_test_case_t, FullDayHour) { tm.tm_hour = 11; EXPECT_EQ("11", generate("%H")); } TEST_F(generator_test_case_t, FullDayHourWithSingleDigit) { tm.tm_hour = 0; EXPECT_EQ("00", generate("%H")); } TEST_F(generator_test_case_t, HalfDayHour) { //!@note: tm_hour is treated as [0; 23], so 00:30 will be 12:30. tm.tm_hour = 11; EXPECT_EQ("11", generate("%I")); } TEST_F(generator_test_case_t, HalfDayHourWithSingleDigit) { tm.tm_hour = 6; EXPECT_EQ("06", generate("%I")); } TEST_F(generator_test_case_t, HalfDayHourWithOverflow) { tm.tm_hour = 13; EXPECT_EQ("01", generate("%I")); } TEST_F(generator_test_case_t, HalfDayHourLowerBorderCase) { tm.tm_hour = 0; EXPECT_EQ("12", generate("%I")); } TEST_F(generator_test_case_t, HalfDayHourUpperBorderCase) { tm.tm_hour = 12; EXPECT_EQ("12", generate("%I")); } TEST_F(generator_test_case_t, Minute) { tm.tm_min = 30; EXPECT_EQ("30", generate("%M")); } TEST_F(generator_test_case_t, MinuteLowerBound) { tm.tm_min = 00; EXPECT_EQ("00", generate("%M")); } TEST_F(generator_test_case_t, MinuteUpperBound) { tm.tm_min = 59; EXPECT_EQ("59", generate("%M")); } TEST_F(generator_test_case_t, Second) { tm.tm_sec = 30; EXPECT_EQ("30", generate("%S")); } TEST_F(generator_test_case_t, SecondLowerBound) { tm.tm_sec = 0; EXPECT_EQ("00", generate("%S")); } TEST_F(generator_test_case_t, SecondUpperBound) { tm.tm_sec = 60; EXPECT_EQ("60", generate("%S")); } TEST_F(generator_test_case_t, ComplexFormatting) { tm.tm_year = 2014; tm.tm_mon = 2; tm.tm_mday = 23; tm.tm_hour = 12; tm.tm_min = 20; tm.tm_sec = 30; EXPECT_EQ("2014-02-23 12:20:30", generate("%Y-%m-%d %H:%M:%S")); } <|endoftext|>