hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9af9dbd4726dc1e201a761fc788ab732f86e97f3
| 28,252
|
cpp
|
C++
|
examples/38_wifiscope/main/WebServer.cpp
|
graealex/qemu_esp32
|
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
|
[
"Apache-2.0"
] | 335
|
2016-10-12T06:59:33.000Z
|
2022-03-29T14:26:04.000Z
|
examples/38_wifiscope/main/WebServer.cpp
|
graealex/qemu_esp32
|
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
|
[
"Apache-2.0"
] | 30
|
2016-10-30T11:23:59.000Z
|
2021-11-12T10:51:20.000Z
|
examples/38_wifiscope/main/WebServer.cpp
|
graealex/qemu_esp32
|
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
|
[
"Apache-2.0"
] | 48
|
2016-10-30T08:41:13.000Z
|
2022-02-15T22:15:09.000Z
|
/*
* WebServer.cpp
*
* Created on: May 19, 2017
* Author: kolban
*/
#include <sstream>
#include <iostream>
#include <vector>
#include <map>
#include <regex>
#include "sdkconfig.h"
#define MG_ENABLE_HTTP_STREAMING_MULTIPART 1
#define MG_ENABLE_FILESYSTEM 1
#include "WebServer.h"
#include <esp_log.h>
#include <mongoose.h>
#include <string>
static char tag[] = "WebServer";
struct WebServerUserData {
WebServer *pWebServer;
WebServer::HTTPMultiPart *pMultiPart;
WebServer::WebSocketHandler *pWebSocketHandler;
void *originalUserData;
};
/**
* @brief Convert a Mongoose event type to a string.
* @param [in] event The received event type.
* @return The string representation of the event.
*/
static std::string mongoose_eventToString(int event) {
switch (event) {
case MG_EV_CONNECT:
return "MG_EV_CONNECT";
case MG_EV_ACCEPT:
return "MG_EV_ACCEPT";
case MG_EV_CLOSE:
return "MG_EV_CLOSE";
case MG_EV_SEND:
return "MG_EV_SEND";
case MG_EV_RECV:
return "MG_EV_RECV";
case MG_EV_POLL:
return "MG_EV_POLL";
case MG_EV_TIMER:
return "MG_EV_TIMER";
case MG_EV_HTTP_PART_DATA:
return "MG_EV_HTTP_PART_DATA";
case MG_EV_HTTP_MULTIPART_REQUEST:
return "MG_EV_HTTP_MULTIPART_REQUEST";
case MG_EV_HTTP_PART_BEGIN:
return "MG_EV_HTTP_PART_BEGIN";
case MG_EV_HTTP_PART_END:
return "MG_EV_HTTP_PART_END";
case MG_EV_HTTP_MULTIPART_REQUEST_END:
return "MG_EV_HTTP_MULTIPART_REQUEST_END";
case MG_EV_HTTP_REQUEST:
return "MG_EV_HTTP_REQUEST";
case MG_EV_HTTP_REPLY:
return "MG_EV_HTTP_REPLY";
case MG_EV_HTTP_CHUNK:
return "MG_EV_HTTP_CHUNK";
case MG_EV_MQTT_CONNACK:
return "MG_EV_MQTT_CONNACK";
case MG_EV_MQTT_CONNECT:
return "MG_EV_MQTT_CONNECT";
case MG_EV_MQTT_DISCONNECT:
return "MG_EV_MQTT_DISCONNECT";
case MG_EV_MQTT_PINGREQ:
return "MG_EV_MQTT_PINGREQ";
case MG_EV_MQTT_PINGRESP:
return "MG_EV_MQTT_PINGRESP";
case MG_EV_MQTT_PUBACK:
return "MG_EV_MQTT_PUBACK";
case MG_EV_MQTT_PUBCOMP:
return "MG_EV_MQTT_PUBCOMP";
case MG_EV_MQTT_PUBLISH:
return "MG_EV_MQTT_PUBLISH";
case MG_EV_MQTT_PUBREC:
return "MG_EV_MQTT_PUBREC";
case MG_EV_MQTT_PUBREL:
return "MG_EV_MQTT_PUBREL";
case MG_EV_MQTT_SUBACK:
return "MG_EV_MQTT_SUBACK";
case MG_EV_MQTT_SUBSCRIBE:
return "MG_EV_MQTT_SUBSCRIBE";
case MG_EV_MQTT_UNSUBACK:
return "MG_EV_MQTT_UNSUBACK";
case MG_EV_MQTT_UNSUBSCRIBE:
return "MG_EV_MQTT_UNSUBSCRIBE";
case MG_EV_WEBSOCKET_HANDSHAKE_REQUEST:
return "MG_EV_WEBSOCKET_HANDSHAKE_REQUEST";
case MG_EV_WEBSOCKET_HANDSHAKE_DONE:
return "MG_EV_WEBSOCKET_HANDSHAKE_DONE";
case MG_EV_WEBSOCKET_FRAME:
return "MG_EV_WEBSOCKET_FRAME";
case MG_EV_WEBSOCKET_CONTROL_FRAME:
return "MG_EV_WEBSOCKET_CONTROL_FRAME";
}
std::ostringstream s;
s << "Unknown event: " << event;
return s.str();
} //eventToString
/**
* @brief Convert a Mongoose string type to a string.
* @param [in] mgStr The Mongoose string.
* @return A std::string representation of the Mongoose string.
*/
static std::string mgStrToString(struct mg_str mgStr) {
return std::string(mgStr.p, mgStr.len);
} // mgStrToStr
static void dumpHttpMessage(struct http_message *pHttpMessage) {
ESP_LOGD(tag, "HTTP Message");
ESP_LOGD(tag, "Message: %s", mgStrToString(pHttpMessage->message).c_str());
ESP_LOGD(tag, "URI: %s", mgStrToString(pHttpMessage->uri).c_str());
}
/*
static struct mg_str uploadFileNameHandler(struct mg_connection *mgConnection, struct mg_str fname) {
ESP_LOGD(tag, "uploadFileNameHandler: %s", mgStrToString(fname).c_str());
return fname;
}
*/
/**
* @brief Mongoose event handler.
* The event handler is called when an event occurs associated with the WebServer
* listening network connection.
*
* @param [in] mgConnection The network connection associated with the event.
* @param [in] event The type of event.
* @param [in] eventData Data associated with the event.
* @return N/A.
*/
static void mongoose_event_handler_web_server(
struct mg_connection *mgConnection, // The network connection associated with the event.
int event, // The type of event.
void *eventData // Data associated with the event.
) {
if (event == MG_EV_POLL) {
return;
}
ESP_LOGD(tag, "Event: %s [%d]", mongoose_eventToString(event).c_str(), mgConnection->sock);
switch (event) {
case MG_EV_HTTP_REQUEST: {
struct http_message *message = (struct http_message *) eventData;
dumpHttpMessage(message);
struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
WebServer *pWebServer = pWebServerUserData->pWebServer;
if (!pWebServer->processRequest(mgConnection, message))
{
}
break;
} // MG_EV_HTTP_REQUEST
case MG_EV_HTTP_MULTIPART_REQUEST: {
struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
ESP_LOGD(tag, "User_data address 0x%d", (uint32_t)pWebServerUserData);
WebServer *pWebServer = pWebServerUserData->pWebServer;
if (pWebServer->m_pMultiPartFactory == nullptr) {
return;
}
WebServer::HTTPMultiPart *pMultiPart = pWebServer->m_pMultiPartFactory->newInstance();
struct WebServerUserData *p2 = new WebServerUserData();
ESP_LOGD(tag, "New User_data address 0x%d", (uint32_t)p2);
p2->originalUserData = pWebServerUserData;
p2->pWebServer = pWebServerUserData->pWebServer;
p2->pMultiPart = pMultiPart;
p2->pWebSocketHandler = nullptr;
mgConnection->user_data = p2;
//struct http_message *message = (struct http_message *) eventData;
//dumpHttpMessage(message);
break;
} // MG_EV_HTTP_MULTIPART_REQUEST
case MG_EV_HTTP_MULTIPART_REQUEST_END: {
struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
if (pWebServerUserData->pMultiPart != nullptr) {
delete pWebServerUserData->pMultiPart;
pWebServerUserData->pMultiPart = nullptr;
}
mgConnection->user_data = pWebServerUserData->originalUserData;
delete pWebServerUserData;
WebServer::HTTPResponse httpResponse = WebServer::HTTPResponse(mgConnection);
httpResponse.setStatus(200);
httpResponse.sendData("");
break;
} // MG_EV_HTTP_MULTIPART_REQUEST_END
case MG_EV_HTTP_PART_BEGIN: {
struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
struct mg_http_multipart_part *part = (struct mg_http_multipart_part *)eventData;
ESP_LOGD(tag, "file_name: \"%s\", var_name: \"%s\", status: %d, user_data: 0x%d",
part->file_name, part->var_name, part->status, (uint32_t)part->user_data);
if (pWebServerUserData->pMultiPart != nullptr) {
pWebServerUserData->pMultiPart->begin(std::string(part->var_name), std::string(part->file_name));
}
break;
} // MG_EV_HTTP_PART_BEGIN
case MG_EV_HTTP_PART_DATA: {
struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
struct mg_http_multipart_part *part = (struct mg_http_multipart_part *)eventData;
ESP_LOGD(tag, "file_name: \"%s\", var_name: \"%s\", status: %d, user_data: 0x%d",
part->file_name, part->var_name, part->status, (uint32_t)part->user_data);
if (pWebServerUserData->pMultiPart != nullptr) {
pWebServerUserData->pMultiPart->data(mgStrToString(part->data));
}
break;
} // MG_EV_HTTP_PART_DATA
case MG_EV_HTTP_PART_END: {
struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
struct mg_http_multipart_part *part = (struct mg_http_multipart_part *)eventData;
ESP_LOGD(tag, "file_name: \"%s\", var_name: \"%s\", status: %d, user_data: 0x%d",
part->file_name, part->var_name, part->status, (uint32_t)part->user_data);
if (pWebServerUserData->pMultiPart != nullptr) {
pWebServerUserData->pMultiPart->end();
}
break;
} // MG_EV_HTTP_PART_END
case MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: {
struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
WebServer *pWebServer = pWebServerUserData->pWebServer;
if (pWebServer->m_pWebSocketHandlerFactory != nullptr) {
if (pWebServerUserData->pWebSocketHandler != nullptr) {
ESP_LOGD(tag, "Warning: MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: pWebSocketHandler was NOT null");
}
struct WebServerUserData *p2 = new WebServerUserData();
ESP_LOGD(tag, "New User_data address 0x%d", (uint32_t)p2);
p2->originalUserData = pWebServerUserData;
p2->pWebServer = pWebServerUserData->pWebServer;
p2->pWebSocketHandler = pWebServer->m_pWebSocketHandlerFactory->newInstance();
mgConnection->user_data = p2;
} else {
ESP_LOGD(tag, "We received a WebSocket request but we have no handler factory!");
}
break;
} // MG_EV_WEBSOCKET_HANDSHAKE_REQUEST
case MG_EV_WEBSOCKET_HANDSHAKE_DONE: {
struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
if (pWebServerUserData->pWebSocketHandler == nullptr) {
ESP_LOGE(tag, "Error: MG_EV_WEBSOCKET_FRAME: pWebSocketHandler is null");
return;
}
pWebServerUserData->pWebSocketHandler->onCreated();
break;
} // MG_EV_WEBSOCKET_HANDSHAKE_DONE
/*
* When we receive a MG_EV_WEBSOCKET_FRAME then we have received a chunk of data over the network.
* Our goal will be to send this to the web socket handler (if one exists).
*/
case MG_EV_WEBSOCKET_FRAME: {
struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data;
if (pWebServerUserData->pWebSocketHandler == nullptr) {
ESP_LOGE(tag, "Error: MG_EV_WEBSOCKET_FRAME: pWebSocketHandler is null");
return;
}
struct websocket_message *ws_message = (websocket_message *)eventData;
ESP_LOGD(tag, "Received data length: %d", ws_message->size);
pWebServerUserData->pWebSocketHandler->onMessage(std::string((char *)ws_message->data, ws_message->size));
break;
} // MG_EV_WEBSOCKET_FRAME
} // End of switch
} // End of mongoose_event_handler
/**
* @brief Constructor.
*/
WebServer::WebServer() {
m_rootPath = "";
m_pMultiPartFactory = nullptr;
m_pWebSocketHandlerFactory = nullptr;
} // WebServer
WebServer::~WebServer() {
}
/**
* @brief Get the current root path.
* @return The current root path.
*/
std::string WebServer::getRootPath() {
return m_rootPath;
} // getRootPath
/**
* @brief Register a handler for a path.
*
* When a browser request arrives, the request will contain a method (GET, POST, etc) and a path
* to be accessed. Using this method we can register a regular expression and, if the incoming method
* and path match the expression, the corresponding handler will be called.
*
* Example:
* @code{.cpp}
* static void handle_REST_WiFi(WebServer::HTTPRequest *pRequest, WebServer::HTTPResponse *pResponse) {
* ...
* }
*
* webServer.addPathHandler("GET", "\\/ESP32\\/WiFi", handle_REST_WiFi);
* @endcode
*
* @param [in] method The method being used for access ("GET", "POST" etc).
* @param [in] pathExpr The path being accessed.
* @param [in] handler The callback function to be invoked when a request arrives.
*/
void WebServer::addPathHandler(std::string method, std::string pathExpr, void (*handler)(WebServer::HTTPRequest *pHttpRequest, WebServer::HTTPResponse *pHttpResponse)) {
m_pathHandlers.push_back(PathHandler(method, pathExpr, handler));
} // addPathHandler
/**
* @brief Run the web server listening at the given port.
*
* This function does not return.
*
* @param [in] port The port number of which to listen.
* @return N/A.
*/
void WebServer::start(uint16_t port) {
ESP_LOGD(tag, "WebServer task starting");
struct mg_mgr mgr;
mg_mgr_init(&mgr, NULL);
std::stringstream stringStream;
stringStream << ':' << port;
struct mg_connection *mgConnection = mg_bind(&mgr, stringStream.str().c_str(), mongoose_event_handler_web_server);
if (mgConnection == NULL) {
ESP_LOGE(tag, "No connection from the mg_bind()");
vTaskDelete(NULL);
return;
}
struct WebServerUserData *pWebServerUserData = new WebServerUserData();
pWebServerUserData->pWebServer = this;
pWebServerUserData->pMultiPart = nullptr;
mgConnection->user_data = pWebServerUserData; // Save the WebServer instance reference in user_data.
ESP_LOGD(tag, "start: User_data address 0x%d", (uint32_t)pWebServerUserData);
mg_set_protocol_http_websocket(mgConnection);
ESP_LOGD(tag, "WebServer listening on port %d", port);
while (1) {
mg_mgr_poll(&mgr, 2000);
}
} // run
/**
* @brief Set the multi part factory.
* @param [in] pMultiPart A pointer to the multi part factory.
*/
void WebServer::setMultiPartFactory(HTTPMultiPartFactory *pMultiPartFactory) {
m_pMultiPartFactory = pMultiPartFactory;
}
/**
* @brief Set the root path for URL file mapping.
*
* When a browser requests a file, it uses the address form:
*
* @code{.unparsed}
* http://<host>:<port>/<path>
* @endcode
*
* The path part can be considered the path to where the file should be retrieved on the
* file system available to the web server. Typically, we want a directory structure on the file
* system to host the web served files and not expose the whole file system. Using this method
* we specify the root directory from which the files will be served.
*
* @param [in] path The root path on the file system.
* @return N/A.
*/
void WebServer::setRootPath(std::string path) {
m_rootPath = path;
} // setRootPath
/**
* @brief Register the factory for creating web socket handlers.
*
* @param [in] pWebSocketHandlerFactory The instance that will create WebSocketHandlers.
* @return N/A.
*/
void WebServer::setWebSocketHandlerFactory(WebSocketHandlerFactory* pWebSocketHandlerFactory) {
m_pWebSocketHandlerFactory = pWebSocketHandlerFactory;
} // setWebSocketHandlerFactory
/**
* @brief Constructor.
* @param [in] nc The network connection for the response.
*/
WebServer::HTTPResponse::HTTPResponse(struct mg_connection* nc) {
m_nc = nc;
m_status = 200;
m_dataSent = false;
} // HTTPResponse
/**
* @brief Add a header to the response.
* @param [in] name The name of the header.
* @param [in] value The value of the header.
*/
void WebServer::HTTPResponse::addHeader(std::string name, std::string value) {
m_headers[name] = value;
} // addHeader
/**
* @brief Send data to the HTTP caller.
* Send the data to the HTTP caller. No further data should be sent after this call.
* @param [in] data The data to be sent to the HTTP caller.
* @return N/A.
*/
void WebServer::HTTPResponse::sendData(std::string data) {
sendData((uint8_t *)data.data(), data.length());
} // sendData
/**
* @brief Send data to the HTTP caller.
* Send the data to the HTTP caller. No further data should be sent after this call.
* @param [in] pData The data to be sent to the HTTP caller.
* @param [in] length The length of the data to be sent.
* @return N/A.
*/
void WebServer::HTTPResponse::sendData(uint8_t *pData, size_t length) {
if (m_dataSent) {
ESP_LOGE(tag, "HTTPResponse: Data already sent! Attempt to send again/more.");
return;
}
m_dataSent = true;
std::map<std::string, std::string>::iterator iter;
std::string headers;
for (iter = m_headers.begin(); iter != m_headers.end(); iter++) {
if (headers.length() == 0) {
headers = iter->first + ": " + iter->second;
} else {
headers = "; " + iter->first + "=" + iter->second;
}
}
mg_send_head(m_nc, m_status, length, headers.c_str());
mg_send(m_nc, pData, length);
m_nc->flags |= MG_F_SEND_AND_CLOSE;
} // sendData
/**
* @brief Send more data to the HTTP caller.
* Send the data to the HTTP caller.
* @param [in] pData The data to be sent to the HTTP caller.
* @param [in] length The length of the data to be sent.
* @return N/A.
*/
void WebServer::HTTPResponse::sendMoreData(uint8_t *pData, size_t length) {
m_nc->flags &= ~MG_F_SEND_AND_CLOSE;
mg_send(m_nc, pData, length);
m_nc->flags |= MG_F_SEND_AND_CLOSE;
}
/**
* @brief Set the headers to be sent in the HTTP response.
* @param [in] headers The complete set of headers to send to the caller.
* @return N/A.
*/
void WebServer::HTTPResponse::setHeaders(std::map<std::string, std::string> headers) {
m_headers = headers;
} // setHeaders
/**
* @brief Get the current root path.
* @return The current root path.
*/
std::string WebServer::HTTPResponse::getRootPath() {
return m_rootPath;
} // getRootPath
/**
* @brief Set the root path for URL file mapping.
* @param [in] path The root path on the file system.
* @return N/A.
*/
void WebServer::HTTPResponse::setRootPath(std::string path) {
m_rootPath = path;
} // setRootPath
/**
* @brief Set the status value in the HTTP response.
*
* The default if not set is 200.
* @param [in] status The HTTP status code sent to the caller.
* @return N/A.
*/
void WebServer::HTTPResponse::setStatus(int status) {
m_status = status;
} // setStatus
extern "C" struct mg_str mg_get_mime_type(const char *path);
/**
* @brief Process an incoming HTTP request.
*
* We look at the path of the request and see if it has a matching path handler. If it does,
* we invoke the handler function. If it does not, we try and find a file on the file system
* that would resolve to the path.
*
* @param [in] mgConnection The network connection on which the request was received.
* @param [in] message The message representing the request.
*/
bool WebServer::processRequest(struct mg_connection *mgConnection, struct http_message* message) {
std::string uri = mgStrToString(message->uri);
ESP_LOGD(tag, "WebServer::processRequest: Matching: %s", uri.c_str());
HTTPResponse httpResponse = HTTPResponse(mgConnection);
httpResponse.setRootPath(getRootPath());
/*
* Iterate through each of the path handlers looking for a match with the method and specified path.
*/
std::vector<PathHandler>::iterator it;
for (it = m_pathHandlers.begin(); it < m_pathHandlers.end(); it++) {
if ((*it).match(mgStrToString(message->method), uri)) {
HTTPRequest httpRequest(message);
(*it).invoke(&httpRequest, &httpResponse);
ESP_LOGD(tag, "Found a match!!");
return true;
}
} // End of examine path handlers.
// Because we reached here, it means that we did NOT match a handler. Now we want to attempt
// to retrieve the corresponding file content.
std::string filePath = httpResponse.getRootPath() + uri;
if (uri.size()==1)
{
filePath = httpResponse.getRootPath() + std::string("/index.html");
}
mg_http_serve_file(mgConnection, message, filePath.c_str(),
mg_get_mime_type(filePath.c_str()), mg_mk_str(""));
#if 0
std::string filePath = httpResponse.getRootPath() + uri;
ESP_LOGD(tag, "Opening file: %s", filePath.c_str());
FILE *file = fopen(filePath.c_str(), "r");
if (file != nullptr) {
fseek(file, 0L, SEEK_END);
size_t length = ftell(file);
fseek(file, 0L, SEEK_SET);
uint8_t *pData = (uint8_t *)malloc(length);
if (pData!=NULL) {
fread(pData, length, 1, file);
fclose(file);
httpResponse.sendData(pData, length);
free(pData);
} else {
uint8_t *pData = (uint8_t *)malloc(1024);
if (pData==NULL) {
httpResponse.setStatus(404); // Not found, TODO Out of memory
httpResponse.sendData("");
}
fread(pData, 1024, 1, file);
httpResponse.sendData(pData, 1024);
int remaining=length-1024;
while (remaining>0) {
fread(pData, 1024, 1, file);
if (remaining>1024) {
httpResponse.sendMoreData(pData, 1024);
} else {
httpResponse.sendMoreData(pData, remaining);
}
remaining-=1024;
}
free(pData);
}
} else {
// Handle unable to open file
httpResponse.setStatus(404); // Not found
httpResponse.sendData("");
}
#endif
return false;
} // processRequest
/**
* @brief Construct an instance of a PathHandler.
*
* @param [in] method The method to be matched.
* @param [in] pathPattern The path pattern to be matched.
* @param [in] webServerRequestHandler The request handler to be called.
*/
WebServer::PathHandler::PathHandler(std::string method, std::string pathPattern, void (*webServerRequestHandler)(WebServer::HTTPRequest *pHttpRequest, WebServer::HTTPResponse *pHttpResponse)) {
m_method = method;
m_pattern = std::regex(pathPattern);
m_requestHandler = webServerRequestHandler;
} // PathHandler
/**
* @brief Determine if the path matches.
*
* @param [in] method The method to be matched.
* @param [in] path The path to be matched.
* @return True if the path matches.
*/
bool WebServer::PathHandler::match(std::string method, std::string path) {
//ESP_LOGD(tag, "match: %s with %s", m_pattern.c_str(), path.c_str());
if (method != m_method) {
return false;
}
return std::regex_search(path, m_pattern);
} // match
/**
* @brief Invoke the handler.
* @param [in] request An object representing the request.
* @param [in] response An object representing the response.
* @return N/A.
*/
void WebServer::PathHandler::invoke(WebServer::HTTPRequest* request, WebServer::HTTPResponse *response) {
m_requestHandler(request, response);
} // invoke
/**
* @brief Create an HTTPRequest instance.
* When mongoose received an HTTP request, we want to encapsulate that to hide the
* mongoose complexities. We create an instance of this class to hide those.
* @param [in] message The description of the underlying Mongoose message.
*/
WebServer::HTTPRequest::HTTPRequest(struct http_message* message) {
m_message = message;
} // HTTPRequest
/**
* @brief Get the body of the request.
* When an HTTP request is either PUT or POST then it may contain a payload that is also
* known as the body. This method returns that payload (if it exists).
* @return The body of the request.
*/
std::string WebServer::HTTPRequest::getBody() {
return mgStrToString(m_message->body);
} // getBody
/**
* @brief Get the method of the request.
* An HTTP request contains a request method which is one of GET, PUT, POST, etc.
* @return The method of the request.
*/
std::string WebServer::HTTPRequest::getMethod() {
return mgStrToString(m_message->method);
} // getMethod
/**
* @brief Get the path of the request.
* The path of an HTTP request is the portion of the URL that follows the hostname/port pair
* but does not include any query parameters.
* @return The path of the request.
*/
std::string WebServer::HTTPRequest::getPath() {
return mgStrToString(m_message->uri);
} // getPath
#define STATE_NAME 0
#define STATE_VALUE 1
/**
* @brief Get the query part of the request.
* The query is a set of name = value pairs. The return is a map keyed by the name items.
*
* @return The query part of the request.
*/
std::map<std::string, std::string> WebServer::HTTPRequest::getQuery() {
// Walk through all the characters in the query string maintaining a simple state machine
// that lets us know what we are parsing.
std::map<std::string, std::string> queryMap;
std::string queryString = mgStrToString(m_message->query_string);
int i=0;
/*
* We maintain a simple state machine with states of:
* * STATE_NAME - We are parsing a name.
* * STATE_VALUE - We are parsing a value.
*/
int state = STATE_NAME;
std::string name = "";
std::string value;
// Loop through each character in the query string.
for (i=0; i<queryString.length(); i++) {
char currentChar = queryString[i];
if (state == STATE_NAME) {
if (currentChar != '=') {
name += currentChar;
} else {
state = STATE_VALUE;
value = "";
}
} // End state = STATE_NAME
else if (state == STATE_VALUE) {
if (currentChar != '&') {
value += currentChar;
} else {
//ESP_LOGD(tag, "name=%s, value=%s", name.c_str(), value.c_str());
queryMap[name] = value;
state = STATE_NAME;
name = "";
}
} // End state = STATE_VALUE
} // End for loop
if (state == STATE_VALUE) {
//ESP_LOGD(tag, "name=%s, value=%s", name.c_str(), value.c_str());
queryMap[name] = value;
}
return queryMap;
} // getQuery
/**
* @brief Return the constituent parts of the path.
* If we imagine a path as composed of parts separated by slashes, then this function
* returns a vector composed of the parts. For example:
*
* ```
* /x/y/z
* ```
* will break out to:
*
* ```
* path[0] = ""
* path[1] = "x"
* path[2] = "y"
* path[3] = "z"
* ```
*
* @return A vector of the constituent parts of the path.
*/
std::vector<std::string> WebServer::HTTPRequest::pathSplit() {
std::istringstream stream(getPath());
std::vector<std::string> ret;
std::string pathPart;
while(std::getline(stream, pathPart, '/')) {
ret.push_back(pathPart);
}
// Debug
for (int i=0; i<ret.size(); i++) {
ESP_LOGD(tag, "part[%d]: %s", i, ret[i].c_str());
}
return ret;
} // pathSplit
/**
* @brief Indicate the beginning of a multipart part.
* An HTTP Multipart form is where each of the fields in the form are broken out into distinct
* sections. We commonly see this with file uploads.
* @param [in] varName The name of the form variable.
* @param [in] fileName The name of the file being uploaded (may not be present).
* @return N/A.
*/
void WebServer::HTTPMultiPart::begin(std::string varName, std::string fileName) {
ESP_LOGD(tag, "WebServer::HTTPMultiPart::begin(varName=\"%s\", fileName=\"%s\")",
varName.c_str(), fileName.c_str());
} // WebServer::HTTPMultiPart::begin
/**
* @brief Indicate the end of a multipart part.
* This will eventually be called after a corresponding begin().
* @return N/A.
*/
void WebServer::HTTPMultiPart::end() {
ESP_LOGD(tag, "WebServer::HTTPMultiPart::end()");
} // WebServer::HTTPMultiPart::end
/**
* @brief Indicate the arrival of data of a multipart part.
* This will be called after a begin() and it may be called many times. Each
* call will result in more data. The end of the data will be indicated by a call to end().
* @param [in] data The data received in this callback.
* @return N/A.
*/
void WebServer::HTTPMultiPart::data(std::string data) {
ESP_LOGD(tag, "WebServer::HTTPMultiPart::data(), length=%d", data.length());
} // WebServer::HTTPMultiPart::data
/**
* @brief Indicate the end of all the multipart parts.
* @return N/A.
*/
void WebServer::HTTPMultiPart::multipartEnd() {
ESP_LOGD(tag, "WebServer::HTTPMultiPart::multipartEnd()");
} // WebServer::HTTPMultiPart::multipartEnd
/**
* @brief Indicate the start of all the multipart parts.
* @return N/A.
*/
void WebServer::HTTPMultiPart::multipartStart() {
ESP_LOGD(tag, "WebServer::HTTPMultiPart::multipartStart()");
} // WebServer::HTTPMultiPart::multipartStart
/**
* @brief Indicate that a new WebSocket instance has been created.
* @return N/A.
*/
void WebServer::WebSocketHandler::onCreated() {
} // onCreated
/**
* @brief Indicate that a new message has been received.
* @param [in] message The message received from the client.
* @return N/A.
*/
void WebServer::WebSocketHandler::onMessage(std::string message){
} // onMessage
/**
* @brief Indicate that the client has closed the WebSocket.
* @return N/A
*/
void WebServer::WebSocketHandler::onClosed() {
} // onClosed
/**
* @brief Send data down the WebSocket
* @param [in] message The message to send down the socket.
* @return N/A.
*/
void WebServer::WebSocketHandler::sendData(std::string message) {
ESP_LOGD(tag, "WebSocketHandler::sendData(length=%d)", message.length());
mg_send_websocket_frame(m_mgConnection,
WEBSOCKET_OP_BINARY | WEBSOCKET_OP_CONTINUE,
message.data(), message.length());
} // sendData
/**
* @brief Send data down the WebSocket
* @param [in] data The message to send down the socket.
* @param [in] size The size of the message
* @return N/A.
*/
void WebServer::WebSocketHandler::sendData(uint8_t *data, uint32_t size) {
mg_send_websocket_frame(m_mgConnection,
WEBSOCKET_OP_BINARY | WEBSOCKET_OP_CONTINUE,
data, size);
} // sendData
/**
* @brief Close the WebSocket from the web server end.
* Previously a client has connected to us and created a WebSocket. By making this call we are
* declaring that the socket should be closed from the server end.
* @return N/A.
*/
void WebServer::WebSocketHandler::close() {
mg_send_websocket_frame(m_mgConnection, WEBSOCKET_OP_CLOSE, nullptr, 0);
} // close
| 31.286822
| 193
| 0.713507
|
graealex
|
9afc2831afbd5563db7d88221277b3ce9196b57d
| 1,326
|
cpp
|
C++
|
src/error_code.cpp
|
tomsksoft-llc/cis1-webui-native-srv-cpp
|
9ac8f7867977a2f9af5713f60942200d25582f7f
|
[
"MIT"
] | 2
|
2019-04-26T07:48:26.000Z
|
2019-06-03T07:04:22.000Z
|
src/error_code.cpp
|
tomsksoft-llc/cis1-webui-native-srv-cpp
|
9ac8f7867977a2f9af5713f60942200d25582f7f
|
[
"MIT"
] | 73
|
2019-04-25T07:41:34.000Z
|
2020-04-14T16:23:54.000Z
|
src/error_code.cpp
|
tomsksoft-llc/cis1-webui-native-srv-cpp
|
9ac8f7867977a2f9af5713f60942200d25582f7f
|
[
"MIT"
] | null | null | null |
/*
* TomskSoft CIS1 WebUI
*
* (c) 2019 TomskSoft LLC
* (c) Mokin Innokentiy [mia@tomsksoft.com]
*
*/
#include "error_code.h"
namespace cis
{
const char * error_category::name() const noexcept
{
return "cis::error";
}
std::string error_category::message(int ev) const
{
switch(static_cast<error_code>(ev))
{
case error_code::ok:
return "OK";
case error_code::too_many_args:
return "Too many arguments";
case error_code::cant_parse_config_ini:
return "Can't parse config.ini";
case error_code::incorrect_environment:
return "Incorrect environment";
case error_code::cant_run_http_listener:
return "Can't run HTTP listener";
case error_code::cant_resolve_address:
return "Can't resolve network address";
case error_code::cant_open_file:
return "Can't open file";
case error_code::cant_cast_config_entry:
return "Can't cast config entry";
case error_code::database_error:
return "Database error";
default:
return "(unrecognized error)";
}
}
const error_category category;
std::error_code make_error_code(error_code e)
{
return {static_cast<int>(e), category};
}
} // namespace cis
| 21.047619
| 51
| 0.625189
|
tomsksoft-llc
|
b1044d9ffddb5ffa4140bcb649ba809328945b61
| 1,070
|
cpp
|
C++
|
Stp/Base/Error/Exception.cpp
|
markazmierczak/Polonite
|
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
|
[
"MIT"
] | 1
|
2019-07-11T12:47:52.000Z
|
2019-07-11T12:47:52.000Z
|
Stp/Base/Error/Exception.cpp
|
Polonite/Polonite
|
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
|
[
"MIT"
] | null | null | null |
Stp/Base/Error/Exception.cpp
|
Polonite/Polonite
|
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
|
[
"MIT"
] | 1
|
2019-07-11T12:47:53.000Z
|
2019-07-11T12:47:53.000Z
|
// Copyright 2017 Polonite Authors. All rights reserved.
// Distributed under MIT license that can be found in the LICENSE file.
#include "Base/Error/Exception.h"
#include "Base/Io/TextWriter.h"
#include <exception>
#if !COMPILER(MSVC)
#include <cxxabi.h>
namespace __cxxabiv1 {
struct __cxa_eh_globals {
void* caughtExceptions;
unsigned int uncaughtExceptions;
};
}
#endif // COMPILER(*)
namespace stp {
Exception::~Exception() {
}
StringSpan Exception::getName() const noexcept {
return "Exception";
}
void Exception::formatImpl(TextWriter& out) const {
out << getName() << ": ";
onFormat(out);
}
void Exception::onFormat(TextWriter& out) const {
}
int countUncaughtExceptions() noexcept {
#if COMPILER(MSVC)
return std::uncaught_exceptions();
#elif defined(_LIBCPPABI_VERSION)
return __cxxabiv1::__cxa_uncaught_exceptions();
#else
auto* globals = __cxxabiv1::__cxa_get_globals_fast();
return globals->uncaughtExceptions;
#endif
}
bool hasUncaughtExceptions() noexcept {
return std::uncaught_exception();
}
} // namespace stp
| 19.454545
| 71
| 0.73271
|
markazmierczak
|
b10bd5d386f889e97ab8fc690423153b35491f77
| 19,181
|
cpp
|
C++
|
Samples/AppWindow/cppwinrt/Code/BU/MusionBU/CodeLine.cpp
|
OSIREM/ecoin-minimal
|
7d8314484c0cd47c673046c86c273cc48eaa43d2
|
[
"MIT"
] | null | null | null |
Samples/AppWindow/cppwinrt/Code/BU/MusionBU/CodeLine.cpp
|
OSIREM/ecoin-minimal
|
7d8314484c0cd47c673046c86c273cc48eaa43d2
|
[
"MIT"
] | null | null | null |
Samples/AppWindow/cppwinrt/Code/BU/MusionBU/CodeLine.cpp
|
OSIREM/ecoin-minimal
|
7d8314484c0cd47c673046c86c273cc48eaa43d2
|
[
"MIT"
] | null | null | null |
/*
CodeLine - osirem.com
Copyright OSIREM LTD (C) 2016
www.bitolyl.com/osirem bitcoin-office.com ecn.world
This source is proprietary, and cannot be used, in part or in full without
the express permission of the original author. The original author retain the
rights to use, modify, and/or relicense this code without notice.
*/
#include "pch.h"
#include "Code/Work/Contract.h"
using namespace ecoin;
namespace ecoin
{
template<class T>
T ag_any_cast(boost::any f_Any)
{
#ifdef ECOIN_SECURE
try
{
return boost::any_cast<T>(f_Any);
}
catch (boost::bad_any_cast &e)
{
#if 1
std::cerr << e.what() << '\n';
#endif
for(;;)
{
//pause
}
}
#else
return boost::any_cast<T>(f_Any);
#endif
}
CodeLine::CodeLine(std::string f_Line, uint f_CHK, System* f_System)
{ ////////////////
////////////////
// Construct
//
//
acClear();
m_CodeString = f_Line;
m_Chk = f_CHK;
m_System = f_System;
bool f_Scan = true;
int f_Size = f_Line.size();
if(m_Chk < f_Size - 6)
{
std::shared_ptr<Code> f_CodeB = std::make_shared<Code>(f_Line, m_Chk, 0);
if (f_CodeB->m_Code_DigitA == '#' ||
f_CodeB->m_Code_DigitB == '#' ||
f_CodeB->m_Code_DigitC == '#')
{
f_Scan = false;
}
else
{
m_vec_Code.push_back(f_CodeB);
}
//////////
//////////
// END
if(f_Scan)
{
m_END = f_CodeB->acDecide_END();
m_Chk = f_CodeB->acDecide_MAX();
uint f_Cntr = 1;
while(f_Scan)
{
if(m_Chk < f_Line.size() - 6)
{
std::shared_ptr<Code> f_CodeA = std::make_shared<Code>(f_Line, m_Chk, f_Cntr);
m_Chk = f_CodeA->m_Chk;
if(f_CodeA->m_Code_DigitA == '/' &&
f_CodeA->m_Code_DigitB == '/')
{
f_Scan = false;
}
if (f_CodeA->m_Code_DigitA == '#' ||
f_CodeA->m_Code_DigitB == '#' ||
f_CodeA->m_Code_DigitC == '#')
{
f_Scan = false;
}
else
{
m_vec_Code.push_back(f_CodeA);
}
}
else
{
f_Scan = false;
}
f_Cntr++;
}
}
}
//////////////////////
//////////////
// Setup
//
//
uint f_CodeSize = m_vec_Code.size();
uint f_Count = 0;
while(f_Count < f_CodeSize)
{
std::shared_ptr<Code> f_Code = m_vec_Code[f_Count];
if(f_Code->m_Code_DigitB != '/' &&
f_Code->m_Code_DigitB != '#')
{
switch(f_Code->m_Code)
{
case MuCode_Var:
{
int f_Type = 0;
if(m_vec_Code.size() > 1)
{
if(f_Count == 0)
{
if(m_vec_Code[1]->m_Code == MuCode_Condition)
{
f_Type = 2;
}
}
}
if(f_Type <= 1)
{
if((m_CodeLine != MuLine_Assign_Opr) &&
(m_CodeLine != MuLine_Function) &&
(m_CodeLine != MuLine_Function_Frame) &&
(m_CodeLine != MuLine_Function_Custom) &&
(m_CodeLine != MuLine_Condition_Ajax) &&
(m_CodeLine != MuCode_For_Loop))
{
m_CodeLine = MuLine_Assign;
}
std::shared_ptr<Variable> f_Var = std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code);
m_vec_Variable.push_back(f_Var);
if((f_Code->m_Number.size() == 1) && ((f_CodeSize == 1) || (f_Count > 1)))
{
if((m_CodeLine != MuLine_Assign_Opr) &&
(m_CodeLine != MuLine_Function) &&
(m_CodeLine != MuLine_Condition_Ajax))
{
m_CodeLine = MuLine_Init_Var;
}
std::shared_ptr<Variable> f_VarFRT = std::make_shared<Variable>("Con", MuCode_Constant);
*(f_VarFRT) = *(f_Code->m_Number[0]->m_MxVar);
m_vec_Variable.push_back(f_VarFRT);
}
}
else
{
m_CodeLine = MuLine_Condition_Ajax;
std::shared_ptr<Variable> f_Var = std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code);
m_vec_Variable.push_back(f_Var);
}
}break;
case MuCode_Function:
case MuCode_FunctionStart:
{
m_CodeLine = MuLine_Function;
if(f_Code->m_Type[0]->m_VarType == MuFunc_Custom)
{ //////////////////////
// Custom Function
m_CodeLine = MuLine_Function_Custom;
}
else if (f_Code->m_Type[0]->m_VarType == MuFunc_Frame)
{
m_CodeLine = MuLine_Function_Frame;
}
else //////////////////////////////////////////////
{ // Math and System and Other (already storage) Function Calls
m_CodeLine = MuLine_Function;
}
#if 0
m_vec_Variable.push_back(f_Code->m_MxVar);
m_vec_Variable.push_back(m_vec_Code[f_Code->m_Index + 1]->m_MxVar);
m_vec_Variable.push_back(m_vec_Code[f_Code->m_Index + 2]->m_MxVar);
#endif
}break;
case MuCode_System:
{
if(f_Count > 0)
{
if((m_CodeLine != MuLine_Assign_Opr) &&
(m_CodeLine != MuLine_Function) &&
(m_CodeLine != MuLine_Function_Frame) &&
(m_CodeLine != MuLine_Function_Custom) &&
(m_CodeLine != MuLine_Condition_Ajax) &&
(m_CodeLine != MuCode_For_Loop))
{
m_CodeLine = MuLine_Assign;
}
std::shared_ptr<Variable> f_Var = m_System->av_Var(f_Code->m_Name[0]->m_MxName);
m_vec_Variable.push_back(f_Var);
if(f_Code->m_Number.size() == 1 && f_CodeSize == 1)
{
if((m_CodeLine != MuLine_Assign_Opr) &&
(m_CodeLine != MuLine_Function) &&
(m_CodeLine != MuLine_Function_Frame) &&
(m_CodeLine != MuLine_Function_Custom) &&
(m_CodeLine != MuLine_Condition_Ajax) &&
(m_CodeLine != MuCode_For_Loop))
{
m_CodeLine = MuLine_Init_Var;
}
std::shared_ptr<Variable> f_VarFRT = std::make_shared<Variable>("Con", MuCode_Constant);
*(f_VarFRT) = *(f_Code->m_Number[0]->m_MxVar);
m_vec_Variable.push_back(f_VarFRT);
}
}
else
{
if((m_CodeLine != MuLine_Assign_Opr) &&
(m_CodeLine != MuLine_Function) &&
(m_CodeLine != MuLine_Function_Frame) &&
(m_CodeLine != MuLine_Function_Custom) &&
(m_CodeLine != MuLine_Condition_Ajax) &&
(m_CodeLine != MuCode_For_Loop))
{
m_CodeLine = MuLine_Init_Var;
}
std::shared_ptr<Variable> f_Var = m_System->av_Var(f_Code->m_Name[0]->m_MxName);
m_vec_Variable.push_back(f_Var);
}
}break;
case MuCode_Constant:
{
if((m_CodeLine != MuLine_Assign_Opr) &&
(m_CodeLine != MuLine_Function) &&
(m_CodeLine != MuLine_Function_Frame) &&
(m_CodeLine != MuLine_Function_Custom) &&
(m_CodeLine != MuLine_Condition_Ajax) &&
(m_CodeLine != MuCode_For_Loop))
{
m_CodeLine = MuLine_Init_Var;
}
std::shared_ptr<Variable> f_Var = std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, MuCode_Constant);
m_vec_Variable.push_back(f_Var);
if(f_Code->m_Number.size() == 1 && f_CodeSize == 1)
{
if((m_CodeLine != MuLine_Assign_Opr) &&
(m_CodeLine != MuLine_Function) &&
(m_CodeLine != MuLine_Function_Frame) &&
(m_CodeLine != MuLine_Function_Custom) &&
(m_CodeLine != MuLine_Condition_Ajax) &&
(m_CodeLine != MuCode_For_Loop))
{
m_CodeLine = MuLine_Init_Var;
}
std::shared_ptr<Variable> f_VarFRT = std::make_shared<Variable>("Con", MuCode_Constant);
*(f_VarFRT) = *(f_Code->m_Number[0]->m_MxVar);
m_vec_Variable.push_back(f_VarFRT);
}
else if(f_Code->m_Number.size() > 1)
{
#ifdef ECOIN_SECURE
throw;
#endif
}
}break;
case MuCode_For_Loop:
{
m_CodeLine = MuLine_For_Loop;
if(f_Code->m_Param.size() > 0)
{
std::shared_ptr<Variable> f_VarFRT = std::make_shared<Variable>(f_Code->m_Param[0]->m_MxName, MuCode_Var);
*(f_VarFRT) = *(f_Code->m_Param[0]->m_MxVar);
m_vec_Variable.push_back(f_VarFRT);
}
if(f_Code->m_Param.size() > 1)
{
std::shared_ptr<Variable> f_VarFRT = std::make_shared<Variable>(f_Code->m_Param[1]->m_MxName, MuCode_Var);
*(f_VarFRT) = *(f_Code->m_Param[0]->m_MxVar);
m_vec_Variable.push_back(f_VarFRT);
}
}break;
case MuCode_Operator:
{
m_CodeLine = MuLine_Assign_Opr;
std::shared_ptr<Code> f_LtCode = m_vec_Code[f_Code->m_Index - 1];
std::shared_ptr<Code> f_OpCode = m_vec_Code[f_Code->m_Index];
std::shared_ptr<Code> f_RtCode = m_vec_Code[f_Code->m_Index + 1];
std::shared_ptr<Operator> f_Operator = std::make_shared<Operator>(f_OpCode->m_MxName);
f_Operator->m_Operator = f_OpCode->m_Type[0]->m_VarType;
std::string f_StrCode = f_LtCode->m_MxName;
std::string f_StrCodeName = f_LtCode->m_Name[0]->m_MxName;
if(f_StrCode.compare("Sys") == 0)
{
if(f_StrCodeName.compare("Pos") == 0)
{
f_Operator->resultHand = m_System->Pos;
m_vec_Variable.push_back(m_System->Pos);
f_Operator->leftHand = m_System->Pos;
m_vec_Variable.push_back(m_System->Pos);
#if 0
f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code);
#endif
f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar;
m_vec_Variable.push_back(f_Operator->rightHand);
}
if(f_StrCodeName.compare("Posx") == 0)
{
f_Operator->resultHand = m_System->Posx;
m_vec_Variable.push_back(m_System->Posx);
f_Operator->leftHand = m_System->Posx;
m_vec_Variable.push_back(m_System->Posx);
#if 0
f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code);
#endif
f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar;
m_vec_Variable.push_back(f_Operator->rightHand);
}
if(f_StrCodeName.compare("Posy") == 0)
{
f_Operator->resultHand = m_System->Posy;
m_vec_Variable.push_back(m_System->Posy);
f_Operator->leftHand = m_System->Posy;
m_vec_Variable.push_back(m_System->Posy);
#if 0
f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code);
#endif
f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar;
m_vec_Variable.push_back(f_Operator->rightHand);
}
if(f_StrCodeName.compare("Posz") == 0)
{
f_Operator->resultHand = m_System->Posz;
m_vec_Variable.push_back(m_System->Posz);
f_Operator->leftHand = m_System->Posz;
m_vec_Variable.push_back(m_System->Posz);
#if 0
f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code);
#endif
f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar;
m_vec_Variable.push_back(f_Operator->rightHand);
}
else if(f_StrCodeName.compare("Color") == 0)
{
f_Operator->resultHand = m_System->Color;
m_vec_Variable.push_back(m_System->Color);
f_Operator->leftHand = m_System->Color;
m_vec_Variable.push_back(m_System->Color);
#if 0
f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code);
#endif
f_Operator->rightHand = f_RtCode->m_MxVar;
m_vec_Variable.push_back(f_Operator->rightHand);
}
}
else if(f_StrCode.compare("Var") == 0)
{
f_Operator->resultHand = std::make_shared<Variable>(f_LtCode->m_Name[0]->m_MxName, f_LtCode->m_Code);
m_vec_Variable.push_back(f_Operator->resultHand);
f_Operator->leftHand = std::make_shared<Variable>(f_LtCode->m_Name[0]->m_MxName, f_LtCode->m_Code);
m_vec_Variable.push_back(f_Operator->leftHand);
if(f_RtCode->m_Number.size() >= 1)
{
f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar;
m_vec_Variable.push_back(f_Operator->rightHand);
}
else
{
f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code);
m_vec_Variable.push_back(f_Operator->rightHand);
}
}
else
{
#ifdef ECOIN_SECURE
throw;
#endif
}
m_vec_Operator.push_back(f_Operator);
}break;
case MuCode_Condition:
{
m_CodeLine = MuLine_Condition_Ajax;
}break;
case MuCode_Override:
{ /////////////
/// Pause ///
/////////////
}break;
}
}
f_Count++;
}
}
CodeLine::~CodeLine()
{
m_vec_Code.clear();
m_vec_Variable.clear();
m_vec_Operator.clear();
}
int CodeLine::acSearch_CodeType(uint f_TYPE)
{
for(uint f_CT = 0; f_CT < m_vec_Code.size(); f_CT++)
{
std::shared_ptr<Code> f_Code = m_vec_Code[f_CT];
if(f_Code->m_Code == f_TYPE)
{
return f_CT;
}
}
return -5;
}
void CodeLine::ac_Variable_Align(void)
{
uint f_VarSize = m_vec_Variable.size();
switch(m_CodeLine)
{
#if 0
case MuLine_Assign:
case MuLine_Assign_Opr:
case MuLine_Init_Var:
{
if(f_VarSize == 1)
{
m_vec_Code[0]->m_MxVar = m_vec_Variable[0];
}
else if(f_VarSize == 2)
{
m_vec_Code[0]->m_MxVar = m_vec_Variable[0];
m_vec_Code[1]->m_MxVar = m_vec_Variable[1];
}
else
{
throw;
}
}break;
#endif
case MuLine_Condition_Ajax:
{
if(f_VarSize == 5)
{
if(m_vec_Variable[2]->m_MxName.compare("Con") == 0)
{
m_vec_Code[0]->m_MxVar = m_vec_Variable[0];
m_vec_Code[2]->m_MxVar = m_vec_Variable[2];
m_vec_Code[1]->m_Condition[0]->leftHand = m_vec_Variable[3];
m_vec_Code[1]->m_Condition[0]->rightHand = m_vec_Variable[4];
}
else
{
throw;
}
}
else if(f_VarSize == 2)
{
m_vec_Code[0]->m_MxVar = m_vec_Variable[0];
m_vec_Code[2]->m_MxVar = m_vec_Variable[1];
m_vec_Code[1]->m_Condition[0]->leftHand = m_vec_Variable[0];
m_vec_Code[1]->m_Condition[0]->rightHand = m_vec_Variable[1];
}
else if(f_VarSize == 4)
{
m_vec_Code[0]->m_MxVar = m_vec_Variable[0];
m_vec_Code[2]->m_MxVar = m_vec_Variable[1];
m_vec_Code[1]->m_Condition[0]->leftHand = m_vec_Variable[2];
m_vec_Code[1]->m_Condition[0]->rightHand = m_vec_Variable[3];
}
else
{
throw;
}
}break;
case MuLine_Function:
case MuLine_Function_Custom:
{
if(f_VarSize >= 1)
{
g_Function[m_vec_Code[1]->m_ContractID]->m_Return = m_vec_Variable[0];
for(int f_XY = 0; f_XY < g_Function[m_vec_Code[1]->m_ContractID]->m_vec_Variable.size(); f_XY++)
{
g_Function[m_vec_Code[1]->m_ContractID]->m_vec_Variable[f_XY] = m_vec_Variable[f_XY + 1];
}
}
}break;
}
}
bool CodeLine::ac_Execute(void)
{
//////////////////////
//////////////
// Setup
//
//
uint f_VarSize = m_vec_Code.size();
if(f_VarSize == 0 ||
f_VarSize == 1)
{
#ifdef ECOIN_SECURE
#if 0
throw;
#else
return false;
#endif
#endif
}
#if 0
printf("ESL_EXEC-f_VarSize %i m_CodeLine %i\n", f_VarSize, m_CodeLine);
#endif
//////////////////
// Operator
//
if(m_CodeLine == MuLine_Assign_Opr)
{
if(m_vec_Operator.size() > 0)
{
uint f_OpSize = m_vec_Operator.size();
uint f_Count = 0;
while(f_Count < f_OpSize)
{
std::shared_ptr<Operator> f_Operator = m_vec_Operator[f_Count];
f_Operator->ac_Execute();
f_Count++;
}
} /////////////
else
{
#ifdef ECOIN_SECURE
throw;
#endif
}
} // Assign
else if(m_CodeLine == MuLine_Assign)
{
if(f_VarSize == 0 ||
f_VarSize == 1)
{
#ifdef ECOIN_SECURE
throw;
#endif
}
else
{
if(f_VarSize == 2)
{
std::shared_ptr<Variable> f_VarA = m_vec_Variable[0];
std::shared_ptr<Variable> f_VarB = m_vec_Variable[1];
*(f_VarA) = *(f_VarB);
}
else
{
if(f_VarSize == 3)
{
std::shared_ptr<Variable> f_VarA = m_vec_Variable[0];
std::shared_ptr<Variable> f_VarB = m_vec_Variable[1];
std::shared_ptr<Variable> f_VarC = m_vec_Variable[2];
*(f_VarA) = *(f_VarB);
*(f_VarC) = *(f_VarB);
}
else
{
#ifdef ECOIN_SECURE
throw;
#endif
}
}
}
}
else if(m_CodeLine == MuLine_Condition_Ajax)
{
std::shared_ptr<Condition> f_Condition = m_vec_Code[1]->m_Condition[0];
f_Condition->ac_Execute();
}
else if(m_CodeLine == MuLine_Init_Var)
{
if(f_VarSize == 0 ||
f_VarSize == 1)
{
#ifdef ECOIN_SECURE
throw;
#endif
}
else
{
if(f_VarSize == 2)
{
std::shared_ptr<Variable> f_VarRes = m_vec_Variable[0];
std::shared_ptr<Variable> f_VarB = m_vec_Variable[1];
*(f_VarRes) = *(f_VarB);
}
else
{
if(f_VarSize == 3)
{
std::shared_ptr<Variable> f_VarRes = m_vec_Variable[0];
std::shared_ptr<Variable> f_VarB = m_vec_Variable[1];
std::shared_ptr<Variable> f_VarC = m_vec_Variable[2];
*(f_VarRes) = *(f_VarB);
*(f_VarB) = *(f_VarC);
}
else
{
#ifdef ECOIN_SECURE
throw;
#endif
}
}
}
}
else if(m_CodeLine == MuLine_Function)
{
std::shared_ptr<Function> f_Function = g_systemFunction[m_vec_Code[0]->m_ContractID];
f_Function->acExecute();
}
else if(m_CodeLine == MuLine_Function_Custom)
{
std::shared_ptr<Function> f_Function = g_Function[m_vec_Code[0]->m_ContractID];
f_Function->acExecute();
}
else if(m_CodeLine == MuLine_For_Loop)
{
int f_ParamCount = m_vec_Code[0]->m_Param.size();
if(f_ParamCount == 1)
{
std::shared_ptr<Variable> f_VarCount = m_vec_Variable[0];
int f_Count = 0;
if(f_VarCount->m_Var.type() == typeid(int))
{
f_Count = ag_any_cast<int>(f_VarCount->m_Var);
}
else
{
#ifdef ECOIN_SECURE
throw;
#endif
}
if(f_Count < 0)
{
#ifdef ECOIN_SECURE
throw;
#endif
}
std::shared_ptr<Function> f_Function = g_Function[m_vec_Code[0]->m_ContractID];
for(int f_XY = 0; f_XY < f_Count; f_XY++)
{
f_Function->acExecute();
}
}
else if(f_ParamCount == 2)
{
std::shared_ptr<Variable> f_VarCountVar = m_vec_Variable[0];
std::shared_ptr<Variable> f_VarCount = m_vec_Variable[1];
int f_Count = 0;
if(f_VarCount->m_Var.type() == typeid(int))
{
f_Count = ag_any_cast<int>(f_VarCount->m_Var);
}
else
{
#ifdef ECOIN_SECURE
throw;
#endif
}
if(f_Count < 0)
{
#ifdef ECOIN_SECURE
throw;
#endif
}
std::shared_ptr<Function> f_Function = g_Function[m_vec_Code[0]->m_ContractID];
for(int f_XY = 0; f_XY < f_Count; f_XY++)
{
*(f_VarCountVar) = f_XY;
f_Function->acExecute();
}
}
else
{
#ifdef ECOIN_SECURE
throw;
#endif
}
}
return true;
}
std::string CodeLine::ac_Print(void)
{
return m_CodeString;
}
};
| 24.528133
| 113
| 0.584485
|
OSIREM
|
623eceee55e152c9d156f3651743cef7f48c5b69
| 3,418
|
hpp
|
C++
|
spike/models/stratum/RockType.hpp
|
davidson16807/libtectonics
|
aa0ae2b8a4a1d2a9a346bbdeb334be876ad75646
|
[
"CC-BY-4.0"
] | 7
|
2020-06-09T19:56:55.000Z
|
2021-02-17T01:53:30.000Z
|
spike/models/stratum/RockType.hpp
|
davidson16807/tectonics.cpp
|
c40278dba14260c598764467c7abf23b190e676b
|
[
"CC-BY-4.0"
] | null | null | null |
spike/models/stratum/RockType.hpp
|
davidson16807/tectonics.cpp
|
c40278dba14260c598764467c7abf23b190e676b
|
[
"CC-BY-4.0"
] | null | null | null |
#pragma once
namespace stratum
{
/*
"RockType" attempts to be a comprehensive collection of every earth-like rock that the model is capable of representing.
RockType is used to quickly describe to the user what type of rock he's looking at.
RockType is only used for descriptive purposes, it is never to be used in model behavior.
This requirement is needed so that the logic in get_rock_type can grow to whatever absurd proportion is desired,
while still allowing the rest of the code base to be easily reasoned with.
RockType only describes the fraction of rock that is composed of minerals found on earth.
For instance, if a rock on an icy moon is a conglomerate of silicates and water ice,
then the RockType will only describe the silicate fraction of the rock,
and the user interface will describe the rock as being a mixture of that rock type plus water ice.
*/
enum RockType
{
// IGNEOUS
igneous,
komatiite,
peridotite,
basalt,
gabbro,
andesite,
diorite,
// dacite,
// ganodiorite,
rhyolite,
granite,
// SEDIMENT
sediment,
sand,
silt,
clay,
loam,
sand_loam,
silt_loam,
clay_loam,
sand_clay,
silt_clay,
// SEDIMENTARY
// NOTE: from http://www.kgs.ku.edu/General/Class/sedimentary.html
// defined by particle size
sedimentary,
breccia,
sandstone,
wacke,
siltstone,
shale,
// defined by composition
limestone, // any carbonate
chalk, // calcite
marl, // partly calcite
coal, // organics
arkose, // feldspar
ironstone, // iron
// defined by composition and particle size
chert, // quartz, silt or smaller
asphalt, // organics, silt or smaller
tuff, // feldspar, sand or smaller
coquina, // calcite, granule or larger
caliche, // partly calcite, granule or larger
peat, // organics, sand or granule
jet, // organics, pebble or larger
// METAMORPHIC
metamorphic,
// generic
zeolite,
hornfels,
// one schist, two schist...
greenschist,
blueschist,
sanidinite,
amphibolite,
granulite,
eclogite,
// sedimentary based
slate, // silt or smaller, low grade
phyllite, // silt or smaller, low/medium grade
schist, // silt or smaller, medium grade
gneiss, // any igneous or sedimentary, high grade
metaconglomerate, // granule or larger
// ultramafic
serpentinite, // ultramafic, low grade
soapstone, // ultramafic, medium grade
jadeite, // ultramafic, high grade
// special compositions
quartzite, // silica, medium grade or higher
marble, // calcite, low grade or higher
anthracite,// organics, low grade or higher
nephrite, // quartz/calcite/marl
// miscellaneous
// partially metamorphic, partially soidified
// technically possible to represent but possibly difficult to express within get_rock_type()
migmatite,
count
};
}
| 28.483333
| 124
| 0.589819
|
davidson16807
|
62422949e13c032724be2671822871fa8ac278b0
| 6,214
|
cpp
|
C++
|
src/physics/physics_system.cpp
|
galek/LumixEngine
|
d7d1738f7fc2bc7f6cf08d1217330a591b370ed9
|
[
"MIT"
] | 8
|
2015-09-06T20:05:27.000Z
|
2021-07-14T11:12:33.000Z
|
src/physics/physics_system.cpp
|
gamedevforks/LumixEngine
|
d7d1738f7fc2bc7f6cf08d1217330a591b370ed9
|
[
"MIT"
] | null | null | null |
src/physics/physics_system.cpp
|
gamedevforks/LumixEngine
|
d7d1738f7fc2bc7f6cf08d1217330a591b370ed9
|
[
"MIT"
] | null | null | null |
#include "physics/physics_system.h"
#include <PxPhysicsAPI.h>
#include "cooking/PxCooking.h"
#include "core/base_proxy_allocator.h"
#include "core/crc32.h"
#include "core/log.h"
#include "core/resource_manager.h"
#include "editor/world_editor.h"
#include "engine.h"
#include "engine/property_descriptor.h"
#include "physics/physics_geometry_manager.h"
#include "physics/physics_scene.h"
namespace Lumix
{
static const uint32_t BOX_ACTOR_HASH = crc32("box_rigid_actor");
static const uint32_t MESH_ACTOR_HASH = crc32("mesh_rigid_actor");
static const uint32_t CONTROLLER_HASH = crc32("physical_controller");
static const uint32_t HEIGHTFIELD_HASH = crc32("physical_heightfield");
struct PhysicsSystemImpl : public PhysicsSystem
{
PhysicsSystemImpl(Engine& engine)
: m_allocator(engine.getAllocator())
, m_engine(engine)
, m_manager(*this, engine.getAllocator())
{
m_manager.create(ResourceManager::PHYSICS, engine.getResourceManager());
registerProperties();
}
virtual bool create() override;
virtual IScene* createScene(UniverseContext& universe) override;
virtual void destroyScene(IScene* scene) override;
virtual void destroy() override;
virtual physx::PxControllerManager* getControllerManager() override
{
return m_controller_manager;
}
virtual physx::PxPhysics* getPhysics() override
{
return m_physics;
}
virtual physx::PxCooking* getCooking() override
{
return m_cooking;
}
bool connect2VisualDebugger();
void registerProperties();
physx::PxPhysics* m_physics;
physx::PxFoundation* m_foundation;
physx::PxControllerManager* m_controller_manager;
physx::PxAllocatorCallback* m_physx_allocator;
physx::PxErrorCallback* m_error_callback;
physx::PxCooking* m_cooking;
PhysicsGeometryManager m_manager;
class Engine& m_engine;
class BaseProxyAllocator m_allocator;
};
extern "C" LUMIX_PHYSICS_API IPlugin* createPlugin(Engine& engine)
{
return engine.getAllocator().newObject<PhysicsSystemImpl>(engine);
}
struct CustomErrorCallback : public physx::PxErrorCallback
{
virtual void reportError(physx::PxErrorCode::Enum code, const char* message, const char* file, int line);
};
IScene* PhysicsSystemImpl::createScene(UniverseContext& ctx)
{
return PhysicsScene::create(*this, *ctx.m_universe, m_engine, m_allocator);
}
void PhysicsSystemImpl::destroyScene(IScene* scene)
{
PhysicsScene::destroy(static_cast<PhysicsScene*>(scene));
}
class AssertNullAllocator : public physx::PxAllocatorCallback
{
public:
virtual void* allocate(size_t size, const char* typeName, const char* filename, int line) override
{
void* ret = _aligned_malloc(size, 16);
//g_log_info.log("PhysX") << "Allocated " << size << " bytes for " << typeName << " from " << filename << "(" << line << ")";
ASSERT(ret);
return ret;
}
virtual void deallocate(void* ptr) override
{
_aligned_free(ptr);
}
};
void PhysicsSystemImpl::registerProperties()
{
m_engine.registerComponentType("box_rigid_actor", "Physics Box");
m_engine.registerComponentType("physical_controller",
"Physics Controller");
m_engine.registerComponentType("mesh_rigid_actor", "Physics Mesh");
m_engine.registerComponentType("physical_heightfield",
"Physics Heightfield");
IAllocator& allocator = m_engine.getAllocator();
m_engine.registerProperty(
"box_rigid_actor",
allocator.newObject<BoolPropertyDescriptor<PhysicsScene>>(
"dynamic",
&PhysicsScene::isDynamic,
&PhysicsScene::setIsDynamic,
allocator));
m_engine.registerProperty(
"box_rigid_actor",
allocator.newObject<Vec3PropertyDescriptor<PhysicsScene>>(
"size",
&PhysicsScene::getHalfExtents,
&PhysicsScene::setHalfExtents,
allocator));
m_engine.registerProperty(
"mesh_rigid_actor",
allocator.newObject<ResourcePropertyDescriptor<PhysicsScene>>(
"source",
&PhysicsScene::getShapeSource,
&PhysicsScene::setShapeSource,
"Physics (*.pda)",
allocator));
m_engine.registerProperty(
"physical_heightfield",
allocator.newObject<ResourcePropertyDescriptor<PhysicsScene>>(
"heightmap",
&PhysicsScene::getHeightmap,
&PhysicsScene::setHeightmap,
"Image (*.raw)",
allocator));
m_engine.registerProperty(
"physical_heightfield",
allocator.newObject<DecimalPropertyDescriptor<PhysicsScene>>(
"xz_scale",
&PhysicsScene::getHeightmapXZScale,
&PhysicsScene::setHeightmapXZScale,
0.0f,
FLT_MAX,
0.0f,
allocator));
m_engine.registerProperty(
"physical_heightfield",
allocator.newObject<DecimalPropertyDescriptor<PhysicsScene>>(
"y_scale",
&PhysicsScene::getHeightmapYScale,
&PhysicsScene::setHeightmapYScale,
0.0f,
FLT_MAX,
0.0f,
allocator));
}
bool PhysicsSystemImpl::create()
{
m_physx_allocator = m_allocator.newObject<AssertNullAllocator>();
m_error_callback = m_allocator.newObject<CustomErrorCallback>();
m_foundation = PxCreateFoundation(
PX_PHYSICS_VERSION,
*m_physx_allocator,
*m_error_callback
);
m_physics = PxCreatePhysics(
PX_PHYSICS_VERSION,
*m_foundation,
physx::PxTolerancesScale()
);
m_controller_manager = PxCreateControllerManager(*m_foundation);
m_cooking = PxCreateCooking(PX_PHYSICS_VERSION, *m_foundation, physx::PxCookingParams());
connect2VisualDebugger();
return true;
}
void PhysicsSystemImpl::destroy()
{
m_controller_manager->release();
m_cooking->release();
m_physics->release();
m_foundation->release();
m_allocator.deleteObject(m_physx_allocator);
m_allocator.deleteObject(m_error_callback);
}
bool PhysicsSystemImpl::connect2VisualDebugger()
{
if(m_physics->getPvdConnectionManager() == nullptr)
return false;
const char* pvd_host_ip = "127.0.0.1";
int port = 5425;
unsigned int timeout = 100;
physx::PxVisualDebuggerConnectionFlags connectionFlags = physx::PxVisualDebuggerExt::getAllConnectionFlags();
PVD::PvdConnection* theConnection = physx::PxVisualDebuggerExt::createConnection(m_physics->getPvdConnectionManager(), pvd_host_ip, port, timeout, connectionFlags);
return theConnection != nullptr;
}
void CustomErrorCallback::reportError(physx::PxErrorCode::Enum code, const char* message, const char* file, int line)
{
g_log_error.log("PhysX") << message;
}
} // !namespace Lumix
| 26.219409
| 165
| 0.760863
|
galek
|
624352c3d78824f4a26883cd032fab20f01b400a
| 2,155
|
hpp
|
C++
|
include/rusty-cpp/impl/maybe_uninit.hpp
|
QuarticCat/rusty-cpp
|
089089f076f461c3d84fc70478104ae8d1384aa3
|
[
"MIT"
] | 4
|
2021-08-28T10:04:00.000Z
|
2021-11-08T03:29:37.000Z
|
include/rusty-cpp/impl/maybe_uninit.hpp
|
QuarticCat/rusty-cpp
|
089089f076f461c3d84fc70478104ae8d1384aa3
|
[
"MIT"
] | 1
|
2021-08-25T07:30:19.000Z
|
2021-08-25T09:26:23.000Z
|
include/rusty-cpp/impl/maybe_uninit.hpp
|
QuarticCat/rusty-cpp
|
089089f076f461c3d84fc70478104ae8d1384aa3
|
[
"MIT"
] | null | null | null |
#pragma once
#include <utility>
namespace rc {
/// The counterpart of `MaybeUninit` in Rust.
///
/// It's impossible to make it exactly the same as in Rust. There are some key features that Rust's
/// `MaybeUninit` relies on:
///
/// 1. All objects in Rust are trivially relocatable (if you have the ownership). That means
/// `assume_init` can safely copy bytes to another location.
///
/// 2. Rust has ownership mechanism. `assume_init` takes ownership so that we cannot perform
/// another `assume_init` on the same object. And thus the compiler is totally safe to put
/// initialized object in the same place to save memory space.
///
/// There is no way to detect whether a type is trivially relocatable in C++, since C++ has no
/// borrow checker. A simple example is that any object contains a pointer may be self-referential.
/// As a compromise, we try to find a way that semantically guarantees no move. One way is letting
/// `assume_init` return a smart-pointer-like object. Obviously, this is also easy to exploit or
/// mistakenly use it. A better approach is to assume that the object is initialized before
/// destruction. For this approach, please use `rc::DeferredInit` instead.
///
/// # Safety
///
/// `assume_init` can only be called once, and must be called before initialized.
///
/// # Example
///
/// ```
/// rc::MaybeUninit<T> x{};
/// new (&x) T(args...);
/// auto inited_x = x.assume_init();
/// ```
template<class T>
class MaybeUninit {
private:
union {
T obj;
};
public:
class Inited {
private:
T& ref;
public:
Inited(T& ref): ref(ref) {}
operator T&() {
return ref;
}
~Inited() {
ref.~T();
}
};
MaybeUninit() {}
MaybeUninit(T obj): obj(std::move(obj)) {}
// TODO: How to deal with move/copy?
MaybeUninit(const MaybeUninit&) = delete;
MaybeUninit(MaybeUninit&&) = delete;
MaybeUninit& operator=(const MaybeUninit&) = delete;
MaybeUninit& operator=(MaybeUninit&&) = delete;
~MaybeUninit() {}
Inited assume_init() {
return {obj};
}
};
} // namespace rc
| 27.278481
| 99
| 0.643619
|
QuarticCat
|
625ec381e9f2eea54cd4dd735892d3b63c54e482
| 538
|
cpp
|
C++
|
utils/minval.3.cpp
|
ivan100sic/competelib-snippets
|
e40170a63b37d92c91e2dfef08b2794e67ccb0b2
|
[
"Unlicense"
] | 3
|
2022-01-17T01:56:05.000Z
|
2022-02-23T07:30:02.000Z
|
utils/minval.3.cpp
|
ivan100sic/competelib-snippets
|
e40170a63b37d92c91e2dfef08b2794e67ccb0b2
|
[
"Unlicense"
] | null | null | null |
utils/minval.3.cpp
|
ivan100sic/competelib-snippets
|
e40170a63b37d92c91e2dfef08b2794e67ccb0b2
|
[
"Unlicense"
] | null | null | null |
// Minimum accumulator
#include <limits>
#include <algorithm>
using namespace std;
/*snippet-begin*/
template<class T = int>
struct minval {
T x;
minval(T x = numeric_limits<T>::max()) : x(x) {}
T operator() () const { return x; }
minval operator+ (const minval& b) const { return min(x, b.x); }
minval& operator+= (const minval& b) { x = min(x, b.x); return *this; }
};
/*snippet-end*/
int main() {
minval<int> x = 4;
x = x + 3;
if (x() != 3) return 1;
(x += 2) += 1;
if (x() != 1) return 1;
}
| 21.52
| 75
| 0.553903
|
ivan100sic
|
625f16aacc167e9d5dde894985a7f206b01d4d91
| 24,013
|
cpp
|
C++
|
src/util2019.cpp
|
atyre2/HABITAT
|
bbf231fcfe48cb11b27117266bfc85f427225414
|
[
"MIT"
] | null | null | null |
src/util2019.cpp
|
atyre2/HABITAT
|
bbf231fcfe48cb11b27117266bfc85f427225414
|
[
"MIT"
] | 2
|
2019-03-29T22:15:17.000Z
|
2019-03-29T22:15:50.000Z
|
src/util2019.cpp
|
atyre2/HABITAT
|
bbf231fcfe48cb11b27117266bfc85f427225414
|
[
"MIT"
] | null | null | null |
//---------------------------------------------------------------------------
// #include <vcl.h>
// #pragma hdrstop
#include <stdlib.h>
#include <math.h>
#include "mt19937.h"
#include "matrices.h"
#include "util2019.h"
//---------------------------------------------------------------------------
#define NR_END 1
#define FREE_ARG char*
#define ENDRUN '!'
#define COMMENT '*'
#define MAXOUTFILES 10
#define ALLFILES -1
#define MAKESTR(A,B,C) A ## B ## C
/* singly linked list of parameter structures */
/* used by the multiple run functions */
struct varlist plist = {"parmlist",NULL,NOTYPE,NULL};
// void error(char error_text[])
// /* Drew Tyre's standard error handler */
// {
// fprintf(stderr,"Drew Tyre run-time error...\n");
// fprintf(stderr,"%s\n",error_text);
// fprintf(stderr,"...now exiting to system...\n");
// // ShowMessage(error_text);
// exit(1);
// } /* end function error */
// int getnextrun(char rerunname[])
// /* reads all meaningful lines in a rerun file, resets the named variables,
// and returns non-zero if another rerun is to be performed. It handles the
// opening of the rerun file itself. If the file does not exist, or if the
// end of the file has been reached, then the function returns zero */
// {
// static long int oldfilepos = 0L;
// char buffer[LINELEN] = "\0", message[LINELEN] = "\0";
// unsigned int foundit = FALSE, check1 = 0, check2 = 0;
// struct varlist *curparm;
// FILE *rerunfile;
//
// if ((rerunfile = fopen(rerunname,"r")) == NULL)
// { /* no rerun file exists, so return 0 to calling program */
// return 0;
// }
//
// /* move to last position read */
// if (fseek(rerunfile,oldfilepos,SEEK_SET))
// {
// error("Bad oldfilepos in getnewrun");
// }
//
// /* read in file one line at a time, discarding lines beginning with
// COMMENT, and stopping when a line starts with ENDRUN or EOF
// is reached */
// fgets(buffer,LINELEN,rerunfile);
// while (!feof(rerunfile) && (buffer[0] != ENDRUN))
// {
// if (buffer[0] != COMMENT)
// { /* line contains a variable, so find the variable in plist */
// curparm = plist.next;
// foundit = FALSE;
// while (curparm != NULL)
// {
// check1 = 0;
// check2 = 0;
// while (buffer[check1++] == curparm->name[check2++]);
// if (check1 > strlen(curparm->name))
// { /* found the variable in plist */
// foundit = TRUE;
// switch(curparm->type)
// {
// case REAL :
// sscanf(&buffer[check1]," %f",(float *) curparm->address);
// break;
// case DOUBLE :
// sscanf(&buffer[check1]," %lf",(double *) curparm->address);
// break;
// case INTEGER :
// sscanf(&buffer[check1]," %d",(int *) curparm->address);
// break;
// case LONGINT :
// sscanf(&buffer[check1]," %ld",(long int *) curparm->address);
// break;
// case STRING :
// sscanf(&buffer[check1]," %s",(char *) curparm->address);
// break;
// default :
// strcat(message,"Bad parmtype in plist, ");
// strcat(message,curparm->name);
// error(message);
// }
// /* exit loop over plist */
// break;
// }
// /* skip to next entry in plist */
// curparm = curparm->next;
// } /* end of loop over plist */
//
// if (!foundit)
// {
// strcat(message,"Bad variable name ");
// strcat(message,buffer);
// strcat(message," in rerunfile");
// error(message);
// }
// } /* end if buffer[0] != comment */
// /* get next line in rerunfile */
// fgets(buffer,LINELEN,rerunfile);
//
// } /* end of while !feof && buffer[0] != comment */
//
// /* remember where we reached in the file */
// oldfilepos = ftell(rerunfile);
//
// /* close the rerunfile, or the file handles overflow! */
// fclose(rerunfile);
//
// if (foundit)
// { /* found something, so do another run */
// return 1;
// }
// else
// { /* found nothing, so don't do another run */
// return 0;
// }
//
// } /* end of getnewrun */
//
// void rdsvar(FILE *infile, char varname[], void *address, int parmtype)
// /* reads a variable of parmtype in from infile. Assumes that the next
// line is the one that has the variable in question but will wrap once to
// find the variable */
// {
// int foundit, namelen, check1, check2, wrapped, gotit;
// char buffer[LINELEN] = "\0"; /* for storing the line found in the file */
// char message[LINELEN] = "\0"; /* for storing errormessages */
//
// namelen = strlen(varname); /* figure out how long the string is */
// foundit = FALSE;
// wrapped = FALSE;
//
// do
// { /* loop through file looking for varname */
// check1 = 0;
// check2 = 0;
// fgets(buffer,LINELEN,infile);
// if (feof(infile) && !(wrapped))
// { /* reached the end of the file for the first time */
// wrapped = TRUE;
// rewind(infile);
// }
//
// while (buffer[check1++] == varname[check2++]);
// if (check1 > (namelen-1))
// { /* varname matches upto namelen */
// foundit = TRUE;
//
// switch(parmtype)
// {
// case REAL :
// gotit = sscanf(&buffer[check1]," %f", (float *) address);
// break;
// case DOUBLE :
// gotit = sscanf(&buffer[check1]," %lf", (double *) address);
// break;
// case INTEGER :
// gotit = sscanf(&buffer[check1]," %d", (int *) address);
// break;
// case LONGINT :
// gotit = sscanf(&buffer[check1]," %ld", (long int *) address);
// break;
// case STRING :
// gotit = sscanf(&buffer[check1]," %s", (char *) address);
// break;
// default :
// strcat(message,"Bad parmtype in rdsvar, ");
// strcat(message,varname);
// error(message);
// } /* end of switch(parmtype) */
//
// if (!gotit)
// {
// strcat(message,"Unable to scan ");
// strcat(message,varname);
// error(message);
// } /* end of if (!gotit) */
//
// if (!addsvar(&plist,varname,address,parmtype))
// { /* unable to stick variable info into plist */
// strcat(message,"Unable to put ");
// strcat(message,varname);
// strcat(message," in plist");
// error(message);
// } /* end of if !addsvar */
// } /* end of if (check1 > (namelen - 1)) */
// } /* end of do-while */
// while (!foundit && !(feof(infile) && wrapped));
// if (!foundit)
// {
// strcat(message, "Unable to find ");
// strcat(message,varname);
// error(message);
// }
// return;
// }
// int addsvar(struct varlist *list, char varname[],void *address,int parmtype)
// /* adds a variable to a singly linked list plist. The list is used by the
// functions rdsets and rdrun to update variables for multiple runs */
// {
//
// /* find the end of the list */
// while (list->next != NULL) list = list->next;
//
// /* allocate a new structure */
// list->next = (struct varlist *) malloc(sizeof(struct varlist));
//
// /* check for success */
// if (list->next == NULL) return 0;
//
// /* set list to new structure */
// list = list->next;
//
// /* fill in the blanks */
// strcpy(list->name,varname);
// list->address = address;
// list->type = parmtype;
// list->next = NULL; /* VERY IMPORTANT!!! */
//
// return 1; /* successfully added variable */
//
// }
//
// int dumpvars(struct varlist *list)
// /* dumps the entire variable list */
// {
// struct varlist *top, *next;
//
// /* can't deallocate the head of the list, so move to the next item */
// top = list->next;
//
// while (top != NULL)
// {
// next = top->next;
// free(top);
// top = next;
// }
//
// return 0; /* successfully dumped list */
//
// }
// double lint(char tname[], struct rtable table[], double key)
// /* This function performs a linear interpolation on a function stored in */
// /* table. key gives the independent variable that is to be used to */
// /* initiate the table lookup. lint assumes that key is sorted in */
// /* order in table */
// {
// double result, slope;
// int bottom, top;
//
// top = tsearch(tname, table, key);
// bottom = top - 1;
//
// slope = (table[top].yval - table[bottom].yval) /
// (table[top].xval - table[bottom].xval);
//
// result = (slope * (key - table[bottom].xval)) + table[bottom].yval;
// return result;
// }
//
// int tsearch(char tname[], struct rtable table[], double key)
// /* This function searches table for the first value greater than or */
// /* equal to key, and returns the array index of that value */
// /* The function relies on the fact that the last key in the table */
// /* will be much larger than any key that will be passed. The function also */
// /* "remembers" which table it last searched, and where it reached in that */
// /* table. The static variables lasttable and lastreached are used for this. */
// /* This fact is used to speed up sequential searches on sorted tables. */
// {
// int current, result;
// static char lasttable[VNAMELEN];
// static int lastreached;
//
// if((strcmp(tname,lasttable)==0) && (table[lastreached].xval < key))
// { /* searching the same table as last time */
// current = lastreached;
// }
// else
// { /* searching a new table, or a previous value */
// current = 0;
// strcpy(lasttable,tname);
// }
//
// /* loop through the table until the value is greater than or */
// /* equal the key */
// while (table[current++].xval < key);
//
// lastreached = current - 1; /* set the global variable lastreached */
// result = current - 1; /* return a 'pointer' to the previous entry */
// return result;
// }
// void rdtable(FILE *initfile, char searchstr[], struct rtable table[])
// /* Reads the x and y values from a table. Table has to have the */
// /* following format : */
// /* tablename tablelength */
// /* xvalue yvalue */
// /* ... ... */
// {
// int i, arraysize;
// char foundstr[80];
//
// rdsvar(initfile,searchstr,&arraysize,INTEGER);
//
// if (arraysize > TABMAX)
// {
// fprintf(stderr, "table '%s' has too many lines\n", searchstr);
// exit(1);
// }
//
// for (i = 0; i <= (arraysize-1); i++)
// {
// fgets(foundstr,80,initfile);
// sscanf(foundstr," %lf %lf",&table[i].xval,&table[i].yval);
// }
//
// return;
// }
// void rdvector(FILE *initfile, char searchstr[], void *vector, int parmtype)
// /* Reads vector values from a list. List has to have the */
// /* following format : */
// /* vectorname # of entries */
// /* value */
// /* ... */
// /*********************************************************************/
// /* NB!! assumes that sufficient space has been set aside in vector!! */
// /*********************************************************************/
// {
// int i, vectorsize;
// char foundstr[80];
// char message[LINELEN] = "\0"; /* for storing errormessages */
//
// /* use rdsvar to find the start of the list */
// rdsvar(initfile,searchstr,&vectorsize,INTEGER);
//
// for (i = 0; i <= (vectorsize-1); i++)
// {
// fgets(foundstr,80,initfile);
// switch(parmtype){
// case REAL :
// sscanf(foundstr," %f", &(((float *) vector)[i]));
// break;
// case INTEGER :
// sscanf(foundstr," %d", &(((int *) vector)[i]));
// break;
// case DOUBLE :
// sscanf(foundstr," %lf", &(((double *) vector)[i]));
// break;
// default :
// strcat(message,"Bad parmtype in rdvector , ");
// strcat(message,searchstr);
// error(message);
// } /* end switch */
// }
//
// return;
// }
double chop(double x, int a, int b)
{
if (x < a)
{
x = a;
}
else if (x > b)
{
x = b;
}
return x;
} /* end of chop */
// int round(double x)
// {
// int dum1, result;
// double dum2;
//
// dum1 = x;
// dum2 = x - dum1;
// if(dum2 < 0.5)
// {
// result = floor(x); /* round x down */
// }
// else
// {
// result = ceil(x); /* round x up */
// }
// return result;
// } /* end of round */
//
/* Returns the probability of finding an odourconcentration of */
/* i individuals in a quadrat, */
/* given a mean of 'mean' and the aggregation coefficient 'k' */
/* Taken from Krebs 1989 Ecological Methodology, page 82 */
/* I assume that n hosts produce an odourconc of n */
double negbin(int i, double k, double mean)
{
double tmp1, tmp2, tmp3, result;
tmp1 = exp(gammln(k + i)) / (factrl(i) * exp(gammln(k)));
tmp2 = mean / (mean + k);
tmp3 = k / (k + mean);
if (tmp2 < 0) exit(425); //printf("Domain error: tmp2\n");
if (tmp3 < 0) exit(426); //printf("Domain error: tmp3\n");
result = tmp1 * pow(tmp2,(double)i) * pow(tmp3,k);
return result;
}
/* Computes the log of Lanczos approximation to gamma function */
/* From Numerical recepies in C. error < 2E-10!! */
/* Some modifications were also taken from the numerical recipes book */
/* in fortran */
double gammln(double xx)
{
double czero = 1.000000000190015;
double roottwopi = 2.5066282746310005;
double cof[8] = {0, 76.1800917294716, -86.50532032941677,
24.01409824083091, -1.231739572450155,
0.1208650973866179E-2, -0.5395239384953E-5};
double x, series, tmp1, tmp2;
int j;
double result;
x = xx - 1;
tmp1 = x + 5.5;
tmp2 = (x + 0.5) * log(tmp1) - tmp1;
/* initialize the series with the first term */
series = czero;
/* loop summs each coefficient divided by x+j */
for(j = 1;j <= 6;j ++)
{
series += cof[j] / (x + j);
}
result = tmp2 + log(roottwopi * series); /* return this value */
return result;
}
/* Returns the factorial of n as a doubleing point number */
double factrl(int n)
{
double result;
int ntop = 4; /* This is the top of the table */
/* This is the table of results, fill up as required */
double a[33] = {1.0, 1.0, 2.0, 6.0, 24.0};
if(n < 0)
{
//printf("Negative factorial in routine factl\n");
exit(n);
}
if(n > 32) /* larger value than is in table, probably will overflow */
{
result = exp(gammln(n + 1.0));
}
else
{
while(ntop < n) /* fill in table up to required value */
{
ntop ++;
a[ntop] = a[ntop - 1] * ntop;
}
result = a[n]; /* return table value */
}
return result;
}
/* This function calculates the probability that there are i hosts on
a plant, given the plant is occupied */
double con_negbin(int i, double k, double mean)
{
double result, b, a;
a = negbin(i,k,mean);
b = 1-negbin(0,k,mean);
result = a/b;
return result;
}
// /* Returns a normally distributed deviate with zero mean and unit variance,
// using ran1(idum) as the source of uniform deviates. Taken from
// numerical recipes book in c, p.289 */
//
// float gasdev(void)
// {
// /* float ran3(long *idum); */
// static int iset=0;
// static float gset;
// float fac, rsq, v1, v2, temp;
//
// /* We don't have an extra deviate handy, so pick 2 uniform numbers in
// the square extending from -1 to +1 in each direction, see if they
// are in the unit circle, and if they are not, try again.*/
// if (iset == 0){
// do{
// v1 = 2.0*rand0to1()-1.0;
// v2 = 2.0*rand0to1()-1.0;
// rsq=v1*v1+v2*v2;
// }while (rsq >= 1.0 ||rsq == 0.0);
//
// temp = -2.0*log(rsq)/rsq;
// if (temp >= 0.0) fac = sqrt(temp);
// else {
// printf("error in gasdev\n");
// }
// /* Now make the Box-Muller transformation to get 2 normal deviates.
// Return one and save the other for the next time. */
// gset = v1*fac;
// iset=1; /*set flag */
// return v2*fac;
// } else{
// /* We have an extra deviate handy, so unset the flag, and return it.*/
// iset = 0;
// return gset;
// }
// }
//
// int randompick(double prob[], int maxint)
// {
// double x, sumprob = 0;
// int z = 0, choose = 0, i = -1;
//
// /* x determines the target variable */
// x = genrand();
//
// do
// {
// i++;
// sumprob += prob[i];
// if (x <= sumprob)
// {
// choose = i;
// z = 1;
// }
// } while (!z);
//
// if (choose > maxint){
// fprintf(stderr,"choose: %d maxint: %d\n",choose,maxint);
// for (i = 0; i<=choose; i++) fprintf(stderr,"%d %f\n",i,prob[i]);
// fprintf(stderr,"bad probability sum in randompick!\n");
// exit(1);
// }
//
// return choose;
// }
// float **matrix(long nrl, long nrh, long ncl, long nch)
// /* allocate a float matrix with subscript range m[nrl..nrh][ncl..nch] */
// {
// long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
// float **m;
//
// /* allocate pointers to rows */
// m=(float **) malloc((size_t)((nrow+NR_END)*sizeof(float*)));
// if (!m) exit(1); // error("allocation failure 1 in matrix()");
// m += NR_END;
// m -= nrl;
//
// /* allocate rows and set pointers to them */
// m[nrl]=(float *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(float)));
// if (!m[nrl]) exit(1); //error("allocation failure 2 in matrix()");
// m[nrl] += NR_END;
// m[nrl] -= ncl;
//
// for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
//
// /* return pointer to array of pointers to rows */
// return m;
// }
//
// void free_matrix(float **m, long nrl, long nrh, long ncl, long nch)
// /* free a float matrix allocated by matrix() */
// {
// free((FREE_ARG) (m[nrl]+ncl-NR_END));
// free((FREE_ARG) (m+nrl-NR_END));
// }
float *vector(long nl, long nh)
/* allocate a float vector with subscript range v[nl..nh] */
{
float *v;
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
if (!v) exit(1); //error("allocation failure in vector()");
return v-nl+NR_END;
}
void free_vector(float *v, long nl, long nh)
/* free a float vector allocated with vector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void hqr(float **a, int n, float wr[], float wi[])
{
int nn,m,l,k,j,its,i,mmin;
float z,y,x,w,v,u,t,s,r,q,p,anorm;
anorm=fabs(a[1][1]);
for (i=2;i<=n;i++)
for (j=(i-1);j<=n;j++)
anorm += fabs(a[i][j]);
nn=n;
t=0.0;
while (nn >= 1) {
its=0;
do {
for (l=nn;l>=2;l--) {
s=fabs(a[l-1][l-1])+fabs(a[l][l]);
if (s == 0.0) s=anorm;
if ((float)(fabs(a[l][l-1]) + s) == s) break;
}
x=a[nn][nn];
if (l == nn) {
wr[nn]=x+t;
wi[nn--]=0.0;
} else {
y=a[nn-1][nn-1];
w=a[nn][nn-1]*a[nn-1][nn];
if (l == (nn-1)) {
p=0.5*(y-x);
q=p*p+w;
z=sqrt(fabs(q));
x += t;
if (q >= 0.0) {
z=p+SIGN(z,p);
wr[nn-1]=wr[nn]=x+z;
if (z) wr[nn]=x-w/z;
wi[nn-1]=wi[nn]=0.0;
} else {
wr[nn-1]=wr[nn]=x+p;
wi[nn-1]= -(wi[nn]=z);
}
nn -= 2;
} else {
if (its == 30) exit(663); //error("Too many iterations in hqr");
if (its == 10 || its == 20) {
t += x;
for (i=1;i<=nn;i++) a[i][i] -= x;
s=fabs(a[nn][nn-1])+fabs(a[nn-1][nn-2]);
y=x=0.75*s;
w = -0.4375*s*s;
}
++its;
for (m=(nn-2);m>=l;m--) {
z=a[m][m];
r=x-z;
s=y-z;
p=(r*s-w)/a[m+1][m]+a[m][m+1];
q=a[m+1][m+1]-z-r-s;
r=a[m+2][m+1];
s=fabs(p)+fabs(q)+fabs(r);
p /= s;
q /= s;
r /= s;
if (m == l) break;
u=fabs(a[m][m-1])*(fabs(q)+fabs(r));
v=fabs(p)*(fabs(a[m-1][m-1])+fabs(z)+fabs(a[m+1][m+1]));
if ((float)(u+v) == v) break;
}
for (i=m+2;i<=nn;i++) {
a[i][i-2]=0.0;
if (i != (m+2)) a[i][i-3]=0.0;
}
for (k=m;k<=nn-1;k++) {
if (k != m) {
p=a[k][k-1];
q=a[k+1][k-1];
r=0.0;
if (k != (nn-1)) r=a[k+2][k-1];
if ((x=fabs(p)+fabs(q)+fabs(r)) != 0.0) {
p /= x;
q /= x;
r /= x;
}
}
if ((s=SIGN(sqrt(p*p+q*q+r*r),p)) != 0.0) {
if (k == m) {
if (l != m)
a[k][k-1] = -a[k][k-1];
} else
a[k][k-1] = -s*x;
p += s;
x=p/s;
y=q/s;
z=r/s;
q /= p;
r /= p;
for (j=k;j<=nn;j++) {
p=a[k][j]+q*a[k+1][j];
if (k != (nn-1)) {
p += r*a[k+2][j];
a[k+2][j] -= p*z;
}
a[k+1][j] -= p*y;
a[k][j] -= p*x;
}
mmin = nn<k+3 ? nn : k+3;
for (i=l;i<=mmin;i++) {
p=x*a[i][k]+y*a[i][k+1];
if (k != (nn-1)) {
p += z*a[i][k+2];
a[i][k+2] -= p*r;
}
a[i][k+1] -= p*q;
a[i][k] -= p;
}
}
}
}
}
} while (l < nn-1);
}
}
#define CON 1.4
#define CON2 (CON*CON)
#define BIG 1.0e30
#define NTAB 10
#define SAFE 2.0
float dfridr(float (*func)(float), float x, float h, float *err)
{
int i,j;
float errt,fac,hh,**a,ans;
if (h == 0.0) exit(754); //error("h must be nonzero in dfridr.");
a=matrix(1,NTAB,1,NTAB);
hh=h;
a[1][1]=((*func)(x+hh)-(*func)(x-hh))/(2.0*hh);
*err=BIG;
for (i=2;i<=NTAB;i++) {
hh /= CON;
a[1][i]=((*func)(x+hh)-(*func)(x-hh))/(2.0*hh);
fac=CON2;
for (j=2;j<=i;j++) {
a[j][i]=(a[j-1][i]*fac-a[j-1][i-1])/(fac-1.0);
fac=CON2*fac;
errt=FMAX(fabs(a[j][i]-a[j-1][i]),fabs(a[j][i]-a[j-1][i-1]));
if (errt <= *err) {
*err=errt;
ans=a[j][i];
}
}
if (fabs(a[i][i]-a[i-1][i-1]) >= SAFE*(*err)) {
free_matrix(a,1,NTAB,1,NTAB);
return ans;
}
}
free_matrix(a,1,NTAB,1,NTAB);
return ans;
}
#undef CON
#undef CON2
#undef BIG
#undef NTAB
#undef SAFE
/* following 3 routines do romberg integration on closed intervals */
void polint(float xa[], float ya[], int n, float x, float *y, float *dy)
{
int i,m,ns=1;
float den,dif,dift,ho,hp,w;
float *c,*d;
dif=fabs(x-xa[1]);
c=vector(1,n);
d=vector(1,n);
for (i=1;i<=n;i++) {
if ( (dift=fabs(x-xa[i])) < dif) {
ns=i;
dif=dift;
}
c[i]=ya[i];
d[i]=ya[i];
}
*y=ya[ns--];
for (m=1;m<n;m++) {
for (i=1;i<=n-m;i++) {
ho=xa[i]-x;
hp=xa[i+m]-x;
w=c[i+1]-d[i];
if ( (den=ho-hp) == 0.0) exit(810); // error("Error in routine polint");
den=w/den;
d[i]=hp*den;
c[i]=ho*den;
}
*y += (*dy=(2*ns < (n-m) ? c[ns+1] : d[ns--]));
}
free_vector(d,1,n);
free_vector(c,1,n);
}
#define FUNC(x) ((*func)(x))
float trapzd(float (*func)(float), float a, float b, int n)
{
float x,tnm,sum,del;
static float s;
int it,j;
if (n == 1) {
return (s=0.5*(b-a)*(FUNC(a)+FUNC(b)));
} else {
for (it=1,j=1;j<n-1;j++) it <<= 1;
tnm=it;
del=(b-a)/tnm;
x=a+0.5*del;
for (sum=0.0,j=1;j<=it;j++,x+=del) sum += FUNC(x);
s=0.5*(s+(b-a)*sum/tnm);
return s;
}
}
#undef FUNC
#define EPS 1.0e-6
#define JMAX 20
#define JMAXP (JMAX+1)
#define K 5
float qromb(float (*func)(float), float a, float b)
{
void polint(float xa[], float ya[], int n, float x, float *y, float *dy);
float trapzd(float (*func)(float), float a, float b, int n);
float ss,dss;
float s[JMAXP+1],h[JMAXP+1];
int j;
h[1]=1.0;
for (j=1;j<=JMAX;j++) {
s[j]=trapzd(func,a,b,j);
if (j >= K) {
polint(&h[j-K],&s[j-K],K,0.0,&ss,&dss);
if (fabs(dss) < EPS*fabs(ss)) return ss;
}
s[j+1]=s[j];
h[j+1]=0.25*h[j];
}
exit(866); //error("Too many steps in routine qromb");
return 0.0;
}
#undef EPS
#undef JMAX
#undef JMAXP
#undef K
| 27.4121
| 85
| 0.510848
|
atyre2
|
62613226c0ef2b43ecb6ec9f8c8a941374abf6f4
| 445
|
cpp
|
C++
|
glfw3_app/nesemu/tools.cpp
|
hirakuni45/glfw3_app
|
d9ceeef6d398229fda4849afe27f8b48d1597fcf
|
[
"BSD-3-Clause"
] | 9
|
2015-09-22T21:36:57.000Z
|
2021-04-01T09:16:53.000Z
|
glfw3_app/nesemu/tools.cpp
|
hirakuni45/glfw3_app
|
d9ceeef6d398229fda4849afe27f8b48d1597fcf
|
[
"BSD-3-Clause"
] | null | null | null |
glfw3_app/nesemu/tools.cpp
|
hirakuni45/glfw3_app
|
d9ceeef6d398229fda4849afe27f8b48d1597fcf
|
[
"BSD-3-Clause"
] | 2
|
2019-02-21T04:22:13.000Z
|
2021-03-02T17:24:32.000Z
|
//=====================================================================//
/*! @file
@brief Emulator Tools クラス @n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "tools.hpp"
gui::widget_terminal* emu::tools::terminal_;
extern "C" {
int emu_log(const char* text)
{
emu::tools::put(text);
return 0;
}
};
| 20.227273
| 74
| 0.408989
|
hirakuni45
|
6264f8e9d3635d9a6d7e0fced804644032b46d42
| 739
|
hpp
|
C++
|
file_util/tests/fixtures.hpp
|
ScottGarman/leatherman
|
7c1407c29b056148e6332dabf4017ca50f064a94
|
[
"Apache-2.0"
] | 55
|
2015-08-27T13:17:42.000Z
|
2022-02-07T15:19:59.000Z
|
file_util/tests/fixtures.hpp
|
ScottGarman/leatherman
|
7c1407c29b056148e6332dabf4017ca50f064a94
|
[
"Apache-2.0"
] | 236
|
2015-02-23T23:50:10.000Z
|
2021-09-01T18:09:12.000Z
|
file_util/tests/fixtures.hpp
|
ScottGarman/leatherman
|
7c1407c29b056148e6332dabf4017ca50f064a94
|
[
"Apache-2.0"
] | 88
|
2015-02-23T22:40:27.000Z
|
2022-02-07T15:19:59.000Z
|
#pragma once
#include <string>
#include <boost/filesystem/path.hpp>
/**
* Class to create a temporary directory with a unique name
* and destroy it once it is no longer needed.
* */
class temp_directory {
public:
temp_directory();
~temp_directory();
std::string const& get_dir_name() const;
private:
std::string dir_name;
};
/**
* Class to create a temporary file with a unique name and
* destroy it once it is no longer needed.
*/
class temp_file {
public:
temp_file(std::string const& content);
~temp_file();
std::string const& get_file_name() const;
private:
std::string file_name;
};
/** Generates a unique string for use as a file path. */
boost::filesystem::path unique_fixture_path();
| 18.948718
| 59
| 0.690122
|
ScottGarman
|
62650a65e609cedbe8ee98bbc962ff63c7f98e28
| 1,391
|
cpp
|
C++
|
targets/simple_router/primitives.cpp
|
edgarcosta92/behavioral-model
|
de9ec3ddc45c2b210681a7675c0bded6e56ec9d3
|
[
"Apache-2.0"
] | 390
|
2015-10-13T05:22:51.000Z
|
2022-03-30T19:18:14.000Z
|
targets/simple_router/primitives.cpp
|
edgarcosta92/behavioral-model
|
de9ec3ddc45c2b210681a7675c0bded6e56ec9d3
|
[
"Apache-2.0"
] | 919
|
2015-08-10T17:50:50.000Z
|
2022-03-31T17:46:07.000Z
|
targets/simple_router/primitives.cpp
|
edgarcosta92/behavioral-model
|
de9ec3ddc45c2b210681a7675c0bded6e56ec9d3
|
[
"Apache-2.0"
] | 351
|
2015-09-18T03:32:32.000Z
|
2022-03-31T03:56:38.000Z
|
/* Copyright 2013-present Barefoot Networks, 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.
*/
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
#include <bm/bm_sim/actions.h>
#include <bm/bm_sim/core/primitives.h>
template <typename... Args>
using ActionPrimitive = bm::ActionPrimitive<Args...>;
using bm::Data;
using bm::Field;
using bm::Header;
class modify_field : public ActionPrimitive<Field &, const Data &> {
void operator ()(Field &f, const Data &d) {
bm::core::assign()(f, d);
}
};
REGISTER_PRIMITIVE(modify_field);
class add_to_field : public ActionPrimitive<Field &, const Data &> {
void operator ()(Field &f, const Data &d) {
f.add(f, d);
}
};
REGISTER_PRIMITIVE(add_to_field);
class drop : public ActionPrimitive<> {
void operator ()() {
get_field("standard_metadata.egress_spec").set(511);
}
};
REGISTER_PRIMITIVE(drop);
| 25.759259
| 75
| 0.71028
|
edgarcosta92
|
6266e72f69150a43924556ec15b610e0c9ce2ee3
| 3,530
|
cpp
|
C++
|
ObjOrientedProgramming/Ticket/Ticket/TicketDemo.cpp
|
jhbrian/Learning-Progress
|
de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb
|
[
"MIT"
] | null | null | null |
ObjOrientedProgramming/Ticket/Ticket/TicketDemo.cpp
|
jhbrian/Learning-Progress
|
de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb
|
[
"MIT"
] | null | null | null |
ObjOrientedProgramming/Ticket/Ticket/TicketDemo.cpp
|
jhbrian/Learning-Progress
|
de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb
|
[
"MIT"
] | null | null | null |
//****************************************************************************************************
//Program Name: Tickets
//Author: Jin Han Ho
//IDE Used: Visual Studio 2019
//Program description: This program will show the status of ticket that is issued the police in a day
//****************************************************************************************************
#include "Police.h"
#include "Ticket.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//************************************************************************************
//Function name: Print1
//Purpose: Print out the daily report before payments are done
//List of parameters: vector<Ticket> TicketInfo, double sum
//Returns: no return variable
//Return type: void
//************************************************************************************
//************************************************************************************
//Function name: Print2
//Purpose: Print out the daily report after payments are done
//List of parameters: vector<Ticket> TicketInfo, double sum, double sum2, int counter
//Returns: no return variable
//Return type: void
//************************************************************************************
void Print1(vector<Ticket> TicketInfo, double &sum) {
cout << "Daily ticket report: " << endl;
for (int i = 0; i < TicketInfo.size(); i++) {
TicketInfo.at(i).printTicket();
sum += TicketInfo.at(i).getFine();
}
cout << "Number of tickets: " << TicketInfo.size() << endl;
cout << "Revenues due: $" << fixed << setprecision(2) << sum << endl << endl;
}
void Print2(vector<Ticket> TicketInfo, double &sum, double &sum2, int counter) {
cout << "Payment processing complete; new status report: " << endl;
for (int i = 0; i < TicketInfo.size(); i++) {
TicketInfo.at(i).printTicket();
TicketInfo.at(i).getStatus() ? counter++ //counter + 1 if the status is paid;
: sum2 += TicketInfo.at(i).getFine();
}
cout << "Number paid: " << counter
<< " (Total: $" << (sum - sum2) << ")" << endl; //Total due before payment minus unpaid
cout << "Number unpaid: " << TicketInfo.size() - counter
<< " (Total: $" << fixed << setprecision(2) << sum2 << ")" << endl;
}
int main()
{
vector<Ticket>TicketInfo;
ifstream fin;
int tnum, badgenum, counter = 0;
double due, sum = 0, sum2 = 0;
bool pay;
string vio, name;
fin.open("tickets.txt");
while (fin >> vio) {
fin >> tnum;
fin >> due;
fin >> name;
fin >> badgenum;
TicketInfo.push_back(Ticket(vio, tnum, due, name, badgenum));
}
Print1(TicketInfo, sum); //print first report
fin.close();
fin.open("payments.txt");
int i = 0;
while (fin >> pay) {
TicketInfo.at(i).setStatus(pay); //setting new payment status
i++;
}
Print2(TicketInfo, sum, sum2, counter); //print second report
fin.close();
cout << endl << endl << endl;
cout << "I attest that this code is my original programming work, and that I received" << endl
<< "no help creating it.I attest that I did not copy this code or any portion of this" << endl
<< "code from any source." << endl;
return 0;
}
| 36.020408
| 103
| 0.490935
|
jhbrian
|
62671ee1cbacfc0750822aa3e74857d8a24f97a9
| 10,662
|
cpp
|
C++
|
example/SVG_text_width_height.cpp
|
pabristow/svg_plot
|
59e06b752acc252498e0ddff560b01fb951cb909
|
[
"BSL-1.0"
] | 24
|
2016-03-09T03:23:06.000Z
|
2021-01-12T14:02:07.000Z
|
example/SVG_text_width_height.cpp
|
pabristow/svg_plot
|
59e06b752acc252498e0ddff560b01fb951cb909
|
[
"BSL-1.0"
] | 11
|
2018-03-05T14:39:48.000Z
|
2021-08-22T09:00:33.000Z
|
example/SVG_text_width_height.cpp
|
pabristow/svg_plot
|
59e06b752acc252498e0ddff560b01fb951cb909
|
[
"BSL-1.0"
] | 10
|
2016-11-04T14:36:04.000Z
|
2020-07-17T08:12:03.000Z
|
/*!
\brief
Demonstrates actual length of text displayed as SVG.
Shows warning from too much compression using text_length.
And also shows use of text_length can undercompress to space out glyphs to become unreadable.
Font Support for Unicode Characters
https://www.fileformat.info/info/unicode/font/index.htm
Shows aspect ratio for font size 10 varys from 0.55 to 0.4
no of chars that fit the 1000 image varies from
120 letter M units (em width) - the widest
340 letter i - the narrowest
random letters from 180 to 240
aspect ratios
lucida sans unicode 0.49
verdana 0.48
arial 0.42
Tme New Roman 0.4
in svg_style.hpp
static const fp_type aspect_ratio = 0.6; //!< aspect_ratio is a guess at average height to width of font.
Examples of using function plot.title_text_length(1000); so squeeze or expand title.
*/
// svg_text_width_height.cpp
// Copyright Paul A. Bristow 2018, 2020
// Use, modification and distribution are 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 <boost/svg_plot/svg_style.hpp>
#include <boost/svg_plot/svg_2d_plot.hpp>
// using namespace boost::svg;
#include <boost/svg_plot/show_2d_settings.hpp>
#include <iostream>
#include <string>
int main()
{
using namespace boost::svg;
// Very convenient to allow easy access to colors, data-point marker shapes and other svg_plot items.
try
{ // try'n'catch blocks are needed to ensure error messages from any exceptions are shown.
svg_2d_plot my_2d_plot; // Construct a plot with all the default constructor values.
// Containers to hold some data.
std::map<const double, double> my_data_0;
my_data_0[0.0] = 0.0;
my_data_0[10.0] = 10.0;
std::string a_title(340, 'i'); //
my_2d_plot // Nearly all default settings.
.size(1000, 200)
.title("Ω") // 116 l fill 1000 exactly 465 ll
.title("ΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩ") // 116 Ω fill 1000 exactly 465 ΩΩ
// .title("ΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩΩ") // 116 l fill 1000 exactly 465 ll
// .title("llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll") // 116 l fill 1000 exactly 465 ll
// .title("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM") // 116 M fill 1000 exactly 465 mm
// So for font width = 20 (type normal) width of an M is 1000/
// .title("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM") // 100 M width 400 mm
// .title("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii") // 116 i width 160 mm .title_on(true)
// .title(a_title) // std::string a_title(116, 'W'); Fills 1000 completely like 'M'
// .title("The Quick brown Fox jumped over the lazy dog. The Quick brown Fox jumped over the lazy dog.The Quick brown Fox jumped over the lazy dog. The Quick brown Fox jumped over the lazy dog.")
// 181 'mixed' chars 10 font size almost fills (435 mm) 1000 width so each char is 1000 / 181 = 5.5 svg unit aspect ratio = 0.55
// and triggers warning message:
// "width 1092 (SVG units) may overflow plot image!
// (Reduce font size from 10, or number of characters from 182, or increase image size from 1000)."
// .title("The Quick brown Fox jumped over the lazy dog. The Quick brown Fox jumped over the lazy dog.The Quick brown Fox jumped over the lazy dog. The Quick brown Fox jumped over the lazy dog. The quick b")
// Fills exactly char count 194 = 470 mm 1000/194 = 5.15, aspect ratio = 10/5.16 = 0.516
// so a string of 194 * 0.516 = 1000
// .title(a_title) // std::string a_title(340, 'i'); // will exactly, char count 340
//.title_font_family("Lucida sans Unicode")
//.title("Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is")
// default Lucida sans Unicode 204 chars fill 1000 pixels, so aspect ratio = 1000 /204 = 4.9 div 10 = 0.49
//.title("Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is time time for all good men to come to the")
//But 204 chars Times New Roman is only 370 mm long
//.title("Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid")
//// 249 chars fit. So aspect ratio = 1000/250 = 4, so for 10 point aspect ratio = 0.4
//.title_font_family("Arial")
//.title("Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men")
// Arial 10 point 240 chars so aspect ratio = 1000/240 = 0.42
//.title_font_family("verdana")
// verdana 10 point 208 chars so aspect ratio = 1/10 * 1000/208 = 0.48
// Example of using all the text styles:
// .title("Now is the time for all good men to come to the aid of the party.")
.title_font_size(10)
//.title_font_family("Arial")
.title_font_family("Times new roman")
// .title_font_style("italic")
// .title_font_weight("bold")
// .title_font_stretch("narrower") // May have no effect here.
// .title_font_decoration("underline")
.title_text_length(1500) // Force into an arbitrary chosen fixed width 1500 = more than full width of image so spaced out.
// and overflowing chars are lost at both end.
.title_text_length(1000) // Force into an arbitrary chosen fixed width 1000 = full width of image.
// .title_text_length(800) // Force into an arbitrary chosen fixed width very tight so letter M just touching.
// This is very long title test:
// .title("Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the ")
// if no text_length() then get warning
// font size = 5 is far too small and stretch to fit
// font size = 20 makes all the letters on top of each other.
// font size = 12 is just readable with text_length 1000.
// font size = 13 is too close and some glyphs collide with text_length 1000.
/* Error message example:
title style text_style(13, "Arial", "italic", "bold", "", "underline", 1000), text_length = 1000
Title "Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the "
estimated width 1630.2 (SVG units) may overflow plot image or or over-compress text!
(Reduce font size from 13, or number of characters from 209, or increase image size from 1000).
*/
// Squash Factor 1.6 chosen on this basis, but might be different for other fonts?
.plot(my_data_0)
;
// Show just couple of text styles
//std::cout << "title family " << my_2d_plot.title_font_family() << ", size " << my_2d_plot.title_font_size() << std::endl;
// title family Lucida Sans Unicode, size 10
std::cout << "title style " << my_2d_plot.title_style() // title style text_style(12, "Arial", "italic", "bold", "narrower", "underline", 1000)
<< ", text_length = " << my_2d_plot.title_text_length() // text_length = 1000
<< std::endl;
// Title text "Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the "
// with an estimated width 1630.2 (SVG units) may overflow plot space 1000 or over-compress text with compression ratio 1.6302.
// Reduce font size from 13, or number of characters from 209, or increase image size from 1000?.
my_2d_plot.write("./svg_text_width_height.svg"); // Plot output to file.
// Output contains for the title:
//<g id="title">
// <text x="500" y="18" text-anchor="middle" font-size="12"
//font-family="Arial" font-style="italic" font-weight="bold" font-stretch="narrower"
// text-decoration="underline"
// textLength="1e+03"> <<<<<<<< note how is forced to use the exact (estimated) width.
// Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the
// </text>
//</g>
}
catch(const std::exception& e)
{
std::cout <<
"\n""Message from thrown exception was:\n " << e.what() << std::endl;
}
return 0;
} // int main()
| 66.6375
| 881
| 0.679422
|
pabristow
|
626d06dcabb8411965addf56d6ba8c2c70b666ff
| 2,559
|
hh
|
C++
|
tests/Titon/Route/Annotation/RouteTest.hh
|
ciklon-z/framework
|
cbf44729173d3a83b91a2b0a217c6b3827512e44
|
[
"BSD-2-Clause"
] | 206
|
2015-01-02T20:01:12.000Z
|
2021-04-15T09:49:56.000Z
|
tests/Titon/Route/Annotation/RouteTest.hh
|
ciklon-z/framework
|
cbf44729173d3a83b91a2b0a217c6b3827512e44
|
[
"BSD-2-Clause"
] | 44
|
2015-01-02T06:03:43.000Z
|
2017-11-20T18:29:06.000Z
|
tests/Titon/Route/Annotation/RouteTest.hh
|
titon/framework
|
cbf44729173d3a83b91a2b0a217c6b3827512e44
|
[
"BSD-2-Clause"
] | 27
|
2015-01-03T05:51:29.000Z
|
2022-02-21T13:50:40.000Z
|
<?hh
namespace Titon\Route\Annotation;
use Titon\Annotation\Reader;
use Titon\Test\Stub\Route\RouteAnnotatedStub;
use Titon\Test\TestCase;
class RouteTest extends TestCase {
public function testParamsAreSetOnRouteAnnotation(): void {
$reader = new Reader(new RouteAnnotatedStub());
// Class
$class = $reader->getClassAnnotation('Route');
invariant($class instanceof Route, 'Must be a Route annotation.');
$this->assertEquals('parent', $class->getKey());
$this->assertEquals('/controller', $class->getPath());
$this->assertEquals(Vector {}, $class->getMethods());
$this->assertEquals(Vector {}, $class->getFilters());
$this->assertEquals(Map {}, $class->getPatterns());
// Foo
$foo = $reader->getMethodAnnotation('foo', 'Route');
invariant($foo instanceof Route, 'Must be a Route annotation.');
$this->assertEquals('foo', $foo->getKey());
$this->assertEquals('/foo', $foo->getPath());
$this->assertEquals(Vector {}, $foo->getMethods());
$this->assertEquals(Vector {}, $foo->getFilters());
$this->assertEquals(Map {}, $foo->getPatterns());
// Bar
$bar = $reader->getMethodAnnotation('bar', 'Route');
invariant($bar instanceof Route, 'Must be a Route annotation.');
$this->assertEquals('bar', $bar->getKey());
$this->assertEquals('/bar', $bar->getPath());
$this->assertEquals(Vector {'post'}, $bar->getMethods());
$this->assertEquals(Vector {}, $bar->getFilters());
$this->assertEquals(Map {}, $bar->getPatterns());
// Baz
$baz = $reader->getMethodAnnotation('baz', 'Route');
invariant($baz instanceof Route, 'Must be a Route annotation.');
$this->assertEquals('baz', $baz->getKey());
$this->assertEquals('/baz', $baz->getPath());
$this->assertEquals(Vector {'get'}, $baz->getMethods());
$this->assertEquals(Vector {'auth', 'guest'}, $baz->getFilters());
$this->assertEquals(Map {}, $baz->getPatterns());
// Qux
$qux = $reader->getMethodAnnotation('qux', 'Route');
invariant($qux instanceof Route, 'Must be a Route annotation.');
$this->assertEquals('qux', $qux->getKey());
$this->assertEquals('/qux', $qux->getPath());
$this->assertEquals(Vector {'put', 'post'}, $qux->getMethods());
$this->assertEquals(Vector {}, $qux->getFilters());
$this->assertEquals(Map {'id' => '[1-8]+'}, $qux->getPatterns());
}
}
| 36.557143
| 74
| 0.593591
|
ciklon-z
|
626eecb961d44ed5a1d7ddb33f467d95ee7b6237
| 71,731
|
tcc
|
C++
|
Vc/include/Vc/avx/vector.tcc
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 52
|
2016-12-11T13:04:01.000Z
|
2022-03-11T11:49:35.000Z
|
Vc/include/Vc/avx/vector.tcc
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 1,388
|
2016-11-01T10:27:36.000Z
|
2022-03-30T15:26:09.000Z
|
Vc/include/Vc/avx/vector.tcc
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 275
|
2016-06-21T20:24:05.000Z
|
2022-03-31T13:06:19.000Z
|
/* This file is part of the Vc library.
Copyright (C) 2011-2012 Matthias Kretz <kretz@kde.org>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include "limits.h"
#include "const.h"
#include "macros.h"
namespace AliRoot {
namespace Vc
{
ALIGN(64) extern unsigned int RandomState[16];
namespace AVX
{
///////////////////////////////////////////////////////////////////////////////////////////
// constants {{{1
template<typename T> Vc_ALWAYS_INLINE Vector<T>::Vector(VectorSpecialInitializerZero::ZEnum) : d(HT::zero()) {}
template<typename T> Vc_ALWAYS_INLINE Vector<T>::Vector(VectorSpecialInitializerOne::OEnum) : d(HT::one()) {}
template<typename T> Vc_ALWAYS_INLINE Vector<T>::Vector(VectorSpecialInitializerIndexesFromZero::IEnum)
: d(HV::load(IndexesFromZeroData<T>::address(), Aligned)) {}
template<typename T> Vc_INTRINSIC Vector<T> Vc_CONST Vector<T>::Zero() { return HT::zero(); }
template<typename T> Vc_INTRINSIC Vector<T> Vc_CONST Vector<T>::One() { return HT::one(); }
template<typename T> Vc_INTRINSIC Vector<T> Vc_CONST Vector<T>::IndexesFromZero() { return HV::load(IndexesFromZeroData<T>::address(), Aligned); }
template<typename T> template<typename T2> Vc_ALWAYS_INLINE Vector<T>::Vector(VC_ALIGNED_PARAMETER(Vector<T2>) x)
: d(StaticCastHelper<T2, T>::cast(x.data())) {}
template<typename T> Vc_ALWAYS_INLINE Vector<T>::Vector(EntryType x) : d(HT::set(x)) {}
template<> Vc_ALWAYS_INLINE Vector<double>::Vector(EntryType x) : d(_mm256_set1_pd(x)) {}
///////////////////////////////////////////////////////////////////////////////////////////
// load ctors {{{1
template<typename T> Vc_ALWAYS_INLINE Vector<T>::Vector(const EntryType *x) { load(x); }
template<typename T> template<typename A> Vc_ALWAYS_INLINE Vector<T>::Vector(const EntryType *x, A a) { load(x, a); }
template<typename T> template<typename OtherT> Vc_ALWAYS_INLINE Vector<T>::Vector(const OtherT *x) { load(x); }
template<typename T> template<typename OtherT, typename A> Vc_ALWAYS_INLINE Vector<T>::Vector(const OtherT *x, A a) { load(x, a); }
///////////////////////////////////////////////////////////////////////////////////////////
// load member functions {{{1
template<typename T> Vc_INTRINSIC void Vector<T>::load(const EntryType *mem)
{
load(mem, Aligned);
}
template<typename T> template<typename A> Vc_INTRINSIC void Vector<T>::load(const EntryType *mem, A align)
{
d.v() = HV::load(mem, align);
}
template<typename T> template<typename OtherT> Vc_INTRINSIC void Vector<T>::load(const OtherT *mem)
{
load(mem, Aligned);
}
// LoadHelper {{{2
template<typename DstT, typename SrcT, typename Flags> struct LoadHelper;
// float {{{2
template<typename Flags> struct LoadHelper<float, double, Flags> {
static m256 load(const double *mem, Flags f)
{
return concat(_mm256_cvtpd_ps(VectorHelper<m256d>::load(&mem[0], f)),
_mm256_cvtpd_ps(VectorHelper<m256d>::load(&mem[4], f)));
}
};
template<typename Flags> struct LoadHelper<float, unsigned int, Flags> {
static m256 load(const unsigned int *mem, Flags f)
{
return StaticCastHelper<unsigned int, float>::cast(VectorHelper<m256i>::load(mem, f));
}
};
template<typename Flags> struct LoadHelper<float, int, Flags> {
static m256 load(const int *mem, Flags f)
{
return StaticCastHelper<int, float>::cast(VectorHelper<m256i>::load(mem, f));
}
};
template<typename Flags> struct LoadHelper<float, unsigned short, Flags> {
static m256 load(const unsigned short *mem, Flags f)
{
return StaticCastHelper<unsigned short, float>::cast(VectorHelper<m128i>::load(mem, f));
}
};
template<typename Flags> struct LoadHelper<float, short, Flags> {
static m256 load(const short *mem, Flags f)
{
return StaticCastHelper<short, float>::cast(VectorHelper<m128i>::load(mem, f));
}
};
template<typename Flags> struct LoadHelper<float, unsigned char, Flags> {
static m256 load(const unsigned char *mem, Flags f)
{
return StaticCastHelper<unsigned int, float>::cast(LoadHelper<unsigned int, unsigned char, Flags>::load(mem, f));
}
};
template<typename Flags> struct LoadHelper<float, signed char, Flags> {
static m256 load(const signed char *mem, Flags f)
{
return StaticCastHelper<int, float>::cast(LoadHelper<int, signed char, Flags>::load(mem, f));
}
};
template<typename SrcT, typename Flags> struct LoadHelper<sfloat, SrcT, Flags> : public LoadHelper<float, SrcT, Flags> {};
// int {{{2
template<typename Flags> struct LoadHelper<int, unsigned int, Flags> {
static m256i load(const unsigned int *mem, Flags f)
{
return VectorHelper<m256i>::load(mem, f);
}
};
template<typename Flags> struct LoadHelper<int, unsigned short, Flags> {
static m256i load(const unsigned short *mem, Flags f)
{
return StaticCastHelper<unsigned short, unsigned int>::cast(VectorHelper<m128i>::load(mem, f));
}
};
template<typename Flags> struct LoadHelper<int, short, Flags> {
static m256i load(const short *mem, Flags f)
{
return StaticCastHelper<short, int>::cast(VectorHelper<m128i>::load(mem, f));
}
};
template<typename Flags> struct LoadHelper<int, unsigned char, Flags> {
static m256i load(const unsigned char *mem, Flags)
{
// the only available streaming load loads 16 bytes - twice as much as we need => can't use
// it, or we risk an out-of-bounds read and an unaligned load exception
const m128i epu8 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(mem));
const m128i epu16 = _mm_cvtepu8_epi16(epu8);
return StaticCastHelper<unsigned short, unsigned int>::cast(epu16);
}
};
template<typename Flags> struct LoadHelper<int, signed char, Flags> {
static m256i load(const signed char *mem, Flags)
{
// the only available streaming load loads 16 bytes - twice as much as we need => can't use
// it, or we risk an out-of-bounds read and an unaligned load exception
const m128i epi8 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(mem));
const m128i epi16 = _mm_cvtepi8_epi16(epi8);
return StaticCastHelper<short, int>::cast(epi16);
}
};
// unsigned int {{{2
template<typename Flags> struct LoadHelper<unsigned int, unsigned short, Flags> {
static m256i load(const unsigned short *mem, Flags f)
{
return StaticCastHelper<unsigned short, unsigned int>::cast(VectorHelper<m128i>::load(mem, f));
}
};
template<typename Flags> struct LoadHelper<unsigned int, unsigned char, Flags> {
static m256i load(const unsigned char *mem, Flags)
{
// the only available streaming load loads 16 bytes - twice as much as we need => can't use
// it, or we risk an out-of-bounds read and an unaligned load exception
const m128i epu8 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(mem));
const m128i epu16 = _mm_cvtepu8_epi16(epu8);
return StaticCastHelper<unsigned short, unsigned int>::cast(epu16);
}
};
// short {{{2
template<typename Flags> struct LoadHelper<short, unsigned short, Flags> {
static m128i load(const unsigned short *mem, Flags f)
{
return StaticCastHelper<unsigned short, short>::cast(VectorHelper<m128i>::load(mem, f));
}
};
template<typename Flags> struct LoadHelper<short, unsigned char, Flags> {
static m128i load(const unsigned char *mem, Flags)
{
// the only available streaming load loads 16 bytes - twice as much as we need => can't use
// it, or we risk an out-of-bounds read and an unaligned load exception
const m128i epu8 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(mem));
return _mm_cvtepu8_epi16(epu8);
}
};
template<typename Flags> struct LoadHelper<short, signed char, Flags> {
static m128i load(const signed char *mem, Flags)
{
// the only available streaming load loads 16 bytes - twice as much as we need => can't use
// it, or we risk an out-of-bounds read and an unaligned load exception
const m128i epi8 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(mem));
return _mm_cvtepi8_epi16(epi8);
}
};
// unsigned short {{{2
template<typename Flags> struct LoadHelper<unsigned short, unsigned char, Flags> {
static m128i load(const unsigned char *mem, Flags)
{
// the only available streaming load loads 16 bytes - twice as much as we need => can't use
// it, or we risk an out-of-bounds read and an unaligned load exception
const m128i epu8 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(mem));
return _mm_cvtepu8_epi16(epu8);
}
};
// general load, implemented via LoadHelper {{{2
template<typename DstT> template<typename SrcT, typename Flags> Vc_INTRINSIC void Vector<DstT>::load(const SrcT *x, Flags f)
{
d.v() = LoadHelper<DstT, SrcT, Flags>::load(x, f);
}
///////////////////////////////////////////////////////////////////////////////////////////
// zeroing {{{1
template<typename T> Vc_INTRINSIC void Vector<T>::setZero()
{
data() = HV::zero();
}
template<typename T> Vc_INTRINSIC void Vector<T>::setZero(const Mask &k)
{
data() = HV::andnot_(avx_cast<VectorType>(k.data()), data());
}
template<> Vc_INTRINSIC void Vector<double>::setQnan()
{
data() = _mm256_setallone_pd();
}
template<> Vc_INTRINSIC void Vector<double>::setQnan(MaskArg k)
{
data() = _mm256_or_pd(data(), k.dataD());
}
template<> Vc_INTRINSIC void Vector<float>::setQnan()
{
data() = _mm256_setallone_ps();
}
template<> Vc_INTRINSIC void Vector<float>::setQnan(MaskArg k)
{
data() = _mm256_or_ps(data(), k.data());
}
template<> Vc_INTRINSIC void Vector<sfloat>::setQnan()
{
data() = _mm256_setallone_ps();
}
template<> Vc_INTRINSIC void Vector<sfloat>::setQnan(MaskArg k)
{
data() = _mm256_or_ps(data(), k.data());
}
///////////////////////////////////////////////////////////////////////////////////////////
// stores {{{1
template<typename T> Vc_INTRINSIC void Vector<T>::store(EntryType *mem) const
{
HV::store(mem, data(), Aligned);
}
template<typename T> Vc_INTRINSIC void Vector<T>::store(EntryType *mem, const Mask &mask) const
{
HV::store(mem, data(), avx_cast<VectorType>(mask.data()), Aligned);
}
template<typename T> template<typename A> Vc_INTRINSIC void Vector<T>::store(EntryType *mem, A align) const
{
HV::store(mem, data(), align);
}
template<typename T> template<typename A> Vc_INTRINSIC void Vector<T>::store(EntryType *mem, const Mask &mask, A align) const
{
HV::store(mem, data(), avx_cast<VectorType>(mask.data()), align);
}
///////////////////////////////////////////////////////////////////////////////////////////
// expand/merge 1 float_v <=> 2 double_v XXX rationale? remove it for release? XXX {{{1
template<typename T> Vc_ALWAYS_INLINE Vc_FLATTEN Vector<T>::Vector(const Vector<typename HT::ConcatType> *a)
: d(a[0])
{
}
template<> Vc_ALWAYS_INLINE Vc_FLATTEN Vector<float>::Vector(const Vector<HT::ConcatType> *a)
: d(concat(_mm256_cvtpd_ps(a[0].data()), _mm256_cvtpd_ps(a[1].data())))
{
}
template<> Vc_ALWAYS_INLINE Vc_FLATTEN Vector<short>::Vector(const Vector<HT::ConcatType> *a)
: d(_mm_packs_epi32(lo128(a->data()), hi128(a->data())))
{
}
template<> Vc_ALWAYS_INLINE Vc_FLATTEN Vector<unsigned short>::Vector(const Vector<HT::ConcatType> *a)
: d(_mm_packus_epi32(lo128(a->data()), hi128(a->data())))
{
}
template<typename T> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::expand(Vector<typename HT::ConcatType> *x) const
{
x[0] = *this;
}
template<> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<float>::expand(Vector<HT::ConcatType> *x) const
{
x[0].data() = _mm256_cvtps_pd(lo128(d.v()));
x[1].data() = _mm256_cvtps_pd(hi128(d.v()));
}
template<> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<short>::expand(Vector<HT::ConcatType> *x) const
{
x[0].data() = concat(_mm_cvtepi16_epi32(d.v()),
_mm_cvtepi16_epi32(_mm_unpackhi_epi64(d.v(), d.v())));
}
template<> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned short>::expand(Vector<HT::ConcatType> *x) const
{
x[0].data() = concat(_mm_cvtepu16_epi32(d.v()),
_mm_cvtepu16_epi32(_mm_unpackhi_epi64(d.v(), d.v())));
}
///////////////////////////////////////////////////////////////////////////////////////////
// swizzles {{{1
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE &Vector<T>::abcd() const { return *this; }
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::cdab() const { return Mem::permute<X2, X3, X0, X1>(data()); }
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::badc() const { return Mem::permute<X1, X0, X3, X2>(data()); }
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::aaaa() const { return Mem::permute<X0, X0, X0, X0>(data()); }
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::bbbb() const { return Mem::permute<X1, X1, X1, X1>(data()); }
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::cccc() const { return Mem::permute<X2, X2, X2, X2>(data()); }
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dddd() const { return Mem::permute<X3, X3, X3, X3>(data()); }
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::bcad() const { return Mem::permute<X1, X2, X0, X3>(data()); }
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::bcda() const { return Mem::permute<X1, X2, X3, X0>(data()); }
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dabc() const { return Mem::permute<X3, X0, X1, X2>(data()); }
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::acbd() const { return Mem::permute<X0, X2, X1, X3>(data()); }
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dbca() const { return Mem::permute<X3, X1, X2, X0>(data()); }
template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dcba() const { return Mem::permute<X3, X2, X1, X0>(data()); }
template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::cdab() const { return Mem::shuffle128<X1, X0>(data(), data()); }
template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::badc() const { return Mem::permute<X1, X0, X3, X2>(data()); }
template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::aaaa() const { const double &tmp = d.m(0); return _mm256_broadcast_sd(&tmp); }
template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::bbbb() const { const double &tmp = d.m(1); return _mm256_broadcast_sd(&tmp); }
template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::cccc() const { const double &tmp = d.m(2); return _mm256_broadcast_sd(&tmp); }
template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::dddd() const { const double &tmp = d.m(3); return _mm256_broadcast_sd(&tmp); }
template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::bcad() const { return Mem::shuffle<X1, Y0, X2, Y3>(Mem::shuffle128<X0, X0>(data(), data()), Mem::shuffle128<X1, X1>(data(), data())); }
template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::bcda() const { return Mem::shuffle<X1, Y0, X3, Y2>(data(), Mem::shuffle128<X1, X0>(data(), data())); }
template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::dabc() const { return Mem::shuffle<X1, Y0, X3, Y2>(Mem::shuffle128<X1, X0>(data(), data()), data()); }
template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::acbd() const { return Mem::shuffle<X0, Y0, X3, Y3>(Mem::shuffle128<X0, X0>(data(), data()), Mem::shuffle128<X1, X1>(data(), data())); }
template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::dbca() const { return Mem::shuffle<X1, Y1, X2, Y2>(Mem::shuffle128<X1, X1>(data(), data()), Mem::shuffle128<X0, X0>(data(), data())); }
template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::dcba() const { return cdab().badc(); }
#define VC_SWIZZLES_16BIT_IMPL(T) \
template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::cdab() const { return Mem::permute<X2, X3, X0, X1, X6, X7, X4, X5>(data()); } \
template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::badc() const { return Mem::permute<X1, X0, X3, X2, X5, X4, X7, X6>(data()); } \
template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::aaaa() const { return Mem::permute<X0, X0, X0, X0, X4, X4, X4, X4>(data()); } \
template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::bbbb() const { return Mem::permute<X1, X1, X1, X1, X5, X5, X5, X5>(data()); } \
template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::cccc() const { return Mem::permute<X2, X2, X2, X2, X6, X6, X6, X6>(data()); } \
template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dddd() const { return Mem::permute<X3, X3, X3, X3, X7, X7, X7, X7>(data()); } \
template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::bcad() const { return Mem::permute<X1, X2, X0, X3, X5, X6, X4, X7>(data()); } \
template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::bcda() const { return Mem::permute<X1, X2, X3, X0, X5, X6, X7, X4>(data()); } \
template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dabc() const { return Mem::permute<X3, X0, X1, X2, X7, X4, X5, X6>(data()); } \
template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::acbd() const { return Mem::permute<X0, X2, X1, X3, X4, X6, X5, X7>(data()); } \
template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dbca() const { return Mem::permute<X3, X1, X2, X0, X7, X5, X6, X4>(data()); } \
template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dcba() const { return Mem::permute<X3, X2, X1, X0, X7, X6, X5, X4>(data()); }
VC_SWIZZLES_16BIT_IMPL(short)
VC_SWIZZLES_16BIT_IMPL(unsigned short)
#undef VC_SWIZZLES_16BIT_IMPL
///////////////////////////////////////////////////////////////////////////////////////////
// division {{{1
template<typename T> inline Vector<T> &Vector<T>::operator/=(EntryType x)
{
if (HasVectorDivision) {
return operator/=(Vector<T>(x));
}
for_all_vector_entries(i,
d.m(i) /= x;
);
return *this;
}
template<typename T> template<typename TT> inline Vc_PURE VC_EXACT_TYPE(TT, typename DetermineEntryType<T>::Type, Vector<T>) Vector<T>::operator/(TT x) const
{
if (HasVectorDivision) {
return operator/(Vector<T>(x));
}
Vector<T> r;
for_all_vector_entries(i,
r.d.m(i) = d.m(i) / x;
);
return r;
}
// per default fall back to scalar division
template<typename T> inline Vector<T> &Vector<T>::operator/=(const Vector<T> &x)
{
for_all_vector_entries(i,
d.m(i) /= x.d.m(i);
);
return *this;
}
template<typename T> inline Vector<T> Vc_PURE Vector<T>::operator/(const Vector<T> &x) const
{
Vector<T> r;
for_all_vector_entries(i,
r.d.m(i) = d.m(i) / x.d.m(i);
);
return r;
}
// specialize division on type
static Vc_INTRINSIC m256i Vc_CONST divInt(param256i a, param256i b) {
const m256d lo1 = _mm256_cvtepi32_pd(lo128(a));
const m256d lo2 = _mm256_cvtepi32_pd(lo128(b));
const m256d hi1 = _mm256_cvtepi32_pd(hi128(a));
const m256d hi2 = _mm256_cvtepi32_pd(hi128(b));
return concat(
_mm256_cvttpd_epi32(_mm256_div_pd(lo1, lo2)),
_mm256_cvttpd_epi32(_mm256_div_pd(hi1, hi2))
);
}
template<> inline Vector<int> &Vector<int>::operator/=(const Vector<int> &x)
{
d.v() = divInt(d.v(), x.d.v());
return *this;
}
template<> inline Vector<int> Vc_PURE Vector<int>::operator/(const Vector<int> &x) const
{
return divInt(d.v(), x.d.v());
}
static inline m256i Vc_CONST divUInt(param256i a, param256i b) {
m256d loa = _mm256_cvtepi32_pd(lo128(a));
m256d hia = _mm256_cvtepi32_pd(hi128(a));
m256d lob = _mm256_cvtepi32_pd(lo128(b));
m256d hib = _mm256_cvtepi32_pd(hi128(b));
// if a >= 2^31 then after conversion to double it will contain a negative number (i.e. a-2^32)
// to get the right number back we have to add 2^32 where a >= 2^31
loa = _mm256_add_pd(loa, _mm256_and_pd(_mm256_cmp_pd(loa, _mm256_setzero_pd(), _CMP_LT_OS), _mm256_set1_pd(4294967296.)));
hia = _mm256_add_pd(hia, _mm256_and_pd(_mm256_cmp_pd(hia, _mm256_setzero_pd(), _CMP_LT_OS), _mm256_set1_pd(4294967296.)));
// we don't do the same for b because division by b >= 2^31 should be a seldom corner case and
// we rather want the standard stuff fast
//
// there is one remaining problem: a >= 2^31 and b == 1
// in that case the return value would be 2^31
return avx_cast<m256i>(_mm256_blendv_ps(avx_cast<m256>(concat(
_mm256_cvttpd_epi32(_mm256_div_pd(loa, lob)),
_mm256_cvttpd_epi32(_mm256_div_pd(hia, hib))
)), avx_cast<m256>(a), avx_cast<m256>(concat(
_mm_cmpeq_epi32(lo128(b), _mm_setone_epi32()),
_mm_cmpeq_epi32(hi128(b), _mm_setone_epi32())))));
}
template<> Vc_ALWAYS_INLINE Vector<unsigned int> &Vector<unsigned int>::operator/=(const Vector<unsigned int> &x)
{
d.v() = divUInt(d.v(), x.d.v());
return *this;
}
template<> Vc_ALWAYS_INLINE Vector<unsigned int> Vc_PURE Vector<unsigned int>::operator/(const Vector<unsigned int> &x) const
{
return divUInt(d.v(), x.d.v());
}
template<typename T> static inline m128i Vc_CONST divShort(param128i a, param128i b)
{
const m256 r = _mm256_div_ps(StaticCastHelper<T, float>::cast(a),
StaticCastHelper<T, float>::cast(b));
return StaticCastHelper<float, T>::cast(r);
}
template<> Vc_ALWAYS_INLINE Vector<short> &Vector<short>::operator/=(const Vector<short> &x)
{
d.v() = divShort<short>(d.v(), x.d.v());
return *this;
}
template<> Vc_ALWAYS_INLINE Vector<short> Vc_PURE Vector<short>::operator/(const Vector<short> &x) const
{
return divShort<short>(d.v(), x.d.v());
}
template<> Vc_ALWAYS_INLINE Vector<unsigned short> &Vector<unsigned short>::operator/=(const Vector<unsigned short> &x)
{
d.v() = divShort<unsigned short>(d.v(), x.d.v());
return *this;
}
template<> Vc_ALWAYS_INLINE Vector<unsigned short> Vc_PURE Vector<unsigned short>::operator/(const Vector<unsigned short> &x) const
{
return divShort<unsigned short>(d.v(), x.d.v());
}
template<> Vc_INTRINSIC float_v &float_v::operator/=(const float_v &x)
{
d.v() = _mm256_div_ps(d.v(), x.d.v());
return *this;
}
template<> Vc_INTRINSIC float_v Vc_PURE float_v::operator/(const float_v &x) const
{
return _mm256_div_ps(d.v(), x.d.v());
}
template<> Vc_INTRINSIC sfloat_v &sfloat_v::operator/=(const sfloat_v &x)
{
d.v() = _mm256_div_ps(d.v(), x.d.v());
return *this;
}
template<> Vc_INTRINSIC sfloat_v Vc_PURE sfloat_v::operator/(const sfloat_v &x) const
{
return _mm256_div_ps(d.v(), x.d.v());
}
template<> Vc_INTRINSIC double_v &double_v::operator/=(const double_v &x)
{
d.v() = _mm256_div_pd(d.v(), x.d.v());
return *this;
}
template<> Vc_INTRINSIC double_v Vc_PURE double_v::operator/(const double_v &x) const
{
return _mm256_div_pd(d.v(), x.d.v());
}
///////////////////////////////////////////////////////////////////////////////////////////
// integer ops {{{1
#define OP_IMPL(T, symbol) \
template<> Vc_ALWAYS_INLINE Vector<T> &Vector<T>::operator symbol##=(AsArg x) \
{ \
for_all_vector_entries(i, d.m(i) symbol##= x.d.m(i); ); \
return *this; \
} \
template<> Vc_ALWAYS_INLINE Vc_PURE Vector<T> Vector<T>::operator symbol(AsArg x) const \
{ \
Vector<T> r; \
for_all_vector_entries(i, r.d.m(i) = d.m(i) symbol x.d.m(i); ); \
return r; \
}
OP_IMPL(int, <<)
OP_IMPL(int, >>)
OP_IMPL(unsigned int, <<)
OP_IMPL(unsigned int, >>)
OP_IMPL(short, <<)
OP_IMPL(short, >>)
OP_IMPL(unsigned short, <<)
OP_IMPL(unsigned short, >>)
#undef OP_IMPL
template<typename T> Vc_ALWAYS_INLINE Vector<T> &Vector<T>::operator>>=(int shift) {
d.v() = VectorHelper<T>::shiftRight(d.v(), shift);
return *static_cast<Vector<T> *>(this);
}
template<typename T> Vc_ALWAYS_INLINE Vc_PURE Vector<T> Vector<T>::operator>>(int shift) const {
return VectorHelper<T>::shiftRight(d.v(), shift);
}
template<typename T> Vc_ALWAYS_INLINE Vector<T> &Vector<T>::operator<<=(int shift) {
d.v() = VectorHelper<T>::shiftLeft(d.v(), shift);
return *static_cast<Vector<T> *>(this);
}
template<typename T> Vc_ALWAYS_INLINE Vc_PURE Vector<T> Vector<T>::operator<<(int shift) const {
return VectorHelper<T>::shiftLeft(d.v(), shift);
}
#define OP_IMPL(T, symbol, fun) \
template<> Vc_ALWAYS_INLINE Vector<T> &Vector<T>::operator symbol##=(AsArg x) { d.v() = HV::fun(d.v(), x.d.v()); return *this; } \
template<> Vc_ALWAYS_INLINE Vc_PURE Vector<T> Vector<T>::operator symbol(AsArg x) const { return Vector<T>(HV::fun(d.v(), x.d.v())); }
OP_IMPL(int, &, and_)
OP_IMPL(int, |, or_)
OP_IMPL(int, ^, xor_)
OP_IMPL(unsigned int, &, and_)
OP_IMPL(unsigned int, |, or_)
OP_IMPL(unsigned int, ^, xor_)
OP_IMPL(short, &, and_)
OP_IMPL(short, |, or_)
OP_IMPL(short, ^, xor_)
OP_IMPL(unsigned short, &, and_)
OP_IMPL(unsigned short, |, or_)
OP_IMPL(unsigned short, ^, xor_)
OP_IMPL(float, &, and_)
OP_IMPL(float, |, or_)
OP_IMPL(float, ^, xor_)
OP_IMPL(sfloat, &, and_)
OP_IMPL(sfloat, |, or_)
OP_IMPL(sfloat, ^, xor_)
OP_IMPL(double, &, and_)
OP_IMPL(double, |, or_)
OP_IMPL(double, ^, xor_)
#undef OP_IMPL
// operators {{{1
#include "../common/operators.h"
// isNegative {{{1
template<> Vc_INTRINSIC Vc_PURE float_m float_v::isNegative() const
{
return avx_cast<m256>(_mm256_srai_epi32(avx_cast<m256i>(_mm256_and_ps(_mm256_setsignmask_ps(), d.v())), 31));
}
template<> Vc_INTRINSIC Vc_PURE sfloat_m sfloat_v::isNegative() const
{
return avx_cast<m256>(_mm256_srai_epi32(avx_cast<m256i>(_mm256_and_ps(_mm256_setsignmask_ps(), d.v())), 31));
}
template<> Vc_INTRINSIC Vc_PURE double_m double_v::isNegative() const
{
return Mem::permute<X1, X1, X3, X3>(avx_cast<m256>(
_mm256_srai_epi32(avx_cast<m256i>(_mm256_and_pd(_mm256_setsignmask_pd(), d.v())), 31)
));
}
// gathers {{{1
// Better implementation (hopefully) with _mm256_set_
//X template<typename T> template<typename Index> Vector<T>::Vector(const EntryType *mem, const Index *indexes)
//X {
//X for_all_vector_entries(int i,
//X d.m(i) = mem[indexes[i]];
//X );
//X }
template<typename T> template<typename IndexT> Vc_ALWAYS_INLINE Vector<T>::Vector(const EntryType *mem, const IndexT *indexes)
{
gather(mem, indexes);
}
template<typename T> template<typename IndexT> Vc_ALWAYS_INLINE Vector<T>::Vector(const EntryType *mem, VC_ALIGNED_PARAMETER(Vector<IndexT>) indexes)
{
gather(mem, indexes);
}
template<typename T> template<typename IndexT> Vc_ALWAYS_INLINE Vector<T>::Vector(const EntryType *mem, const IndexT *indexes, MaskArg mask)
: d(HT::zero())
{
gather(mem, indexes, mask);
}
template<typename T> template<typename IndexT> Vc_ALWAYS_INLINE Vector<T>::Vector(const EntryType *mem, VC_ALIGNED_PARAMETER(Vector<IndexT>) indexes, MaskArg mask)
: d(HT::zero())
{
gather(mem, indexes, mask);
}
template<typename T> template<typename S1, typename IT> Vc_ALWAYS_INLINE Vector<T>::Vector(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes)
{
gather(array, member1, indexes);
}
template<typename T> template<typename S1, typename IT> Vc_ALWAYS_INLINE Vector<T>::Vector(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes, MaskArg mask)
: d(HT::zero())
{
gather(array, member1, indexes, mask);
}
template<typename T> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE Vector<T>::Vector(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes)
{
gather(array, member1, member2, indexes);
}
template<typename T> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE Vector<T>::Vector(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes, MaskArg mask)
: d(HT::zero())
{
gather(array, member1, member2, indexes, mask);
}
template<typename T> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE Vector<T>::Vector(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes)
{
gather(array, ptrMember1, outerIndexes, innerIndexes);
}
template<typename T> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE Vector<T>::Vector(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes, MaskArg mask)
: d(HT::zero())
{
gather(array, ptrMember1, outerIndexes, innerIndexes, mask);
}
template<typename T, size_t Size> struct IndexSizeChecker { static void check() {} };
template<typename T, size_t Size> struct IndexSizeChecker<Vector<T>, Size>
{
static void check() {
VC_STATIC_ASSERT(Vector<T>::Size >= Size, IndexVector_must_have_greater_or_equal_number_of_entries);
}
};
template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<double>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes)
{
IndexSizeChecker<Index, Size>::check();
d.v() = _mm256_setr_pd(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]]);
}
template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<float>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes)
{
IndexSizeChecker<Index, Size>::check();
d.v() = _mm256_setr_ps(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]],
mem[indexes[4]], mem[indexes[5]], mem[indexes[6]], mem[indexes[7]]);
}
template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<sfloat>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes)
{
IndexSizeChecker<Index, Size>::check();
d.v() = _mm256_setr_ps(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]],
mem[indexes[4]], mem[indexes[5]], mem[indexes[6]], mem[indexes[7]]);
}
template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<int>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes)
{
IndexSizeChecker<Index, Size>::check();
d.v() = _mm256_setr_epi32(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]],
mem[indexes[4]], mem[indexes[5]], mem[indexes[6]], mem[indexes[7]]);
}
template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned int>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes)
{
IndexSizeChecker<Index, Size>::check();
d.v() = _mm256_setr_epi32(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]],
mem[indexes[4]], mem[indexes[5]], mem[indexes[6]], mem[indexes[7]]);
}
template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<short>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes)
{
IndexSizeChecker<Index, Size>::check();
d.v() = _mm_setr_epi16(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]],
mem[indexes[4]], mem[indexes[5]], mem[indexes[6]], mem[indexes[7]]);
}
template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned short>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes)
{
IndexSizeChecker<Index, Size>::check();
d.v() = _mm_setr_epi16(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]],
mem[indexes[4]], mem[indexes[5]], mem[indexes[6]], mem[indexes[7]]);
}
#ifdef VC_USE_SET_GATHERS
template<typename T> template<typename IT> Vc_ALWAYS_INLINE void Vector<T>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Vector<IT>) indexes, MaskArg mask)
{
IndexSizeChecker<Vector<IT>, Size>::check();
Vector<IT> indexesTmp = indexes;
indexesTmp.setZero(!mask);
(*this)(mask) = Vector<T>(mem, indexesTmp);
}
#endif
#ifdef VC_USE_BSF_GATHERS
#define VC_MASKED_GATHER \
int bits = mask.toInt(); \
while (bits) { \
const int i = _bit_scan_forward(bits); \
bits &= ~(1 << i); /* btr? */ \
d.m(i) = ith_value(i); \
}
#elif defined(VC_USE_POPCNT_BSF_GATHERS)
#define VC_MASKED_GATHER \
unsigned int bits = mask.toInt(); \
unsigned int low, high = 0; \
switch (_mm_popcnt_u32(bits)) { \
case 8: \
high = _bit_scan_reverse(bits); \
d.m(high) = ith_value(high); \
high = (1 << high); \
case 7: \
low = _bit_scan_forward(bits); \
bits ^= high | (1 << low); \
d.m(low) = ith_value(low); \
case 6: \
high = _bit_scan_reverse(bits); \
d.m(high) = ith_value(high); \
high = (1 << high); \
case 5: \
low = _bit_scan_forward(bits); \
bits ^= high | (1 << low); \
d.m(low) = ith_value(low); \
case 4: \
high = _bit_scan_reverse(bits); \
d.m(high) = ith_value(high); \
high = (1 << high); \
case 3: \
low = _bit_scan_forward(bits); \
bits ^= high | (1 << low); \
d.m(low) = ith_value(low); \
case 2: \
high = _bit_scan_reverse(bits); \
d.m(high) = ith_value(high); \
case 1: \
low = _bit_scan_forward(bits); \
d.m(low) = ith_value(low); \
case 0: \
break; \
}
#else
#define VC_MASKED_GATHER \
if (mask.isEmpty()) { \
return; \
} \
for_all_vector_entries(i, \
if (mask[i]) d.m(i) = ith_value(i); \
);
#endif
template<typename T> template<typename Index>
Vc_INTRINSIC void Vector<T>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes, MaskArg mask)
{
IndexSizeChecker<Index, Size>::check();
#define ith_value(_i_) (mem[indexes[_i_]])
VC_MASKED_GATHER
#undef ith_value
}
template<> template<typename S1, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<double>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm256_setr_pd(array[indexes[0]].*(member1), array[indexes[1]].*(member1),
array[indexes[2]].*(member1), array[indexes[3]].*(member1));
}
template<> template<typename S1, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<float>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm256_setr_ps(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1),
array[indexes[3]].*(member1), array[indexes[4]].*(member1), array[indexes[5]].*(member1),
array[indexes[6]].*(member1), array[indexes[7]].*(member1));
}
template<> template<typename S1, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<sfloat>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm256_setr_ps(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1),
array[indexes[3]].*(member1), array[indexes[4]].*(member1), array[indexes[5]].*(member1),
array[indexes[6]].*(member1), array[indexes[7]].*(member1));
}
template<> template<typename S1, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<int>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm256_setr_epi32(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1),
array[indexes[3]].*(member1), array[indexes[4]].*(member1), array[indexes[5]].*(member1),
array[indexes[6]].*(member1), array[indexes[7]].*(member1));
}
template<> template<typename S1, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned int>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm256_setr_epi32(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1),
array[indexes[3]].*(member1), array[indexes[4]].*(member1), array[indexes[5]].*(member1),
array[indexes[6]].*(member1), array[indexes[7]].*(member1));
}
template<> template<typename S1, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<short>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm_setr_epi16(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1),
array[indexes[3]].*(member1), array[indexes[4]].*(member1), array[indexes[5]].*(member1),
array[indexes[6]].*(member1), array[indexes[7]].*(member1));
}
template<> template<typename S1, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned short>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm_setr_epi16(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1),
array[indexes[3]].*(member1), array[indexes[4]].*(member1), array[indexes[5]].*(member1),
array[indexes[6]].*(member1), array[indexes[7]].*(member1));
}
template<typename T> template<typename S1, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes, MaskArg mask)
{
IndexSizeChecker<IT, Size>::check();
#define ith_value(_i_) (array[indexes[_i_]].*(member1))
VC_MASKED_GATHER
#undef ith_value
}
template<> template<typename S1, typename S2, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<double>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm256_setr_pd(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2),
array[indexes[2]].*(member1).*(member2), array[indexes[3]].*(member1).*(member2));
}
template<> template<typename S1, typename S2, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<float>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm256_setr_ps(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2),
array[indexes[3]].*(member1).*(member2), array[indexes[4]].*(member1).*(member2), array[indexes[5]].*(member1).*(member2),
array[indexes[6]].*(member1).*(member2), array[indexes[7]].*(member1).*(member2));
}
template<> template<typename S1, typename S2, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<sfloat>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm256_setr_ps(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2),
array[indexes[3]].*(member1).*(member2), array[indexes[4]].*(member1).*(member2), array[indexes[5]].*(member1).*(member2),
array[indexes[6]].*(member1).*(member2), array[indexes[7]].*(member1).*(member2));
}
template<> template<typename S1, typename S2, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<int>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm256_setr_epi32(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2),
array[indexes[3]].*(member1).*(member2), array[indexes[4]].*(member1).*(member2), array[indexes[5]].*(member1).*(member2),
array[indexes[6]].*(member1).*(member2), array[indexes[7]].*(member1).*(member2));
}
template<> template<typename S1, typename S2, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned int>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm256_setr_epi32(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2),
array[indexes[3]].*(member1).*(member2), array[indexes[4]].*(member1).*(member2), array[indexes[5]].*(member1).*(member2),
array[indexes[6]].*(member1).*(member2), array[indexes[7]].*(member1).*(member2));
}
template<> template<typename S1, typename S2, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<short>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm_setr_epi16(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2),
array[indexes[3]].*(member1).*(member2), array[indexes[4]].*(member1).*(member2), array[indexes[5]].*(member1).*(member2),
array[indexes[6]].*(member1).*(member2), array[indexes[7]].*(member1).*(member2));
}
template<> template<typename S1, typename S2, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned short>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes)
{
IndexSizeChecker<IT, Size>::check();
d.v() = _mm_setr_epi16(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2),
array[indexes[3]].*(member1).*(member2), array[indexes[4]].*(member1).*(member2), array[indexes[5]].*(member1).*(member2),
array[indexes[6]].*(member1).*(member2), array[indexes[7]].*(member1).*(member2));
}
template<typename T> template<typename S1, typename S2, typename IT>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes, MaskArg mask)
{
IndexSizeChecker<IT, Size>::check();
#define ith_value(_i_) (array[indexes[_i_]].*(member1).*(member2))
VC_MASKED_GATHER
#undef ith_value
}
template<> template<typename S1, typename IT1, typename IT2>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<double>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes)
{
IndexSizeChecker<IT1, Size>::check();
IndexSizeChecker<IT2, Size>::check();
d.v() = _mm256_setr_pd((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]],
(array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]]);
}
template<> template<typename S1, typename IT1, typename IT2>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<float>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes)
{
IndexSizeChecker<IT1, Size>::check();
IndexSizeChecker<IT2, Size>::check();
d.v() = _mm256_setr_ps((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]],
(array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]],
(array[outerIndexes[4]].*(ptrMember1))[innerIndexes[4]], (array[outerIndexes[5]].*(ptrMember1))[innerIndexes[5]],
(array[outerIndexes[6]].*(ptrMember1))[innerIndexes[6]], (array[outerIndexes[7]].*(ptrMember1))[innerIndexes[7]]);
}
template<> template<typename S1, typename IT1, typename IT2>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<sfloat>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes)
{
IndexSizeChecker<IT1, Size>::check();
IndexSizeChecker<IT2, Size>::check();
d.v() = _mm256_setr_ps((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]],
(array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]],
(array[outerIndexes[4]].*(ptrMember1))[innerIndexes[4]], (array[outerIndexes[5]].*(ptrMember1))[innerIndexes[5]],
(array[outerIndexes[6]].*(ptrMember1))[innerIndexes[6]], (array[outerIndexes[7]].*(ptrMember1))[innerIndexes[7]]);
}
template<> template<typename S1, typename IT1, typename IT2>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<int>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes)
{
IndexSizeChecker<IT1, Size>::check();
IndexSizeChecker<IT2, Size>::check();
d.v() = _mm256_setr_epi32((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]],
(array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]],
(array[outerIndexes[4]].*(ptrMember1))[innerIndexes[4]], (array[outerIndexes[5]].*(ptrMember1))[innerIndexes[5]],
(array[outerIndexes[6]].*(ptrMember1))[innerIndexes[6]], (array[outerIndexes[7]].*(ptrMember1))[innerIndexes[7]]);
}
template<> template<typename S1, typename IT1, typename IT2>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned int>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes)
{
IndexSizeChecker<IT1, Size>::check();
IndexSizeChecker<IT2, Size>::check();
d.v() = _mm256_setr_epi32((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]],
(array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]],
(array[outerIndexes[4]].*(ptrMember1))[innerIndexes[4]], (array[outerIndexes[5]].*(ptrMember1))[innerIndexes[5]],
(array[outerIndexes[6]].*(ptrMember1))[innerIndexes[6]], (array[outerIndexes[7]].*(ptrMember1))[innerIndexes[7]]);
}
template<> template<typename S1, typename IT1, typename IT2>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<short>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes)
{
IndexSizeChecker<IT1, Size>::check();
IndexSizeChecker<IT2, Size>::check();
d.v() = _mm_setr_epi16((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]],
(array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]],
(array[outerIndexes[4]].*(ptrMember1))[innerIndexes[4]], (array[outerIndexes[5]].*(ptrMember1))[innerIndexes[5]],
(array[outerIndexes[6]].*(ptrMember1))[innerIndexes[6]], (array[outerIndexes[7]].*(ptrMember1))[innerIndexes[7]]);
}
template<> template<typename S1, typename IT1, typename IT2>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned short>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes)
{
IndexSizeChecker<IT1, Size>::check();
IndexSizeChecker<IT2, Size>::check();
d.v() = _mm_setr_epi16((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]],
(array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]],
(array[outerIndexes[4]].*(ptrMember1))[innerIndexes[4]], (array[outerIndexes[5]].*(ptrMember1))[innerIndexes[5]],
(array[outerIndexes[6]].*(ptrMember1))[innerIndexes[6]], (array[outerIndexes[7]].*(ptrMember1))[innerIndexes[7]]);
}
template<typename T> template<typename S1, typename IT1, typename IT2>
Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes, MaskArg mask)
{
IndexSizeChecker<IT1, Size>::check();
IndexSizeChecker<IT2, Size>::check();
#define ith_value(_i_) (array[outerIndexes[_i_]].*(ptrMember1))[innerIndexes[_i_]]
VC_MASKED_GATHER
#undef ith_value
}
#undef VC_MASKED_GATHER
#ifdef VC_USE_BSF_SCATTERS
#define VC_MASKED_SCATTER \
int bits = mask.toInt(); \
while (bits) { \
const int i = _bit_scan_forward(bits); \
bits ^= (1 << i); /* btr? */ \
ith_value(i) = d.m(i); \
}
#elif defined(VC_USE_POPCNT_BSF_SCATTERS)
#define VC_MASKED_SCATTER \
unsigned int bits = mask.toInt(); \
unsigned int low, high = 0; \
switch (_mm_popcnt_u32(bits)) { \
case 8: \
high = _bit_scan_reverse(bits); \
ith_value(high) = d.m(high); \
high = (1 << high); \
case 7: \
low = _bit_scan_forward(bits); \
bits ^= high | (1 << low); \
ith_value(low) = d.m(low); \
case 6: \
high = _bit_scan_reverse(bits); \
ith_value(high) = d.m(high); \
high = (1 << high); \
case 5: \
low = _bit_scan_forward(bits); \
bits ^= high | (1 << low); \
ith_value(low) = d.m(low); \
case 4: \
high = _bit_scan_reverse(bits); \
ith_value(high) = d.m(high); \
high = (1 << high); \
case 3: \
low = _bit_scan_forward(bits); \
bits ^= high | (1 << low); \
ith_value(low) = d.m(low); \
case 2: \
high = _bit_scan_reverse(bits); \
ith_value(high) = d.m(high); \
case 1: \
low = _bit_scan_forward(bits); \
ith_value(low) = d.m(low); \
case 0: \
break; \
}
#else
#define VC_MASKED_SCATTER \
if (mask.isEmpty()) { \
return; \
} \
for_all_vector_entries(i, \
if (mask[i]) ith_value(i) = d.m(i); \
);
#endif
template<typename T> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) const
{
for_all_vector_entries(i,
mem[indexes[i]] = d.m(i);
);
}
#if defined(VC_MSVC) && VC_MSVC >= 170000000
// MSVC miscompiles the store mem[indexes[1]] = d.m(1) for T = (u)short
template<> template<typename Index> Vc_ALWAYS_INLINE void short_v::scatter(EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) const
{
const unsigned int tmp = d.v()._d.m128i_u32[0];
mem[indexes[0]] = tmp & 0xffff;
mem[indexes[1]] = tmp >> 16;
mem[indexes[2]] = _mm_extract_epi16(d.v(), 2);
mem[indexes[3]] = _mm_extract_epi16(d.v(), 3);
mem[indexes[4]] = _mm_extract_epi16(d.v(), 4);
mem[indexes[5]] = _mm_extract_epi16(d.v(), 5);
mem[indexes[6]] = _mm_extract_epi16(d.v(), 6);
mem[indexes[7]] = _mm_extract_epi16(d.v(), 7);
}
template<> template<typename Index> Vc_ALWAYS_INLINE void ushort_v::scatter(EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) const
{
const unsigned int tmp = d.v()._d.m128i_u32[0];
mem[indexes[0]] = tmp & 0xffff;
mem[indexes[1]] = tmp >> 16;
mem[indexes[2]] = _mm_extract_epi16(d.v(), 2);
mem[indexes[3]] = _mm_extract_epi16(d.v(), 3);
mem[indexes[4]] = _mm_extract_epi16(d.v(), 4);
mem[indexes[5]] = _mm_extract_epi16(d.v(), 5);
mem[indexes[6]] = _mm_extract_epi16(d.v(), 6);
mem[indexes[7]] = _mm_extract_epi16(d.v(), 7);
}
#endif
template<typename T> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes, MaskArg mask) const
{
#define ith_value(_i_) mem[indexes[_i_]]
VC_MASKED_SCATTER
#undef ith_value
}
template<typename T> template<typename S1, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(S1 *array, EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes) const
{
for_all_vector_entries(i,
array[indexes[i]].*(member1) = d.m(i);
);
}
template<typename T> template<typename S1, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(S1 *array, EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes, MaskArg mask) const
{
#define ith_value(_i_) array[indexes[_i_]].*(member1)
VC_MASKED_SCATTER
#undef ith_value
}
template<typename T> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(S1 *array, S2 S1::* member1, EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes) const
{
for_all_vector_entries(i,
array[indexes[i]].*(member1).*(member2) = d.m(i);
);
}
template<typename T> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(S1 *array, S2 S1::* member1, EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes, MaskArg mask) const
{
#define ith_value(_i_) array[indexes[_i_]].*(member1).*(member2)
VC_MASKED_SCATTER
#undef ith_value
}
template<typename T> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(S1 *array, EntryType *S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes) const
{
for_all_vector_entries(i,
(array[innerIndexes[i]].*(ptrMember1))[outerIndexes[i]] = d.m(i);
);
}
template<typename T> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(S1 *array, EntryType *S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes, MaskArg mask) const
{
#define ith_value(_i_) (array[outerIndexes[_i_]].*(ptrMember1))[innerIndexes[_i_]]
VC_MASKED_SCATTER
#undef ith_value
}
///////////////////////////////////////////////////////////////////////////////////////////
// operator- {{{1
template<> Vc_ALWAYS_INLINE Vector<double> Vc_PURE Vc_FLATTEN Vector<double>::operator-() const
{
return _mm256_xor_pd(d.v(), _mm256_setsignmask_pd());
}
template<> Vc_ALWAYS_INLINE Vector<float> Vc_PURE Vc_FLATTEN Vector<float>::operator-() const
{
return _mm256_xor_ps(d.v(), _mm256_setsignmask_ps());
}
template<> Vc_ALWAYS_INLINE Vector<sfloat> Vc_PURE Vc_FLATTEN Vector<sfloat>::operator-() const
{
return _mm256_xor_ps(d.v(), _mm256_setsignmask_ps());
}
template<> Vc_ALWAYS_INLINE Vector<int> Vc_PURE Vc_FLATTEN Vector<int>::operator-() const
{
return _mm256_sign_epi32(d.v(), _mm256_setallone_si256());
}
template<> Vc_ALWAYS_INLINE Vector<int> Vc_PURE Vc_FLATTEN Vector<unsigned int>::operator-() const
{
return _mm256_sign_epi32(d.v(), _mm256_setallone_si256());
}
template<> Vc_ALWAYS_INLINE Vector<short> Vc_PURE Vc_FLATTEN Vector<short>::operator-() const
{
return _mm_sign_epi16(d.v(), _mm_setallone_si128());
}
template<> Vc_ALWAYS_INLINE Vector<short> Vc_PURE Vc_FLATTEN Vector<unsigned short>::operator-() const
{
return _mm_sign_epi16(d.v(), _mm_setallone_si128());
}
///////////////////////////////////////////////////////////////////////////////////////////
// horizontal ops {{{1
template<typename T> Vc_ALWAYS_INLINE typename Vector<T>::EntryType Vector<T>::min(MaskArg m) const
{
Vector<T> tmp = std::numeric_limits<Vector<T> >::max();
tmp(m) = *this;
return tmp.min();
}
template<typename T> Vc_ALWAYS_INLINE typename Vector<T>::EntryType Vector<T>::max(MaskArg m) const
{
Vector<T> tmp = std::numeric_limits<Vector<T> >::min();
tmp(m) = *this;
return tmp.max();
}
template<typename T> Vc_ALWAYS_INLINE typename Vector<T>::EntryType Vector<T>::product(MaskArg m) const
{
Vector<T> tmp(VectorSpecialInitializerOne::One);
tmp(m) = *this;
return tmp.product();
}
template<typename T> Vc_ALWAYS_INLINE typename Vector<T>::EntryType Vector<T>::sum(MaskArg m) const
{
Vector<T> tmp(VectorSpecialInitializerZero::Zero);
tmp(m) = *this;
return tmp.sum();
}//}}}
// copySign {{{1
template<> Vc_INTRINSIC Vector<float> Vector<float>::copySign(Vector<float>::AsArg reference) const
{
return _mm256_or_ps(
_mm256_and_ps(reference.d.v(), _mm256_setsignmask_ps()),
_mm256_and_ps(d.v(), _mm256_setabsmask_ps())
);
}
template<> Vc_INTRINSIC Vector<sfloat> Vector<sfloat>::copySign(Vector<sfloat>::AsArg reference) const
{
return _mm256_or_ps(
_mm256_and_ps(reference.d.v(), _mm256_setsignmask_ps()),
_mm256_and_ps(d.v(), _mm256_setabsmask_ps())
);
}
template<> Vc_INTRINSIC Vector<double> Vector<double>::copySign(Vector<double>::AsArg reference) const
{
return _mm256_or_pd(
_mm256_and_pd(reference.d.v(), _mm256_setsignmask_pd()),
_mm256_and_pd(d.v(), _mm256_setabsmask_pd())
);
}//}}}1
// exponent {{{1
template<> Vc_INTRINSIC Vector<float> Vector<float>::exponent() const
{
VC_ASSERT((*this >= 0.f).isFull());
return Internal::exponent(d.v());
}
template<> Vc_INTRINSIC Vector<sfloat> Vector<sfloat>::exponent() const
{
VC_ASSERT((*this >= 0.f).isFull());
return Internal::exponent(d.v());
}
template<> Vc_INTRINSIC Vector<double> Vector<double>::exponent() const
{
VC_ASSERT((*this >= 0.).isFull());
return Internal::exponent(d.v());
}
// }}}1
// Random {{{1
static Vc_ALWAYS_INLINE void _doRandomStep(Vector<unsigned int> &state0,
Vector<unsigned int> &state1)
{
state0.load(&Vc::RandomState[0]);
state1.load(&Vc::RandomState[uint_v::Size]);
(state1 * 0xdeece66du + 11).store(&Vc::RandomState[uint_v::Size]);
uint_v(_mm256_xor_si256((state0 * 0xdeece66du + 11).data(), _mm256_srli_epi32(state1.data(), 16))).store(&Vc::RandomState[0]);
}
template<typename T> Vc_ALWAYS_INLINE Vector<T> Vector<T>::Random()
{
Vector<unsigned int> state0, state1;
_doRandomStep(state0, state1);
return state0.reinterpretCast<Vector<T> >();
}
template<> Vc_ALWAYS_INLINE Vector<float> Vector<float>::Random()
{
Vector<unsigned int> state0, state1;
_doRandomStep(state0, state1);
return HT::sub(HV::or_(_cast(_mm256_srli_epi32(state0.data(), 2)), HT::one()), HT::one());
}
template<> Vc_ALWAYS_INLINE Vector<sfloat> Vector<sfloat>::Random()
{
Vector<unsigned int> state0, state1;
_doRandomStep(state0, state1);
return HT::sub(HV::or_(_cast(_mm256_srli_epi32(state0.data(), 2)), HT::one()), HT::one());
}
template<> Vc_ALWAYS_INLINE Vector<double> Vector<double>::Random()
{
const m256i state = VectorHelper<m256i>::load(&Vc::RandomState[0], Vc::Aligned);
for (size_t k = 0; k < 8; k += 2) {
typedef unsigned long long uint64 Vc_MAY_ALIAS;
const uint64 stateX = *reinterpret_cast<const uint64 *>(&Vc::RandomState[k]);
*reinterpret_cast<uint64 *>(&Vc::RandomState[k]) = (stateX * 0x5deece66dull + 11);
}
return (Vector<double>(_cast(_mm256_srli_epi64(state, 12))) | One()) - One();
}
// }}}1
// shifted / rotated {{{1
template<size_t SIMDWidth, size_t Size, typename VectorType, typename EntryType> struct VectorShift;
template<> struct VectorShift<32, 4, m256d, double>
{
static Vc_INTRINSIC m256d shifted(param256d v, int amount)
{
switch (amount) {
case 0: return v;
case 1: return avx_cast<m256d>(_mm256_srli_si256(avx_cast<m256i>(v), 1 * sizeof(double)));
case 2: return avx_cast<m256d>(_mm256_srli_si256(avx_cast<m256i>(v), 2 * sizeof(double)));
case 3: return avx_cast<m256d>(_mm256_srli_si256(avx_cast<m256i>(v), 3 * sizeof(double)));
case -1: return avx_cast<m256d>(_mm256_slli_si256(avx_cast<m256i>(v), 1 * sizeof(double)));
case -2: return avx_cast<m256d>(_mm256_slli_si256(avx_cast<m256i>(v), 2 * sizeof(double)));
case -3: return avx_cast<m256d>(_mm256_slli_si256(avx_cast<m256i>(v), 3 * sizeof(double)));
}
return _mm256_setzero_pd();
}
};
template<typename VectorType, typename EntryType> struct VectorShift<32, 8, VectorType, EntryType>
{
typedef typename SseVectorType<VectorType>::Type SmallV;
static Vc_INTRINSIC VectorType shifted(VC_ALIGNED_PARAMETER(VectorType) v, int amount)
{
switch (amount) {
case 0: return v;
case 1: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 1 * sizeof(EntryType)));
case 2: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 2 * sizeof(EntryType)));
case 3: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 3 * sizeof(EntryType)));
case 4: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 4 * sizeof(EntryType)));
case 5: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 5 * sizeof(EntryType)));
case 6: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 6 * sizeof(EntryType)));
case 7: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 7 * sizeof(EntryType)));
case -1: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 1 * sizeof(EntryType)));
case -2: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 2 * sizeof(EntryType)));
case -3: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 3 * sizeof(EntryType)));
case -4: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 4 * sizeof(EntryType)));
case -5: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 5 * sizeof(EntryType)));
case -6: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 6 * sizeof(EntryType)));
case -7: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 7 * sizeof(EntryType)));
}
return avx_cast<VectorType>(_mm256_setzero_ps());
}
};
template<typename VectorType, typename EntryType> struct VectorShift<16, 8, VectorType, EntryType>
{
enum {
EntryTypeSizeof = sizeof(EntryType)
};
static Vc_INTRINSIC VectorType shifted(VC_ALIGNED_PARAMETER(VectorType) v, int amount)
{
switch (amount) {
case 0: return v;
case 1: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 1 * EntryTypeSizeof));
case 2: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 2 * EntryTypeSizeof));
case 3: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 3 * EntryTypeSizeof));
case 4: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 4 * EntryTypeSizeof));
case 5: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 5 * EntryTypeSizeof));
case 6: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 6 * EntryTypeSizeof));
case 7: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 7 * EntryTypeSizeof));
case -1: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 1 * EntryTypeSizeof));
case -2: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 2 * EntryTypeSizeof));
case -3: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 3 * EntryTypeSizeof));
case -4: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 4 * EntryTypeSizeof));
case -5: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 5 * EntryTypeSizeof));
case -6: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 6 * EntryTypeSizeof));
case -7: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 7 * EntryTypeSizeof));
}
return _mm_setzero_si128();
}
};
template<typename T> Vc_INTRINSIC Vector<T> Vector<T>::shifted(int amount) const
{
return VectorShift<sizeof(VectorType), Size, VectorType, EntryType>::shifted(d.v(), amount);
}
template<size_t SIMDWidth, size_t Size, typename VectorType, typename EntryType> struct VectorRotate;
template<typename VectorType, typename EntryType> struct VectorRotate<32, 4, VectorType, EntryType>
{
typedef typename SseVectorType<VectorType>::Type SmallV;
enum {
EntryTypeSizeof = sizeof(EntryType)
};
static Vc_INTRINSIC VectorType rotated(VC_ALIGNED_PARAMETER(VectorType) v, int amount)
{
const m128i vLo = avx_cast<m128i>(lo128(v));
const m128i vHi = avx_cast<m128i>(hi128(v));
switch (static_cast<unsigned int>(amount) % 4) {
case 0: return v;
case 1: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 1 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 1 * EntryTypeSizeof)));
case 2: return Mem::permute128<X1, X0>(v);
case 3: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 1 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 1 * EntryTypeSizeof)));
}
return _mm256_setzero_pd();
}
};
template<typename VectorType, typename EntryType> struct VectorRotate<32, 8, VectorType, EntryType>
{
typedef typename SseVectorType<VectorType>::Type SmallV;
enum {
EntryTypeSizeof = sizeof(EntryType)
};
static Vc_INTRINSIC VectorType rotated(VC_ALIGNED_PARAMETER(VectorType) v, int amount)
{
const m128i vLo = avx_cast<m128i>(lo128(v));
const m128i vHi = avx_cast<m128i>(hi128(v));
switch (static_cast<unsigned int>(amount) % 8) {
case 0: return v;
case 1: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 1 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 1 * EntryTypeSizeof)));
case 2: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 2 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 2 * EntryTypeSizeof)));
case 3: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 3 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 3 * EntryTypeSizeof)));
case 4: return Mem::permute128<X1, X0>(v);
case 5: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 1 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 1 * EntryTypeSizeof)));
case 6: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 2 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 2 * EntryTypeSizeof)));
case 7: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 3 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 3 * EntryTypeSizeof)));
}
return avx_cast<VectorType>(_mm256_setzero_ps());
}
};
template<typename VectorType, typename EntryType> struct VectorRotate<16, 8, VectorType, EntryType>
{
enum {
EntryTypeSizeof = sizeof(EntryType)
};
static Vc_INTRINSIC VectorType rotated(VC_ALIGNED_PARAMETER(VectorType) v, int amount)
{
switch (static_cast<unsigned int>(amount) % 8) {
case 0: return v;
case 1: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 1 * EntryTypeSizeof));
case 2: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 2 * EntryTypeSizeof));
case 3: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 3 * EntryTypeSizeof));
case 4: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 4 * EntryTypeSizeof));
case 5: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 5 * EntryTypeSizeof));
case 6: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 6 * EntryTypeSizeof));
case 7: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 7 * EntryTypeSizeof));
}
return _mm_setzero_si128();
}
};
template<typename T> Vc_INTRINSIC Vector<T> Vector<T>::rotated(int amount) const
{
return VectorRotate<sizeof(VectorType), Size, VectorType, EntryType>::rotated(d.v(), amount);
/*
const m128i v0 = avx_cast<m128i>(d.v()[0]);
const m128i v1 = avx_cast<m128i>(d.v()[1]);
switch (static_cast<unsigned int>(amount) % Size) {
case 0: return *this;
case 1: return concat(avx_cast<m128>(_mm_alignr_epi8(v1, v0, 1 * sizeof(EntryType))), avx_cast<m128>(_mm_alignr_epi8(v0, v1, 1 * sizeof(EntryType))));
case 2: return concat(avx_cast<m128>(_mm_alignr_epi8(v1, v0, 2 * sizeof(EntryType))), avx_cast<m128>(_mm_alignr_epi8(v0, v1, 2 * sizeof(EntryType))));
case 3: return concat(avx_cast<m128>(_mm_alignr_epi8(v1, v0, 3 * sizeof(EntryType))), avx_cast<m128>(_mm_alignr_epi8(v0, v1, 3 * sizeof(EntryType))));
case 4: return concat(d.v()[1], d.v()[0]);
case 5: return concat(avx_cast<m128>(_mm_alignr_epi8(v0, v1, 1 * sizeof(EntryType))), avx_cast<m128>(_mm_alignr_epi8(v1, v0, 1 * sizeof(EntryType))));
case 6: return concat(avx_cast<m128>(_mm_alignr_epi8(v0, v1, 2 * sizeof(EntryType))), avx_cast<m128>(_mm_alignr_epi8(v1, v0, 2 * sizeof(EntryType))));
case 7: return concat(avx_cast<m128>(_mm_alignr_epi8(v0, v1, 3 * sizeof(EntryType))), avx_cast<m128>(_mm_alignr_epi8(v1, v0, 3 * sizeof(EntryType))));
}
*/
}
// }}}1
} // namespace AVX
} // namespace Vc
} // namespace AliRoot
#include "undomacros.h"
// vim: foldmethod=marker
| 50.981521
| 262
| 0.656634
|
AllaMaevskaya
|
626f7e41d53914c6d7a2d34755b67e028b8fe0fb
| 637
|
cpp
|
C++
|
oop_ex41.cpp
|
85105/HW
|
2161a1a7ac1082a85454672d359c00f2d42ef21f
|
[
"MIT"
] | null | null | null |
oop_ex41.cpp
|
85105/HW
|
2161a1a7ac1082a85454672d359c00f2d42ef21f
|
[
"MIT"
] | null | null | null |
oop_ex41.cpp
|
85105/HW
|
2161a1a7ac1082a85454672d359c00f2d42ef21f
|
[
"MIT"
] | null | null | null |
/*
oop_ex41.cpp
accessing data members through pointer
*/
#include <iostream>
#include <string>
using namespace std;
struct User
{
string name;
int age;
int tel;
};
void main()
{
User userObject;
User* userPtr = &userObject;
//User* userPtr = new User();
userPtr->name = "Micheal";
userPtr->age = 20;
userPtr->tel = 1234567;
cout << " name | age | tel" << endl;
cout << " userObject: " << userPtr->name << " " << userPtr->age << " " << userPtr->tel << endl << endl;;
cout << " userObject: " << (*userPtr).name << " " << (*userPtr).age << " " << (*userPtr).tel << endl << endl;;
system("pause");
}
| 18.2
| 113
| 0.572998
|
85105
|
62708b59e721ebda2cdf84c9034931cf94c8c8d4
| 612
|
hpp
|
C++
|
include/search/Tokenize.hpp
|
ibanic/search
|
9e7da36bb8512dc9bfc1e65d12aae3406659e318
|
[
"MIT"
] | null | null | null |
include/search/Tokenize.hpp
|
ibanic/search
|
9e7da36bb8512dc9bfc1e65d12aae3406659e318
|
[
"MIT"
] | null | null | null |
include/search/Tokenize.hpp
|
ibanic/search
|
9e7da36bb8512dc9bfc1e65d12aae3406659e318
|
[
"MIT"
] | null | null | null |
//
// Tokenize.hpp
//
// Created by Ignac Banic on 31/12/19.
// Copyright © 2019 Ignac Banic. All rights reserved.
//
#pragma once
#include <string>
#include <vector>
namespace Search {
uint8_t charLen(char ch);
std::vector<std::string> tokenize(std::string_view txt);
std::vector<std::string> tokenize(const std::string& txt);
std::string joinTokens(const std::vector<std::string>& tokens);
std::vector<std::string> splitTokens(std::string_view txt);
bool tokensOverlap(std::string_view all, std::string_view search);
size_t numTokensOverlap(const std::string& all, const std::string& search);
}
| 26.608696
| 76
| 0.722222
|
ibanic
|
6270b83de03cebb175575dca493d1479ad360a7a
| 32,668
|
cpp
|
C++
|
src/OpcUaStackServer/ServiceSet/Session.cpp
|
gianricardo/OpcUaStack
|
ccdef574175ffe8b7e82b886abc5e5403968b280
|
[
"Apache-2.0"
] | 108
|
2018-10-08T17:03:32.000Z
|
2022-03-21T00:52:26.000Z
|
src/OpcUaStackServer/ServiceSet/Session.cpp
|
gianricardo/OpcUaStack
|
ccdef574175ffe8b7e82b886abc5e5403968b280
|
[
"Apache-2.0"
] | 287
|
2018-09-18T14:59:12.000Z
|
2022-01-13T12:28:23.000Z
|
src/OpcUaStackServer/ServiceSet/Session.cpp
|
gianricardo/OpcUaStack
|
ccdef574175ffe8b7e82b886abc5e5403968b280
|
[
"Apache-2.0"
] | 32
|
2018-10-19T14:35:03.000Z
|
2021-11-12T09:36:46.000Z
|
/*
Copyright 2017-2019 Kai Huebl (kai@huebl-sgh.de)
Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser
Datei nur in Übereinstimmung mit der Lizenz erlaubt.
Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0.
Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart,
erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE
GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend.
Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen
im Rahmen der Lizenz finden Sie in der Lizenz.
Autor: Kai Huebl (kai@huebl-sgh.de)
*/
#include "OpcUaStackServer/ServiceSet/Session.h"
#include "OpcUaStackCore/BuildInTypes/OpcUaIdentifier.h"
#include "OpcUaStackCore/Base/Log.h"
#include "OpcUaStackCore/Base/MemoryBuffer.h"
#include "OpcUaStackCore/Base/Utility.h"
#include "OpcUaStackCore/SecureChannel/RequestHeader.h"
#include "OpcUaStackCore/ServiceSet/CreateSessionRequest.h"
#include "OpcUaStackCore/ServiceSet/CreateSessionResponse.h"
#include "OpcUaStackCore/ServiceSet/CloseSessionRequest.h"
#include "OpcUaStackCore/ServiceSet/CloseSessionResponse.h"
#include "OpcUaStackCore/ServiceSet/CancelRequest.h"
#include "OpcUaStackCore/ServiceSet/CancelResponse.h"
#include "OpcUaStackCore/ServiceSet/ActivateSessionResponse.h"
#include "OpcUaStackCore/Application/ApplicationAuthenticationContext.h"
#include "OpcUaStackCore/Application/ApplicationCloseSessionContext.h"
#include "OpcUaStackCore/ServiceSet/AnonymousIdentityToken.h"
#include "OpcUaStackCore/ServiceSet/UserNameIdentityToken.h"
#include "OpcUaStackCore/ServiceSet/IssuedIdentityToken.h"
#include "OpcUaStackCore/ServiceSet/X509IdentityToken.h"
using namespace OpcUaStackCore;
namespace OpcUaStackServer
{
boost::mutex Session::mutex_;
OpcUaUInt32 Session::uniqueSessionId_ = 0;
OpcUaUInt32 Session::uniqueAuthenticationToken_ = 0;
OpcUaUInt32
Session::getUniqueSessionId(void)
{
boost::mutex::scoped_lock g(mutex_);
uniqueSessionId_++;
return uniqueSessionId_;
}
OpcUaUInt32
Session::getUniqueAuthenticationToken(void)
{
boost::mutex::scoped_lock g(mutex_);
uniqueAuthenticationToken_++;
return uniqueAuthenticationToken_;
}
Session::Session(void)
: Component()
, forwardGlobalSync_()
, sessionIf_(nullptr)
, sessionState_(SessionState_Close)
, sessionId_(getUniqueSessionId())
, authenticationToken_(getUniqueAuthenticationToken())
, applicationCertificate_()
, endpointDescriptionArray_()
, endpointDescription_()
, userContext_()
, clientCertificate_()
{
Log(Info, "session construct")
.parameter("SessionId", sessionId_)
.parameter("AuthenticationToken", authenticationToken_);
componentName("Session");
}
Session::~Session(void)
{
}
void
Session::createServerNonce(void)
{
for (uint32_t idx=0; idx<32; idx++) {
serverNonce_[idx] = (rand() / 256);
}
}
void
Session::applicationCertificate(ApplicationCertificate::SPtr& applicationCertificate)
{
applicationCertificate_ = applicationCertificate;
}
void
Session::cryptoManager(CryptoManager::SPtr& cryptoManager)
{
cryptoManager_ = cryptoManager;
}
void
Session::transactionManager(TransactionManager::SPtr transactionManagerSPtr)
{
transactionManagerSPtr_ = transactionManagerSPtr;
}
void
Session::forwardGlobalSync(ForwardGlobalSync::SPtr& forwardGlobalSync)
{
forwardGlobalSync_ = forwardGlobalSync;
}
void
Session::sessionIf(SessionIf* sessionIf)
{
sessionIf_ = sessionIf;
}
OpcUaUInt32
Session::sessionId(void)
{
return sessionId_;
}
OpcUaUInt32
Session::authenticationToken(void)
{
return authenticationToken_;
}
void
Session::endpointDescriptionArray(EndpointDescriptionArray::SPtr& endpointDescriptionArray)
{
endpointDescriptionArray_ = endpointDescriptionArray;
}
void
Session::endpointDescription(EndpointDescription::SPtr& endpointDescription)
{
endpointDescription_ = endpointDescription;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// authentication
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
OpcUaStatusCode
Session::authentication(ActivateSessionRequest& activateSessionRequest)
{
userContext_.reset();
if (forwardGlobalSync_.get() == nullptr) {
// no authentication is activated
return Success;
}
if (!forwardGlobalSync_->authenticationService().isCallback()) {
// no authentication is activated
return Success;
}
if (activateSessionRequest.userIdentityToken().get() == nullptr) {
// user identity token is invalid
Log(Error, "authentication error, because user identity token is invalid");
return BadIdentityTokenInvalid;
}
else {
ExtensibleParameter::SPtr parameter = activateSessionRequest.userIdentityToken();
if (!parameter->exist()) {
// user identity token is invalid
Log(Error, "authentication error, because user identity token not exist");
return BadIdentityTokenInvalid;
}
else {
OpcUaNodeId typeId = parameter->parameterTypeId();
if (typeId == OpcUaNodeId(OpcUaId_AnonymousIdentityToken_Encoding_DefaultBinary)) {
return authenticationAnonymous(activateSessionRequest, parameter);
}
else if (typeId == OpcUaNodeId(OpcUaId_UserNameIdentityToken_Encoding_DefaultBinary)) {
return authenticationUserName(activateSessionRequest, parameter);
}
else if (typeId == OpcUaId_X509IdentityToken_Encoding_DefaultBinary) {
return authenticationX509(activateSessionRequest, parameter);
}
else if (typeId == OpcUaId_IssuedIdentityToken_Encoding_DefaultBinary) {
return authenticationIssued(activateSessionRequest, parameter);
}
else {
// user identity token is invalid
Log(Error, "authentication error, because unknown authentication type")
.parameter("AuthenticationType", typeId);
return BadIdentityTokenInvalid;
}
}
}
return Success;
}
OpcUaStatusCode
Session::authenticationCloseSession(void)
{
ApplicationCloseSessionContext context;
context.sessionId_ = sessionId_;
context.statusCode_ = Success;
context.userContext_ = userContext_;
if (forwardGlobalSync_->closeSessionService().isCallback()) {
forwardGlobalSync_->closeSessionService().callback()(&context);
}
userContext_.reset();
return context.statusCode_;
}
OpcUaStatusCode
Session::authenticationAnonymous(ActivateSessionRequest& activateSessionRequest, ExtensibleParameter::SPtr& parameter)
{
OpcUaStatusCode statusCode;
Log(Debug, "Session::authenticationAnonymous");
AnonymousIdentityToken::SPtr token = parameter->parameter<AnonymousIdentityToken>();
// check token policy
UserTokenPolicy::SPtr userTokenPolicy;
statusCode = checkUserTokenPolicy(token->policyId(), UserIdentityTokenType_Anonymous, userTokenPolicy);
if (statusCode != Success) {
return statusCode;
}
Log(Debug, "authentication anonymous")
.parameter("PolicyId", token->policyId());
// create authentication context
ApplicationAuthenticationContext context;
context.authenticationType_ = OpcUaId_AnonymousIdentityToken_Encoding_DefaultBinary;
context.parameter_ = parameter;
context.sessionId_ = sessionId_;
context.statusCode_ = Success;
context.userContext_.reset();
// call anonymous authentication
forwardGlobalSync_->authenticationService().callback()(&context);
if (context.statusCode_ == Success) {
userContext_ = context.userContext_;
}
return context.statusCode_;
}
OpcUaStatusCode
Session::authenticationUserName(ActivateSessionRequest& activateSessionRequest, ExtensibleParameter::SPtr& parameter)
{
OpcUaStatusCode statusCode;
Log(Debug, "Session::authenticationUserName");
UserNameIdentityToken::SPtr token = parameter->parameter<UserNameIdentityToken>();
// check parameter and password
if (token->userName().size() == 0) {
Log(Debug, "user name invalid");
return BadIdentityTokenInvalid;
}
// check token policy
UserTokenPolicy::SPtr userTokenPolicy;
statusCode = checkUserTokenPolicy(token->policyId(), UserIdentityTokenType_Username, userTokenPolicy);
if (statusCode != Success) {
return statusCode;
}
Log(Debug, "authentication user name")
.parameter("PolicyId", token->policyId())
.parameter("UserName", token->userName())
.parameter("SecurityPolicyUri", userTokenPolicy->securityPolicyUri())
.parameter("EncyptionAlgorithmus", token->encryptionAlgorithm());
if (token->encryptionAlgorithm() == "") {
// we use a plain password
// create application context
ApplicationAuthenticationContext context;
context.authenticationType_ = OpcUaId_UserNameIdentityToken_Encoding_DefaultBinary;
context.parameter_ = parameter;
context.sessionId_ = sessionId_;
context.statusCode_ = Success;
context.userContext_.reset();
// call user name authentication
forwardGlobalSync_->authenticationService().callback()(&context);
if (context.statusCode_ == Success) {
userContext_ = context.userContext_;
}
return context.statusCode_;
}
// get cryption base and check cryption alg
CryptoBase::SPtr cryptoBase = cryptoManager_->get(userTokenPolicy->securityPolicyUri());
if (cryptoBase.get() == nullptr) {
Log(Debug, "crypto manager not found")
.parameter("SecurityPolicyUri", userTokenPolicy->securityPolicyUri());
return BadIdentityTokenRejected;
}
uint32_t encryptionAlg = EnryptionAlgs::uriToEncryptionAlg(token->encryptionAlgorithm());
if (encryptionAlg == 0) {
Log(Debug, "encryption alg invalid")
.parameter("EncryptionAlgorithm", token->encryptionAlgorithm());
return BadIdentityTokenRejected;;
}
// decrypt password
char* encryptedTextBuf;
int32_t encryptedTextLen;
token->password((OpcUaByte**)&encryptedTextBuf, &encryptedTextLen);
if (encryptedTextLen <= 0) {
Log(Debug, "password format invalid");
return BadIdentityTokenRejected;;
}
char* plainTextBuf;
uint32_t plainTextLen;
MemoryBuffer plainText(encryptedTextLen);
plainTextBuf = plainText.memBuf();
plainTextLen = plainText.memLen();
PrivateKey::SPtr privateKey = applicationCertificate_->privateKey();
statusCode = cryptoBase->asymmetricDecrypt(
encryptedTextBuf,
encryptedTextLen,
*privateKey.get(),
plainTextBuf,
&plainTextLen
);
if (statusCode != Success) {
Log(Debug, "decrypt password error");
return BadIdentityTokenRejected;;
}
// check decrypted password and server nonce
if (memcmp(serverNonce_, &plainTextBuf[plainTextLen-32] , 32) != 0) {
Log(Debug, "decrypt password server nonce error");
return BadIdentityTokenRejected;;
}
size_t passwordLen = plainTextLen-36;
if (passwordLen < 0) {
Log(Debug, "decrypted password length < 0");
return BadIdentityTokenRejected;;
}
token->password((const OpcUaByte*)&plainTextBuf[4], passwordLen);
// create application context
ApplicationAuthenticationContext context;
context.authenticationType_ = OpcUaId_UserNameIdentityToken_Encoding_DefaultBinary;
context.parameter_ = parameter;
context.sessionId_ = sessionId_;
context.statusCode_ = Success;
context.userContext_.reset();
forwardGlobalSync_->authenticationService().callback()(&context);
if (context.statusCode_ == Success) {
userContext_ = context.userContext_;
}
return context.statusCode_;
}
OpcUaStatusCode
Session::authenticationX509(ActivateSessionRequest& activateSessionRequest, ExtensibleParameter::SPtr& parameter)
{
OpcUaStatusCode statusCode;
Log(Debug, "Session::authenticationX509");
X509IdentityToken::SPtr token = parameter->parameter<X509IdentityToken>();
// check parameter and password
if (token->certificateData().size() == 0) {
Log(Debug, "token data invalid");
return BadIdentityTokenInvalid;
}
// check token policy
UserTokenPolicy::SPtr userTokenPolicy;
statusCode = checkUserTokenPolicy(token->policyId(), UserIdentityTokenType_Certificate, userTokenPolicy);
if (statusCode != Success) {
return statusCode;
}
// get signature data
SignatureData::SPtr userTokenSignature = activateSessionRequest.userTokenSignature();
if (userTokenSignature.get() == nullptr) {
Log(Debug, "missing user token signature")
.parameter("PolicyId", token->policyId());
return BadIdentityTokenInvalid;
}
Log(Debug, "authentication x509")
.parameter("PolicyId", token->policyId())
.parameter("CertificateData", token->certificateData())
.parameter("SecurityPolicyUri", userTokenPolicy->securityPolicyUri());
// get cryption base and check cryption alg
CryptoBase::SPtr cryptoBase = cryptoManager_->get(userTokenPolicy->securityPolicyUri());
if (cryptoBase.get() == nullptr) {
Log(Debug, "crypto manager not found")
.parameter("SecurityPolicyUri", userTokenPolicy->securityPolicyUri());
return BadIdentityTokenRejected;
}
uint32_t signatureAlg = SignatureAlgs::uriToSignatureAlg(userTokenSignature->algorithm());
if (signatureAlg == 0) {
Log(Debug, "encryption alg invalid")
.parameter("SignatureAlgorithm", userTokenSignature->algorithm());
return BadIdentityTokenRejected;;
}
// get public key
MemoryBuffer certificateText(token->certificateData());
Certificate certificate;
if (!certificate.fromDERBuf(certificateText)) {
Log(Debug, "certificate invalid");
return BadIdentityTokenRejected;;
}
PublicKey publicKey = certificate.publicKey();
// FIXME: certificate must be trusted ...
// validate signature
statusCode = userTokenSignature->verifySignature(
certificateText,
publicKey,
*cryptoBase
);
// create application context
ApplicationAuthenticationContext context;
context.authenticationType_ = OpcUaId_X509IdentityToken_Encoding_DefaultBinary;
context.parameter_ = parameter;
context.sessionId_ = sessionId_;
context.statusCode_ = Success;
context.userContext_.reset();
forwardGlobalSync_->authenticationService().callback()(&context);
if (context.statusCode_ == Success) {
userContext_ = context.userContext_;
}
return context.statusCode_;
}
OpcUaStatusCode
Session::authenticationIssued(ActivateSessionRequest& activateSessionRequest, ExtensibleParameter::SPtr& parameter)
{
OpcUaStatusCode statusCode;
Log(Debug, "Session::authenticationIssued");
IssuedIdentityToken::SPtr token = parameter->parameter<IssuedIdentityToken>();
// check parameter and password
if (token->tokenData().size() == 0) {
Log(Debug, "token data invalid");
return BadIdentityTokenInvalid;
}
// check token policy
UserTokenPolicy::SPtr userTokenPolicy;
statusCode = checkUserTokenPolicy(token->policyId(), UserIdentityTokenType_IssuedToken, userTokenPolicy);
if (statusCode != Success) {
return statusCode;
}
Log(Debug, "authentication issued")
.parameter("PolicyId", token->policyId())
.parameter("TokenData", token->tokenData())
.parameter("SecurityPolicyUri", userTokenPolicy->securityPolicyUri())
.parameter("EncyptionAlgorithmus", token->encryptionAlgorithm());
// get cryption base and check cryption alg
CryptoBase::SPtr cryptoBase = cryptoManager_->get(userTokenPolicy->securityPolicyUri());
if (cryptoBase.get() == nullptr) {
Log(Debug, "crypto manager not found")
.parameter("SecurityPolicyUri", userTokenPolicy->securityPolicyUri());
return BadIdentityTokenRejected;
}
uint32_t encryptionAlg = EnryptionAlgs::uriToEncryptionAlg(token->encryptionAlgorithm());
if (encryptionAlg == 0) {
Log(Debug, "encryption alg invalid")
.parameter("EncryptionAlgorithm", token->encryptionAlgorithm());
return BadIdentityTokenRejected;;
}
// decrypt token data
char* encryptedTextBuf;
int32_t encryptedTextLen;
token->tokenData((OpcUaByte**)&encryptedTextBuf, &encryptedTextLen);
if (encryptedTextLen <= 0) {
Log(Debug, "token data format invalid");
return BadIdentityTokenRejected;;
}
char* plainTextBuf;
uint32_t plainTextLen;
MemoryBuffer plainText(encryptedTextLen);
plainTextBuf = plainText.memBuf();
plainTextLen = plainText.memLen();
PrivateKey::SPtr privateKey = applicationCertificate_->privateKey();
statusCode = cryptoBase->asymmetricDecrypt(
encryptedTextBuf,
encryptedTextLen,
*privateKey.get(),
plainTextBuf,
&plainTextLen
);
if (statusCode != Success) {
Log(Debug, "decrypt token data error");
return BadIdentityTokenRejected;;
}
// check decrypted password and server nonce
if (memcmp(serverNonce_, &plainTextBuf[plainTextLen-32] , 32) != 0) {
Log(Debug, "decrypt token data server nonce error");
return BadIdentityTokenRejected;;
}
token->tokenData((const OpcUaByte*)&plainTextBuf[4], plainTextLen-36);
// create application context
ApplicationAuthenticationContext context;
context.authenticationType_ = OpcUaId_IssuedIdentityToken_Encoding_DefaultBinary;
context.parameter_ = parameter;
context.sessionId_ = sessionId_;
context.statusCode_ = Success;
context.userContext_.reset();
forwardGlobalSync_->authenticationService().callback()(&context);
if (context.statusCode_ == Success) {
userContext_ = context.userContext_;
}
return context.statusCode_;
}
OpcUaStatusCode
Session::checkUserTokenPolicy(
const std::string& policyId,
UserIdentityTokenType userIdentityTokenType,
UserTokenPolicy::SPtr& userTokenPolicy
)
{
if (endpointDescription_.get() == nullptr) {
Log(Debug, "endpoint description not exist");
return BadIdentityTokenInvalid;
}
if (endpointDescription_->userIdentityTokens().get() == nullptr) {
Log(Debug, "user identity token not exist");
return BadIdentityTokenInvalid;
}
// find related identity token
bool found = false;
for (uint32_t idx=0; idx<endpointDescription_->userIdentityTokens()->size(); idx++) {
if (!endpointDescription_->userIdentityTokens()->get(idx, userTokenPolicy)) {
continue;
}
if (userTokenPolicy->tokenType() != userIdentityTokenType) {
continue;
}
if (userTokenPolicy->policyId() == policyId) {
found = true;
break;
}
}
if (!found) {
Log(Debug, "identity token for policy not found in endpoint")
.parameter("PolicyId", policyId);
return BadIdentityTokenInvalid;
}
return Success;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// create session request
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
void
Session::createSessionRequest(
RequestHeader::SPtr requestHeader,
SecureChannelTransaction::SPtr secureChannelTransaction
)
{
createServerNonce();
OpcUaStatusCode statusCode;
OpcUaStatusCode serviceResult = Success;
Log(Debug, "receive create session request");
secureChannelTransaction->responseTypeNodeId_ = OpcUaId_CreateSessionResponse_Encoding_DefaultBinary;
if (sessionState_ != SessionState_Close) {
Log(Error, "receive create session request in invalid state")
.parameter("SessionState", sessionState_);
// FIXME: handle error ...
}
std::iostream ios(&secureChannelTransaction->is_);
CreateSessionRequest createSessionRequest;
createSessionRequest.opcUaBinaryDecode(ios);
std::iostream iosres(&secureChannelTransaction->os_);
CreateSessionResponse createSessionResponse;
createSessionResponse.responseHeader()->requestHandle(requestHeader->requestHandle());
createSessionResponse.responseHeader()->serviceResult(serviceResult);
if (createSessionRequest.clientCertificate().exist()) {
clientCertificate_.fromDERBuf(
createSessionRequest.clientCertificate().memBuf(),
createSessionRequest.clientCertificate().size()
);
}
createSessionResponse.sessionId().namespaceIndex(1);
createSessionResponse.sessionId().nodeId(sessionId_);
createSessionResponse.authenticationToken().namespaceIndex(1);
createSessionResponse.authenticationToken().nodeId(authenticationToken_);
createSessionResponse.receivedSessionTimeout(120000);
createSessionResponse.serverEndpoints(endpointDescriptionArray_);
createSessionResponse.maxRequestMessageSize(0);
// added server certificate
createSessionResponse.serverNonce((const OpcUaByte*)serverNonce_, 32);
applicationCertificate_->certificate()->toDERBuf(createSessionResponse.serverCertificate());
if (applicationCertificate_.get() != nullptr && secureChannelTransaction->cryptoBase_.get() != nullptr) {
// create server signature
MemoryBuffer clientCertificate(createSessionRequest.clientCertificate());
MemoryBuffer clientNonce(createSessionRequest.clientNonce());
PrivateKey privateKey = *applicationCertificate_->privateKey();
statusCode = createSessionResponse.signatureData()->createSignature(
clientCertificate,
clientNonce,
privateKey,
*secureChannelTransaction->cryptoBase_
);
if (statusCode != Success) {
Log(Error, "create server signature in create session request error")
.parameter("StatusCode", OpcUaStatusCodeMap::shortString(statusCode));
createSessionResponse.responseHeader()->serviceResult(BadSecurityChecksFailed);
}
}
createSessionResponse.responseHeader()->opcUaBinaryEncode(iosres);
createSessionResponse.opcUaBinaryEncode(iosres);
sessionState_ = SessionState_CreateSessionResponse;
if (sessionIf_ != nullptr) {
ResponseHeader::SPtr responseHeader = createSessionResponse.responseHeader();
sessionIf_->responseMessage(responseHeader, secureChannelTransaction);
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// activate session request
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
void
Session::activateSessionRequest(
RequestHeader::SPtr requestHeader,
SecureChannelTransaction::SPtr secureChannelTransaction
)
{
OpcUaStatusCode statusCode;
Log(Debug, "receive activate session request");
secureChannelTransaction->responseTypeNodeId_ = OpcUaId_ActivateSessionResponse_Encoding_DefaultBinary;
// FIXME: if authenticationToken in the secureChannelTransaction contains 0 then
// the session has a new secure channel
std::iostream ios(&secureChannelTransaction->is_);
ActivateSessionRequest activateSessionRequest;
activateSessionRequest.opcUaBinaryDecode(ios);
if (sessionState_ != SessionState_CreateSessionResponse && sessionState_ != SessionState_Ready) {
Log(Error, "receive activate session request in invalid state")
.parameter("SessionState", sessionState_);
activateSessionRequestError(requestHeader, secureChannelTransaction, BadIdentityTokenInvalid);
return;
}
// check client signature
if (secureChannelTransaction->cryptoBase_.get() != nullptr) {
// create certificate
uint32_t derCertSize = applicationCertificate_->certificate()->getDERBufSize();
MemoryBuffer certificate(derCertSize);
applicationCertificate_->certificate()->toDERBuf(
certificate.memBuf(),
&derCertSize
);
// create server nonce
MemoryBuffer serverNonce(serverNonce_, 32);
// verify signature
PublicKey publicKey = clientCertificate_.publicKey();
statusCode = activateSessionRequest.clientSignature()->verifySignature(
certificate,
serverNonce,
publicKey,
*secureChannelTransaction->cryptoBase_
);
if (statusCode != Success) {
Log(Error, "client signature error");
activateSessionRequestError(requestHeader, secureChannelTransaction, BadSecurityChecksFailed);
return;
}
}
// check username and password
statusCode = authentication(activateSessionRequest);
std::iostream iosres(&secureChannelTransaction->os_);
createServerNonce();
ActivateSessionResponse activateSessionResponse;
activateSessionResponse.responseHeader()->requestHandle(requestHeader->requestHandle());
activateSessionResponse.responseHeader()->serviceResult(statusCode);
activateSessionResponse.serverNonce((const OpcUaByte*)serverNonce_, 32);
activateSessionResponse.responseHeader()->opcUaBinaryEncode(iosres);
activateSessionResponse.opcUaBinaryEncode(iosres);
sessionState_ = SessionState_Ready;
//secureChannelTransaction->authenticationToken_ = authenticationToken_;
if (sessionIf_ != nullptr) {
ResponseHeader::SPtr responseHeader = activateSessionResponse.responseHeader();
sessionIf_->responseMessage(responseHeader, secureChannelTransaction);
}
}
void
Session::activateSessionRequestError(
RequestHeader::SPtr& requestHeader,
SecureChannelTransaction::SPtr secureChannelTransaction,
OpcUaStatusCode statusCode,
bool deleteSession
)
{
std::iostream iosres(&secureChannelTransaction->os_);
ActivateSessionResponse activateSessionResponse;
activateSessionResponse.responseHeader()->requestHandle(requestHeader->requestHandle());
activateSessionResponse.responseHeader()->serviceResult(statusCode);
activateSessionResponse.responseHeader()->opcUaBinaryEncode(iosres);
activateSessionResponse.opcUaBinaryEncode(iosres);
if (sessionIf_ != nullptr) {
ResponseHeader::SPtr responseHeader = activateSessionResponse.responseHeader();
sessionIf_->responseMessage(responseHeader, secureChannelTransaction);
if (deleteSession) {
sessionIf_->deleteSession(authenticationToken_);
}
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// close session request
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
void
Session::closeSessionRequest(
RequestHeader::SPtr requestHeader,
SecureChannelTransaction::SPtr secureChannelTransaction
)
{
Log(Debug, "receive close session request");
secureChannelTransaction->responseTypeNodeId_ = OpcUaId_CloseSessionResponse_Encoding_DefaultBinary;
std::iostream ios(&secureChannelTransaction->is_);
CloseSessionRequest closeSessionRequest;
closeSessionRequest.opcUaBinaryDecode(ios);
std::iostream iosres(&secureChannelTransaction->os_);
CloseSessionResponse closeSessionResponse;
closeSessionResponse.responseHeader()->requestHandle(requestHeader->requestHandle());
closeSessionResponse.responseHeader()->serviceResult(Success);
closeSessionResponse.responseHeader()->opcUaBinaryEncode(iosres);
closeSessionResponse.opcUaBinaryEncode(iosres);
// close session
authenticationCloseSession();
if (sessionIf_ != nullptr) {
ResponseHeader::SPtr responseHeader = closeSessionResponse.responseHeader();
sessionIf_->responseMessage(responseHeader, secureChannelTransaction);
// FIXME: BUG - After deleting the session, the monitored item will send a notification. -> CORE
//sessionIf_->deleteSession(authenticationToken_);
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// cancel request
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
void
Session::cancelRequest(
RequestHeader::SPtr requestHeader,
SecureChannelTransaction::SPtr secureChannelTransaction
)
{
Log(Debug, "receive cancel request");
secureChannelTransaction->responseTypeNodeId_ = OpcUaId_CancelResponse_Encoding_DefaultBinary;
std::iostream ios(&secureChannelTransaction->is_);
CancelRequest cancelRequest;
cancelRequest.opcUaBinaryDecode(ios);
cancelRequestError(requestHeader, secureChannelTransaction, BadNotImplemented);
}
void
Session::cancelRequestError(
RequestHeader::SPtr& requestHeader,
SecureChannelTransaction::SPtr secureChannelTransaction,
OpcUaStatusCode statusCode
)
{
std::iostream iosres(&secureChannelTransaction->os_);
CancelResponse cancelResponse;
cancelResponse.responseHeader()->requestHandle(requestHeader->requestHandle());
cancelResponse.responseHeader()->serviceResult(statusCode);
cancelResponse.responseHeader()->opcUaBinaryEncode(iosres);
cancelResponse.opcUaBinaryEncode(iosres);
if (sessionIf_ != nullptr) {
ResponseHeader::SPtr responseHeader = cancelResponse.responseHeader();
sessionIf_->responseMessage(responseHeader, secureChannelTransaction);
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// message request
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
void
Session::messageRequest(
RequestHeader::SPtr requestHeader,
SecureChannelTransaction::SPtr secureChannelTransaction
)
{
Log(Debug, "receive message request");
if (sessionState_ != SessionState_Ready) {
Log(Error, "receive message request in invalid state")
.parameter("SessionState", sessionState_)
.parameter("TypeId", secureChannelTransaction->requestTypeNodeId_);
// FIXME: error handling
return;
}
if (transactionManagerSPtr_.get() == nullptr) {
Log(Error, "transaction manager empty");
// ignore request - we cannot generate a response
return;
}
ServiceTransaction::SPtr serviceTransactionSPtr = transactionManagerSPtr_->getTransaction(secureChannelTransaction->requestTypeNodeId_);
if (serviceTransactionSPtr.get() == nullptr) {
Log(Error, "receive invalid message type")
.parameter("TypeId", secureChannelTransaction->requestTypeNodeId_);
// ignore request - we cannot generate a response
return;
}
secureChannelTransaction->responseTypeNodeId_ = OpcUaNodeId(serviceTransactionSPtr->nodeTypeResponse().nodeId<uint32_t>());
serviceTransactionSPtr->componentSession(this);
serviceTransactionSPtr->sessionId(sessionId_);
serviceTransactionSPtr->userContext(userContext_);
Object::SPtr handle = secureChannelTransaction;
serviceTransactionSPtr->handle(handle);
// FIXME: serviceTransactionSPtr->channelId(secureChannelTransaction->channelId_);
std::iostream ios(&secureChannelTransaction->is_);
serviceTransactionSPtr->requestHeader(requestHeader);
//OpcUaStackCore::dumpHex(sb);
serviceTransactionSPtr->opcUaBinaryDecodeRequest(ios);
//OpcUaStackCore::dumpHex(sb);
serviceTransactionSPtr->requestId_ = secureChannelTransaction->requestId_;
serviceTransactionSPtr->statusCode(Success);
Log(Debug, "receive request in session")
.parameter("TrxId", serviceTransactionSPtr->transactionId())
.parameter("TypeId", serviceTransactionSPtr->requestName())
.parameter("RequestId", serviceTransactionSPtr->requestId_);
serviceTransactionSPtr->componentService()->send(serviceTransactionSPtr);
}
void
Session::messageRequestError(
SecureChannelTransaction::SPtr secureChannelTransaction,
OpcUaStatusCode statusCode
)
{
// FIXME: todo
}
void
Session::receive(Message::SPtr message)
{
ServiceTransaction::SPtr serviceTransactionSPtr = boost::static_pointer_cast<ServiceTransaction>(message);
Log(Debug, "receive response in session")
.parameter("TrxId", serviceTransactionSPtr->transactionId())
.parameter("TypeId", serviceTransactionSPtr->responseName())
.parameter("RequestId", serviceTransactionSPtr->requestId_)
.parameter("StatusCode", OpcUaStatusCodeMap::shortString(serviceTransactionSPtr->statusCode()));
RequestHeader::SPtr requestHeader = serviceTransactionSPtr->requestHeader();
ResponseHeader::SPtr responseHeader = serviceTransactionSPtr->responseHeader();
responseHeader->requestHandle(requestHeader->requestHandle());
responseHeader->serviceResult(serviceTransactionSPtr->statusCode());
SecureChannelTransaction::SPtr secureChannelTransaction;
secureChannelTransaction = boost::static_pointer_cast<SecureChannelTransaction>(serviceTransactionSPtr->handle());
std::iostream iosres(&secureChannelTransaction->os_);
responseHeader->opcUaBinaryEncode(iosres);
serviceTransactionSPtr->opcUaBinaryEncodeResponse(iosres);
if (sessionIf_ != nullptr) {
sessionIf_->responseMessage(responseHeader, secureChannelTransaction);
}
}
}
| 33.064777
| 138
| 0.725603
|
gianricardo
|
627a9f9b7a3e6d26795666bd022e97da4938b46b
| 4,295
|
cpp
|
C++
|
bside-code/bside_tokenizer.cpp
|
mgolden/basic_stamp_linux64
|
eb547eae358c5fab220d159cb932b5a34beb3711
|
[
"Linux-OpenIB"
] | 4
|
2018-06-03T23:12:54.000Z
|
2022-03-27T23:20:19.000Z
|
bside-code/bside_tokenizer.cpp
|
mgolden/basic_stamp_linux64
|
eb547eae358c5fab220d159cb932b5a34beb3711
|
[
"Linux-OpenIB"
] | null | null | null |
bside-code/bside_tokenizer.cpp
|
mgolden/basic_stamp_linux64
|
eb547eae358c5fab220d159cb932b5a34beb3711
|
[
"Linux-OpenIB"
] | 2
|
2016-02-01T17:56:49.000Z
|
2016-07-14T09:39:57.000Z
|
/*
bside_tokenize.cpp
This interfaces with Parallax, Inc.'s PBASIC Tokenizer Shared Library for
the Linux operating system.
It reads a PBASIC source file and writes the tokenized results to a file
which can then be sent to the BASIC Stamp microcontroller using the
"bstamp_run" program.
Based on "stampapp.cpp" example from the "PBASIC_Tokenizer.tar.gz" archive,
(c) 2002 Parallax, Inc. All rights reserved.
http://www.parallax.com/
PBASIC is a trademark and BASIC Stamp is a registered trademark of
Parallax, Inc.
*/
extern "C" {
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
}
#include "tokenizer.h"
#include "open_tokenizer_so.h"
/* Globals: */
TModuleRec *ModuleRec;
char Source[MaxSourceSize];
int fd;
float bside_tokenizer_ver = 0.02;
float PBasic_tokenizer_ver;
/* Prototypes */
int write_file(char *filename);
void handle_args(int argsc, char *arr[]);
void print_usage(char *args[]);
int main(int argc, char *args[])
{
int i;
void *hso;
char *error;
/* Check for proper arguments: */
handle_args(argc, args);
/* (Function prototypes): */
STDAPI (*GetVersion)(void);
STDAPI (*CompileIt)(TModuleRec *, char *Src, bool DirectivesOnly, bool ParseStampDirectives, TSrcTokReference *Ref);
STDAPI (*doTestRecAlignment)(TModuleRec *);
/* Open the .so */
hso = open_tokenizer_so(TOKENIZER_SO);
/* (Map functions in tokenizer.so) */
GetVersion= (STDAPI(*)(void))dlsym(hso,"Version");
CompileIt= (STDAPI(*)(TModuleRec *, char *Src, bool DirectivesOnly,bool ParseStampDirectives, TSrcTokReference *Ref))dlsym(hso,"Compile");
doTestRecAlignment= (STDAPI(*)(TModuleRec *))dlsym(hso,"TestRecAlignment");
/* (Test for any errors) */
error = dlerror();
if (error != NULL)
{
perror(error);
dlclose(hso);
exit(EXIT_FAILURE);
}
/* Allocate TModuleRec */
ModuleRec = (TModuleRec *)malloc(sizeof(TModuleRec));
/* Display version of tokenizer */
PBasic_tokenizer_ver = (((float)GetVersion())/100.0);
printf("PBASIC Tokenizer Library version %1.2f\n\n", PBasic_tokenizer_ver);
/* Call TestRecAlignment and display the results of the TModuleRec fields. */
doTestRecAlignment(ModuleRec);
/* Load source code from file: */
fd = open(args[1], O_RDONLY);
if (fd == -1)
{
printf("Can't open %s\n", args[1]);
exit(EXIT_FAILURE);
}
ModuleRec->SourceSize = read(fd, Source, sizeof(Source));
Source[ModuleRec->SourceSize] = '\0';
close(fd);
/* Tokenize the code: */
CompileIt(ModuleRec, Source, false, true,NULL);
/* Close shared library: */
dlclose(hso);
/* Did it succeed? */
if (!ModuleRec->Succeeded)
{
printf("Error: Tokenization of %s failed.\n", args[1]);
printf("Failed compile: %s\n", ModuleRec->Error);
printf("Error in :\n\t ");
for (i=0; i < ModuleRec->ErrorLength; i++)
{
putchar( (int) *(Source + ModuleRec->ErrorStart + i) );
}
putchar((int) '\n');
exit(EXIT_FAILURE);
}
printf("Tokenized Succesfully!\n");
if(write_file(args[2]))
{
printf("Error: Can't create %s\n", args[2]);
exit(EXIT_FAILURE);
}
printf("%s created succesfully!\n", args[2]);
/* All Done */
return 0;
}
/* Save the tokenized results to a file: */
int write_file(char *filename)
{
fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0644);
if (fd == -1)
{
return 1;
}
write(fd, ModuleRec->PacketBuffer, ModuleRec->PacketCount * 18);
close(fd);
return 0;
}
/* Processes all the command line arguments */
void handle_args(int argsc, char *args[])
{
int c;
if(argsc > 2)
{
while ( (c = getopt(argsc, args, "hv")) != -1)
{
switch(c)
{
case 'h':
case '?':
print_usage(args);
exit(EXIT_SUCCESS);
break;
case 'v':
printf("Bside-tokenizer Version: %.2f\n", bside_tokenizer_ver);
exit(EXIT_SUCCESS);
break;
default:
print_usage(args);
exit(EXIT_FAILURE);
break;
}
}
}
else
{
print_usage(args);
exit(EXIT_SUCCESS);
}
}
void print_usage (char *args[]) {
printf("Usage: %s {[OPTION] | infile.txt outfile.tok}\n\n", args[0]);
printf("Options\n");
printf("\t-h\t this screen\n");
printf("\t-v\t print version information\n");
return;
}
| 21.582915
| 139
| 0.65518
|
mgolden
|
627c3def3d92f3aae785a307ead6cb3985524231
| 85
|
cpp
|
C++
|
src/Global_renderer.cpp
|
romz-pl/pong-game
|
2deadc419fb9340b333aa6b94bb7f861b93ffe6d
|
[
"MIT"
] | null | null | null |
src/Global_renderer.cpp
|
romz-pl/pong-game
|
2deadc419fb9340b333aa6b94bb7f861b93ffe6d
|
[
"MIT"
] | null | null | null |
src/Global_renderer.cpp
|
romz-pl/pong-game
|
2deadc419fb9340b333aa6b94bb7f861b93ffe6d
|
[
"MIT"
] | null | null | null |
#include "Global_renderer.h"
namespace Global
{
unique< SDL_Renderer* > renderer;
}
| 12.142857
| 33
| 0.752941
|
romz-pl
|
627d27713021070890784a463c60934f94e9136d
| 708
|
cpp
|
C++
|
src/eventBus.cpp
|
HenadziMatuts/snake1
|
c5ecb731c25222b7b8e46803f9f26277ad48bc52
|
[
"MIT"
] | 8
|
2017-08-31T16:43:10.000Z
|
2021-11-14T17:44:05.000Z
|
src/eventBus.cpp
|
HenadziMatuts/snake1
|
c5ecb731c25222b7b8e46803f9f26277ad48bc52
|
[
"MIT"
] | null | null | null |
src/eventBus.cpp
|
HenadziMatuts/snake1
|
c5ecb731c25222b7b8e46803f9f26277ad48bc52
|
[
"MIT"
] | 1
|
2020-03-19T19:46:56.000Z
|
2020-03-19T19:46:56.000Z
|
#include "eventBus.h"
void EventBus::PostGameEvent(GameEvent gameEvent)
{
m_GameEvents.push_back(gameEvent);
};
void EventBus::PostInGameEvent(InGameEvent inGameEvent, InGameEventSource source)
{
m_InGameEventsNext[source].push_back(inGameEvent);
}
std::vector<GameEvent>* EventBus::GameEvents()
{
return &m_GameEvents;
}
std::vector<InGameEvent>* EventBus::InGameEvents(InGameEventSource source)
{
return &m_InGameEventsCurrent[source];
}
void EventBus::Proceed()
{
m_GameEvents.clear();
for (int i = 0; i < IN_GAME_EVENT_SOURCE_TOTAL; i++)
{
m_InGameEventsCurrent[i].clear();
}
auto *swap = m_InGameEventsCurrent;
m_InGameEventsCurrent = m_InGameEventsNext;
m_InGameEventsNext = swap;
}
| 20.228571
| 81
| 0.768362
|
HenadziMatuts
|
627da4a2450cb31b32ef7e22c79914633a747b78
| 2,134
|
cpp
|
C++
|
src/ctl/ctlListView.cpp
|
dpage/pgadmin3
|
6784e6281831a083fe5a0bbd49eac90e1a6ac547
|
[
"Artistic-1.0"
] | 2
|
2021-07-16T21:45:41.000Z
|
2021-08-14T15:54:17.000Z
|
src/ctl/ctlListView.cpp
|
dpage/pgadmin3
|
6784e6281831a083fe5a0bbd49eac90e1a6ac547
|
[
"Artistic-1.0"
] | null | null | null |
src/ctl/ctlListView.cpp
|
dpage/pgadmin3
|
6784e6281831a083fe5a0bbd49eac90e1a6ac547
|
[
"Artistic-1.0"
] | 2
|
2017-11-18T15:00:24.000Z
|
2021-08-14T15:54:30.000Z
|
//////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
// RCS-ID: $Id$
// Copyright (C) 2002 - 2010, The pgAdmin Development Team
// This software is released under the Artistic Licence
//
// ctlListView.cpp - enhanced listview control
//
//////////////////////////////////////////////////////////////////////////
// wxWindows headers
#include <wx/wx.h>
#include <wx/imaglist.h>
// App headers
#include "ctl/ctlListView.h"
#include "base/base.h"
ctlListView::ctlListView(wxWindow *p, int id, wxPoint pos, wxSize siz, long attr)
: wxListView(p, id, pos, siz, attr | wxLC_REPORT)
{
}
long ctlListView::GetSelection()
{
return GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
}
wxString ctlListView::GetText(long row, long col)
{
wxListItem item;
item.SetId(row);
item.SetColumn(col);
item.SetMask(wxLIST_MASK_TEXT);
GetItem(item);
return item.GetText();
};
void ctlListView::AddColumn(const wxChar *text, int size, int format)
{
InsertColumn(GetColumnCount(), text, format, ConvertDialogToPixels(wxPoint(size,0)).x);
}
long ctlListView::AppendItem(int icon, const wxChar *val, const wxChar *val2, const wxChar *val3)
{
long pos=InsertItem(GetItemCount(), val, icon);
if (val2 && *val2)
SetItem(pos, 1, val2);
if (val3 && *val3)
SetItem(pos, 2, val3);
return pos;
}
void ctlListView::CreateColumns(wxImageList *images, const wxString &left, const wxString &right, int leftSize)
{
int rightSize;
if (leftSize < 0)
{
leftSize = rightSize = GetClientSize().GetWidth()/2;
}
else
{
if (leftSize)
leftSize = ConvertDialogToPixels(wxPoint(leftSize, 0)).x;
rightSize = GetClientSize().GetWidth()-leftSize;
}
if (!leftSize)
{
InsertColumn(0, left, wxLIST_FORMAT_LEFT, GetClientSize().GetWidth());
}
else
{
InsertColumn(0, left, wxLIST_FORMAT_LEFT, leftSize);
InsertColumn(1, right, wxLIST_FORMAT_LEFT, rightSize);
}
if (images)
SetImageList(images, wxIMAGE_LIST_SMALL);
}
| 24.25
| 111
| 0.616214
|
dpage
|
627f3bac77ef5ca45503753e8a5623643f23d25f
| 977
|
cpp
|
C++
|
Lesson4/inheritance.cpp
|
hari-learningspace/CPP_Learning
|
f32a250e284e9b9d876c4ef20bbb28e5c81cea27
|
[
"MIT"
] | null | null | null |
Lesson4/inheritance.cpp
|
hari-learningspace/CPP_Learning
|
f32a250e284e9b9d876c4ef20bbb28e5c81cea27
|
[
"MIT"
] | null | null | null |
Lesson4/inheritance.cpp
|
hari-learningspace/CPP_Learning
|
f32a250e284e9b9d876c4ef20bbb28e5c81cea27
|
[
"MIT"
] | null | null | null |
/*
Instructions
Add a new member variable to class Vehicle.
Output that new member in main().
Derive a new class from Vehicle, alongside Car and Bicycle.
Instantiate an object of that new class.
Print the object.
*/
#include <iostream>
#include <string>
using std::string;
class Vehicle {
public:
int wheels = 0;
string color = "blue";
int weight = 0;
void Print() const {
std::cout << "This " << color << " vehicle has " << wheels << " wheels!\n";
}
};
class Car : public Vehicle {
public:
bool sunroof = false;
};
class Bicycle : public Vehicle {
public:
bool kickstand = true;
};
class Truck : public Vehicle {
public:
std::string OEM;
};
int main() {
Car car;
car.wheels = 4;
car.sunroof = true;
car.Print();
if (car.sunroof)
std::cout << "And a sunroof!\n";
Truck truck;
truck.color = "red";
truck.OEM = "Diamler";
truck.weight = 100;
truck.wheels = 4;
if (truck.OEM == "Diamler")
std::cout << "Diamler Truck\n";
}
| 17.763636
| 79
| 0.63869
|
hari-learningspace
|
6282eed5f049f3edffad889963aca0e381a4ab46
| 612
|
cc
|
C++
|
tools/patch/tfs/util/retrier.cc
|
Cuda-GDB/tensorrt-inference-server
|
71376ccb1244ed9707b8d81e479e165c152b5767
|
[
"BSD-3-Clause"
] | 2
|
2021-06-01T09:27:12.000Z
|
2021-09-18T22:33:08.000Z
|
tools/patch/tfs/util/retrier.cc
|
Cuda-GDB/tensorrt-inference-server
|
71376ccb1244ed9707b8d81e479e165c152b5767
|
[
"BSD-3-Clause"
] | null | null | null |
tools/patch/tfs/util/retrier.cc
|
Cuda-GDB/tensorrt-inference-server
|
71376ccb1244ed9707b8d81e479e165c152b5767
|
[
"BSD-3-Clause"
] | null | null | null |
--- tensorflow_serving/util/retrier.cc 2018-05-15 13:11:26.068986416 -0700
+++ /home/david/dev/gitlab/dgx/tensorrtserver/tools/patch/tfs/util/retrier.cc 2018-10-12 12:44:37.280572118 -0700
@@ -42,7 +42,9 @@
if (is_cancelled()) {
LOG(INFO) << "Retrying of " << description << " was cancelled.";
}
- if (num_tries == max_num_retries + 1) {
+
+ // NVIDIA: Add max_num_retries>0 check to avoid spurious logging
+ if ((max_num_retries > 0) && (num_tries == max_num_retries + 1)) {
LOG(INFO) << "Retrying of " << description
<< " exhausted max_num_retries: " << max_num_retries;
}
| 43.714286
| 113
| 0.645425
|
Cuda-GDB
|
62841f0aefa1262b5e71f0c3b8d8647913cdea5c
| 666
|
cpp
|
C++
|
src/MediaDataImpl.cpp
|
gumb0/cpp-instagram
|
da3286d8d0945daedb10e00011a09be98c22dcd6
|
[
"MIT"
] | 11
|
2015-03-10T01:24:09.000Z
|
2020-01-30T23:07:09.000Z
|
src/MediaDataImpl.cpp
|
gumb0/cpp-instagram
|
da3286d8d0945daedb10e00011a09be98c22dcd6
|
[
"MIT"
] | 5
|
2016-03-03T09:05:09.000Z
|
2016-03-03T09:16:52.000Z
|
src/MediaDataImpl.cpp
|
gumb0/cpp-instagram
|
da3286d8d0945daedb10e00011a09be98c22dcd6
|
[
"MIT"
] | 5
|
2015-11-16T11:46:31.000Z
|
2022-01-06T11:09:22.000Z
|
#include "MediaDataImpl.h"
#include <assert.h>
using namespace Instagram;
MediaDataImpl::MediaDataImpl(CurlPtr curl, const MediaDataInfo& info) :
mCurl(curl),
mInfo(info)
{
}
int MediaDataImpl::getWidth() const
{
return mInfo.mWidth;
}
int MediaDataImpl::getHeight() const
{
return mInfo.mHeight;
}
std::string MediaDataImpl::getUrl() const
{
return mInfo.mUrl;
}
void MediaDataImpl::download(const std::string& localPath) const
{
mCurl->download(mInfo.mUrl, localPath);
}
MediaDataPtr Instagram::CreateMediaDataImpl(CurlPtr curl, MediaDataInfoPtr info)
{
assert(info);
return MediaDataPtr(new MediaDataImpl(curl, *info));
}
| 17.526316
| 80
| 0.726727
|
gumb0
|
628d03cf81dd36dfeeaf4ac4a41241bf9e3cd5cd
| 896
|
cpp
|
C++
|
review/src/android/ReviewAndroid.cpp
|
dapetcu21/extension-review
|
1e9e3471ce98141016562aeec693f4cfd98a5c48
|
[
"MIT"
] | 10
|
2020-11-23T21:16:56.000Z
|
2022-03-07T20:17:40.000Z
|
review/src/android/ReviewAndroid.cpp
|
dapetcu21/extension-review
|
1e9e3471ce98141016562aeec693f4cfd98a5c48
|
[
"MIT"
] | 2
|
2020-08-12T19:34:36.000Z
|
2020-10-09T22:06:36.000Z
|
review/src/android/ReviewAndroid.cpp
|
dapetcu21/extension-review
|
1e9e3471ce98141016562aeec693f4cfd98a5c48
|
[
"MIT"
] | 8
|
2017-10-03T12:01:35.000Z
|
2020-10-09T21:06:44.000Z
|
#if defined(DM_PLATFORM_ANDROID)
#include "../private_review.h"
#include "jni.h"
namespace ext_review {
const char* JAR_PATH = "com/defold/review/Review";
bool isSupported() {
ThreadAttacher attacher;
JNIEnv *env = attacher.env;
jclass cls = ClassLoader(env).load(JAR_PATH);
jmethodID method = env->GetStaticMethodID(cls, "isSupported", "(Landroid/app/Activity;)Z");
jboolean return_value = (jboolean)env->CallStaticBooleanMethod(cls,
method, dmGraphics::GetNativeAndroidActivity());
return JNI_TRUE == return_value;
}
void requestReview() {
ThreadAttacher attacher;
JNIEnv *env = attacher.env;
jclass cls = ClassLoader(env).load(JAR_PATH);
jmethodID method = env->GetStaticMethodID(cls, "requestReview", "(Landroid/app/Activity;)V");
env->CallStaticVoidMethod(cls, method, dmGraphics::GetNativeAndroidActivity());
}
}//namespace
#endif
| 28.903226
| 97
| 0.722098
|
dapetcu21
|
6290fc655f2607265e486f3f63eea181c565935e
| 2,537
|
cpp
|
C++
|
patched_D-ITG-2.8.1-r1023/src/ITGSend/newran/extreal.cpp
|
akhila-s-rao/high-fidelity-wireless-measurements
|
64bcaa9e0da5338b9495b63cd7aa67d94eaf3bf5
|
[
"Apache-2.0"
] | 4
|
2015-07-07T13:00:16.000Z
|
2021-02-25T13:03:25.000Z
|
patched_D-ITG-2.8.1-r1023/src/ITGSend/newran/extreal.cpp
|
akhila-s-rao/high-fidelity-wireless-measurements
|
64bcaa9e0da5338b9495b63cd7aa67d94eaf3bf5
|
[
"Apache-2.0"
] | 1
|
2022-02-04T08:43:41.000Z
|
2022-02-20T22:54:28.000Z
|
patched_D-ITG-2.8.1-r1023/src/ITGSend/newran/extreal.cpp
|
akhila-s-rao/high-fidelity-wireless-measurements
|
64bcaa9e0da5338b9495b63cd7aa67d94eaf3bf5
|
[
"Apache-2.0"
] | 2
|
2018-06-07T20:47:50.000Z
|
2020-07-20T09:55:04.000Z
|
/// \ingroup newran
///@{
/// \file extreal.cpp
/// "Extended real" - body file.
#define WANT_FSTREAM
#include "include.h"
#include "extreal.h"
#ifdef use_namespace
namespace RBD_COMMON {
#endif
ExtReal ExtReal::operator+(const ExtReal& er) const
{
if (c==Finite && er.c==Finite) return ExtReal(value+er.value);
if (c==Missing || er.c==Missing) return ExtReal(Missing);
if (c==Indefinite || er.c==Indefinite) return ExtReal(Indefinite);
if (c==PlusInfinity)
{
if (er.c==MinusInfinity) return ExtReal(Indefinite);
return *this;
}
if (c==MinusInfinity)
{
if (er.c==PlusInfinity) return ExtReal(Indefinite);
return *this;
}
return er;
}
ExtReal ExtReal::operator-(const ExtReal& er) const
{
if (c==Finite && er.c==Finite) return ExtReal(value-er.value);
if (c==Missing || er.c==Missing) return ExtReal(Missing);
if (c==Indefinite || er.c==Indefinite) return ExtReal(Indefinite);
if (c==PlusInfinity)
{
if (er.c==PlusInfinity) return ExtReal(Indefinite);
return *this;
}
if (c==MinusInfinity)
{
if (er.c==MinusInfinity) return ExtReal(Indefinite);
return *this;
}
return er;
}
ExtReal ExtReal::operator*(const ExtReal& er) const
{
if (c==Finite && er.c==Finite) return ExtReal(value*er.value);
if (c==Missing || er.c==Missing) return ExtReal(Missing);
if (c==Indefinite || er.c==Indefinite) return ExtReal(Indefinite);
if (c==Finite)
{
if (value==0.0) return ExtReal(Indefinite);
if (value>0.0) return er;
return (-er);
}
if (er.c==Finite)
{
if (er.value==0.0) return ExtReal(Indefinite);
if (er.value>0.0) return *this;
return -(*this);
}
if (c==PlusInfinity) return er;
return (-er);
}
ExtReal ExtReal::operator-() const
{
switch (c)
{
case Finite: return ExtReal(-value);
case PlusInfinity: return ExtReal(MinusInfinity);
case MinusInfinity: return ExtReal(PlusInfinity);
case Indefinite: return ExtReal(Indefinite);
case Missing: return ExtReal(Missing);
}
return 0.0;
}
ostream& operator<<(ostream& os, const ExtReal& er)
{
switch (er.c)
{
case Finite: os << er.value; break;
case PlusInfinity: os << "plus-infinity"; break;
case MinusInfinity: os << "minus-infinity"; break;
case Indefinite: os << "indefinite"; break;
case Missing: os << "missing"; break;
}
return os;
}
#ifdef use_namespace
}
#endif
///@}
| 24.161905
| 69
| 0.615294
|
akhila-s-rao
|
6292e28d9e2382ecb28c3f579b8c7f3d2219272a
| 1,215
|
hpp
|
C++
|
example/vgg16/vgg16.hpp
|
wzppengpeng/LittleConv
|
12aab4cfbbe965fa8b4053bb464db1165cc4ec31
|
[
"MIT"
] | 93
|
2017-10-25T07:48:42.000Z
|
2022-02-02T15:18:11.000Z
|
example/vgg16/vgg16.hpp
|
wzppengpeng/LittleConv
|
12aab4cfbbe965fa8b4053bb464db1165cc4ec31
|
[
"MIT"
] | null | null | null |
example/vgg16/vgg16.hpp
|
wzppengpeng/LittleConv
|
12aab4cfbbe965fa8b4053bb464db1165cc4ec31
|
[
"MIT"
] | 20
|
2018-02-06T10:01:36.000Z
|
2019-07-07T09:26:40.000Z
|
#ifndef VGG16_HPP
#define VGG16_HPP
#include "licon/licon.hpp"
using namespace licon;
// get the conv block
nn::NodePtr ConvBlock(int in_channel, int out_channel, bool triple = false) {
auto block = nn::Squential::CreateSquential();
block->Add(nn::Conv::CreateConv(in_channel, out_channel, 3, 1, 1));
block->Add(nn::BatchNorm::CreateBatchNorm(out_channel));
block->Add(nn::Relu::CreateRelu());
block->Add(nn::Conv::CreateConv(out_channel, out_channel, 3, 1, 1));
block->Add(nn::BatchNorm::CreateBatchNorm(out_channel));
block->Add(nn::Relu::CreateRelu());
if(triple) {
block->Add(nn::Conv::CreateConv(out_channel, out_channel, 3, 1, 1));
block->Add(nn::BatchNorm::CreateBatchNorm(out_channel));
block->Add(nn::Relu::CreateRelu());
}
block->Add(nn::MaxPool::CreateMaxPool(2));
return block;
}
nn::Model Vgg() {
auto net = nn::Squential::CreateSquential();
net->Add(ConvBlock(3, 16)); //16 * 16
net->Add(ConvBlock(16, 32)); //8 * 8
net->Add(ConvBlock(32, 64)); // 4 * 4
net->Add(ConvBlock(64, 128)); //2 * 2
net->Add(ConvBlock(128, 256)); //1 * 1
net->Add(nn::Linear::CreateLinear(256, 10));
return net;
}
#endif
| 32.837838
| 77
| 0.641152
|
wzppengpeng
|
62a6695ad70f068176da027d6b83b47de6814540
| 11,501
|
cpp
|
C++
|
src/goto-symex/memory_model_sc.cpp
|
dan-blank/yogar-cbmc
|
05b4f056b585b65828acf39546c866379dca6549
|
[
"MIT"
] | 1
|
2017-07-25T02:44:56.000Z
|
2017-07-25T02:44:56.000Z
|
src/goto-symex/memory_model_sc.cpp
|
dan-blank/yogar-cbmc
|
05b4f056b585b65828acf39546c866379dca6549
|
[
"MIT"
] | 1
|
2017-02-22T14:35:19.000Z
|
2017-02-27T08:49:58.000Z
|
src/goto-symex/memory_model_sc.cpp
|
dan-blank/yogar-cbmc
|
05b4f056b585b65828acf39546c866379dca6549
|
[
"MIT"
] | 4
|
2019-01-19T03:32:21.000Z
|
2021-12-20T14:25:19.000Z
|
/*******************************************************************\
Module: Memory model for partial order concurrency
Author: Michael Tautschnig, michael.tautschnig@cs.ox.ac.uk
\*******************************************************************/
#include <util/std_expr.h>
#include <util/i2string.h>
#include "memory_model_sc.h"
#include <iostream>
/*******************************************************************\
Function: memory_model_sct::operator()
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void memory_model_sct::operator()(symex_target_equationt &equation)
{
print(8, "Adding SC constraints");
build_event_lists(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n";
build_clock_type(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n";
set_events_ssa_id(equation);
read_from(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n";
// read_from_backup(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n";
// write_serialization_external(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n";
// program_order(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n";
// from_read(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n";
}
/*******************************************************************\
Function: memory_model_sct::before
Inputs:
Outputs:
Purpose:
\*******************************************************************/
exprt memory_model_sct::before(event_it e1, event_it e2)
{
return partial_order_concurrencyt::before(
e1, e2, AX_PROPAGATION);
}
/*******************************************************************\
Function: memory_model_sct::program_order_is_relaxed
Inputs:
Outputs:
Purpose:
\*******************************************************************/
bool memory_model_sct::program_order_is_relaxed(
partial_order_concurrencyt::event_it e1,
partial_order_concurrencyt::event_it e2) const
{
assert(is_shared_read(e1) || is_shared_write(e1));
assert(is_shared_read(e2) || is_shared_write(e2));
return false;
}
/*******************************************************************\
Function: memory_model_sct::build_per_thread_map
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void memory_model_sct::build_per_thread_map(
const symex_target_equationt &equation,
per_thread_mapt &dest) const
{
// this orders the events within a thread
for(eventst::const_iterator
e_it=equation.SSA_steps.begin();
e_it!=equation.SSA_steps.end();
e_it++)
{
// concurreny-related?
if(!is_shared_read(e_it) &&
!is_shared_write(e_it) &&
!is_spawn(e_it) &&
!is_memory_barrier(e_it)) continue;
dest[e_it->source.thread_nr].push_back(e_it);
}
}
/*******************************************************************\
Function: memory_model_sct::thread_spawn
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void memory_model_sct::thread_spawn(
symex_target_equationt &equation,
const per_thread_mapt &per_thread_map)
{
// thread spawn: the spawn precedes the first
// instruction of the new thread in program order
unsigned next_thread_id=0;
for(eventst::const_iterator
e_it=equation.SSA_steps.begin();
e_it!=equation.SSA_steps.end();
e_it++)
{
if(is_spawn(e_it))
{
per_thread_mapt::const_iterator next_thread=
per_thread_map.find(++next_thread_id);
if(next_thread==per_thread_map.end()) continue;
// For SC and several weaker memory models a memory barrier
// at the beginning of a thread can simply be ignored, because
// we enforce program order in the thread-spawn constraint
// anyway. Memory models with cumulative memory barriers
// require explicit handling of these.
event_listt::const_iterator n_it=next_thread->second.begin();
for( ;
n_it!=next_thread->second.end() &&
(*n_it)->is_memory_barrier();
++n_it)
;
if(n_it!=next_thread->second.end())
std::cout << "PO: (" << e_it->ssa_lhs.get_identifier() << ", " << (*n_it)->ssa_lhs.get_identifier() << ") \n";
add_constraint(
equation,
before(e_it, *n_it),
"thread-spawn",
e_it->source);
}
}
}
/*******************************************************************\
Function: memory_model_sct::program_order
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void memory_model_sct::program_order(
symex_target_equationt &equation)
{
per_thread_mapt per_thread_map;
build_per_thread_map(equation, per_thread_map);
thread_spawn(equation, per_thread_map);
// iterate over threads
int num = 0;
int tt = 0;
for(per_thread_mapt::const_iterator
t_it=per_thread_map.begin();
t_it!=per_thread_map.end();
t_it++)
{
// std::cout << "======== begin thread " << num << "===========\n";
const event_listt &events=t_it->second;
// iterate over relevant events in the thread
event_it previous=equation.SSA_steps.end();
for(event_listt::const_iterator
e_it=events.begin();
e_it!=events.end();
e_it++)
{
if(is_memory_barrier(*e_it))
continue;
if(previous==equation.SSA_steps.end())
{
// first one?
previous=*e_it;
continue;
}
// std::cout << tt << "PO: (" << previous->ssa_lhs.get_identifier() << ", " << (*e_it)->ssa_lhs.get_identifier() << ") \n";
add_constraint(
equation,
before(previous, *e_it),
"po",
(*e_it)->source);
previous=*e_it;
}
// std::cout << "======== end thread " << num++ << "===========\n";
}
}
/*******************************************************************\
Function: memory_model_sct::write_serialization_external
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void memory_model_sct::write_serialization_external(
symex_target_equationt &equation)
{
for(address_mapt::const_iterator
a_it=address_map.begin();
a_it!=address_map.end();
a_it++)
{
const a_rect &a_rec=a_it->second;
// This is quadratic in the number of writes
// per address. Perhaps some better encoding
// based on 'places'?
for(event_listt::const_iterator
w_it1=a_rec.writes.begin();
w_it1!=a_rec.writes.end();
++w_it1)
{
event_listt::const_iterator next=w_it1;
++next;
for(event_listt::const_iterator w_it2=next;
w_it2!=a_rec.writes.end();
++w_it2)
{
// external?
if((*w_it1)->source.thread_nr==
(*w_it2)->source.thread_nr)
continue;
// ws is a total order, no two elements have the same rank
// s -> w_evt1 before w_evt2; !s -> w_evt2 before w_evt1
symbol_exprt s=nondet_bool_symbol("ws-ext");
// write-to-write edge
add_constraint(
equation,
implies_exprt(s, before(*w_it1, *w_it2)),
"ws-ext",
(*w_it1)->source);
add_constraint(
equation,
implies_exprt(not_exprt(s), before(*w_it2, *w_it1)),
"ws-ext",
(*w_it1)->source);
}
}
}
}
/*******************************************************************\
Function: memory_model_sct::from_read
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void memory_model_sct::from_read(symex_target_equationt &equation)
{
// from-read: (w', w) in ws and (w', r) in rf -> (r, w) in fr
for(address_mapt::const_iterator
a_it=address_map.begin();
a_it!=address_map.end();
a_it++)
{
const a_rect &a_rec=a_it->second;
// This is quadratic in the number of writes per address.
for(event_listt::const_iterator
w_prime=a_rec.writes.begin();
w_prime!=a_rec.writes.end();
++w_prime)
{
event_listt::const_iterator next=w_prime;
++next;
for(event_listt::const_iterator w=next;
w!=a_rec.writes.end();
++w)
{
exprt ws1, ws2;
if(po(*w_prime, *w) &&
!program_order_is_relaxed(*w_prime, *w))
{
ws1=true_exprt();
ws2=false_exprt();
}
else if(po(*w, *w_prime) &&
!program_order_is_relaxed(*w, *w_prime))
{
ws1=false_exprt();
ws2=true_exprt();
}
else
{
ws1=before(*w_prime, *w);
ws2=before(*w, *w_prime);
}
// smells like cubic
for(choice_symbolst::const_iterator
c_it=choice_symbols.begin();
c_it!=choice_symbols.end();
c_it++)
{
event_it r=c_it->first.first;
exprt rf=c_it->second;
exprt cond;
cond.make_nil();
if(c_it->first.second==*w_prime && !ws1.is_false())
{
exprt fr=before(r, *w);
// the guard of w_prime follows from rf; with rfi
// optimisation such as the previous write_symbol_primed
// it would even be wrong to add this guard
cond=
implies_exprt(
and_exprt(r->guard, (*w)->guard, ws1, rf),
fr);
}
else if(c_it->first.second==*w && !ws2.is_false())
{
exprt fr=before(r, *w_prime);
// the guard of w follows from rf; with rfi
// optimisation such as the previous write_symbol_primed
// it would even be wrong to add this guard
cond=
implies_exprt(
and_exprt(r->guard, (*w_prime)->guard, ws2, rf),
fr);
}
if(cond.is_not_nil())
add_constraint(equation,
cond, "fr", r->source);
}
}
}
}
}
void memory_model_sct::get_symbols(const exprt &expr, std::vector<symbol_exprt>& symbols)
{
forall_operands(it, expr)
get_symbols(*it, symbols);
if(expr.id()==ID_symbol)
symbols.push_back(to_symbol_expr(expr));
}
void memory_model_sct::set_events_ssa_id(symex_target_equationt &equation)
{
int id = 0;
for(eventst::iterator
e_it=equation.SSA_steps.begin();
e_it!=equation.SSA_steps.end();
e_it++)
{
if(e_it->is_assignment())
{
unsigned event_num = 0;
std::vector<symbol_exprt> symbols;
get_symbols(e_it->cond_expr, symbols);
for (unsigned i = 0; i < symbols.size(); i++)
{
unsigned result = set_single_event_ssa_id(equation, symbols[i], id);
event_num += result;
}
if (event_num > 0)
e_it->event_flag = true;
}
id++;
}
}
unsigned memory_model_sct::set_single_event_ssa_id(symex_target_equationt &equation, symbol_exprt event, int id)
{
for(eventst::iterator
e_it=equation.SSA_steps.begin();
e_it!=equation.SSA_steps.end();
e_it++)
{
if ((e_it->is_shared_read() || e_it->is_shared_write()))
{
if (e_it->ssa_lhs.get_identifier() == event.get_identifier())
{
e_it->appear_ssa_id = id;
return 1;
}
}
}
return 0;
}
| 25.332599
| 125
| 0.537692
|
dan-blank
|
62abb37eaa85a0249284ab8ff4fe48f8b94351ba
| 2,567
|
cpp
|
C++
|
common/util/src/TokenRateLimiter.cpp
|
ewb4/HDTN
|
a0e577351bd28c3aeb7e656e03a2d93cf84712a0
|
[
"NASA-1.3"
] | null | null | null |
common/util/src/TokenRateLimiter.cpp
|
ewb4/HDTN
|
a0e577351bd28c3aeb7e656e03a2d93cf84712a0
|
[
"NASA-1.3"
] | null | null | null |
common/util/src/TokenRateLimiter.cpp
|
ewb4/HDTN
|
a0e577351bd28c3aeb7e656e03a2d93cf84712a0
|
[
"NASA-1.3"
] | null | null | null |
#include "TokenRateLimiter.h"
#include <iostream>
TokenRateLimiter::TokenRateLimiter() : m_rateTokens(0), m_limit(0), m_remain(0) {}
TokenRateLimiter::~TokenRateLimiter() {}
void TokenRateLimiter::SetRate(const uint64_t tokens, const boost::posix_time::time_duration & interval, const boost::posix_time::time_duration & window) {
if (interval.is_special()) {
return;
}
m_rateTokens = tokens;
m_rateInterval = interval;
m_limit = m_rateTokens * window.ticks();
m_remain = m_limit;
}
void TokenRateLimiter::AddTime(const boost::posix_time::time_duration & interval) {
if (interval.is_special()) {
return;
}
const uint64_t delta = m_rateTokens * interval.ticks();
m_remain += delta;
if (m_remain > m_limit) {
m_remain = m_limit;
}
}
uint64_t TokenRateLimiter::GetRemainingTokens() const {
return m_remain / m_rateInterval.ticks();
}
bool TokenRateLimiter::HasFullBucketOfTokens() const {
return (m_remain == m_limit);
}
bool TokenRateLimiter::TakeTokens(const uint64_t tokens) {
const uint64_t delta = tokens * m_rateInterval.ticks();
if (delta > m_remain) {
return false;
}
m_remain -= delta;
return true;
}
BorrowableTokenRateLimiter::BorrowableTokenRateLimiter() : m_rateTokens(0), m_limit(0), m_remain(0) {}
BorrowableTokenRateLimiter::~BorrowableTokenRateLimiter() {}
void BorrowableTokenRateLimiter::SetRate(const int64_t tokens, const boost::posix_time::time_duration & interval, const boost::posix_time::time_duration & window) {
if (interval.is_special()) {
return;
}
m_rateTokens = tokens;
m_rateInterval = interval;
m_limit = m_rateTokens * window.ticks();
m_remain = m_limit;
}
void BorrowableTokenRateLimiter::AddTime(const boost::posix_time::time_duration & interval) {
if (interval.is_special()) {
return;
}
const int64_t delta = m_rateTokens * interval.ticks();
m_remain += delta;
if (m_remain > m_limit) {
m_remain = m_limit;
}
}
int64_t BorrowableTokenRateLimiter::GetRemainingTokens() const {
return m_remain / m_rateInterval.ticks();
}
bool BorrowableTokenRateLimiter::HasFullBucketOfTokens() const {
return (m_remain == m_limit);
}
bool BorrowableTokenRateLimiter::TakeTokens(const uint64_t tokens) {
if(m_remain < 0) {
return false;
}
const int64_t delta = tokens * m_rateInterval.ticks();
m_remain -= delta;
return true;
}
bool BorrowableTokenRateLimiter::CanTakeTokens() const {
return (m_remain >= 0);
}
| 26.463918
| 164
| 0.695754
|
ewb4
|
62acd74a7eae39c649b5709498645dad6fba7850
| 3,191
|
cpp
|
C++
|
plugins/libimhex/source/helpers/lang.cpp
|
Laxer3a/psdebugtool
|
41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb
|
[
"MIT"
] | 4
|
2021-05-09T23:33:54.000Z
|
2022-03-06T10:16:31.000Z
|
plugins/libimhex/source/helpers/lang.cpp
|
Laxer3a/psdebugtool
|
41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb
|
[
"MIT"
] | null | null | null |
plugins/libimhex/source/helpers/lang.cpp
|
Laxer3a/psdebugtool
|
41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb
|
[
"MIT"
] | 6
|
2021-05-09T21:41:48.000Z
|
2021-09-08T10:54:28.000Z
|
#include "hex/helpers/lang.hpp"
#include "hex/helpers/shared_data.hpp"
namespace hex {
LanguageDefinition::LanguageDefinition(std::initializer_list<std::pair<std::string, std::string>> entries) {
for (auto pair : entries)
this->m_entries.insert(pair);
}
const std::map<std::string, std::string>& LanguageDefinition::getEntries() const {
return this->m_entries;
}
LangEntry::LangEntry(const char *unlocalizedString) : m_unlocalizedString(unlocalizedString) { }
LangEntry::LangEntry(const std::string &unlocalizedString) : m_unlocalizedString(unlocalizedString) { }
LangEntry::LangEntry(std::string_view unlocalizedString) : m_unlocalizedString(unlocalizedString) { }
LangEntry::operator std::string() const {
return std::string(get());
}
LangEntry::operator std::string_view() const {
return get();
}
LangEntry::operator const char*() const {
return get().data();
}
std::string operator+(const std::string &&left, const LangEntry &&right) {
return left + static_cast<std::string>(right);
}
std::string operator+(const LangEntry &&left, const std::string &&right) {
return static_cast<std::string>(left) + right;
}
std::string operator+(const LangEntry &&left, const LangEntry &&right) {
return static_cast<std::string>(left) + static_cast<std::string>(right);
}
std::string operator+(const std::string_view &&left, const LangEntry &&right) {
return std::string(left) + static_cast<std::string>(right);
}
std::string operator+(const LangEntry &&left, const std::string_view &&right) {
return static_cast<std::string>(left) + std::string(right);
}
std::string operator+(const char *left, const LangEntry &&right) {
return left + static_cast<std::string>(right);
}
std::string operator+(const LangEntry &&left, const char *right) {
return static_cast<std::string>(left) + right;
}
std::string_view LangEntry::get() const {
auto &lang = SharedData::loadedLanguageStrings;
if (lang.find(this->m_unlocalizedString) != lang.end())
return lang[this->m_unlocalizedString];
else
return this->m_unlocalizedString;
}
void LangEntry::loadLanguage(std::string_view language) {
constexpr auto DefaultLanguage = "en-US";
SharedData::loadedLanguageStrings.clear();
auto &definitions = ContentRegistry::Language::getLanguageDefinitions();
if (!definitions.contains(language.data()))
return;
for (auto &definition : definitions[language.data()])
SharedData::loadedLanguageStrings.insert(definition.getEntries().begin(), definition.getEntries().end());
if (language != DefaultLanguage) {
for (auto &definition : definitions[DefaultLanguage])
SharedData::loadedLanguageStrings.insert(definition.getEntries().begin(), definition.getEntries().end());
}
}
const std::map<std::string, std::string>& LangEntry::getSupportedLanguages() {
return ContentRegistry::Language::getLanguages();
}
}
| 35.065934
| 121
| 0.655907
|
Laxer3a
|
62acf418bcf9c8a2720f202b27b4b065944b3730
| 1,416
|
cpp
|
C++
|
solved-uva/10583.cpp
|
Maruf-Tuhin/Online_Judge
|
cf9b2a522e8b1a9623d3996a632caad7fd67f751
|
[
"MIT"
] | 1
|
2019-03-31T05:47:30.000Z
|
2019-03-31T05:47:30.000Z
|
solved-uva/10583.cpp
|
the-redback/competitive-programming
|
cf9b2a522e8b1a9623d3996a632caad7fd67f751
|
[
"MIT"
] | null | null | null |
solved-uva/10583.cpp
|
the-redback/competitive-programming
|
cf9b2a522e8b1a9623d3996a632caad7fd67f751
|
[
"MIT"
] | null | null | null |
/**
* @author : Maruf Tuhin
* @School : CUET CSE 11
* @TOPCODER : the_redback
* @CodeForces : the_redback
* @UVA : Redback
* @link : http://www.fb.com/maruf.2hin
*/
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
#include<set>
#include<sstream>
#include<stack>
using namespace std;
#define inf 10000000
#define mem(a,b) memset(a,b,sizeof(a))
#define NN 50000
int prnt[NN+7];
int a[NN+7];
int root(int n)
{
if(prnt[n]==n)
return n;
return root(prnt[n]);
}
main()
{
//freopen("C:\\Users\\Maruf Tuhin\\Desktop\\in.txt","r",stdin);
//ios_base::sync_with_stdio(false);
int i,j,k,l,n,r,c,count;
int tc,t=1;
//scanf("%d",&tc);
while(~scanf("%d%d",&n,&r))
{
if(n==0 && r==0)
return 0;
for(i=1;i<=n;i++)
prnt[i]=i;
while(r--)
{
scanf("%d%d",&k,&l);
int u=root(k);
int v=root(l);
if(u!=v)
prnt[u]=v;
}
mem(a,0);
count=0;
for(i=1;i<=n;i++)
{
int u=root(i);
if(a[u]==0)
count++;
a[u]=1;
}
printf("Case %d: %d\n",t++,count);
}
return 0;
}
| 19.39726
| 67
| 0.484463
|
Maruf-Tuhin
|
62b96cc0e71367910cf61c48ca64a1ca20e1e487
| 826
|
cpp
|
C++
|
src/MdCharm/util/updatetocthread.cpp
|
MonkeyMo/MdCharm
|
78799f0bd85603aae9361b4fca05384a69f690e6
|
[
"BSD-3-Clause"
] | 387
|
2015-01-01T17:51:59.000Z
|
2021-06-13T19:40:15.000Z
|
src/MdCharm/util/updatetocthread.cpp
|
MonkeyMo/MdCharm
|
78799f0bd85603aae9361b4fca05384a69f690e6
|
[
"BSD-3-Clause"
] | 26
|
2015-01-09T08:36:26.000Z
|
2020-04-02T12:51:01.000Z
|
src/MdCharm/util/updatetocthread.cpp
|
heefan/MdCharm
|
78799f0bd85603aae9361b4fca05384a69f690e6
|
[
"BSD-3-Clause"
] | 145
|
2015-01-10T18:07:45.000Z
|
2021-09-14T07:39:35.000Z
|
// Copyright (c) 2014 zhangshine. All rights reserved.
// Use of this source code is governed by a BSD license that can be
// found in the LICENSE file.
#include "updatetocthread.h"
UpdateTocThread::UpdateTocThread(QObject *parent) :
QThread(parent)
{
}
void UpdateTocThread::run()
{
if(this->type == MarkdownToHtml::MultiMarkdown){
emit workerResult(QString());
} else {
std::string stdResult;
QByteArray content = this->content.toUtf8();
MarkdownToHtml::renderMarkdownExtarToc(this->type, content.data(), content.length(), stdResult);
emit workerResult(QString::fromUtf8(stdResult.c_str(), stdResult.length()));
}
}
void UpdateTocThread::setContent(MarkdownToHtml::MarkdownType type, const QString &content)
{
this->type = type;
this->content = content;
}
| 28.482759
| 104
| 0.696126
|
MonkeyMo
|
62be39df916655715856391362c1bee44d19356f
| 485
|
cpp
|
C++
|
Luogu/P1115/P1115.cpp
|
AtomAlpaca/OI-Codes
|
11f8dd4798616f1937d190e7220d7eedaeb75169
|
[
"WTFPL"
] | 1
|
2021-11-12T14:19:53.000Z
|
2021-11-12T14:19:53.000Z
|
Luogu/P1115/P1115.cpp
|
AtomAlpaca/OI-Codes
|
11f8dd4798616f1937d190e7220d7eedaeb75169
|
[
"WTFPL"
] | null | null | null |
Luogu/P1115/P1115.cpp
|
AtomAlpaca/OI-Codes
|
11f8dd4798616f1937d190e7220d7eedaeb75169
|
[
"WTFPL"
] | null | null | null |
#include <iostream>
#include <cmath>
#include <algorithm>
using std::cin;
using std::cout;
int main(int argc, char const *argv[])
{
//int m = -10000000;
int * n = new int;
cin >> *n;
int nums[*n + 1] = {0};
int ans [*n + 1] = {0};
int m = -99999999;
for (int i = 1; i <= *n; ++i)
{
cin >> nums[i];
ans[i] = std::max(ans[i - 1] + nums[i], nums[i]);
m = std::max(m, ans[i]);
}
cout << m;
delete n;
return 0;
}
| 16.724138
| 57
| 0.463918
|
AtomAlpaca
|
62be72f300f0bc4e7c0f81203ee26c504a78719b
| 6,270
|
cpp
|
C++
|
src/main.cpp
|
cowdingus/SFML-Grapher
|
47d0e661aa9c411d9a41f4fe8f4df7860af7ec74
|
[
"Unlicense"
] | 1
|
2021-01-26T09:52:41.000Z
|
2021-01-26T09:52:41.000Z
|
src/main.cpp
|
cowdingus/SFML-Grapher
|
47d0e661aa9c411d9a41f4fe8f4df7860af7ec74
|
[
"Unlicense"
] | 1
|
2020-11-10T06:54:07.000Z
|
2020-11-10T11:40:53.000Z
|
src/main.cpp
|
cowdingus/SFML-Grapher
|
47d0e661aa9c411d9a41f4fe8f4df7860af7ec74
|
[
"Unlicense"
] | null | null | null |
/*
* ToDo:
* look at @setSize implementation
* fix bugs
*
* Bugs Found:
* crashes and hangs the whole computer when setting zoom value to some little value
*/
#include "CartesianGraphView.hpp"
#include "CartesianGrid.hpp"
#include "DotGraph.hpp"
#include <SFML/Graphics.hpp>
#include <SFML/Window/ContextSettings.hpp>
#include <iostream>
#include <cassert>
template<typename T>
std::ostream& operator<<(std::ostream& out, const sf::Vector2<T>& vector)
{
return out << "{" << vector.x << ", " << vector.y << "}";
}
template<typename T>
std::ostream& operator<<(std::ostream& out, const sf::Rect<T>& rect)
{
return out << "{" << rect.left << ", " << rect.top << ", " << rect.width << ", " << rect.height << "}" << std::endl;
}
std::ostream& operator<<(std::ostream& out, const sf::Transform& transform)
{
const float* m = transform.getMatrix();
out << "[" << m[0] << '\t' << m[4] << '\t' << m[8 ] << '\t' << m[12] << '\t' << "]" << std::endl
<< "[" << m[1] << '\t' << m[5] << '\t' << m[9 ] << '\t' << m[13] << '\t' << "]" << std::endl
<< "[" << m[2] << '\t' << m[6] << '\t' << m[10] << '\t' << m[14] << '\t' << "]" << std::endl
<< "[" << m[3] << '\t' << m[7] << '\t' << m[11] << '\t' << m[15] << '\t' << "]" << std::endl;
return out;
}
int main()
{
sf::ContextSettings settings;
settings.antialiasingLevel = 4;
sf::RenderWindow window(sf::VideoMode(800, 600), "NULL", sf::Style::Default, settings);
window.setFramerateLimit(15);
{
std::cout << "Graph Tests" << std::endl;
DotGraph lg;
lg.addPoint({1, 1});
assert(lg.getPoint(0) == sf::Vector2f(1, 1));
lg.removePoint(0);
assert(lg.getPointsCount() == 0);
lg.addPoint({1, 1});
assert(lg.getPoint(0) == sf::Vector2f(1, 1));
lg.clearPoints();
assert(lg.getPointsCount() == 0);
std::cout << "Graph Data Insertion/Deletion Tests Passed" << std::endl;
lg.setGridColor(sf::Color::White);
assert(lg.getGridColor() == sf::Color::White);
lg.setGridGap({10, 10});
assert(lg.getGridGap() == sf::Vector2f(10, 10));
lg.setColor(sf::Color::Black);
assert(lg.getColor() == sf::Color::Black);
CartesianGraphView view = lg.getView();
view.setViewRect({0, 0, 10, 10});
lg.setView(view);
std::cout << lg.getView().getViewRect() << std::endl;
assert(lg.getView().getViewRect() == sf::FloatRect(0, 0, 10, 10));
std::cout << "Visual Properties Tests Passed" << std::endl;
}
{
std::cout << "Graph View Tests" << std::endl;
CartesianGraphView view;
view.setCenter({100, 100});
assert(view.getCenter() == sf::Vector2f(100, 100));
view.setSize({100, 100});
assert(view.getSize() == sf::Vector2f(100, 100));
view.setViewRect({0, 0, 10, 10});
assert(view.getViewRect() == sf::FloatRect(0, 0, 10, 10));
assert(view.getCenter() == sf::Vector2f(5, 5));
assert(view.getSize() == sf::Vector2f(10, 10));
view.setCenter({10, 10});
assert(view.getCenter() == sf::Vector2f(10, 10));
view.setSize({10, 10});
assert(view.getSize() == sf::Vector2f(10, 10));
view.setZoom({10, 10});
assert(view.getZoom() == sf::Vector2f(10, 10));
view = CartesianGraphView();
view.setCenter({1, 1});
view.setSize({2, 2});
std::cout << view.getTransform() * sf::Vector2f(0, 0) << std::endl;
assert(view.getTransform() * sf::Vector2f(0, 0) == sf::Vector2f(0, 0));
}
std::cout << "All Tests Passed" << std::endl << std::endl;
DotGraph lg({400, 400});
lg.setPosition(100, 100);
lg.addPoint({0, 0});
lg.addPoint({-1, 0});
lg.addPoint({1, 0});
lg.addPoint({0, -1});
lg.addPoint({0, 1});
lg.addPoint({0, 2});
lg.addPoint({-3, 0});
lg.setGridGap({1, 1});
lg.setGridColor(sf::Color(100, 100, 100));
CartesianGraphView lgv;
lgv.setCenter({-2, -2});
lgv.setSize({8, 8});
lgv.setViewRect({-2, -2, 8, 8});
lgv.setCenter({0, 0});
lgv.setSize({10, 10});
lgv.setZoom({2,1});
lg.setView(lgv);
lg.setSize({200, 200});
lg.setColor(sf::Color::Cyan);
sf::RectangleShape boundingBox;
boundingBox.setSize(static_cast<sf::Vector2f>(lg.getSize()));
boundingBox.setPosition({100, 100});
boundingBox.setOutlineThickness(1);
boundingBox.setOutlineColor(sf::Color::Magenta);
boundingBox.setFillColor(sf::Color(0, 0, 0, 0));
sf::Font arial;
if (!arial.loadFromFile("debug/Arial.ttf"))
{
sf::err() << "Error: Can't load font file" << std::endl;
}
sf::Text keymapGuide;
keymapGuide.setString(
"[M] to zoom in\n"
"[N] to zoom out\n"
"[Arrow keys] to move graph\n"
"[W | A | S | D] to move view\n"
);
keymapGuide.setFont(arial);
keymapGuide.setCharacterSize(12);
keymapGuide.setFillColor(sf::Color::White);
keymapGuide.setPosition(
{
window.getSize().x - keymapGuide.getGlobalBounds().width,
window.getSize().y - keymapGuide.getGlobalBounds().height
}
);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
{
window.close();
break;
}
case sf::Event::KeyPressed:
{
sf::View newView = window.getView();
CartesianGraphView graphView = lg.getView();
switch (event.key.code)
{
case sf::Keyboard::W:
newView.move(0, -10);
break;
case sf::Keyboard::S:
newView.move(0, 10);
break;
case sf::Keyboard::A:
newView.move(-10, 0);
break;
case sf::Keyboard::D:
newView.move(10, 0);
break;
case sf::Keyboard::Up:
graphView.move({0, 0.1});
break;
case sf::Keyboard::Down:
graphView.move({0, -0.1});
break;
case sf::Keyboard::Left:
graphView.move({-0.1, 0});
break;
case sf::Keyboard::Right:
graphView.move({0.1, 0});
break;
case sf::Keyboard::M:
if (graphView.getZoom().x < 3 && graphView.getZoom().y < 3)
graphView.setZoom(graphView.getZoom() + sf::Vector2f(0.1f, 0.1f));
break;
case sf::Keyboard::N:
if (graphView.getZoom().x > 1 && graphView.getZoom().y > 1)
graphView.setZoom(graphView.getZoom() - sf::Vector2f(0.1f, 0.1f));
break;
default:
break;
}
lg.setView(graphView);
window.setView(newView);
break;
}
default:
{
break;
}
}
}
lg.update();
window.clear();
window.draw(lg);
window.draw(boundingBox);
window.draw(keymapGuide);
window.display();
}
}
| 24.782609
| 117
| 0.59378
|
cowdingus
|
498329ce67e1973db69564b5ac7ac9288d12e1be
| 988
|
hpp
|
C++
|
CTCWordBeamSearch-master/cpp/DataLoader.hpp
|
brucegrapes/htr
|
9f8f07173ccc740dd8a4dfc7e8038abe36664756
|
[
"MIT"
] | 488
|
2018-03-01T11:18:26.000Z
|
2022-03-10T09:29:32.000Z
|
CTCWordBeamSearch-master/cpp/DataLoader.hpp
|
brucegrapes/htr
|
9f8f07173ccc740dd8a4dfc7e8038abe36664756
|
[
"MIT"
] | 60
|
2018-03-10T18:37:51.000Z
|
2022-03-30T19:37:18.000Z
|
CTCWordBeamSearch-master/cpp/DataLoader.hpp
|
brucegrapes/htr
|
9f8f07173ccc740dd8a4dfc7e8038abe36664756
|
[
"MIT"
] | 152
|
2018-03-01T11:18:25.000Z
|
2022-03-08T23:37:46.000Z
|
#pragma once
#include "MatrixCSV.hpp"
#include "LanguageModel.hpp"
#include <string>
#include <vector>
#include <memory>
#include <stdint.h>
#include <cstddef>
// load sample data, create LM from it, iterate over samples
class DataLoader
{
public:
// sample with matrix to be decoded and ground truth text
struct Data
{
MatrixCSV mat;
std::vector<uint32_t> gt;
};
// CTOR. Path points to directory holding files corpus.txt, chars.txt, wordChars.txt and samples mat_X.csv and gt_X.txt with X in {0, 1, 2, ...}
DataLoader(const std::string& path, size_t sampleEach, LanguageModelType lmType, double addK=0.0);
// get LM
std::shared_ptr<LanguageModel> getLanguageModel() const;
// iterator interface
Data getNext() const;
bool hasNext() const;
private:
std::string m_path;
std::shared_ptr<LanguageModel> m_lm;
mutable size_t m_currIdx=0;
const size_t m_sampleEach = 1;
void applySoftmax(MatrixCSV& mat) const;
bool fileExists(const std::string& path) const;
};
| 22.976744
| 145
| 0.733806
|
brucegrapes
|
498f94159e65d0f63e199e4534264d92426142da
| 434
|
cpp
|
C++
|
source/Ch08/orai_anyag/vector_pass_by.cpp
|
Vada200/UDProg-Introduction
|
c424b2676d6e5bfc4d53d61c5d0deded566c1c84
|
[
"CC0-1.0"
] | null | null | null |
source/Ch08/orai_anyag/vector_pass_by.cpp
|
Vada200/UDProg-Introduction
|
c424b2676d6e5bfc4d53d61c5d0deded566c1c84
|
[
"CC0-1.0"
] | null | null | null |
source/Ch08/orai_anyag/vector_pass_by.cpp
|
Vada200/UDProg-Introduction
|
c424b2676d6e5bfc4d53d61c5d0deded566c1c84
|
[
"CC0-1.0"
] | null | null | null |
#include "std_lib_facilities.h"
void print (vector <double>& v)
//& -->referencia miatt gyorsabb a lefutás
//mert nem másolódik a v, hanem a v ugyanaz lesz mint a vd1
{
cout << "{";
for (int i = 0; i < v.size(); i++)
{
cout << v[i];
if(i < v.size()-1) cout << ",";
}
cout << "}\n";
}
int main()
{
vector <double> vd1 (10);
vector <double> vd2 (100000);
print(vd2);
return 0;
}
| 16.692308
| 60
| 0.520737
|
Vada200
|
499ad331e198929ca8c0116e353dc02b3e64887b
| 14,774
|
cpp
|
C++
|
src/program_options.cpp
|
WenbinHou/xcp-old
|
e1efbebe625e379189d82b4641e575849fbcf628
|
[
"MIT"
] | 1
|
2020-09-10T19:50:38.000Z
|
2020-09-10T19:50:38.000Z
|
src/program_options.cpp
|
WenbinHou/xcp-old
|
e1efbebe625e379189d82b4641e575849fbcf628
|
[
"MIT"
] | null | null | null |
src/program_options.cpp
|
WenbinHou/xcp-old
|
e1efbebe625e379189d82b4641e575849fbcf628
|
[
"MIT"
] | 1
|
2020-07-14T05:10:22.000Z
|
2020-07-14T05:10:22.000Z
|
#include "common.h"
//==============================================================================
// struct host_path
//==============================================================================
bool xcp::host_path::parse(const std::string& value)
{
// Handle strings like:
// "relative"
// "relative/subpath"
// "/absolute/path"
// "C:" (on Windows)
// "C:\" (on Windows)
// "C:/" (on Windows)
// "C:\absolute\path" (on Windows)
// "C:/absolute\path" (on Windows)
// "relative\subpath"
// "hostname:/"
// "hostname:/absolute"
// "127.0.0.1:C:"
// "1.2.3.4:C:\"
// "1.2.3.4:C:/"
// "[::1]:C:\absolute"
// "[1:2:3:4:5:6:7:8]:C:/absolute"
//
// NOTE:
// Remote path MUST be absolute
// Local path might be absolute or relative
// See:
// https://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
// https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
// NOTE: re_valid_hostname matches a superset of valid IPv4
static std::regex* __re = nullptr;
if (__re == nullptr) {
const std::string re_valid_hostname = R"((?:(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*(?:[A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])))";
const std::string re_valid_ipv6 = R"((?:\[(?:(?:[0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,7}:|(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})|:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)|::(?:[Ff]{4}(?::0{1,4})?:)?(?:(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9])|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9]))\]))";
const std::string re_valid_host = "(?:" + re_valid_hostname + "|" + re_valid_ipv6 + ")";
const std::string re_valid_host_path = "^(?:(?:([^@:]+)@)?(" + re_valid_host + "):)?((?:^.+)|(?:.*))$";
__re = new std::regex(re_valid_host_path, std::regex::optimize);
}
if (value.empty()) return false;
//
// Special handling for Windows driver letters (local path)
//
#if PLATFORM_WINDOWS || PLATFORM_CYGWIN
if (value.size() >= 2 && value[1] == ':') {
if ((value[0] >= 'A' && value[0] <= 'Z') || (value[0] >= 'a' && value[0] <= 'z')) {
if (value.size() == 2 || value[2] == '/' || value[2] == '\\') {
user.reset();
host.reset();
path = value;
return true;
}
}
}
#elif PLATFORM_LINUX
#else
# error "Unknown platform"
#endif
std::smatch match;
if (!std::regex_match(value, match, *__re)) {
return false;
}
{
// The user part
std::string tmp(match[1].str());
if (tmp.empty())
user.reset();
else
user= std::move(tmp);
}
{
// The host part
// NOTE: If host is IPv6 surrounded by '[' ']', DO NOT trim the beginning '[' and ending ']'
std::string tmp(match[2].str());
if (tmp.empty())
host.reset();
else
host = std::move(tmp);
}
{
path = match[3].str();
if (path.empty()) {
if (!host.has_value()) {
return false;
}
else {
path = "~";
}
}
}
return true;
}
//==============================================================================
// struct base_program_options
//==============================================================================
void xcp::base_program_options::add_options(CLI::App& app)
{
app.add_flag(
"-V,--version",
[&](const size_t /*count*/) {
printf("Version %d.%d.%d\nGit branch %s commit %s\n",
XCP_VERSION_MAJOR, XCP_VERSION_MINOR, XCP_VERSION_PATCH,
TEXTIFY(XCP_GIT_BRANCH), TEXTIFY(XCP_GIT_COMMIT_HASH));
exit(0);
},
"Print version and exit");
app.add_flag(
"-q,--quiet",
[&](const size_t count) { this->arg_verbosity -= static_cast<int>(count); },
"Be more quiet");
app.add_flag(
"-v,--verbose",
[&](const size_t count) { this->arg_verbosity += static_cast<int>(count); },
"Be more verbose");
}
bool xcp::base_program_options::post_process()
{
// Set verbosity
infra::set_logging_verbosity(this->arg_verbosity);
return true;
}
//==============================================================================
// struct xcp_program_options
//==============================================================================
void xcp::xcp_program_options::add_options(CLI::App& app)
{
base_program_options::add_options(app);
CLI::Option* opt_port = app.add_option(
"-P,-p,--port",
this->arg_port,
"Server portal port to connect to");
opt_port->type_name("<port>");
CLI::Option* opt_from = app.add_option(
"from",
this->arg_from_path,
"Copy from this path");
opt_from->type_name("<from>");
opt_from->required();
CLI::Option* opt_to = app.add_option(
"to",
this->arg_to_path,
"Copy to this path");
opt_to->type_name("<to>");
opt_to->required();
[[maybe_unused]]
CLI::Option* opt_recursive = app.add_flag(
"-r,--recursive",
this->arg_recursive,
"Transfer a directory recursively");
CLI::Option* opt_user = app.add_option(
"-u,--user",
this->arg_user,
"Relative to this user's home directory on server side");
opt_user->type_name("<user>");
CLI::Option* opt_block = app.add_option(
"-B,--block",
this->arg_transfer_block_size,
"Transfer block size");
opt_block->type_name("<size>");
opt_block->transform(CLI::AsSizeValue(false));
}
bool xcp::xcp_program_options::post_process()
{
if (!base_program_options::post_process()) {
return false;
}
//----------------------------------------------------------------
// arg_from_path, arg_to_path
//----------------------------------------------------------------
if (arg_from_path.is_remote()) {
ASSERT(arg_from_path.host.has_value());
LOG_DEBUG("Copy from remote host {} path {}", arg_from_path.host.value(), arg_from_path.path);
}
else {
LOG_DEBUG("Copy from local path {}", arg_from_path.path);
}
if (arg_to_path.is_remote()) {
ASSERT(arg_to_path.host.has_value());
LOG_DEBUG("Copy to remote host {} path {}", arg_to_path.host.value(), arg_to_path.path);
}
else {
LOG_DEBUG("Copy to local path {}", arg_to_path.path);
}
if (arg_from_path.is_remote() && arg_to_path.is_remote()) {
LOG_ERROR("Can't copy between remote hosts");
return false;
}
else if (arg_from_path.is_remote()) {
is_from_server_to_client = true;
server_portal.host = arg_from_path.host.value();
}
else if (arg_to_path.is_remote()) {
is_from_server_to_client = false;
server_portal.host = arg_to_path.host.value();
}
else {
LOG_ERROR("Copy from local to local is to be supported"); // TODO
return false;
}
//----------------------------------------------------------------
// arg_port
//----------------------------------------------------------------
if (arg_port.has_value()) {
if (arg_port.value() == 0) {
LOG_ERROR("Server portal port 0 is invalid");
return false;
}
}
else { // !arg_portal->port.has_value()
arg_port = program_options_defaults::SERVER_PORTAL_PORT;
}
server_portal.port = arg_port.value();
LOG_DEBUG("Server portal: {}", server_portal.to_string());
if (!server_portal.resolve()) {
LOG_ERROR("Can't resolve specified server portal: {}", server_portal.to_string());
return false;
}
else {
for (const infra::tcp_sockaddr& addr : server_portal.resolved_sockaddrs) {
LOG_DEBUG(" Candidate server portal endpoint: {}", addr.to_string());
}
}
//----------------------------------------------------------------
// arg_recursive
//----------------------------------------------------------------
if (arg_recursive) {
LOG_DEBUG("Transfer recursively if source is a directory");
}
//----------------------------------------------------------------
// arg_user
//----------------------------------------------------------------
bool got_user = false;
if (arg_user.has_value()) {
server_user.user_name = arg_user.value();
got_user = true;
}
else {
if (arg_from_path.is_remote()) {
ASSERT(is_from_server_to_client);
if (arg_from_path.user.has_value()) {
server_user.user_name = arg_from_path.user.value();
got_user = true;
}
}
else if (arg_to_path.is_remote()) {
ASSERT(!is_from_server_to_client);
if (arg_to_path.user.has_value()) {
server_user.user_name = arg_to_path.user.value();
got_user = true;
}
}
}
if (!got_user) {
if (infra::get_user_name(server_user)) {
got_user = true;
}
}
if (got_user) {
LOG_TRACE("Use this user for server side: {}", server_user.to_string());
}
else {
server_user = { };
LOG_WARN("Can't get user. Use no user for server side");
}
//----------------------------------------------------------------
// arg_transfer_block_size
//----------------------------------------------------------------
if (arg_transfer_block_size.has_value()) {
if (arg_transfer_block_size.value() > program_options_defaults::MAX_TRANSFER_BLOCK_SIZE) {
LOG_WARN("Transfer block size is too large: {}. Set to MAX_TRANSFER_BLOCK_SIZE: {}",
arg_transfer_block_size.value(), program_options_defaults::MAX_TRANSFER_BLOCK_SIZE);
arg_transfer_block_size = program_options_defaults::MAX_TRANSFER_BLOCK_SIZE;
}
}
else {
arg_transfer_block_size = 0;
}
if (arg_transfer_block_size.value() == 0) {
LOG_TRACE("Transfer block size: automatic tuning");
}
else if (arg_transfer_block_size.value() < 1024 * 64) {
LOG_WARN("Transfer block size {} is too small. You may encounter bad performance!", arg_transfer_block_size.value());
}
else {
LOG_TRACE("Transfer block size: {}", arg_transfer_block_size.value());
}
return true;
}
//==============================================================================
// struct xcpd_program_options
//==============================================================================
void xcp::xcpd_program_options::add_options(CLI::App& app)
{
base_program_options::add_options(app);
CLI::Option* opt_portal = app.add_option(
"-P,-p,--portal",
this->arg_portal,
"Server portal endpoint to bind and listen");
opt_portal->type_name("<endpoint>");
CLI::Option* opt_channel = app.add_option(
"-C,--channel",
this->arg_channels,
"Server channels to bind and listen for transportation");
opt_channel->type_name("<endpoint>");
}
bool xcp::xcpd_program_options::post_process()
{
if (!base_program_options::post_process()) {
return false;
}
//----------------------------------------------------------------
// arg_portal
//----------------------------------------------------------------
if (!arg_portal.has_value()) {
arg_portal = infra::tcp_endpoint();
arg_portal->host = program_options_defaults::SERVER_PORTAL_HOST;
LOG_INFO("Server portal is not specified, use default host {}", program_options_defaults::SERVER_PORTAL_HOST);
}
if (arg_portal->port.has_value()) {
if (arg_portal->port.value() == 0) {
LOG_WARN("Server portal binds to a random port");
}
else {
LOG_TRACE("Server portal binds to port {}", arg_portal->port.value());
}
}
else { // !arg_portal->port.has_value()
arg_portal->port = program_options_defaults::SERVER_PORTAL_PORT;
LOG_TRACE("Server portal binds to default port {}", arg_portal->port.value());
}
LOG_INFO("Server portal endpoint: {}", arg_portal->to_string());
if (!arg_portal->resolve()) {
LOG_ERROR("Can't resolve specified portal: {}", arg_portal->to_string());
return false;
}
else {
for (const infra::tcp_sockaddr& addr : arg_portal->resolved_sockaddrs) {
LOG_DEBUG(" Candidate server portal endpoint: {}", addr.to_string());
}
}
//----------------------------------------------------------------
// arg_channels
//----------------------------------------------------------------
total_channel_repeats_count = 0;
if (arg_channels.empty()) {
// Reuse portal as channel
// Default arg_portal->repeats if not specified by user
if (!arg_portal->repeats.has_value()) {
arg_portal->repeats = program_options_defaults::SERVER_CHANNEL_REPEATS;
}
total_channel_repeats_count += arg_portal->repeats.value();
LOG_INFO("Server channels are not specified, reuse portal as channel: {}", arg_portal->to_string());
}
for (infra::tcp_endpoint& ep : arg_channels) {
if (!ep.port.has_value()) {
ep.port = static_cast<uint16_t>(0);
}
if (!ep.repeats.has_value()) {
ep.repeats = static_cast<size_t>(1);
}
ASSERT(ep.repeats.value() > 0);
LOG_INFO("Server channel: {}", ep.to_string());
if (!ep.resolve()) {
LOG_ERROR("Can't resolve specified channel: {}", ep.to_string());
return false;
}
else {
for (const infra::tcp_sockaddr& addr : ep.resolved_sockaddrs) {
LOG_DEBUG(" Candidate server channel endpoint: {}", addr.to_string());
}
}
total_channel_repeats_count += ep.repeats.value();
}
LOG_INFO("Total server channels (including repeats): {}", total_channel_repeats_count);
return true;
}
| 33.501134
| 690
| 0.500271
|
WenbinHou
|
499b39c54b8f164f0888e1304f52c52505ed1694
| 3,169
|
cpp
|
C++
|
include/lak/stream_util.cpp
|
LAK132/NetworkMaker
|
0ad1ba2488d80e8bba0a710e5d9984d7c5cc0739
|
[
"MIT"
] | null | null | null |
include/lak/stream_util.cpp
|
LAK132/NetworkMaker
|
0ad1ba2488d80e8bba0a710e5d9984d7c5cc0739
|
[
"MIT"
] | null | null | null |
include/lak/stream_util.cpp
|
LAK132/NetworkMaker
|
0ad1ba2488d80e8bba0a710e5d9984d7c5cc0739
|
[
"MIT"
] | 1
|
2020-08-16T16:27:58.000Z
|
2020-08-16T16:27:58.000Z
|
/*
MIT License
Copyright (c) 2018 Lucas Kleiss (LAK132)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "stream_util.h"
void readFile(const string& src, string* dst)
{
*dst = "";
ifstream strm(src.c_str(), std::ios::binary|ifstream::in);
if(!strm.is_open())
{
LERRLOG("Failed to open file " << src.c_str() << endl);
return;
}
streampos start = strm.tellg();
size_t size = 0;
string str = ""; str += EOF;
skipOneS(strm, str) ++size; // I'm not sorry
strm.clear();
strm.seekg(start);
dst->reserve(size);
for(char c = strm.get(); strm >> c;)
*dst += c;
}
void readFile(string&& src, string* dst)
{
readFile(src, dst);
}
string readFile(const string& src)
{
string str;
readFile(src, &str);
return str;
}
string readFile(string&& src)
{
string str;
readFile(src, &str);
return str;
}
// string getString(istream& strm, const char terminator)
// {
// LDEBUG(std::endl);
// string str = "";
// LDEBUG(std::endl);
// char c = strm.get();
// LDEBUG(std::endl);
// while((c = strm.get()) != terminator && strm.good())
// {
// LDEBUG(c << std::endl);
// if(c == '\\')
// {
// switch(strm.get())
// {
// case '\\': str += '\\'; break;
// case '\'': str += '\''; break;
// case '\"': str += '\"'; break;
// // case 'b': str += "\\b"; break;
// case 'f': str += '\f'; break;
// case 'n': str += '\n'; break;
// case 'r': str += '\r'; break;
// case 't': str += '\t'; break;
// case 'u': {
// str += "\\u";
// str += strm.get();
// str += strm.get();
// str += strm.get();
// str += strm.get();
// } break;
// default: {
// str += '\\';
// str += strm.get();
// } break;
// }
// }
// else
// str += c;
// }
// return str;
// }
| 30.180952
| 78
| 0.532029
|
LAK132
|
499c9cd941a0da86a8ba6bfb30de25722b42eba3
| 42
|
cpp
|
C++
|
4781_candyshop/4781.cpp
|
YouminHa/acmicpc
|
dddb457a3cfb03df34db0ed07680ac1a7be6cdd4
|
[
"MIT"
] | null | null | null |
4781_candyshop/4781.cpp
|
YouminHa/acmicpc
|
dddb457a3cfb03df34db0ed07680ac1a7be6cdd4
|
[
"MIT"
] | null | null | null |
4781_candyshop/4781.cpp
|
YouminHa/acmicpc
|
dddb457a3cfb03df34db0ed07680ac1a7be6cdd4
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <iostream>
| 7
| 19
| 0.666667
|
YouminHa
|
49a7dbc2bdc7d142b3de9ff2cfce31e67f3a35fd
| 645
|
cpp
|
C++
|
Source/mods.cpp
|
HaikuArchives/Rez
|
db5e7e1775a379e1e54bc17012047d92ec782202
|
[
"BSD-4-Clause"
] | 1
|
2016-09-12T19:04:30.000Z
|
2016-09-12T19:04:30.000Z
|
Source/mods.cpp
|
HaikuArchives/Rez
|
db5e7e1775a379e1e54bc17012047d92ec782202
|
[
"BSD-4-Clause"
] | null | null | null |
Source/mods.cpp
|
HaikuArchives/Rez
|
db5e7e1775a379e1e54bc17012047d92ec782202
|
[
"BSD-4-Clause"
] | null | null | null |
#include "mods.h"
#include <cstdio>
/*************************************************************************
* Modifications to the standard REZ distribution.
* Copyright (c) 2000, Tim Vernum
* This code may be freely used for any purpose
*************************************************************************/
bool gListDepend = false ;
bool gParseOnly = false ;
void DependFile( const char * file )
{
if( gListDepend )
{
printf( "\t%s \\\n", file ) ;
}
}
void StartDepend( const char * out )
{
if( gListDepend )
{
printf( "%s : \\\n", out ) ;
}
}
void EndDepend( void )
{
if( gListDepend )
{
printf( "\n" ) ;
}
}
| 17.432432
| 75
| 0.472868
|
HaikuArchives
|
49b41afb9d64fe942c0e7c9d0cfbf4b64821414a
| 358
|
cpp
|
C++
|
Graph/main.cpp
|
yanelox/ilab_2year
|
4597b2fbc498a816368101283d2749ac7bbf670a
|
[
"MIT"
] | null | null | null |
Graph/main.cpp
|
yanelox/ilab_2year
|
4597b2fbc498a816368101283d2749ac7bbf670a
|
[
"MIT"
] | null | null | null |
Graph/main.cpp
|
yanelox/ilab_2year
|
4597b2fbc498a816368101283d2749ac7bbf670a
|
[
"MIT"
] | 1
|
2021-10-11T19:18:37.000Z
|
2021-10-11T19:18:37.000Z
|
#include "graph.cpp"
int main ()
{
graph::graph_ <int> G {};
if (G.input() == 0)
{
std::cout << "Incorrect input\n";
return 0;
}
// std::cout << G;
int res = G.colorize();
// G.recolorize();
if (res == 1)
G.print_colors(std::cout);
else
std::cout << "Error: non-bipartite graph\n";
}
| 14.916667
| 52
| 0.472067
|
yanelox
|
49ba8348d2d36c463bd163cb89fee32926da201a
| 401
|
hpp
|
C++
|
include/dotto/debug.hpp
|
mitsukaki/dotto
|
ebea72447e854c9beff676fe609d998a3cb0b3ea
|
[
"CC0-1.0"
] | 4
|
2018-03-05T22:51:40.000Z
|
2018-03-11T00:54:38.000Z
|
include/dotto/debug.hpp
|
mitsukaki/dotto
|
ebea72447e854c9beff676fe609d998a3cb0b3ea
|
[
"CC0-1.0"
] | null | null | null |
include/dotto/debug.hpp
|
mitsukaki/dotto
|
ebea72447e854c9beff676fe609d998a3cb0b3ea
|
[
"CC0-1.0"
] | 1
|
2019-09-14T19:44:14.000Z
|
2019-09-14T19:44:14.000Z
|
#pragma once
#include <string>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <dotto/io.hpp>
class debug
{
private:
TTF_Font* debug_font;
SDL_Rect fps_text_rect;
SDL_Surface* fps_text_surface;
SDL_Texture* fps_text_texture;
public:
debug();
~debug();
void render(SDL_Renderer* renderer);
void init();
float fps;
};
| 12.151515
| 40
| 0.665835
|
mitsukaki
|
49bc2b5de44ea8cffd8978e2372400df92994655
| 590
|
cpp
|
C++
|
hackerrank/problems/GameOfThrones-I.cpp
|
joaquinmd93/competitive-programming
|
681424abd777cc0a3059e1ee66ae2cee958178da
|
[
"MIT"
] | 1
|
2020-10-08T19:28:40.000Z
|
2020-10-08T19:28:40.000Z
|
hackerrank/problems/GameOfThrones-I.cpp
|
joaquinmd93/competitive-programming
|
681424abd777cc0a3059e1ee66ae2cee958178da
|
[
"MIT"
] | null | null | null |
hackerrank/problems/GameOfThrones-I.cpp
|
joaquinmd93/competitive-programming
|
681424abd777cc0a3059e1ee66ae2cee958178da
|
[
"MIT"
] | 1
|
2020-10-24T02:32:27.000Z
|
2020-10-24T02:32:27.000Z
|
#include<bits/stdc++.h>
using namespace std;
int main() {
string s; cin >> s;
int n = s.size();
map<char, int> reps;
for (int i=0; i<n; ++i) {
++reps[s[i]];
}
int odd_reps=0;
for (auto let: reps) {
if (let.second % 2 != 0)
++odd_reps;
}
if (n % 2 == 0) {
if (odd_reps == 0)
cout << "YES" << endl;
else
cout << "NO" << endl;
} else {
if (odd_reps == 1)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}
| 21.071429
| 37
| 0.383051
|
joaquinmd93
|
49bfb9d091eb75a7ace1930c89cc4d2d1b3a5aae
| 1,830
|
hpp
|
C++
|
include/RED4ext/Scripting/Natives/Generated/anim/DangleConstraint_SimulationPendulum.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 42
|
2020-12-25T08:33:00.000Z
|
2022-03-22T14:47:07.000Z
|
include/RED4ext/Scripting/Natives/Generated/anim/DangleConstraint_SimulationPendulum.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 38
|
2020-12-28T22:36:06.000Z
|
2022-02-16T11:25:47.000Z
|
include/RED4ext/Scripting/Natives/Generated/anim/DangleConstraint_SimulationPendulum.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 20
|
2020-12-28T22:17:38.000Z
|
2022-03-22T17:19:01.000Z
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/Vector3.hpp>
#include <RED4ext/Scripting/Natives/Generated/anim/DangleConstraint_SimulationSingleBone.hpp>
#include <RED4ext/Scripting/Natives/Generated/anim/PendulumConstraintType.hpp>
#include <RED4ext/Scripting/Natives/Generated/anim/PendulumProjectionType.hpp>
#include <RED4ext/Scripting/Natives/Generated/anim/VectorLink.hpp>
namespace RED4ext
{
namespace anim {
struct DangleConstraint_SimulationPendulum : anim::DangleConstraint_SimulationSingleBone
{
static constexpr const char* NAME = "animDangleConstraint_SimulationPendulum";
static constexpr const char* ALIAS = NAME;
float simulationFps; // 90
anim::PendulumConstraintType constraintType; // 94
float halfOfMaxApertureAngle; // 98
Vector3 constraintOrientation; // 9C
float mass; // A8
float gravityWS; // AC
float damping; // B0
float pullForceFactor; // B4
Vector3 pullForceDirectionLS; // B8
Vector3 externalForceWS; // C4
anim::VectorLink externalForceWsLink; // D0
anim::PendulumProjectionType projectionType; // F0
float collisionCapsuleRadius; // F4
float collisionCapsuleHeightExtent; // F8
float cosOfHalfXAngle; // FC
float cosOfHalfYAngle; // 100
float cosOfHalfZAngle; // 104
float sinOfHalfXAngle; // 108
float sinOfHalfYAngle; // 10C
float sinOfHalfZAngle; // 110
float cosOfHalfMaxApertureAngle; // 114
float cosOfHalfOfHalfMaxApertureAngle; // 118
float sinOfHalfOfHalfMaxApertureAngle; // 11C
float invertedMass; // 120
uint8_t unk124[0x188 - 0x124]; // 124
};
RED4EXT_ASSERT_SIZE(DangleConstraint_SimulationPendulum, 0x188);
} // namespace anim
} // namespace RED4ext
| 36.6
| 93
| 0.757923
|
jackhumbert
|
49c35d5da78523cf5f60013d0b0803761665d2e9
| 1,548
|
cpp
|
C++
|
src/Parse/Parser.cpp
|
artagnon/rhine
|
ca4ec684162838f4cb13d9d29ef9e4aedbc268dd
|
[
"MIT"
] | 234
|
2015-01-02T18:32:50.000Z
|
2022-02-03T19:41:33.000Z
|
src/Parse/Parser.cpp
|
artagnon/rhine
|
ca4ec684162838f4cb13d9d29ef9e4aedbc268dd
|
[
"MIT"
] | 7
|
2015-02-16T15:02:54.000Z
|
2016-05-26T07:46:02.000Z
|
src/Parse/Parser.cpp
|
artagnon/rhine
|
ca4ec684162838f4cb13d9d29ef9e4aedbc268dd
|
[
"MIT"
] | 13
|
2015-02-16T13:37:12.000Z
|
2020-12-12T04:18:43.000Z
|
#include "rhine/Parse/ParseDriver.hpp"
#include "rhine/Parse/Parser.hpp"
#include "rhine/Parse/Lexer.hpp"
#include "rhine/Diagnostic/Diagnostic.hpp"
#include "rhine/IR/Context.hpp"
#include "rhine/IR/Module.hpp"
#include <vector>
#define K Driver->Ctx
namespace rhine {
Parser::Parser(ParseDriver *Dri) : Driver(Dri), CurStatus(true) {}
Parser::~Parser() {}
void Parser::getTok() {
LastTok = CurTok;
CurTok = Driver->Lexx->lex(&CurSema, &CurLoc);
LastTokWasNewlineTerminated = false;
while (CurTok == NEWLINE) {
LastTokWasNewlineTerminated = true;
CurTok = Driver->Lexx->lex(&CurSema, &CurLoc);
}
}
bool Parser::getTok(int Expected) {
if (CurTok == Expected) {
getTok();
CurLoc.Filename = Driver->InputName;
CurLoc.StringStreamInput = Driver->StringStreamInput;
return true;
}
return false;
}
void Parser::writeError(std::string ErrStr, bool Optional) {
if (Optional) return;
DiagnosticPrinter(CurLoc) << ErrStr;
CurStatus = false;
}
bool Parser::getSemiTerm(std::string ErrFragment, bool Optional) {
if (!getTok(';') && !LastTokWasNewlineTerminated && CurTok != ENDBLOCK) {
auto ErrStr = "expecting ';' or newline to terminate " + ErrFragment;
writeError(ErrStr, Optional);
return false;
}
return true;
}
void Parser::parseToplevelForms() {
getTok();
while (auto Fcn = parseFcnDecl(true)) {
Driver->Root->appendFunction(Fcn);
}
if (CurTok != END)
writeError("expected end of file");
}
bool Parser::parse() {
parseToplevelForms();
return CurStatus;
}
}
| 23.104478
| 75
| 0.687339
|
artagnon
|
49cb02d9b7eecd8c0fe5b389a18b8f277d0733cc
| 5,911
|
cpp
|
C++
|
Quake/Notes005/src/DIYQuake/ModelManager.cpp
|
amroibrahim/DIYQuake
|
957d4b86fc6edc3eedf0e322eafce89dc336261f
|
[
"MIT"
] | 13
|
2020-12-06T20:11:40.000Z
|
2021-12-14T16:28:48.000Z
|
Quake/Notes005/src/DIYQuake/ModelManager.cpp
|
amroibrahim/DIYQuake
|
957d4b86fc6edc3eedf0e322eafce89dc336261f
|
[
"MIT"
] | 1
|
2021-05-02T02:31:51.000Z
|
2021-05-02T17:00:49.000Z
|
Quake/Notes005/src/DIYQuake/ModelManager.cpp
|
amroibrahim/DIYQuake
|
957d4b86fc6edc3eedf0e322eafce89dc336261f
|
[
"MIT"
] | 1
|
2020-12-17T12:17:16.000Z
|
2020-12-17T12:17:16.000Z
|
#include "ModelManager.h"
#include <string>
void ModelManager::Init(MemoryManager* pMemorymanager, Common* pCommon)
{
m_pMemorymanager = pMemorymanager;
m_pCommon = pCommon;
}
ModelData* ModelManager::Load(char* szName)
{
ModelData* pModelData = nullptr;
pModelData = Find(szName);
return Load(pModelData);
}
//Load header to Known list
void ModelManager::LoadHeader(char* szName)
{
ModelData* pModelData = Find(szName);
if (pModelData->eLoadStatus == MODELLOADSTATUS::PRESENT)
{
if (pModelData->eType == MODELTYPE::ALIAS)
{
m_pMemorymanager->Check(&pModelData->pCachData);
}
}
}
void ModelManager::LoadAliasModel(ModelData* pModel, byte_t* pBuffer, char* szHunkName)
{
int32_t iMemoryStartOffset = m_pMemorymanager->GetLowUsed();
ModelHeader* pTempModelHeader = (ModelHeader*)pBuffer;
int32_t iVersion = pTempModelHeader->iVersion;
int32_t iSize = sizeof(AliasModelHeader) + sizeof(ModelHeader);
std::string sloadName(szHunkName);
AliasModelHeader* pAliasModelHeader = (AliasModelHeader*)m_pMemorymanager->NewLowEndNamed(iSize, sloadName);
ModelHeader* pModelHeader = (ModelHeader*)((byte_t*)&pAliasModelHeader[1]);
// pModel->iFlags = pTempModelHeader->iFlags;
pModelHeader->iNumSkins = pTempModelHeader->iNumSkins;
pModelHeader->iSkinWidth = pTempModelHeader->iSkinWidth;
pModelHeader->iSkinHeight = pTempModelHeader->iSkinHeight;
int32_t iNumberOfSkins = pModelHeader->iNumSkins;
// Calculate the skin size in bytes
int32_t iSkinSize = pModelHeader->iSkinHeight * pModelHeader->iSkinWidth;
AliasSkinType* pSkinType = (AliasSkinType*)&pTempModelHeader[1];
AliasSkinDesc* pSkinDesc = (AliasSkinDesc*)m_pMemorymanager->NewLowEndNamed(iNumberOfSkins * sizeof(AliasSkinDesc), sloadName);
pAliasModelHeader->SkinDescOffset = (byte_t*)pSkinDesc - (byte_t*)pAliasModelHeader;
for (int i = 0; i < iNumberOfSkins; i++)
{
pSkinDesc[i].eSkinType = pSkinType->eSkinType;
if (pSkinType->eSkinType == ALIAS_SKIN_SINGLE)
{
pSkinType = (AliasSkinType*)LoadAliasSkin(pSkinType + 1, &pSkinDesc[i].skin, iSkinSize, pAliasModelHeader, sloadName);
}
else
{
pSkinType = (AliasSkinType*)LoadAliasSkinGroup(pSkinType + 1, &pSkinDesc[i].skin, iSkinSize, pAliasModelHeader, sloadName);
}
}
pModel->eType = MODELTYPE::ALIAS;
int32_t iMemoryEndOffset = m_pMemorymanager->GetLowUsed();
int32_t iTotalMemorySize = iMemoryEndOffset - iMemoryStartOffset;
m_pMemorymanager->m_Cache.NewNamed(&pModel->pCachData, iTotalMemorySize, sloadName);
if (!pModel->pCachData.pData)
return;
memcpy(pModel->pCachData.pData, pAliasModelHeader, iTotalMemorySize);
m_pMemorymanager->DeleteToLowMark(iMemoryStartOffset);
}
ModelData* ModelManager::Find(char* szName)
{
ModelData* pAvailable = NULL;
int iCurrentModelIndex = 0;
// Is the model already loaded?
ModelData* pCurrentModel = m_pKnownModels;
while (iCurrentModelIndex < m_iKnownModelCount)
{
if (!strcmp(pCurrentModel->szName, szName))
{
break;
}
if ((pCurrentModel->eLoadStatus == MODELLOADSTATUS::UNREFERENCED) && (!pAvailable || pCurrentModel->eType != MODELTYPE::ALIAS))
{
pAvailable = pCurrentModel;
}
++iCurrentModelIndex;
++pCurrentModel;
}
if (iCurrentModelIndex == m_iKnownModelCount)
{
if (m_iKnownModelCount == MAX_KNOWN_MODEL)
{
if (pAvailable)
{
pCurrentModel = pAvailable;
if (pCurrentModel->eType == MODELTYPE::ALIAS && m_pMemorymanager->Check(&pCurrentModel->pCachData))
{
m_pMemorymanager->CacheEvict(&pCurrentModel->pCachData);
}
}
}
else
{
++m_iKnownModelCount;
}
strcpy(pCurrentModel->szName, szName);
pCurrentModel->eLoadStatus = MODELLOADSTATUS::NEEDS_LOADING;
}
return pCurrentModel;
}
void* ModelManager::ExtraData(ModelData* pModel)
{
void* pData;
pData = m_pMemorymanager->m_Cache.Check(&pModel->pCachData);
if (pData)
return pData;
Load(pModel);
return pModel->pCachData.pData;
}
ModelData* ModelManager::Load(ModelData* pModel)
{
if (pModel->eType == MODELTYPE::ALIAS)
{
if (m_pMemorymanager->Check(&pModel->pCachData))
{
pModel->eLoadStatus = MODELLOADSTATUS::PRESENT;
return pModel;
}
}
else
{
if (pModel->eLoadStatus == MODELLOADSTATUS::PRESENT)
{
return pModel;
}
}
byte_t TempBuffer[1024]; // 1K on stack! Load the model temporary on stack (if they fit)
byte_t* pBuffer = m_pCommon->LoadFile(pModel->szName, TempBuffer, sizeof(TempBuffer));
char szHunkName[32] = { 0 };
m_pCommon->GetFileBaseName(pModel->szName, szHunkName);
//TODO:
//loadmodel = pModel;
pModel->eLoadStatus = MODELLOADSTATUS::PRESENT;
switch (*(uint32_t*)pBuffer)
{
case IDPOLYHEADER:
LoadAliasModel(pModel, (byte_t*)pBuffer, szHunkName);
break;
//case IDSPRITEHEADER:
// LoadSpriteModel(pModel, pBuffer);
// break;
//default:
// LoadBrushModel(pModel, pBuffer);
// break;
}
return pModel;
}
void* ModelManager::LoadAliasSkin(void* pTempModel, int32_t* pSkinOffset, int32_t iSkinSize, AliasModelHeader* pHeader, std::string& sHunkName)
{
byte_t* pSkin = (byte_t*)m_pMemorymanager->NewLowEndNamed(iSkinSize, sHunkName);
byte_t* pSkinInTemp = (byte_t*)pTempModel;
*pSkinOffset = (byte_t*)pSkin - (byte_t*)pHeader;
memcpy(pSkin, pSkinInTemp, iSkinSize);
pSkinInTemp += iSkinSize;
return ((void*)pSkinInTemp);
}
void* ModelManager::LoadAliasSkinGroup(void* pTempModel, int32_t* pSkinOffset, int32_t iSkinSize, AliasModelHeader* pHeader, std::string& sHunkName)
{
return nullptr;
}
| 26.746606
| 148
| 0.682964
|
amroibrahim
|
49ccafc5c5b597763564ff02b523f969ebbb4ede
| 728
|
hpp
|
C++
|
src/utility/apply.hpp
|
spraetor/amdis2
|
53c45c81a65752a8fafbb54f9ae6724a86639dcd
|
[
"MIT"
] | 2
|
2018-07-04T16:44:04.000Z
|
2021-01-03T07:26:27.000Z
|
test/utility/apply.hpp
|
spraetor/amdis2
|
53c45c81a65752a8fafbb54f9ae6724a86639dcd
|
[
"MIT"
] | null | null | null |
test/utility/apply.hpp
|
spraetor/amdis2
|
53c45c81a65752a8fafbb54f9ae6724a86639dcd
|
[
"MIT"
] | null | null | null |
#pragma once
// std c++ headers
#include <tuple>
#include <array>
// AMDiS includes
#include "traits/basic.hpp"
#include "traits/size.hpp"
#include "utility/int_seq.hpp"
namespace AMDiS
{
namespace detail
{
// return f(t[0], t[1], t[2], ...)
template <class F, class Tuple, int... I>
constexpr auto apply_impl(F&& f, Tuple&& t, AMDiS::Seq<I...>) RETURNS
(
(std::forward<F>(f))(std::get<I>(std::forward<Tuple>(t))...)
)
} // end namespace detail
template <class F, class Tuple, int N = Size<Decay_t<Tuple>>::value>
constexpr auto apply(F&& f, Tuple&& t) RETURNS
(
detail::apply_impl(std::forward<F>(f), std::forward<Tuple>(t), MakeSeq_t<N>{})
)
} // end namespace AMDiS
| 22.060606
| 82
| 0.612637
|
spraetor
|
49d165e039d2329018c519729c723a32fecadf17
| 284
|
cpp
|
C++
|
src/Test/src/MockAudioPlayerView.cpp
|
don-reba/peoples-note
|
c22d6963846af833c55f4294dd0474e83344475d
|
[
"BSD-2-Clause"
] | null | null | null |
src/Test/src/MockAudioPlayerView.cpp
|
don-reba/peoples-note
|
c22d6963846af833c55f4294dd0474e83344475d
|
[
"BSD-2-Clause"
] | null | null | null |
src/Test/src/MockAudioPlayerView.cpp
|
don-reba/peoples-note
|
c22d6963846af833c55f4294dd0474e83344475d
|
[
"BSD-2-Clause"
] | null | null | null |
#include "stdafx.h"
#include "MockAudioPlayerView.h"
using namespace std;
void MockAudioPlayerView::Hide()
{
isShown = false;
}
void MockAudioPlayerView::SetFileName(wstring & name)
{
this->name = name;
}
void MockAudioPlayerView::Show()
{
isShown = true;
}
| 14.2
| 54
| 0.676056
|
don-reba
|
49d35ea928779a62915396dd753395a313af8644
| 4,593
|
cpp
|
C++
|
source/networkrequest.cpp
|
KambizAsadzadeh/RestService
|
ca677068954cd9b6f08d42d8deabdaf07c712d93
|
[
"MIT"
] | 7
|
2020-10-31T19:03:12.000Z
|
2022-02-04T09:50:56.000Z
|
source/networkrequest.cpp
|
KambizAsadzadeh/RestService
|
ca677068954cd9b6f08d42d8deabdaf07c712d93
|
[
"MIT"
] | null | null | null |
source/networkrequest.cpp
|
KambizAsadzadeh/RestService
|
ca677068954cd9b6f08d42d8deabdaf07c712d93
|
[
"MIT"
] | null | null | null |
#include "networkrequest.hpp"
#include "core.hpp"
using namespace RestService;
namespace RestService {
NetworkRequest::NetworkRequest()
{
this->result = "Unknown";
curl = curl_easy_init();
if(!curl)
throw std::string ("Curl did not initialize!");
}
NetworkRequest::~NetworkRequest()
{
cleanGlobal();
}
static size_t WriteCallback2(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
size_t NetworkRequest::WriteCallback(char *data, size_t size, size_t nmemb, std::string *buffer)
{
unsigned long result = 0;
if (buffer != nullptr) {
buffer->append(data, size * nmemb);
*buffer += data;
result = size * nmemb;
}
return result;
}
void NetworkRequest::clean() {
curl_easy_cleanup(curl);
}
void NetworkRequest::cleanGlobal() {
curl_global_cleanup();
}
void NetworkRequest::post(const std::string& url, const std::string& query){
/* In windows, this will init the winsock stuff */
curl_global_init(CURL_GLOBAL_ALL);
/* get a curl handle */
curl = curl_easy_init();
if(curl) {
ctype_list = curl_slist_append(ctype_list, Core::headerType.data());
if(Core::isset(Core::headerType)) {
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, ctype_list);
std::clog << "Content type has been set!" << std::endl;
}
curl_easy_setopt(curl, CURLOPT_URL, url.data());
/* Now specify the POST data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, query.data());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
curl_slist_free_all(ctype_list); /* free the ctype_list again */
/* Check for errors */
if(res != CURLE_OK)
std::clog << curl_easy_strerror(res) << std::endl;
fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
clean();
setResult(readBuffer);
}
}
void NetworkRequest::get(const std::string& url)
{
if(curl) {
if(Core::isset(Core::headerType)) {
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, ctype_list);
std::clog << "Content type has been set!" << std::endl;
}
#ifdef SKIP_PEER_VERIFICATION
/*
* If you want to connect to a site who isn't using a certificate that is
* signed by one of the certs in the CA bundle you have, you can skip the
* verification of the server's certificate. This makes the connection
* A LOT LESS SECURE.
*
* If you have a CA cert for the server stored someplace else than in the
* default bundle, then the CURLOPT_CAPATH option might come handy for
* you.
*/
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
#endif
#ifdef SKIP_HOSTNAME_VERIFICATION
/*
* If the site you're connecting to uses a different host name that what
* they have mentioned in their server certificate's commonName (or
* subjectAltName) fields, libcurl will refuse to connect. You can skip
* this check, but this will make the connection less secure.
*/
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
#endif
curl_easy_setopt(curl, CURLOPT_URL, url.data());
//curl_easy_setopt(curl, CURLOPT_HEADER, false);
/* example.com is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback2);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
std::cout << "Done!" << std::endl;
setResult(readBuffer);
/* always cleanup */
curl_easy_cleanup(curl);
}
}
void NetworkRequest::setResult(const std::string& res) {
ApiException apiEx;
if(!res.empty()) {
result = res;
apiEx.setMessage(result);
} else {
result = "unknown";
apiEx.setMessage("Unknown");
}
}
std::string NetworkRequest::getResult() {
return result;
}
}
| 28.52795
| 96
| 0.641193
|
KambizAsadzadeh
|
49d8992285acc111bb590e67ebf8c19642969e2e
| 51
|
cpp
|
C++
|
module/armor/fan_armor.cpp
|
PaPaPR/WolfVision
|
4092a313491349397106e3c050a332b2a5c6e611
|
[
"MIT"
] | null | null | null |
module/armor/fan_armor.cpp
|
PaPaPR/WolfVision
|
4092a313491349397106e3c050a332b2a5c6e611
|
[
"MIT"
] | null | null | null |
module/armor/fan_armor.cpp
|
PaPaPR/WolfVision
|
4092a313491349397106e3c050a332b2a5c6e611
|
[
"MIT"
] | null | null | null |
#include "fan_armor.hpp"
namespace fan_armor {
}
| 8.5
| 24
| 0.72549
|
PaPaPR
|
49da617293b4093c5c6d63da2090ee45557b3e6f
| 1,208
|
cpp
|
C++
|
Engine/OGF-Core/Core/Threads/ThreadPool.cpp
|
simon-bourque/OpenGameFramework
|
e0fed3895000a5ae244fc1ef696f4256af29865b
|
[
"MIT"
] | 4
|
2017-12-31T05:24:24.000Z
|
2021-06-08T07:33:57.000Z
|
Engine/OGF-Core/Core/Threads/ThreadPool.cpp
|
simon-bourque/OpenGameFramework
|
e0fed3895000a5ae244fc1ef696f4256af29865b
|
[
"MIT"
] | 10
|
2018-01-13T22:36:57.000Z
|
2018-06-23T20:03:03.000Z
|
Engine/OGF-Core/Core/Threads/ThreadPool.cpp
|
simon-bourque/OpenGameFramework
|
e0fed3895000a5ae244fc1ef696f4256af29865b
|
[
"MIT"
] | null | null | null |
#include "ThreadPool.h"
ThreadPool::ThreadWorker::ThreadWorker(ThreadPool* threadPool, const int threadIdx)
:m_threadPool(threadPool),m_threadIdx(threadIdx) {}
void ThreadPool::ThreadWorker::operator()()
{
std::function<void()> function;
bool dequeued;
while (!m_threadPool->m_shutdown) {
{
std::unique_lock<std::mutex> lock(m_threadPool->m_conditionalMutex);
if (m_threadPool->m_queue.empty()) {
m_threadPool->m_conditionalLock.wait(lock);
}
dequeued = m_threadPool->m_queue.dequeue(function);
}
if (dequeued) {
function();
}
}
}
ThreadPool::ThreadPool()
:m_threads(std::vector<std::thread>(DEFAULT_NUMBER_THREADS))
, m_shutdown(false)
{
for (int i = 0; i < m_threads.size(); i++)
{
m_threads[i] = std::thread(ThreadWorker(this, i));
}
}
ThreadPool::ThreadPool(const int numberOfThreads)
:m_threads(std::vector<std::thread>(numberOfThreads))
, m_shutdown(false)
{
for (int i = 0; i < m_threads.size(); i++)
{
m_threads[i] = std::thread(ThreadWorker(this, i));
}
}
ThreadPool::~ThreadPool() {
m_shutdown = true;
m_conditionalLock.notify_all();
for (int i = 0; i < m_threads.size(); ++i) {
if (m_threads[i].joinable()) {
m_threads[i].join();
}
}
}
| 23.230769
| 83
| 0.683775
|
simon-bourque
|
49df51121939c40f1c347a5d84b8f2c9c642cf52
| 1,811
|
cpp
|
C++
|
Source/UnrealCPP/ActorLineTrace/ActorLineTrace.cpp
|
Harrison1/unrealcpp-full-project
|
a0a84d124b3023a87cbcbf12cf8ee0a833dd4302
|
[
"MIT"
] | 6
|
2018-04-22T15:27:39.000Z
|
2021-11-02T17:33:58.000Z
|
Source/UnrealCPP/ActorLineTrace/ActorLineTrace.cpp
|
Harrison1/unrealcpp-full-project
|
a0a84d124b3023a87cbcbf12cf8ee0a833dd4302
|
[
"MIT"
] | null | null | null |
Source/UnrealCPP/ActorLineTrace/ActorLineTrace.cpp
|
Harrison1/unrealcpp-full-project
|
a0a84d124b3023a87cbcbf12cf8ee0a833dd4302
|
[
"MIT"
] | 4
|
2018-07-26T15:39:46.000Z
|
2020-12-28T08:10:35.000Z
|
// Harrison McGuire
// UE4 Version 4.19.0
// https://github.com/Harrison1/unrealcpp
// https://severallevels.io
// https://harrisonmcguire.com
#include "ActorLineTrace.h"
#include "ConstructorHelpers.h"
#include "DrawDebugHelpers.h"
// Sets default values
AActorLineTrace::AActorLineTrace()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// add cube to root
UStaticMeshComponent* Cube = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisualRepresentation"));
Cube->SetupAttachment(RootComponent);
static ConstructorHelpers::FObjectFinder<UStaticMesh> CubeAsset(TEXT("/Game/StarterContent/Shapes/Shape_Cube.Shape_Cube"));
if (CubeAsset.Succeeded())
{
Cube->SetStaticMesh(CubeAsset.Object);
Cube->SetRelativeLocation(FVector(0.0f, 0.0f, 0.0f));
Cube->SetWorldScale3D(FVector(1.f));
}
// add another component in the editor to the actor to overlap with the line trace to get the event to fire
}
// Called when the game starts or when spawned
void AActorLineTrace::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AActorLineTrace::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
FHitResult OutHit;
FVector Start = GetActorLocation();
Start.Z += 50.f;
Start.X += 200.f;
FVector ForwardVector = GetActorForwardVector();
FVector End = ((ForwardVector * 500.f) + Start);
FCollisionQueryParams CollisionParams;
DrawDebugLine(GetWorld(), Start, End, FColor::Green, false, 1, 0, 5);
if(ActorLineTraceSingle(OutHit, Start, End, ECC_WorldStatic, CollisionParams))
{
GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Green, FString::Printf(TEXT("The Component Being Hit is: %s"), *OutHit.GetComponent()->GetName()));
}
}
| 28.746032
| 151
| 0.732192
|
Harrison1
|
49e067ba72c9284c68a76f2dc24c67c337584b14
| 3,539
|
hpp
|
C++
|
cmake/templates/spirv.in.hpp
|
EEnginE/engine
|
9d8fe2c8a3051b8d25a15debdf058ac900f6a7fc
|
[
"Apache-2.0"
] | 28
|
2015-01-02T19:06:37.000Z
|
2018-11-23T11:34:17.000Z
|
cmake/templates/spirv.in.hpp
|
EEnginE/engine
|
9d8fe2c8a3051b8d25a15debdf058ac900f6a7fc
|
[
"Apache-2.0"
] | null | null | null |
cmake/templates/spirv.in.hpp
|
EEnginE/engine
|
9d8fe2c8a3051b8d25a15debdf058ac900f6a7fc
|
[
"Apache-2.0"
] | 6
|
2015-01-10T16:48:14.000Z
|
2019-10-08T13:43:44.000Z
|
/*!
* \file @FILENAME_HPP@
* \brief \b Classes: \a @CLASSNAME@
* \warning This file was automatically generated by createSPIRV!
*/
// clang-format off
#pragma once
#include "defines.hpp"
#include "rShaderBase.hpp"
namespace e_engine {
class iInit;
class rWorld;
class @CLASSNAME@ : public rShaderBase {
private:
static const std::vector<unsigned char> vRawData_vert;
static const std::vector<unsigned char> vRawData_tesc;
static const std::vector<unsigned char> vRawData_tese;
static const std::vector<unsigned char> vRawData_geom;
static const std::vector<unsigned char> vRawData_frag;
static const std::vector<unsigned char> vRawData_comp;
public:
virtual std::string getName() { return "@S_NAME@"; }
virtual bool has_vert() const { return @HAS_VERT@; }
virtual bool has_tesc() const { return @HAS_TESC@; }
virtual bool has_tese() const { return @HAS_TESE@; }
virtual bool has_geom() const { return @HAS_GEOM@; }
virtual bool has_frag() const { return @HAS_FRAG@; }
virtual bool has_comp() const { return @HAS_COMP@; }
virtual ShaderInfo getInfo_vert() const {
return {
{ // Input
@INPUT_VERT@
},
{ // Output
@OUTPUT_VERT@
},
{ // Uniforms
@UNIFORM_VERT@
},
{ // Push constants
@PUSH_VERT@
},
{ // Uniform Blocks
@UNIFORM_B_VERT@
}
};
}
virtual ShaderInfo getInfo_tesc() const {
return {
{ // Input
@INPUT_TESC@
},
{ // Output
@OUTPUT_TESC@
},
{ // Uniforms
@UNIFORM_TESC@
},
{ // Push constants
@PUSH_TESC@
},
{ // Uniform Blocks
@UNIFORM_B_TESC@
}
};
}
virtual ShaderInfo getInfo_tese() const {
return {
{ // Input
@INPUT_TESE@
},
{ // Output
@OUTPUT_TESE@
},
{ // Uniforms
@UNIFORM_TESE@
},
{ // Push constants
@PUSH_TESE@
},
{ // Uniform Blocks
@UNIFORM_B_TESE@
}
};
}
virtual ShaderInfo getInfo_geom() const {
return {
{ // Input
@INPUT_GEOM@
},
{ // Output
@OUTPUT_GEOM@
},
{ // Uniforms
@UNIFORM_GEOM@
},
{ // Push constants
@PUSH_GEOM@
},
{ // Uniform Blocks
@UNIFORM_B_GEOM@
}
};
}
virtual ShaderInfo getInfo_frag() const {
return {
{ // Input
@INPUT_FRAG@
},
{ // Output
@OUTPUT_FRAG@
},
{ // Uniforms
@UNIFORM_FRAG@
},
{ // Push constants
@PUSH_FRAG@
},
{ // Uniform Blocks
@UNIFORM_B_FRAG@
}
};
}
virtual ShaderInfo getInfo_comp() const {
return {
{ // Input
@INPUT_COMP@
},
{ // Output
@OUTPUT_COMP@
},
{ // Uniforms
@UNIFORM_COMP@
},
{ // Push constants
@PUSH_COMPT@
},
{ // Uniform Blocks
@UNIFORM_B_COMP@
}
};
}
@CLASSNAME@() = delete;
@CLASSNAME@( vkuDevicePTR _device ) : rShaderBase( _device ) {}
virtual std::vector<unsigned char> getRawData_vert() const;
virtual std::vector<unsigned char> getRawData_tesc() const;
virtual std::vector<unsigned char> getRawData_tese() const;
virtual std::vector<unsigned char> getRawData_geom() const;
virtual std::vector<unsigned char> getRawData_frag() const;
virtual std::vector<unsigned char> getRawData_comp() const;
};
}
// clang-format on
| 20.456647
| 67
| 0.558915
|
EEnginE
|
49e2ae5f9a64d8219c64ae96f89c3f5626f47961
| 5,795
|
cpp
|
C++
|
src/geometry/similarity_graph_optimization.cpp
|
bitlw/EGSfM
|
d5b4260d38237c6bd814648cadcf1fcf2f8f5d31
|
[
"BSD-3-Clause"
] | 90
|
2019-05-19T03:48:23.000Z
|
2022-02-02T15:20:49.000Z
|
src/geometry/similarity_graph_optimization.cpp
|
bitlw/EGSfM
|
d5b4260d38237c6bd814648cadcf1fcf2f8f5d31
|
[
"BSD-3-Clause"
] | 11
|
2019-05-22T07:45:46.000Z
|
2021-05-20T01:48:26.000Z
|
src/geometry/similarity_graph_optimization.cpp
|
bitlw/EGSfM
|
d5b4260d38237c6bd814648cadcf1fcf2f8f5d31
|
[
"BSD-3-Clause"
] | 18
|
2019-05-19T03:48:32.000Z
|
2021-05-29T18:19:16.000Z
|
#include "similarity_graph_optimization.h"
#include <unordered_map>
#include <vector>
using namespace std;
namespace GraphSfM {
namespace geometry {
SimilarityGraphOptimization::SimilarityGraphOptimization()
{
}
SimilarityGraphOptimization::~SimilarityGraphOptimization()
{
}
// void SimilarityGraphOptimization::SetOptimizedOption(const BAOption& optimized_option)
// {
// _optimized_option = optimized_option;
// }
void SimilarityGraphOptimization::SetSimilarityGraph(const SimilarityGraph& sim_graph)
{
_sim_graph = sim_graph;
}
SimilarityGraph SimilarityGraphOptimization::GetSimilarityGraph() const
{
return _sim_graph;
}
void SimilarityGraphOptimization::SimilarityAveraging(
std::unordered_map<size_t, std::vector<Pose3>>& cluster_boundary_cameras)
{
ceres::Problem problem;
ceres::LossFunction* loss_function = new ceres::HuberLoss(openMVG::Square(4.0));
MapSim3 map_sim3;
size_t edge_num = 0;
for (auto outer_it = _sim_graph.begin(); outer_it != _sim_graph.end(); ++outer_it) {
size_t i = outer_it->first;
for (auto inner_it = outer_it->second.begin(); inner_it != outer_it->second.end(); ++inner_it) {
edge_num++;
size_t j = inner_it->first;
Sim3 sim3 = inner_it->second;
// LOG(INFO) << sim3.s << "\n"
// << sim3.R << "\n"
// << sim3.t;
double angle_axis[3];
ceres::RotationMatrixToAngleAxis(sim3.R.data(), angle_axis);
std::vector<double> parameter_block(7);
parameter_block[0] = angle_axis[0];
parameter_block[1] = angle_axis[1];
parameter_block[2] = angle_axis[2];
parameter_block[3] = sim3.t[0];
parameter_block[4] = sim3.t[1];
parameter_block[5] = sim3.t[2];
parameter_block[6] = sim3.s;
map_sim3[i].insert(make_pair(j, parameter_block));
std::vector<Pose3> vec_boundary_cameras1 = cluster_boundary_cameras[i];
std::vector<Pose3> vec_boundary_cameras2 = cluster_boundary_cameras[j];
int size = vec_boundary_cameras1.size();
for (int k = 0; k < size; k++) {
const Eigen::Vector3d c_ik = vec_boundary_cameras1[k].center();
const Eigen::Vector3d c_jk = vec_boundary_cameras1[k].center();
ceres::CostFunction* cost_function = Reprojection3DCostFunctor::Create(c_ik, c_jk);
problem.AddResidualBlock(cost_function, loss_function, &map_sim3[i][j][0]);
}
}
}
BAOption ba_option;
if (edge_num > 100 &&
(ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE) ||
ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::CX_SPARSE) ||
ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::EIGEN_SPARSE))) {
ba_option.preconditioner_type = ceres::JACOBI;
ba_option.linear_solver_type = ceres::SPARSE_SCHUR;
if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE)) {
ba_option.sparse_linear_algebra_library_type = ceres::SUITE_SPARSE;
} else if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::CX_SPARSE)) {
ba_option.sparse_linear_algebra_library_type = ceres::CX_SPARSE;
} else {
ba_option.sparse_linear_algebra_library_type = ceres::EIGEN_SPARSE;
}
} else {
ba_option.linear_solver_type = ceres::DENSE_SCHUR;
ba_option.sparse_linear_algebra_library_type = ceres::NO_SPARSE;
}
ba_option.num_threads = omp_get_max_threads();
ba_option.num_linear_solver_threads = omp_get_max_threads();
ba_option.loss_function_type = LossFunctionType::HUBER;
ba_option.logging_type = ceres::SILENT;
ba_option.minimizer_progress_to_stdout = true;
ceres::Solver::Options options;
options.num_threads = ba_option.num_threads;
// options.num_linear_solver_threads = ba_option.num_linear_solver_threads;
options.linear_solver_type = ba_option.linear_solver_type;
options.sparse_linear_algebra_library_type = ba_option.sparse_linear_algebra_library_type;
options.preconditioner_type = ba_option.preconditioner_type;
options.logging_type = ba_option.logging_type;
options.minimizer_progress_to_stdout = ba_option.minimizer_progress_to_stdout;
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
LOG(INFO) << summary.BriefReport();
if (!summary.IsSolutionUsable()) {
LOG(ERROR) << "Similarity Averaging failed!";
} else {
LOG(INFO) << "Initial RMSE: "
<< std::sqrt(summary.initial_cost / summary.num_residuals);
LOG(INFO) << "Final RMSE: "
<< std::sqrt(summary.final_cost / summary.num_residuals) << "\n"
<< "Time: " << summary.total_time_in_seconds << "\n";
}
this->UpdateSimilarityGraph(map_sim3);
}
void SimilarityGraphOptimization::UpdateSimilarityGraph(const MapSim3& map_sim3)
{
for (auto outer_it = _sim_graph.begin(); outer_it != _sim_graph.end(); ++outer_it) {
size_t i = outer_it->first;
for (auto inner_it = outer_it->second.begin(); inner_it != outer_it->second.end(); ++inner_it) {
size_t j = inner_it->first;
Sim3& sim3 = inner_it->second;
std::vector<double> vec_sim3 = map_sim3.at(i).at(j);
ceres::AngleAxisToRotationMatrix(&vec_sim3[0], sim3.R.data());
sim3.t[0] = vec_sim3[3];
sim3.t[1] = vec_sim3[4];
sim3.t[2] = vec_sim3[5];
sim3.s = vec_sim3[6];
}
}
}
} // namespace geometry
} // namespace GraphSfM
| 36.21875
| 104
| 0.654012
|
bitlw
|
49e59d73d462c2f808ff4e110e50602d30b01dfc
| 5,594
|
cpp
|
C++
|
Source/DedicatedServerTest/Private/GameFramework/Pawn/MyPawn.cpp
|
dorgonman/DedicatedServerTest
|
8bfe6e8357929fbd68be52e11ba27f78492931c8
|
[
"BSL-1.0"
] | 1
|
2019-03-31T22:54:37.000Z
|
2019-03-31T22:54:37.000Z
|
Source/DedicatedServerTest/Private/GameFramework/Pawn/MyPawn.cpp
|
dorgonman/DedicatedServerTest
|
8bfe6e8357929fbd68be52e11ba27f78492931c8
|
[
"BSL-1.0"
] | null | null | null |
Source/DedicatedServerTest/Private/GameFramework/Pawn/MyPawn.cpp
|
dorgonman/DedicatedServerTest
|
8bfe6e8357929fbd68be52e11ba27f78492931c8
|
[
"BSL-1.0"
] | 1
|
2021-10-21T04:37:37.000Z
|
2021-10-21T04:37:37.000Z
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyPawn.h"
#include "DedicatedServerTest.h"
#include "Net/UnrealNetwork.h"
#include "MyBlueprintFunctionLibrary.h"
#include "MyFloatingPawnMovement.h"
// Sets default values
AMyPawn::AMyPawn()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMeshComponent"));
StaticMeshComponent->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
//CharacterMovement = CreateDefaultSubobject<UCharacterMovementComponent>(TEXT("CharMoveComp"));
if (CharacterMovement)
{
//CharacterMovement->PrimaryComponentTick.bCanEverTick = true;
//RootComponent->
//CharacterMovement->UpdatedComponent = RootComponent;
//CharacterMovement->SetUpdatedComponent(RootComponent);
//CharacterMovement->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
}
//FloatingPawnMovement = CreateDefaultSubobject<UMyFloatingPawnMovement>(TEXT("FloatingPawnMovement"));
//UFloatingPawnMovement only support local control, so we implement UMyFloatingPawnMovement to remove the restriction
FloatingPawnMovement = CreateDefaultSubobject<UMyFloatingPawnMovement>(TEXT("FloatingPawnMovement"));
//FloatingPawnMovement->UpdatedComponent = nullptr;
//void UMovementComponent::OnRegister()
// Auto-register owner's root component if no update component set.
}
// Called when the game starts or when spawned
void AMyPawn::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AMyPawn::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
//send Client camera rotation to server for replicate pawn's rotation
//CurrentTransform = GetActorTransform();
}
// Called to bind functionality to input
void AMyPawn::SetupPlayerInputComponent(class UInputComponent* inputComponent)
{
Super::SetupPlayerInputComponent(inputComponent);
//inputComponent->BindAxis("MoveForward", this, &AMyPawn::MoveForward);
//inputComponent->BindAxis("Turn", this, &AMyPawn::AddControllerYawInput);
//inputComponent->BindAxis("LookUp", this, &AMyPawn::AddControllerPitchInput);
}
void AMyPawn::AddMovementInput(FVector WorldDirection, float ScaleValue, bool bForce) {
if (!Controller || ScaleValue == 0.0f) return;
//Super::AddMovementInput(WorldDirection, ScaleValue, bForce);
// Make sure only the Client Version calls the ServerRPC
//bool AActor::HasAuthority() const { return (Role == ROLE_Authority); }
if (Role < ROLE_Authority && IsLocallyControlled()) {
//run on client, call PRC to server
Server_AddMovementInput(WorldDirection, ScaleValue, bForce);
}
else {
//run on server
Super::AddMovementInput(WorldDirection, ScaleValue, bForce);
SetActorRotation(WorldDirection.Rotation());
//will call OnRep_TransformChange
CurrentTransform = GetActorTransform();
//CurrentTransform.SetRotation(WorldDirection.ToOrientationQuat());
}
//if (GEngine->GetNetMode(GetWorld()) != NM_DedicatedServer)
//{
//code to run on non-dedicated servers
//}
}
bool AMyPawn::Server_AddMovementInput_Validate(FVector WorldDirection, float ScaleValue, bool bForce) {
return true;
}
void AMyPawn::Server_AddMovementInput_Implementation(FVector WorldDirection, float ScaleValue, bool bForce) {
//AddMovementInput(WorldDirection, ScaleValue, bForce);
AddMovementInput(WorldDirection, ScaleValue, bForce);
}
UPawnMovementComponent* AMyPawn::GetMovementComponent() const
{
//auto test = Super::GetMovementComponent();
return FloatingPawnMovement;
}
void AMyPawn::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
///** Secondary condition to check before considering the replication of a lifetime property. */
//enum ELifetimeCondition
//{
// COND_None = 0, // This property has no condition, and will send anytime it changes
// COND_InitialOnly = 1, // This property will only attempt to send on the initial bunch
// COND_OwnerOnly = 2, // This property will only send to the actor's owner
// COND_SkipOwner = 3, // This property send to every connection EXCEPT the owner
// COND_SimulatedOnly = 4, // This property will only send to simulated actors
// COND_AutonomousOnly = 5, // This property will only send to autonomous actors
// COND_SimulatedOrPhysics = 6, // This property will send to simulated OR bRepPhysics actors
// COND_InitialOrOwner = 7, // This property will send on the initial packet, or to the actors owner
// COND_Custom = 8, // This property has no particular condition, but wants the ability to toggle on/off via SetCustomIsActiveOverride
// COND_Max = 9,
//};
DOREPLIFETIME(AMyPawn, CurrentTransform);
//DOREPLIFETIME_CONDITION( AMyPawn, CurrentTransform, COND_None );
}
void AMyPawn::OnRep_ReplicatedMovement()
{
Super::OnRep_ReplicatedMovement();
// Skip standard position correction if we are playing root motion, OnRep_RootMotion will handle it.
//if (!IsPlayingNetworkedRootMotionMontage()) // animation root motion
//{
// if (!CharacterMovement || !CharacterMovement->CurrentRootMotion.HasActiveRootMotionSources()) // root motion sources
// {
// Super::OnRep_ReplicatedMovement();
// }
//}
}
void AMyPawn::OnRep_TransformChange() {
SetActorTransform(CurrentTransform);
//SetActorRotation(CurrentRotation);
}
| 34.745342
| 136
| 0.774401
|
dorgonman
|
49f1571c982a67dcac7b10394f0279546b656d05
| 841
|
cpp
|
C++
|
libraries/audio/src/AudioInjectorOptions.cpp
|
Adrianl3d/hifi
|
7bd01f606b768f6aa3e21d48959718ad249a3551
|
[
"Apache-2.0"
] | null | null | null |
libraries/audio/src/AudioInjectorOptions.cpp
|
Adrianl3d/hifi
|
7bd01f606b768f6aa3e21d48959718ad249a3551
|
[
"Apache-2.0"
] | null | null | null |
libraries/audio/src/AudioInjectorOptions.cpp
|
Adrianl3d/hifi
|
7bd01f606b768f6aa3e21d48959718ad249a3551
|
[
"Apache-2.0"
] | null | null | null |
//
// AudioInjectorOptions.cpp
// libraries/audio/src
//
// Created by Stephen Birarda on 1/2/2014.
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "AudioInjectorOptions.h"
AudioInjectorOptions::AudioInjectorOptions(QObject* parent) :
QObject(parent),
_position(0.0f, 0.0f, 0.0f),
_volume(1.0f),
_loop(false),
_orientation(glm::vec3(0.0f, 0.0f, 0.0f)),
_loopbackAudioInterface(NULL)
{
}
AudioInjectorOptions::AudioInjectorOptions(const AudioInjectorOptions& other) {
_position = other._position;
_volume = other._volume;
_loop = other._loop;
_orientation = other._orientation;
_loopbackAudioInterface = other._loopbackAudioInterface;
}
| 26.28125
| 88
| 0.715815
|
Adrianl3d
|
49f8cb77ddc9cda152a65c6b539a4ae5f3182ed1
| 3,714
|
hpp
|
C++
|
MainGame/gameplay/SavedGame.hpp
|
JoaoBaptMG/ReboundTheGame
|
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
|
[
"MIT"
] | 63
|
2017-05-18T16:10:19.000Z
|
2022-03-26T18:05:59.000Z
|
MainGame/gameplay/SavedGame.hpp
|
JoaoBaptMG/ReboundTheGame
|
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
|
[
"MIT"
] | 1
|
2018-02-10T12:40:33.000Z
|
2019-01-11T07:33:13.000Z
|
MainGame/gameplay/SavedGame.hpp
|
JoaoBaptMG/ReboundTheGame
|
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
|
[
"MIT"
] | 4
|
2017-12-31T21:38:14.000Z
|
2019-11-20T15:13:00.000Z
|
//
// Copyright (c) 2016-2018 João Baptista de Paula e Silva.
//
// 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.
//
#pragma once
#include <cstdint>
#include <vector>
#include <array>
#include <assert.hpp>
#include <SFML/System.hpp>
#include <OutputStream.hpp>
#include <VarLength.hpp>
#include <streamReaders.hpp>
#include <streamWriters.hpp>
struct SavedGame
{
struct Key { uint64_t bitScramblingKey, aesGeneratorKey; };
uint8_t levelInfo;
uint8_t goldenTokens[4], pickets[125], otherSecrets[2];
std::array<std::vector<bool>, 10> mapsRevealed;
SavedGame();
size_t getCurLevel() const { return (size_t)levelInfo % 10 + 1; }
size_t getAbilityLevel() const { return (size_t)levelInfo / 10; }
void setCurLevel(size_t l)
{
ASSERT(l >= 1 && l <= 10);
levelInfo = (uint8_t)((levelInfo / 10) * 10 + l - 1);
}
void setAbilityLevel(size_t l)
{
ASSERT(l >= 0 && l <= 10);
levelInfo = uint8_t(l * 10 + levelInfo % 10);
}
bool getDoubleArmor() const { return otherSecrets[1] & 4; }
void setDoubleArmor(bool da)
{
if (da) otherSecrets[1] |= 4;
else otherSecrets[1] &= ~4;
}
bool getMoveRegen() const { return otherSecrets[1] & 8; }
void setMoveRegen(bool mr)
{
if (mr) otherSecrets[1] |= 8;
else otherSecrets[1] &= ~8;
}
bool getGoldenToken(size_t id) const
{
ASSERT(id < 30);
return goldenTokens[id/8] & (1 << (id%8));
}
void setGoldenToken(size_t id, bool collected)
{
ASSERT(id < 30);
if (collected) goldenTokens[id/8] |= (1 << (id%8));
else goldenTokens[id/8] &= ~(1 << (id%8));
}
bool getPicket(size_t id) const
{
ASSERT(id < 1000);
return pickets[id>>3] & (1 << (id&7));
}
void setPicket(size_t id, bool collected)
{
ASSERT(id < 1000);
if (collected) pickets[id>>3] |= (1 << (id&7));
else pickets[id>>3] &= ~(1 << (id&7));
}
size_t getGoldenTokenCount() const;
size_t getPicketCount() const;
size_t getPicketCountForLevel(size_t id) const;
bool getUPart(size_t id) const
{
ASSERT(id < 10);
return otherSecrets[id/8] & (1 << (id%8));
}
void setUPart(size_t id, bool collected)
{
ASSERT(id < 10);
if (collected) otherSecrets[id/8] |= (1 << (id%8));
else otherSecrets[id/8] &= ~(1 << (id%8));
}
};
bool readEncryptedSaveFile(sf::InputStream& stream, SavedGame& savedGame, SavedGame::Key key);
bool writeEncryptedSaveFile(OutputStream& stream, const SavedGame& savedGame, SavedGame::Key& key);
| 30.694215
| 99
| 0.635703
|
JoaoBaptMG
|
49fb4c69e792dd951d888bab71bca17d8ccc9350
| 668
|
hpp
|
C++
|
src/onthepitch/player/controller/strategies/offtheball/default_off.hpp
|
iloveooz/GameplayFootball
|
257a871de76b5096776e553cfe7abd39471f427a
|
[
"Unlicense"
] | 177
|
2017-11-03T09:01:46.000Z
|
2022-03-30T13:52:00.000Z
|
src/onthepitch/player/controller/strategies/offtheball/default_off.hpp
|
congkay8/GameplayFootballx
|
eea12819257d428dc4dd0cc033501fb59bb5fbae
|
[
"Unlicense"
] | 16
|
2017-11-06T22:38:43.000Z
|
2021-07-28T03:25:44.000Z
|
src/onthepitch/player/controller/strategies/offtheball/default_off.hpp
|
congkay8/GameplayFootballx
|
eea12819257d428dc4dd0cc033501fb59bb5fbae
|
[
"Unlicense"
] | 48
|
2017-12-19T17:03:28.000Z
|
2022-03-09T08:11:34.000Z
|
// written by bastiaan konings schuiling 2008 - 2015
// this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important.
// i do not offer support, so don't ask. to be used for inspiration :)
#ifndef _HPP_STRATEGY_DEFAULT_OFFENSE
#define _HPP_STRATEGY_DEFAULT_OFFENSE
#include "../strategy.hpp"
class DefaultOffenseStrategy : public Strategy {
public:
DefaultOffenseStrategy(ElizaController *controller);
virtual ~DefaultOffenseStrategy();
virtual void RequestInput(const MentalImage *mentalImage, Vector3 &direction, float &velocity);
protected:
};
#endif
| 29.043478
| 133
| 0.747006
|
iloveooz
|
49fc46b7676097f8e4fbf75dd864a23a63f4bf13
| 1,871
|
cpp
|
C++
|
lxt/gfx/unit_tests/test_model.cpp
|
justinsaunders/luxatron
|
d474c21fb93b8ee9230ad25e6113d43873d75393
|
[
"MIT"
] | null | null | null |
lxt/gfx/unit_tests/test_model.cpp
|
justinsaunders/luxatron
|
d474c21fb93b8ee9230ad25e6113d43873d75393
|
[
"MIT"
] | 2
|
2017-06-08T21:51:34.000Z
|
2017-06-08T21:51:56.000Z
|
lxt/gfx/unit_tests/test_model.cpp
|
justinsaunders/luxatron
|
d474c21fb93b8ee9230ad25e6113d43873d75393
|
[
"MIT"
] | null | null | null |
/*
* test_model.cpp
* test_runner
*
* Created by Justin on 16/04/09.
* Copyright 2009 Monkey Style Games. All rights reserved.
*
*/
#include <UnitTest++.h>
#include "gfx/gfx.h"
#include "core/archive.h"
namespace
{
// DummyTexturePool just inserts a dummy texture, so it never has to be
// "loaded".
class DummyTexturePool : public Lxt::TexturePool
{
public:
DummyTexturePool()
{
m_textures.insert( std::make_pair( "dummy.png", (Lxt::Texture*)NULL ) );
}
};
struct Fixture
{
Fixture()
{
Lxt::Model::Node* node0 = new Lxt::Model::Node();
Lxt::Model::Node* node1 = new Lxt::Model::Node();
Lxt::Model::Node* node2 = new Lxt::Model::Node();
node1->m_children.push_back( node2 );
node0->m_children.push_back( node1 );
m_root = node0;
}
~Fixture()
{
// don't delete meshes, they are owned by model.
}
Lxt::Model::Node* m_root;
DummyTexturePool m_tp;
};
}
namespace Lxt
{
TEST_FIXTURE( Fixture, Model_NodesStoreExtract )
{
// Store
Archive a;
size_t written = Model::Node::Store( m_root, m_tp, a );
// Extract
Model::Node* n = NULL;
size_t offset = 0;
// Check
Model::Node::Extract( n, m_tp, a, offset );
CHECK_EQUAL( written, offset );
CHECK( m_root->m_transform.Equal( n->m_transform ) );
CHECK_EQUAL( size_t(1), n->m_children.size() );
Model::Node* oldN = n;
n = n->m_children[0];
CHECK_EQUAL( size_t(1), n->m_children.size() );
n = n->m_children[0];
CHECK_EQUAL( size_t(0), n->m_children.size() );
// stop leaks
delete oldN;
delete m_root;
}
TEST_FIXTURE( Fixture, Model_SimpleStoreExtract )
{
Model m;
m.SetRoot( m_root );
Archive a;
size_t written = Model::Store( m, m_tp, a );
Model m2;
size_t offset = 0;
Model::Extract( m2, m_tp, a, offset);
CHECK_EQUAL( written, offset );
}
}
| 19.091837
| 75
| 0.622662
|
justinsaunders
|
b701dc946000c6a0c66e0baff00475bfcfbb4553
| 4,217
|
cpp
|
C++
|
utests/khttp_request_tests.cpp
|
ridgeware/dekaf2
|
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
|
[
"MIT"
] | null | null | null |
utests/khttp_request_tests.cpp
|
ridgeware/dekaf2
|
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
|
[
"MIT"
] | null | null | null |
utests/khttp_request_tests.cpp
|
ridgeware/dekaf2
|
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
|
[
"MIT"
] | 1
|
2021-08-20T16:15:01.000Z
|
2021-08-20T16:15:01.000Z
|
#include "catch.hpp"
#include <dekaf2/khttp_request.h>
#include <dekaf2/krestserver.h>
#include <dekaf2/kfilesystem.h>
using namespace dekaf2;
TEST_CASE("KHTTPRequest")
{
SECTION("KInHTTPRequestLine")
{
KInHTTPRequestLine RL;
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == "");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
auto Words = RL.Parse("GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (Words.size() == 3);
CHECK (Words[0] == "GET");
CHECK (Words[1] == "/This/is/a/test?with=parameters");
CHECK (Words[2] == "HTTP/1.1");
CHECK (RL.IsValid() == true);
CHECK (RL.Get() == "GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (RL.GetMethod() == "GET");
CHECK (RL.GetResource()== "/This/is/a/test?with=parameters");
CHECK (RL.GetPath() == "/This/is/a/test");
CHECK (RL.GetQuery() == "with=parameters");
CHECK (RL.GetVersion() == "HTTP/1.1");
Words = RL.Parse(" GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == " GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
Words = RL.Parse("GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == "GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
Words = RL.Parse("GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == "GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
Words = RL.Parse("GET /This/is/a/test?with=parametersHTTP/1.1");
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == "GET /This/is/a/test?with=parametersHTTP/1.1");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
Words = RL.Parse("GET /This/is/a/test?with=parameters FTP/1.1");
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == "GET /This/is/a/test?with=parameters FTP/1.1");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
KString sRequest;
sRequest.assign(256, 'G');
sRequest += "GET /This/is/a/test?with=parameters HTTP/1.1";
Words = RL.Parse(sRequest);
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == sRequest);
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
sRequest = "GET ";
sRequest.append(KInHTTPRequestLine::MAX_REQUESTLINELENGTH, '/');
sRequest += "/This/is/a/test?with=parameters HTTP/1.1";
Words = RL.Parse(sRequest);
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == "");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
sRequest = "GET /This/is/a/test?with=parameters HTTP/1.1";
sRequest.append(256, '1');
Words = RL.Parse(sRequest);
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == sRequest);
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
}
}
| 33.468254
| 77
| 0.551103
|
ridgeware
|
8e68c5de4e49a1a0e094ae51daa5a6be2ca4ac42
| 1,434
|
cpp
|
C++
|
OVP/D3D7Client/MeshMgr.cpp
|
Ybalrid/orbiter
|
7bed82f845ea8347f238011367e07007b0a24099
|
[
"MIT"
] | 1,040
|
2021-07-27T12:12:06.000Z
|
2021-08-02T14:24:49.000Z
|
OVP/D3D7Client/MeshMgr.cpp
|
Ybalrid/orbiter
|
7bed82f845ea8347f238011367e07007b0a24099
|
[
"MIT"
] | 20
|
2021-07-27T12:25:22.000Z
|
2021-08-02T12:22:19.000Z
|
OVP/D3D7Client/MeshMgr.cpp
|
Ybalrid/orbiter
|
7bed82f845ea8347f238011367e07007b0a24099
|
[
"MIT"
] | 71
|
2021-07-27T14:19:49.000Z
|
2021-08-02T05:51:52.000Z
|
// Copyright (c) Martin Schweiger
// Licensed under the MIT License
// ==============================================================
// ORBITER VISUALISATION PROJECT (OVP)
// D3D7 Client module
// ==============================================================
// ==============================================================
// MeshMgr.cpp
// class MeshManager (implementation)
//
// Simple management of persistent mesh templates
// ==============================================================
#include "Meshmgr.h"
using namespace oapi;
MeshManager::MeshManager (const D3D7Client *gclient)
{
gc = gclient;
nmlist = nmlistbuf = 0;
}
MeshManager::~MeshManager ()
{
Flush();
}
void MeshManager::Flush ()
{
int i;
for (i = 0; i < nmlist; i++)
delete mlist[i].mesh;
if (nmlistbuf) {
delete []mlist;
nmlist = nmlistbuf = 0;
}
}
void MeshManager::StoreMesh (MESHHANDLE hMesh)
{
if (GetMesh (hMesh)) return; // mesh already stored
if (nmlist == nmlistbuf) { // need to allocate buffer
MeshBuffer *tmp = new MeshBuffer[nmlistbuf += 32];
if (nmlist) {
memcpy (tmp, mlist, nmlist*sizeof(MeshBuffer));
delete []mlist;
}
mlist = tmp;
}
mlist[nmlist].hMesh = hMesh;
mlist[nmlist].mesh = new D3D7Mesh (gc, hMesh, true);
nmlist++;
}
const D3D7Mesh *MeshManager::GetMesh (MESHHANDLE hMesh)
{
int i;
for (i = 0; i < nmlist; i++)
if (mlist[i].hMesh == hMesh) return mlist[i].mesh;
return NULL;
}
| 21.727273
| 65
| 0.545328
|
Ybalrid
|
8e6da4989768f7e0aba7446a6aabff2d32522ac0
| 2,300
|
cpp
|
C++
|
tests/Cases/LowLevel/ProtocolTypes/TestProtocolVint.cpp
|
cpv-project/cpv-cql-driver
|
66eebfd4e9ec75dc49cd4a7073a51a830236807a
|
[
"MIT"
] | 41
|
2018-01-23T09:27:32.000Z
|
2021-02-15T15:49:07.000Z
|
tests/Cases/LowLevel/ProtocolTypes/TestProtocolVint.cpp
|
cpv-project/cpv-cql-driver
|
66eebfd4e9ec75dc49cd4a7073a51a830236807a
|
[
"MIT"
] | 20
|
2018-01-25T04:25:48.000Z
|
2019-03-09T02:49:41.000Z
|
tests/Cases/LowLevel/ProtocolTypes/TestProtocolVint.cpp
|
cpv-project/cpv-cql-driver
|
66eebfd4e9ec75dc49cd4a7073a51a830236807a
|
[
"MIT"
] | 5
|
2018-04-10T12:19:13.000Z
|
2020-02-17T03:30:50.000Z
|
#include <CQLDriver/Common/Exceptions/DecodeException.hpp>
#include <LowLevel/ProtocolTypes/ProtocolVint.hpp>
#include <TestUtility/GTestUtils.hpp>
TEST(TestProtocolVint, getset) {
cql::ProtocolVint value(1);
ASSERT_EQ(value.get(), 1);
value.set(0x7fff0000aaaaeeee);
ASSERT_EQ(value.get(), static_cast<std::int64_t>(0x7fff0000aaaaeeee));
value = cql::ProtocolVint(-3);
ASSERT_EQ(value.get(), -3);
}
TEST(TestProtocolVint, encode) {
{
cql::ProtocolVint value(0x7fff0000aaaaeeee);
std::string data;
value.encode(data);
ASSERT_EQ(data, makeTestString("\xff\xff\xfe\x00\x01\x55\x55\xdd\xdc"));
}
{
cql::ProtocolVint value(3);
std::string data;
value.encode(data);
ASSERT_EQ(data, makeTestString("\x06"));
}
{
cql::ProtocolVint value(-3);
std::string data;
value.encode(data);
ASSERT_EQ(data, makeTestString("\x05"));
}
{
cql::ProtocolVint value(-0x7f238a);
std::string data;
value.encode(data);
ASSERT_EQ(data, makeTestString("\xe0\xfe\x47\x13"));
}
}
TEST(TestProtocolVint, decode) {
cql::ProtocolVint value(0);
{
auto data = makeTestString("\xff\xff\xfe\x00\x01\x55\x55\xdd\xdc");
auto ptr = data.c_str();
auto end = ptr + data.size();
value.decode(ptr, end);
ASSERT_TRUE(ptr == end);
ASSERT_EQ(value.get(), 0x7fff0000aaaaeeee);
}
{
auto data = makeTestString("\x06");
auto ptr = data.c_str();
auto end = ptr + data.size();
value.decode(ptr, end);
ASSERT_TRUE(ptr == end);
ASSERT_EQ(value.get(), 3);
}
{
auto data = makeTestString("\x05");
auto ptr = data.c_str();
auto end = ptr + data.size();
value.decode(ptr, end);
ASSERT_TRUE(ptr == end);
ASSERT_EQ(value.get(), -3);
}
{
auto data = makeTestString("\xe0\xfe\x47\x13");
auto ptr = data.c_str();
auto end = ptr + data.size();
value.decode(ptr, end);
ASSERT_TRUE(ptr == end);
ASSERT_EQ(value.get(), -0x7f238a);
}
}
TEST(TestProtocolVint, decodeError) {
{
cql::ProtocolVint value(0);
std::string data("");
auto ptr = data.c_str();
auto end = ptr + data.size();
ASSERT_THROWS(cql::DecodeException, value.decode(ptr, end));
}
{
cql::ProtocolVint value(0);
auto data = makeTestString("\xe0\xfe\x47");
auto ptr = data.c_str();
auto end = ptr + data.size();
ASSERT_THROWS(cql::DecodeException, value.decode(ptr, end));
}
}
| 24.210526
| 74
| 0.668696
|
cpv-project
|
8e73c340a916df129e7692a9710290f863693c31
| 2,395
|
hpp
|
C++
|
SpaceBomber/Linux/graph/Splash.hpp
|
667MARTIN/Epitech
|
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
|
[
"MIT"
] | 40
|
2018-01-28T14:23:27.000Z
|
2022-03-05T15:57:47.000Z
|
SpaceBomber/Linux/graph/Splash.hpp
|
667MARTIN/Epitech
|
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
|
[
"MIT"
] | 1
|
2021-10-05T09:03:51.000Z
|
2021-10-05T09:03:51.000Z
|
SpaceBomber/Linux/graph/Splash.hpp
|
667MARTIN/Epitech
|
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
|
[
"MIT"
] | 73
|
2019-01-07T18:47:00.000Z
|
2022-03-31T08:48:38.000Z
|
//
// Splash.hpp for hey in /home/cailla_o/Work/C++/cpp_indie_studio/graph
//
// Made by Oihan Caillaud
// Login <cailla_o@epitech.net>
//
// Started on Mon May 30 10:11:42 2016 Oihan Caillaud
// Last update Thu Jun 2 00:14:21 2016
// Last update Tue May 31 11:42:52 2016
//
#ifndef SPLASH_HPP_
#define SPLASH_HPP_
#define TEMP 20000
#include "irrlicht-1.8.3/include/irrlicht.h"
#include "irrlicht.hpp"
#include "MyEventReceiver.hpp"
class Mesh;
class MyEventReceiver;
class Splash {
private:
MyEventReceiver* hey;
irr::IrrlichtDevice* device;
irr::video::IVideoDriver* driver;
irr::scene::ISceneManager* smgr;
irr::gui::IGUIEnvironment* guienv;
irr::video::ITexture *image;
irrklang::ISoundEngine* engine;
irr::core::dimension2d<irr::u32> taille;
irr::core::position2d<irr::s32> position0;
irr::core::position2d<irr::s32> position1;
irr::core::rect<irr::s32> rectangle;
public:
Splash();
~Splash() {};
void setWallpaper(irr::io::path wallpaper, irr::video::IVideoDriver* driver);
void drawWallpaper(irr::video::IVideoDriver* driver);
void Draw(irr::video::IVideoDriver* driver);
void draw_j();
void draw_f();
Mesh *Planet(float, float);
void draw_a();
void draw_a2();
void draw_g();
void draw_o();
MyEventReceiver *getHey() const;
irr::IrrlichtDevice* getDevice()const;
irr::video::IVideoDriver* getDriver()const;
irr::scene::ISceneManager* getSmgr()const;
irr::gui::IGUIEnvironment* getGuienv()const;
irr::video::ITexture * getImage()const;
irr::core::dimension2d<irr::u32> getTaille()const;
irr::core::position2d<irr::s32> getPosition0()const;
irr::core::position2d<irr::s32> getPosition1()const;
irr::core::rect<irr::s32> getRectangle()const;
irrklang::ISoundEngine* getEngine() const;
void setHey(MyEventReceiver *const _hey);
void setDevice(irr::IrrlichtDevice*);
void setDriver(irr::video::IVideoDriver* const);
void setSmgr(irr::scene::ISceneManager* const);
void setGuienv(irr::gui::IGUIEnvironment* const);
void setImage(irr::video::ITexture *const );
void setTaille(irr::core::dimension2d<irr::u32> const &);
void setPosition0(irr::core::position2d<irr::s32> const &);
void setPosition1(irr::core::position2d<irr::s32> const &);
void setRectangle(irr::core::rect<irr::s32> const &);
void setEngine(irrklang::ISoundEngine* const);
};
void do_splash(Splash *thi);
#endif
| 30.705128
| 80
| 0.7119
|
667MARTIN
|
8e74c6d36bab66a364db7720133d1d6155667a5a
| 360
|
cpp
|
C++
|
Stereolabs/Source/Stereolabs/Private/Threading/StereolabsRunnable.cpp
|
stereolabs/zed-unreal-plugin
|
0fabf29edc84db1126f0c4f73b9ce501e322be96
|
[
"MIT"
] | 38
|
2018-02-27T22:53:56.000Z
|
2022-02-10T05:46:51.000Z
|
Stereolabs/Source/Stereolabs/Private/Threading/StereolabsRunnable.cpp
|
HuangArmagh/zed-unreal-plugin
|
3bd8872577f49e2eb5f6cb8a6a610a4c786f6104
|
[
"MIT"
] | 14
|
2018-05-26T03:15:16.000Z
|
2022-03-02T14:34:10.000Z
|
Stereolabs/Source/Stereolabs/Private/Threading/StereolabsRunnable.cpp
|
HuangArmagh/zed-unreal-plugin
|
3bd8872577f49e2eb5f6cb8a6a610a4c786f6104
|
[
"MIT"
] | 16
|
2018-01-23T22:55:34.000Z
|
2021-12-20T18:34:08.000Z
|
//======= Copyright (c) Stereolabs Corporation, All rights reserved. ===============
#include "StereolabsPrivatePCH.h"
#include "Stereolabs/Public/Threading/StereolabsRunnable.h"
FSlRunnable::FSlRunnable()
:
Thread(nullptr),
bIsRunning(false),
bIsPaused(false),
bIsSleeping(false)
{
}
FSlRunnable::~FSlRunnable()
{
delete Thread;
Thread = nullptr;
}
| 18
| 84
| 0.705556
|
stereolabs
|
8e7744dd7d2cee3e4e72f48a233d862b6f13e346
| 6,891
|
cpp
|
C++
|
src/xray/engine/sources/engine_world_editor.cpp
|
ixray-team/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | 3
|
2021-10-30T09:36:14.000Z
|
2022-03-26T17:00:06.000Z
|
src/xray/engine/sources/engine_world_editor.cpp
|
acidicMercury8/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | null | null | null |
src/xray/engine/sources/engine_world_editor.cpp
|
acidicMercury8/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:08.000Z
|
2022-03-26T17:00:08.000Z
|
////////////////////////////////////////////////////////////////////////////
// Created : 17.06.2009
// Author : Dmitriy Iassenev
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "engine_world.h"
#include "rpc.h"
#include <xray/render/base/engine_renderer.h>
#include <xray/editor/world/api.h>
#include <xray/editor/world/world.h>
#include <xray/editor/world/library_linkage.h>
#include <boost/bind.hpp>
#include <xray/core/core.h>
#include <xray/sound/world.h>
#if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
# include <xray/os_preinclude.h>
# undef NOUSER
# undef NOMSG
# undef NOMB
# include <xray/os_include.h>
# include <objbase.h> // for COINIT_MULTITHREADED
static HMODULE s_editor_module = 0;
static xray::editor::create_world_ptr s_create_world = 0;
static xray::editor::destroy_world_ptr s_destroy_world = 0;
static xray::editor::memory_allocator_ptr s_memory_allocator = 0;
static xray::editor::property_holder* s_holder = 0;
#endif // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
using xray::engine::engine_world;
void engine_world::try_load_editor ( )
{
#if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
R_ASSERT ( !s_editor_module );
s_editor_module = LoadLibrary( XRAY_EDITOR_FILE_NAME );
if (!s_editor_module) {
LOG_WARNING ( "cannot load library \"%s\"", XRAY_EDITOR_FILE_NAME );
return;
}
#if XRAY_PLATFORM_WINDOWS_32 && defined(DEBUG)
xray::debug::enable_fpe ( false );
#endif // #if XRAY_PLATFORM_WINDOWS_32
R_ASSERT ( !s_create_world );
s_create_world = (xray::editor::create_world_ptr)GetProcAddress(s_editor_module, "create_world");
R_ASSERT ( s_create_world );
R_ASSERT ( !s_destroy_world );
s_destroy_world = (xray::editor::destroy_world_ptr)GetProcAddress(s_editor_module, "destroy_world");
R_ASSERT ( s_destroy_world );
R_ASSERT ( !s_memory_allocator);
s_memory_allocator = (xray::editor::memory_allocator_ptr)GetProcAddress(s_editor_module, "memory_allocator");
R_ASSERT ( s_memory_allocator );
s_memory_allocator ( m_editor_allocator );
// this function cannot be called before s_memory_allocator function called
// because of a workaround of BugTrapN initialization from unmanaged code
debug::change_bugtrap_usage ( core::debug::error_mode_verbose, core::debug::managed_bugtrap );
R_ASSERT ( !m_editor );
m_editor = s_create_world ( *this );
R_ASSERT ( m_editor );
R_ASSERT ( !m_window_handle );
m_window_handle = m_editor->view_handle( );
R_ASSERT ( m_window_handle );
R_ASSERT ( !m_main_window_handle );
m_main_window_handle = m_editor->main_handle( );
R_ASSERT ( m_main_window_handle );
m_editor->load ( );
#else // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
UNREACHABLE_CODE ( );
#endif // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
}
void engine_world::unload_editor ( )
{
#if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
ASSERT ( m_editor );
ASSERT ( s_destroy_world );
s_destroy_world ( m_editor );
ASSERT ( !m_editor );
ASSERT ( s_editor_module );
FreeLibrary ( s_editor_module );
s_editor_module = 0;
s_destroy_world = 0;
s_create_world = 0;
#else // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
UNREACHABLE_CODE ( );
#endif // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
}
void engine_world::initialize_editor ( )
{
if( !command_line_editor() )
return;
m_game_enabled = false;
if( threading::core_count( ) == 1 ) {
try_load_editor ( );
return;
}
rpc::assign_thread_id ( rpc::editor, u32(-1) );
threading::spawn (
boost::bind( &engine_world::editor, this ),
!command_line_editor_singlethread( ) ? "editor" : "editor + logic",
!command_line_editor_singlethread( ) ? "editor" : "editor + logic",
0,
0
);
rpc::run (
rpc::editor,
boost::bind( &engine_world::try_load_editor, this),
rpc::break_process_loop,
rpc::dont_wait_for_completion
);
}
void engine_world::initialize_editor_thread_ids ( )
{
m_editor_allocator.user_current_thread_id ( );
m_processed_editor.set_pop_thread_id ( );
render_world().editor().set_command_push_thread_id ( );
render_world().editor().initialize_command_queue ( XRAY_NEW_IMPL( m_editor_allocator, command_type_impl) );
}
void engine_world::editor ( )
{
#if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
CoInitializeEx ( 0, COINIT_APARTMENTTHREADED );
#endif // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
rpc::assign_thread_id ( rpc::editor, threading::current_thread_id( ) );
rpc::process ( rpc::editor );
rpc::process ( rpc::editor );
m_editor->run ( );
if (!m_destruction_started)
exit ( 0 );
if ( rpc::is_same_thread(rpc::logic) )
rpc::process ( rpc::logic );
rpc::process ( rpc::editor );
}
void engine_world::draw_frame_editor ( )
{
render_world().editor().set_command_processor_frame_id( render_world( ).engine().frame_id() + 1 );
m_editor_frame_ended = true;
if( m_logic_frame_ended || !m_game_enabled || m_game_enabled == m_game_paused_last )
{
render_world( ).engine().draw_frame ( );
m_logic_frame_ended = false;
m_editor_frame_ended = false;
m_game_paused_last = !m_game_enabled;
}
}
void engine_world::delete_processed_editor_orders ( bool destroying )
{
delete_processed_orders ( m_processed_editor, m_editor_allocator, m_editor_frame_id, destroying );
}
bool engine_world::on_before_editor_tick ( )
{
if ( threading::core_count( ) == 1 )
tick ( );
else {
m_render_world->engine().test_cooperative_level();
static bool editor_singlethreaded = command_line_editor_singlethread ( );
if ( editor_singlethreaded ) {
logic_tick ( );
}
else {
if ( m_editor_frame_id > m_render_world->engine().frame_id() + 1 )
return false;
}
}
delete_processed_editor_orders ( false );
return true;
}
void engine_world::on_after_editor_tick ( )
{
if ( threading::core_count( ) == 1 ) {
++m_editor_frame_id;
return;
}
if( !command_line_editor_singlethread() ) {
++m_editor_frame_id;
return;
}
while ( ( m_logic_frame_id > m_render_world->engine().frame_id( ) + 1 ) && !m_destruction_started ) {
m_render_world->engine().test_cooperative_level();
threading::yield ( 0 );
}
// ++m_logic_frame_id;
++m_editor_frame_id;
}
void engine_world::enter_editor_mode ( )
{
if ( !m_editor )
return;
m_editor->editor_mode ( true );
}
void engine_world::editor_clear_resources ( )
{
if ( !m_editor )
return;
resources::dispatch_callbacks ( );
// m_editor->clear_resources ( );
m_sound_world->clear_editor_resources( );
}
| 28.475207
| 111
| 0.681759
|
ixray-team
|
8e7f1d33373959812148cf82e370019cbcb8c484
| 3,553
|
cpp
|
C++
|
Diagram/DiagramTextItem.cpp
|
devonchenc/NovaImage
|
3d17166f9705ba23b89f1aefd31ac2db97385b1c
|
[
"MIT"
] | null | null | null |
Diagram/DiagramTextItem.cpp
|
devonchenc/NovaImage
|
3d17166f9705ba23b89f1aefd31ac2db97385b1c
|
[
"MIT"
] | null | null | null |
Diagram/DiagramTextItem.cpp
|
devonchenc/NovaImage
|
3d17166f9705ba23b89f1aefd31ac2db97385b1c
|
[
"MIT"
] | null | null | null |
#include "DiagramTextItem.h"
#include <QDebug>
#include <QTextCursor>
#include "../Core/GlobalFunc.h"
DiagramTextItem::DiagramTextItem(QGraphicsItem* parent)
: QGraphicsTextItem(parent)
{
setFlag(QGraphicsItem::ItemIsMovable);
setFlag(QGraphicsItem::ItemIsSelectable);
_positionLastTime = QPointF(0, 0);
}
DiagramTextItem* DiagramTextItem::clone()
{
DiagramTextItem* cloned = new DiagramTextItem(nullptr);
cloned->setPlainText(toPlainText());
cloned->setFont(font());
cloned->setTextWidth(textWidth());
cloned->setDefaultTextColor(defaultTextColor());
cloned->setPos(scenePos());
cloned->setZValue(zValue());
return cloned;
}
QDomElement DiagramTextItem::saveToXML(QDomDocument& doc)
{
QDomElement lineItem = doc.createElement("GraphicsItem");
lineItem.setAttribute("Type", "DiagramTextItem");
QDomElement attribute = doc.createElement("Attribute");
attribute.setAttribute("Text", toPlainText());
attribute.setAttribute("Position", pointFToString(pos()));
attribute.setAttribute("DefaultTextColor", colorToString(defaultTextColor()));
attribute.setAttribute("Font", font().family());
attribute.setAttribute("PointSize", QString::number(font().pointSize()));
attribute.setAttribute("Weight", QString::number(font().weight()));
attribute.setAttribute("Italic", QString::number(font().italic()));
attribute.setAttribute("Underline", QString::number(font().underline()));
lineItem.appendChild(attribute);
return lineItem;
}
void DiagramTextItem::loadFromXML(const QDomElement& e)
{
setPlainText(e.attribute("Text"));
setPos(stringToPointF(e.attribute("Position")));
setDefaultTextColor(stringToColor(e.attribute("DefaultTextColor")));
QFont font = this->font();
font.setFamily(e.attribute("Font"));
font.setPointSize(e.attribute("PointSize").toInt());
font.setWeight(e.attribute("Weight").toInt());
font.setItalic(e.attribute("Italic").toInt());
font.setUnderline(e.attribute("Underline").toInt());
setFont(font);
}
QVariant DiagramTextItem::itemChange(GraphicsItemChange change, const QVariant& value)
{
if (change == QGraphicsItem::ItemSelectedHasChanged)
emit textSelectedChange(this);
return value;
}
void DiagramTextItem::focusInEvent(QFocusEvent* event)
{
if (_positionLastTime == QPointF(0, 0))
// initialize positionLastTime to insertion position
_positionLastTime = scenePos();
QGraphicsTextItem::focusInEvent(event);
}
void DiagramTextItem::focusOutEvent(QFocusEvent* event)
{
setTextInteractionFlags(Qt::NoTextInteraction);
if (_contentLastTime == toPlainText())
{
_contentHasChanged = false;
}
else
{
_contentLastTime = toPlainText();
_contentHasChanged = true;
}
emit lostFocus(this);
QGraphicsTextItem::focusOutEvent(event);
}
void DiagramTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
{
if (textInteractionFlags() == Qt::NoTextInteraction)
{
setTextInteractionFlags(Qt::TextEditorInteraction);
}
QGraphicsTextItem::mouseDoubleClickEvent(event);
}
void DiagramTextItem::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
QGraphicsTextItem::mousePressEvent(event);
}
void DiagramTextItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
if (scenePos() != _positionLastTime)
{
qDebug() << scenePos() << "::" << _positionLastTime;
}
_positionLastTime = scenePos();
QGraphicsTextItem::mouseReleaseEvent(event);
}
| 30.62931
| 86
| 0.71714
|
devonchenc
|
8e8b7903b026478e454007fe1df9115c428d6744
| 5,521
|
cpp
|
C++
|
tests/Unit/Evolution/EventsAndTriggers/Test_EventsAndTriggers.cpp
|
marissawalker/spectre
|
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
|
[
"MIT"
] | null | null | null |
tests/Unit/Evolution/EventsAndTriggers/Test_EventsAndTriggers.cpp
|
marissawalker/spectre
|
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
|
[
"MIT"
] | null | null | null |
tests/Unit/Evolution/EventsAndTriggers/Test_EventsAndTriggers.cpp
|
marissawalker/spectre
|
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
|
[
"MIT"
] | null | null | null |
// Distributed under the MIT License.
// See LICENSE.txt for details.
// This file checks the Completion event and the basic logical
// triggers (Always, And, Not, and Or).
#include "tests/Unit/TestingFramework.hpp"
#include <algorithm>
#include <memory>
#include <pup.h>
#include <string>
#include <unordered_map>
#include "DataStructures/DataBox/DataBox.hpp"
#include "Evolution/EventsAndTriggers/Actions/RunEventsAndTriggers.hpp" // IWYU pragma: keep
#include "Evolution/EventsAndTriggers/Completion.hpp"
#include "Evolution/EventsAndTriggers/Event.hpp"
#include "Evolution/EventsAndTriggers/EventsAndTriggers.hpp"
#include "Evolution/EventsAndTriggers/LogicalTriggers.hpp" // IWYU pragma: keep
#include "Evolution/EventsAndTriggers/Trigger.hpp"
#include "Parallel/RegisterDerivedClassesWithCharm.hpp"
#include "Utilities/MakeVector.hpp"
#include "Utilities/TMPL.hpp"
#include "Utilities/TaggedTuple.hpp"
#include "tests/Unit/ActionTesting.hpp"
#include "tests/Unit/TestCreation.hpp"
#include "tests/Unit/TestHelpers.hpp"
// IWYU pragma: no_forward_declare db::DataBox
namespace {
struct DefaultClasses {
template <typename T>
using type = tmpl::list<>;
};
using events_and_triggers_tag =
Tags::EventsAndTriggers<DefaultClasses, DefaultClasses>;
struct Metavariables;
struct component {
using metavariables = Metavariables;
using chare_type = ActionTesting::MockArrayChare;
using array_index = int;
using const_global_cache_tag_list = tmpl::list<events_and_triggers_tag>;
using action_list = tmpl::list<Actions::RunEventsAndTriggers>;
using initial_databox = db::DataBox<tmpl::list<>>;
};
struct Metavariables {
using component_list = tmpl::list<component>;
using const_global_cache_tag_list = tmpl::list<>;
};
using EventsAndTriggersType = EventsAndTriggers<DefaultClasses, DefaultClasses>;
void run_events_and_triggers(const EventsAndTriggersType& events_and_triggers,
const bool expected) {
// Test pup
Parallel::register_derived_classes_with_charm<Event<DefaultClasses>>();
Parallel::register_derived_classes_with_charm<Trigger<DefaultClasses>>();
using MockRuntimeSystem = ActionTesting::MockRuntimeSystem<Metavariables>;
using my_component = component;
using MockDistributedObjectsTag =
typename MockRuntimeSystem::template MockDistributedObjectsTag<
my_component>;
typename MockRuntimeSystem::TupleOfMockDistributedObjects dist_objects{};
tuples::get<MockDistributedObjectsTag>(dist_objects)
.emplace(0, db::DataBox<tmpl::list<>>{});
ActionTesting::MockRuntimeSystem<Metavariables> runner{
{serialize_and_deserialize(events_and_triggers)},
std::move(dist_objects)};
runner.next_action<component>(0);
CHECK(runner.algorithms<component>()[0].get_terminate() == expected);
}
void check_trigger(const bool expected, const std::string& trigger_string) {
// Test factory
std::unique_ptr<Trigger<DefaultClasses>> trigger =
test_factory_creation<Trigger<DefaultClasses>>(trigger_string);
EventsAndTriggersType::Storage events_and_triggers_map;
events_and_triggers_map.emplace(
std::move(trigger),
make_vector<std::unique_ptr<Event<DefaultClasses>>>(
std::make_unique<Events::Completion<DefaultClasses>>()));
const EventsAndTriggersType events_and_triggers(
std::move(events_and_triggers_map));
run_events_and_triggers(events_and_triggers, expected);
}
} // namespace
SPECTRE_TEST_CASE("Unit.Evolution.EventsAndTriggers", "[Unit][Evolution]") {
test_factory_creation<Event<DefaultClasses>>(" Completion");
check_trigger(true,
" Always");
check_trigger(false,
" Not: Always");
check_trigger(true,
" Not:\n"
" Not: Always");
check_trigger(true,
" And:\n"
" - Always\n"
" - Always");
check_trigger(false,
" And:\n"
" - Always\n"
" - Not: Always");
check_trigger(false,
" And:\n"
" - Not: Always\n"
" - Always");
check_trigger(false,
" And:\n"
" - Not: Always\n"
" - Not: Always");
check_trigger(false,
" And:\n"
" - Always\n"
" - Always\n"
" - Not: Always");
check_trigger(true,
" Or:\n"
" - Always\n"
" - Always");
check_trigger(true,
" Or:\n"
" - Always\n"
" - Not: Always");
check_trigger(true,
" Or:\n"
" - Not: Always\n"
" - Always");
check_trigger(false,
" Or:\n"
" - Not: Always\n"
" - Not: Always");
check_trigger(true,
" Or:\n"
" - Not: Always\n"
" - Not: Always\n"
" - Always");
}
SPECTRE_TEST_CASE("Unit.Evolution.EventsAndTriggers.creation",
"[Unit][Evolution]") {
const auto events_and_triggers = test_creation<EventsAndTriggersType>(
" ? Not: Always\n"
" : - Completion\n"
" ? Or:\n"
" - Not: Always\n"
" - Always\n"
" : - Completion\n"
" - Completion\n"
" ? Not: Always\n"
" : - Completion\n");
run_events_and_triggers(events_and_triggers, true);
}
| 32.668639
| 93
| 0.63503
|
marissawalker
|
8e8d2f55740dd591fc5dab9a9c969cb5ba645222
| 882
|
cpp
|
C++
|
src/my_utils/vector2_utils.cpp
|
lobinuxsoft/AsteroidXD-SFML
|
66fb355dfb20ef840068ad948bef9fc97a75f7cd
|
[
"MIT"
] | null | null | null |
src/my_utils/vector2_utils.cpp
|
lobinuxsoft/AsteroidXD-SFML
|
66fb355dfb20ef840068ad948bef9fc97a75f7cd
|
[
"MIT"
] | 16
|
2021-11-09T15:22:24.000Z
|
2021-11-23T14:02:43.000Z
|
src/my_utils/vector2_utils.cpp
|
lobinuxsoft/AsteroidXD-SFML
|
66fb355dfb20ef840068ad948bef9fc97a75f7cd
|
[
"MIT"
] | null | null | null |
#include "vector2_utils.h"
float Vector2Angle(Vector2f v1, Vector2f v2)
{
float result = atan2f(v2.y - v1.y, v2.x - v1.x) * (180.0f / PI);
if (result < 0) result += 360.0f;
return result;
}
float Vector2Distance(Vector2f v1, Vector2f v2)
{
return sqrtf((v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y - v2.y));
}
float Vector2Length(Vector2f v)
{
return sqrtf((v.x * v.x) + (v.y * v.y));
}
Vector2f Vector2Scale(Vector2f v, float scale)
{
return Vector2f( v.x * scale, v.y * scale );
}
Vector2f Vector2Normalize(Vector2f v)
{
float length = Vector2Length(v);
if (length <= 0)
return v;
return Vector2Scale(v, 1 / length);
}
Vector2f Vector2Add(Vector2f v1, Vector2f v2)
{
return Vector2f( v1.x + v2.x, v1.y + v2.y );
}
Vector2f Vector2Subtract(Vector2f v1, Vector2f v2)
{
return Vector2f(v1.x - v2.x, v1.y - v2.y);
}
| 21
| 80
| 0.620181
|
lobinuxsoft
|
8e8e54a5dc9f20dc63765ef2a60be805e89c0bea
| 4,428
|
cpp
|
C++
|
Cutscene Manager Handout/Motor2D/j1CutsceneManager.cpp
|
pauraurell/Cutscene-Manager
|
f887b2a14e1c4e3623d2d8933d7893280ab27f53
|
[
"MIT"
] | null | null | null |
Cutscene Manager Handout/Motor2D/j1CutsceneManager.cpp
|
pauraurell/Cutscene-Manager
|
f887b2a14e1c4e3623d2d8933d7893280ab27f53
|
[
"MIT"
] | null | null | null |
Cutscene Manager Handout/Motor2D/j1CutsceneManager.cpp
|
pauraurell/Cutscene-Manager
|
f887b2a14e1c4e3623d2d8933d7893280ab27f53
|
[
"MIT"
] | null | null | null |
#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Scene.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1CutsceneCharacters.h"
#include "j1CutsceneManager.h"
j1CutsceneManager::j1CutsceneManager() : j1Module()
{
name.create("cutscene");
}
// Destructor
j1CutsceneManager::~j1CutsceneManager()
{}
// Called before the first frame
bool j1CutsceneManager::Start()
{
black_bars.fase = None;
black_bars.alpha = 0;
int bar_height = 100;
black_bars.top_rect.x = 0;
black_bars.top_rect.y = 0;
black_bars.top_rect.w = App->win->width;
black_bars.top_rect.h = bar_height;
black_bars.down_rect.x = 0;
black_bars.down_rect.y = App->win->height - bar_height;
black_bars.down_rect.w = App->win->width;
black_bars.down_rect.h = bar_height;
result = data.load_file("CutsceneEditor.xml");
cutsceneManager = data.document_element();
LOG("Starting Cutscene Manager");
return true;
}
// Called each loop iteration
bool j1CutsceneManager::Update(float dt)
{
return true;
}
// Called each loop iteration
bool j1CutsceneManager::PostUpdate(float dt)
{
//Black Bars Drawing
switch (black_bars.fase)
{
case FadeIn:
black_bars.FadeIn();
break;
case Drawing:
black_bars.Draw();
break;
case FadeOut:
black_bars.FadeOut();
break;
}
return true;
}
// Called before quitting
bool j1CutsceneManager::CleanUp()
{
return true;
}
void BlackBars::FadeIn()
{
//TODO 5.2: Complete this function doing a smooth fade in raising the value of the alpha
// (alpha = 0: invisible, alpha = 255: Completely black)
}
void BlackBars::Draw()
{
//TODO 5.1: Draw both quads unsing the alpha variable. Both rects are (top_rect and down_rect) already
// created, you just have to draw them.
}
void BlackBars::FadeOut()
{
//TODO 5.2: Similar to fade out
}
void j1CutsceneManager::StartCutscene(string name)
{
if (!SomethingActive())
{
for (pugi::xml_node cutscene = cutsceneManager.child("cutscene"); cutscene; cutscene = cutscene.next_sibling("cutscene"))
{
if (cutscene.attribute("name").as_string() == name)
{
LoadSteps(cutscene);
if (black_bars.fase == None) { black_bars.fase = FadeIn; }
}
}
if (App->characters->player.active) {App->characters->player.UpdateStep(); }
if (App->characters->character1.active) {App->characters->character1.UpdateStep(); }
if (App->characters->character2.active) { App->characters->character2.UpdateStep(); }
if (App->render->cinematic_camera.active) { App->render->cinematic_camera.UpdateStep(); }
}
}
bool j1CutsceneManager::LoadSteps(pugi::xml_node node)
{
//TODO 1: Check the structure of the Cutscene Editor xml and fill this function. You just have to get the attributes from
// the xml and push the step to the list of the correspondent Cutscene Object depending on its objective and set the active
// bool to true of each loaded Cutscene Object.
return true;
}
void j1CutsceneManager::DoCutscene(CutsceneObject &character, iPoint &objective_position)
{
Step step = character.current_step;
if(character.active)
{
Movement(step, objective_position);
//TODO 4: This todo is very easy, just check if the object position is equal to the last position of the cutscene and if it
// is call the FinishCutscene function. If it has reached the step.position but it is not the last one just call the Update step
// function you've just made right before.
}
}
void j1CutsceneManager::Movement(Step &step, iPoint &objective_position)
{
//TODO 2: Now we want to move the object to the destiny point. To do that compare the object postion with the position
// we want to reach and move it with the speed values.
}
void CutsceneObject::UpdateStep()
{
//TODO 3: Now that the object will move wherever we want, we have to call this function every time the object reaches a point.
// To do this, in this function you just have to update the current_step value with the next step in the list.
}
void j1CutsceneManager::FinishCutscene(CutsceneObject& character)
{
character.steps.clear();
character.active = false;
App->characters->input = true;
if (black_bars.fase == Drawing) { black_bars.fase = FadeOut; }
}
bool j1CutsceneManager::SomethingActive()
{
bool ret;
if (App->characters->player.active || App->characters->character1.active || App->characters->character2.active){ret = true;}
else { ret = false; }
return ret;
}
| 24.464088
| 131
| 0.727191
|
pauraurell
|
8e8fb299899a755581ac3a9945f0b7b0ae52f35b
| 362
|
cpp
|
C++
|
ch04/th4-5-1.cpp
|
nanonashy/PPPUCpp2ndJP
|
b829867e9e21bf59d9c5ea6c2fbe96bb03597301
|
[
"MIT"
] | 3
|
2021-12-17T17:25:18.000Z
|
2022-03-02T15:52:23.000Z
|
ch04/th4-5-1.cpp
|
nashinium/PPPUCpp2ndJP
|
b829867e9e21bf59d9c5ea6c2fbe96bb03597301
|
[
"MIT"
] | 1
|
2020-04-22T07:16:34.000Z
|
2020-04-22T10:04:04.000Z
|
ch04/th4-5-1.cpp
|
nashinium/PPPUCpp2ndJP
|
b829867e9e21bf59d9c5ea6c2fbe96bb03597301
|
[
"MIT"
] | 1
|
2020-04-22T08:13:51.000Z
|
2020-04-22T08:13:51.000Z
|
#include "../include/std_lib_facilities.h"
int square(int x) {
int result{0};
for (int i = 1; i <= x; ++i)
result += x;
return result;
}
int main() {
std::cout << "Number\tSquare\n";
for (int i = 1; i <= 100; ++i)
std::cout << i << '\t' << square(i) << std::endl;
keep_window_open();
return 0;
}
| 19.052632
| 58
| 0.477901
|
nanonashy
|
8e8fcbbb94e6ebae074192cb4816cf0be70a6a58
| 14,565
|
cpp
|
C++
|
src/llri-vk/detail/device.cpp
|
Rythe-Interactive/Rythe-LLRI
|
0bf9ff71c41b39f7189cbc5ebbf4a74420cedc05
|
[
"MIT"
] | 2
|
2022-02-08T07:11:32.000Z
|
2022-02-08T08:10:31.000Z
|
src/llri-vk/detail/device.cpp
|
Rythe-Interactive/Rythe-LLRI
|
0bf9ff71c41b39f7189cbc5ebbf4a74420cedc05
|
[
"MIT"
] | 1
|
2022-02-14T18:26:31.000Z
|
2022-02-14T18:26:31.000Z
|
src/llri-vk/detail/device.cpp
|
Rythe-Interactive/Rythe-LLRI
|
0bf9ff71c41b39f7189cbc5ebbf4a74420cedc05
|
[
"MIT"
] | null | null | null |
/**
* @file device.cpp
* Copyright (c) 2021 Leon Brands, Rythe Interactive
* SPDX-License-Identifier: MIT
*/
#include <llri/llri.hpp>
#include <llri-vk/utils.hpp>
namespace llri
{
result Device::impl_createCommandGroup(queue_type type, CommandGroup** cmdGroup)
{
auto* output = new CommandGroup();
output->m_device = this;
output->m_deviceFunctionTable = m_functionTable;
output->m_validationCallbackMessenger = m_validationCallbackMessenger;
output->m_type = type;
auto families = detail::findQueueFamilies(static_cast<VkPhysicalDevice>(m_adapter->m_ptr));
VkCommandPoolCreateInfo info;
info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
info.pNext = nullptr;
info.queueFamilyIndex = families[type];
info.flags = {};
VkCommandPool pool;
const auto r = static_cast<VolkDeviceTable*>(m_functionTable)->
vkCreateCommandPool(static_cast<VkDevice>(m_ptr), &info, nullptr, &pool);
if (r != VK_SUCCESS)
{
destroyCommandGroup(output);
return detail::mapVkResult(r);
}
output->m_ptr = pool;
*cmdGroup = output;
return result::Success;
}
void Device::impl_destroyCommandGroup(CommandGroup* cmdGroup)
{
if (!cmdGroup)
return;
if (cmdGroup->m_ptr)
{
static_cast<VolkDeviceTable*>(m_functionTable)->
vkDestroyCommandPool(static_cast<VkDevice>(m_ptr), static_cast<VkCommandPool>(cmdGroup->m_ptr), nullptr);
}
delete cmdGroup;
}
result Device::impl_createFence(fence_flags flags, Fence** fence)
{
const bool signaled = (flags & fence_flag_bits::Signaled) == fence_flag_bits::Signaled;
VkFenceCreateFlags vkFlags = 0;
if (signaled)
vkFlags |= VK_FENCE_CREATE_SIGNALED_BIT;
VkFenceCreateInfo info;
info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
info.pNext = nullptr;
info.flags = vkFlags;
VkFence vkFence;
const auto r = static_cast<VolkDeviceTable*>(m_functionTable)->
vkCreateFence(static_cast<VkDevice>(m_ptr), &info, nullptr, &vkFence);
if (r != VK_SUCCESS)
return detail::mapVkResult(r);
auto* output = new Fence();
output->m_flags = flags;
output->m_ptr = vkFence;
output->m_signaled = signaled;
*fence = output;
return result::Success;
}
void Device::impl_destroyFence(Fence* fence)
{
if (fence->m_ptr)
{
static_cast<VolkDeviceTable*>(m_functionTable)->
vkDestroyFence(static_cast<VkDevice>(m_ptr), static_cast<VkFence>(fence->m_ptr), nullptr);
}
delete fence;
}
result Device::impl_waitFences(uint32_t numFences, Fence** fences, uint64_t timeout)
{
uint64_t vkTimeout = timeout;
if (timeout != LLRI_TIMEOUT_MAX)
vkTimeout *= 1000000u; // milliseconds to nanoseconds
std::vector<VkFence> vkFences(numFences);
for (size_t i = 0; i < numFences; i++)
vkFences[i] = static_cast<VkFence>(fences[i]->m_ptr);
const VkResult r = static_cast<VolkDeviceTable*>(m_functionTable)->
vkWaitForFences(static_cast<VkDevice>(m_ptr), numFences, vkFences.data(), true, vkTimeout);
if (r == VK_SUCCESS)
{
static_cast<VolkDeviceTable*>(m_functionTable)->
vkResetFences(static_cast<VkDevice>(m_ptr), numFences, vkFences.data());
for (size_t i = 0; i < numFences; i++)
fences[i]->m_signaled = false;
}
return detail::mapVkResult(r);
}
result Device::impl_createSemaphore(Semaphore** semaphore)
{
VkSemaphoreCreateInfo info;
info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
info.pNext = nullptr;
info.flags = {};
VkSemaphore vkSemaphore;
const VkResult r = static_cast<VolkDeviceTable*>(m_functionTable)->
vkCreateSemaphore(static_cast<VkDevice>(m_ptr), &info, nullptr, &vkSemaphore);
if (r != VK_SUCCESS)
return detail::mapVkResult(r);
auto* output = new Semaphore();
output->m_ptr = vkSemaphore;
*semaphore = output;
return result::Success;
}
void Device::impl_destroySemaphore(Semaphore* semaphore)
{
if (semaphore->m_ptr)
{
static_cast<VolkDeviceTable*>(m_functionTable)->
vkDestroySemaphore(static_cast<VkDevice>(m_ptr), static_cast<VkSemaphore>(semaphore->m_ptr), nullptr);
}
delete semaphore;
}
result Device::impl_createResource(const resource_desc& desc, Resource** resource)
{
auto* table = static_cast<VolkDeviceTable*>(m_functionTable);
const bool isTexture = desc.type != resource_type::Buffer;
// get all valid queue families
const auto& families = detail::findQueueFamilies(static_cast<VkPhysicalDevice>(m_adapter->m_ptr));
std::vector<uint32_t> familyIndices;
for (const auto& [key, family] : families)
{
if (family != std::numeric_limits<uint32_t>::max())
familyIndices.push_back(family);
}
// get memory flags
const auto memFlags = detail::mapMemoryType(desc.memoryType);
uint64_t dataSize = 0;
uint32_t memoryTypeIndex = 0;
VkImage image = VK_NULL_HANDLE;
VkBuffer buffer = VK_NULL_HANDLE;
if (isTexture)
{
uint32_t depth = desc.type == resource_type::Texture3D ? desc.depthOrArrayLayers : 1;
uint32_t arrayLayers = desc.type == resource_type::Texture3D ? 1 : desc.depthOrArrayLayers;
VkImageCreateInfo imageCreate;
imageCreate.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageCreate.pNext = nullptr;
imageCreate.flags = 0;
imageCreate.imageType = detail::mapTextureType(desc.type);
imageCreate.format = detail::mapTextureFormat(desc.textureFormat);
imageCreate.extent = VkExtent3D{ desc.width, desc.height, depth };
imageCreate.mipLevels = desc.mipLevels;
imageCreate.arrayLayers = arrayLayers;
imageCreate.samples = (VkSampleCountFlagBits)desc.sampleCount;
imageCreate.tiling = VK_IMAGE_TILING_OPTIMAL;
imageCreate.usage = detail::mapTextureUsage(desc.usage);
imageCreate.sharingMode = familyIndices.size() > 1 ? VK_SHARING_MODE_CONCURRENT : VK_SHARING_MODE_EXCLUSIVE;
imageCreate.queueFamilyIndexCount = static_cast<uint32_t>(familyIndices.size());
imageCreate.pQueueFamilyIndices = familyIndices.data();
imageCreate.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
auto r = table->vkCreateImage(static_cast<VkDevice>(m_ptr), &imageCreate, nullptr, &image);
if (r != VK_SUCCESS)
return detail::mapVkResult(r);
VkMemoryRequirements reqs;
table->vkGetImageMemoryRequirements(static_cast<VkDevice>(m_ptr), image, &reqs);
dataSize = reqs.size;
memoryTypeIndex = detail::findMemoryTypeIndex(static_cast<VkPhysicalDevice>(m_adapter->m_ptr), reqs.memoryTypeBits, memFlags);
}
else
{
VkBufferCreateInfo bufferCreate;
bufferCreate.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferCreate.pNext = nullptr;
bufferCreate.flags = 0;
bufferCreate.size = desc.width;
bufferCreate.usage = detail::mapBufferUsage(desc.usage);
bufferCreate.sharingMode = familyIndices.size() > 1 ? VK_SHARING_MODE_CONCURRENT : VK_SHARING_MODE_EXCLUSIVE;
bufferCreate.queueFamilyIndexCount = static_cast<uint32_t>(familyIndices.size());
bufferCreate.pQueueFamilyIndices = familyIndices.data();
auto r = table->vkCreateBuffer(static_cast<VkDevice>(m_ptr), &bufferCreate, nullptr, &buffer);
if (r != VK_SUCCESS)
return detail::mapVkResult(r);
VkMemoryRequirements reqs;
table->vkGetBufferMemoryRequirements(static_cast<VkDevice>(m_ptr), buffer, &reqs);
dataSize = reqs.size;
memoryTypeIndex = detail::findMemoryTypeIndex(static_cast<VkPhysicalDevice>(m_adapter->m_ptr), reqs.memoryTypeBits, memFlags);
}
VkMemoryAllocateFlagsInfoKHR flagsInfo;
flagsInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO;
flagsInfo.pNext = nullptr;
flagsInfo.deviceMask = desc.visibleNodeMask;
flagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT;
VkMemoryAllocateInfo allocInfo;
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.pNext = m_adapter->queryNodeCount() > 1 ? &flagsInfo : nullptr;
allocInfo.allocationSize = dataSize;
allocInfo.memoryTypeIndex = memoryTypeIndex;
VkDeviceMemory memory;
auto r = table->vkAllocateMemory(static_cast<VkDevice>(m_ptr), &allocInfo, nullptr, &memory);
if (r != VK_SUCCESS)
{
if (isTexture)
table->vkDestroyImage(static_cast<VkDevice>(m_ptr), image, nullptr);
else
table->vkDestroyBuffer(static_cast<VkDevice>(m_ptr), buffer, nullptr);
return detail::mapVkResult(r);
}
if (isTexture)
r = table->vkBindImageMemory(static_cast<VkDevice>(m_ptr), image, memory, 0);
else
r = table->vkBindBufferMemory(static_cast<VkDevice>(m_ptr), buffer, memory, 0);
if (r != VK_SUCCESS)
{
if (isTexture)
table->vkDestroyImage(static_cast<VkDevice>(m_ptr), image, nullptr);
else
table->vkDestroyBuffer(static_cast<VkDevice>(m_ptr), buffer, nullptr);
table->vkFreeMemory(static_cast<VkDevice>(m_ptr), memory, nullptr);
return detail::mapVkResult(r);
}
// this part is necessary because in vulkan images are created in the UNDEFINED layout
// so we must transition them to desc.initialState manually.
if (isTexture)
{
table->vkResetCommandPool(static_cast<VkDevice>(m_ptr), static_cast<VkCommandPool>(m_workCmdGroup), {});
// Record commandbuffer to transition texture from undefined
VkCommandBufferBeginInfo beginInfo {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.pNext = nullptr;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
beginInfo.pInheritanceInfo = nullptr;
table->vkBeginCommandBuffer(static_cast<VkCommandBuffer>(m_workCmdList), &beginInfo);
// use the texture format to detect the aspect flags
VkImageAspectFlags aspectFlags = {};
if (has_color_component(desc.textureFormat))
aspectFlags |= VK_IMAGE_ASPECT_COLOR_BIT;
if (has_depth_component(desc.textureFormat))
aspectFlags |= VK_IMAGE_ASPECT_DEPTH_BIT;
if (has_stencil_component(desc.textureFormat))
aspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT;
VkImageMemoryBarrier imageMemoryBarrier {};
imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
imageMemoryBarrier.pNext = nullptr;
imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageMemoryBarrier.newLayout = detail::mapResourceState(desc.initialState);
imageMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imageMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imageMemoryBarrier.srcAccessMask = VK_ACCESS_NONE_KHR;
imageMemoryBarrier.dstAccessMask = detail::mapStateToAccess(desc.initialState);
imageMemoryBarrier.image = image;
imageMemoryBarrier.subresourceRange = VkImageSubresourceRange { aspectFlags, 0, desc.mipLevels, 0, desc.depthOrArrayLayers };
table->vkCmdPipelineBarrier(static_cast<VkCommandBuffer>(m_workCmdList),
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, detail::mapStateToPipelineStage(desc.initialState), {},
0, nullptr, 0, nullptr, 1, &imageMemoryBarrier);
table->vkEndCommandBuffer(static_cast<VkCommandBuffer>(m_workCmdList));
VkSubmitInfo submit {};
submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit.pNext = nullptr;
submit.commandBufferCount = 1;
submit.pCommandBuffers = reinterpret_cast<VkCommandBuffer*>(&m_workCmdList);
submit.signalSemaphoreCount = 0;
submit.pSignalSemaphores = nullptr;
submit.waitSemaphoreCount = 0;
submit.pWaitSemaphores = nullptr;
submit.pWaitDstStageMask = nullptr;
table->vkQueueSubmit(static_cast<VkQueue>(getQueue(m_workQueueType, 0)->m_ptrs[0]), 1, &submit, static_cast<VkFence>(m_workFence));
table->vkWaitForFences(static_cast<VkDevice>(m_ptr), 1, reinterpret_cast<VkFence*>(&m_workFence), VK_TRUE, std::numeric_limits<uint64_t>::max());
table->vkResetFences(static_cast<VkDevice>(m_ptr), 1, reinterpret_cast<VkFence*>(&m_workFence));
}
auto* output = new Resource();
output->m_desc = desc;
output->m_resource = isTexture ? static_cast<Resource::native_resource*>(image) : static_cast<Resource::native_resource*>(buffer);
output->m_memory = memory;
*resource = output;
return result::Success;
}
void Device::impl_destroyResource(Resource* resource)
{
const bool isTexture = resource->m_desc.type != resource_type::Buffer;
if (isTexture)
static_cast<VolkDeviceTable*>(m_functionTable)->vkDestroyImage(static_cast<VkDevice>(m_ptr), static_cast<VkImage>(resource->m_resource), nullptr);
else
static_cast<VolkDeviceTable*>(m_functionTable)->vkDestroyBuffer(static_cast<VkDevice>(m_ptr), static_cast<VkBuffer>(resource->m_resource), nullptr);
static_cast<VolkDeviceTable*>(m_functionTable)->vkFreeMemory(static_cast<VkDevice>(m_ptr), static_cast<VkDeviceMemory>(resource->m_memory), nullptr);
}
}
| 42.340116
| 160
| 0.646413
|
Rythe-Interactive
|
8e90fefa694ca74307c3d8b7758f4510a1e6acf2
| 11,757
|
cpp
|
C++
|
src/args.cpp
|
valet-bridge/valet
|
8e20da1b496cb6fa42894b9ef420375cb7a5d2cd
|
[
"Apache-2.0"
] | null | null | null |
src/args.cpp
|
valet-bridge/valet
|
8e20da1b496cb6fa42894b9ef420375cb7a5d2cd
|
[
"Apache-2.0"
] | 1
|
2015-11-15T08:20:33.000Z
|
2018-03-04T09:48:23.000Z
|
src/args.cpp
|
valet-bridge/valet
|
8e20da1b496cb6fa42894b9ef420375cb7a5d2cd
|
[
"Apache-2.0"
] | null | null | null |
/*
Valet, a generalized Butler scorer for bridge.
Copyright (C) 2015 by Soren Hein.
See LICENSE and README.
*/
// These functions parse the command line for options.
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
#include <string.h>
#include "args.h"
#include "cst.h"
using namespace std;
extern OptionsType options;
struct optEntry
{
string shortName;
string longName;
unsigned numArgs;
};
#define VALET_NUM_OPTIONS 16
const optEntry optList[VALET_NUM_OPTIONS] =
{
{"v", "valettype", 1},
{"d", "directory", 1},
{"n", "names", 1},
{"s", "scores", 1},
{"r", "rounds", 1},
{"m", "minhands", 1},
{"l", "leads", 0},
{"e", "extremes", 0},
{"h", "hardround", 0},
{"t", "tableau", 1},
{"x", "nocloud", 0},
{"c", "compensate", 0},
{"o", "order", 1},
{"a", "average", 0},
{"f", "format", 1},
{"j", "join", 1}
};
string shortOptsAll, shortOptsWithArg;
int GetNextArgToken(
int argc,
char * argv[]);
void SetDefaults();
bool ParseRound();
void Usage(
const char base[])
{
string basename(base);
const size_t l = basename.find_last_of("\\/");
if (l != string::npos)
basename.erase(0, l+1);
cout <<
"Usage: " << basename << " [options]\n\n" <<
"-v, --valettype s Valet type, one of datum, imps, matchpoints\n" <<
" (default: imps).\n" <<
"\n" <<
"-d, --directory s Read the input files from directory s.\n" <<
"\n" <<
"-n, --names s Use s as the names file (default names.txt)\n" <<
"\n" <<
"-s, --scores s Use s as the scores file (default scores.txt)\n" <<
"\n" <<
"-r, --rounds list Selects only rounds specified in list.\n" <<
" Example (note: no spaces) 1,3-5,7 (default all)\n" <<
"\n" <<
"-m, --minhands m Only show results for pairs/players who have\n" <<
" played at least m hands (default 0)\n" <<
"\n" <<
"-l, --lead Show a Valet score for the lead separately\n" <<
" (default: no)\n" <<
"\n" <<
"-e, --extremes When calculating datum score (only for Butler\n" <<
" IMPs), throw out the maximum and minimum\n" <<
" scores (default: no, -e turns it on).\n" <<
"\n" <<
"-h, --hardround When calculating datum score (only for Butler\n" <<
" IMPs), round down and not to the nearest\n" <<
" score. So 379 rounds to 370, not to 380\n" <<
" (default: no).\n" <<
"\n" <<
"-x, --nocloud Use the simpler, but mathematically less\n" <<
" satisfying Valet score (default: not set).\n" <<
"\n" <<
"-t, --tableau Output a file of tableaux for each hand\n" <<
" to file argument (default: not set).\n" <<
"\n" <<
"-c, -compensate Compensate overall score for the average strength\n" <<
" of the specific opponents faced (default: no).\n" <<
"\n" <<
"-o, --order s Sorting order of the output. Valid orders are\n" <<
" overall, bidding, play, defense, lead,\n" <<
" bidoverplay (bidding minus play),\n" <<
" defoverplay (defense minus play),\n" <<
" leadoverplay (lead minus play),\n" <<
" (case-insensitive).\n" <<
"\n" <<
"-a, --average Show certain averages in the output tables.\n"
"\n" <<
"-f, --format s Output file format: text or csv (broadly\n" <<
" speaking, comma-separated values suitable for\n" <<
" loading into e.g. Microsoft Excel)\n" <<
" (default: text).\n" <<
"\n" <<
"-j, --join c Separator for csv output (default the comma,\n" <<
" ',' (without the marks). In German Excel it \n" <<
" is useful to set this to ';', and so on.\n" <<
endl;
}
int nextToken = 1;
char * optarg;
int GetNextArgToken(
int argc,
char * argv[])
{
// 0 means done, -1 means error.
if (nextToken >= argc)
return 0;
string str(argv[nextToken]);
if (str[0] != '-' || str.size() == 1)
return -1;
if (str[1] == '-')
{
if (str.size() == 2)
return -1;
str.erase(0, 2);
}
else if (str.size() == 2)
str.erase(0, 1);
else
return -1;
for (unsigned i = 0; i < VALET_NUM_OPTIONS; i++)
{
if (str == optList[i].shortName || str == optList[i].longName)
{
if (optList[i].numArgs == 1)
{
if (nextToken+1 >= argc)
return -1;
optarg = argv[nextToken+1];
nextToken += 2;
}
else
nextToken++;
return str[0];
}
}
return -1;
}
void SetDefaults()
{
options.valet = VALET_IMPS_ACROSS_FIELD;
options.directory = ".";
options.nameFile = "names.txt";
options.scoresFile = "scores.txt";
options.roundFlag = false;
options.roundFirst = 0;
options.roundLast = 0;
options.minHands = 0;
options.leadFlag = false;
options.datumFilter = false;
options.datumHardRounding = false;
options.cloudFlag = true;
options.tableauFlag = false;
options.compensateFlag = false;
options.sort = VALET_SORT_OVERALL;
options.averageFlag = false;
options.format = VALET_FORMAT_TEXT;
options.separator = ',';
}
void PrintOptions()
{
cout << left;
cout << setw(12) << "valettype" << setw(12) <<
scoringTags[options.valet].arg << "\n";
cout << setw(12) << "directory" << setw(12) << options.directory << "\n";
cout << setw(12) << "names" << setw(12) << options.nameFile << "\n";
cout << setw(12) << "scores" << setw(12) << options.scoresFile << "\n";
if (options.roundFlag)
cout << setw(12) << "rounds" << options.roundFirst << " to " <<
options.roundLast << "\n";
else
cout << setw(12) << "rounds" << "no limitation\n";
cout << setw(12) << "minhands" << setw(12) << options.minHands << "\n";
cout << setw(12) << "lead" << setw(12) <<
(options.leadFlag ? "true" : "false") << "\n";
cout << setw(12) << "extremes" << setw(12) <<
(options.datumFilter ? "true" : "false") << "\n";
cout << setw(12) << "hardround" << setw(12) <<
(options.datumHardRounding ? "true" : "false") << "\n";
cout << setw(12) << "cloud" << setw(12) <<
(options.cloudFlag ? "true" : "false") << "\n";
cout << setw(12) << "tableau" << setw(12) <<
(options.datumHardRounding ? options.tableauFile : "false") << "\n";
cout << setw(12) << "compensate" << setw(12) <<
(options.compensateFlag ? "true" : "false") << "\n";
cout << setw(12) << "order" << setw(12) <<
sortingTags[options.sort].str << "\n";
cout << setw(12) << "average" << setw(12) <<
(options.averageFlag ? "true" : "false") << "\n";
cout << setw(12) << "format" << setw(12) <<
(options.format == VALET_FORMAT_TEXT ? "text" : "csv") << "\n";
cout << setw(12) << "join" << setw(12) << options.separator << "\n";
cout << "\n" << right;
}
bool ParseRound()
{
// Allow 5 as well as 1-3
char * temp;
int m = static_cast<int>(strtol(optarg, &temp, 0));
if (* temp == '\0')
{
if (m <= 0)
{
return false;
}
else
{
options.roundFirst = static_cast<unsigned>(m);
options.roundLast = static_cast<unsigned>(m);
return true;
}
}
string stmp(optarg);
string::size_type pos;
pos = stmp.find_first_of("-", 0);
if (pos == std::string::npos || pos > 7)
return false;
char str1[8], str2[8];
#if (! defined(_MSC_VER) || _MSC_VER < 1400)
strncpy(str1, stmp.c_str(), pos);
#else
strncpy_s(str1, stmp.c_str(), pos);
#endif
str1[pos] = '\0';
if ((m = atoi(str1)) <= 0)
return false;
options.roundFirst = static_cast<unsigned>(m);
stmp.erase(0, pos+1);
#if (! defined(_MSC_VER) || _MSC_VER < 1400)
strncpy(str2, stmp.c_str(), stmp.size());
#else
strncpy_s(str2, stmp.c_str(), stmp.size());
#endif
str2[stmp.size()] = '\0';
if ((m = atoi(str2)) <= 0)
return false;
options.roundLast = static_cast<unsigned>(m);
if (options.roundLast < options.roundFirst)
return false;
return true;
}
void ReadArgs(
int argc,
char * argv[])
{
for (unsigned i = 0; i < VALET_NUM_OPTIONS; i++)
{
shortOptsAll += optList[i].shortName;
if (optList[i].numArgs)
shortOptsWithArg += optList[i].shortName;
}
if (argc == 1)
{
Usage(argv[0]);
exit(0);
}
SetDefaults();
int c, m;
bool errFlag = false, matchFlag;
string stmp;
while ((c = GetNextArgToken(argc, argv)) > 0)
{
switch(c)
{
case 'v':
stmp = optarg;
matchFlag = false;
for (unsigned i = 0; i < 3; i++)
{
if (stmp == scoringTags[i].arg)
{
options.valet = scoringTags[i].scoring;
matchFlag = true;
break;
}
}
if (! matchFlag)
{
cout << "valet must be written exactly as in the list\n";
nextToken -= 2;
errFlag = true;
}
break;
case 'd':
options.directory = optarg;
break;
case 'n':
options.nameFile = optarg;
break;
case 's':
options.scoresFile = optarg;
break;
case 'r':
options.roundFlag = true;
if (! ParseRound())
{
cout << " Could not parse round\n";
nextToken -= 2;
errFlag = true;
}
break;
case 'm':
char * temp;
m = static_cast<int>(strtol(optarg, &temp, 0));
if (m < 1)
{
cout << "Number of hands must be >= 1\n\n";
nextToken -= 2;
errFlag = true;
}
options.minHands = static_cast<unsigned>(m);
break;
case 'l':
options.leadFlag = true;
break;
case 'e':
options.datumFilter = true;
break;
case 'h':
options.datumHardRounding = true;
break;
case 'x':
options.cloudFlag = false;
break;
case 't':
options.tableauFlag = true;
options.tableauFile = optarg;
break;
case 'c':
options.compensateFlag = true;
break;
case 'o':
stmp = optarg;
matchFlag = false;
for (unsigned i = 0; i < 8; i++)
{
if (stmp == sortingTags[i].str)
{
options.sort = sortingTags[i].sort;
matchFlag = true;
break;
}
}
if (! matchFlag)
{
cout << "order must be written exactly as in the list\n";
nextToken -= 2;
errFlag = true;
}
break;
case 'a':
options.averageFlag = true;
break;
case 'f':
stmp = optarg;
if (stmp == "text")
options.format = VALET_FORMAT_TEXT;
else if (stmp == "csv")
options.format = VALET_FORMAT_CSV;
else
{
cout << "format must be text or csv\n";
nextToken -= 2;
errFlag = true;
}
break;
case 'j':
options.separator = optarg;
if (options.separator.size() != 1)
{
cout << "char must consist of a single character\n";
nextToken -= 2;
errFlag = true;
}
break;
default:
cout << "Unknown option\n";
errFlag = true;
break;
}
if (errFlag)
break;
}
if (errFlag || c == -1)
{
cout << "Error while parsing option '" << argv[nextToken] << "'\n";
cout << "Invoke the program without arguments for help" << endl;
exit(0);
}
}
| 25.06823
| 79
| 0.514417
|
valet-bridge
|
8e91c7f6dbd37560842a3312c31bd1bb3530d8c5
| 1,258
|
cpp
|
C++
|
source/ktwgEngine/Shaders/cpp/SimpleForwardParams.cpp
|
JasonWyx/ktwgEngine
|
410ba799f7000895995b9f9fc59d738f293f8871
|
[
"MIT"
] | null | null | null |
source/ktwgEngine/Shaders/cpp/SimpleForwardParams.cpp
|
JasonWyx/ktwgEngine
|
410ba799f7000895995b9f9fc59d738f293f8871
|
[
"MIT"
] | 12
|
2019-09-15T07:48:18.000Z
|
2019-12-08T17:23:22.000Z
|
source/ktwgEngine/Shaders/cpp/SimpleForwardParams.cpp
|
JasonWyx/ktwgEngine
|
410ba799f7000895995b9f9fc59d738f293f8871
|
[
"MIT"
] | null | null | null |
#include "SimpleForwardParams.h"
#include "../../d3d11staticresources.h"
#include "../../d3d11device.h"
#include "../../d3d11renderapi.h"
#include "../../d3d11hardwarebuffer.h"
DEFINE_STATIC_BUFFER(SimpleForwardParamsCbuf);
void ShaderInputs::SimpleForwardParams::InitializeHWResources()
{
D3D11Device* device = D3D11RenderAPI::GetInstance().GetDevice();
GET_STATIC_RESOURCE(SimpleForwardParamsCbuf) = new D3D11HardwareBuffer{ device, D3D11_BT_CONSTANT, D3D11_USAGE_DYNAMIC, 4, sizeof(float), false, false, true, false };
}
void ShaderInputs::SimpleForwardParams::SetColor(float r, float g, float b, float a)
{
m_Color[0] = r;
m_Color[1] = g;
m_Color[2] = b;
m_Color[3] = a;
}
void ShaderInputs::SimpleForwardParams::GetColor(float & r, float & g, float & b, float & a)
{
r = m_Color[0];
g = m_Color[1];
b = m_Color[2];
a = m_Color[3];
}
void ShaderInputs::SimpleForwardParams::Set()
{
D3D11Device* device = D3D11RenderAPI::GetInstance().GetDevice();
device->GetImmediateContext().AddConstantBuffer<VS>(GET_STATIC_RESOURCE(SimpleForwardParamsCbuf));
device->GetImmediateContext().FlushConstantBuffers(SimpleForwardParamsSlot);
GET_STATIC_RESOURCE(SimpleForwardParamsCbuf)->Write(0, 4 * sizeof(float), m_Color, WT_DISCARD);
}
| 33.105263
| 168
| 0.744038
|
JasonWyx
|
8e9305816904c0b57e845732123269d7b633b295
| 935
|
cc
|
C++
|
list/reversed_linked_list.cc
|
windscope/Cracking
|
0db01f531ff56428bafff72aaea1d046dbc14112
|
[
"Apache-2.0"
] | null | null | null |
list/reversed_linked_list.cc
|
windscope/Cracking
|
0db01f531ff56428bafff72aaea1d046dbc14112
|
[
"Apache-2.0"
] | null | null | null |
list/reversed_linked_list.cc
|
windscope/Cracking
|
0db01f531ff56428bafff72aaea1d046dbc14112
|
[
"Apache-2.0"
] | null | null | null |
// Reverse Linked List
// https://leetcode.com/problems/reverse-linked-list/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <cassert>
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr) {
return nullptr;
}
ListNode* next_head = head->next;
head->next = nullptr;
ListNode* ret_head = head;
while (next_head != nullptr) {
ListNode* ret_head_next = ret_head;
ret_head = next_head;
next_head = next_head->next;
ret_head->next = ret_head_next;
}
}
};
int main() {
cout << "You Passed" << endl;
return 0;
}
| 19.479167
| 53
| 0.562567
|
windscope
|
8e97a5b95fe2ad04a91d0beb91126d71b13e1664
| 1,885
|
cpp
|
C++
|
state.cpp
|
sl424/hunting-game
|
f79bea39a061c8b8cfbf430ab0d73cd6539ddb0f
|
[
"Apache-2.0"
] | null | null | null |
state.cpp
|
sl424/hunting-game
|
f79bea39a061c8b8cfbf430ab0d73cd6539ddb0f
|
[
"Apache-2.0"
] | null | null | null |
state.cpp
|
sl424/hunting-game
|
f79bea39a061c8b8cfbf430ab0d73cd6539ddb0f
|
[
"Apache-2.0"
] | null | null | null |
/***************************************************
* Program Filename: state.cpp
* Author: Chewie Lin
* Date: 12 Feb 2016
* Description: main driver functions
***************************************************/
#include "state.hpp"
/*****************************************
* Function: pEnter()
* Description: press enter to continue
******************************************/
void pEnter() {
std::cin.ignore(125,'\n');
std::cout << "Press enter to continue: " << std::flush;
std::cin.ignore(125,'\n');
}
/*****************************************
* Function: pick()
* Description: ask user input
******************************************/
int pick() {
int pick;
do {
std::cout << "Select a creature: ";
std::cin >> pick;
if ( std::cin.fail() || pick < 1 || pick > 5 ) {
std::cout << "invalid pick" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
}
} while ( pick < 1 || pick > 5 );
return pick;
}
/*****************************************
* Function: showGraphics()
* Description:
******************************************/
void showGraphics(std::string& s) {
std::string aline;
std::ifstream input;
input.open(s.c_str(), std::ifstream::in);
if ( input.is_open() ) {
while ( std::getline (input,aline) )
std::cout << aline << '\n';
input.close();
}
else std::cout << "error opening file";
}
/*****************************************
* Function: displayMenu()
* Description: show the list of creatures
******************************************/
bool displayMenu() {
char a;
do {
std::cout << " 0: How to play \n 1: Start Game \n 2: Quit \n";
std::cout << "Enter input: ";
std::cin >> a;
if ( a == '0' )
showGamePlay();
if ( a == '1' )
return true;
else if ( a == '2' )
return false;
} while ( a != '1' && a != '2' );
}
void showGamePlay(){
std::string s = "gameplay.txt";
showGraphics(s);
}
| 24.802632
| 63
| 0.448276
|
sl424
|
8e9a7dfe8704ce896e0a39c9eea55cf64eb395f7
| 89
|
cpp
|
C++
|
applications/Example/Example.cpp
|
203Electronics/MatrixOS
|
ea6d84b21a97f58e2077d37d5645c5339f344d77
|
[
"MIT"
] | 8
|
2021-12-30T05:29:16.000Z
|
2022-03-30T08:44:45.000Z
|
applications/Example/Example.cpp
|
203Electronics/MatrixOS
|
ea6d84b21a97f58e2077d37d5645c5339f344d77
|
[
"MIT"
] | null | null | null |
applications/Example/Example.cpp
|
203Electronics/MatrixOS
|
ea6d84b21a97f58e2077d37d5645c5339f344d77
|
[
"MIT"
] | null | null | null |
#include "Example.h"
void ExampleAPP::Setup()
{
}
void ExampleAPP::Loop()
{
}
| 7.416667
| 24
| 0.58427
|
203Electronics
|
8ea74d1a47c9c79b1f9ab67b2ce4a36f7bc94a10
| 1,380
|
cc
|
C++
|
test/HttpServer/compute_unittest.cc
|
wfrest/wfrest
|
5aa8c3ab5ad749ef8e9b93c8aa32d8c475062dde
|
[
"Apache-2.0"
] | 312
|
2021-12-05T15:17:27.000Z
|
2022-03-30T10:53:01.000Z
|
test/HttpServer/compute_unittest.cc
|
chanchann/wfrest
|
5aa8c3ab5ad749ef8e9b93c8aa32d8c475062dde
|
[
"Apache-2.0"
] | 15
|
2021-12-14T16:01:15.000Z
|
2022-03-15T04:27:47.000Z
|
test/HttpServer/compute_unittest.cc
|
wfrest/wfrest
|
5aa8c3ab5ad749ef8e9b93c8aa32d8c475062dde
|
[
"Apache-2.0"
] | 46
|
2021-12-06T08:08:45.000Z
|
2022-03-01T06:26:38.000Z
|
#include "workflow/WFFacilities.h"
#include "workflow/Workflow.h"
#include <gtest/gtest.h>
#include "wfrest/HttpServer.h"
#include "wfrest/ErrorCode.h"
using namespace wfrest;
using namespace protocol;
WFHttpTask *create_http_task(const std::string &path)
{
return WFTaskFactory::create_http_task("http://127.0.0.1:8888/" + path, 4, 2, nullptr);
}
void Factorial(int n, HttpResp *resp)
{
unsigned long long factorial = 1;
for(int i = 1; i <= n; i++)
{
factorial *= i;
}
resp->String(std::to_string(factorial));
}
TEST(HttpServer, String_short_str)
{
HttpServer svr;
WFFacilities::WaitGroup wait_group(1);
svr.GET("/test", [](const HttpReq *req, HttpResp *resp)
{
resp->Compute(1, Factorial, 10, resp);
});
EXPECT_TRUE(svr.start("127.0.0.1", 8888) == 0) << "http server start failed";
WFHttpTask *client_task = create_http_task("test");
client_task->set_callback([&wait_group](WFHttpTask *task)
{
const void *body;
size_t body_len;
task->get_resp()->get_parsed_body(&body, &body_len);
EXPECT_TRUE(strcmp("3628800", static_cast<const char *>(body)) == 0);
wait_group.done();
});
client_task->start();
wait_group.wait();
svr.stop();
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 24.210526
| 91
| 0.642029
|
wfrest
|
8ea86625c443698315f5223a9ad55d2a3299a44b
| 242
|
cpp
|
C++
|
tests/aoj/bigint.multiplication_bigint_1.test.cpp
|
Zeldacrafter/CompProg
|
5367583f45b6fe30c4c84f3ae81accf14f8f7fd3
|
[
"Unlicense"
] | 4
|
2020-02-06T15:44:57.000Z
|
2020-12-21T03:51:21.000Z
|
tests/aoj/bigint.multiplication_bigint_1.test.cpp
|
Zeldacrafter/CompProg
|
5367583f45b6fe30c4c84f3ae81accf14f8f7fd3
|
[
"Unlicense"
] | null | null | null |
tests/aoj/bigint.multiplication_bigint_1.test.cpp
|
Zeldacrafter/CompProg
|
5367583f45b6fe30c4c84f3ae81accf14f8f7fd3
|
[
"Unlicense"
] | null | null | null |
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=NTL_2_C"
#include "../../code/utils/bigint.cc"
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
bigint a, b;
cin >> a >> b;
cout << a * b << endl;
}
| 18.615385
| 82
| 0.619835
|
Zeldacrafter
|
8ea8a2ac3154f2b3d99c1dffbf24fc33b56b1b3c
| 3,018
|
cpp
|
C++
|
test/tsarray2.cpp
|
drypot/san-2.x
|
44e626793b1dc50826ba0f276d5cc69b7c9ca923
|
[
"MIT"
] | 5
|
2019-12-27T07:30:03.000Z
|
2020-10-13T01:08:55.000Z
|
test/tsarray2.cpp
|
drypot/san-2.x
|
44e626793b1dc50826ba0f276d5cc69b7c9ca923
|
[
"MIT"
] | null | null | null |
test/tsarray2.cpp
|
drypot/san-2.x
|
44e626793b1dc50826ba0f276d5cc69b7c9ca923
|
[
"MIT"
] | 1
|
2020-07-27T22:36:40.000Z
|
2020-07-27T22:36:40.000Z
|
#include <pub\config.hpp>
#include <stdpub\io.hpp>
#include <pub\except.hpp>
#include <pub\inline.hpp>
#include <pub\char.hpp>
#include <cnt\sarray.tem>
#include <conpub\io.hpp>
#include <time.h>
#include <pub\buffer.hpp>
#include <pub\fbuf.hpp>
typedef sarray<char16,8*1024> arrayt;
//char* fname = "fmid";
char* fname = "fbig";
buffer<char16,8*1024> buf;
arrayt ary;
clock_t clk;
FILE* f;
int32 cnt,i;
void view(arrayt* pa)
{
arrayt::frame* p;
p = pa->head.p_next;
while (p!= (arrayt::frame*) &pa->tail)
{
printf("%4d ",p->cnt);
p = p->p_next;
}
printf("\n");
}
void iter_test()
{
printf("iter ready\n");
getch();
printf("iter start\n");
clk = clock();
forcnt(i,cnt) ary[i]=ary[i]+1;
printf("%u clocks\n",clock()-clk);
printf("end\n");
}
void fread_test()
{
//ifbuf f("fbig",32*1024);
int ch;
cnt = 0;
buf.reset();
ary.reset();
f = fopen(fname,"rb");
printf("ready\n");
getch();
printf("start\n");
clk = clock();
while (ch = fgetc(f) , ch != EOF) ary[cnt++] = ch;
printf("%u clocks\n",clock()-clk);
printf("%d chars\n",cnt);
fclose(f);
}
void fread2_test()
{
//ifbuf f("fbig",32*1024);
int ch;
int ch2;
cnt = 0;
buf.reset();
ary.reset();
f = fopen(fname,"rb");
printf("ready\n");
getch();
printf("start\n");
clk = clock();
while (ch = fgetc(f) , ch != EOF)
{
cnt++;
if (is_full((byte)ch))
{
ch2 = fgetc(f);
buf.append(char16_make(ch,ch2));
}
else buf.append(ch);
if (buf.is_full())
{
ary.locate_end();
ary.insert(buf.cnt());
ary.read(buf,buf.cnt());
buf.reset();
//view(&ary);
//getch();
}
}
printf("%u clocks\n",clock()-clk);
printf("%d chars\n",cnt);
fclose(f);
}
void fread3_test()
{
ifbuf f(fname,16*1024);
int ch;
int ch2;
cnt = 0;
buf.reset();
ary.reset();
printf("ready\n");
getch();
printf("start\n");
clk = clock();
forever
{
if ( f.rest() <= 2 )
{
if ( f.file_rest() == 0 )
{
if ( f.rest() == 1 && is_full(f.peek8()) ) f.append(0);
if ( f.rest() == 0 ) break;
}
else f.fill();
}
ch = f.get8();
cnt++;
if (is_full((byte)ch))
{
ch2 = f.get8();
buf.append(char16_make(ch,ch2));
}
else buf.append(ch);
if (buf.is_full())
{
ary.locate_end();
ary.insert(buf.cnt());
ary.read(buf,buf.cnt());
buf.reset();
//view(&ary);
//getch();
}
}
printf("%u clocks\n",clock()-clk);
printf("%d chars\n",cnt);
}
void main()
{
touch_err_module();
throw int();
fread_test();
fread2_test();
//fread3_test();
//test_iter();
}
| 18.745342
| 68
| 0.470179
|
drypot
|
8ea9435ee69f6139fa6d3430ace8728bd50421b8
| 1,795
|
cpp
|
C++
|
src/one_tree.cpp
|
LukasErlenbach/tsp_solver
|
016a1e794de7b58f666b3635977e39aeadb46c99
|
[
"MIT"
] | null | null | null |
src/one_tree.cpp
|
LukasErlenbach/tsp_solver
|
016a1e794de7b58f666b3635977e39aeadb46c99
|
[
"MIT"
] | null | null | null |
src/one_tree.cpp
|
LukasErlenbach/tsp_solver
|
016a1e794de7b58f666b3635977e39aeadb46c99
|
[
"MIT"
] | null | null | null |
#include "branching_node.hpp"
/**
* @file one_tree.hpp
* @brief Implementation of class @c OneTree.
* **/
namespace Core {
/////////////////////////////////////////////
//! \c OneTree definitions
/////////////////////////////////////////////
OneTree::OneTree(const PredVec &preds, const Degrees °rees, const double cost)
: _preds(preds), _degrees(degrees), _cost(cost) {}
// this test is sufficient since PredVecs are assumed to be connected (since
// they encode OneTrees)
bool OneTree::is_tour() const {
for (Degree d : _degrees) {
if (d != 2) {
return false;
}
}
return true;
}
// greedily finds a node with degree > 2
NodeId OneTree::hd_node() const {
for (NodeId node_id = 0; node_id < _degrees.size(); ++node_id) {
if (_degrees[node_id] > 2) {
return node_id;
}
}
// this case should never occur, we only call this after checking with
// is_tour()
throw std::runtime_error("Error in OneTree::hd_node(): No node with degree > 2.");
return invalid_node_id;
}
NodeIds OneTree::neighbors(const NodeId node_id) const {
NodeIds neighbors = {};
neighbors.reserve(_degrees[node_id]);
if (node_id == 0) {
// -> first 2 entrys are neighbors
neighbors.push_back(_preds[0]);
neighbors.push_back(_preds[1]);
}
if (node_id == _preds[0] or node_id == _preds[1]) {
// -> adjacent to node 0
neighbors.push_back(0);
}
for (NodeId other_id = 2; other_id < _preds.size(); ++other_id) {
if (_preds[other_id] == node_id) {
// -> other_id is successor in the OneTree
neighbors.push_back(other_id);
continue;
}
if (other_id == node_id) {
// -> other_id is predecessor in the OneTree
neighbors.push_back(_preds[node_id]);
}
}
return neighbors;
}
} // namespace Core
| 26.397059
| 84
| 0.615042
|
LukasErlenbach
|
8eaa13d41994856cf8f60f3702734dace09604e2
| 1,619
|
hpp
|
C++
|
src/rpcz/sync_call_handler.hpp
|
jinq0123/rpcz
|
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
|
[
"Apache-2.0"
] | 4
|
2015-06-14T13:38:40.000Z
|
2020-11-07T02:29:59.000Z
|
src/rpcz/sync_call_handler.hpp
|
jinq0123/rpcz
|
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
|
[
"Apache-2.0"
] | 1
|
2015-06-19T07:54:53.000Z
|
2015-11-12T10:38:21.000Z
|
src/rpcz/sync_call_handler.hpp
|
jinq0123/rpcz
|
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
|
[
"Apache-2.0"
] | 3
|
2015-06-15T02:28:39.000Z
|
2018-10-18T11:02:59.000Z
|
// Licensed under the Apache License, Version 2.0 (the "License");
// Author: Jin Qing (http://blog.csdn.net/jq0123)
#ifndef RPCZ_SYNC_CALL_HANDLER_HPP
#define RPCZ_SYNC_CALL_HANDLER_HPP
#include <boost/noncopyable.hpp>
#include <boost/optional.hpp>
#include <google/protobuf/message.h>
#include <rpcz/common.hpp> // for scoped_ptr
#include <rpcz/rpc_error.hpp>
#include <rpcz/sync_event.hpp>
namespace rpcz {
class rpc_error;
// Handler to simulate sync call.
class sync_call_handler : boost::noncopyable {
public:
inline explicit sync_call_handler(
google::protobuf::Message* response)
: response_(response) {}
inline ~sync_call_handler(void) {}
public:
inline void operator()(const rpc_error* error,
const void* data, size_t size);
inline void wait() { sync_.wait(); }
inline const rpc_error* get_rpc_error() const {
return error_.get_ptr();
}
private:
void handle_error(const rpc_error& err);
void handle_invalid_message();
inline void signal() { sync_.signal(); }
private:
sync_event sync_;
google::protobuf::Message* response_;
boost::optional<rpc_error> error_;
};
inline void sync_call_handler::operator()(
const rpc_error* error,
const void* data, size_t size) {
if (error) {
handle_error(*error);
signal();
return;
}
BOOST_ASSERT(data);
if (NULL == response_) {
signal();
return;
}
if (response_->ParseFromArray(data, size)) {
BOOST_ASSERT(!error_);
signal();
return;
}
// invalid message
handle_invalid_message();
signal();
}
} // namespace rpcz
#endif // RPCZ_SYNC_CALL_HANDLER_HPP
| 22.486111
| 66
| 0.696726
|
jinq0123
|
8eb1fb99e1744279d9305287c855c2e611b06c83
| 2,294
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_Exosuit_parameters.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_Exosuit_parameters.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_Exosuit_parameters.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PrimalItem_Spawner_Exosuit_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function PrimalItem_Spawner_Exosuit.PrimalItem_Spawner_Exosuit_C.BPCanUse
struct UPrimalItem_Spawner_Exosuit_C_BPCanUse_Params
{
bool* bIgnoreCooldown; // (Parm, ZeroConstructor, IsPlainOldData)
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function PrimalItem_Spawner_Exosuit.PrimalItem_Spawner_Exosuit_C.GetStatDisplayString
struct UPrimalItem_Spawner_Exosuit_C_GetStatDisplayString_Params
{
TEnumAsByte<EPrimalCharacterStatusValue>* Stat; // (Parm, ZeroConstructor, IsPlainOldData)
int* Value; // (Parm, ZeroConstructor, IsPlainOldData)
int* StatConvertMapIndex; // (Parm, ZeroConstructor, IsPlainOldData)
class FString StatDisplay; // (Parm, OutParm, ZeroConstructor)
class FString ValueDisplay; // (Parm, OutParm, ZeroConstructor)
bool ShowInTooltip; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PrimalItem_Spawner_Exosuit.PrimalItem_Spawner_Exosuit_C.ExecuteUbergraph_PrimalItem_Spawner_Exosuit
struct UPrimalItem_Spawner_Exosuit_C_ExecuteUbergraph_PrimalItem_Spawner_Exosuit_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 49.869565
| 173
| 0.493897
|
2bite
|
8eb80589d93faf35ad4eb82fda45dc979a250a07
| 1,207
|
cpp
|
C++
|
test/delegate/test_bad_delegate_call.cpp
|
rmettler/cpp_delegates
|
8557a1731eccbad9608f3111c5599f666b74750e
|
[
"BSL-1.0"
] | 4
|
2020-01-30T19:17:57.000Z
|
2020-04-02T13:03:13.000Z
|
test/delegate/test_bad_delegate_call.cpp
|
rmettler/cpp_delegates
|
8557a1731eccbad9608f3111c5599f666b74750e
|
[
"BSL-1.0"
] | null | null | null |
test/delegate/test_bad_delegate_call.cpp
|
rmettler/cpp_delegates
|
8557a1731eccbad9608f3111c5599f666b74750e
|
[
"BSL-1.0"
] | null | null | null |
//
// Project: C++ delegates
//
// Copyright Roger Mettler 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// https://www.boost.org/LICENSE_1_0.txt)
//
#include <doctest.h>
#include <rome/detail/bad_delegate_call.hpp>
#include <type_traits>
TEST_SUITE_BEGIN("header file: rome/bad_delegate_call.hpp");
TEST_CASE("rome::bad_delegate_call") {
static_assert(std::is_nothrow_default_constructible<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_copy_constructible<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_copy_assignable<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_move_constructible<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_move_assignable<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_destructible<rome::bad_delegate_call>::value, "");
static_assert(std::is_base_of<std::exception, rome::bad_delegate_call>::value, "");
CHECK_THROWS_WITH_AS(
throw rome::bad_delegate_call{}, "rome::bad_delegate_call", rome::bad_delegate_call);
}
TEST_SUITE_END(); // rome/bad_delegate_call.hpp
| 40.233333
| 93
| 0.754764
|
rmettler
|
8ebd11dc81d5d857155b39acd498a54c06eaf01b
| 1,487
|
hpp
|
C++
|
discregrid/include/Discregrid/acceleration/bounding_sphere_hierarchy.hpp
|
lasagnaphil/Discregrid
|
83bec4b39445e7ed62229e6f84d94c0cfcc1136b
|
[
"MIT"
] | null | null | null |
discregrid/include/Discregrid/acceleration/bounding_sphere_hierarchy.hpp
|
lasagnaphil/Discregrid
|
83bec4b39445e7ed62229e6f84d94c0cfcc1136b
|
[
"MIT"
] | null | null | null |
discregrid/include/Discregrid/acceleration/bounding_sphere_hierarchy.hpp
|
lasagnaphil/Discregrid
|
83bec4b39445e7ed62229e6f84d94c0cfcc1136b
|
[
"MIT"
] | null | null | null |
#pragma once
#include "types.hpp"
#include "bounding_sphere.hpp"
#include "kd_tree.hpp"
#include <span.hpp>
namespace Discregrid
{
class TriangleMeshBSH : public KDTree<BoundingSphere>
{
public:
using super = KDTree<BoundingSphere>;
TriangleMeshBSH(std::span<const Vector3r> vertices,
std::span<const Eigen::Vector3i> faces);
Vector3r const& entityPosition(int i) const final;
void computeHull(int b, int n, BoundingSphere& hull) const final;
private:
std::span<const Vector3r> m_vertices;
std::span<const Eigen::Vector3i> m_faces;
std::vector<Vector3r> m_tri_centers;
};
class TriangleMeshBBH : public KDTree<AlignedBox3r>
{
public:
using super = KDTree<AlignedBox3r>;
TriangleMeshBBH(std::span<const Vector3r> vertices,
std::span<const Eigen::Vector3i> faces);
Vector3r const& entityPosition(int i) const final;
void computeHull(int b, int n, AlignedBox3r& hull) const final;
private:
std::span<const Vector3r> m_vertices;
std::span<const Eigen::Vector3i> m_faces;
std::vector<Vector3r> m_tri_centers;
};
class PointCloudBSH : public KDTree<BoundingSphere>
{
public:
using super = KDTree<BoundingSphere>;
PointCloudBSH();
PointCloudBSH(std::span<const Vector3r> vertices);
Vector3r const& entityPosition(int i) const final;
void computeHull(int b, int n, BoundingSphere& hull)
const final;
private:
std::span<const Vector3r> m_vertices;
};
}
| 19.826667
| 67
| 0.705447
|
lasagnaphil
|
8ebde15b22131d13eebeffbf14d860e37bc7ed26
| 4,173
|
cpp
|
C++
|
src/mirrage/net/src/server.cpp
|
lowkey42/mirrage
|
2527537989a548062d0bbca8370d063fc6b81a18
|
[
"MIT"
] | 14
|
2017-10-26T08:45:54.000Z
|
2021-04-06T11:44:17.000Z
|
src/mirrage/net/src/server.cpp
|
lowkey42/mirrage
|
2527537989a548062d0bbca8370d063fc6b81a18
|
[
"MIT"
] | 17
|
2017-10-09T20:11:58.000Z
|
2018-11-08T22:05:14.000Z
|
src/mirrage/net/src/server.cpp
|
lowkey42/mirrage
|
2527537989a548062d0bbca8370d063fc6b81a18
|
[
"MIT"
] | 1
|
2018-09-26T23:10:06.000Z
|
2018-09-26T23:10:06.000Z
|
#include <mirrage/net/server.hpp>
#include <mirrage/net/error.hpp>
#include <mirrage/utils/container_utils.hpp>
#include <enet/enet.h>
namespace mirrage::net {
Server_builder::Server_builder(Host_type type,
std::string hostname,
std::uint16_t port,
const Channel_definitions& channels)
: _type(type), _hostname(std::move(hostname)), _port(port), _channels(channels)
{
}
auto Server_builder::create() -> Server
{
return {_type,
_hostname,
_port,
_channels,
_max_clients,
_max_in_bandwidth,
_max_out_bandwidth,
_on_connect,
_on_disconnect};
}
namespace {
auto open_server_host(Server_builder::Host_type type,
const std::string& hostname,
std::uint16_t port,
std::size_t channel_count,
int max_clients,
int max_in_bandwidth,
int max_out_bandwidth)
{
ENetAddress address;
address.port = port;
switch(type) {
case Server_builder::Host_type::any: address.host = ENET_HOST_ANY; break;
case Server_builder::Host_type::broadcast:
#ifdef WIN32
address.host = ENET_HOST_ANY;
#else
address.host = ENET_HOST_BROADCAST;
#endif
break;
case Server_builder::Host_type::named:
auto ec = enet_address_set_host(&address, hostname.c_str());
if(ec != 0) {
const auto msg = "Couldn't resolve host \"" + hostname + "\".";
LOG(plog::warning) << msg;
throw std::system_error(Net_error::unknown_host, msg);
}
break;
}
auto host = enet_host_create(&address,
gsl::narrow<size_t>(max_clients),
channel_count,
gsl::narrow<enet_uint32>(max_in_bandwidth),
gsl::narrow<enet_uint32>(max_out_bandwidth));
if(!host) {
constexpr auto msg = "Couldn't create the host data structure (out of memory?)";
LOG(plog::warning) << msg;
throw std::system_error(Net_error::unspecified_network_error, msg);
}
return std::unique_ptr<ENetHost, void (*)(ENetHost*)>(host, &enet_host_destroy);
}
} // namespace
Server::Server(Server_builder::Host_type type,
const std::string& hostname,
std::uint16_t port,
const Channel_definitions& channels,
int max_clients,
int max_in_bandwidth,
int max_out_bandwidth,
Connected_callback on_connected,
Disconnected_callback on_disconnected)
: Connection(
open_server_host(
type, hostname, port, channels.size(), max_clients, max_in_bandwidth, max_out_bandwidth),
channels,
std::move(on_connected),
std::move(on_disconnected))
{
}
auto Server::broadcast_channel(util::Str_id channel) -> Channel
{
auto&& c = _channels.by_name(channel);
if(c.is_nothing()) {
const auto msg = "Unknown channel \"" + channel.str() + "\".";
LOG(plog::warning) << msg;
throw std::system_error(Net_error::unknown_channel, msg);
}
return Channel(_host.get(), c.get_or_throw());
}
auto Server::client_channel(util::Str_id channel, Client_handle client) -> Channel
{
auto&& c = _channels.by_name(channel);
if(c.is_nothing()) {
const auto msg = "Unknown channel \"" + channel.str() + "\".";
LOG(plog::warning) << msg;
throw std::system_error(Net_error::unknown_channel, msg);
}
return Channel(client, c.get_or_throw());
}
void Server::_on_connected(Client_handle client) { _clients.emplace_back(client); }
void Server::_on_disconnected(Client_handle client, std::uint32_t) { util::erase_fast(_clients, client); }
} // namespace mirrage::net
| 32.348837
| 108
| 0.565061
|
lowkey42
|
8ebee5f2aa9ebe853f989c65ce409b121fc4bd7a
| 8,870
|
hpp
|
C++
|
include/libndgpp/network_byte_order.hpp
|
goodfella/libndgpp
|
2e3d4b993a04664905c1e257fb2af3a5faab5296
|
[
"MIT"
] | null | null | null |
include/libndgpp/network_byte_order.hpp
|
goodfella/libndgpp
|
2e3d4b993a04664905c1e257fb2af3a5faab5296
|
[
"MIT"
] | null | null | null |
include/libndgpp/network_byte_order.hpp
|
goodfella/libndgpp
|
2e3d4b993a04664905c1e257fb2af3a5faab5296
|
[
"MIT"
] | null | null | null |
#ifndef LIBNDGPP_NETWORK_BYTE_ORDER_HPP
#define LIBNDGPP_NETWORK_BYTE_ORDER_HPP
#include <algorithm>
#include <array>
#include <cstring>
#include <type_traits>
#include <utility>
#include <ostream>
#include <libndgpp/network_byte_order_ops.hpp>
namespace ndgpp
{
/** Stores a native type value in network byte order
*
* The ndgpp::network_byte_order class is a regular type that
* will seemlessly represent a native type value in network byte
* order.
*
* @tparam T The native type i.e. uint16_t, uint32_t, uint64_t
*/
template <class T>
class network_byte_order
{
static_assert(std::is_integral<T>::value, "T is not an integral type");
static_assert(!std::is_signed<T>::value, "T is not unsigned");
public:
using value_type = T;
constexpr
network_byte_order() noexcept;
/** Constructs a network_byte_order instance with the specified value
*
* @param value An instance of type T in host byte order
*/
explicit
constexpr
network_byte_order(const T value) noexcept;
constexpr
network_byte_order(const network_byte_order & other) noexcept;
network_byte_order(network_byte_order && other) noexcept;
/** Assigns this to the value of rhs
*
* @param rhs An instance of type T in host byte order
*/
network_byte_order & operator= (const T rhs) noexcept;
network_byte_order & operator= (const network_byte_order & rhs) noexcept;
network_byte_order & operator= (network_byte_order && rhs) noexcept;
/// Returns the stored value in host byte order
constexpr
operator value_type () const noexcept;
/** Returns the address of the underlying value
*
* This is useful for sending the value over a socket:
*
* \code
* const int ret = send(&v, v.size());
*/
value_type const * operator &() const noexcept;
value_type * operator &() noexcept;
/// Returns the size of the underlying value
constexpr std::size_t size() const noexcept;
void swap(network_byte_order<T> & other) noexcept;
private:
value_type value_;
friend bool operator== <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator!= <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator< <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator> <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator<= <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator>= <> (const network_byte_order<T>, const network_byte_order<T>);
};
template <class T>
inline
bool operator== (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return lhs.value_ == rhs.value_;
}
template <class T>
inline
bool operator!= (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return !(lhs == rhs);
}
template <class T>
inline
bool operator< (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return lhs.value_ < rhs.value_;
}
template <class T>
inline
bool operator> (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return rhs < lhs;
}
template <class T>
inline
bool operator<= (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return !(rhs < lhs);
}
template <class T>
inline
bool operator>= (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return !(lhs < rhs);
}
inline uint16_t host_to_network(const uint16_t val) noexcept
{
alignas(std::alignment_of<uint16_t>::value) std::array<uint8_t, 2> buf;
buf[0] = static_cast<uint8_t>((val & 0xff00) >> 8);
buf[1] = static_cast<uint8_t>((val & 0x00ff));
return *reinterpret_cast<uint16_t*>(buf.data());
}
inline uint32_t host_to_network(const uint32_t val) noexcept
{
alignas(std::alignment_of<uint32_t>::value) std::array<uint8_t, 4> buf;
buf[0] = static_cast<uint8_t>((val & 0xff000000) >> 24);
buf[1] = static_cast<uint8_t>((val & 0x00ff0000) >> 16);
buf[2] = static_cast<uint8_t>((val & 0x0000ff00) >> 8);
buf[3] = static_cast<uint8_t>((val & 0x000000ff));
return *reinterpret_cast<uint32_t*>(buf.data());
}
inline uint64_t host_to_network(const uint64_t val) noexcept
{
alignas(std::alignment_of<uint64_t>::value) std::array<uint8_t, 8> buf;
buf[0] = static_cast<uint8_t>((val & 0xff00000000000000) >> 56);
buf[1] = static_cast<uint8_t>((val & 0x00ff000000000000) >> 48);
buf[2] = static_cast<uint8_t>((val & 0x0000ff0000000000) >> 40);
buf[3] = static_cast<uint8_t>((val & 0x000000ff00000000) >> 32);
buf[4] = static_cast<uint8_t>((val & 0x00000000ff000000) >> 24);
buf[5] = static_cast<uint8_t>((val & 0x0000000000ff0000) >> 16);
buf[6] = static_cast<uint8_t>((val & 0x000000000000ff00) >> 8);
buf[7] = static_cast<uint8_t>((val & 0x00000000000000ff));
return *reinterpret_cast<uint64_t*>(buf.data());
}
inline uint16_t network_to_host(const uint16_t val)
{
std::array<uint8_t, 2> buf;
std::memcpy(buf.data(), &val, sizeof(val));
return
static_cast<uint16_t>(buf[0]) << 8 |
static_cast<uint16_t>(buf[1]);
}
inline uint32_t network_to_host(const uint32_t val) noexcept
{
std::array<uint8_t, 4> buf;
std::memcpy(buf.data(), &val, sizeof(val));
return
static_cast<uint32_t>(buf[0]) << 24 |
static_cast<uint32_t>(buf[1]) << 16 |
static_cast<uint32_t>(buf[2]) << 8 |
static_cast<uint32_t>(buf[3]);
}
inline uint64_t network_to_host(const uint64_t val) noexcept
{
std::array<uint8_t, 8> buf;
std::memcpy(buf.data(), &val, sizeof(val));
return
static_cast<uint64_t>(buf[0]) << 56 |
static_cast<uint64_t>(buf[1]) << 48 |
static_cast<uint64_t>(buf[2]) << 40 |
static_cast<uint64_t>(buf[3]) << 32 |
static_cast<uint64_t>(buf[4]) << 24 |
static_cast<uint64_t>(buf[5]) << 16 |
static_cast<uint64_t>(buf[6]) << 8 |
static_cast<uint64_t>(buf[7]);
}
template <class T>
void swap(network_byte_order<T> & lhs, network_byte_order<T> & rhs)
{
lhs.swap(rhs);
}
template <class T>
inline
std::ostream & operator <<(std::ostream & out, const network_byte_order<T> val)
{
out << static_cast<T>(val);
return out;
}
}
template <class T>
inline
constexpr
ndgpp::network_byte_order<T>::network_byte_order() noexcept = default;
template <class T>
inline
constexpr
ndgpp::network_byte_order<T>::network_byte_order(const ndgpp::network_byte_order<T>& other) noexcept = default;
template <class T>
inline
ndgpp::network_byte_order<T>::network_byte_order(ndgpp::network_byte_order<T>&& other) noexcept = default;
template <class T>
inline
ndgpp::network_byte_order<T> & ndgpp::network_byte_order<T>::operator= (const ndgpp::network_byte_order<T>& other) noexcept = default;
template <class T>
inline
ndgpp::network_byte_order<T> & ndgpp::network_byte_order<T>::operator= (ndgpp::network_byte_order<T>&& other) noexcept = default;
template <class T>
inline
constexpr
ndgpp::network_byte_order<T>::network_byte_order(const T value) noexcept:
value_(ndgpp::host_to_network(value))
{}
template <class T>
inline
ndgpp::network_byte_order<T> & ndgpp::network_byte_order<T>::operator= (const T value) noexcept
{
this->value_ = ndgpp::host_to_network(value);
return *this;
}
template <class T>
inline
constexpr
ndgpp::network_byte_order<T>::operator T() const noexcept
{
return ndgpp::network_to_host(this->value_);
}
template <class T>
inline
T const * ndgpp::network_byte_order<T>::operator &() const noexcept
{
return &this->value_;
}
template <class T>
inline
T * ndgpp::network_byte_order<T>::operator &() noexcept
{
return &this->value_;
}
template <class T>
inline
constexpr
std::size_t ndgpp::network_byte_order<T>::size() const noexcept
{
return sizeof(T);
}
template <class T>
inline
void ndgpp::network_byte_order<T>::swap(ndgpp::network_byte_order<T> & other) noexcept
{
std::swap(this->value_, other.value_);
}
#endif
| 29.966216
| 134
| 0.632131
|
goodfella
|
8ecca67a112fa7fab1224acf1833c07ebef08c75
| 2,361
|
cpp
|
C++
|
source/main-http.cpp
|
janjongboom/mbed-os-example-fota-http
|
20ef030aa95052a82c31c0eaece154dbc408de75
|
[
"MIT"
] | 6
|
2017-10-11T08:56:32.000Z
|
2022-02-24T14:09:30.000Z
|
source/main-http.cpp
|
janjongboom/mbed-os-example-fota-http
|
20ef030aa95052a82c31c0eaece154dbc408de75
|
[
"MIT"
] | 2
|
2017-08-28T16:08:36.000Z
|
2018-06-20T20:07:54.000Z
|
source/main-http.cpp
|
janjongboom/mbed-os-example-fota-http
|
20ef030aa95052a82c31c0eaece154dbc408de75
|
[
"MIT"
] | 5
|
2018-03-27T08:59:23.000Z
|
2022-01-26T21:08:50.000Z
|
#include "mbed.h"
#include "easy-connect.h"
#include "http_request.h"
#include "SDBlockDevice.h"
#include "FATFileSystem.h"
#define SD_MOUNT_PATH "sd"
#define FULL_UPDATE_FILE_PATH "/" SD_MOUNT_PATH "/" MBED_CONF_APP_UPDATE_FILE
//Pin order: MOSI, MISO, SCK, CS
SDBlockDevice sd(MBED_CONF_APP_SD_CARD_MOSI, MBED_CONF_APP_SD_CARD_MISO,
MBED_CONF_APP_SD_CARD_SCK, MBED_CONF_APP_SD_CARD_CS);
FATFileSystem fs(SD_MOUNT_PATH);
NetworkInterface* network;
EventQueue queue;
InterruptIn btn(SW0);
FILE* file;
size_t received = 0;
size_t received_packets = 0;
void store_fragment(const char* buffer, size_t size) {
fwrite(buffer, 1, size, file);
received += size;
received_packets++;
if (received_packets % 20 == 0) {
printf("Received %u bytes\n", received);
}
}
void check_for_update() {
btn.fall(NULL); // remove the button listener
file = fopen(FULL_UPDATE_FILE_PATH, "wb");
HttpRequest* req = new HttpRequest(network, HTTP_GET, "http://192.168.0.105:8000/update.bin", &store_fragment);
HttpResponse* res = req->send();
if (!res) {
printf("HttpRequest failed (error code %d)\n", req->get_error());
return;
}
printf("Done downloading: %d - %s\n", res->get_status_code(), res->get_status_message().c_str());
fclose(file);
delete req;
printf("Rebooting...\n\n");
NVIC_SystemReset();
}
DigitalOut led(LED1);
void blink_led() {
led = !led;
}
int main() {
printf("Hello from THE ORIGINAL application\n");
Thread eventThread;
eventThread.start(callback(&queue, &EventQueue::dispatch_forever));
queue.call_every(500, &blink_led);
btn.mode(PullUp); // PullUp mode on the ODIN W2 EVK
btn.fall(queue.event(&check_for_update));
int r;
if ((r = sd.init()) != 0) {
printf("Could not initialize SD driver (%d)\n", r);
return 1;
}
if ((r = fs.mount(&sd)) != 0) {
printf("Could not mount filesystem, is the SD card formatted as FAT? (%d)\n", r);
return 1;
}
// Connect to the network (see mbed_app.json for the connectivity method used)
network = easy_connect(true);
if (!network) {
printf("Cannot connect to the network, see serial output\n");
return 1;
}
printf("Press SW0 to check for update\n");
wait(osWaitForever);
}
| 25.117021
| 115
| 0.650148
|
janjongboom
|
8ecfa08d7f74ed2312be0182606f1b456a6efff4
| 17,900
|
cpp
|
C++
|
src/remotecommandhandler.cpp
|
hrxcodes/cbftp
|
bf2784007dcc4cc42775a2d40157c51b80383f81
|
[
"MIT"
] | 8
|
2019-04-30T00:37:00.000Z
|
2022-02-03T13:35:31.000Z
|
src/remotecommandhandler.cpp
|
Xtravaganz/cbftp
|
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
|
[
"MIT"
] | 2
|
2019-11-19T12:46:13.000Z
|
2019-12-20T22:13:57.000Z
|
src/remotecommandhandler.cpp
|
Xtravaganz/cbftp
|
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
|
[
"MIT"
] | 9
|
2020-01-15T02:38:36.000Z
|
2022-02-15T20:05:20.000Z
|
#include "remotecommandhandler.h"
#include <vector>
#include <list>
#include "core/tickpoke.h"
#include "core/iomanager.h"
#include "core/types.h"
#include "crypto.h"
#include "globalcontext.h"
#include "engine.h"
#include "eventlog.h"
#include "util.h"
#include "sitelogicmanager.h"
#include "sitelogic.h"
#include "uibase.h"
#include "sitemanager.h"
#include "site.h"
#include "race.h"
#include "localstorage.h"
#include "httpserver.h"
#define DEFAULT_PASS "DEFAULT"
#define RETRY_DELAY 30000
namespace {
enum RaceType {
RACE,
DISTRIBUTE,
PREPARE
};
std::list<std::shared_ptr<SiteLogic> > getSiteLogicList(const std::string & sitestring) {
std::list<std::shared_ptr<SiteLogic> > sitelogics;
std::list<std::string> sites;
if (sitestring == "*") {
std::vector<std::shared_ptr<Site> >::const_iterator it;
for (it = global->getSiteManager()->begin(); it != global->getSiteManager()->end(); it++) {
if (!(*it)->getDisabled()) {
sites.push_back((*it)->getName());
}
}
}
else {
sites = util::trim(util::split(sitestring, ","));
}
std::list<std::string> notfoundsites;
for (std::list<std::string>::const_iterator it = sites.begin(); it != sites.end(); it++) {
const std::shared_ptr<SiteLogic> sl = global->getSiteLogicManager()->getSiteLogic(*it);
if (!sl) {
notfoundsites.push_back(*it);
continue;
}
sitelogics.push_back(sl);
}
if (sitelogics.empty()) {
for (std::vector<std::shared_ptr<Site> >::const_iterator it = global->getSiteManager()->begin(); it != global->getSiteManager()->end(); ++it) {
if ((*it)->hasSection(sitestring) && !(*it)->getDisabled()) {
std::shared_ptr<SiteLogic> sl = global->getSiteLogicManager()->getSiteLogic((*it)->getName());
sitelogics.push_back(sl);
}
}
}
if (!notfoundsites.empty()) {
std::string notfound = util::join(notfoundsites, ",");
if (sites.size() == 1) {
global->getEventLog()->log("RemoteCommandHandler", "Site or section not found: " + notfound);
}
else {
global->getEventLog()->log("RemoteCommandHandler", "Sites not found: " + notfound);
}
}
return sitelogics;
}
bool useOrSectionTranslate(Path& path, const std::shared_ptr<Site>& site) {
if (path.isRelative()) {
path.level(0);
std::string section = path.level(0).toString();
if (site->hasSection(section)) {
path = site->getSectionPath(section) / path.cutLevels(-1);
}
else {
global->getEventLog()->log("RemoteCommandHandler", "Path must be absolute or a section name on " +
site->getName() + ": " + path.toString());
return false;
}
}
return true;
}
}
RemoteCommandHandler::RemoteCommandHandler() :
enabled(false),
encrypted(true),
password(DEFAULT_PASS),
port(DEFAULT_API_PORT),
retrying(false),
connected(false),
notify(RemoteCommandNotify::DISABLED) {
}
bool RemoteCommandHandler::isEnabled() const {
return enabled;
}
bool RemoteCommandHandler::isEncrypted() const {
return encrypted;
}
int RemoteCommandHandler::getUDPPort() const {
return port;
}
std::string RemoteCommandHandler::getPassword() const {
return password;
}
void RemoteCommandHandler::setPassword(const std::string & newpass) {
password = newpass;
}
void RemoteCommandHandler::setPort(int newport) {
bool reopen = !(port == newport || !enabled);
port = newport;
if (reopen) {
setEnabled(false);
setEnabled(true);
}
}
RemoteCommandNotify RemoteCommandHandler::getNotify() const {
return notify;
}
void RemoteCommandHandler::setNotify(RemoteCommandNotify notify) {
this->notify = notify;
}
void RemoteCommandHandler::connect() {
int udpport = getUDPPort();
sockid = global->getIOManager()->registerUDPServerSocket(this, udpport);
if (sockid >= 0) {
connected = true;
global->getEventLog()->log("RemoteCommandHandler", "Listening on UDP port " + std::to_string(udpport));
}
else {
int delay = RETRY_DELAY / 1000;
global->getEventLog()->log("RemoteCommandHandler", "Retrying in " + std::to_string(delay) + " seconds.");
retrying = true;
global->getTickPoke()->startPoke(this, "RemoteCommandHandler", RETRY_DELAY, 0);
}
}
void RemoteCommandHandler::FDData(int sockid, char * data, unsigned int datalen) {
std::string message;
if (encrypted) {
Core::BinaryData encrypted(datalen);
memcpy(encrypted.data(), data, datalen);
Core::BinaryData decrypted;
Core::BinaryData key(password.begin(), password.end());
Crypto::decrypt(encrypted, key, decrypted);
if (!Crypto::isMostlyASCII(decrypted)) {
global->getEventLog()->log("RemoteCommandHandler", "Received " + std::to_string(datalen) + " bytes of garbage or wrongly encrypted data");
return;
}
message = std::string(decrypted.begin(), decrypted.end());
}
else {
message = std::string(data, datalen);
}
handleMessage(message);
}
void RemoteCommandHandler::handleMessage(const std::string & message) {
std::string trimmedmessage = util::trim(message);
std::vector<std::string> tokens = util::splitVec(trimmedmessage);
if (tokens.size() < 2) {
global->getEventLog()->log("RemoteCommandHandler", "Bad message format: " + trimmedmessage);
return;
}
std::string & pass = tokens[0];
bool passok = pass == password;
if (passok) {
for (unsigned int i = 0; i < pass.length(); i++) {
pass[i] = '*';
}
}
global->getEventLog()->log("RemoteCommandHandler", "Received: " + util::join(tokens));
if (!passok) {
global->getEventLog()->log("RemoteCommandHandler", "Invalid password.");
return;
}
std::string command = tokens[1];
std::vector<std::string> remainder(tokens.begin() + 2, tokens.end());
bool notification = notify == RemoteCommandNotify::ALL_COMMANDS;
if (command == "race") {
bool started = commandRace(remainder);
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "distribute") {
bool started = commandDistribute(remainder) && notify >= RemoteCommandNotify::JOBS_ADDED;
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "prepare") {
bool created = commandPrepare(remainder);
if (created && notify >= RemoteCommandNotify::ACTION_REQUESTED) {
notification = true;
}
}
else if (command == "raw") {
commandRaw(remainder);
}
else if (command == "rawwithpath") {
commandRawWithPath(remainder);
}
else if (command == "fxp") {
bool started = commandFXP(remainder);
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "download") {
bool started = commandDownload(remainder);
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "upload") {
bool started = commandUpload(remainder);
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "idle") {
commandIdle(remainder);
}
else if (command == "abort") {
commandAbort(remainder);
}
else if (command == "delete") {
commandDelete(remainder);
}
else if (command == "abortdeleteincomplete") {
commandAbortDeleteIncomplete(remainder);
}
else if(command == "reset") {
commandReset(remainder, false);
}
else if(command == "hardreset") {
commandReset(remainder, true);
}
else {
global->getEventLog()->log("RemoteCommandHandler", "Invalid remote command: " + util::join(tokens));
return;
}
if (notification) {
global->getUIBase()->notify();
}
}
bool RemoteCommandHandler::commandRace(const std::vector<std::string> & message) {
return parseRace(message, RACE);
}
bool RemoteCommandHandler::commandDistribute(const std::vector<std::string> & message) {
return parseRace(message, DISTRIBUTE);
}
bool RemoteCommandHandler::commandPrepare(const std::vector<std::string> & message) {
return parseRace(message, PREPARE);
}
void RemoteCommandHandler::commandRaw(const std::vector<std::string> & message) {
if (message.size() < 2) {
global->getEventLog()->log("RemoteCommandHandler", "Bad remote raw command format: " + util::join(message));
return;
}
std::string sitestring = message[0];
std::string rawcommand = util::join(std::vector<std::string>(message.begin() + 1, message.end()));
std::list<std::shared_ptr<SiteLogic> > sites = getSiteLogicList(sitestring);
for (std::list<std::shared_ptr<SiteLogic> >::const_iterator it = sites.begin(); it != sites.end(); it++) {
(*it)->requestRawCommand(nullptr, rawcommand);
}
}
void RemoteCommandHandler::commandRawWithPath(const std::vector<std::string> & message) {
if (message.size() < 3) {
global->getEventLog()->log("RemoteCommandHandler", "Bad remote rawwithpath command format: " + util::join(message));
return;
}
std::string sitestring = message[0];
std::string pathstr = message[1];
std::string rawcommand = util::join(std::vector<std::string>(message.begin() + 2, message.end()));
std::list<std::shared_ptr<SiteLogic> > sites = getSiteLogicList(sitestring);
for (std::list<std::shared_ptr<SiteLogic> >::const_iterator it = sites.begin(); it != sites.end(); it++) {
Path path(pathstr);
if (!useOrSectionTranslate(path, (*it)->getSite())) {
continue;
}
(*it)->requestRawCommand(nullptr, path, rawcommand);
}
}
bool RemoteCommandHandler::commandFXP(const std::vector<std::string> & message) {
if (message.size() < 5) {
global->getEventLog()->log("RemoteCommandHandler", "Bad remote fxp command format: " + util::join(message));
return false;
}
std::shared_ptr<SiteLogic> srcsl = global->getSiteLogicManager()->getSiteLogic(message[0]);
std::shared_ptr<SiteLogic> dstsl = global->getSiteLogicManager()->getSiteLogic(message[3]);
if (!srcsl) {
global->getEventLog()->log("RemoteCommandHandler", "Bad site name: " + message[0]);
return false;
}
if (!dstsl) {
global->getEventLog()->log("RemoteCommandHandler", "Bad site name: " + message[3]);
return false;
}
std::string dstfile = message.size() > 5 ? message[5] : message[2];
Path srcpath(message[1]);
if (!useOrSectionTranslate(srcpath, srcsl->getSite())) {
return false;
}
Path dstpath(message[4]);
if (!useOrSectionTranslate(dstpath, dstsl->getSite())) {
return false;
}
global->getEngine()->newTransferJobFXP(message[0], srcpath, message[2], message[3], dstpath, dstfile);
return true;
}
bool RemoteCommandHandler::commandDownload(const std::vector<std::string> & message) {
if (message.size() < 2) {
global->getEventLog()->log("RemoteCommandHandler", "Bad download command format: " + util::join(message));
return false;
}
std::shared_ptr<SiteLogic> srcsl = global->getSiteLogicManager()->getSiteLogic(message[0]);
if (!srcsl) {
global->getEventLog()->log("RemoteCommandHandler", "Bad site name: " + message[0]);
return false;
}
Path srcpath = message[1];
if (!useOrSectionTranslate(srcpath, srcsl->getSite())) {
return false;
}
std::string file = srcpath.baseName();
if (message.size() == 2) {
srcpath = srcpath.dirName();
}
else {
file = message[2];
}
global->getEngine()->newTransferJobDownload(message[0], srcpath, file, global->getLocalStorage()->getDownloadPath(), file);
return true;
}
bool RemoteCommandHandler::commandUpload(const std::vector<std::string> & message) {
if (message.size() < 3) {
global->getEventLog()->log("RemoteCommandHandler", "Bad upload command format: " + util::join(message));
return false;
}
Path srcpath = message[0];
std::string file = srcpath.baseName();
std::string dstsite;
Path dstpath;
if (message.size() == 3) {
srcpath = srcpath.dirName();
dstsite = message[1];
dstpath = message[2];
}
else {
file = message[1];
dstsite = message[2];
dstpath = message[3];
}
std::shared_ptr<SiteLogic> dstsl = global->getSiteLogicManager()->getSiteLogic(dstsite);
if (!dstsl) {
global->getEventLog()->log("RemoteCommandHandler", "Bad site name: " + dstsite);
return false;
}
if (!useOrSectionTranslate(dstpath, dstsl->getSite())) {
return false;
}
global->getEngine()->newTransferJobUpload(srcpath, file, dstsite, dstpath, file);
return true;
}
void RemoteCommandHandler::commandIdle(const std::vector<std::string> & message) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad idle command format: " + util::join(message));
return;
}
int idletime;
std::string sitestring;
if (message.size() < 2) {
sitestring = message[0];
idletime = 0;
}
else {
sitestring = message[0];
idletime = std::stoi(message[1]);
}
std::list<std::shared_ptr<SiteLogic> > sites = getSiteLogicList(sitestring);
for (std::list<std::shared_ptr<SiteLogic> >::const_iterator it = sites.begin(); it != sites.end(); it++) {
(*it)->requestAllIdle(nullptr, idletime);
}
}
void RemoteCommandHandler::commandAbort(const std::vector<std::string> & message) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad abort command format: " + util::join(message));
return;
}
std::shared_ptr<Race> race = global->getEngine()->getRace(message[0]);
if (!race) {
global->getEventLog()->log("RemoteCommandHandler", "No matching race: " + message[0]);
return;
}
global->getEngine()->abortRace(race);
}
void RemoteCommandHandler::commandDelete(const std::vector<std::string> & message) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad delete command format: " + util::join(message));
return;
}
std::string release = message[0];
std::string sitestring;
if (message.size() >= 2) {
sitestring = message[1];
}
std::shared_ptr<Race> race = global->getEngine()->getRace(release);
if (!race) {
global->getEventLog()->log("RemoteCommandHandler", "No matching race: " + release);
return;
}
if (!sitestring.length()) {
global->getEngine()->deleteOnAllSites(race, false, true);
return;
}
std::list<std::shared_ptr<SiteLogic> > sitelogics = getSiteLogicList(sitestring);
std::list<std::shared_ptr<Site> > sites;
for (std::list<std::shared_ptr<SiteLogic> >::const_iterator it = sitelogics.begin(); it != sitelogics.end(); it++) {
sites.push_back((*it)->getSite());
}
global->getEngine()->deleteOnSites(race, sites, false);
}
void RemoteCommandHandler::commandAbortDeleteIncomplete(const std::vector<std::string> & message) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad abortdeleteincomplete command format: " + util::join(message));
return;
}
std::string release = message[0];
std::shared_ptr<Race> race = global->getEngine()->getRace(release);
if (!race) {
global->getEventLog()->log("RemoteCommandHandler", "No matching race: " + release);
return;
}
global->getEngine()->deleteOnAllSites(race, false, false);
}
void RemoteCommandHandler::commandReset(const std::vector<std::string> & message, bool hard) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad reset command format: " + util::join(message));
return;
}
std::shared_ptr<Race> race = global->getEngine()->getRace(message[0]);
if (!race) {
global->getEventLog()->log("RemoteCommandHandler", "No matching race: " + message[0]);
return;
}
global->getEngine()->resetRace(race, hard);
}
bool RemoteCommandHandler::parseRace(const std::vector<std::string> & message, int type) {
if (message.size() < 3) {
global->getEventLog()->log("RemoteCommandHandler", "Bad remote race command format: " + util::join(message));
return false;
}
std::string section = message[0];
std::string release = message[1];
std::string sitestring = message[2];
std::list<std::string> sites;
if (sitestring == "*") {
for (std::vector<std::shared_ptr<Site> >::const_iterator it = global->getSiteManager()->begin(); it != global->getSiteManager()->end(); it++) {
if ((*it)->hasSection(section) && !(*it)->getDisabled()) {
sites.push_back((*it)->getName());
}
}
}
else {
sites = util::trim(util::split(sitestring, ","));
}
std::list<std::string> dlonlysites;
if (message.size() >= 4) {
std::string dlonlysitestring = message[3];
dlonlysites = util::trim(util::split(dlonlysitestring, ","));
}
if (type == RACE) {
return !!global->getEngine()->newRace(release, section, sites, false, dlonlysites);
}
else if (type == DISTRIBUTE){
return !!global->getEngine()->newDistribute(release, section, sites, false, dlonlysites);
}
else {
return global->getEngine()->prepareRace(release, section, sites, false, dlonlysites);
}
}
void RemoteCommandHandler::FDFail(int sockid, const std::string & message) {
global->getEventLog()->log("RemoteCommandHandler", "UDP binding on port " +
std::to_string(getUDPPort()) + " failed: " + message);
}
void RemoteCommandHandler::disconnect() {
if (connected) {
global->getIOManager()->closeSocket(sockid);
global->getEventLog()->log("RemoteCommandHandler", "Closing UDP socket");
connected = false;
}
}
void RemoteCommandHandler::setEnabled(bool enabled) {
if (this->enabled == enabled) {
return;
}
if (retrying) {
stopRetry();
}
if (enabled) {
connect();
}
else {
disconnect();
}
this->enabled = enabled;
}
void RemoteCommandHandler::setEncrypted(bool encrypted) {
this->encrypted = encrypted;
}
void RemoteCommandHandler::stopRetry() {
if (retrying) {
global->getTickPoke()->stopPoke(this, 0);
retrying = false;
}
}
void RemoteCommandHandler::tick(int) {
stopRetry();
if (enabled) {
connect();
}
}
| 31.458699
| 147
| 0.662011
|
hrxcodes
|
8ed04f1821a61c8d2ef1152f7dc235c1047a0bff
| 1,076
|
hpp
|
C++
|
lib/STL+/strings/string_hash.hpp
|
knela96/Game-Engine
|
06659d933c4447bd8d6c8536af292825ce4c2ab1
|
[
"Unlicense"
] | 3
|
2018-05-07T19:09:23.000Z
|
2019-05-03T14:19:38.000Z
|
deps/stlplus/strings/string_hash.hpp
|
evpo/libencryptmsg
|
fa1ea59c014c0a9ce339d7046642db4c80fc8701
|
[
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | null | null | null |
deps/stlplus/strings/string_hash.hpp
|
evpo/libencryptmsg
|
fa1ea59c014c0a9ce339d7046642db4c80fc8701
|
[
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | null | null | null |
#ifndef STLPLUS_STRING_HASH
#define STLPLUS_STRING_HASH
////////////////////////////////////////////////////////////////////////////////
// Author: Andy Rushton
// Copyright: (c) Southampton University 1999-2004
// (c) Andy Rushton 2004 onwards
// License: BSD License, see ../docs/license.html
// Generate a string representation of a hash
////////////////////////////////////////////////////////////////////////////////
#include "strings_fixes.hpp"
#include "hash.hpp"
#include <string>
////////////////////////////////////////////////////////////////////////////////
namespace stlplus
{
template<typename K, typename T, typename H, typename E, typename KS, typename TS>
std::string hash_to_string(const hash<K,T,H,E>& values,
KS key_to_string_fn,
TS value_to_string_fn,
const std::string& pair_separator = ":",
const std::string& separator = ",");
} // end namespace stlplus
#include "string_hash.tpp"
#endif
| 32.606061
| 84
| 0.47026
|
knela96
|
8ed99072c5824ac16f4a579bfc9832b3a4202f97
| 198
|
cpp
|
C++
|
qfb-messenger/src/network_reply_handler.cpp
|
NickCis/harbour-facebook-messenger
|
b2c2305fdcec27321893c3230bbd9e724773bd7d
|
[
"MIT"
] | 1
|
2015-05-05T22:45:11.000Z
|
2015-05-05T22:45:11.000Z
|
qfb-messenger/src/network_reply_handler.cpp
|
NickCis/harbour-facebook-messenger
|
b2c2305fdcec27321893c3230bbd9e724773bd7d
|
[
"MIT"
] | null | null | null |
qfb-messenger/src/network_reply_handler.cpp
|
NickCis/harbour-facebook-messenger
|
b2c2305fdcec27321893c3230bbd9e724773bd7d
|
[
"MIT"
] | null | null | null |
#include "network_reply_handler.h"
NetworkReplyHandler::NetworkReplyHandler(QNetworkReply* r) :
QObject(r),
reply(r)
{
connect(this->reply, SIGNAL(finished()), this, SLOT(replyFinished()));
}
| 18
| 71
| 0.737374
|
NickCis
|
8eda40c7ef81d7a9161be254020ec7fa33e68e6e
| 801
|
cpp
|
C++
|
HW1Submit/main.cpp
|
manamhr/ITP365
|
616ea8f4074e05fd26eb8ece712b2df6aa70111f
|
[
"MIT"
] | null | null | null |
HW1Submit/main.cpp
|
manamhr/ITP365
|
616ea8f4074e05fd26eb8ece712b2df6aa70111f
|
[
"MIT"
] | null | null | null |
HW1Submit/main.cpp
|
manamhr/ITP365
|
616ea8f4074e05fd26eb8ece712b2df6aa70111f
|
[
"MIT"
] | null | null | null |
// ITP 365 Spring 2017
// HW1 - Sieve of Eratosthenes
// Name: Mana Mehraein
// Email: mehraein@usc.edu
// Platform: Mac
#include <iostream>
#include "gwindow.h"
#include "sieve.h"
#include <string>
#include "vector.h"
#include "strlib.h"
int main(int argc, char** argv)
{
// Create a 500x500 window
GWindow gw(500, 500);
Vector<int> number;
Vector<NumberType> type;
// Call initVectors in main
initVectors (number, type);
// drawGrid
drawGrid(gw,number,type);
int index=2;
// loop to find prime numbers and composites
while (calcNextPrime(number, type, index)!=-1)
{
drawGrid(gw,number,type);
pause(1000.0);
index++;
}
return 0;
}
| 18.627907
| 51
| 0.561798
|
manamhr
|
8edd65aebe7ac2a9a4c04604b60008f586d0ae7b
| 239
|
hh
|
C++
|
mimosa/rpc/http-call.hh
|
abique/mimosa
|
42c0041b570b55a24c606a7da79c70c9933c07d4
|
[
"MIT"
] | 24
|
2015-01-19T16:38:24.000Z
|
2022-01-15T01:25:30.000Z
|
mimosa/rpc/http-call.hh
|
abique/mimosa
|
42c0041b570b55a24c606a7da79c70c9933c07d4
|
[
"MIT"
] | 2
|
2017-01-07T10:47:06.000Z
|
2018-01-16T07:19:57.000Z
|
mimosa/rpc/http-call.hh
|
abique/mimosa
|
42c0041b570b55a24c606a7da79c70c9933c07d4
|
[
"MIT"
] | 7
|
2015-01-19T16:38:31.000Z
|
2020-12-12T19:10:30.000Z
|
#pragma once
#include "json.hh"
namespace mimosa
{
namespace rpc
{
bool httpCall(const std::string &url,
const google::protobuf::Message &request,
google::protobuf::Message *response);
}
}
| 17.071429
| 57
| 0.589958
|
abique
|
8ee250a474a297cfa9773bc8ee3176d49ab97767
| 1,935
|
cpp
|
C++
|
BasiliskII/src/BeOS/xpram_beos.cpp
|
jvernet/macemu
|
c616a0dae0f451fc15016765c896175fae3f46cf
|
[
"Intel",
"X11"
] | 940
|
2015-01-04T12:20:10.000Z
|
2022-03-29T12:35:27.000Z
|
BasiliskII/src/BeOS/xpram_beos.cpp
|
Seanpm2001-virtual-machines/macemu
|
c616a0dae0f451fc15016765c896175fae3f46cf
|
[
"Intel",
"X11"
] | 163
|
2015-02-10T09:08:10.000Z
|
2022-03-13T05:48:10.000Z
|
BasiliskII/src/BeOS/xpram_beos.cpp
|
Seanpm2001-virtual-machines/macemu
|
c616a0dae0f451fc15016765c896175fae3f46cf
|
[
"Intel",
"X11"
] | 188
|
2015-01-07T19:46:11.000Z
|
2022-03-26T19:06:00.000Z
|
/*
* xpram_beos.cpp - XPRAM handling, BeOS specific stuff
*
* Basilisk II (C) 1997-2008 Christian Bauer
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <StorageKit.h>
#include <unistd.h>
#include "sysdeps.h"
#include "xpram.h"
// XPRAM file name and path
#if POWERPC_ROM
const char XPRAM_FILE_NAME[] = "SheepShaver_NVRAM";
#else
const char XPRAM_FILE_NAME[] = "BasiliskII_XPRAM";
#endif
static BPath xpram_path;
/*
* Load XPRAM from settings file
*/
void LoadXPRAM(const char *vmdir)
{
// Construct XPRAM path
find_directory(B_USER_SETTINGS_DIRECTORY, &xpram_path, true);
xpram_path.Append(XPRAM_FILE_NAME);
// Load XPRAM from settings file
int fd;
if ((fd = open(xpram_path.Path(), O_RDONLY)) >= 0) {
read(fd, XPRAM, XPRAM_SIZE);
close(fd);
}
}
/*
* Save XPRAM to settings file
*/
void SaveXPRAM(void)
{
if (xpram_path.InitCheck() != B_NO_ERROR)
return;
int fd;
if ((fd = open(xpram_path.Path(), O_WRONLY | O_CREAT, 0666)) >= 0) {
write(fd, XPRAM, XPRAM_SIZE);
close(fd);
}
}
/*
* Delete PRAM file
*/
void ZapPRAM(void)
{
// Construct PRAM path
find_directory(B_USER_SETTINGS_DIRECTORY, &xpram_path, true);
xpram_path.Append(XPRAM_FILE_NAME);
// Delete file
unlink(xpram_path.Path());
}
| 22.764706
| 77
| 0.710078
|
jvernet
|
8ee65978c71f54b000ca8db80dcf15b9bcd191ff
| 11,443
|
cpp
|
C++
|
jmax/Window.cpp
|
JeanGamain/jmax
|
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
|
[
"MIT"
] | null | null | null |
jmax/Window.cpp
|
JeanGamain/jmax
|
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
|
[
"MIT"
] | null | null | null |
jmax/Window.cpp
|
JeanGamain/jmax
|
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
|
[
"MIT"
] | null | null | null |
#include "Window.hpp"
#include "jmax.hpp"
#include "math.h"
#include "shader/Shader.hpp"
#include <map>
#include <stdexcept>
#include <string>
#include <utility>
namespace jmax {
Window::Window(unsigned int width, unsigned int height)
: view(width, height)
, _windowIO()
, _resizeAction(
std::string("window_resize"), std::string("Resize window image buffer"), IO_INPUT_FWINDOW, actionResizeWindow)
, _fileDropAction(
std::string("window_filedrop"),
std::string("Process files drag&drop as new model to import"),
IO_INPUT_FWINDOW,
actionFileDropImport)
, _renderTimer()
, _background(NULL)
, _somvp("omvp")
, _sgCameraLocalPos("gCameraLocalPos")
, _globalLight(vec3(0.6f))
, _simpleUniDirectLight(vec3(0.0f, -1.0f, 0.15f), vec3(0.4f))
, _materialUniform(Material::getUniform())
, _simpleUniDirectLightUniform(UniDirectionalLight::getUniform())
, _mainShaderProg(NULL)
, _guiShaderProg(NULL)
, _mainVs(NULL)
, _mainFs(NULL)
, _maxFps(0)
, _vsync(true)
, _fps(0)
// GUI stuff
, _guiInit(false)
, _guiEnable(false)
, _modelPickerEnable(false)
, _selectionBuffer(0)
, _selectionIds{0}
, _selectedModel(NULL)
, _selectedMaterialId(0)
, _guiFpsStats()
, _guiFs(NULL)
{
const char* error;
if ((error = jmax::init()) != NULL) {
throw new std::runtime_error(error);
}
initRender(width, height, "JMAX");
setupRenderSettings();
initInputBind();
setupSceneRender();
setMaxFps(222);
}
Window::~Window()
{
delete _materialUniform;
delete _simpleUniDirectLightUniform;
disableBackgroundSurface();
for (jmax::Model* model : _models) {
delete model;
}
if (_mainShaderProg) delete _mainShaderProg;
if (_guiShaderProg) delete _guiShaderProg;
if (_mainVs) delete _mainVs;
if (_mainFs) delete _mainFs;
// UI
if (_guiFs) delete _guiFs;
if (_guiInit) gui::deleteUI();
glfwDestroyWindow(_window);
glfwTerminate();
}
void Window::initRender(unsigned int width, unsigned height, char* windowsTitle)
{
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true); // DEBUG
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, JMAX_GLVERSION_MAJOR);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, JMAX_GLVERSION_MINOR);
glfwWindowHint(GLFW_OPENGL_PROFILE, JMAX_GLVERSION_TYPE);
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
if (!(_window = glfwCreateWindow(width, height, windowsTitle, NULL, NULL))) {
fprintf(stderr, "Error glfwCreateWindow()");
}
glfwMakeContextCurrent(_window);
glfwSwapInterval(_vsync ? 1 : 0);
jmax::setGLDebug();
}
void Window::setClearColor(vec4 color)
{
GLclampf Red = color.x, Green = color.y, Blue = color.z, Alpha = color.w;
glClearColor(Red, Green, Blue, Alpha);
}
void Window::setupRenderSettings()
{
setClearColor();
glEnable(GL_CULL_FACE);
/*
glFrontFace(GL_CW);
glCullFace(GL_BACK);
*/
glFrontFace(GL_CW);
glCullFace(GL_FRONT);
glEnable(GL_MULTISAMPLE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// GUI model/material picker
glGenBuffers(1, &_selectionBuffer);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, _selectionBuffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, _selectionBuffer);
glBufferStorage(GL_SHADER_STORAGE_BUFFER, sizeof(_selectionIds), &_selectionIds[0], GL_MAP_READ_BIT);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
}
void Window::setupSceneRender()
{
_mainVs = new Shader("../jmax/shader/shader.vs");
_mainFs = new Shader("../jmax/shader/shader.fs");
_guiFs = new Shader("../jmax/shader/gui_shader.fs");
_mainShaderProg = new jmax::ShaderProgram({_mainVs, _mainFs});
_guiShaderProg = new jmax::ShaderProgram({_mainVs, _guiFs});
_mainShaderProg->enable();
_scene.scale = vec3(1.0f);
_scene.position = vec3(0.0f, 0.0f, 2.0f);
_scene.rotation = vec3(0.0f, 0.01f, 0.0f);
}
void Window::initInputBind()
{
_input = new IO::InputActionManager(_window, this);
_input->addInput(&_windowIO);
_windowIO.bindAction(&_resizeAction, jmax::IO::WindowEvent(IO::WindowEvent::RESIZE));
_windowIO.bindAction(&_fileDropAction, jmax::IO::WindowEvent(IO::WindowEvent::FILEDROP));
}
void Window::render()
{
makeCurrent();
applyFpsControls();
_input->sync(1);
_renderTimer.reset();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
mat4 omvp;
mat4 mprojection = view.getProjection();
mat4 mview = view.getView();
mat4 mmodel = _scene.getMatrix();
mat4 mvp = mprojection * mview * mmodel;
view.bindUniform();
vec4 camLocPos =
_scene.getReversedRotationMatrix() * _scene.getReversedTranslationMatrix() * vec4(view.getPosition(), 1.0f);
glUniform3f(_sgCameraLocalPos(), camLocPos.x, camLocPos.y, camLocPos.z);
if (_background) {
_background->render(_somvp, _materialUniform);
}
glEnable(GL_DEPTH_TEST);
for (jmax::Model* model : _models) {
// sun
_simpleUniDirectLight.calcDirection(mmodel * mat4(mat3(model->getTransformation())));
_simpleUniDirectLight.bind(_simpleUniDirectLightUniform);
// global light
_globalLight.bind();
omvp = mvp * model->getTransformation();
glUniformMatrix4fv(_somvp(), 1, GL_FALSE, glm::value_ptr(omvp));
model->render(_materialUniform);
}
glDisable(GL_DEPTH_TEST);
renderGUI();
}
void Window::renderGUI()
{
gui::fpsStatsCalc(&_guiFpsStats, glfwGetTime(), _fps);
if (!_guiEnable || !_guiInit) {
return;
}
gui::newFrame();
ImGui::Begin("JMAX");
if (ImGui::CollapsingHeader("Render")) {
gui::LabelText("Render", "%s", (const char*)glGetString(GL_RENDERER));
gui::LabelText("Version", "%s", (const char*)glGetString(GL_VERSION));
gui::fpsStatsHistogram(&_guiFpsStats);
ImGui::Separator();
gui::Label("Vsync");
if (gui::ToggleSwitchBool(&_vsync)) {
setVSync(_vsync, true);
}
gui::SliderFloat("MAX", &_maxFps, 0.0f, _maxFpsMax, "%.1f fps");
}
if (ImGui::CollapsingHeader("Scene")) {
static_cast<Entity3d&>(_scene).drawUI();
if (ImGui::TreeNode("Light")) {
_globalLight.drawUI();
_simpleUniDirectLight.drawUI();
ImGui::TreePop();
}
if (ImGui::TreeNode("Background")) {
_background->drawUI();
ImGui::TreePop();
}
}
if (ImGui::CollapsingHeader("Camera")) {
view.drawUI();
}
if (ImGui::CollapsingHeader("Model")) {
gui::Label("Model picker");
if (gui::ToggleSwitchBool(&_modelPickerEnable) && !_modelPickerEnable) {
_selectedMaterialId = 0;
}
if (_modelPickerEnable) {
glBindBuffer(GL_SHADER_STORAGE_BUFFER, _selectionBuffer);
glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, sizeof(_selectionIds), &_selectionIds[0]);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
_selectedModel = getModel(_selectionIds[0]);
_selectedMaterialId = _selectionIds[1];
}
gui::Label("Model");
const char* current_item = _selectedModel ? _selectedModel->getName().c_str() : NULL;
ImGui::PushItemWidth(ImGui::CalcItemWidth());
if (ImGui::BeginCombo("##Model combo", current_item)) {
int n = 0;
for (jmax::Model* model : _models) {
const char* item = model->getName().c_str();
bool is_selected = (current_item == item);
if (ImGui::Selectable(item, is_selected)) {
_selectedModel = model;
_selectedMaterialId = 0;
_modelPickerEnable = false;
}
if (is_selected) ImGui::SetItemDefaultFocus();
++n;
}
ImGui::EndCombo();
}
ImGui::PopItemWidth();
if (_selectedModel) {
_selectedModel->drawUI(_selectedMaterialId);
}
}
ImGui::End();
gui::render();
}
void Window::swapBuffer()
{
glfwSwapBuffers(_window);
}
void Window::renderLoop()
{
while (!shouldClose()) {
render();
swapBuffer();
pollEvents();
}
}
Model* Window::getModel(unsigned int id) const
{
if (id < 1) {
return NULL;
}
for (jmax::Model* model : _models) {
if (model->id == id) {
return model;
}
}
return NULL;
}
double Window::getDelta()
{
return _renderTimer();
}
float Window::getfDelta()
{
return (float)_renderTimer();
}
void Window::setVSync(bool enable, bool force)
{
if (_vsync == enable && !force) {
return;
}
_vsync = enable;
glfwSwapInterval(_vsync ? 1 : 0);
// ifdef WIN32
/* if (wglSwapIntervalEXT != nullptr) {
_vsync = enable;
if (enable) {
wglSwapIntervalEXT(1);
} else {
wglSwapIntervalEXT(0);
}
} else {
_vsync = false;
}
*/
}
bool Window::getVSync()
{
bool vsyncEnable = _vsync;
/*
if (wglGetSwapIntervalEXT != nullptr) {
vsyncEnable = wglGetSwapIntervalEXT() > 0;
}*/
return vsyncEnable;
}
void Window::makeCurrent()
{
glfwMakeContextCurrent(_window);
}
bool Window::shouldClose() const
{
return glfwWindowShouldClose(_window);
}
void Window::pollEvents()
{
glfwPollEvents();
}
void Window::enableBackgroundSurface(Texture* surfacePath)
{
if (!_background) {
makeCurrent();
_background = new BackgroundSurface(surfacePath);
}
}
void Window::disableBackgroundSurface()
{
if (_background) {
delete _background;
_background = NULL;
}
}
Model* Window::addModel(const char* modelPath)
{
const char* error;
printf("Adding model \"%s\"\n", modelPath);
makeCurrent();
Model* newObject = new Model();
if ((error = newObject->import(modelPath)) != NULL) {
printf("%s", error);
delete newObject;
return NULL;
}
_models.push_back(newObject);
// delete newObject;
return newObject;
}
void Window::setMaxFps(float fps)
{
_maxFps = (fps < _maxFpsMin || fps > _maxFpsMax) ? 0.0f : fps;
}
void Window::applyFpsControls()
{
double time = _renderTimer.getSecond();
if (_maxFps > 0.0f) {
double minTime = 1;
minTime /= _maxFps;
while (minTime > time) {
// glfwPollEvents();
time = _renderTimer.getSecond();
}
}
_fps = static_cast<float>(1. / time);
}
IO::InputActionManager* Window::getInputManager()
{
return _input;
}
void Window::setGuiEnable(bool enable)
{
_guiEnable = enable;
if (_guiEnable) {
if (!_guiInit) {
gui::newUI(_window);
_guiInit = true;
}
_guiShaderProg->enable();
} else {
_mainShaderProg->enable();
}
}
bool Window::getGuiEnable() const
{
return _guiEnable;
}
void Window::actionResizeWindow(Window* window, IO::IInput* input, void* userContext)
{
IO::Window* windowIO = (IO::Window*)input;
ivec2 size = windowIO->getResizeData();
if (size.x == 0 || size.y == 0) {
return;
}
window->makeCurrent();
// glfwGetFramebufferSize(me->window, &size.x, &size.y);
window->view.resize(size.x, size.y);
glViewport(0, 0, size.x, size.y);
}
/*
void Engine::hRefresh(GLFWwindow* window)
{
Engine* me = (Engine*)jmax::IO::InputActionManager::getAppContext(window);
me->render();
}
*/
void Window::actionFileDropImport(Window* window, IO::IInput* input, void* userContext)
{
IO::Window* windowIO = (IO::Window*)input;
const std::list<std::string>& files = windowIO->getFileDropsData();
for (auto const& file : files) {
window->addModel(file.c_str());
}
windowIO->clearFileDropsData();
}
} // namespace jmax
| 24.450855
| 120
| 0.672289
|
JeanGamain
|
8ee690a8f8a24b61111ea21d5c0190700cbe681f
| 955
|
hpp
|
C++
|
include/cores/pdump_log.hpp
|
dotcom/QDPDK
|
9f430f9b0cef36228d14f763a023d0ff13f6a8a8
|
[
"MIT"
] | 1
|
2022-02-17T03:56:57.000Z
|
2022-02-17T03:56:57.000Z
|
include/cores/pdump_log.hpp
|
dotcom/QDPDK
|
9f430f9b0cef36228d14f763a023d0ff13f6a8a8
|
[
"MIT"
] | null | null | null |
include/cores/pdump_log.hpp
|
dotcom/QDPDK
|
9f430f9b0cef36228d14f763a023d0ff13f6a8a8
|
[
"MIT"
] | null | null | null |
#pragma once
#include "qdpdk.hpp"
#define BURST_SIZE 32
template<class FROM, class TO>
class CorePdumpLog{
protected:
QDPDK::DeqInterface<FROM> from;
QDPDK::EnqInterface<TO> to;
public:
CorePdumpLog(FROM deq, TO enq) : from(deq), to(enq){};
void FirstCycle(){}
void LastCycle(){}
void Cycle() {
rte_mbuf *bufs[BURST_SIZE];
int nb_rx = from.Dequeue((rte_mbuf **)bufs, BURST_SIZE);
if (unlikely(nb_rx == 0))
return;
for (int n = 0; n < nb_rx; n++){
int len = bufs[n]->data_len;
auto pkt = rte_pktmbuf_mtod(bufs[n], char*);
char str[ETHER_MAX_LEN*5] = "";
for (int i=0;i<len;i++){
sprintf(str, "%s 0x%02x", str, 0x000000ff & pkt[i]);
}
rte_log(RTE_LOG_INFO, RTE_LOGTYPE_USER3, "==== PDUMP LOG ==== %u\n %s\n", rte_lcore_id(), str);
}
to.Enqueue((rte_mbuf **)bufs, nb_rx);
}
};
| 27.285714
| 107
| 0.548691
|
dotcom
|
8eebfa9caf8a5e3d6fecfa5e877de0fd423374bd
| 224
|
cpp
|
C++
|
core/src/task/semaphore.cpp
|
ExaBerries/spruce
|
85845244f7d6cd5a662f0dbc9b4079a1230d9a4b
|
[
"MIT"
] | null | null | null |
core/src/task/semaphore.cpp
|
ExaBerries/spruce
|
85845244f7d6cd5a662f0dbc9b4079a1230d9a4b
|
[
"MIT"
] | null | null | null |
core/src/task/semaphore.cpp
|
ExaBerries/spruce
|
85845244f7d6cd5a662f0dbc9b4079a1230d9a4b
|
[
"MIT"
] | null | null | null |
#include <task/semaphore.h>
namespace spruce {
void semaphore::lock() noexcept {
locked = true;
}
void semaphore::unlock() noexcept {
locked = false;
}
void semaphore::wait() noexcept {
while (locked) {};
}
}
| 14
| 36
| 0.647321
|
ExaBerries
|
8ef370a2a057895eb2c6f29c4b72e2fbe7035c89
| 109
|
cpp
|
C++
|
src/add.cpp
|
JacknJo/JacksHome
|
b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2
|
[
"MIT"
] | null | null | null |
src/add.cpp
|
JacknJo/JacksHome
|
b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2
|
[
"MIT"
] | null | null | null |
src/add.cpp
|
JacknJo/JacksHome
|
b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2
|
[
"MIT"
] | null | null | null |
#include "add.hpp"
namespace jhm
{
add::add() = default;
add::~add() = default;
} // namespace jhm.
| 15.571429
| 26
| 0.577982
|
JacknJo
|
8ef5895790d79b560e252c6e6e7f40634ccff4a0
| 2,574
|
cpp
|
C++
|
01-dda-chessboard/DDA_Chessboard.cpp
|
ChetanaHegde/vtu-mca-sem3-cg
|
92667bef2b89726d6a272cd6425217257d47846d
|
[
"MIT"
] | 2
|
2020-10-08T10:36:40.000Z
|
2021-05-11T16:23:19.000Z
|
01-dda-chessboard/DDA_Chessboard.cpp
|
ChetanaHegde/vtu-mca-sem3-cg
|
92667bef2b89726d6a272cd6425217257d47846d
|
[
"MIT"
] | null | null | null |
01-dda-chessboard/DDA_Chessboard.cpp
|
ChetanaHegde/vtu-mca-sem3-cg
|
92667bef2b89726d6a272cd6425217257d47846d
|
[
"MIT"
] | 2
|
2017-01-25T13:43:09.000Z
|
2019-03-18T12:03:40.000Z
|
/* Program 1: Write a program to implement Chessboard using DDA Line drawing algorithm.
Coded by: Basavaraju R, Assistant Professor, RNSIT, Bangalore
Email: basavaraju dot revanna at gmail dot com
*/
#include<gl\glut.h>
#include<math.h>
GLint start_x=50,start_y=40,end_x=start_x+80,end_y=start_y+80;
void setPixel(GLint, GLint);
void init();
void display();
void lineDDA(GLint,GLint,GLint,GLint);
void fillRow(GLint,GLint,GLint,GLint,GLfloat);
void main(int argc, char** argv)
{
glutInit(&argc, argv); //initialize GLUT
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); //initialize display mode
glutInitWindowPosition(250,100); //set display-window upper-left position
glutInitWindowSize(600,500); //set display-window width & height
glutCreateWindow("Chess Board using DDA Line Algorithm"); //create display-window with a title
init(); //initialize window prpperties
glutDisplayFunc(display); //call graphics to be displayed on the window
glutMainLoop(); //display everything and wait
}
inline int round(const float a)
{
return int(a+0.5);
}
void setPixel(GLint xCoordinate, GLint yCoordinate)
{
glBegin(GL_POINTS);
glVertex2i(xCoordinate,yCoordinate);
glEnd();
glFlush(); //executes all OpenGL functions as quickly as possible
}
void init(void)
{
glClearColor(0.0,0.5,0.5,0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0,200.0,0.0,150.0);
}
//DDA line drawing procedure
void lineDDA(GLint x0,GLint y0, GLint xe, GLint ye)
{
GLint dx=xe-x0, dy=ye-y0, steps, k;
GLfloat xinc, yinc, x=x0, y=y0;
if(abs(dx)>abs(dy))
steps=abs(dx);
else
steps=abs(dy);
xinc=float(dx)/float(steps);
yinc=float(dy)/float(steps);
setPixel(round(x),round(y));
for(k=0;k<steps;k++)
{
x+=xinc;
y+=yinc;
setPixel(round(x), round(y));
}
}
//Function fills one row of chessbord with alternate black and white color
void fillRow(GLint x1,GLint y1,GLint x2,GLint y2,GLfloat c)
{
while(x1<end_x)
{
glColor3f(c,c,c);
glRecti(x1,y1,x2,y2);
x1=x2;
x2+=10;
if(c==0.0)
c=1.0;
else
c=0.0;
}
}
void display(void)
{
GLint i=0,a,b;
a=start_x;
b=start_y;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,0.0);
while(i<9)
{
lineDDA(a,start_y,a,end_y);
a+=10;
lineDDA(start_x,b,end_x,b);
b+=10;
i++;
}
GLint x1=start_x,y1=end_y,x2=start_x+10,y2=end_y-10;
GLfloat cl=0.0;
while(y1>start_y)
{
fillRow(x1,y1,x2,y2,cl);
if(cl==0.0)
cl=1.0;
else
cl=0.0;
y1=y2;
y2-=10;
}
glFlush();
}
| 22.578947
| 97
| 0.661616
|
ChetanaHegde
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.