hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b3424a83eaf1848544c4cb5edf861d35b17a92f2 | 38,140 | cpp | C++ | src/system.cpp | breudes/agree | 6ca352028b0ca53e460ac09d95dea60c766aed38 | [
"MIT"
] | null | null | null | src/system.cpp | breudes/agree | 6ca352028b0ca53e460ac09d95dea60c766aed38 | [
"MIT"
] | null | null | null | src/system.cpp | breudes/agree | 6ca352028b0ca53e460ac09d95dea60c766aed38 | [
"MIT"
] | null | null | null | #include "../include/system.h"
//Constructor
System::System(){
/** Default constructor of system. Enters all properties's values as null. The vectors doesn't require to be
* initialized.
*/
this->userLoggedId = 0;
this->currentServerName = "";
this->currentChannelName = "";
}
//Destructor
System::~System(){
/** Default destructor of system. Clears all string properties. The vectors doesn't require to be
* deleted.
*/
this->currentServerName.clear();
this->currentServerName.clear();
}
//Get System Users
std::vector<User> System::getSystemUsers(){
/** Returns this system users.
@return: an int vector.
*/
return this->users;
}
//Get System Servers
std::vector<Server> System::getSystemServers(){
/** Returns this system servers.
@return: an server vector.
*/
return this->servers;
}
//Get System User Logged Id
int System::getSystemUserLoggedId() const{
/** Returns this system an id of the current user logged.
@return: an int value.
*/
return this->userLoggedId;
}
//Get System Current Server Name
std::string System::getSystemServerCurrentName() const{
/** Returns this system a name of the current active server.
@return: a string value.
*/
return this->currentServerName;
}
//Get System Current Channel Name
std::string System::getSystemChannelCurrentName() const{
/** Returns this system a name of the current active channel.
@return: a string value.
*/
return this->currentChannelName;
}
//Set System Users
void System::setSystemUsers(std::vector<User> new_users){
/** Set a new int vector, with users's id, for this system's users.
@param new_users: int vector.
*/
this->users = new_users;
}
//Set System Servers
void System::setSystemServers(std::vector<Server> new_servers){
/** Set a new server vector for this system's servers.
@param new_servers: server vector.
*/
this->servers = new_servers;
}
//Set System User Logged Id
void System::setSystemUserLoggedId(int new_user_logged){
/** Set a new user logged for this system's (active) current user.
@param new_user_logged: int value of new user logged's id.
*/
this->userLoggedId = new_user_logged;
}
//Set System Current Server Name
void System::setSystemCurrentServerName(std::string server_name){
/** Set a new server name for this system's (active) current server.
@param server_name: string value of new current server's name.
*/
this->currentServerName = server_name;
}
//Set System Current Channel Name
void System::setSystemCurrentChannelName(std::string channel_name){
/** Set a new channel name for this system's (active) current channel.
@param channel_name: string value of new current channel's name.
*/
this->currentChannelName = channel_name;
}
//Search User By Id
int System::searchUserById(int id){
/** Returns 1 (one) if one user matches a given id. Otherwise, returns 0 (zero). Search on all users of Agree System.
@param id: int value of a given user's id;
@return: int value to return if this command was successful.
*/
std::vector<User> users_list = this->getSystemUsers();
for(size_t i=0; i<users_list.size(); i++){
if(users_list[i].getUserId() == id) return 1;
}
return 0;
}
//Search User By Email
int System::searchUserByEmail(std::string email){
/** Returns 1 (one) if one user matches a given email. Otherwise, returns 0 (zero). Search on all users of Agree System.
@param email: string value of a given user's email;
@return: int value to return if this command was successful.
*/
std::vector<User> users_list = this->getSystemUsers();
for(size_t i=0; i<users_list.size(); i++){
if(users_list[i].getUserEmail() == email) return 1;
}
return 0;
}
//Search Server By Name
int System::searchServerByName(std::string name){
/** Returns 1 (one) if one server matches a given name. Otherwise, returns 0 (zero). Search on all servers of Agree System.
@param name: string value of a given server's name;
@return: int value to return if this command was successful.
*/
std::vector<Server> servers_list = this->getSystemServers();
for(size_t i=0; i<servers_list.size(); i++){
if(servers_list[i].getServerName() == name) return 1;
}
return 0;
}
//Get User By Id
const User System::getUserById(int id){
/** Returns an user object if user's id matches the given id. Otherwise, will return the first element
* of users's vector (on Agree System).
@param id: int value of a given id;
@return: a const user object.
*/
std::vector<User> users_list = this->getSystemUsers();
for(size_t i=0; i<users_list.size(); i++){
if(users_list[i].getUserId() == id) return users_list[i];
}
return users_list[0];
}
//Get User By Password
const User System::getUserByPassword(std::string password){
/** Returns an user object if user's password matches the given password. Otherwise, will return the first element
* of users's vector (on Agree System).
@param password: string value of a given password;
@return: a const user object.
*/
std::vector<User> users_list = this->getSystemUsers();
for(size_t i=0; i<users_list.size(); i++){
if(users_list[i].getUserPassword() == password) return users_list[i];
}
return users_list[0];
}
//Updates Server Description
int System::updatesServerDescription(std::string server_name, std::string description){
/** Updates a given server's description. This is only possible if the current logged user is also the owner of
* this given server.
@param server_name: string value of a given server's name;
@param description: string value of a given server's new description;
@return: int value to return if this command was successful.
*/
for(size_t i=0; i<this->getSystemServers().size(); i++){
if(this->getSystemServers()[i].getServerName() == server_name){
if(this->getSystemServers()[i].getServerOwnerId()==this->getSystemUserLoggedId()){
this->servers[i].setServerDescription(description);
return 1;
}else{
std::cout << "You cannot change another user's server description!\n" << std::endl;
return 0;
}
}
}
return 0;
}
//Updates Server Invite Code
int System::updatesServerInviteCode(std::string server_name, std::string invite_code){
/** Updates a given server's invite code. This is only possible if the current logged user is also the owner of
* this given server.
@param server_name: string value of a given server's name;
@param invite_code: string value of a given server's new invite code;
@return: int value to return if this command was successful.
*/
for(size_t i=0; i<this->getSystemServers().size(); i++){
if(this->getSystemServers()[i].getServerName() == server_name){
if(this->getSystemServers()[i].getServerOwnerId()==this->getSystemUserLoggedId()){
this->servers[i].setServerInviteCode(invite_code);
if(invite_code==""){
std::cout << "Removed '" << server_name << "' server invitation code!\n" << std::endl;
}else std::cout << "Modified '" << server_name << "' server invitation code!\n" << std::endl;
return 1;
}else{
std::cout << "You cannot change another user's server invite code!\n" << std::endl;
return 0;
}
}
}
return 0;
}
//Removes Server
int System::removesServer(std::string server_name){
/** Removes a given server using its name. This is only possible if the current logged user is also the owner of
* this given server.
@param server_name: string value of a given server's name;
@return: int value to return if this command was successful.
*/
for(auto index=this->servers.begin(); index!=this->servers.end(); ++index){
if((*index).getServerName() == server_name){
if((*index).getServerOwnerId()==this->getSystemUserLoggedId()){
this->servers.erase(index);
this->setSystemCurrentServerName("");
std::cout << "Removed '" << server_name << "' server!\n" << std::endl;
return 1;
}else{
std::cout << "You are not the owner of the '" << server_name << "' server!\n" << std::endl;
return 0;
}
}
}
return 0;
}
//Enters Server
int System::entersServer(std::string server_name, std::string invite_code){
/** The current logged user on Agree System will enter a server, by using its name and invite code.
@param server_name: string value of chosen server's name;
@param invite_code: string value of chosen server's invite code;
@return: int value to return if this command was successful.
*/
for(size_t i=0; i<this->getSystemServers().size(); i++){
if(this->getSystemServers()[i].getServerName() == server_name){
if(this->getSystemServers()[i].getServerInviteCode()==""){
int result = 0;
result = this->servers[i].getServerOneMemberId(this->getSystemUserLoggedId());
std::cout << "This is an open server!" << std::endl;
std::cout << "Entering '" << server_name << "' server!\n" << std::endl;
if(result==1){
this->setSystemCurrentServerName(server_name);
}else if(result==0){
this->servers[i].setServerOneMemberId(this->getSystemUserLoggedId());
this->setSystemCurrentServerName(server_name);
}
return 1;
}else{
std::cout << "This is a closed server. You need an invite code to enter!\n" << std::endl;
if(this->getSystemServers()[i].getServerInviteCode()==invite_code){
int result = 0;
result = this->servers[i].getServerOneMemberId(this->getSystemUserLoggedId());
std::cout << "Entering '" << server_name << "' server!\n" << std::endl;
if(result==1){
this->setSystemCurrentServerName(server_name);
}else if(result==0){
this->servers[i].setServerOneMemberId(this->getSystemUserLoggedId());
this->setSystemCurrentServerName(server_name);
}
return 1;
}else std::cout << "Invalid invite code for this server. You can try again!\n" << std::endl;
}
}
}
return 0;
}
//Return Server By Name
const Server System::returnServerByName(std::string server_name){
/** Returns a server object if its name was equal to a giver string name. Otherwise, will return the first element of servers vector.
@param server_name: string value of given name;
@return: a const server's object.
*/
for(size_t i=0; i<this->getSystemServers().size(); i++){
if(this->getSystemServers()[i].getServerName() == server_name){
return this->getSystemServers()[i];
}
}
return this->getSystemServers()[0];
}
//Quit
void System::quit(){
/** This stops the execution of Agree System.
*/
std::cout << "You're logging off from Agree System. Goodbye!\n" << std::endl;
}
//Create User
void System::createUser(User user){
/** Creates a new user on Agree System, this user is not logged on system, only will be logged if press command login,
* with all required info.
@param user: an user class's object.
*/
int searchUserEmail = this->searchUserByEmail(user.getUserEmail());
if(searchUserEmail == 0){
this->users.push_back(user);
std::cout << "Created user!\n" << std::endl;
} else std::cout << "User already exists!\n" << std::endl;
}
//Login
void System::login(std::string email, std::string password){
/** Enters a user on Agree System by a given email and password. If this user exists, it'll now logged on Agree.
@param email: string value of user's email;
@param password: string value of user's password.
*/
int searchUserEmail = this->searchUserByEmail(email);
if(searchUserEmail == 1){
const User searchUserPassword = getUserByPassword(password);
if(searchUserPassword.getUserPassword()==password){
this->setSystemUserLoggedId(searchUserPassword.getUserId());
std::cout << "You're now logged as '" << email << "' on Agree System!\n" << std::endl;
}else std::cout << "Invalid user's password!\n" << std::endl;
} else std::cout << "User not found. You can try again!\n" << std::endl;
}
//Disconnect
void System::disconnect(){
/** Disconnect the current user logged on Agree System.
*/
if(this->getSystemUserLoggedId()!=0){
std::cout << "Disconnecting user " << this->getUserById(this->getSystemUserLoggedId()).getUserEmail() << "\n";
this->setSystemUserLoggedId(0);
}else{
std::cout << "Not connected!\n" << std::endl;
}
std::cout << "Note that Agree System is still on!\n" << std::endl;
}
//Create Server
void System::createServer(std::string server_name){
/** Creates a new server, considering a given name. And this new server has the current logged user as its owner.
@param server_name: string value of a given name.
*/
int searchServerName = this->searchServerByName(server_name);
if(this->getSystemUserLoggedId()!=0){
if(searchServerName == 0){
Server new_server;
new_server.setServerName(server_name);
new_server.setServerOwnerId(this->getSystemUserLoggedId());
new_server.setServerOneMemberId(this->getSystemUserLoggedId());
this->servers.push_back(new_server);
std::cout << "Created server!\n" << std::endl;
} else std::cout << "Server already exists with this name!\n" << std::endl;
}else std::cout << "Enter with an user before create a server!" << std::endl;
}
//Update Server Description
void System::updateServerDescription(std::string server_name, std::string new_server_description){
/** Updates a given server's description. Only if the logged user is also the owner of this server.
@param server_name: a given server's name;
@param new_server_description: a new description for given server.
*/
if(this->getSystemUserLoggedId()!=0){
int searchServerName = this->searchServerByName(server_name);
if(searchServerName == 1){
int result = this->updatesServerDescription(server_name,new_server_description);
if(result==1) std::cout << "Modified '" << server_name << "' server description!\n" << std::endl;
} else std::cout << "Server not found! You can try again!\n" << std::endl;
}else std::cout << "Log with an user before create a server!" << std::endl;
}
//Update Server Invite
void System::updateServerInvite(std::string server_name, std::string invite){
/** Updates a given server's invite code. Only if the logged user is also the owner of this server.
@param server_name: a given server's name;
@param invite: a new invite code for given server.
*/
if(this->getSystemUserLoggedId()!=0){
int searchServerName = this->searchServerByName(server_name);
if(searchServerName == 1){
this->updatesServerInviteCode(server_name,invite);
} else std::cout << "Server not found! You can try again!\n" << std::endl;
}else std::cout << "Log with an user before create a server!" << std::endl;
}
//List Servers
void System::listServers(){
/** List all servers's name on Agree System.
*/
std::vector<Server> servers_list = this->getSystemServers();
std::cout << "List of all servers on Agree System: " << std::endl;
for(size_t i=0; i<servers_list.size(); i++){
std::cout << servers_list[i].getServerName() << std::endl;
}
std::cout << "\n";
}
//Remove Server
void System::removeServer(std::string server_name){
/** The logged user removes a server, i.e., on Agree System the current active server is now empty.
* This is only possible if the user is the owner of a given server, passed as input by its name.
@param server_name: given server's name.
*/
if(this->getSystemUserLoggedId()!=0){
int searchServerName = this->searchServerByName(server_name);
if(searchServerName == 1){
this->removesServer(server_name);
} else std::cout << "Server not found! You can try again!\n" << std::endl;
}else std::cout << "You had to be logged on Agree System to remove a server of yours!" << std::endl;
}
//Enter Server
void System::enterServer(std::string server_name, std::string invite_code){
/** The logged user enters a given server, i.e., on Agree System the current active server is now this server.
* This is only possible if the user enters the server name and the invite code (if the server is a closed one).
@param server_name: given server's name;
@param invite_code: given server's invite code.
*/
if(this->getSystemUserLoggedId()!=0){
int searchServerName = this->searchServerByName(server_name);
if(searchServerName == 1){
this->entersServer(server_name, invite_code);
this->setSystemCurrentServerName(server_name);
} else std::cout << "Server not found! You can try again!\n" << std::endl;
}else std::cout << "You had to be logged on Agree System to enter a server!" << std::endl;
}
//Leave Server
void System::leaveServer(){
/** The logged user leaves a server, i.e., on Agree System the current active server is now empty.
*/
if(this->getSystemUserLoggedId()!=0){
int searchServerName = this->searchServerByName(this->getSystemServerCurrentName());
if(searchServerName == 1){
std::cout << "Leaving '" << this->getSystemServerCurrentName() << "' server!\n" << std::endl;
this->setSystemCurrentServerName("");
} else std::cout << "Server not found! You can try again!\n" << std::endl;
}else std::cout << "You had to be logged on Agree System and to on server, to leave this server!" << std::endl;
}
//List Server Members
void System::listServerMembers(){
/** Displays all members of the current active server on Agree System.
*/
if(this->getSystemServerCurrentName()!=""){
const Server aux_server = this->returnServerByName(this->getSystemServerCurrentName());
std::cout << "List of all members on server '" << aux_server.getServerName() << "': " << std::endl;
for(size_t i=0; i<aux_server.getServerMembersId().size(); i++){
const User aux_user = this->getUserById(aux_server.getServerMembersId()[i]);
std::cout << aux_user.getUserName() << std::endl;
}
std::cout << "\n";
}else{
std::cout << "You have to log on a server first!\n\n";
return;
}
}
//List Server Channels
void System::listServerChannels(){
if(this->getSystemServerCurrentName()==""){
std::cout << "You have to log on a server before creates a channel on it!\n" << std::endl;
return;
}
std::cout << "List of channels on the current server '" << this->getSystemServerCurrentName() << "'"<< std::endl;
for(size_t i=0; i<this->servers.size(); i++){
if(this->servers[i].getServerName() == this->getSystemServerCurrentName()){
for(size_t j=0; j<this->servers[i].getServerChannels().size(); j++){
std::cout << this->servers[i].getServerChannels()[j]->getChannelName() << std::endl;
}
}
}
std::cout << "\n\n" << std::endl;
}
//Create Server Channel
void System::createServerChannel(std::string name, std::string type){
/** Creates a new channel for the current active server on Agree System.
@param name: string value for the new channel's name;
@param type: string value for the new channel's type;
*/
if(this->getSystemServerCurrentName()=="" && this->getSystemUserLoggedId()==0){
std::cout << "You have to log on Agree System and log on a server before creates a channel on it!\n" << std::endl;
return;
}
std::vector<Server>::iterator server_iterator;
std::string current_server = this->getSystemServerCurrentName();
server_iterator = std::find_if(this->servers.begin(), this->servers.end(), [current_server](Server server) {
return current_server == server.getServerName();
});
if(server_iterator!=this->servers.end()){
int result = server_iterator->checkChannelExists(name,type);
if(result==0){
Channel *new_channel;
if(type=="voice"){
new_channel = new VoiceChannel();
new_channel->setChannelName(name);
new_channel->setChannelType(type);
server_iterator->addChannel(new_channel);
std::cout << "A voice channel '"<< name << "' created on this server!\n" << std::endl;
}else if(type=="text"){
new_channel = new TextChannel();
new_channel->setChannelName(name);
new_channel->setChannelType(type);
server_iterator->addChannel(new_channel);
std::cout << "A text channel '"<< name << "' created on this server!\n" << std::endl;
}
}else{
std::cout << "A text channel '"<< name << "' already exists on this server!\n" << std::endl;
return;
}
}
}
//Enter Server Channel
void System::enterServerChannel(std::string name){
/** Enters the current active user on an channel of current active server on Agree System.
@param name: string value for the channel's name that user will enters to.
*/
if(this->getSystemServerCurrentName()==""){
std::cout << "You have to log on a server before enters a channel on it!\n" << std::endl;
return;
}
for(size_t i=0; i<this->servers.size(); i++){
if(this->servers[i].getServerName() == this->getSystemServerCurrentName() && this->getSystemUserLoggedId() != 0){
int result = this->servers[i].checkChannelExists(name,"");
if(result) {
this->setSystemCurrentChannelName(name);
std::cout << "Entered the channel '"<< name << "' !\n" << std::endl;
}else{
std::cout << "Channel '"<< name << "' was not found on this server!\n" << std::endl;
}
}
}
}
//Leave Server Channel
void System::leaveServerChannel(){
/** Execute the 'leave-channel' command, i.e., set this system current active channel name to an empty string.
*/
if(this->getSystemServerCurrentName()==""){
std::cout << "You have to log on a server before leaves a channel on it!\n" << std::endl;
return;
}
if(this->getSystemChannelCurrentName()==""){
std::cout << "You have to log on a channel before leaves it!\n" << std::endl;
return;
}
std::cout << "Leaving channel '" << this->getSystemChannelCurrentName() << "' of server '" << this->getSystemServerCurrentName() << "'" << std::endl;
this->setSystemCurrentChannelName("");
}
//Send Message
void System::sendMessage(std::string content){
/** Send a message on the current active channel, its content is passed by user input.
@param content: string value for message's content.
*/
if(this->getSystemServerCurrentName()=="" && this->getSystemUserLoggedId()==0){
std::cout << "You have to log on a server before sends a message!\n" << std::endl;
return;
}
if(this->getSystemChannelCurrentName()==""){
std::cout << "You have to log on a channel before sends a message!\n" << std::endl;
return;
}
char date[100];
time_t s = time(nullptr);
strftime(date, 50, "%m/%d/%Y - %R", localtime(&s));
Message new_message = Message(date,this->getSystemUserLoggedId(),content);
std::vector<Server>::iterator server_iterator;
std::string current_server = this->getSystemServerCurrentName();
std::string current_channel = this->getSystemChannelCurrentName();
server_iterator = std::find_if(this->servers.begin(), this->servers.end(), [current_server](Server server) {
return server.getServerName()==current_server;
});
if(server_iterator!=this->servers.end()){
for(size_t i=0; i<server_iterator->getServerChannels().size(); i++){
if(server_iterator->getServerChannels()[i]->getChannelName()==current_channel){
if(server_iterator->getServerChannels()[i]->getChannelType()=="voice"){
server_iterator->getServerChannels()[i]->setVoiceChannelLastMessage(new_message);
}else if(server_iterator->getServerChannels()[i]->getChannelType()=="text"){
server_iterator->getServerChannels()[i]->addMessage(new_message);
}
std::cout << "Message sended.\n\n";
}
}
}else{
std::cout << "Server not found!\n\n";
return;
}
}
//Display All Messages
void System::displayAllMessages(){
/** Displays all messagens on the current active channel.
*/
if(this->getSystemServerCurrentName()=="" && this->getSystemUserLoggedId()==0){
std::cout << "You have to log on a server before creates a channel on it!\n" << std::endl;
return;
}
if(this->getSystemChannelCurrentName()==""){
std::cout << "You have to log on a channel before leaves it!\n" << std::endl;
return;
}
std::vector<Server>::iterator server_iterator;
std::string current_server = this->getSystemServerCurrentName();
std::string current_channel = this->getSystemChannelCurrentName();
server_iterator = std::find_if(this->servers.begin(), this->servers.end(), [current_server](Server server) {
return server.getServerName()==current_server;
});
if(server_iterator!=this->servers.end()){
for(size_t i=0; i<server_iterator->getServerChannels().size(); i++){
if(server_iterator->getServerChannels()[i]->getChannelName()==current_channel){
if(server_iterator->getServerChannels()[i]->getChannelType()=="voice"){
int user_id = server_iterator->getServerChannels()[i]->getVoiceChannelLastMessage().getMessageSender();
std::string message_date = server_iterator->getServerChannels()[i]->getVoiceChannelLastMessage().getMessageDate();
std::string message_content = server_iterator->getServerChannels()[i]->getVoiceChannelLastMessage().getMessageContent();
const User new_user = this->getUserById(user_id);
if(message_content!=""){
std::cout << "\n" << new_user.getUserName() << "<" << message_date << ">:" << message_content << std::endl;
}else std::cout << "There is no message to display.\n" << std::endl;
}else if(server_iterator->getServerChannels()[i]->getChannelType()=="text"){
for(size_t j=0; j<server_iterator->getServerChannels()[i]->getTextChannelMessages().size(); j++){
int user_id = server_iterator->getServerChannels()[i]->getTextChannelMessages()[j].getMessageSender();
std::string message_date = server_iterator->getServerChannels()[i]->getTextChannelMessages()[j].getMessageDate();
std::string message_content = server_iterator->getServerChannels()[i]->getTextChannelMessages()[j].getMessageContent();
const User new_user = this->getUserById(user_id);
std::cout << new_user.getUserName() << "\n" << "<" << message_date << ">:" << message_content << std::endl;
}
}
}
}
}else{
std::cout << "Server not found!\n\n";
return;
}
}
//Save
void System::save(std::string option){
if(option=="users"){
this->saveUsers();
}else if(option=="servers"){
this->saveServers();
}else{
std::cout << "\n\nInvalid option";
return;
}
}
//Save Users
void System::saveUsers(){
/** This function saves all users created on Agree System.
*/
std::ofstream users("./src/txt/data/users.txt");
if(!users){
std::cout << "\nFile was not open";
exit(1);
}else{
users << this->getSystemUsers().size() << std::endl;
for(size_t i=0; i<this->getSystemUsers().size(); i++){
users << this->getSystemUsers()[i].getUserId() << std::endl;
users << this->getSystemUsers()[i].getUserName() << std::endl;
users << this->getSystemUsers()[i].getUserEmail() << std::endl;
users << this->getSystemUsers()[i].getUserPassword() << std::endl;
}
users.close();
}
}
//Save Servers
void System::saveServers(){
/** This function saves all servers created on Agree System.
*/
std::ofstream servers("./src/txt/data/servers.txt");
if(!servers){
std::cout << "\nFile was not open";
exit(1);
}else{
servers << this->servers.size() << std::endl;
for(auto it_server = this->servers.begin(); it_server!=this->servers.end(); it_server++){
servers << it_server->getServerOwnerId() << std::endl;
servers << it_server->getServerName() << std::endl;
servers << it_server->getServerDescription() << std::endl;
servers << it_server->getServerInviteCode() << std::endl;
servers << it_server->getServerMembersId().size() << std::endl;
for(size_t member = 0; member< it_server->getServerMembersId().size(); member++){
servers << it_server->getServerMembersId()[member] << std::endl;
}
servers << it_server->getServerChannels().size() << std::endl;
for(size_t i=0; i<it_server->getServerChannels().size(); i++){
servers << it_server->getServerChannels()[i]->getChannelName() << std::endl;
servers << it_server->getServerChannels()[i]->getChannelType() << std::endl;
if(it_server->getServerChannels()[i]->getChannelType() == "voice"){
servers << "1" << std::endl;
servers << it_server->getServerChannels()[i]->getVoiceChannelLastMessage().getMessageSender() << std::endl;
servers << it_server->getServerChannels()[i]->getVoiceChannelLastMessage().getMessageDate() << std::endl;
servers << it_server->getServerChannels()[i]->getVoiceChannelLastMessage().getMessageContent() << std::endl;
}else if(it_server->getServerChannels()[i]->getChannelType() == "text"){
servers << it_server->getServerChannels()[i]->getTextChannelMessages().size() << std::endl;
for(size_t j=0; j<it_server->getServerChannels()[i]->getTextChannelMessages().size(); j++){
servers << it_server->getServerChannels()[i]->getTextChannelMessages()[j].getMessageSender() << std::endl;
servers << it_server->getServerChannels()[i]->getTextChannelMessages()[j].getMessageDate() << std::endl;
servers << it_server->getServerChannels()[i]->getTextChannelMessages()[j].getMessageContent() << std::endl;
}
}
}
}
servers.close();
}
}
//Load
void System::load(){
/** Load all data from users and servers on this Agree System.
*/
//this->loadUsers();
this->loadServers();
}
//Load Users
void System::loadUsers(){
/** Load all data from users on this Agree System.
*/
std::ifstream usersLoadFile("./src/txt/data/users.txt");
if (!usersLoadFile) {
std::cout << "\nFile was not open";
exit(1);
} else {
std::string size;
std::string id_user, name_user, email_user, password_user;
usersLoadFile >> size;
size_t users_size = std::stoi(size);
usersLoadFile.ignore();
for (size_t i = 0; i < users_size ; ++i) {
std::getline(usersLoadFile, id_user);
std::getline(usersLoadFile, name_user);
std::getline(usersLoadFile, email_user);
std::getline(usersLoadFile, password_user);
int new_id = std::stoi(id_user);
auto iterator_user = find_if(this->users.begin(), this->users.end(), [new_id](User user) {
return new_id == user.getUserId();
});
if(iterator_user==this->users.end()){
User new_user = User();
new_user.setUserId(new_id);
new_user.setUserName(name_user);
new_user.setUserEmail(email_user);
new_user.setUserPassword(password_user);
this->users.push_back(new_user);
}
}
usersLoadFile.close();
}
}
//Load Servers
void System::loadServers(){
/** Load all data from servers on this Agree System.
*/
std::ifstream serversLoadFile("./src/txt/data/servers.txt");
if (!serversLoadFile) {
std::cout << "\nFile was not open";
exit(1);
} else {
std::string size;
std::string owner_server, name_server, desc_server, invite_server;
serversLoadFile >> size;
size_t servers_size = std::stoi(size);
serversLoadFile.ignore();
Server new_server = Server();
for (size_t i = 0; i < servers_size ; ++i) {
std::getline(serversLoadFile,owner_server);
std::getline(serversLoadFile,name_server);
std::getline(serversLoadFile,desc_server);
std::getline(serversLoadFile,invite_server);
int owner_id = std::stoi(owner_server);
auto iterator_server = find_if(this->servers.begin(), this->servers.end(), [owner_id](Server server) {
return owner_id == server.getServerOwnerId();
});
if(iterator_server==this->servers.end()){
new_server.setServerOwnerId(owner_id);
new_server.setServerName(name_server);
new_server.setServerDescription(desc_server);
new_server.setServerInviteCode(invite_server);
//Length of members's vector and its id (as integer)
std::string user_size;
std::string user_id;
user_size.clear();
std::getline(serversLoadFile,user_size);
size_t users_size = std::stoi(user_size);
for (size_t j=0; j<users_size; ++j){
std::getline(serversLoadFile,user_id);
int user = std::stoi(user_id);
new_server.setServerOneMemberId(user);
}
//Length of channels's vector and its info
std::string channel_size;
std::getline(serversLoadFile,channel_size);
size_t channels_size = std::stoi(channel_size);
std::string name_channel, type_channel, message_size;
std::string m_sender,m_date,m_content;
for (size_t k=0; k<channels_size; ++k) {
std::getline(serversLoadFile,name_channel);
std::getline(serversLoadFile,type_channel);
Channel* new_channel;
if(type_channel=="voice"){
new_channel = new VoiceChannel();
new_channel->setChannelName(name_channel);
//get voice channel message
std::getline(serversLoadFile,message_size);
std::getline(serversLoadFile,m_sender);
std::getline(serversLoadFile,m_date);
std::getline(serversLoadFile,m_content);
int sender = std::stoi(m_sender);
//create and set new message from this voice channel
Message new_message = Message(m_date,sender,m_content);
new_channel->setVoiceChannelLastMessage(new_message);
}else if(type_channel=="text"){
new_channel = new TextChannel();
new_channel->setChannelName(name_channel);
//get text channel messages
std::getline(serversLoadFile,message_size);
size_t m_size = std::stoi(message_size);
//create and set new messages from this text channel
for (size_t m=0; m<m_size; ++m){
//get voice channel message
std::getline(serversLoadFile,m_sender);
std::getline(serversLoadFile,m_date);
std::getline(serversLoadFile,m_content);
int sender = std::stoi(m_sender);
Message new_message = Message(m_date,sender,m_content);
new_channel->addMessage(new_message);
}
}
new_server.addChannel(new_channel);
}
//Add new server on Agree System
this->servers.push_back(new_server);
}else std::cout << "\nServer already exists on Agree System!\n";
}
serversLoadFile.close();
}
} | 45.676647 | 153 | 0.604824 | [
"object",
"vector"
] |
b345418cb563cae408d488b4f76b011c6e5ad3be | 13,330 | cpp | C++ | src/util/dataAccess.cpp | balint42/nix | 50f1de33b946b7b194c82fb0efd9b0cecba9ed54 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/util/dataAccess.cpp | balint42/nix | 50f1de33b946b7b194c82fb0efd9b0cecba9ed54 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/util/dataAccess.cpp | balint42/nix | 50f1de33b946b7b194c82fb0efd9b0cecba9ed54 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/util/dataAccess.hpp>
#include <nix/util/util.hpp>
#include <string>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <boost/optional.hpp>
using namespace std;
namespace nix {
namespace util {
int positionToIndex(double position, const string &unit, const Dimension &dimension) {
size_t pos;
if (dimension.dimensionType() == nix::DimensionType::Sample) {
SampledDimension dim;
dim = dimension;
pos = positionToIndex(position, unit, dim);
} else if (dimension.dimensionType() == nix::DimensionType::Set) {
SetDimension dim;
dim = dimension;
pos = positionToIndex(position, unit, dim);
} else {
RangeDimension dim;
dim = dimension;
pos = positionToIndex(position, unit, dim);
}
return static_cast<int>(pos); //FIXME: int, really?
}
size_t positionToIndex(double position, const string &unit, const SampledDimension &dimension) {
size_t index;
boost::optional<string> dim_unit = dimension.unit();
double scaling = 1.0;
if (!dim_unit && unit != "none") {
throw nix::IncompatibleDimensions("Units of position and SampledDimension must both be given!", "nix::util::positionToIndex");
}
if (dim_unit && unit != "none") {
try {
scaling = util::getSIScaling(unit, *dim_unit);
} catch (...) {
throw nix::IncompatibleDimensions("Cannot apply a position with unit to a SetDimension", "nix::util::positionToIndex");
}
}
index = dimension.indexOf(position * scaling);
return index;
}
size_t positionToIndex(double position, const string &unit, const SetDimension &dimension) {
size_t index;
index = static_cast<size_t>(round(position));
if (unit.length() > 0 && unit != "none") {
throw nix::IncompatibleDimensions("Cannot apply a position with unit to a SetDimension", "nix::util::positionToIndex");
}
if (dimension.labels().size() > 0 && index > dimension.labels().size()) {
throw nix::OutOfBounds("Position is out of bounds in setDimension.", static_cast<int>(position));
}
return index;
}
size_t positionToIndex(double position, const string &unit, const RangeDimension &dimension) {
boost::optional<string> dim_unit = dimension.unit();
double scaling = 1.0;
if (dim_unit && unit != "none") {
try {
scaling = util::getSIScaling(unit, *dim_unit);
} catch (...) {
throw nix::IncompatibleDimensions("Provided units are not scalable!", "nix::util::positionToIndex");
}
}
return dimension.indexOf(position * scaling);
}
void getOffsetAndCount(const Tag &tag, const DataArray &array, NDSize &offset, NDSize &count) {
vector<double> position = tag.position();
vector<double> extent = tag.extent();
vector<string> units = tag.units();
NDSize temp_offset(position.size());
NDSize temp_count(position.size(), 1);
if (array.dimensionCount() != position.size() || (extent.size() > 0 && extent.size() != array.dimensionCount())) {
throw std::runtime_error("Dimensionality of position or extent vector does not match dimensionality of data!");
}
for (size_t i = 0; i < position.size(); ++i) {
Dimension dim = array.getDimension(i+1);
temp_offset[i] = positionToIndex(position[i], i >= units.size() ? "none" : units[i], dim);
if (i < extent.size()) {
ndsize_t c = positionToIndex(position[i] + extent[i], i >= units.size() ? "none" : units[i], dim) - temp_offset[i];
temp_count[i] = (c > 1) ? c : 1;
}
}
offset = temp_offset;
count = temp_count;
}
void getOffsetAndCount(const MultiTag &tag, const DataArray &array, size_t index, NDSize &offsets, NDSize &counts) {
DataArray positions = tag.positions();
DataArray extents = tag.extents();
NDSize position_size, extent_size;
size_t dimension_count = array.dimensionCount();
if (positions) {
position_size = positions.dataExtent();
}
if (extents) {
extent_size = extents.dataExtent();
}
if (!positions || index >= position_size[0]) {
throw nix::OutOfBounds("Index out of bounds of positions!", 0);
}
if (extents && index >= extent_size[0]) {
throw nix::OutOfBounds("Index out of bounds of positions or extents!", 0);
}
if (position_size.size() == 1 && dimension_count != 1) {
throw nix::IncompatibleDimensions("Number of dimensions in positions does not match dimensionality of data",
"util::getOffsetAndCount");
}
if (position_size.size() > 1 && position_size[1] > dimension_count) {
throw nix::IncompatibleDimensions("Number of dimensions in positions does not match dimensionality of data",
"util::getOffsetAndCount");
}
if (extents && extent_size.size() > 1 && extent_size[1] > dimension_count) {
throw nix::IncompatibleDimensions("Number of dimensions in extents does not match dimensionality of data",
"util::getOffsetAndCount");
}
NDSize temp_offset = NDSize{static_cast<NDSize::value_type>(index), static_cast<NDSize::value_type>(0)};
NDSize temp_count{static_cast<NDSize::value_type>(1), static_cast<NDSize::value_type>(dimension_count)};
vector<double> offset;
positions.getData(offset, temp_count, temp_offset);
NDSize data_offset(dimension_count, static_cast<size_t>(0));
NDSize data_count(dimension_count, static_cast<size_t>(1));
vector<string> units = tag.units();
for (size_t i = 0; i < offset.size(); ++i) {
Dimension dimension = array.getDimension(i+1);
string unit = "none";
if (i <= units.size() && units.size() > 0) {
unit = units[i];
}
data_offset[i] = positionToIndex(offset[i], unit, dimension);
}
if (extents) {
vector<double> extent;
extents.getData(extent, temp_count, temp_offset);
for (size_t i = 0; i < extent.size(); ++i) {
Dimension dimension = array.getDimension(i+1);
string unit = "none";
if (i <= units.size() && units.size() > 0) {
unit = units[i];
}
ndsize_t c = positionToIndex(offset[i] + extent[i], unit, dimension) - data_offset[i];
data_count[i] = (c > 1) ? c : 1;
}
}
offsets = data_offset;
counts = data_count;
}
bool positionInData(const DataArray &data, const NDSize &position) {
NDSize data_size = data.dataExtent();
bool valid = true;
if (!(data_size.size() == position.size())) {
return false;
}
for (size_t i = 0; i < data_size.size(); i++) {
valid &= position[i] < data_size[i];
}
return valid;
}
bool positionAndExtentInData(const DataArray &data, const NDSize &position, const NDSize &count) {
NDSize pos = position + count;
pos -= 1;
return positionInData(data, pos);
}
DataView retrieveData(const MultiTag &tag, size_t position_index, size_t reference_index) {
DataArray positions = tag.positions();
DataArray extents = tag.extents();
vector<DataArray> refs = tag.references();
if (refs.size() == 0) {
throw nix::OutOfBounds("There are no references in this tag!", 0);
}
if (position_index >= positions.dataExtent()[0] ||
(extents && position_index >= extents.dataExtent()[0])) {
throw nix::OutOfBounds("Index out of bounds of positions or extents!", 0);
}
if (!(reference_index < tag.referenceCount())) {
throw nix::OutOfBounds("Reference index out of bounds.", 0);
}
size_t dimension_count = refs[reference_index].dimensionCount();
if (positions.dataExtent().size() == 1 && dimension_count != 1) {
throw nix::IncompatibleDimensions("Number of dimensions in position or extent do not match dimensionality of data",
"util::retrieveData");
} else if (positions.dataExtent().size() > 1) {
if (positions.dataExtent()[1] > dimension_count ||
(extents && extents.dataExtent()[1] > dimension_count)) {
throw nix::IncompatibleDimensions("Number of dimensions in position or extent do not match dimensionality of data",
"util::retrieveData");
}
}
NDSize offset, count;
getOffsetAndCount(tag, refs[reference_index], position_index, offset, count);
if (!positionAndExtentInData(refs[reference_index], offset, count)) {
throw nix::OutOfBounds("References data slice out of the extent of the DataArray!", 0);
}
DataView io = DataView(refs[reference_index], count, offset);
return io;
}
DataView retrieveData(const Tag &tag, size_t reference_index) {
vector<double> positions = tag.position();
vector<double> extents = tag.extent();
vector<DataArray> refs = tag.references();
if (refs.size() == 0) {
throw nix::OutOfBounds("There are no references in this tag!", 0);
}
if (!(reference_index < tag.referenceCount())) {
throw nix::OutOfBounds("Reference index out of bounds.", 0);
}
size_t dimension_count = refs[reference_index].dimensionCount();
if (positions.size() != dimension_count || (extents.size() > 0 && extents.size() != dimension_count)) {
throw nix::IncompatibleDimensions("Number of dimensions in position or extent do not match dimensionality of data","util::retrieveData");
}
NDSize offset, count;
getOffsetAndCount(tag, refs[reference_index], offset, count);
if (!positionAndExtentInData(refs[reference_index], offset, count)) {
throw nix::OutOfBounds("Referenced data slice out of the extent of the DataArray!", 0);
}
DataView io = DataView(refs[reference_index], count, offset);
return io;
}
DataView retrieveFeatureData(const Tag &tag, size_t feature_index) {
if (tag.featureCount() == 0) {
throw nix::OutOfBounds("There are no features associated with this tag!", 0);
}
if (feature_index > tag.featureCount()) {
throw nix::OutOfBounds("Feature index out of bounds.", 0);
}
Feature feat = tag.getFeature(feature_index);
DataArray data = feat.data();
if (data == nix::none) {
throw nix::UninitializedEntity();
//return NDArray(nix::DataType::Float,{0});
}
if (feat.linkType() == nix::LinkType::Tagged) {
NDSize offset, count;
getOffsetAndCount(tag, data, offset, count);
if (!positionAndExtentInData(data, offset, count)) {
throw nix::OutOfBounds("Requested data slice out of the extent of the Feature!", 0);
}
DataView io = DataView(data, count, offset);
return io;
}
// for untagged and indexed return the full data
NDSize offset(data.dataExtent().size(), 0);
DataView io = DataView(data, data.dataExtent(), offset);
return io;
}
DataView retrieveFeatureData(const MultiTag &tag, size_t position_index, size_t feature_index) {
if (tag.featureCount() == 0) {
throw nix::OutOfBounds("There are no features associated with this tag!", 0);
}
if (feature_index >= tag.featureCount()) {
throw nix::OutOfBounds("Feature index out of bounds.", 0);
}
Feature feat = tag.getFeature(feature_index);
DataArray data = feat.data();
if (data == nix::none) {
throw nix::UninitializedEntity();
//return NDArray(nix::DataType::Float,{0});
}
if (feat.linkType() == nix::LinkType::Tagged) {
NDSize offset, count;
getOffsetAndCount(tag, data, position_index, offset, count);
if (!positionAndExtentInData(data, offset, count)) {
throw nix::OutOfBounds("Requested data slice out of the extent of the Feature!", 0);
}
DataView io = DataView(data, count, offset);
return io;
} else if (feat.linkType() == nix::LinkType::Indexed) {
//FIXME does the feature data to have a setdimension in the first dimension for the indexed case?
//For now it will just be a slice across the first dim.
if (position_index > data.dataExtent()[0]){
throw nix::OutOfBounds("Position is larger than the data stored in the feature.", 0);
}
NDSize offset(data.dataExtent().size(), 0);
offset[0] = position_index;
NDSize count(data.dataExtent());
count[0] = 1;
if (!positionAndExtentInData(data, offset, count)) {
throw nix::OutOfBounds("Requested data slice out of the extent of the Feature!", 0);
}
DataView io = DataView(data, count, offset);
return io;
}
// FIXME is this expected behavior? In the untagged case all data is returned
NDSize offset(data.dataExtent().size(), 0);
DataView io = DataView(data, data.dataExtent(), offset);
return io;
}
} // namespace util
} // namespace nix
| 37.76204 | 145 | 0.631133 | [
"vector"
] |
b348b7c12a76bd5a1edae019f3b26232eb105881 | 3,367 | cpp | C++ | Orz3D/Drawable/TexBox.cpp | bzhou830/Orz3D | 95d419446811e837c56bbed48d215b181edd4bfa | [
"MIT"
] | 1 | 2021-08-22T02:09:55.000Z | 2021-08-22T02:09:55.000Z | Orz3D/Drawable/TexBox.cpp | bzhou830/Orz3D | 95d419446811e837c56bbed48d215b181edd4bfa | [
"MIT"
] | null | null | null | Orz3D/Drawable/TexBox.cpp | bzhou830/Orz3D | 95d419446811e837c56bbed48d215b181edd4bfa | [
"MIT"
] | null | null | null | #include "TexBox.h"
#include "../Bindable/BindableBase.h"
#include "../GraphicsThrowMacros.h"
#include "../Surface.h"
TexBox::TexBox(Graphics& gfx,
std::mt19937& rng,
std::uniform_real_distribution<float>& adist,
std::uniform_real_distribution<float>& ddist,
std::uniform_real_distribution<float>& odist,
std::uniform_real_distribution<float>& rdist)
:
r(rdist(rng)),
droll(ddist(rng)),
dpitch(ddist(rng)),
dyaw(ddist(rng)),
dphi(odist(rng)),
dtheta(odist(rng)),
dchi(odist(rng)),
chi(adist(rng)),
theta(adist(rng)),
phi(adist(rng))
{
struct Vertex
{
struct
{
float x;
float y;
float z;
} pos;
struct
{
float u;
float v;
} texCoord;
};
const std::vector<Vertex> vertices =
{
// Front Face
{-1.0f, -1.0f, -1.0f, 0.0f, 1.0f},
{-1.0f, 1.0f, -1.0f, 0.0f, 0.0f},
{1.0f, 1.0f, -1.0f, 1.0f, 0.0f},
{1.0f, -1.0f, -1.0f, 1.0f, 1.0f},
// Back Face
{-1.0f, -1.0f, 1.0f, 1.0f, 1.0f},
{1.0f, -1.0f, 1.0f, 0.0f, 1.0f},
{1.0f, 1.0f, 1.0f, 0.0f, 0.0f},
{-1.0f, 1.0f, 1.0f, 1.0f, 0.0f},
// Top Face
{-1.0f, 1.0f, -1.0f, 0.0f, 1.0f},
{-1.0f, 1.0f, 1.0f, 0.0f, 0.0f},
{1.0f, 1.0f, 1.0f, 1.0f, 0.0f},
{1.0f, 1.0f, -1.0f, 1.0f, 1.0f},
// Bottom Face
{-1.0f, -1.0f, -1.0f, 1.0f, 1.0f},
{1.0f, -1.0f, -1.0f, 0.0f, 1.0f},
{1.0f, -1.0f, 1.0f, 0.0f, 0.0f},
{-1.0f, -1.0f, 1.0f, 1.0f, 0.0f},
// Left Face
{-1.0f, -1.0f, 1.0f, 0.0f, 1.0f},
{-1.0f, 1.0f, 1.0f, 0.0f, 0.0f},
{-1.0f, 1.0f, -1.0f, 1.0f, 0.0f},
{-1.0f, -1.0f, -1.0f, 1.0f, 1.0f},
// Right Face
{1.0f, -1.0f, -1.0f, 0.0f, 1.0f},
{1.0f, 1.0f, -1.0f, 0.0f, 0.0f},
{1.0f, 1.0f, 1.0f, 1.0f, 0.0f},
{1.0f, -1.0f, 1.0f, 1.0f, 1.0f},
};
AddBind(std::make_unique<VertexBuffer>(gfx, vertices));
auto pvs = std::make_unique<VertexShader>(gfx, L"VertexShaderTex.cso");
auto pvsbc = pvs->GetBytecode();
AddBind(std::move(pvs));
AddBind(std::make_unique<PixelShader>(gfx, L"PixelShaderTex.cso"));
AddBind(std::make_unique<Sampler>(gfx));
std::shared_ptr<Surface> surface = std::make_shared<Surface>("1.png", 200, 200);
AddTexture(std::make_unique<Texture>(gfx, surface));
const std::vector<unsigned short> indices =
{
// Front Face
0, 1, 2,
0, 2, 3,
// Back Face
4, 5, 6,
4, 6, 7,
// Top Face
8, 9, 10,
8, 10, 11,
// Bottom Face
12, 13, 14,
12, 14, 15,
// Left Face
16, 17, 18,
16, 18, 19,
// Right Face
20, 21, 22,
20, 22, 23
};
AddIndexBuffer(std::make_unique<IndexBuffer>(gfx, indices));
const std::vector<D3D11_INPUT_ELEMENT_DESC> ied =
{
{ "Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, sizeof(Vertex::pos), D3D11_INPUT_PER_VERTEX_DATA, 0},
};
AddBind(std::make_unique<InputLayout>(gfx, ied, pvsbc));
AddBind(std::make_unique<Topology>(gfx, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST));
AddBind(std::make_unique<TransformCbuf>(gfx, *this));
}
void TexBox::Update(float dt) noexcept
{
roll += droll * dt;
pitch += dpitch * dt;
yaw += dyaw * dt;
theta += dtheta * dt;
phi += dphi * dt;
chi += dchi * dt;
}
DirectX::XMMATRIX TexBox::GetTransformXM() const noexcept
{
return DirectX::XMMatrixRotationRollPitchYaw(pitch, yaw, roll) *
DirectX::XMMatrixTranslation(r, 0.0f, 0.0f) *
DirectX::XMMatrixRotationRollPitchYaw(theta, phi, chi);
}
| 22.597315 | 101 | 0.600535 | [
"vector"
] |
b34a63b74430c338b7cf908ae7ae3328045a1dba | 3,056 | cpp | C++ | src/rht-main.cpp | veselink1/refl-cpp-preprocessor | 4286991f03e21165920b68e652467fb4e1977682 | [
"MIT"
] | 8 | 2019-06-30T17:59:11.000Z | 2020-05-28T01:47:09.000Z | src/rht-main.cpp | veselink1/refl-cpp-preprocessor | 4286991f03e21165920b68e652467fb4e1977682 | [
"MIT"
] | null | null | null | src/rht-main.cpp | veselink1/refl-cpp-preprocessor | 4286991f03e21165920b68e652467fb4e1977682 | [
"MIT"
] | 2 | 2019-08-21T23:35:08.000Z | 2021-01-23T04:19:23.000Z | /**
* Created by veselink1.
* Released under the MIT license.
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>
#include <optional>
#include <unordered_map>
#include <algorithm>
#include <regex>
#include <chrono>
#include <clang-c/Index.h>
#include "rht-engine.hpp"
#include "rht-fs.hpp"
std::unordered_map<std::string, std::string> parse_arguments(int cargs, const char *const *vargs);
int main(int cargs, const char *const vargs[]) try
{
auto process_start_time = std::chrono::high_resolution_clock::now();
auto args = parse_arguments(cargs, vargs);
if (!args["verbose"].empty())
{
if (args["verbose"] == "y" || args["verbose"] == "yes")
{
rht::util::enable_log_info();
}
else if (args["verbose"] != "n" && args["verbose"] != "no")
{
std::cerr << "Argument '-verbose' must be one of y|yes|n|no!\n";
std::exit(-1);
}
}
rht::engine::process_file(rht::fs::canonical(args["input"]).c_str());
auto process_total_time = std::chrono::duration_cast<std::chrono::duration<double>>(
std::chrono::high_resolution_clock::now() - process_start_time);
std::cout << std::fixed << std::setprecision(2);
std::cout << "[" << rht::fs::filename(vargs[0]) << "]: Metadata processing took " << process_total_time.count() << "s. [exited]\n";
}
catch (const std::exception& e)
{
rht::util::log_error() << rht::util::to_string(e) << "\n";
}
std::unordered_map<std::string, std::string> parse_arguments(int cargs, const char *const *vargs)
{
static const std::vector<std::string> known_args{"input", "verbose"};
static const std::vector<std::string> required_args{"input"};
std::unordered_map<std::string, std::string> args;
for (int i = 1; i < cargs; i++)
{
std::string arg{vargs[i]};
if (arg[0] != '-')
{
std::cerr << "Arguments must be passed in the format -arg=value!\n";
std::exit(-1);
}
if (auto delim = arg.find('='); delim != std::string::npos)
{
std::string key{std::next(arg.begin()), std::next(arg.begin(), delim)};
std::string value{std::next(arg.begin(), delim + 1), arg.end()};
if (std::find(known_args.begin(), known_args.end(), key) == known_args.end())
{
std::cerr << "Unknown argument '-" << key << "=<value>'!\n";
std::cerr << "Known arguments: ";
for (auto&& known_arg : known_args)
{
std::cerr << '-' << known_arg << "=<value> ";
}
std::cerr << '\n';
std::exit(-1);
}
args.insert({key, value});
}
}
for (auto&& required_arg : required_args)
{
if (args[required_arg].size() == 0)
{
std::cerr << "Required argument -" << required_arg << "=<value> missing!\n";
std::exit(-1);
}
}
return args;
} | 31.183673 | 135 | 0.544503 | [
"vector"
] |
b35a99ce03a4186a8bb308d7ce3d79e24197b70e | 1,800 | cpp | C++ | pde.cpp | QuentinLam95/fqs_pde1d | da52690355f1094e9002d6afc74970e542e0d90f | [
"BSD-3-Clause"
] | null | null | null | pde.cpp | QuentinLam95/fqs_pde1d | da52690355f1094e9002d6afc74970e542e0d90f | [
"BSD-3-Clause"
] | null | null | null | pde.cpp | QuentinLam95/fqs_pde1d | da52690355f1094e9002d6afc74970e542e0d90f | [
"BSD-3-Clause"
] | null | null | null | #ifndef pde_cpp
#define pde_cpp
#include "pde.hpp"
#include <math.h>
BS_PDE::BS_PDE(VanillaOption* _option, const std::string& _left_boundary_type , const std::string& _right_boundary_type)
: option(_option), left_boundary_type(_left_boundary_type), right_boundary_type(_right_boundary_type) {}
std::string BS_PDE::get_right_boundary_type() const {
return right_boundary_type ;
}
std::string BS_PDE::get_left_boundary_type() const {
return left_boundary_type ;
}
double BS_PDE::diff_coeff(double t, double x, double v) const {
double vol = option->sigma;
return 0.5 * vol * vol ;
}
double BS_PDE::conv_coeff(double t, double x, double v) const {
return (option->r) - diff_coeff(t, x, v) ;
}
double BS_PDE::zero_coeff(double t, double x, double v) const {
return (option->r) ;
}
//maybe delete this
double BS_PDE::source_coeff(double t, double x, double v) const {
return 0.0;
}
double BS_PDE::boundary_left(double t, double x, double v) const {
return 0.0;
}
double BS_PDE::boundary_right(double t, double x, double v) const {
double res = 1.0;
if (left_boundary_type.compare("D") == 0) {
res = (x - (option->K) * exp(-(option->r) * ((option->T) - t))); //careful to use exp(x) when calling this function
}
return res;
}
double BS_PDE::init_cond(double x) {
return option->pay_off->operator()(x);
}
std::vector<double> BS_PDE::init_cond(std::vector<double> X)
{
size_t l = X.size();
std::vector<double> res(l);
//std::transform(X.begin(), X.end(), res.begin(), [this](double x)->{ return init_cond(x);});
std::transform(X.begin(), X.end(), res.begin(),
[this](double arg) { return BS_PDE::init_cond(arg); });
return res;
}
double BS_PDE::standard_dev() {
double vol = option->sigma;
double maturity = option->T;
return vol * sqrt(maturity);
}
#endif // !1
| 25.714286 | 120 | 0.693889 | [
"vector",
"transform"
] |
b35b4c75a5063996bbce459e850f5f61fe8252b3 | 18,344 | cpp | C++ | src/hvppdrv/vmexit_custom.cpp | 393686984/vt-driver | 8f3fae63846eb28b3040bced29b8fb2b10688afa | [
"MIT"
] | 11 | 2022-03-15T00:59:05.000Z | 2022-03-30T09:54:18.000Z | src/hvppdrv/vmexit_custom.cpp | gllhack/vt-driver | ab3d65a72944814738543e553247c9fcc4a7abd2 | [
"MIT"
] | null | null | null | src/hvppdrv/vmexit_custom.cpp | gllhack/vt-driver | ab3d65a72944814738543e553247c9fcc4a7abd2 | [
"MIT"
] | 10 | 2022-03-15T00:58:58.000Z | 2022-03-31T01:36:08.000Z | #include "vmexit_custom.h"
#include <hvpp/lib/cr3_guard.h>
#include <hvpp/lib/mp.h>
#include <hvpp/lib/log.h>
#include "SsdtHook.h"
#include "MemoryHide.h"
#include "DbgApi.h"
#include "NoTraceBP.h"
#include "hvpp/ia32/cpuid/cpuid_eax_01.h"
extern MemoryHide hide;
extern SSDTHook* ssdthook;
extern ddy::DbgkKernel dbgkapi;
extern NoTraceBP infbp;
extern InfEvent infevent;
extern set<PEPROCESS> AttachPreocess;
extern map<PETHREAD, CONTEXT> threadcontext;
pa_t last_mtf[100] = { 0 };
ULONG64 last_rip[100] = { 0 };
vmx::io_bitmap_t io_bitmap{ 0 };
auto vmexit_custom_handler::setup(vcpu_t& vp) noexcept -> error_code_t
{
base_type::setup(vp);
//
// Set per-VCPU data and mirror current physical memory in EPT.
//
auto data = new per_vcpu_data{};
data->ept.map_identity();
data->page_exec = 0;
data->page_read = 0;
vp.user_data(data);
//
// Enable EPT.
//
vp.ept(data->ept);
vp.ept_enable();
#if 1
//
// Enable exitting on 0x64 I/O port (keyboard).
//
//这里关闭I/O指令 太卡了
auto procbased_ctls = vp.processor_based_controls();
procbased_ctls.use_io_bitmaps = true;
vp.processor_based_controls(procbased_ctls);
//开启无限模式
auto procsecond = vp.processor_based_controls2();
procsecond.unrestricted_guest = true;
vp.processor_based_controls2(procsecond);
//bitmap<>(io_bitmap.a).set(0x64);
vp.io_bitmap(io_bitmap);
//trap cpuid异常
msr::vmx_entry_ctls_t entry_ctls = vp.vm_entry_controls();
entry_ctls.load_debug_controls = true;
vp.vm_entry_controls(entry_ctls);
msr::vmx_exit_ctls_t exit_ctls = vp.vm_exit_controls();
exit_ctls.acknowledge_interrupt_on_exit = true;
exit_ctls.save_debug_controls = true;
vp.vm_exit_controls(exit_ctls);
#else
//
// Turn on VM-exit on everything we support.
//
auto procbased_ctls = vp.processor_based_controls();
//
// Since VMWare handles rdtsc(p) instructions by its own
// magical way, we'll disable our own handling. Setting
// this in VMWare makes the guest OS completely bananas.
//
// procbased_ctls.rdtsc_exiting = true;
//
// Use either "use_io_bitmaps" or "unconditional_io_exiting",
// try to avoid using both of them.
//
// #define USE_IO_BITMAPS
// #define DISABLE_GP_EXITING
#ifdef USE_IO_BITMAPS
procbased_ctls.use_io_bitmaps = true;
#else
procbased_ctls.unconditional_io_exiting = true;
#endif
procbased_ctls.mov_dr_exiting = true;
procbased_ctls.cr3_load_exiting = true;
procbased_ctls.cr3_store_exiting = true;
procbased_ctls.invlpg_exiting = true;
vp.processor_based_controls(procbased_ctls);
auto procbased_ctls2 = vp.processor_based_controls2();
procbased_ctls2.descriptor_table_exiting = true;
vp.processor_based_controls2(procbased_ctls2);
vmx::msr_bitmap_t msr_bitmap{};
memset(msr_bitmap.data, 0xff, sizeof(msr_bitmap));
vp.msr_bitmap(msr_bitmap);
#ifdef USE_IO_BITMAPS
vmx::io_bitmap_t io_bitmap{};
memset(io_bitmap.data, 0xff, sizeof(io_bitmap));
//
// Disable VMWare backdoor.
//
bitmap<>(io_bitmap.a).clear(0x5658);
bitmap<>(io_bitmap.a).clear(0x5659);
vp.io_bitmap(io_bitmap);
#endif
#ifdef DISABLE_GP_EXITING
//
// Catch all exceptions except #GP.
//
vmx::exception_bitmap_t exception_bitmap{ ~0ul };
exception_bitmap.general_protection = false;
vp.exception_bitmap(exception_bitmap);
#else
//
// Catch all exceptions.
//
vp.exception_bitmap(vmx::exception_bitmap_t{ ~0ul });
#endif
//
// VM-execution control fields include guest/host masks
// and read shadows for the CR0 and CR4 registers.
// These fields control executions of instructions that
// access those registers (including CLTS, LMSW, MOV CR,
// and SMSW).
// They are 64 bits on processors that support Intel 64
// architecture and 32 bits on processors that do not.
//
// In general, bits set to 1 in a guest/host mask correspond
// to bits "owned" by the host:
// - Guest attempts to set them (using CLTS, LMSW, or
// MOV to CR) to values differing from the corresponding
// bits in the corresponding read shadow cause VM exits.
// - Guest reads (using MOV from CR or SMSW) return values
// for these bits from the corresponding read shadow.
//
// Bits cleared to 0 correspond to bits "owned" by the
// guest; guest attempts to modify them succeed and guest
// reads return values for these bits from the control
// register itself.
// (ref: Vol3C[24.6.6(Guest/Host Masks and Read Shadows for CR0 and CR4)])
//
// TL;DR:
// When bit in guest/host mask is set, write to the control
// register causes VM-exit. Mov FROM CR0 and CR4 returns
// values in the shadow register values.
//
// Note that SHADOW register value and REAL register value may
// differ. The guest will behave according to the REAL control
// register value. Only read from that register will return the
// fake (aka "shadow") value.
//
vp.cr0_guest_host_mask(cr0_t{ ~0ull });
vp.cr4_guest_host_mask(cr4_t{ ~0ull });
#endif
return {};
}
void vmexit_custom_handler::teardown(vcpu_t& vp) noexcept
{
auto& data = user_data(vp);
delete& data;
vp.user_data(nullptr);
}
void vmexit_custom_handler::handle_execute_cpuid(vcpu_t& vp) noexcept
{
if (vp.context().eax == 1)//这个是vmx启动标志
{
cpuid_eax_01 cpuid_info;
ia32_asm_cpuid(cpuid_info.cpu_info, 1);
vp.context().rax = cpuid_info.eax;
vp.context().rbx = cpuid_info.ebx;
cpuid_info.feature_information_ecx.hypervisor_present = 0;
cpuid_info.feature_information_ecx.virtual_machine_extensions = 0;
vp.context().rcx = cpuid_info.ecx;
vp.context().rdx = cpuid_info.edx;
}
else
{
base_type::handle_execute_cpuid(vp);
}
}
void vmexit_custom_handler::handle_execute_vmcall(vcpu_t& vp) noexcept
{
auto& data = user_data(vp);
switch (vp.context().rcx)
{
case VMCALLVALUE::DDYMemoryHide:
{
auto data = static_cast<HookData*>((PVOID)vp.context().rdx);
auto guestpa1 = pa_t::from_va(data->rw_page_va);
auto guestpa2 = pa_t::from_va(data->e_page_va);
vp.ept().split_2mb_to_4kb(guestpa1 & ept_pd_t::mask, guestpa1 & ept_pd_t::mask);
vp.ept().split_2mb_to_4kb(guestpa2 & ept_pd_t::mask, guestpa2 & ept_pd_t::mask);
vp.ept().map_4kb(guestpa1, guestpa2, epte_t::access_type::execute);
vmx::invept_single_context(vp.ept().ept_pointer());
break;
}
case VMCALLVALUE::DDYRemoveMemoryHide:
{
auto data = static_cast<HookData*>((PVOID)vp.context().rdx);
auto guestpa1 = pa_t::from_va(data->rw_page_va);
pa_t pa{ (ULONG64)data->rw_page_pa };
if (guestpa1.value() == 0)
{
guestpa1 = pa;
}
auto guestpa2 = pa_t::from_va(data->e_page_va);
vp.ept().map_4kb(guestpa1, guestpa1, epte_t::access_type::read_write_execute);
vmx::invept_single_context(vp.ept().ept_pointer());
break;
}
case VMCALLVALUE::DDYInfHook:
{
if (infbp.pagemonitor.locked)
{
pa_t guestpa{ (ULONG64)infbp.pagemonitor.page_pa };
vp.ept().split_2mb_to_4kb(guestpa & ept_pd_t::mask, guestpa & ept_pd_t::mask);
vp.ept().map_4kb(guestpa, guestpa, epte_t::access_type::none);//读写执行断点
}
vmx::invept_single_context(vp.ept().ept_pointer());
break;
}
case VMCALLVALUE::DDYInfUnHook:
{
if (infbp.pagemonitor.locked)
{
pa_t guestpa{ (ULONG64)infbp.pagemonitor.page_pa };
vp.ept().map_4kb(guestpa, guestpa, epte_t::access_type::read_write_execute);//恢复所有页面权限
}
vmx::invept_single_context(vp.ept().ept_pointer());
break;
}
default:
base_type::handle_execute_vmcall(vp);
return;
}
}
void vmexit_custom_handler::handle_monitor_trap_flag(vcpu_t& vp) noexcept
{
auto pa = last_mtf[KeGetCurrentProcessorNumber()];
vp.ept().map_4kb(pa, pa, ia32::epte_t::access_type::none);
auto ctr = vp.processor_based_controls();
ctr.monitor_trap_flag = false;
vp.processor_based_controls(ctr);
vmx::invept_single_context(vp.ept().ept_pointer());
vp.suppress_rip_adjust();
}
void vmexit_custom_handler::handle_mov_cr(vcpu_t& vp) noexcept
{
base_type::handle_mov_cr(vp);
}
void vmexit_custom_handler::handle_mov_dr(vcpu_t& vp) noexcept
{
base_type::handle_mov_dr(vp);
}
void vmexit_custom_handler::handle_gdtr_idtr_access(vcpu_t& vp) noexcept
{
base_type::handle_gdtr_idtr_access(vp);
}
void vmexit_custom_handler::handle_ldtr_tr_access(vcpu_t& vp) noexcept
{
base_type::handle_ldtr_tr_access(vp);
}
void vmexit_custom_handler::handle_execute_invpcid(vcpu_t& vp) noexcept
{
base_type::handle_execute_invpcid(vp);
}
void vmexit_custom_handler::handle_execute_rdtsc(vcpu_t& vp) noexcept
{
base_type::handle_execute_rdtsc(vp);
}
void vmexit_custom_handler::handle_execute_rdtscp(vcpu_t& vp) noexcept
{
base_type::handle_emulate_rdtscp(vp);
}
void vmexit_custom_handler::handle_execute_wbinvd(vcpu_t& vp) noexcept
{
base_type::handle_execute_wbinvd(vp);
}
void vmexit_custom_handler::handle_execute_xsetbv(vcpu_t& vp) noexcept
{
base_type::handle_execute_xsetbv(vp);
}
void vmexit_custom_handler::handle_execute_rdmsr(vcpu_t& vp) noexcept
{
base_type::handle_execute_rdmsr(vp);
}
void vmexit_custom_handler::handle_execute_wrmsr(vcpu_t& vp) noexcept
{
base_type::handle_execute_wrmsr(vp);
}
void vmexit_custom_handler::handle_execute_io_instruction(vcpu_t& vp) noexcept
{
base_type::handle_execute_io_instruction(vp);
}
void vmexit_custom_handler::handle_execute_invd(vcpu_t& vp) noexcept
{
base_type::handle_execute_invd(vp);
}
void vmexit_custom_handler::handle_execute_invlpg(vcpu_t& vp) noexcept
{
base_type::handle_execute_invlpg(vp);
}
void vmexit_custom_handler::handle_execute_vmclear(vcpu_t& vp) noexcept
{
base_type::handle_execute_vmclear(vp);
}
void vmexit_custom_handler::handle_execute_vmlaunch(vcpu_t& vp) noexcept
{
base_type::handle_execute_vmlaunch(vp);
}
void vmexit_custom_handler::handle_execute_vmptrld(vcpu_t& vp) noexcept
{
base_type::handle_execute_vmptrld(vp);
}
void vmexit_custom_handler::handle_execute_vmptrst(vcpu_t& vp) noexcept
{
base_type::handle_execute_vmptrst(vp);
}
void vmexit_custom_handler::handle_execute_vmread(vcpu_t& vp) noexcept
{
base_type::handle_execute_vmread(vp);
}
void vmexit_custom_handler::handle_execute_vmresume(vcpu_t& vp) noexcept
{
base_type::handle_execute_vmresume(vp);
}
void vmexit_custom_handler::handle_execute_vmwrite(vcpu_t& vp) noexcept
{
base_type::handle_execute_vmwrite(vp);
}
void vmexit_custom_handler::handle_execute_vmxoff(vcpu_t& vp) noexcept
{
base_type::handle_execute_vmxoff(vp);
}
void vmexit_custom_handler::handle_execute_vmxon(vcpu_t& vp) noexcept
{
base_type::handle_execute_vmxon(vp);
}
void vmexit_custom_handler::handle_execute_invept(vcpu_t& vp) noexcept
{
base_type::handle_execute_invept(vp);
}
void vmexit_custom_handler::handle_execute_invvpid(vcpu_t& vp) noexcept
{
base_type::handle_execute_invvpid(vp);
}
void vmexit_custom_handler::handle_ept_violation(vcpu_t& vp) noexcept
{
auto exit_qualification = vp.exit_qualification().ept_violation;
auto guest_pa = vp.exit_guest_physical_address();
auto guest_va = vp.exit_guest_linear_address();
if (exit_qualification.data_read || exit_qualification.data_write)
{
//
// Someone requested read or write access to the guest_pa,
// but the page has execute-only access. Map the page with
// the "data.page_read" we've saved before in the VMCALL
// handler and set the access to RW.
//
//hvpp_trace("data_read LA: 0x%p PA: 0x%p", guest_va.value(), guest_pa.value());
if (hide.memoryhide.count(PAGE_ALIGN(guest_va.value())))
{
auto data = hide.memoryhide[PAGE_ALIGN(guest_va.value())];
auto pa_rw = pa_t::from_va(data->rw_page_va);
auto pa_e = pa_t::from_va(data->e_page_va);
vp.ept().map_4kb(guest_pa, pa_rw, epte_t::access_type::read_write);
}
else//INF HOOK
{
CreateDebugException(vp, guest_pa, guest_va, false);
}
}
else if (exit_qualification.data_execute)
{
//
// Someone requested execute access to the guest_pa, but
// the page has only read-write access. Map the page with
// the "data.page_execute" we've saved before in the VMCALL
// handler and set the access to execute-only.
//
//hvpp_trace("data_execute LA: 0x%p PA: 0x%p", guest_va.value(), guest_pa.value());
if (hide.memoryhide.count(PAGE_ALIGN(guest_va.value())))
{
auto data = hide.memoryhide[PAGE_ALIGN(guest_va.value())];
auto pa_rw = pa_t::from_va(data->rw_page_va);
auto pa_e = pa_t::from_va(data->e_page_va);
vp.ept().map_4kb(guest_pa, pa_e, epte_t::access_type::execute);
}
else
{
CreateDebugException(vp, guest_pa, guest_va, true);
//刷新缓存
vmx::invept_single_context(vp.ept().ept_pointer());
}
}
//vmx::invept_single_context(vp.ept().ept_pointer());
//
// An EPT violation invalidates any guest-physical mappings
// (associated with the current EP4TA) that would be used to
// translate the guest-physical address that caused the EPT
// violation. If that guest-physical address was the translation
// of a linear address, the EPT violation also invalidates
// any combined mappings for that linear address associated
// with the current PCID, the current VPID and the current EP4TA.
// (ref: Vol3C[28.3.3.1(Operations that Invalidate Cached Mappings)])
//
//
// TL;DR:
// We don't need to call INVEPT (nor INVVPID) here, because
// CPU invalidates mappings for the accessed linear address
// for us.
//
// Note1:
// In the paragraph above, "EP4TA" is the value of bits
// 51:12 of EPTP. These 40 bits contain the address of
// the EPT-PML4-table (the notation EP4TA refers to those
// 40 bits).
//
// Note2:
// If we would change any other EPT structure, INVEPT or
// INVVPID might be needed.
//
//
// Make the instruction which fetched the memory to be executed
// again (this time without EPT violation).
//
vp.suppress_rip_adjust();
}
void CreateDebugException(hvpp::vcpu_t& vp, const ia32::pa_t& guest_pa, ia32::va_t& guest_va, bool excute)
{
//无论是否是断点的页面,都需要恢复页面权限
vp.ept().map_4kb(guest_pa, guest_pa, epte_t::access_type::read_write_execute);
last_mtf[KeGetCurrentProcessorNumber()] = guest_pa;
auto ctr = vp.processor_based_controls();
ctr.monitor_trap_flag = true;
vp.processor_based_controls(ctr);
PageMonitor pm;
BreakPoint bp;
pm.eprocess = PsGetCurrentProcess();
pm.page_va = PAGE_ALIGN(guest_va.value());
if (excute)
{
bp.address = vp.context().rip;
}
else
{
bp.address = guest_va.value();
}
bp.size = 8;
if (AttachPreocess.count(pm.eprocess))//只有被调试进程才注入异常
{
if (!excute)
{
if (!infbp.IsBpInCurrentBp(bp))
{
return;
}
if (vp.guest_ss().access.descriptor_privilege_level != 3)//只有R3且没有执行过的RIP才注入异常
{
return;
}
}
else
{
if (infbp.current_bp.address != bp.address)
{
return;
}
}
if (infevent.last_lock.count(pm.eprocess))//如果没有锁住
{
if (!infevent.last_lock[pm.eprocess])
{
if (last_rip[KeGetCurrentProcessorNumber()] != vp.context().rip)//别重复执行
{
infevent.last_lock[pm.eprocess] = true;
infevent.debugevent[pm.eprocess]->dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
infevent.debugevent[pm.eprocess]->dwProcessId = (DWORD)PsGetCurrentProcessId();
infevent.debugevent[pm.eprocess]->dwThreadId = (DWORD)PsGetCurrentThreadId();
infevent.debugevent[pm.eprocess]->u.Exception.dwFirstChance = true;
infevent.debugevent[pm.eprocess]->u.Exception.ExceptionRecord.ExceptionAddress = (PVOID)bp.address;
infevent.debugevent[pm.eprocess]->u.Exception.ExceptionRecord.ExceptionCode = EXCEPTION_SINGLE_STEP;
infevent.debugevent[pm.eprocess]->u.Exception.ExceptionRecord.ExceptionInformation[8] = 8;
infevent.debugevent[pm.eprocess]->u.Exception.ExceptionRecord.ExceptionRecord = 0;
infevent.debugevent[pm.eprocess]->u.Exception.ExceptionRecord.NumberParameters = 0;
infevent.debugevent[pm.eprocess]->u.Exception.ExceptionRecord.ExceptionFlags = 0;
last_rip[KeGetCurrentProcessorNumber()] = vp.context().rip;
//采集线程上下文
auto pth = PsGetCurrentThread();
threadcontext[pth] = { 0 };
threadcontext[pth].Dr0 = __readdr(0);
threadcontext[pth].Dr1 = __readdr(1);
threadcontext[pth].Dr2 = __readdr(2);
threadcontext[pth].Dr3 = __readdr(3);
threadcontext[pth].Dr6 = __readdr(6);
threadcontext[pth].Dr7 = vp.guest_dr7().flags;
threadcontext[pth].DebugControl = vp.guest_debugctl().flags;
threadcontext[pth].EFlags = vp.context().rflags.flags;
threadcontext[pth].R10 = vp.context().r10;
threadcontext[pth].R11 = vp.context().r11;
threadcontext[pth].R12 = vp.context().r12;
threadcontext[pth].R13 = vp.context().r13;
threadcontext[pth].R14 = vp.context().r14;
threadcontext[pth].R15 = vp.context().r15;
threadcontext[pth].R8 = vp.context().r8;
threadcontext[pth].R9 = vp.context().r9;
threadcontext[pth].Rax = vp.context().rax;
threadcontext[pth].Rbp = vp.context().rbp;
threadcontext[pth].Rbx = vp.context().rbx;
threadcontext[pth].Rcx = vp.context().rcx;
threadcontext[pth].Rdi = vp.context().rdi;
threadcontext[pth].Rdx = vp.context().rdx;
threadcontext[pth].Rip = vp.context().rip;
threadcontext[pth].Rsi = vp.context().rsi;
threadcontext[pth].Rsp = vp.context().rsp;
threadcontext[pth].SegCs = vp.guest_cs().selector.flags;
threadcontext[pth].SegDs = vp.guest_ds().selector.flags;
threadcontext[pth].SegEs = vp.guest_es().selector.flags;
threadcontext[pth].SegFs = vp.guest_fs().selector.flags;
threadcontext[pth].SegGs = vp.guest_gs().selector.flags;
threadcontext[pth].SegSs = vp.guest_ss().selector.flags;
//通知调试器
infevent.last_inf[pm.eprocess] = true;
//解锁
infevent.last_lock[pm.eprocess] = false;
vp.interrupt_inject(interrupt::debug);//注入调试异常
}
else
{
last_rip[KeGetCurrentProcessorNumber()] = 0;
}
}
}
}
}
void vmexit_custom_handler::handle_exception_or_nmi(vcpu_t& vp) noexcept
{
const auto interrupt = vp.interrupt_info();
if (interrupt.type() == vmx::interrupt_type::hardware_exception)
{
if (interrupt.vector() == exception_vector::invalid_opcode)//用#UD代替int3 可能会和r3的中断冲突
{
if (ssdthook != nullptr && ssdthook->ssdtpoint.count(vp.context().rip_as_pointer))
{
vp.context().rip = (ULONG64)ssdthook->ssdtpoint[vp.context().rip_as_pointer];
vp.suppress_rip_adjust();
return;
}
}
}
base_type::handle_exception_or_nmi(vp);
}
auto vmexit_custom_handler::user_data(vcpu_t& vp) noexcept -> per_vcpu_data&
{
return *reinterpret_cast<per_vcpu_data*>(vp.user_data());
}
| 29.210191 | 106 | 0.731247 | [
"vector"
] |
b35d0ac0de153c9b6f4353ce42ea54308354ff59 | 3,777 | cpp | C++ | Tokenizer.cpp | JeffTM/Markov-Bot-CPP | a2354bdfa48a213c896d6aff25ff7ba2cfbb1973 | [
"MIT"
] | null | null | null | Tokenizer.cpp | JeffTM/Markov-Bot-CPP | a2354bdfa48a213c896d6aff25ff7ba2cfbb1973 | [
"MIT"
] | null | null | null | Tokenizer.cpp | JeffTM/Markov-Bot-CPP | a2354bdfa48a213c896d6aff25ff7ba2cfbb1973 | [
"MIT"
] | null | null | null | #include "Tokenizer.h"
//Breaks the string src into substrings that represent words in the markov chain
void Tokenizer::operator()(const std::string & fileName, std::vector<std::string> & dest) const
{
using namespace std;
string src(slurp(fileName));
size_t i = 0;
while (true)
{
//Advance past any white space characters
while (isWhiteSpace(src[i]) && i < src.size())
++i;
if (i == src.size())
return;
//If src[i] is an opening character add the substring contained
//between i and its closing tag
if (isOpeningTag(src[i]))
{
size_t closeIndex = findClosingTag(src, src[i], i + 1);
if (closeIndex == string::npos)
{
dest.push_back(lowercase(src.substr(i)));
return;
}
dest.push_back(lowercase(src.substr(i, closeIndex - i + 1))); //Remove the lowercase?
i = closeIndex + 1;
}
//else if scr[i] is a punctuation character add it and any following equal characters
else if (isPunctuation(src[i]))
{
size_t count = groupCount(src, i);
dest.push_back(src.substr(i, count));
i += count;
}
//else add the token is the substring from i up to but not including
//the next stop character
else
{
size_t nextStopper = findStopper(src, i + 1);
if (nextStopper == string::npos)
{
dest.push_back(lowercase(src.substr(i)));
return;
}
dest.push_back(lowercase(src.substr(i, nextStopper - i)));
i = nextStopper;
}
}
}
//private:
//Returns the closing character of c
//e.g. closer('[') returns ']'
char Tokenizer::closer(char c)
{
switch (c)
{
case '(':
return ')';
case '[':
return ']';
case '<':
return '>';
case '{':
return '}';
default:
return '\0';
}
}
//Returns the number of characters that compare equal to scr[start] continuously starting at start
//e.g. if scr is "aaaba", start is 0 the function will return 3
std::size_t Tokenizer::groupCount(const std::string & src, size_t start)
{
char key = src[start];
std::size_t count = 1;
for (++start; src[start] == key && start < src.size(); ++start)
++count;
return count;
}
//Returns the index of the closing character of c in src starting at start
//if not found returns string::npos
std::size_t Tokenizer::findClosingTag(const std::string & src, char c, size_t start)
{
c = closer(c);
return src.find(c, start);
}
//Returns the index of the first character in src for which isStopper returns true
std::size_t Tokenizer::findStopper(const std::string & src, size_t start)
{
while (start < src.size())
{
if (isStopper(src[start]))
return start;
++start;
}
return std::string::npos;
}
//returns true if c is contained in the string "c[<{"
bool Tokenizer::isOpeningTag(char c)
{
return std::string("([<{").find(c) != std::string::npos;
}
//returns true if c is a stopping character character
//C is a stopping character if isPunctuation(c) or isWhiteSpace(c) returns true
bool Tokenizer::isStopper(char c)
{
return isWhiteSpace(c) || isPunctuation(c);
}
//Returns true if c is contained in " \n\t\r\f\v"
bool Tokenizer::isWhiteSpace(char c)
{
return std::string(" \n\t\r\f\v").find(c) != std::string::npos;
}
//Returns s with all uppercase letters replaced with their lowercase version
std::string Tokenizer::lowercase(std::string s) //Upgrade this with move semantics? I think it is already used automatically
{
for (std::size_t i = 0; i < s.size(); ++i)
{
if ('A' <= s[i] && s[i] <= 'Z')
s[i] += 32;
}
return s;
}
//Returns the entire file at fileName as a string
//Modified from: https://stackoverflow.com/questions/116038/what-is-the-best-way-to-read-an-entire-file-into-a-stdstring-in-c
std::string Tokenizer::slurp(const std::string & fileName)
{
std::ifstream file(fileName);
std::stringstream sstr;
sstr << file.rdbuf();
file.close();
return sstr.str();
}
| 25.693878 | 125 | 0.670373 | [
"vector"
] |
b36862be5a22b2edb5e0382208b6150780ebad7f | 5,900 | cpp | C++ | src/GraphicsDevice.cpp | foxostro/CheeseTesseract | 737ebbd19cee8f5a196bf39a11ca793c561e56cb | [
"MIT"
] | 1 | 2016-05-17T03:36:52.000Z | 2016-05-17T03:36:52.000Z | src/GraphicsDevice.cpp | foxostro/CheeseTesseract | 737ebbd19cee8f5a196bf39a11ca793c561e56cb | [
"MIT"
] | null | null | null | src/GraphicsDevice.cpp | foxostro/CheeseTesseract | 737ebbd19cee8f5a196bf39a11ca793c561e56cb | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Application.h"
#include "GraphicsDevice.h"
#ifdef _WIN32
void GraphicsDevice::flushMessageQueue() {
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT) break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
#endif
GraphicsDevice::~GraphicsDevice() {
SDL_FreeSurface(windowSurface);
windowSurface = 0;
}
GraphicsDevice::GraphicsDevice(const ivec2 &windowSize, bool fullscreen)
: windowSurface(0),
dimensions(0,0),
nearClip(0.1f),
farClip(100.0f) {
attr = generateDefaultAttributes();
setAttributes();
SDL_WM_SetCaption(PROJECT_NAME, PROJECT_NAME);
windowSurface = SDL_SetVideoMode(windowSize.x,
windowSize.y,
0,
SDL_OPENGL
| SDL_HWSURFACE
| SDL_DOUBLEBUF
| (fullscreen?SDL_FULLSCREEN:0)
);
#ifdef _WIN32
/*
See:
<http://listas.apesol.org/pipermail/sdl-libsdl.org/2002-July/028824.html>
Sometimes, after calling SDL_SetVideoMode, MessageBox and standard assert
(which calls MessageBox internally) will return immediately without
displaying a message box window.
*/
flushMessageQueue();
#endif
ASSERT(windowSurface, "Couldn't create window!");
initializeOpenGLState();
initializeOpenGLExtensions();
resizeOpenGLViewport(windowSize, nearClip, farClip);
SDL_ShowCursor(SDL_DISABLE);
TRACE(getOpenGLInfo());
}
GraphicsDevice::GL_ATTRIBUTES GraphicsDevice::generateDefaultAttributes() {
int red = 8;
int green = 8;
int blue = 8;
int alpha = 8;
bool doublebuffer = true;
int depth = 24;
int fsaaBuffers = 0; // FSAA is not available on Intel X3100
int fsaaSamples = 0;
GL_ATTRIBUTES attr;
attr.insert(make_pair(SDL_GL_RED_SIZE, red));
attr.insert(make_pair(SDL_GL_GREEN_SIZE, green));
attr.insert(make_pair(SDL_GL_BLUE_SIZE, blue));
attr.insert(make_pair(SDL_GL_ALPHA_SIZE, alpha));
attr.insert(make_pair(SDL_GL_DOUBLEBUFFER, doublebuffer?1:0));
attr.insert(make_pair(SDL_GL_DEPTH_SIZE, depth));
attr.insert(make_pair(SDL_GL_MULTISAMPLEBUFFERS, fsaaBuffers));
attr.insert(make_pair(SDL_GL_MULTISAMPLESAMPLES, fsaaSamples));
return attr;
}
void GraphicsDevice::setAttribute(pair<SDL_GLattr, int> attribute) {
SDL_GL_SetAttribute(attribute.first, attribute.second);
}
void GraphicsDevice::setAttributes() {
for_each(attr.begin(), attr.end(), GraphicsDevice::setAttribute);
}
mat4 GraphicsDevice::getProjectionMatrix() {
float m[16];
glGetFloatv(GL_PROJECTION_MATRIX, m);
return mat4(m);
}
mat4 GraphicsDevice::getModelViewMatrix() {
float m[16];
glGetFloatv(GL_MODELVIEW_MATRIX, m);
return mat4(m);
}
Frustum GraphicsDevice::getCameraFrustum() {
return Frustum(getModelViewMatrix(), getProjectionMatrix());
}
mat3 GraphicsDevice::getCameraOrientation() {
const mat4 modl = getModelViewMatrix();
mat3 orientation;
orientation.setAxisX(modl.getAxisX());
orientation.setAxisY(modl.getAxisY());
orientation.setAxisZ(modl.getAxisZ());
return orientation;
}
string GraphicsDevice::getOpenGLInfo() {
return string("OpenGL Specs:") +
"\nVendor: " + (const char*)glGetString(GL_VENDOR) +
"\nRenderer: " + (const char*)glGetString(GL_RENDERER) +
"\nVersion: " + (const char*)glGetString(GL_VERSION) +
"\nExtensions: " + (const char*)glGetString(GL_EXTENSIONS);
}
void GraphicsDevice::initializeOpenGLState() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearStencil(0);
glClearDepth(1.0f);
glDepthFunc(GL_LEQUAL);
glEnable(GL_DEPTH_TEST);
// Polygon color should be mixed with texture color
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// Set pixel packing to be "tight," that is, with a 1 byte row alignment
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
// Backface Culling
glEnable(GL_CULL_FACE);
glFrontFace(GL_CW);
glCullFace(GL_BACK);
// Set up a default colored material
setDefaultMaterial();
// Initial lighting settings
glEnable(GL_LIGHTING);
glEnable(GL_NORMALIZE);
// Initialize FFP specular highlights
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, black);
}
void GraphicsDevice::initializeOpenGLExtensions() {
GLenum err = glewInit();
VERIFY(GLEW_OK == err, (const char*)glewGetErrorString(err));
}
void GraphicsDevice::resizeOpenGLViewport(const ivec2 &_dimensions,
float _nearClip,
float _farClip) {
ASSERT(_dimensions.x!=0, "Window width equals zero");
ASSERT(_dimensions.y!=0, "Window height equals zero");
ASSERT(_nearClip > 0, "Near clip plan is too close");
ASSERT(_farClip > _nearClip, "Far clip plane is too close");
dimensions = _dimensions;
nearClip = _nearClip;
farClip = _farClip;
const float aspectRatio = (GLfloat)dimensions.x/(GLfloat)dimensions.y;
// Reset view port
glViewport(0, 0, dimensions.x, dimensions.y);
// Reset projection matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, aspectRatio, nearClip, farClip);
// Reset model-view matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void GraphicsDevice::setDefaultMaterial() {
glShadeModel(GL_SMOOTH);
glEnable(GL_COLOR_MATERIAL);
color ambient = color(0.0f,0.0f,0.0f,1.0f);
color diffuse = color(0.7f,0.7f,0.7f,1.0f);
color specular = color(1.0f,1.0f,1.0f,1.0f);
float shininess = 64.0f;
glMaterialfv(GL_FRONT, GL_AMBIENT, ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, specular);
glMaterialf(GL_FRONT, GL_SHININESS, shininess);
}
| 28.640777 | 75 | 0.711186 | [
"model"
] |
b3693cf9267d368c31d1cfe6d30e09d6a4c4d84d | 4,600 | hh | C++ | stock_chart_wx.hh | pedro-vicente/stock_chart_wx | b8fcc417a45254466b14b31b6363844bf35f94de | [
"Apache-2.0"
] | 1 | 2019-02-08T03:12:09.000Z | 2019-02-08T03:12:09.000Z | stock_chart_wx.hh | pedro-vicente/stock_chart_wx | b8fcc417a45254466b14b31b6363844bf35f94de | [
"Apache-2.0"
] | 1 | 2018-08-29T04:09:01.000Z | 2018-08-29T04:09:01.000Z | stock_chart_wx.hh | pedro-vicente/stock_chart_wx | b8fcc417a45254466b14b31b6363844bf35f94de | [
"Apache-2.0"
] | null | null | null | #ifndef WX_ELLIOT_FRAME
#define WX_ELLIOT_FRAME 1
#include "wx/wxprec.h"
#include "wx/wx.h"
#include "wx/splitter.h"
#include "wx/artprov.h"
#include "wx/imaglist.h"
#include "wx/grid.h"
#include "wx/mdi.h"
#include "wx/toolbar.h"
#include "wx/laywin.h"
#include "wx/list.h"
#include "wx/cmdline.h"
#include "wx/datetime.h"
#include "wx/datectrl.h"
#include "wx/stattext.h"
#include "wx/dateevt.h"
#include "wx/panel.h"
#include "wx/calctrl.h"
#include "wx/timectrl.h"
#include "wx/collpane.h"
#include "icons/sample.xpm"
#include "icons/file.xpm"
#include "icons/forward.xpm"
#include "icons/folder.xpm"
#include "icons/doc_blue.xpm"
#include "grafix.hh"
#include "model.hh"
#include "connect_alpha.hh"
enum
{
SOCKET_ID = wxID_HIGHEST + 1,
ID_CONNECT_DLG,
ID_TRADE_DLG,
ID_COMBO_PERIOD,
ID_COMBO_INTERVAL,
ID_COMBO_TICKER,
ID_CONNECT_HTTP,
ID_CONNECT_HTTP_UPDATE,
ID_CONNECT_BUTTON,
ID_TEXT_CTRL_INTERVAL,
ID_TEXT_CTRL_TITLE,
ID_TEXT_CTRL_PERIOD,
ID_TEXT_CTRL_TRADE_INDEX,
ID_TEXT_CTRL_TRADE_AMOUNT,
WAVE_0,
WAVE_1,
WAVE_2,
WAVE_3,
WAVE_4,
WAVE_5,
WAVE_A,
WAVE_B,
WAVE_C,
};
/////////////////////////////////////////////////////////////////////////////////////////////////////
//DialogConnect
/////////////////////////////////////////////////////////////////////////////////////////////////////
class DialogConnect : public wxDialog
{
public:
DialogConnect(wxWindow *parent);
void OnConnect(wxCommandEvent& event);
void OnComboInterval(wxCommandEvent& event);
void OnComboPeriod(wxCommandEvent& event);
void OnComboTicker(wxCommandEvent& event);
private:
wxDECLARE_EVENT_TABLE();
};
/////////////////////////////////////////////////////////////////////////////////////////////////////
//DialogTrade
/////////////////////////////////////////////////////////////////////////////////////////////////////
class DialogTrade : public wxDialog
{
public:
DialogTrade(wxWindow *parent);
private:
wxDECLARE_EVENT_TABLE();
};
/////////////////////////////////////////////////////////////////////////////////////////////////////
//wxChart
/////////////////////////////////////////////////////////////////////////////////////////////////////
class wxChart : public wxScrolledWindow
{
public:
wxChart(wxWindow *parent);
virtual void OnDraw(wxDC& dc);
void OnMouseDown(wxMouseEvent &event);
void OnMouseMove(wxMouseEvent &event);
void parse_response(const std::vector<time_price_t> &tp, int interval, const std::string &ticker);
void read_file(const std::string &file_name);
void store(const std::string &wave);
void update();
size_t trades();
void delete_trades();
graf_t m_graf;
void write();
model_t m_model;
private:
void initialize_chart();
size_t m_pt; //current selected index data point (mouse down)
wxDECLARE_EVENT_TABLE();
};
/////////////////////////////////////////////////////////////////////////////////////////////////////
//wxFrameMain
/////////////////////////////////////////////////////////////////////////////////////////////////////
class wxFrameMain : public wxFrame
{
public:
wxFrameMain();
~wxFrameMain();
void OnInput(wxCommandEvent& event);
void OnTrade(wxCommandEvent& event);
void OnFileOpen(wxCommandEvent &event);
void OnMRUFile(wxCommandEvent& event);
void OnQuit(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event);
void OnConnect(wxCommandEvent& event);
void OnWave_0(wxCommandEvent& event);
void OnWave_1(wxCommandEvent& event);
void OnWave_2(wxCommandEvent& event);
void OnWave_3(wxCommandEvent& event);
void OnWave_4(wxCommandEvent& event);
void OnWave_5(wxCommandEvent& event);
void OnConnectUpdate(wxCommandEvent& event);
wxString m_current_file;
protected:
wxWindow *m_win_grid;
wxWindow *m_win_chart;
wxSplitterWindow* m_splitter;
void get_results();
int read(const std::string &file_name);
wxFileHistory m_file_history;
//[INTERVAL] : Interval or frequency in seconds
//[PERIOD] : The historical data period, "d" or "Y"
//[TICKER] : This is the ticker symbol of the stock
public:
int m_interval; //model, in seconds
wxString m_period; //"90d"
wxString m_ticker;
private:
wxDECLARE_EVENT_TABLE();
};
/////////////////////////////////////////////////////////////////////////////////////////////////////
//wxAppAlert
/////////////////////////////////////////////////////////////////////////////////////////////////////
class wxAppAlert : public wxApp
{
public:
virtual bool OnInit();
void OnInitCmdLine(wxCmdLineParser& pParser);
bool OnCmdLineParsed(wxCmdLineParser& pParser);
};
#endif
| 26.285714 | 101 | 0.577826 | [
"vector",
"model"
] |
b36b39ded4fcd0d45107b641a1623e6c63b4e948 | 14,855 | cpp | C++ | neutrino/graphics/src/font/tables/character_to_glyph_index_mapping.cpp | alexiynew/nih_framework | a65335586331daa0ece892f98265bd1d2f8f579f | [
"MIT"
] | 1 | 2017-07-14T04:51:54.000Z | 2017-07-14T04:51:54.000Z | neutrino/graphics/src/font/tables/character_to_glyph_index_mapping.cpp | alexiynew/nih_framework | a65335586331daa0ece892f98265bd1d2f8f579f | [
"MIT"
] | 32 | 2017-02-02T14:49:41.000Z | 2019-06-25T19:38:27.000Z | neutrino/graphics/src/font/tables/character_to_glyph_index_mapping.cpp | alexiynew/nih_framework | a65335586331daa0ece892f98265bd1d2f8f579f | [
"MIT"
] | null | null | null | #include <set>
#include <common/exceptions.hpp>
#include <common/utils.hpp>
#include <graphics/src/font/tables/character_to_glyph_index_mapping.hpp>
namespace
{
namespace utils = framework::utils;
namespace details = framework::graphics::details::font;
using details::BufferReader;
using details::BytesData;
using details::CharacterToGlyphIndexMapping;
using details::CodePoint;
using details::GlyphId;
using details::PlatformId;
using framework::NotImplementedError;
struct EncodingRecord
{
PlatformId platform_id = PlatformId::Undefined;
std::uint16_t encoding_id = 0;
std::uint32_t offset = 0; // Byte offset from beginning of table to the subtable for this encoding.
};
#pragma region SubtableFormat4
class SubtableFormat4 final : public CharacterToGlyphIndexMapping::Subtable
{
public:
void parse(std::uint32_t offset, const BytesData& data) override;
GlyphId glyph_index(CodePoint codepoint) const override;
bool valid() const override;
std::unique_ptr<Subtable> copy() const override;
private:
std::uint16_t m_format = 0;
std::uint16_t m_length = 0;
std::uint16_t m_language = 0;
std::uint16_t m_seg_count_x2 = 0;
std::uint16_t m_search_range = 0;
std::uint16_t m_entry_selector = 0;
std::uint16_t m_range_shift = 0;
std::vector<std::uint16_t> m_end_code; //[segcount]
std::uint16_t m_reserved_pad = 0;
std::vector<std::uint16_t> m_start_code; //[segcount]
std::vector<std::int16_t> m_id_delta; //[segcount]
std::vector<std::uint16_t> m_id_range_offset; //[segcount]
std::vector<std::uint16_t> m_glyph_id_array;
};
void SubtableFormat4::parse(std::uint32_t offset, const BytesData& data)
{
const auto from = std::next(data.begin(), offset);
BufferReader in = utils::make_big_endian_buffer_reader(from, data.end());
in >> m_format;
in >> m_length;
in >> m_language;
in >> m_seg_count_x2;
in >> m_search_range;
in >> m_entry_selector;
in >> m_range_shift;
const size_t seg_count = m_seg_count_x2 / 2;
m_end_code.reserve(seg_count);
for (size_t i = 0; i < seg_count; ++i) {
m_end_code.push_back(in.get<std::uint16_t>());
}
in >> m_reserved_pad;
m_start_code.reserve(seg_count);
for (size_t i = 0; i < seg_count; ++i) {
m_start_code.push_back(in.get<std::uint16_t>());
}
m_id_delta.reserve(seg_count);
for (size_t i = 0; i < seg_count; ++i) {
m_id_delta.push_back(in.get<std::int16_t>());
}
m_id_range_offset.reserve(seg_count);
for (size_t i = 0; i < seg_count; ++i) {
m_id_range_offset.push_back(in.get<std::uint16_t>());
}
const auto begin = in.current();
const auto end = std::next(in.begin(), m_length);
const size_t glyph_id_array_size = static_cast<size_t>(std::distance(begin, end) / 2);
if (glyph_id_array_size > 0) {
m_glyph_id_array.reserve(glyph_id_array_size);
for (BufferReader glyph_ids_reader = utils::make_big_endian_buffer_reader(begin, end); glyph_ids_reader;) {
m_glyph_id_array.push_back(glyph_ids_reader.get<std::uint16_t>());
}
}
}
GlyphId SubtableFormat4::glyph_index(CodePoint codepoint) const
{
auto it = std::lower_bound(m_end_code.begin(), m_end_code.end(), codepoint);
if (it == m_end_code.end()) {
return details::missig_glyph_id;
}
const std::uint16_t seg_count = m_seg_count_x2 / 2;
const std::uint16_t segment_index = static_cast<std::uint16_t>(std::distance(m_end_code.begin(), it));
const std::uint16_t start_code = m_start_code[segment_index];
const std::uint16_t range_offset = m_id_range_offset[segment_index];
const std::int16_t id_delta = m_id_delta[segment_index];
if (start_code > codepoint) {
return details::missig_glyph_id;
}
if (range_offset == 0) {
return static_cast<GlyphId>((static_cast<std::int32_t>(codepoint) + id_delta) & 0xffff);
}
// glyphId = *(idRangeOffset[i]/2
// + (c - startCode[i])
// + &idRangeOffset[i])
const std::uint16_t offset_to_the_end_of_range_offsets = seg_count - segment_index;
// idRangeOffset[i]/2 + + &idRangeOffset[i]
const std::uint16_t offset_in_glyph_id_array = range_offset / 2 - offset_to_the_end_of_range_offsets;
// (c - startCode[i])
const auto start_code_offset = static_cast<std::uint16_t>(codepoint - start_code);
// glyphId = *(idRangeOffset[i]/2 + (c - startCode[i]) + &idRangeOffset[i])
const std::uint16_t glyph_id_index = offset_in_glyph_id_array + start_code_offset;
if (glyph_id_index > m_glyph_id_array.size()) {
return details::missig_glyph_id;
}
const std::uint16_t glyph_id = m_glyph_id_array[glyph_id_index];
if (glyph_id == 0) {
return details::missig_glyph_id;
}
return static_cast<GlyphId>((static_cast<std::int32_t>(glyph_id) + id_delta) & 0xffff);
}
bool SubtableFormat4::valid() const
{
const size_t seg_count = m_seg_count_x2 / 2;
const bool table_sizes_valid = m_format == 4 && m_end_code.size() == seg_count &&
m_start_code.size() == seg_count && m_id_delta.size() == seg_count &&
m_id_range_offset.size() == seg_count;
const bool offsets_valid = !m_glyph_id_array.empty() || std::all_of(m_id_range_offset.begin(),
m_id_range_offset.end(),
[](std::uint16_t o) { return o == 0; });
return table_sizes_valid && offsets_valid;
}
std::unique_ptr<CharacterToGlyphIndexMapping::Subtable> SubtableFormat4::copy() const
{
return std::make_unique<SubtableFormat4>(*this);
}
#pragma endregion
#pragma region SubtableFormat6
class SubtableFormat6 final : public CharacterToGlyphIndexMapping::Subtable
{
public:
void parse(std::uint32_t offset, const BytesData& data) override;
GlyphId glyph_index(CodePoint codepoint) const override;
bool valid() const override;
std::unique_ptr<Subtable> copy() const override;
private:
// std::uint16_t m_format = 0;
// std::uint16_t m_length = 0;
// std::uint16_t m_language = 0;
// std::uint16_t m_first_code = 0;
// std::uint16_t m_entry_count = 0;
// std::vector<std::uint16_t> m_glyph_id_array; //[entrycount]
};
void SubtableFormat6::parse(std::uint32_t, const BytesData&)
{
throw NotImplementedError("SubtableFormat6 parsing is not implemented yet");
}
GlyphId SubtableFormat6::glyph_index(CodePoint) const
{
throw NotImplementedError("SubtableFormat6 glyph_index is not implemented yet");
}
bool SubtableFormat6::valid() const
{
return false;
}
std::unique_ptr<CharacterToGlyphIndexMapping::Subtable> SubtableFormat6::copy() const
{
return std::make_unique<SubtableFormat6>(*this);
}
#pragma endregion
#pragma region SubtableFormat10
class SubtableFormat10 final : public CharacterToGlyphIndexMapping::Subtable
{
public:
void parse(std::uint32_t offset, const BytesData& data) override;
GlyphId glyph_index(CodePoint codepoint) const override;
bool valid() const override;
std::unique_ptr<Subtable> copy() const override;
};
void SubtableFormat10::parse(std::uint32_t, const BytesData&)
{
throw NotImplementedError("SubtableFormat10 parsing is not implemented yet");
}
GlyphId SubtableFormat10::glyph_index(CodePoint) const
{
throw NotImplementedError("SubtableFormat10 glyph_index is not implemented yet");
}
bool SubtableFormat10::valid() const
{
return false;
}
std::unique_ptr<CharacterToGlyphIndexMapping::Subtable> SubtableFormat10::copy() const
{
return std::make_unique<SubtableFormat10>(*this);
}
#pragma endregion
#pragma region SubtableFormat12
class SubtableFormat12 final : public CharacterToGlyphIndexMapping::Subtable
{
public:
void parse(std::uint32_t offset, const BytesData& data) override;
GlyphId glyph_index(CodePoint codepoint) const override;
bool valid() const override;
std::unique_ptr<Subtable> copy() const override;
};
void SubtableFormat12::parse(std::uint32_t, const BytesData&)
{
throw NotImplementedError("SubtableFormat12 parsing is not implemented yet");
}
GlyphId SubtableFormat12::glyph_index(CodePoint) const
{
throw NotImplementedError("SubtableFormat12 glyph_index is not implemented yet");
}
bool SubtableFormat12::valid() const
{
return false;
}
std::unique_ptr<CharacterToGlyphIndexMapping::Subtable> SubtableFormat12::copy() const
{
return std::make_unique<SubtableFormat12>(*this);
}
#pragma endregion
#pragma region SubtableFormat13
class SubtableFormat13 final : public CharacterToGlyphIndexMapping::Subtable
{
public:
void parse(std::uint32_t offset, const BytesData& data) override;
GlyphId glyph_index(CodePoint codepoint) const override;
bool valid() const override;
std::unique_ptr<Subtable> copy() const override;
};
void SubtableFormat13::parse(std::uint32_t, const BytesData&)
{
throw NotImplementedError("SubtableFormat13 parsing is not implemented yet");
}
GlyphId SubtableFormat13::glyph_index(CodePoint) const
{
throw NotImplementedError("SubtableFormat13 glyph_index is not implemented yet");
}
bool SubtableFormat13::valid() const
{
return false;
}
std::unique_ptr<CharacterToGlyphIndexMapping::Subtable> SubtableFormat13::copy() const
{
return std::make_unique<SubtableFormat13>(*this);
}
#pragma endregion
#pragma region SubtableFormat14
class SubtableFormat14 final : public CharacterToGlyphIndexMapping::Subtable
{
public:
void parse(std::uint32_t offset, const BytesData& data) override;
GlyphId glyph_index(CodePoint codepoint) const override;
bool valid() const override;
std::unique_ptr<Subtable> copy() const override;
};
void SubtableFormat14::parse(std::uint32_t, const BytesData&)
{
throw NotImplementedError("SubtableFormat14 parsing is not implemented yet");
}
GlyphId SubtableFormat14::glyph_index(CodePoint) const
{
throw NotImplementedError("SubtableFormat14 glyph_index is not implemented yet");
}
bool SubtableFormat14::valid() const
{
return false;
}
std::unique_ptr<CharacterToGlyphIndexMapping::Subtable> SubtableFormat14::copy() const
{
return std::make_unique<SubtableFormat14>(*this);
}
#pragma endregion
#pragma region Helper functions
std::vector<EncodingRecord> get_encoding_records(std::uint32_t offset, size_t num_tables, const BytesData& data)
{
static constexpr size_t record_size = 8;
std::vector<EncodingRecord> encoding_records;
encoding_records.reserve(num_tables);
auto from = std::next(data.begin(), offset);
for (size_t i = 0; i < num_tables; ++i) {
EncodingRecord record;
record.platform_id = utils::big_endian_value<PlatformId>(from);
record.encoding_id = utils::big_endian_value<std::uint16_t>(from + 2);
record.offset = utils::big_endian_value<std::uint32_t>(from + 4);
encoding_records.push_back(record);
std::advance(from, record_size);
}
return encoding_records;
}
std::vector<EncodingRecord> find_unicode_encoding_records(const std::vector<EncodingRecord>& encoding_records)
{
using framework::graphics::details::font::PlatformId;
auto is_unicode = [](const EncodingRecord& record) {
constexpr static std::array<std::uint16_t, 4> supported_encoding_ids = {3, 4, 5, 6};
const bool supported_encoding = std::find(supported_encoding_ids.begin(),
supported_encoding_ids.end(),
record.encoding_id) != supported_encoding_ids.end();
return record.platform_id == PlatformId::Unicode && supported_encoding;
};
std::vector<EncodingRecord> unicode_records;
std::copy_if(encoding_records.begin(), encoding_records.end(), std::back_inserter(unicode_records), is_unicode);
return unicode_records;
}
std::unique_ptr<CharacterToGlyphIndexMapping::Subtable> parse_subtable(
const std::vector<EncodingRecord>& encoding_records,
const BytesData& data)
{
auto create_subtable = [](std::uint16_t format) -> std::unique_ptr<CharacterToGlyphIndexMapping::Subtable> {
switch (format) {
case 4: return std::make_unique<SubtableFormat4>();
case 6: return std::make_unique<SubtableFormat6>();
case 10: return std::make_unique<SubtableFormat10>();
case 12: return std::make_unique<SubtableFormat12>();
case 13: return std::make_unique<SubtableFormat13>();
case 14: return std::make_unique<SubtableFormat14>();
}
return nullptr;
};
for (const auto& record : encoding_records) {
const auto from = std::next(data.begin(), record.offset);
std::uint16_t format = utils::big_endian_value<std::uint16_t>(from);
auto subtable = create_subtable(format);
if (subtable) {
subtable->parse(record.offset, data);
return subtable;
}
}
return nullptr;
}
#pragma endregion
} // namespace
namespace framework::graphics::details::font
{
CharacterToGlyphIndexMapping::CharacterToGlyphIndexMapping(const BytesData& data)
{
const std::uint16_t version = utils::big_endian_value<std::uint16_t>(data.begin());
const std::uint16_t num_tables = utils::big_endian_value<std::uint16_t>(data.begin() + 2);
const std::vector<EncodingRecord> encoding_records = get_encoding_records(4, num_tables, data);
const std::vector<EncodingRecord> unicode_encoding_records = find_unicode_encoding_records(encoding_records);
if (unicode_encoding_records.empty()) {
throw UnsupportedError("Can't find unicode encoding records");
}
m_version = version;
m_subtable = parse_subtable(unicode_encoding_records, data);
}
CharacterToGlyphIndexMapping::CharacterToGlyphIndexMapping(const CharacterToGlyphIndexMapping& other)
: m_version(other.m_version)
, m_subtable(other.m_subtable->copy())
{}
CharacterToGlyphIndexMapping& CharacterToGlyphIndexMapping::operator=(const CharacterToGlyphIndexMapping& other)
{
using std::swap;
CharacterToGlyphIndexMapping tmp(other);
swap(tmp.m_version, m_version);
swap(tmp.m_subtable, m_subtable);
return *this;
}
bool CharacterToGlyphIndexMapping::valid() const
{
return m_version == 0 && m_subtable != nullptr && m_subtable->valid();
}
GlyphId CharacterToGlyphIndexMapping::glyph_index(CodePoint codepoint) const
{
if (m_subtable) {
return m_subtable->glyph_index(codepoint);
}
return missig_glyph_id;
}
} // namespace framework::graphics::details::font
| 30.755694 | 116 | 0.699966 | [
"vector"
] |
b3791723e95c65ad27b0ed1f68a77c290a06855c | 87,192 | cpp | C++ | Unity-Project/App-HL2/Il2CppOutputProject/Source/il2cppOutput/Microsoft.MixedReality.Toolkit.Gltf_Attr.cpp | JBrentJ/mslearn-mixed-reality-and-azure-digital-twins-in-unity | 6e13b31a0b053443b9c93267d8f174f1554e79dd | [
"CC-BY-4.0",
"MIT"
] | 1 | 2021-06-01T19:33:53.000Z | 2021-06-01T19:33:53.000Z | Unity-Project/App-HL2/Il2CppOutputProject/Source/il2cppOutput/Microsoft.MixedReality.Toolkit.Gltf_Attr.cpp | JBrentJ/mslearn-mixed-reality-and-azure-digital-twins-in-unity | 6e13b31a0b053443b9c93267d8f174f1554e79dd | [
"CC-BY-4.0",
"MIT"
] | null | null | null | Unity-Project/App-HL2/Il2CppOutputProject/Source/il2cppOutput/Microsoft.MixedReality.Toolkit.Gltf_Attr.cpp | JBrentJ/mslearn-mixed-reality-and-azure-digital-twins-in-unity | 6e13b31a0b053443b9c93267d8f174f1554e79dd | [
"CC-BY-4.0",
"MIT"
] | null | null | null | #include "pch-cpp.hpp"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <limits>
#include <stdint.h>
// System.Char[]
struct CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34;
// System.Type[]
struct TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755;
// System.Runtime.CompilerServices.AsyncStateMachineAttribute
struct AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6;
// System.Reflection.Binder
struct Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30;
// System.Runtime.CompilerServices.CompilationRelaxationsAttribute
struct CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF;
// System.Runtime.CompilerServices.CompilerGeneratedAttribute
struct CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C;
// System.Diagnostics.DebuggableAttribute
struct DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B;
// System.Diagnostics.DebuggerHiddenAttribute
struct DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88;
// System.Runtime.CompilerServices.ExtensionAttribute
struct ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC;
// System.Runtime.CompilerServices.InternalsVisibleToAttribute
struct InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C;
// System.Reflection.MemberFilter
struct MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81;
// System.Runtime.CompilerServices.RuntimeCompatibilityAttribute
struct RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80;
// UnityEngine.SerializeField
struct SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25;
// System.String
struct String_t;
// System.Type
struct Type_t;
// System.Void
struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5;
IL2CPP_EXTERN_C const RuntimeType* U3CConstructAsyncU3Ed__19_t2CEBB449CCB1AC8F210D3036C331C51331107531_0_0_0_var;
IL2CPP_EXTERN_C const RuntimeType* U3CConstructMaterialAsyncU3Ed__22_tE4FE45B75E7B9D6414C3D9AB5C48E08C062131CA_0_0_0_var;
IL2CPP_EXTERN_C const RuntimeType* U3CConstructMeshAsyncU3Ed__27_t64D05762DC351830A551BCADA3E0FA5B3F1D518E_0_0_0_var;
IL2CPP_EXTERN_C const RuntimeType* U3CConstructMeshPrimitiveAsyncU3Ed__28_tA958F7C69894685E245BE2E70ACC328D7A24B186_0_0_0_var;
IL2CPP_EXTERN_C const RuntimeType* U3CConstructNodeAsyncU3Ed__26_tBC58C69D6F3538087AE893C5A97482C1E4254C21_0_0_0_var;
IL2CPP_EXTERN_C const RuntimeType* U3CConstructSceneAsyncU3Ed__25_t233186A16E43DAF0312FAE42938228273A25B0CB_0_0_0_var;
IL2CPP_EXTERN_C const RuntimeType* U3CConstructTextureAsyncU3Ed__21_tEF4B03242DD3E5D2E8E8B69D6681CCC87389720A_0_0_0_var;
IL2CPP_EXTERN_C const RuntimeType* U3CCreateMRTKShaderMaterialU3Ed__23_t0FD867448D76F96B3F706AC8E21E9AB5794F6757_0_0_0_var;
IL2CPP_EXTERN_C const RuntimeType* U3CCreateStandardShaderMaterialU3Ed__24_t2ABF29742A69220D0B9FC29D5C9BF1B79E834FE9_0_0_0_var;
IL2CPP_EXTERN_C_BEGIN
IL2CPP_EXTERN_C_END
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
// System.Attribute
struct Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 : public RuntimeObject
{
public:
public:
};
// System.Reflection.MemberInfo
struct MemberInfo_t : public RuntimeObject
{
public:
public:
};
// System.String
struct String_t : public RuntimeObject
{
public:
// System.Int32 System.String::m_stringLength
int32_t ___m_stringLength_0;
// System.Char System.String::m_firstChar
Il2CppChar ___m_firstChar_1;
public:
inline static int32_t get_offset_of_m_stringLength_0() { return static_cast<int32_t>(offsetof(String_t, ___m_stringLength_0)); }
inline int32_t get_m_stringLength_0() const { return ___m_stringLength_0; }
inline int32_t* get_address_of_m_stringLength_0() { return &___m_stringLength_0; }
inline void set_m_stringLength_0(int32_t value)
{
___m_stringLength_0 = value;
}
inline static int32_t get_offset_of_m_firstChar_1() { return static_cast<int32_t>(offsetof(String_t, ___m_firstChar_1)); }
inline Il2CppChar get_m_firstChar_1() const { return ___m_firstChar_1; }
inline Il2CppChar* get_address_of_m_firstChar_1() { return &___m_firstChar_1; }
inline void set_m_firstChar_1(Il2CppChar value)
{
___m_firstChar_1 = value;
}
};
struct String_t_StaticFields
{
public:
// System.String System.String::Empty
String_t* ___Empty_5;
public:
inline static int32_t get_offset_of_Empty_5() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_5)); }
inline String_t* get_Empty_5() const { return ___Empty_5; }
inline String_t** get_address_of_Empty_5() { return &___Empty_5; }
inline void set_Empty_5(String_t* value)
{
___Empty_5 = value;
Il2CppCodeGenWriteBarrier((void**)(&___Empty_5), (void*)value);
}
};
// System.ValueType
struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52 : public RuntimeObject
{
public:
public:
};
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_com
{
};
// System.Boolean
struct Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37
{
public:
// System.Boolean System.Boolean::m_value
bool ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37, ___m_value_0)); }
inline bool get_m_value_0() const { return ___m_value_0; }
inline bool* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(bool value)
{
___m_value_0 = value;
}
};
struct Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields
{
public:
// System.String System.Boolean::TrueString
String_t* ___TrueString_5;
// System.String System.Boolean::FalseString
String_t* ___FalseString_6;
public:
inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields, ___TrueString_5)); }
inline String_t* get_TrueString_5() const { return ___TrueString_5; }
inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; }
inline void set_TrueString_5(String_t* value)
{
___TrueString_5 = value;
Il2CppCodeGenWriteBarrier((void**)(&___TrueString_5), (void*)value);
}
inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields, ___FalseString_6)); }
inline String_t* get_FalseString_6() const { return ___FalseString_6; }
inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; }
inline void set_FalseString_6(String_t* value)
{
___FalseString_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___FalseString_6), (void*)value);
}
};
// System.Runtime.CompilerServices.CompilationRelaxationsAttribute
struct CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
// System.Int32 System.Runtime.CompilerServices.CompilationRelaxationsAttribute::m_relaxations
int32_t ___m_relaxations_0;
public:
inline static int32_t get_offset_of_m_relaxations_0() { return static_cast<int32_t>(offsetof(CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF, ___m_relaxations_0)); }
inline int32_t get_m_relaxations_0() const { return ___m_relaxations_0; }
inline int32_t* get_address_of_m_relaxations_0() { return &___m_relaxations_0; }
inline void set_m_relaxations_0(int32_t value)
{
___m_relaxations_0 = value;
}
};
// System.Runtime.CompilerServices.CompilerGeneratedAttribute
struct CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
public:
};
// System.Diagnostics.DebuggerHiddenAttribute
struct DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
public:
};
// System.Enum
struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA : public ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52
{
public:
public:
};
struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_StaticFields
{
public:
// System.Char[] System.Enum::enumSeperatorCharArray
CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* ___enumSeperatorCharArray_0;
public:
inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t23B90B40F60E677A8025267341651C94AE079CDA_StaticFields, ___enumSeperatorCharArray_0)); }
inline CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; }
inline CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; }
inline void set_enumSeperatorCharArray_0(CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* value)
{
___enumSeperatorCharArray_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___enumSeperatorCharArray_0), (void*)value);
}
};
// Native definition for P/Invoke marshalling of System.Enum
struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.Enum
struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_marshaled_com
{
};
// System.Runtime.CompilerServices.ExtensionAttribute
struct ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
public:
};
// System.IntPtr
struct IntPtr_t
{
public:
// System.Void* System.IntPtr::m_value
void* ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }
inline void* get_m_value_0() const { return ___m_value_0; }
inline void** get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(void* value)
{
___m_value_0 = value;
}
};
struct IntPtr_t_StaticFields
{
public:
// System.IntPtr System.IntPtr::Zero
intptr_t ___Zero_1;
public:
inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }
inline intptr_t get_Zero_1() const { return ___Zero_1; }
inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }
inline void set_Zero_1(intptr_t value)
{
___Zero_1 = value;
}
};
// System.Runtime.CompilerServices.InternalsVisibleToAttribute
struct InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
// System.String System.Runtime.CompilerServices.InternalsVisibleToAttribute::_assemblyName
String_t* ____assemblyName_0;
// System.Boolean System.Runtime.CompilerServices.InternalsVisibleToAttribute::_allInternalsVisible
bool ____allInternalsVisible_1;
public:
inline static int32_t get_offset_of__assemblyName_0() { return static_cast<int32_t>(offsetof(InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C, ____assemblyName_0)); }
inline String_t* get__assemblyName_0() const { return ____assemblyName_0; }
inline String_t** get_address_of__assemblyName_0() { return &____assemblyName_0; }
inline void set__assemblyName_0(String_t* value)
{
____assemblyName_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&____assemblyName_0), (void*)value);
}
inline static int32_t get_offset_of__allInternalsVisible_1() { return static_cast<int32_t>(offsetof(InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C, ____allInternalsVisible_1)); }
inline bool get__allInternalsVisible_1() const { return ____allInternalsVisible_1; }
inline bool* get_address_of__allInternalsVisible_1() { return &____allInternalsVisible_1; }
inline void set__allInternalsVisible_1(bool value)
{
____allInternalsVisible_1 = value;
}
};
// System.Runtime.CompilerServices.RuntimeCompatibilityAttribute
struct RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
// System.Boolean System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::m_wrapNonExceptionThrows
bool ___m_wrapNonExceptionThrows_0;
public:
inline static int32_t get_offset_of_m_wrapNonExceptionThrows_0() { return static_cast<int32_t>(offsetof(RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80, ___m_wrapNonExceptionThrows_0)); }
inline bool get_m_wrapNonExceptionThrows_0() const { return ___m_wrapNonExceptionThrows_0; }
inline bool* get_address_of_m_wrapNonExceptionThrows_0() { return &___m_wrapNonExceptionThrows_0; }
inline void set_m_wrapNonExceptionThrows_0(bool value)
{
___m_wrapNonExceptionThrows_0 = value;
}
};
// UnityEngine.SerializeField
struct SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
public:
};
// System.Runtime.CompilerServices.StateMachineAttribute
struct StateMachineAttribute_tA6E77C77F821508E405473BA1C4C08A69FDA0AC3 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
// System.Type System.Runtime.CompilerServices.StateMachineAttribute::<StateMachineType>k__BackingField
Type_t * ___U3CStateMachineTypeU3Ek__BackingField_0;
public:
inline static int32_t get_offset_of_U3CStateMachineTypeU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(StateMachineAttribute_tA6E77C77F821508E405473BA1C4C08A69FDA0AC3, ___U3CStateMachineTypeU3Ek__BackingField_0)); }
inline Type_t * get_U3CStateMachineTypeU3Ek__BackingField_0() const { return ___U3CStateMachineTypeU3Ek__BackingField_0; }
inline Type_t ** get_address_of_U3CStateMachineTypeU3Ek__BackingField_0() { return &___U3CStateMachineTypeU3Ek__BackingField_0; }
inline void set_U3CStateMachineTypeU3Ek__BackingField_0(Type_t * value)
{
___U3CStateMachineTypeU3Ek__BackingField_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___U3CStateMachineTypeU3Ek__BackingField_0), (void*)value);
}
};
// System.Void
struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5
{
public:
union
{
struct
{
};
uint8_t Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5__padding[1];
};
public:
};
// System.Runtime.CompilerServices.AsyncStateMachineAttribute
struct AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 : public StateMachineAttribute_tA6E77C77F821508E405473BA1C4C08A69FDA0AC3
{
public:
public:
};
// System.Reflection.BindingFlags
struct BindingFlags_tAAAB07D9AC588F0D55D844E51D7035E96DF94733
{
public:
// System.Int32 System.Reflection.BindingFlags::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(BindingFlags_tAAAB07D9AC588F0D55D844E51D7035E96DF94733, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
// System.RuntimeTypeHandle
struct RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9
{
public:
// System.IntPtr System.RuntimeTypeHandle::value
intptr_t ___value_0;
public:
inline static int32_t get_offset_of_value_0() { return static_cast<int32_t>(offsetof(RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9, ___value_0)); }
inline intptr_t get_value_0() const { return ___value_0; }
inline intptr_t* get_address_of_value_0() { return &___value_0; }
inline void set_value_0(intptr_t value)
{
___value_0 = value;
}
};
// System.Diagnostics.DebuggableAttribute/DebuggingModes
struct DebuggingModes_t279D5B9C012ABA935887CB73C5A63A1F46AF08A8
{
public:
// System.Int32 System.Diagnostics.DebuggableAttribute/DebuggingModes::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(DebuggingModes_t279D5B9C012ABA935887CB73C5A63A1F46AF08A8, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
// System.Diagnostics.DebuggableAttribute
struct DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
// System.Diagnostics.DebuggableAttribute/DebuggingModes System.Diagnostics.DebuggableAttribute::m_debuggingModes
int32_t ___m_debuggingModes_0;
public:
inline static int32_t get_offset_of_m_debuggingModes_0() { return static_cast<int32_t>(offsetof(DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B, ___m_debuggingModes_0)); }
inline int32_t get_m_debuggingModes_0() const { return ___m_debuggingModes_0; }
inline int32_t* get_address_of_m_debuggingModes_0() { return &___m_debuggingModes_0; }
inline void set_m_debuggingModes_0(int32_t value)
{
___m_debuggingModes_0 = value;
}
};
// System.Type
struct Type_t : public MemberInfo_t
{
public:
// System.RuntimeTypeHandle System.Type::_impl
RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 ____impl_9;
public:
inline static int32_t get_offset_of__impl_9() { return static_cast<int32_t>(offsetof(Type_t, ____impl_9)); }
inline RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 get__impl_9() const { return ____impl_9; }
inline RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 * get_address_of__impl_9() { return &____impl_9; }
inline void set__impl_9(RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 value)
{
____impl_9 = value;
}
};
struct Type_t_StaticFields
{
public:
// System.Reflection.MemberFilter System.Type::FilterAttribute
MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * ___FilterAttribute_0;
// System.Reflection.MemberFilter System.Type::FilterName
MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * ___FilterName_1;
// System.Reflection.MemberFilter System.Type::FilterNameIgnoreCase
MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * ___FilterNameIgnoreCase_2;
// System.Object System.Type::Missing
RuntimeObject * ___Missing_3;
// System.Char System.Type::Delimiter
Il2CppChar ___Delimiter_4;
// System.Type[] System.Type::EmptyTypes
TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755* ___EmptyTypes_5;
// System.Reflection.Binder System.Type::defaultBinder
Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30 * ___defaultBinder_6;
public:
inline static int32_t get_offset_of_FilterAttribute_0() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterAttribute_0)); }
inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * get_FilterAttribute_0() const { return ___FilterAttribute_0; }
inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 ** get_address_of_FilterAttribute_0() { return &___FilterAttribute_0; }
inline void set_FilterAttribute_0(MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * value)
{
___FilterAttribute_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___FilterAttribute_0), (void*)value);
}
inline static int32_t get_offset_of_FilterName_1() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterName_1)); }
inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * get_FilterName_1() const { return ___FilterName_1; }
inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 ** get_address_of_FilterName_1() { return &___FilterName_1; }
inline void set_FilterName_1(MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * value)
{
___FilterName_1 = value;
Il2CppCodeGenWriteBarrier((void**)(&___FilterName_1), (void*)value);
}
inline static int32_t get_offset_of_FilterNameIgnoreCase_2() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterNameIgnoreCase_2)); }
inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * get_FilterNameIgnoreCase_2() const { return ___FilterNameIgnoreCase_2; }
inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 ** get_address_of_FilterNameIgnoreCase_2() { return &___FilterNameIgnoreCase_2; }
inline void set_FilterNameIgnoreCase_2(MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * value)
{
___FilterNameIgnoreCase_2 = value;
Il2CppCodeGenWriteBarrier((void**)(&___FilterNameIgnoreCase_2), (void*)value);
}
inline static int32_t get_offset_of_Missing_3() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___Missing_3)); }
inline RuntimeObject * get_Missing_3() const { return ___Missing_3; }
inline RuntimeObject ** get_address_of_Missing_3() { return &___Missing_3; }
inline void set_Missing_3(RuntimeObject * value)
{
___Missing_3 = value;
Il2CppCodeGenWriteBarrier((void**)(&___Missing_3), (void*)value);
}
inline static int32_t get_offset_of_Delimiter_4() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___Delimiter_4)); }
inline Il2CppChar get_Delimiter_4() const { return ___Delimiter_4; }
inline Il2CppChar* get_address_of_Delimiter_4() { return &___Delimiter_4; }
inline void set_Delimiter_4(Il2CppChar value)
{
___Delimiter_4 = value;
}
inline static int32_t get_offset_of_EmptyTypes_5() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___EmptyTypes_5)); }
inline TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755* get_EmptyTypes_5() const { return ___EmptyTypes_5; }
inline TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755** get_address_of_EmptyTypes_5() { return &___EmptyTypes_5; }
inline void set_EmptyTypes_5(TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755* value)
{
___EmptyTypes_5 = value;
Il2CppCodeGenWriteBarrier((void**)(&___EmptyTypes_5), (void*)value);
}
inline static int32_t get_offset_of_defaultBinder_6() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___defaultBinder_6)); }
inline Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30 * get_defaultBinder_6() const { return ___defaultBinder_6; }
inline Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30 ** get_address_of_defaultBinder_6() { return &___defaultBinder_6; }
inline void set_defaultBinder_6(Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30 * value)
{
___defaultBinder_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___defaultBinder_6), (void*)value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// System.Void System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void CompilationRelaxationsAttribute__ctor_mAC3079EBC4EEAB474EED8208EF95DB39C922333B (CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF * __this, int32_t ___relaxations0, const RuntimeMethod* method);
// System.Void System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(System.String)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void InternalsVisibleToAttribute__ctor_m420071A75DCEEC72356490C64B4B0B9270DA32B9 (InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C * __this, String_t* ___assemblyName0, const RuntimeMethod* method);
// System.Void System.Runtime.CompilerServices.ExtensionAttribute::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * __this, const RuntimeMethod* method);
// System.Void System.Diagnostics.DebuggableAttribute::.ctor(System.Diagnostics.DebuggableAttribute/DebuggingModes)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void DebuggableAttribute__ctor_m7FF445C8435494A4847123A668D889E692E55550 (DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B * __this, int32_t ___modes0, const RuntimeMethod* method);
// System.Void System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void RuntimeCompatibilityAttribute__ctor_m551DDF1438CE97A984571949723F30F44CF7317C (RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 * __this, const RuntimeMethod* method);
// System.Void System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::set_WrapNonExceptionThrows(System.Boolean)
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void RuntimeCompatibilityAttribute_set_WrapNonExceptionThrows_m8562196F90F3EBCEC23B5708EE0332842883C490_inline (RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 * __this, bool ___value0, const RuntimeMethod* method);
// System.Void System.Runtime.CompilerServices.AsyncStateMachineAttribute::.ctor(System.Type)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * __this, Type_t * ___stateMachineType0, const RuntimeMethod* method);
// System.Void System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35 (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * __this, const RuntimeMethod* method);
// System.Void System.Diagnostics.DebuggerHiddenAttribute::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3 (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * __this, const RuntimeMethod* method);
// System.Void UnityEngine.SerializeField::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3 (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * __this, const RuntimeMethod* method);
static void Microsoft_MixedReality_Toolkit_Gltf_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF * tmp = (CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF *)cache->attributes[0];
CompilationRelaxationsAttribute__ctor_mAC3079EBC4EEAB474EED8208EF95DB39C922333B(tmp, 8LL, NULL);
}
{
InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C * tmp = (InternalsVisibleToAttribute_t1D9772A02892BAC440952F880A43C257E6C3E68C *)cache->attributes[1];
InternalsVisibleToAttribute__ctor_m420071A75DCEEC72356490C64B4B0B9270DA32B9(tmp, il2cpp_codegen_string_new_wrapper("\x4D\x69\x63\x72\x6F\x73\x6F\x66\x74\x2E\x4D\x69\x78\x65\x64\x52\x65\x61\x6C\x69\x74\x79\x2E\x54\x6F\x6F\x6C\x6B\x69\x74\x2E\x47\x6C\x74\x66\x2E\x49\x6D\x70\x6F\x72\x74\x65\x72\x73"), NULL);
}
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[2];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
{
DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B * tmp = (DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B *)cache->attributes[3];
DebuggableAttribute__ctor_m7FF445C8435494A4847123A668D889E692E55550(tmp, 2LL, NULL);
}
{
RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 * tmp = (RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 *)cache->attributes[4];
RuntimeCompatibilityAttribute__ctor_m551DDF1438CE97A984571949723F30F44CF7317C(tmp, NULL);
RuntimeCompatibilityAttribute_set_WrapNonExceptionThrows_m8562196F90F3EBCEC23B5708EE0332842883C490_inline(tmp, true, NULL);
}
}
static void ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructAsync_m1C52A32415C37E949AD6C4A5FDA17DDA0F2ADAFC(CustomAttributesCache* cache)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CConstructAsyncU3Ed__19_t2CEBB449CCB1AC8F210D3036C331C51331107531_0_0_0_var);
s_Il2CppMethodInitialized = true;
}
{
AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[0];
AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CConstructAsyncU3Ed__19_t2CEBB449CCB1AC8F210D3036C331C51331107531_0_0_0_var), NULL);
}
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[1];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructBufferView_m0168DB9CDB07F6FC97EE3A06788BCA1D598A81BB(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructTextureAsync_mB47AF294D372ED12B04A2D1F86F9985454478140(CustomAttributesCache* cache)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CConstructTextureAsyncU3Ed__21_tEF4B03242DD3E5D2E8E8B69D6681CCC87389720A_0_0_0_var);
s_Il2CppMethodInitialized = true;
}
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
{
AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[1];
AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CConstructTextureAsyncU3Ed__21_tEF4B03242DD3E5D2E8E8B69D6681CCC87389720A_0_0_0_var), NULL);
}
}
static void ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructMaterialAsync_m91FA494C83A557F9777804D80CF10029E590A99A(CustomAttributesCache* cache)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CConstructMaterialAsyncU3Ed__22_tE4FE45B75E7B9D6414C3D9AB5C48E08C062131CA_0_0_0_var);
s_Il2CppMethodInitialized = true;
}
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
{
AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[1];
AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CConstructMaterialAsyncU3Ed__22_tE4FE45B75E7B9D6414C3D9AB5C48E08C062131CA_0_0_0_var), NULL);
}
}
static void ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_CreateMRTKShaderMaterial_mAD27679B68956F7A306AA11302ED7B9743F0838C(CustomAttributesCache* cache)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CCreateMRTKShaderMaterialU3Ed__23_t0FD867448D76F96B3F706AC8E21E9AB5794F6757_0_0_0_var);
s_Il2CppMethodInitialized = true;
}
{
AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[0];
AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CCreateMRTKShaderMaterialU3Ed__23_t0FD867448D76F96B3F706AC8E21E9AB5794F6757_0_0_0_var), NULL);
}
}
static void ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_CreateStandardShaderMaterial_m948E20DCA6986A23A63A9B3463D57A1A1B4D129C(CustomAttributesCache* cache)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CCreateStandardShaderMaterialU3Ed__24_t2ABF29742A69220D0B9FC29D5C9BF1B79E834FE9_0_0_0_var);
s_Il2CppMethodInitialized = true;
}
{
AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[0];
AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CCreateStandardShaderMaterialU3Ed__24_t2ABF29742A69220D0B9FC29D5C9BF1B79E834FE9_0_0_0_var), NULL);
}
}
static void ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructSceneAsync_mC1DFF99FC6A4A831002F8A11A4131034C0C8A3BC(CustomAttributesCache* cache)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CConstructSceneAsyncU3Ed__25_t233186A16E43DAF0312FAE42938228273A25B0CB_0_0_0_var);
s_Il2CppMethodInitialized = true;
}
{
AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[0];
AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CConstructSceneAsyncU3Ed__25_t233186A16E43DAF0312FAE42938228273A25B0CB_0_0_0_var), NULL);
}
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[1];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructNodeAsync_m8872D41E18DDF621F23995085DECB63C38DC0201(CustomAttributesCache* cache)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CConstructNodeAsyncU3Ed__26_tBC58C69D6F3538087AE893C5A97482C1E4254C21_0_0_0_var);
s_Il2CppMethodInitialized = true;
}
{
AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[0];
AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CConstructNodeAsyncU3Ed__26_tBC58C69D6F3538087AE893C5A97482C1E4254C21_0_0_0_var), NULL);
}
}
static void ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructMeshAsync_mD4178E74AAFB315123C64F9E14DE436DDF6CBFFD(CustomAttributesCache* cache)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CConstructMeshAsyncU3Ed__27_t64D05762DC351830A551BCADA3E0FA5B3F1D518E_0_0_0_var);
s_Il2CppMethodInitialized = true;
}
{
AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[0];
AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CConstructMeshAsyncU3Ed__27_t64D05762DC351830A551BCADA3E0FA5B3F1D518E_0_0_0_var), NULL);
}
}
static void ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructMeshPrimitiveAsync_mADC4A60D01E735DC20EB26E3274FA5F50D37493E(CustomAttributesCache* cache)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CConstructMeshPrimitiveAsyncU3Ed__28_tA958F7C69894685E245BE2E70ACC328D7A24B186_0_0_0_var);
s_Il2CppMethodInitialized = true;
}
{
AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 * tmp = (AsyncStateMachineAttribute_tBDB4B958CFB5CD3BEE1427711FFC8C358C9BA6E6 *)cache->attributes[0];
AsyncStateMachineAttribute__ctor_m9530B59D9722DE383A1703C52EBC1ED1FEFB100B(tmp, il2cpp_codegen_type_get_object(U3CConstructMeshPrimitiveAsyncU3Ed__28_tA958F7C69894685E245BE2E70ACC328D7A24B186_0_0_0_var), NULL);
}
}
static void U3CConstructAsyncU3Ed__19_t2CEBB449CCB1AC8F210D3036C331C51331107531_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void U3CConstructAsyncU3Ed__19_t2CEBB449CCB1AC8F210D3036C331C51331107531_CustomAttributesCacheGenerator_U3CConstructAsyncU3Ed__19_SetStateMachine_m734B1A7142E0AF22710D5B76549146BF20B9CD48(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CConstructTextureAsyncU3Ed__21_tEF4B03242DD3E5D2E8E8B69D6681CCC87389720A_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void U3CConstructTextureAsyncU3Ed__21_tEF4B03242DD3E5D2E8E8B69D6681CCC87389720A_CustomAttributesCacheGenerator_U3CConstructTextureAsyncU3Ed__21_SetStateMachine_mE106C2E3A9E6934CC6A2680E5C60FF95DB3D383A(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CConstructMaterialAsyncU3Ed__22_tE4FE45B75E7B9D6414C3D9AB5C48E08C062131CA_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void U3CConstructMaterialAsyncU3Ed__22_tE4FE45B75E7B9D6414C3D9AB5C48E08C062131CA_CustomAttributesCacheGenerator_U3CConstructMaterialAsyncU3Ed__22_SetStateMachine_mC550A45FE52DBBF052540F0D1E5931C060208532(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CCreateMRTKShaderMaterialU3Ed__23_t0FD867448D76F96B3F706AC8E21E9AB5794F6757_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void U3CCreateMRTKShaderMaterialU3Ed__23_t0FD867448D76F96B3F706AC8E21E9AB5794F6757_CustomAttributesCacheGenerator_U3CCreateMRTKShaderMaterialU3Ed__23_SetStateMachine_m708DCD5F3ACE1B8CC506B51EED2B2D70DC45A30D(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CCreateStandardShaderMaterialU3Ed__24_t2ABF29742A69220D0B9FC29D5C9BF1B79E834FE9_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void U3CCreateStandardShaderMaterialU3Ed__24_t2ABF29742A69220D0B9FC29D5C9BF1B79E834FE9_CustomAttributesCacheGenerator_U3CCreateStandardShaderMaterialU3Ed__24_SetStateMachine_m410D5041E6D7A317A3C59A8042FC9760C996B064(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CConstructSceneAsyncU3Ed__25_t233186A16E43DAF0312FAE42938228273A25B0CB_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void U3CConstructSceneAsyncU3Ed__25_t233186A16E43DAF0312FAE42938228273A25B0CB_CustomAttributesCacheGenerator_U3CConstructSceneAsyncU3Ed__25_SetStateMachine_mB0CF6186843F0131EAC4012F0B82C6EF92669523(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CConstructNodeAsyncU3Ed__26_tBC58C69D6F3538087AE893C5A97482C1E4254C21_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void U3CConstructNodeAsyncU3Ed__26_tBC58C69D6F3538087AE893C5A97482C1E4254C21_CustomAttributesCacheGenerator_U3CConstructNodeAsyncU3Ed__26_SetStateMachine_mEF5B54D11C01423F64312E8E8C60C34DBB5C8AA8(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CConstructMeshAsyncU3Ed__27_t64D05762DC351830A551BCADA3E0FA5B3F1D518E_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void U3CConstructMeshAsyncU3Ed__27_t64D05762DC351830A551BCADA3E0FA5B3F1D518E_CustomAttributesCacheGenerator_U3CConstructMeshAsyncU3Ed__27_SetStateMachine_m522DFB44F66E8732BD8673AA8B769AEC49225732(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CConstructMeshPrimitiveAsyncU3Ed__28_tA958F7C69894685E245BE2E70ACC328D7A24B186_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void U3CConstructMeshPrimitiveAsyncU3Ed__28_tA958F7C69894685E245BE2E70ACC328D7A24B186_CustomAttributesCacheGenerator_U3CConstructMeshPrimitiveAsyncU3Ed__28_SetStateMachine_m8035A4149A7F60A57B3FDED286639CAAF24CA42A(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetTrsProperties_m3691FAC2BAD2B23BB1ED82DF1E67B9E59161B54B(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetColorValue_m4352D0083623D247C7AC4AC3E40BDB0A4D64A617(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetVector3Value_mD471CFF8228FEB8480733DAECA2E41E1ABBEB775(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetQuaternionValue_mCA875AC61AD5E70778E10C847A3C736B5D502789(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetMatrix4X4Value_m693DAC0751CFF49A2081897EF8576824467981AA(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetTrsProperties_mF7FFA6D1851155388BD96D917EA8FD31D06204FE(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetIntArray_m56DFEA796C0DC5B5C7C2AB8EE744AEE31001B494(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetVector2Array_m0BA88B213F395E133ADAD12E19D4035CF8847B66(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetVector3Array_m4329F582C356B0A25AA5D94E4D2B8B9B0A6AD1A4(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetVector4Array_mD6428A7D503A0049749CE6D3AD5EE5F4B7B677B4(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetColorArray_m973015E7DBC22E262ACA528F21D584E5EE1F9339(CustomAttributesCache* cache)
{
{
ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC * tmp = (ExtensionAttribute_t917F3F92E717DC8B2D7BC03967A9790B1B8EF7CC *)cache->attributes[0];
ExtensionAttribute__ctor_mB331519C39C4210259A248A4C629DF934937C1FA(tmp, NULL);
}
}
static void GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_U3CComponentTypeU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_componentType(CustomAttributesCache* cache)
{
{
SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[0];
SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL);
}
}
static void GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_U3CBufferViewU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_GltfAccessor_get_ComponentType_mC450DC10341DA466A375478B138C9E03252D5512(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_GltfAccessor_set_ComponentType_m13736F946070E59C468F12061F0815A3E5210861(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_GltfAccessor_get_BufferView_m5AC5B267A721DC84CBCCC57128E4617A9331AC0F(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_GltfAccessor_set_BufferView_m463835F426B1C28CC08BEB51074DBC6C745D436C(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfBuffer_tE7C65B67F85BE09BEB0DD065CFB17D942330A414_CustomAttributesCacheGenerator_U3CBufferDataU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfBuffer_tE7C65B67F85BE09BEB0DD065CFB17D942330A414_CustomAttributesCacheGenerator_GltfBuffer_get_BufferData_mCD0457E906A537C2C5C17999D307002379B86A80(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfBuffer_tE7C65B67F85BE09BEB0DD065CFB17D942330A414_CustomAttributesCacheGenerator_GltfBuffer_set_BufferData_m0993261853DFC89EA9AEF96A79D914749B7F5962(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_U3CTargetU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_target(CustomAttributesCache* cache)
{
{
SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[0];
SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL);
}
}
static void GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_U3CBufferU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_GltfBufferView_get_Target_mB36248F10F80C52BCF6772769B02B5FD4C482DD3(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_GltfBufferView_set_Target_m2EDA2C63585ABBDCF658D36D0A5CA85617F067AF(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_GltfBufferView_get_Buffer_m9A6CD4E79950D95C062692716C82F3C34B0C0E9A(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_GltfBufferView_set_Buffer_m90774ADDC6EBA4240037F5D9CA4967129AB362BA(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfImage_t6A545649736ECEE616EDE7C78AF97221E56986BF_CustomAttributesCacheGenerator_U3CTextureU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfImage_t6A545649736ECEE616EDE7C78AF97221E56986BF_CustomAttributesCacheGenerator_GltfImage_get_Texture_mC38D166B2082586F371904A916B6AF16DA2CDA01(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfImage_t6A545649736ECEE616EDE7C78AF97221E56986BF_CustomAttributesCacheGenerator_GltfImage_set_Texture_m0CA339CAC0C835D33DCC012425B73183C8B6AC4A(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMaterial_tC9A8E7147BA72C3EEF1C1AFA51CCD3CB50A0AB44_CustomAttributesCacheGenerator_U3CMaterialU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMaterial_tC9A8E7147BA72C3EEF1C1AFA51CCD3CB50A0AB44_CustomAttributesCacheGenerator_GltfMaterial_get_Material_m9D0060C72D71437CCB581D32ABEADC7F5095B3BC(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMaterial_tC9A8E7147BA72C3EEF1C1AFA51CCD3CB50A0AB44_CustomAttributesCacheGenerator_GltfMaterial_set_Material_m3BEB059ECE338D471F943AF5D8E74FC4843674D9(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMesh_t7C7577B2D50175DD94E40092D27F5FC0B7C6B4CC_CustomAttributesCacheGenerator_U3CMeshU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMesh_t7C7577B2D50175DD94E40092D27F5FC0B7C6B4CC_CustomAttributesCacheGenerator_GltfMesh_get_Mesh_m652F79610B4AC4AF62C025F3DC86A2E26D2B787D(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMesh_t7C7577B2D50175DD94E40092D27F5FC0B7C6B4CC_CustomAttributesCacheGenerator_GltfMesh_set_Mesh_m526141FFAB42C3D5DB4FF56BD13E9A5E9ED65001(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_U3CModeU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_mode(CustomAttributesCache* cache)
{
{
SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 * tmp = (SerializeField_t6B23EE6CC99B21C3EBD946352112832A70E67E25 *)cache->attributes[0];
SerializeField__ctor_mDE6A7673BA2C1FAD03CFEC65C6D473CC37889DD3(tmp, NULL);
}
}
static void GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_U3CAttributesU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_U3CSubMeshU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_GltfMeshPrimitive_get_Mode_mB619B90CEBD39EF25AC7EF4202590F6C2E1BA836(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_GltfMeshPrimitive_set_Mode_m74F0AB8F3674E86BEB14E7C3CEA64E69551785F1(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_GltfMeshPrimitive_get_Attributes_m2D6AB1B3BE85FC5240AB5EB8DA4EB53C96ABA55C(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_GltfMeshPrimitive_set_Attributes_m685804E425F354BA13EE2E43518E9D2F1013641C(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_GltfMeshPrimitive_set_SubMesh_mDD08F534352C16D4519FD066BD8BFA5A99A0A6DE(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfNode_t06C0FB36F1AF44BF30BE02B75D2A2AA074FE1FA5_CustomAttributesCacheGenerator_U3CMatrixU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfNode_t06C0FB36F1AF44BF30BE02B75D2A2AA074FE1FA5_CustomAttributesCacheGenerator_GltfNode_get_Matrix_m739FB9317BD7CF3E1A02D9B071E434ECAE1ADDED(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfNode_t06C0FB36F1AF44BF30BE02B75D2A2AA074FE1FA5_CustomAttributesCacheGenerator_GltfNode_set_Matrix_mE7B9F23579F6E9789D75477517171D30B613F1D5(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_U3CNameU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_U3CUriU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_U3CGameObjectReferenceU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_U3CRegisteredExtensionsU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_U3CUseBackgroundThreadU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_GltfObject_get_Name_m81A0992AC0CA5B145AC14359FCC7CDAB3FAAFBF0(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_GltfObject_get_Uri_m35E7F119B534DA747562446CD488CFC360EA7766(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_GltfObject_set_GameObjectReference_m3100B6305C38D432FAA492645429D3DEB5067470(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_GltfObject_get_UseBackgroundThread_m5FB73CAC1C0FE752F3B586D3FA3AAFC78AD35AF8(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfTexture_t7352ECF988F026029F728B8852450DF648E6788E_CustomAttributesCacheGenerator_U3CTextureU3Ek__BackingField(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void GltfTexture_t7352ECF988F026029F728B8852450DF648E6788E_CustomAttributesCacheGenerator_GltfTexture_set_Texture_m52E06CFD8B4FDCB128DB7A81BC5FB6E3BE5D4290(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void U3CPrivateImplementationDetailsU3E_tC49ADD0797DA84BE1FBCE593D159416A7DCE5CA8_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
IL2CPP_EXTERN_C const CustomAttributesCacheGenerator g_Microsoft_MixedReality_Toolkit_Gltf_AttributeGenerators[];
const CustomAttributesCacheGenerator g_Microsoft_MixedReality_Toolkit_Gltf_AttributeGenerators[92] =
{
ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator,
U3CConstructAsyncU3Ed__19_t2CEBB449CCB1AC8F210D3036C331C51331107531_CustomAttributesCacheGenerator,
U3CConstructTextureAsyncU3Ed__21_tEF4B03242DD3E5D2E8E8B69D6681CCC87389720A_CustomAttributesCacheGenerator,
U3CConstructMaterialAsyncU3Ed__22_tE4FE45B75E7B9D6414C3D9AB5C48E08C062131CA_CustomAttributesCacheGenerator,
U3CCreateMRTKShaderMaterialU3Ed__23_t0FD867448D76F96B3F706AC8E21E9AB5794F6757_CustomAttributesCacheGenerator,
U3CCreateStandardShaderMaterialU3Ed__24_t2ABF29742A69220D0B9FC29D5C9BF1B79E834FE9_CustomAttributesCacheGenerator,
U3CConstructSceneAsyncU3Ed__25_t233186A16E43DAF0312FAE42938228273A25B0CB_CustomAttributesCacheGenerator,
U3CConstructNodeAsyncU3Ed__26_tBC58C69D6F3538087AE893C5A97482C1E4254C21_CustomAttributesCacheGenerator,
U3CConstructMeshAsyncU3Ed__27_t64D05762DC351830A551BCADA3E0FA5B3F1D518E_CustomAttributesCacheGenerator,
U3CConstructMeshPrimitiveAsyncU3Ed__28_tA958F7C69894685E245BE2E70ACC328D7A24B186_CustomAttributesCacheGenerator,
GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator,
U3CPrivateImplementationDetailsU3E_tC49ADD0797DA84BE1FBCE593D159416A7DCE5CA8_CustomAttributesCacheGenerator,
GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_U3CComponentTypeU3Ek__BackingField,
GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_componentType,
GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_U3CBufferViewU3Ek__BackingField,
GltfBuffer_tE7C65B67F85BE09BEB0DD065CFB17D942330A414_CustomAttributesCacheGenerator_U3CBufferDataU3Ek__BackingField,
GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_U3CTargetU3Ek__BackingField,
GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_target,
GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_U3CBufferU3Ek__BackingField,
GltfImage_t6A545649736ECEE616EDE7C78AF97221E56986BF_CustomAttributesCacheGenerator_U3CTextureU3Ek__BackingField,
GltfMaterial_tC9A8E7147BA72C3EEF1C1AFA51CCD3CB50A0AB44_CustomAttributesCacheGenerator_U3CMaterialU3Ek__BackingField,
GltfMesh_t7C7577B2D50175DD94E40092D27F5FC0B7C6B4CC_CustomAttributesCacheGenerator_U3CMeshU3Ek__BackingField,
GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_U3CModeU3Ek__BackingField,
GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_mode,
GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_U3CAttributesU3Ek__BackingField,
GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_U3CSubMeshU3Ek__BackingField,
GltfNode_t06C0FB36F1AF44BF30BE02B75D2A2AA074FE1FA5_CustomAttributesCacheGenerator_U3CMatrixU3Ek__BackingField,
GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_U3CNameU3Ek__BackingField,
GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_U3CUriU3Ek__BackingField,
GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_U3CGameObjectReferenceU3Ek__BackingField,
GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_U3CRegisteredExtensionsU3Ek__BackingField,
GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_U3CUseBackgroundThreadU3Ek__BackingField,
GltfTexture_t7352ECF988F026029F728B8852450DF648E6788E_CustomAttributesCacheGenerator_U3CTextureU3Ek__BackingField,
ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructAsync_m1C52A32415C37E949AD6C4A5FDA17DDA0F2ADAFC,
ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructBufferView_m0168DB9CDB07F6FC97EE3A06788BCA1D598A81BB,
ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructTextureAsync_mB47AF294D372ED12B04A2D1F86F9985454478140,
ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructMaterialAsync_m91FA494C83A557F9777804D80CF10029E590A99A,
ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_CreateMRTKShaderMaterial_mAD27679B68956F7A306AA11302ED7B9743F0838C,
ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_CreateStandardShaderMaterial_m948E20DCA6986A23A63A9B3463D57A1A1B4D129C,
ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructSceneAsync_mC1DFF99FC6A4A831002F8A11A4131034C0C8A3BC,
ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructNodeAsync_m8872D41E18DDF621F23995085DECB63C38DC0201,
ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructMeshAsync_mD4178E74AAFB315123C64F9E14DE436DDF6CBFFD,
ConstructGltf_t31BFCCCA5F6DBBD01CBC15686CA3889140A21401_CustomAttributesCacheGenerator_ConstructGltf_ConstructMeshPrimitiveAsync_mADC4A60D01E735DC20EB26E3274FA5F50D37493E,
U3CConstructAsyncU3Ed__19_t2CEBB449CCB1AC8F210D3036C331C51331107531_CustomAttributesCacheGenerator_U3CConstructAsyncU3Ed__19_SetStateMachine_m734B1A7142E0AF22710D5B76549146BF20B9CD48,
U3CConstructTextureAsyncU3Ed__21_tEF4B03242DD3E5D2E8E8B69D6681CCC87389720A_CustomAttributesCacheGenerator_U3CConstructTextureAsyncU3Ed__21_SetStateMachine_mE106C2E3A9E6934CC6A2680E5C60FF95DB3D383A,
U3CConstructMaterialAsyncU3Ed__22_tE4FE45B75E7B9D6414C3D9AB5C48E08C062131CA_CustomAttributesCacheGenerator_U3CConstructMaterialAsyncU3Ed__22_SetStateMachine_mC550A45FE52DBBF052540F0D1E5931C060208532,
U3CCreateMRTKShaderMaterialU3Ed__23_t0FD867448D76F96B3F706AC8E21E9AB5794F6757_CustomAttributesCacheGenerator_U3CCreateMRTKShaderMaterialU3Ed__23_SetStateMachine_m708DCD5F3ACE1B8CC506B51EED2B2D70DC45A30D,
U3CCreateStandardShaderMaterialU3Ed__24_t2ABF29742A69220D0B9FC29D5C9BF1B79E834FE9_CustomAttributesCacheGenerator_U3CCreateStandardShaderMaterialU3Ed__24_SetStateMachine_m410D5041E6D7A317A3C59A8042FC9760C996B064,
U3CConstructSceneAsyncU3Ed__25_t233186A16E43DAF0312FAE42938228273A25B0CB_CustomAttributesCacheGenerator_U3CConstructSceneAsyncU3Ed__25_SetStateMachine_mB0CF6186843F0131EAC4012F0B82C6EF92669523,
U3CConstructNodeAsyncU3Ed__26_tBC58C69D6F3538087AE893C5A97482C1E4254C21_CustomAttributesCacheGenerator_U3CConstructNodeAsyncU3Ed__26_SetStateMachine_mEF5B54D11C01423F64312E8E8C60C34DBB5C8AA8,
U3CConstructMeshAsyncU3Ed__27_t64D05762DC351830A551BCADA3E0FA5B3F1D518E_CustomAttributesCacheGenerator_U3CConstructMeshAsyncU3Ed__27_SetStateMachine_m522DFB44F66E8732BD8673AA8B769AEC49225732,
U3CConstructMeshPrimitiveAsyncU3Ed__28_tA958F7C69894685E245BE2E70ACC328D7A24B186_CustomAttributesCacheGenerator_U3CConstructMeshPrimitiveAsyncU3Ed__28_SetStateMachine_m8035A4149A7F60A57B3FDED286639CAAF24CA42A,
GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetTrsProperties_m3691FAC2BAD2B23BB1ED82DF1E67B9E59161B54B,
GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetColorValue_m4352D0083623D247C7AC4AC3E40BDB0A4D64A617,
GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetVector3Value_mD471CFF8228FEB8480733DAECA2E41E1ABBEB775,
GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetQuaternionValue_mCA875AC61AD5E70778E10C847A3C736B5D502789,
GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetMatrix4X4Value_m693DAC0751CFF49A2081897EF8576824467981AA,
GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetTrsProperties_mF7FFA6D1851155388BD96D917EA8FD31D06204FE,
GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetIntArray_m56DFEA796C0DC5B5C7C2AB8EE744AEE31001B494,
GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetVector2Array_m0BA88B213F395E133ADAD12E19D4035CF8847B66,
GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetVector3Array_m4329F582C356B0A25AA5D94E4D2B8B9B0A6AD1A4,
GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetVector4Array_mD6428A7D503A0049749CE6D3AD5EE5F4B7B677B4,
GltfConversions_t1F3AE8B00EE6B049DC0714A850EA39A4F408561E_CustomAttributesCacheGenerator_GltfConversions_GetColorArray_m973015E7DBC22E262ACA528F21D584E5EE1F9339,
GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_GltfAccessor_get_ComponentType_mC450DC10341DA466A375478B138C9E03252D5512,
GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_GltfAccessor_set_ComponentType_m13736F946070E59C468F12061F0815A3E5210861,
GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_GltfAccessor_get_BufferView_m5AC5B267A721DC84CBCCC57128E4617A9331AC0F,
GltfAccessor_tA29C9908CF06B3E496D0DE5A968D74C2CF146939_CustomAttributesCacheGenerator_GltfAccessor_set_BufferView_m463835F426B1C28CC08BEB51074DBC6C745D436C,
GltfBuffer_tE7C65B67F85BE09BEB0DD065CFB17D942330A414_CustomAttributesCacheGenerator_GltfBuffer_get_BufferData_mCD0457E906A537C2C5C17999D307002379B86A80,
GltfBuffer_tE7C65B67F85BE09BEB0DD065CFB17D942330A414_CustomAttributesCacheGenerator_GltfBuffer_set_BufferData_m0993261853DFC89EA9AEF96A79D914749B7F5962,
GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_GltfBufferView_get_Target_mB36248F10F80C52BCF6772769B02B5FD4C482DD3,
GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_GltfBufferView_set_Target_m2EDA2C63585ABBDCF658D36D0A5CA85617F067AF,
GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_GltfBufferView_get_Buffer_m9A6CD4E79950D95C062692716C82F3C34B0C0E9A,
GltfBufferView_t97FF480B7E4BA8F47158507413222C253EBD8CC2_CustomAttributesCacheGenerator_GltfBufferView_set_Buffer_m90774ADDC6EBA4240037F5D9CA4967129AB362BA,
GltfImage_t6A545649736ECEE616EDE7C78AF97221E56986BF_CustomAttributesCacheGenerator_GltfImage_get_Texture_mC38D166B2082586F371904A916B6AF16DA2CDA01,
GltfImage_t6A545649736ECEE616EDE7C78AF97221E56986BF_CustomAttributesCacheGenerator_GltfImage_set_Texture_m0CA339CAC0C835D33DCC012425B73183C8B6AC4A,
GltfMaterial_tC9A8E7147BA72C3EEF1C1AFA51CCD3CB50A0AB44_CustomAttributesCacheGenerator_GltfMaterial_get_Material_m9D0060C72D71437CCB581D32ABEADC7F5095B3BC,
GltfMaterial_tC9A8E7147BA72C3EEF1C1AFA51CCD3CB50A0AB44_CustomAttributesCacheGenerator_GltfMaterial_set_Material_m3BEB059ECE338D471F943AF5D8E74FC4843674D9,
GltfMesh_t7C7577B2D50175DD94E40092D27F5FC0B7C6B4CC_CustomAttributesCacheGenerator_GltfMesh_get_Mesh_m652F79610B4AC4AF62C025F3DC86A2E26D2B787D,
GltfMesh_t7C7577B2D50175DD94E40092D27F5FC0B7C6B4CC_CustomAttributesCacheGenerator_GltfMesh_set_Mesh_m526141FFAB42C3D5DB4FF56BD13E9A5E9ED65001,
GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_GltfMeshPrimitive_get_Mode_mB619B90CEBD39EF25AC7EF4202590F6C2E1BA836,
GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_GltfMeshPrimitive_set_Mode_m74F0AB8F3674E86BEB14E7C3CEA64E69551785F1,
GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_GltfMeshPrimitive_get_Attributes_m2D6AB1B3BE85FC5240AB5EB8DA4EB53C96ABA55C,
GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_GltfMeshPrimitive_set_Attributes_m685804E425F354BA13EE2E43518E9D2F1013641C,
GltfMeshPrimitive_tF128674A3ADD35A410D4981C4D48693D031AA20F_CustomAttributesCacheGenerator_GltfMeshPrimitive_set_SubMesh_mDD08F534352C16D4519FD066BD8BFA5A99A0A6DE,
GltfNode_t06C0FB36F1AF44BF30BE02B75D2A2AA074FE1FA5_CustomAttributesCacheGenerator_GltfNode_get_Matrix_m739FB9317BD7CF3E1A02D9B071E434ECAE1ADDED,
GltfNode_t06C0FB36F1AF44BF30BE02B75D2A2AA074FE1FA5_CustomAttributesCacheGenerator_GltfNode_set_Matrix_mE7B9F23579F6E9789D75477517171D30B613F1D5,
GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_GltfObject_get_Name_m81A0992AC0CA5B145AC14359FCC7CDAB3FAAFBF0,
GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_GltfObject_get_Uri_m35E7F119B534DA747562446CD488CFC360EA7766,
GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_GltfObject_set_GameObjectReference_m3100B6305C38D432FAA492645429D3DEB5067470,
GltfObject_t4812A0D21F182A9B9C500A7CE5C70D7B49A942DE_CustomAttributesCacheGenerator_GltfObject_get_UseBackgroundThread_m5FB73CAC1C0FE752F3B586D3FA3AAFC78AD35AF8,
GltfTexture_t7352ECF988F026029F728B8852450DF648E6788E_CustomAttributesCacheGenerator_GltfTexture_set_Texture_m52E06CFD8B4FDCB128DB7A81BC5FB6E3BE5D4290,
Microsoft_MixedReality_Toolkit_Gltf_CustomAttributesCacheGenerator,
};
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void RuntimeCompatibilityAttribute_set_WrapNonExceptionThrows_m8562196F90F3EBCEC23B5708EE0332842883C490_inline (RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 * __this, bool ___value0, const RuntimeMethod* method)
{
{
bool L_0 = ___value0;
__this->set_m_wrapNonExceptionThrows_0(L_0);
return;
}
}
| 60.466019 | 308 | 0.898844 | [
"object"
] |
b37c346516a8bab1269ac4e7a9902c00fda68522 | 1,595 | cpp | C++ | 221.最大正方形/maximalSquare.cpp | YichengZhong/Top-Interview-Questions | 124828d321f482a0eaa30012b3706267487bfd24 | [
"MIT"
] | 1 | 2019-10-21T14:40:39.000Z | 2019-10-21T14:40:39.000Z | 221.最大正方形/maximalSquare.cpp | YichengZhong/Top-Interview-Questions | 124828d321f482a0eaa30012b3706267487bfd24 | [
"MIT"
] | null | null | null | 221.最大正方形/maximalSquare.cpp | YichengZhong/Top-Interview-Questions | 124828d321f482a0eaa30012b3706267487bfd24 | [
"MIT"
] | 1 | 2020-11-04T07:33:34.000Z | 2020-11-04T07:33:34.000Z | class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
//每次遇到1,作为左上
if(matrix.size()==0 || matrix[0].size()==0) return 0;
int maxlen=0;
for(int i=0;i<matrix.size();++i)
{
for(int j=0;j<matrix[0].size();++j)
{
if(matrix[i][j]=='1')
{
maxlen=max(maxlen, 1);
// 计算可能的最大正方形边长
int currentMaxSide = min(matrix.size() - i, matrix[0].size() - j);
for(int k=1;k<currentMaxSide;++k)
{
//斜线
bool flag=true;
if (matrix[i + k][j + k] == '0')
{
flag=false;
break;
}
//新增一行、一列
for (int m = 0; m < k; m++)
{
if (matrix[i + k][j + m] == '0' || matrix[i + m][j + k] == '0')
{
flag = false;
break;
}
}
if (flag)
{
maxlen = max(maxlen, k + 1);
} else
{
break;
}
}
}
}
}
return maxlen * maxlen;
}
}; | 30.673077 | 92 | 0.251411 | [
"vector"
] |
b37c8bbf60837f4b7f8886755b5703cde471b8cf | 6,177 | cpp | C++ | Modules/TArc/Sources/TArc/Controls/Private/RadioButtonsGroup.cpp | stinvi/dava.engine | 2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e | [
"BSD-3-Clause"
] | 26 | 2018-09-03T08:48:22.000Z | 2022-02-14T05:14:50.000Z | Modules/TArc/Sources/TArc/Controls/Private/RadioButtonsGroup.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | null | null | null | Modules/TArc/Sources/TArc/Controls/Private/RadioButtonsGroup.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | 45 | 2018-05-11T06:47:17.000Z | 2022-02-03T11:30:55.000Z | #include "TArc/Controls/RadioButtonsGroup.h"
#include "TArc/DataProcessing/AnyQMetaType.h"
#include <Base/FastName.h>
#include <QGridLayout>
#include <QVariant>
#include <QRadioButton>
#include <QLabel>
namespace RadioButtonsGroupDetails
{
const char* dataPropertyName = "data";
}
namespace DAVA
{
RadioButtonsGroup::RadioButtonsGroup(const Params& params, DataWrappersProcessor* wrappersProcessor, Reflection model, QWidget* parent)
: ControlProxyImpl<QWidget>(params, ControlDescriptor(params.fields), wrappersProcessor, model, parent)
{
SetupControl();
}
RadioButtonsGroup::RadioButtonsGroup(const Params& params, Reflection model, QWidget* parent)
: ControlProxyImpl<QWidget>(params, ControlDescriptor(params.fields), params.accessor, model, parent)
{
SetupControl();
}
void RadioButtonsGroup::SetupControl()
{
connections.AddConnection(&buttonGroup, static_cast<void (QButtonGroup::*)(QAbstractButton*)>(&QButtonGroup::buttonClicked), MakeFunction(this, &RadioButtonsGroup::OnButtonToggled));
}
void RadioButtonsGroup::UpdateControl(const ControlDescriptor& changedFields)
{
DVASSERT(updateControlProceed == false);
ScopedValueGuard<bool> guard(updateControlProceed, true);
bool enabledChanged = changedFields.IsChanged(Fields::Enabled);
bool valueChanged = changedFields.IsChanged(Fields::Value);
if (enabledChanged || valueChanged)
{
bool enabled = IsValueEnabled(changedFields, Fields::Value, Fields::Enabled);
setEnabled(enabled);
}
Reflection fieldEnumerator;
const FastName& enumeratorName = changedFields.GetName(Fields::Enumerator);
if (enumeratorName.IsValid())
{
fieldEnumerator = model.GetField(enumeratorName);
}
Qt::Orientation orientation = Qt::Horizontal;
const FastName& orientationName = changedFields.GetName(Fields::Orientation);
if (orientationName.IsValid())
{
Any orientationValue = model.GetField(orientationName).GetValue();
if (orientationValue.CanCast<Qt::Orientation>())
{
orientation = orientationValue.Cast<Qt::Orientation>();
}
}
Reflection fieldValue = model.GetField(changedFields.GetName(Fields::Value));
DVASSERT(fieldValue.IsValid());
if (buttonGroup.buttons().isEmpty() || changedFields.IsChanged(Fields::Enumerator) || changedFields.IsChanged(Fields::Orientation))
{
CreateItems(fieldValue, fieldEnumerator, orientation);
}
int currentIndex = SelectCurrentItem(fieldValue, fieldEnumerator);
DVASSERT(currentIndex != -1);
}
int RadioButtonsGroup::SelectCurrentItem(const Reflection& fieldValue, const Reflection& fieldEnumerator)
{
Any value = fieldValue.GetValue();
if (value.IsEmpty() == false)
{
QList<QAbstractButton*> radioButtons = buttonGroup.buttons();
for (int i = 0, count = radioButtons.size(); i < count; ++i)
{
QAbstractButton* button = radioButtons.at(i);
Any iAny = button->property(RadioButtonsGroupDetails::dataPropertyName).value<Any>();
if (value == iAny)
{
button->setChecked(true);
return i;
}
else if (iAny.CanCast<int>() && value.CanCast<int>() &&
iAny.Cast<int>() == value.Cast<int>())
{
button->setChecked(true);
return i;
}
}
}
return -1;
}
void RadioButtonsGroup::CreateItems(const Reflection& fieldValue, const Reflection& fieldEnumerator, Qt::Orientation orientation)
{
delete layout();
QGridLayout* newLayout = new QGridLayout();
newLayout->setVerticalSpacing(10);
setLayout(newLayout);
const M::Enum* enumMeta = fieldValue.GetMeta<M::Enum>();
if (enumMeta != nullptr)
{
const EnumMap* enumMap = enumMeta->GetEnumMap();
for (size_t i = 0, count = enumMap->GetCount(); i < count; ++i)
{
int iValue = 0;
bool ok = enumMap->GetValue(i, iValue);
if (ok)
{
QVariant dataValue;
dataValue.setValue(Any(iValue));
CreateItem(enumMap->ToString(iValue), dataValue, orientation, static_cast<int32>(i));
}
else
{
DVASSERT(false);
}
}
}
else
{
DVASSERT(fieldEnumerator.IsValid() == true);
Vector<Reflection::Field> fields = fieldEnumerator.GetFields();
for (size_t i = 0, count = fields.size(); i < count; ++i)
{
const Reflection::Field& field = fields.at(i);
Any fieldDescr = field.ref.GetValue();
QVariant dataValue;
dataValue.setValue(field.key);
CreateItem(fieldDescr.Cast<String>().c_str(), dataValue, orientation, static_cast<int32>(i));
}
}
}
void RadioButtonsGroup::CreateItem(const String& text, const QVariant& data, Qt::Orientation orientation, int32 index)
{
QRadioButton* radioButton = new QRadioButton();
radioButton->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
radioButton->setProperty(RadioButtonsGroupDetails::dataPropertyName, data);
buttonGroup.addButton(radioButton);
QLabel* label = new QLabel(QString::fromStdString(text));
label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
QGridLayout* currentLayout = qobject_cast<QGridLayout*>(layout());
DVASSERT(currentLayout != nullptr);
if (orientation == Qt::Horizontal)
{
currentLayout->addWidget(radioButton, 0, index, 1, 1, Qt::AlignCenter);
currentLayout->addWidget(label, 1, index, 1, 1, Qt::AlignCenter);
}
else
{
currentLayout->addWidget(radioButton, index, 0);
currentLayout->addWidget(label, index, 1);
}
}
void RadioButtonsGroup::OnButtonToggled(QAbstractButton* button)
{
if (updateControlProceed)
{
// ignore reaction on control initialization
return;
}
wrapper.SetFieldValue(GetFieldName(Fields::Value), button->property(RadioButtonsGroupDetails::dataPropertyName).value<Any>());
}
} // namespace DAVA
| 33.209677 | 186 | 0.660677 | [
"vector",
"model"
] |
b395c85889cc131a0c4a5004ce4c015beea734a5 | 6,444 | cpp | C++ | cntk_cpp/main.cpp | hiroog/cppapimnist | 30d7e01954fc43da2eea5fe3ebf034b37e79cfd1 | [
"MIT"
] | null | null | null | cntk_cpp/main.cpp | hiroog/cppapimnist | 30d7e01954fc43da2eea5fe3ebf034b37e79cfd1 | [
"MIT"
] | null | null | null | cntk_cpp/main.cpp | hiroog/cppapimnist | 30d7e01954fc43da2eea5fe3ebf034b37e79cfd1 | [
"MIT"
] | null | null | null | // 2019/12/29 Hiroyuki Ogasawara
// vim:ts=4 sw=4 noet:
#include <CNTKLibrary.h>
#include <random>
#include <iostream>
#include "mnist_loader.h"
namespace {
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
CNTK::FunctionPtr Dense( CNTK::Variable input_var, int output_size, const CNTK::DeviceDescriptor& device )
{
size_t input_size= input_var.Shape()[0];
auto weight= CNTK::Parameter(
{ (size_t)output_size, (size_t)input_size },
CNTK::DataType::Float,
CNTK::HeNormalInitializer(),
device
);
auto bias= CNTK::Parameter(
{ (size_t)output_size },
CNTK::DataType::Float,
0.0f,
device
);
return CNTK::Plus( bias, CNTK::Times( weight, input_var ) );
}
CNTK::FunctionPtr Conv2D( CNTK::Variable input_var, int output_ch, int kernel_size, int stride, bool padding, const CNTK::DeviceDescriptor& device )
{
size_t input_ch= input_var.Shape()[2];
auto filter= CNTK::Parameter(
{ (size_t)kernel_size, (size_t)kernel_size, input_ch, (size_t)output_ch },
CNTK::DataType::Float,
CNTK::HeNormalInitializer(),
device
);
auto bias= CNTK::Parameter(
{ CNTK::NDShape::InferredDimension },
CNTK::DataType::Float,
0.0f,
device
);
auto y= CNTK::Convolution(
filter,
input_var,
{ (size_t)stride, (size_t)stride, (size_t)input_ch },
{ true },
{ padding }
);
return CNTK::Plus( bias, y );
}
CNTK::FunctionPtr MaxPool2D( CNTK::Variable input_var, int kernel_size, int stride, bool padding )
{
return CNTK::Pooling(
input_var,
CNTK::PoolingType::Max,
{ (size_t)kernel_size, (size_t)kernel_size },
{ (size_t)stride, (size_t)stride },
{ padding }
);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
}
class Model_MNist {
public:
CNTK::FunctionPtr PredictFunc;
CNTK::Variable InputVar;
public:
Model_MNist( CNTK::DeviceDescriptor device )
{
CNTK::NDShape flatten_shape( 1 );
flatten_shape[0]= -1;
InputVar= CNTK::InputVariable( { 28, 28, 1 }, CNTK::DataType::Float, L"xinput0" );
auto c0= CNTK::ReLU( Conv2D( InputVar, 16, 5, 1, false, device ) );
auto m0= MaxPool2D( c0, 2, 2, false );
auto d0= CNTK::Dropout( m0, 0.25f );
auto c1= CNTK::ReLU( Conv2D( d0, 32, 5, 1, false, device ) );
auto m1= MaxPool2D( c1, 2, 2, false );
auto d1= CNTK::Dropout( m1, 0.25f );
auto f= CNTK::Reshape( d1, flatten_shape );
auto f0= CNTK::ReLU( Dense( f, 128, device ) );
auto d2= CNTK::Dropout( f0, 0.5f );
auto f1= CNTK::ReLU( Dense( d2, 64, device ) );
auto d3= CNTK::Dropout( f1, 0.5f );
auto f3= Dense( d3, 10, device );
PredictFunc= f3;
}
};
static void torch_test_train()
{
constexpr int EPOCH= 2;
constexpr int BATCH_SIZE= 32;
constexpr int DATA_COUNT= MNistLoader::TRAINDATA_SIZE;
constexpr int loop_count= DATA_COUNT / BATCH_SIZE;
std::random_device seed;
std::mt19937 engine( seed() );
std::uniform_int_distribution<int> rand(0,DATA_COUNT-1);
MNistLoader loader( "../mnist" );
auto device= CNTK::DeviceDescriptor::UseDefaultDevice();
Model_MNist model( device );
auto label_var= CNTK::InputVariable( { 10 }, CNTK::DataType::Float, L"yinput" );
auto loss_func= CNTK::SquaredError( model.PredictFunc, label_var );
auto optimizer= CNTK::AdamLearner( model.PredictFunc->Parameters(), CNTK::LearningRateSchedule( 0.1f ), 0.9f );
auto trainer= CNTK::CreateTrainer( model.PredictFunc, loss_func, { optimizer } );
std::vector<float> image_input;
std::vector<float> label_input;
image_input.resize( 28*28*BATCH_SIZE );
label_input.resize( 10*BATCH_SIZE );
std::unordered_map<CNTK::Variable,CNTK::MinibatchData> input_map;
for( int ei= 0 ; ei< EPOCH ; ei++ ){
float total_loss= 0.0f;
for( int di= 0 ; di< loop_count ; di++ ){
for( int bi= 0 ; bi< BATCH_SIZE ; bi++ ){
int ri= rand( engine );
loader.GetFloatImage( &image_input[bi*28*28], ri );
loader.GetFloatLabel10( &label_input[bi*10], ri );
}
input_map[model.InputVar]= CNTK::Value::CreateBatch( { 28, 28, 1 }, image_input, device, true );
input_map[label_var]= CNTK::Value::CreateBatch( { 10 }, label_input, device, true );
trainer->TrainMinibatch( input_map, device );
total_loss+= static_cast<float>(trainer->PreviousMinibatchLossAverage());
}
std::cout << ei << " loss=" << total_loss / loop_count << '\n';
}
model.PredictFunc->Save( L"cpp_mnist_cntk.dnn" );
std::cout << "ok\n";
}
static void torch_test_predict()
{
constexpr int BATCH_SIZE= 128;
constexpr int DATA_COUNT= MNistLoader::TESTDATA_SIZE;
constexpr int loop_count= DATA_COUNT / BATCH_SIZE;
MNistLoader loader( "../mnist" );
auto device= CNTK::DeviceDescriptor::UseDefaultDevice();
CNTK::FunctionPtr PredictFunc= CNTK::Function::Load( L"cpp_mnist_cntk.dnn", device );
auto input_var= PredictFunc->Arguments()[0];
auto output_var= PredictFunc->Outputs()[0];
std::vector<float> image_input;
image_input.resize( 28*28*BATCH_SIZE );
int index_table[BATCH_SIZE];
std::unordered_map<CNTK::Variable,CNTK::ValuePtr> input_map;
std::unordered_map<CNTK::Variable,CNTK::ValuePtr> output_map;
int data_index= 0;
int score= 0;
for( int di= 0 ; di< loop_count ; di++ ){
for( int bi= 0 ; bi< BATCH_SIZE ; bi++ ){
index_table[bi]= data_index;
loader.GetFloatImageTest( &image_input[bi*28*28], data_index );
data_index++;
}
input_map[input_var]= CNTK::Value::CreateBatch( { 28, 28, 1 }, image_input, device, true );
output_map[output_var]= nullptr;
PredictFunc->Evaluate( input_map, output_map, device );
const auto& output_val= output_map[output_var];
std::vector<std::vector<float>> buffer;
output_val->CopyVariableValueTo<float>( output_var, buffer );
for( int bi= 0 ; bi< BATCH_SIZE ; bi++ ){
float max_val= 0.0f;
int max_index= -1;
const float* fptr= &buffer[bi][0];
for( int fi= 0 ; fi< 10 ; fi++ ){
float fval= *fptr++;
if( fval > max_val ){
max_index= fi;
max_val= fval;
}
}
score+= (int)loader.GetLabelTest( index_table[bi] ) == max_index;
}
}
std::cout << score * 100.0f / (loop_count*BATCH_SIZE) << " %\n";
std::cout << "ok\n";
}
int main()
{
torch_test_train();
torch_test_predict();
return 0;
}
| 28.387665 | 148 | 0.63113 | [
"shape",
"vector",
"model"
] |
b39e9f35b228e24d0577a6037761d68483f22228 | 6,250 | cpp | C++ | frameworks/zone/test/unittest/zone_util_performance_test.cpp | openharmony-gitee-mirror/global_i18n_standard | 7cffb4a5a14db773ad679c6fb2f0f0a1c6e7ab3d | [
"Apache-2.0"
] | null | null | null | frameworks/zone/test/unittest/zone_util_performance_test.cpp | openharmony-gitee-mirror/global_i18n_standard | 7cffb4a5a14db773ad679c6fb2f0f0a1c6e7ab3d | [
"Apache-2.0"
] | null | null | null | frameworks/zone/test/unittest/zone_util_performance_test.cpp | openharmony-gitee-mirror/global_i18n_standard | 7cffb4a5a14db773ad679c6fb2f0f0a1c6e7ab3d | [
"Apache-2.0"
] | 1 | 2021-09-13T11:16:51.000Z | 2021-09-13T11:16:51.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "zone_util_performance_test.h"
#include <chrono>
#include <ctime>
#include <gtest/gtest.h>
#include "zone_util.h"
using namespace OHOS::Global::I18n;
using testing::ext::TestSize;
using namespace std;
namespace {
class ZoneUtilPerformanceTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void ZoneUtilPerformanceTest::SetUpTestCase(void)
{}
void ZoneUtilPerformanceTest::TearDownTestCase(void)
{}
void ZoneUtilPerformanceTest::SetUp(void)
{
}
void ZoneUtilPerformanceTest::TearDown(void)
{}
/**
* @tc.name: ZoneUtilPerformanceFuncTest001
* @tc.desc: Test ZoneUtil GetDefaultZone
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilPerformanceTest, ZoneUtilPerformanceFuncTest001, TestSize.Level1)
{
unsigned long long total = 0;
double average = 0;
string expects[] = { "Asia/Shanghai", "America/New_York" };
string countries[] = { "JP", "KR" };
int count = 2;
ZoneUtil util;
for (int k = 0; k < 1000; ++k) {
for (int i = 0; i < count; ++i) {
auto t1= std::chrono::high_resolution_clock::now();
string out = util.GetDefaultZone(countries[i].c_str());
auto t2 = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
}
}
average = total / (1000.0 * 2);
EXPECT_LT(average, 9300);
}
/**
* @tc.name: ZoneUtilPerformanceFuncTest002
* @tc.desc: Test ZoneUtil GetDefaultZone with offset
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilPerformanceTest, ZoneUtilPerformanceFuncTest002, TestSize.Level1)
{
unsigned long long total = 0;
double average = 0;
string expects[] = { "Asia/Shanghai", "America/Detroit" };
int32_t offsets[] = { 3600 * 1000 * 8, -3600 * 1000 * 5 };
string countries[] = { "CN", "US" };
int count = 2;
ZoneUtil util;
for (int k = 0; k < 1000; ++k) {
for (int i = 0; i < count; ++i) {
auto t1= std::chrono::high_resolution_clock::now();
string out = util.GetDefaultZone(countries[i].c_str(), offsets[i]);
auto t2 = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
}
}
average = total / (1000.0 * 2);
EXPECT_LT(average, 10800);
}
/**
* @tc.name: ZoneUtilPerformanceFuncTest003
* @tc.desc: Test ZoneUtil GetDefaultZoneList for CN
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilPerformanceTest, ZoneUtilPerformanceFuncTest003, TestSize.Level1)
{
unsigned long long total = 0;
double average = 0;
vector<string> expects = { "Asia/Shanghai", "Asia/Urumqi"};
string country = "CN";
vector<string> out;
ZoneUtil util;
for (int k = 0; k < 1000; ++k) {
auto t1= std::chrono::high_resolution_clock::now();
util.GetZoneList(country, out);
auto t2 = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
}
average = total / 1000.0;
EXPECT_LT(average, 9300);
}
/**
* @tc.name: ZoneUtilPerformanceFuncTest004
* @tc.desc: Test ZoneUtil GetDefaultZoneList for GB
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilPerformanceTest, ZoneUtilPerformanceFuncTest004, TestSize.Level1)
{
unsigned long long total = 0;
double average = 0;
vector<string> expects = { "Europe/London" };
string country = "GB";
vector<string> out;
ZoneUtil util;
for (int k = 0; k < 1000; ++k) {
auto t1= std::chrono::high_resolution_clock::now();
util.GetZoneList(country, out);
auto t2 = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
}
average = total / 1000.0;
EXPECT_LT(average, 9300);
}
/**
* @tc.name: ZoneUtilPerformanceFuncTest003
* @tc.desc: Test ZoneUtil GetDefaultZoneList for de
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilPerformanceTest, ZoneUtilPerformanceFuncTest005, TestSize.Level1)
{
unsigned long long total = 0;
double average = 0;
vector<string> expects = { "Europe/Berlin", "Europe/Busingen" };
string country = "DE";
vector<string> out;
ZoneUtil util;
for (int k = 0; k < 1000; ++k) {
auto t1= std::chrono::high_resolution_clock::now();
util.GetZoneList(country, out);
auto t2 = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
}
average = total / 1000.0;
EXPECT_LT(average, 9300);
}
/**
* @tc.name: ZoneUtilPerformanceFuncTest006
* @tc.desc: Test ZoneUtil GetDefaultZoneList for CN with offset 8 hours
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilPerformanceTest, ZoneUtilPerformanceFuncTest006, TestSize.Level1)
{
unsigned long long total = 0;
double average = 0;
vector<string> expects = { "Asia/Shanghai" };
string country = "CN";
vector<string> out;
ZoneUtil util;
for (int k = 0; k < 1000; ++k) {
auto t1= std::chrono::high_resolution_clock::now();
util.GetZoneList(country, 3600 * 1000 * 8, out);
auto t2 = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
}
average = total / 1000.0;
EXPECT_LT(average, 10300);
}
}
| 32.722513 | 93 | 0.63472 | [
"vector"
] |
b3aee0d39e5c0fc564f5fa971c1d8ec2015525c4 | 20,133 | cpp | C++ | src/libSBML/src/sbml/validator/SBMLInternalValidator.cpp | copasi/copasi-dependencies | c01dd455c843522375c32c2989aa8675f59bb810 | [
"Unlicense"
] | 5 | 2015-04-16T14:27:38.000Z | 2021-11-30T14:54:39.000Z | src/libSBML/src/sbml/validator/SBMLInternalValidator.cpp | copasi/copasi-dependencies | c01dd455c843522375c32c2989aa8675f59bb810 | [
"Unlicense"
] | 8 | 2017-05-30T16:58:39.000Z | 2022-02-22T16:51:34.000Z | src/libSBML/src/sbml/validator/SBMLInternalValidator.cpp | copasi/copasi-dependencies | c01dd455c843522375c32c2989aa8675f59bb810 | [
"Unlicense"
] | 7 | 2016-05-29T08:12:59.000Z | 2019-05-02T13:39:25.000Z | /**
* @file SBMLInternalValidator.cpp
* @brief Implementation of SBMLInternalValidator, the validator for all internal validation performed by libSBML.
* @author Frank Bergmann
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2020 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. University of Heidelberg, Heidelberg, Germany
* 3. University College London, London, UK
*
* Copyright (C) 2019 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. University of Heidelberg, Heidelberg, Germany
*
* Copyright (C) 2013-2018 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
* 3. University of Heidelberg, Heidelberg, Germany
*
* Copyright (C) 2009-2013 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* ------------------------------------------------------------------------ -->
*/
#include <sbml/validator/SBMLInternalValidator.h>
#ifdef __cplusplus
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <sbml/validator/ConsistencyValidator.h>
#include <sbml/validator/IdentifierConsistencyValidator.h>
#include <sbml/validator/MathMLConsistencyValidator.h>
#include <sbml/validator/SBOConsistencyValidator.h>
#include <sbml/validator/UnitConsistencyValidator.h>
#include <sbml/validator/OverdeterminedValidator.h>
#include <sbml/validator/ModelingPracticeValidator.h>
#include <sbml/validator/L1CompatibilityValidator.h>
#include <sbml/validator/L2v1CompatibilityValidator.h>
#include <sbml/validator/L2v2CompatibilityValidator.h>
#include <sbml/validator/L2v3CompatibilityValidator.h>
#include <sbml/validator/L2v4CompatibilityValidator.h>
#include <sbml/validator/L3v1CompatibilityValidator.h>
#include <sbml/validator/L3v2CompatibilityValidator.h>
#include <sbml/validator/InternalConsistencyValidator.h>
#include <sbml/SBMLDocument.h>
#include <sbml/SBMLWriter.h>
#include <sbml/SBMLReader.h>
#include <sbml/AlgebraicRule.h>
#include <sbml/AssignmentRule.h>
#include <sbml/RateRule.h>
using namespace std;
LIBSBML_CPP_NAMESPACE_BEGIN
SBMLInternalValidator::SBMLInternalValidator()
: SBMLValidator()
, mApplicableValidators(0)
, mApplicableValidatorsForConversion(0)
{
}
SBMLInternalValidator::SBMLInternalValidator(const SBMLInternalValidator& orig)
: SBMLValidator(orig)
, mApplicableValidators(orig.mApplicableValidators)
, mApplicableValidatorsForConversion(orig.mApplicableValidatorsForConversion)
{
}
SBMLValidator*
SBMLInternalValidator::clone() const
{
return new SBMLInternalValidator(*this);
}
/*
* Destroy this object.
*/
SBMLInternalValidator::~SBMLInternalValidator ()
{
}
void
SBMLInternalValidator::setConsistencyChecks(SBMLErrorCategory_t category,
bool apply)
{
switch (category)
{
case LIBSBML_CAT_IDENTIFIER_CONSISTENCY:
if (apply)
{
mApplicableValidators |= IdCheckON;
}
else
{
mApplicableValidators &= IdCheckOFF;
}
break;
case LIBSBML_CAT_GENERAL_CONSISTENCY:
if (apply)
{
mApplicableValidators |= SBMLCheckON;
}
else
{
mApplicableValidators &= SBMLCheckOFF;
}
break;
case LIBSBML_CAT_SBO_CONSISTENCY:
if (apply)
{
mApplicableValidators |= SBOCheckON;
}
else
{
mApplicableValidators &= SBOCheckOFF;
}
break;
case LIBSBML_CAT_MATHML_CONSISTENCY:
if (apply)
{
mApplicableValidators |= MathCheckON;
}
else
{
mApplicableValidators &= MathCheckOFF;
}
break;
case LIBSBML_CAT_UNITS_CONSISTENCY:
if (apply)
{
mApplicableValidators |= UnitsCheckON;
}
else
{
mApplicableValidators &= UnitsCheckOFF;
}
break;
case LIBSBML_CAT_OVERDETERMINED_MODEL:
if (apply)
{
mApplicableValidators |= OverdeterCheckON;
}
else
{
mApplicableValidators &= OverdeterCheckOFF;
}
break;
case LIBSBML_CAT_MODELING_PRACTICE:
if (apply)
{
mApplicableValidators |= PracticeCheckON;
}
else
{
mApplicableValidators &= PracticeCheckOFF;
}
break;
default:
// If it's a category for which we don't have validators, ignore it.
break;
}
}
void
SBMLInternalValidator::setConsistencyChecksForConversion(SBMLErrorCategory_t category,
bool apply)
{
switch (category)
{
case LIBSBML_CAT_IDENTIFIER_CONSISTENCY:
if (apply)
{
mApplicableValidatorsForConversion |= IdCheckON;
}
else
{
mApplicableValidatorsForConversion &= IdCheckOFF;
}
break;
case LIBSBML_CAT_GENERAL_CONSISTENCY:
if (apply)
{
mApplicableValidatorsForConversion |= SBMLCheckON;
}
else
{
mApplicableValidatorsForConversion &= SBMLCheckOFF;
}
break;
case LIBSBML_CAT_SBO_CONSISTENCY:
if (apply)
{
mApplicableValidatorsForConversion |= SBOCheckON;
}
else
{
mApplicableValidatorsForConversion &= SBOCheckOFF;
}
break;
case LIBSBML_CAT_MATHML_CONSISTENCY:
if (apply)
{
mApplicableValidatorsForConversion |= MathCheckON;
}
else
{
mApplicableValidatorsForConversion &= MathCheckOFF;
}
break;
case LIBSBML_CAT_UNITS_CONSISTENCY:
if (apply)
{
mApplicableValidatorsForConversion |= UnitsCheckON;
}
else
{
mApplicableValidatorsForConversion &= UnitsCheckOFF;
}
break;
case LIBSBML_CAT_OVERDETERMINED_MODEL:
if (apply)
{
mApplicableValidatorsForConversion |= OverdeterCheckON;
}
else
{
mApplicableValidatorsForConversion &= OverdeterCheckOFF;
}
break;
case LIBSBML_CAT_MODELING_PRACTICE:
if (apply)
{
mApplicableValidatorsForConversion |= PracticeCheckON;
}
else
{
mApplicableValidatorsForConversion &= PracticeCheckOFF;
}
break;
default:
// If it's a category for which we don't have validators, ignore it.
break;
}
}
/*
* Performs a set of semantic consistency checks on the document. Query
* the results by calling getNumErrors() and getError().
*
* @return the number of failed checks (errors) encountered.
*/
unsigned int
SBMLInternalValidator::checkConsistency (bool writeDocument)
{
unsigned int nerrors = 0;
unsigned int total_errors = 0;
//if (getLevel() == 3)
//{
// logError(L3NotSupported);
// return 1;
//}
/* determine which validators to run */
bool id = ((mApplicableValidators & 0x01) == 0x01);
bool sbml = ((mApplicableValidators & 0x02) == 0x02);
bool sbo = ((mApplicableValidators & 0x04) == 0x04);
bool math = ((mApplicableValidators & 0x08) == 0x08);
bool units = ((mApplicableValidators & 0x10) == 0x10);
bool over = ((mApplicableValidators & 0x20) == 0x20);
bool practice = ((mApplicableValidators & 0x40) == 0x40);
/* taken the state machine concept out for now
if (LibSBMLStateMachine::isActive())
{
units = LibSBMLStateMachine::getUnitState();
}
*/
SBMLDocument *doc;
SBMLErrorLog *log = getErrorLog();
if (writeDocument)
{
char* sbmlString = writeSBMLToString(getDocument());
log->clearLog();
doc = readSBMLFromString(sbmlString);
free (sbmlString);
}
else
{
doc = getDocument();
}
/* calls each specified validator in turn
* - stopping when errors are encountered */
/* look to see if we have serious errors from the read
* these may cause other validators to crash
* although hopefully not it is probably best to guard
* against trying
*/
bool seriousErrors = doc->getNumErrors(LIBSBML_SEV_FATAL) > 0
|| doc->getNumErrors(LIBSBML_SEV_ERROR) > 0;
// do not try and go further but do not report the errors as these
// will have been recorded elsewhere and do not come from the validators
if (seriousErrors == true)
{
return 0;
}
if (id)
{
IdentifierConsistencyValidator id_validator;
id_validator.init();
nerrors = id_validator.validate(*doc);
if (nerrors > 0)
{
unsigned int origNum = log->getNumErrors();
log->add( id_validator.getFailures() );
if (origNum > 0 && log->contains(InvalidUnitIdSyntax) == true)
{
/* do not log dangling ref */
while (log->contains(DanglingUnitSIdRef) == true)
{
log->remove(DanglingUnitSIdRef);
nerrors--;
}
total_errors += nerrors;
if (nerrors > 0)
{
if (writeDocument)
SBMLDocument_free(doc);
return total_errors;
}
}
else if (log->contains(DanglingUnitSIdRef) == false)
{
total_errors += nerrors;
if (writeDocument)
SBMLDocument_free(doc);
return total_errors;
}
else
{
bool onlyDangRef = true;
for (unsigned int a = 0; a < log->getNumErrors(); a++)
{
if (log->getError(a)->getErrorId() != DanglingUnitSIdRef)
{
onlyDangRef = false;
break;
}
}
total_errors += nerrors;
if (onlyDangRef == false)
{
if (writeDocument)
SBMLDocument_free(doc);
return total_errors;
}
}
}
}
if (sbml)
{
ConsistencyValidator validator;
validator.init();
nerrors = validator.validate(*doc);
total_errors += nerrors;
if (nerrors > 0)
{
log->add( validator.getFailures() );
/* only want to bail if errors not warnings */
if (log->getNumFailsWithSeverity(LIBSBML_SEV_ERROR) > 0)
{
if (writeDocument)
SBMLDocument_free(doc);
return total_errors;
}
}
}
if (sbo)
{
SBOConsistencyValidator sbo_validator;
sbo_validator.init();
nerrors = sbo_validator.validate(*doc);
total_errors += nerrors;
if (nerrors > 0)
{
log->add( sbo_validator.getFailures() );
/* only want to bail if errors not warnings */
if (log->getNumFailsWithSeverity(LIBSBML_SEV_ERROR) > 0)
{
if (writeDocument)
SBMLDocument_free(doc);
return total_errors;
}
}
}
if (math)
{
MathMLConsistencyValidator math_validator;
math_validator.init();
nerrors = math_validator.validate(*doc);
total_errors += nerrors;
if (nerrors > 0)
{
log->add( math_validator.getFailures() );
/* at this point bail if any problems
* unit checks may crash if there have been math errors/warnings
*/
if (writeDocument)
SBMLDocument_free(doc);
return total_errors;
}
}
if (units)
{
UnitConsistencyValidator unit_validator;
unit_validator.init();
nerrors = unit_validator.validate(*doc);
total_errors += nerrors;
if (nerrors > 0)
{
log->add( unit_validator.getFailures() );
/* only want to bail if errors not warnings */
if (log->getNumFailsWithSeverity(LIBSBML_SEV_ERROR) > 0)
{
if (writeDocument)
SBMLDocument_free(doc);
return total_errors;
}
}
}
/* do not even try if there have been unit warnings
* changed this as would have bailed */
if (over)
{
OverdeterminedValidator over_validator;
over_validator.init();
nerrors = over_validator.validate(*doc);
total_errors += nerrors;
if (nerrors > 0)
{
log->add( over_validator.getFailures() );
/* only want to bail if errors not warnings */
if (log->getNumFailsWithSeverity(LIBSBML_SEV_ERROR) > 0)
{
if (writeDocument)
SBMLDocument_free(doc);
return total_errors;
}
}
}
if (practice)
{
ModelingPracticeValidator practice_validator;
practice_validator.init();
nerrors = practice_validator.validate(*doc);
if (nerrors > 0)
{
unsigned int errorsAdded = 0;
const std::list<SBMLError> practiceErrors = practice_validator.getFailures();
list<SBMLError>::const_iterator end = practiceErrors.end();
list<SBMLError>::const_iterator iter;
for (iter = practiceErrors.begin(); iter != end; ++iter)
{
if (SBMLError(*iter).getErrorId() != 80701)
{
log->add( SBMLError(*iter) );
errorsAdded++;
}
else
{
if (units)
{
log->add( SBMLError(*iter) );
errorsAdded++;
}
}
}
total_errors += errorsAdded;
}
}
if (writeDocument)
SBMLDocument_free(doc);
return total_errors;
}
/*
* Performs consistency checking on libSBML's internal representation of
* an SBML Model.
*
* Callers should query the results of the consistency check by calling
* getError().
*
* @return the number of failed checks (errors) encountered.
*/
unsigned int
SBMLInternalValidator::checkInternalConsistency()
{
unsigned int nerrors = 0;
unsigned int totalerrors = 0;
InternalConsistencyValidator validator;
validator.init();
nerrors = validator.validate(*getDocument());
if (nerrors > 0)
{
getErrorLog()->add( validator.getFailures() );
}
totalerrors += nerrors;
/* hack to catch errors normally caught at read time */
char* doc = writeSBMLToString(getDocument());
SBMLDocument *d = readSBMLFromString(doc);
util_free(doc);
nerrors = d->getNumErrors();
for (unsigned int i = 0; i < nerrors; i++)
{
getErrorLog()->add(*(d->getError(i)));
}
delete d;
totalerrors += nerrors;
return totalerrors;
}
/*
* Performs a set of semantic consistency checks on the document to establish
* whether it is compatible with L1 and can be converted. Query
* the results by calling getNumErrors() and getError().
*
* @return the number of failed checks (errors) encountered.
*/
unsigned int
SBMLInternalValidator::checkL1Compatibility ()
{
if (getModel() == NULL) return 0;
L1CompatibilityValidator validator;
validator.init();
unsigned int nerrors = validator.validate(*getDocument());
if (nerrors > 0) getErrorLog()->add( validator.getFailures() );
return nerrors;
}
/*
* Performs a set of semantic consistency checks on the document to establish
* whether it is compatible with L2v1 and can be converted. Query
* the results by calling getNumErrors() and getError().
*
* @return the number of failed checks (errors) encountered.
*/
unsigned int
SBMLInternalValidator::checkL2v1Compatibility ()
{
if (getModel() == NULL) return 0;
L2v1CompatibilityValidator validator;
validator.init();
unsigned int nerrors = validator.validate(*getDocument());
if (nerrors > 0) getErrorLog()->add( validator.getFailures() );
return nerrors;
}
/*
* Performs a set of semantic consistency checks on the document to establish
* whether it is compatible with L2v2 and can be converted. Query
* the results by calling getNumErrors() and getError().
*
* @return the number of failed checks (errors) encountered.
*/
unsigned int
SBMLInternalValidator::checkL2v2Compatibility ()
{
if (getModel() == NULL) return 0;
L2v2CompatibilityValidator validator;
validator.init();
unsigned int nerrors = validator.validate(*getDocument());
if (nerrors > 0) getErrorLog()->add( validator.getFailures() );
return nerrors;
}
/*
* Performs a set of semantic consistency checks on the document to establish
* whether it is compatible with L2v3 and can be converted. Query
* the results by calling getNumErrors() and getError().
*
* @return the number of failed checks (errors) encountered.
*/
unsigned int
SBMLInternalValidator::checkL2v3Compatibility ()
{
if (getModel() == NULL) return 0;
L2v3CompatibilityValidator validator;
validator.init();
unsigned int nerrors = validator.validate(*getDocument());
if (nerrors > 0) getErrorLog()->add( validator.getFailures() );
return nerrors;
}
/*
* Performs a set of semantic consistency checks on the document to establish
* whether it is compatible with L2v4 and can be converted. Query
* the results by calling getNumErrors() and getError().
*
* @return the number of failed checks (errors) encountered.
*/
unsigned int
SBMLInternalValidator::checkL2v4Compatibility ()
{
if (getModel() == NULL) return 0;
L2v4CompatibilityValidator validator;
validator.init();
unsigned int nerrors = validator.validate(*getDocument());
if (nerrors > 0) getErrorLog()->add( validator.getFailures() );
return nerrors;
}
/*
* Performs a set of semantic consistency checks on the document to establish
* whether it is compatible with L2v4 and can be converted. Query
* the results by calling getNumErrors() and getError().
*
* @return the number of failed checks (errors) encountered.
*/
unsigned int
SBMLInternalValidator::checkL2v5Compatibility ()
{
if (getModel() == NULL) return 0;
// use the L2V4 validator as it is identical
L2v4CompatibilityValidator validator;
validator.init();
unsigned int nerrors = validator.validate(*getDocument());
if (nerrors > 0) getErrorLog()->add( validator.getFailures() );
return nerrors;
}
/*
* Performs a set of semantic consistency checks on the document to establish
* whether it is compatible with L2v1 and can be converted. Query
* the results by calling getNumErrors() and getError().
*
* @return the number of failed checks (errors) encountered.
*/
unsigned int
SBMLInternalValidator::checkL3v1Compatibility ()
{
if (getModel() == NULL) return 0;
L3v1CompatibilityValidator validator;
validator.init();
unsigned int nerrors = validator.validate(*getDocument());
if (nerrors > 0) getErrorLog()->add( validator.getFailures() );
return nerrors;
}
/*
* Performs a set of semantic consistency checks on the document to establish
* whether it is compatible with L3v2 and can be converted. Query
* the results by calling getNumErrors() and getError().
*
* @return the number of failed checks (errors) encountered.
*/
unsigned int
SBMLInternalValidator::checkL3v2Compatibility()
{
if (getModel() == NULL) return 0;
L3v2CompatibilityValidator validator;
validator.init();
unsigned int nerrors = validator.validate(*getDocument());
if (nerrors > 0) getErrorLog()->add(validator.getFailures());
return nerrors;
}
unsigned char
SBMLInternalValidator::getApplicableValidators() const
{
return mApplicableValidators;
}
unsigned char
SBMLInternalValidator::getConversionValidators() const
{
return mApplicableValidatorsForConversion;
}
void
SBMLInternalValidator::setApplicableValidators(unsigned char appl)
{
mApplicableValidators = appl;
}
void
SBMLInternalValidator::setConversionValidators(unsigned char appl)
{
mApplicableValidatorsForConversion = appl;
}
unsigned int
SBMLInternalValidator::validate()
{
return checkConsistency();
}
/** @cond doxygenIgnored */
/** @endcond */
LIBSBML_CPP_NAMESPACE_END
#endif /* __cplusplus */
| 24.344619 | 116 | 0.672379 | [
"object",
"vector",
"model"
] |
a2b4fc44405366332e9127fe5450b897d226d917 | 846 | cpp | C++ | src/engine/guidance/assemble_route.cpp | EricWang1hitsz/osrm-backend | ff1af413d6c78f8e454584fe978d5468d984d74a | [
"BSD-2-Clause"
] | 4,526 | 2015-01-01T15:31:00.000Z | 2022-03-31T17:33:49.000Z | src/engine/guidance/assemble_route.cpp | serarca/osrm-backend | 3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb | [
"BSD-2-Clause"
] | 4,497 | 2015-01-01T15:29:12.000Z | 2022-03-31T19:19:35.000Z | src/engine/guidance/assemble_route.cpp | serarca/osrm-backend | 3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb | [
"BSD-2-Clause"
] | 3,023 | 2015-01-01T18:40:53.000Z | 2022-03-30T13:30:46.000Z | #include "engine/guidance/assemble_route.hpp"
#include <numeric>
namespace osrm
{
namespace engine
{
namespace guidance
{
Route assembleRoute(const std::vector<RouteLeg> &route_legs)
{
auto distance = std::accumulate(
route_legs.begin(), route_legs.end(), 0., [](const double sum, const RouteLeg &leg) {
return sum + leg.distance;
});
auto duration = std::accumulate(
route_legs.begin(), route_legs.end(), 0., [](const double sum, const RouteLeg &leg) {
return sum + leg.duration;
});
auto weight = std::accumulate(
route_legs.begin(), route_legs.end(), 0., [](const double sum, const RouteLeg &leg) {
return sum + leg.weight;
});
return Route{distance, duration, weight};
}
} // namespace guidance
} // namespace engine
} // namespace osrm
| 25.636364 | 93 | 0.630024 | [
"vector"
] |
a2d52ed8c2671dc64920c1cdefb4ab09d91efeb7 | 588 | cpp | C++ | 07 July Leetcode Challenge 2021/06_minSetSize.cpp | FazeelUsmani/Leetcode | aff4c119178f132c28a39506ffaa75606e0a861b | [
"MIT"
] | 7 | 2020-12-01T14:27:57.000Z | 2022-02-12T09:17:22.000Z | 07 July Leetcode Challenge 2021/06_minSetSize.cpp | FazeelUsmani/Leetcode | aff4c119178f132c28a39506ffaa75606e0a861b | [
"MIT"
] | 4 | 2020-11-12T17:49:22.000Z | 2021-09-06T07:46:37.000Z | 07 July Leetcode Challenge 2021/06_minSetSize.cpp | FazeelUsmani/Leetcode | aff4c119178f132c28a39506ffaa75606e0a861b | [
"MIT"
] | 6 | 2021-05-21T03:49:22.000Z | 2022-01-20T20:36:53.000Z | class Solution {
public:
int minSetSize(vector<int>& arr) {
unordered_map<int, int> cnt;
for (int x : arr) ++cnt[x];
vector<int> bucket(1e5 + 1);
int maxFreq = 1;
for (auto [_, freq] : cnt) {
++bucket[freq];
maxFreq = max(maxFreq, freq);
}
int ans = 0, removed = 0, half = arr.size() / 2, freq = maxFreq;
while (removed < half) {
ans += 1;
while (bucket[freq] == 0) --freq;
removed += freq;
--bucket[freq];
}
return ans;
}
};
| 24.5 | 72 | 0.44898 | [
"vector"
] |
a2d8a77774b37779035ef34defb0d3b023612ecd | 9,138 | cpp | C++ | TrabalhoPOO/Game.cpp | mbcrocci/TrabalhoPOO | 30378382b412e3ed875dbb2bfb897061dafc73ef | [
"MIT"
] | null | null | null | TrabalhoPOO/Game.cpp | mbcrocci/TrabalhoPOO | 30378382b412e3ed875dbb2bfb897061dafc73ef | [
"MIT"
] | null | null | null | TrabalhoPOO/Game.cpp | mbcrocci/TrabalhoPOO | 30378382b412e3ed875dbb2bfb897061dafc73ef | [
"MIT"
] | null | null | null | #include "Game.h"
Game::Game () : tick_ ( 0 )
{ }
Game::~Game ()
{}
int Game::getTick() const
{
return tick_;
}
std::string Game::list_configs () const
{
std::ostringstream oss;
oss << "Config:\n"
<< "\tWidth: " << config_world_width_ << "\n"
<< "\tHeight: " << config_world_heigth_ << "\n"
<< "\tNCoins: " << config_num_coins_ << "\n"
<< "\tNCOlonies: " << config_num_colonies << "\n"
<< "\tColonies:\n";
for ( auto const & colony : colonies_map_ )
oss << "\t\t" << colony.first << ": (" << colony.second.first << "," << colony.second.second << ")\n";
// TODO: profiles
return oss.str ();
}
void Game::makeProfile ( std::string p_name )
{
bool found = false;
for ( auto profile : profiles_ )
if ( profile->getName () != p_name )
found = true;
if ( !found )
profiles_.push_back ( std::make_shared<Profile> ( p_name ) );
}
void Game::addToProfile ( std::string p_name, std::string trait )
{
auto profile = findProfile ( p_name );
if ( profile )
{
profile->addTrait ( trait );
}
}
void Game::removeProfile ( std::string p_name )
{
int pos;
for ( unsigned int i = 0; i < profiles_.size (); i++ )
if ( profiles_[ i ]->getName () == p_name )
pos = i;
profiles_.erase ( profiles_.begin () + pos, profiles_.end () );
}
std::shared_ptr<Profile> Game::findProfile ( std::string s )
{
for ( auto p : profiles_ )
if ( p->getName () == s )
return p;
return nullptr;
}
bool Game::colonyExists ( std::string c_name ) const
{
if ( colonies_map_.find ( c_name ) != colonies_map_.end () )
return true;
return false;
}
void Game::loadInitFile(std::string file_name)
{
auto commands = input_handler_.read_file ( file_name );
for ( auto command : commands )
if ( command[ 0 ] == "dim" )
{
if ( command.size () != 3 )
continue;
auto w = std::stoi ( command[ 1 ] );
auto h = std::stoi ( command[ 2 ] );
//TODO: validade
config_world_width_ = w;
config_world_heigth_ = h;
}
else if ( command[ 0 ] == "moedas" )
{
if ( command.size () != 2 )
continue;
auto n = std::stoi ( command[ 1 ] );
//TODO: validade
config_num_coins_ = n;
}
else if ( command[ 0 ] == "oponentes" )
{
if ( command.size () != 2 )
continue;
auto n = std::stoi ( command[ 1 ] );
//TODO: validade
config_num_colonies = n;
}
else if ( command[ 0 ] == "castelo" )
{
if ( command.size () != 4 || config_num_colonies <= 0 )
continue;
//TODO: validade colony
if ( colonyExists ( command[ 1 ] ) )
continue;
auto l = std::stoi ( command[ 2 ] );
auto c = std::stoi ( command[ 3 ] );
//TODO: validade
colonies_map_[ command[ 1 ] ] = std::make_pair ( l, c );
}
else if ( command[ 0 ] == "mkperfil" )
{
if ( command.size () != 2 )
continue;
//TODO: validate
makeProfile ( command[ 1 ] );
}
else if ( command[ 0 ] == "addperfil" )
{
if ( command.size () != 3 )
continue;
// TODO: validate
addToProfile ( command[ 1 ], command[ 2 ] );
}
else if ( command[ 0 ] == "subperfil" )
{
if ( command.size () != 3 )
continue;
// TODO: validate
addToProfile ( command[ 1 ], command[ 2 ] );
}
else if ( command[ 0 ] == "rmperfil" )
{
if ( command.size () != 2 )
continue;
removeProfile ( command[ 1 ] );
}
else if ( command[ 0 ] == "load" )
{
if ( command.size () != 2 )
continue;
loadInitFile ( command[ 1 ] );
}
else if ( command[ 0 ] == "inicio" )
{
// doesnt do anything, use it in init loop to start the game
break;
}
}
void Game::init ()
{
while ( true )
{
auto command = input_handler_.handleInput ();
if ( command[ 0 ] == "dim" )
{
if ( command.size () != 3 )
continue;
auto w = std::stoi ( command[ 1 ] );
auto h = std::stoi ( command[ 2 ] );
//TODO: validade
config_world_width_ = w;
config_world_heigth_ = h;
}
else if ( command[ 0 ] == "moedas" )
{
if ( command.size () != 2 )
continue;
auto n = std::stoi ( command[ 1 ] );
//TODO: validade
config_num_coins_ = n;
}
else if ( command[ 0 ] == "oponentes" )
{
if ( command.size () != 2 )
continue;
auto n = std::stoi ( command[ 1 ] );
//TODO: validade
config_num_colonies = n;
}
else if ( command[ 0 ] == "castelo" )
{
if ( command.size () != 4 || config_num_colonies <= 0 )
continue;
//TODO: validade colony
if ( colonyExists ( command[ 1 ] ) )
continue;
auto l = std::stoi ( command[ 2 ] );
auto c = std::stoi ( command[ 3 ] );
//TODO: validade
colonies_map_[ command[ 1 ] ] = std::make_pair ( l, c );
}
else if ( command[ 0 ] == "mkperfil" )
{
if ( command.size () != 2 )
continue;
//TODO: validate
makeProfile ( command[ 1 ] );
}
else if ( command[ 0 ] == "addperfil" )
{
if ( command.size () != 3 )
continue;
// TODO: validate
addToProfile ( command[ 1 ], command[ 2 ] );
}
else if ( command[ 0 ] == "subperfil" )
{
if ( command.size () != 3 )
continue;
// TODO: validate
addToProfile ( command[ 1 ], command[ 2 ] );
}
else if ( command[ 0 ] == "rmperfil" )
{
if ( command.size () != 2 )
continue;
removeProfile ( command[ 1 ] );
}
else if ( command[ 0 ] == "load" )
{
if ( command.size () != 2 )
continue;
loadInitFile ( command[ 1 ] );
}
else if ( command[ 0 ] == "inicio" )
{
break;
}
else
{
std::cout << "Command invalid!\n";
}
}
}
void Game::run ()
{
Consola::clrscr ();
World world_(
config_world_width_, config_world_heigth_,
config_num_coins_, colonies_map_, profiles_
);
// show once before startin game loop
render ( world_ );
while ( true )
{
//std::chrono::time_point<std::chrono::system_clock> start, end;
//start = std::chrono::system_clock::now (); // gets current time
Consola::debugPrint ( "listing all entities" );
Consola::debugPrint ( world_.list_all_entities () );
// Get input
auto command = input_handler_.handleInput ();
if ( command[0] == "foco" )
{
if ( command.size () != 3 )
continue;
auto w = std::stoi ( command[ 1 ] );
auto h = std::stoi ( command[ 2 ] );
//TODO: validate
world_.setViewCoord ( w, h );
}
else if ( command[ 0 ] == "zoomout" )
{
if ( command.size () != 2 )
continue;
auto n = std::stoi ( command[ 1 ] );
//TODO: validate
world_.zoomOutN ( n );
}
else if ( command[ 0 ] == "setmoedas" )
{
if ( command.size () != 3 )
continue;
auto n = std::stoi ( command[ 2 ] );
world_.setColonyCoins ( command[ 1 ], n );
}
else if ( command[ 0 ] == "build" )
{
}
else if ( command[ 0 ] == "list" )
{
continue;
}
else if ( command[ 0 ] == "listp" )
{
continue;
}
else if ( command[ 0 ] == "listallp" )
{
continue;
}
else if ( command[ 0 ] == "mkbuild" )
{
continue;
}
else if ( command[ 0 ] == "repair" )
{
continue;
}
else if ( command[ 0 ] == "upgrade" )
{
continue;
}
else if ( command[ 0 ] == "sell" )
{
continue;
}
else if ( command[ 0 ] == "ser" )
{
if ( command.size() != 3 )
continue;
auto num = std::stoi ( command[ 1 ] );
for ( auto i = 0; i < num; i++ )
world_.makeBeeing ( command[ 2 ] );
}
else if ( command[ 0 ] == "next" )
{
// go to next iteration = next tick
continue;
}
else if ( command[ 0 ] == "nextn" )
{
if ( command.size() != 2 )
continue;
auto n = std::stoi ( command[ 1 ] );
tick_ += n - 1; // -1 because it will always increase after render()
}
else if ( command[ 0 ] == "ataca" )
{
// TODO: Do this right!
auto coord = world_.getUserColony ()->getCastle ()->getCoord ();
auto beeings = world_.getAllBeeings ( coord.first, coord.second );
for ( auto beeing : beeings )
beeing->setCoord ( coord.first + 2, coord.second + 3 );
}
else if ( command[ 0 ] == "recolhe" )
{
continue;
}
else if ( command[ 0 ] == "fim" )
{
break;
}
else if ( command[ 0 ] == "save" )
{
continue;
}
else if ( command[ 0 ] == "restore" )
{
continue;
}
else if ( command[ 0 ] == "erase" )
{
continue;
}
else if ( command[ 0 ] == "load" )
{
continue;
}
else
{
std::cout << "Command invalid!\n";
}
//update ();
render (world_);
tick_++;
//end = std::chrono::system_clock::now ();
//std::this_thread::sleep_for ( std::chrono::milliseconds ( start + MS_PER_FRAME - end ) );
}
}
void Game::render( World& world_) const
{
Consola::clrscr ();
//Consola::debugPrint ( list_configs () );
//Consola::debugPrint ( world_.list_config () );
auto view_coord = world_.getViewCoord ();
auto view_limit = world_.getViewLimits ();
for ( auto y = view_coord.second; y < view_limit.second; y++ )
{
for ( auto x = view_coord.first; x < view_limit.first; x++ )
{
std::string chr;
auto entity = world_.getFirstEntity ( x, y );
if ( entity )
{
Consola::setTextColor ( Consola::VERDE );
std::cout << entity->getString ();
Consola::setTextColor ( Consola::BRANCO );
}
else
{
std::cout << "_";
}
}
std::cout << "\n";
}
}
| 20.083516 | 104 | 0.550886 | [
"render"
] |
a2e7ae2a84b0c55cfbeb09502772a7a5fc5044de | 8,807 | cpp | C++ | source/librenderer/geometry.cpp | Lauvak/ray | 906d3991ddd232a7f78f0e51f29aeead008a139a | [
"BSD-3-Clause"
] | 113 | 2015-06-25T06:24:59.000Z | 2021-09-26T02:46:02.000Z | source/librenderer/geometry.cpp | Lauvak/ray | 906d3991ddd232a7f78f0e51f29aeead008a139a | [
"BSD-3-Clause"
] | 2 | 2015-05-03T07:22:49.000Z | 2017-12-11T09:17:20.000Z | source/librenderer/geometry.cpp | Lauvak/ray | 906d3991ddd232a7f78f0e51f29aeead008a139a | [
"BSD-3-Clause"
] | 17 | 2015-11-10T15:07:15.000Z | 2021-01-19T15:28:16.000Z | // +----------------------------------------------------------------------
// | Project : ray.
// | All rights reserved.
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014.
// +----------------------------------------------------------------------
// | * Redistribution and use of this software in source and binary forms,
// | with or without modification, are permitted provided that the following
// | conditions are met:
// |
// | * Redistributions of source code must retain the above
// | copyright notice, this list of conditions and the
// | following disclaimer.
// |
// | * Redistributions in binary form must reproduce the above
// | copyright notice, this list of conditions and the
// | following disclaimer in the documentation and/or other
// | materials provided with the distribution.
// |
// | * Neither the name of the ray team, nor the names of its
// | contributors may be used to endorse or promote products
// | derived from this software without specific prior
// | written permission of the ray team.
// |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// +----------------------------------------------------------------------
#include <ray/geometry.h>
#include <ray/render_pipeline.h>
#include <ray/render_object_manager.h>
#include <ray/material.h>
#include <ray/graphics_data.h>
#include <ray/camera.h>
_NAME_BEGIN
__ImplementSubClass(Geometry, RenderObject, "Geometry")
GraphicsIndirect::GraphicsIndirect() noexcept
: startVertice(0)
, startIndice(0)
, startInstances(0)
, numVertices(0)
, numIndices(0)
, numInstances(1)
{
}
GraphicsIndirect::GraphicsIndirect(std::uint32_t _numVertices, std::uint32_t _numIndices, std::uint32_t _numInstance, std::uint32_t _startVertice, std::uint32_t _startIndice, std::uint32_t _startInstance) noexcept
: startVertice(_startVertice)
, startIndice(_startIndice)
, startInstances(_startInstance)
, numVertices(_numVertices)
, numIndices(_numIndices)
, numInstances(_numInstance)
{
}
Geometry::Geometry() noexcept
: _isCastShadow(true)
, _isReceiveShadow(true)
, _indexType(GraphicsIndexType::GraphicsIndexTypeUInt32)
, _vertexOffset(0)
, _indexOffset(0)
{
}
Geometry::~Geometry() noexcept
{
}
void
Geometry::setReceiveShadow(bool enable) noexcept
{
_isReceiveShadow = enable;
}
bool
Geometry::getReceiveShadow() const noexcept
{
return _isReceiveShadow;
}
void
Geometry::setCastShadow(bool value) noexcept
{
_isCastShadow = value;
}
bool
Geometry::getCastShadow() const noexcept
{
return _isCastShadow;
}
void
Geometry::setMaterial(const MaterialPtr& material) noexcept
{
if (_material != material)
{
if (material)
{
const auto& techs = material->getTechs();
for (auto& tech : techs)
{
RenderQueue queue = stringToRenderQueue(tech->getName());
if (queue == RenderQueue::RenderQueueMaxEnum)
continue;
_techniques[queue] = tech;
}
}
else
{
for (std::size_t i = 0; i < RenderQueue::RenderQueueRangeSize; i++)
_techniques[i] = nullptr;
}
_material = material;
}
}
const MaterialPtr&
Geometry::getMaterial() noexcept
{
return _material;
}
void
Geometry::setVertexBuffer(const GraphicsDataPtr& data, std::intptr_t offset) noexcept
{
assert(!data || (data && data->getGraphicsDataDesc().getType() == GraphicsDataType::GraphicsDataTypeStorageVertexBuffer));
_vbo = data;
_vertexOffset = offset;
}
const GraphicsDataPtr&
Geometry::getVertexBuffer() const noexcept
{
return _vbo;
}
void
Geometry::setIndexBuffer(const GraphicsDataPtr& data, std::intptr_t offset, GraphicsIndexType indexType) noexcept
{
assert(!data || (data && data->getGraphicsDataDesc().getType() == GraphicsDataType::GraphicsDataTypeStorageIndexBuffer));
assert(indexType == GraphicsIndexType::GraphicsIndexTypeUInt16 || indexType == GraphicsIndexType::GraphicsIndexTypeUInt32);
_ibo = data;
_indexType = indexType;
}
const GraphicsDataPtr&
Geometry::getIndexBuffer() const noexcept
{
return _ibo;
}
void
Geometry::setGraphicsIndirect(GraphicsIndirectPtr&& renderable) noexcept
{
_renderable = std::move(renderable);
}
void
Geometry::setGraphicsIndirect(const GraphicsIndirectPtr& renderable) noexcept
{
_renderable = renderable;
}
GraphicsIndirectPtr
Geometry::getGraphicsIndirect() noexcept
{
return _renderable;
}
bool
Geometry::onVisiableTest(const Camera& camera, const Frustum& fru) noexcept
{
if (camera.getCameraOrder() == CameraOrder::CameraOrderShadow)
{
if (!this->getCastShadow())
return false;
}
if (camera.getCameraType() == CameraType::CameraTypeCube)
return math::sqrDistance(camera.getTranslate(), this->getTranslate()) < (camera.getFar() * camera.getFar());
else
return fru.contains(this->getBoundingBoxInWorld().aabb());
}
void
Geometry::onAddRenderData(RenderDataManager& manager) noexcept
{
if (this->getCastShadow())
{
if (_techniques[RenderQueue::RenderQueueShadow])
manager.addRenderData(RenderQueue::RenderQueueShadow, this);
if (_techniques[RenderQueue::RenderQueueReflectiveShadow])
manager.addRenderData(RenderQueue::RenderQueueReflectiveShadow, this);
}
for (std::size_t i = 0; i < RenderQueue::RenderQueueRangeSize; i++)
{
if (i != RenderQueue::RenderQueueShadow && i != RenderQueue::RenderQueueReflectiveShadow)
{
if (_techniques[i])
manager.addRenderData((RenderQueue)i, this);
}
}
}
void
Geometry::onRenderObject(RenderPipeline& pipeline, RenderQueue queue, MaterialTech* tech) noexcept
{
if (_techniques[queue] || tech)
{
pipeline.setTransform(this->getTransform());
pipeline.setTransformInverse(this->getTransformInverse());
if (_vbo)
pipeline.setVertexBuffer(0, _vbo, _vertexOffset);
if (_ibo)
pipeline.setIndexBuffer(_ibo, _indexOffset, _indexType);
if (_techniques[queue])
{
auto& passList = _techniques[queue]->getPassList();
for (auto& pass : passList)
{
pipeline.setMaterialPass(pass);
pipeline.drawIndexedLayer(_renderable->numIndices, _renderable->numInstances, _renderable->startIndice, _renderable->startVertice, _renderable->startInstances, this->getLayer());
}
}
else if (tech)
{
auto& passList = tech->getPassList();
for (auto& pass : passList)
{
pipeline.setMaterialPass(pass);
pipeline.drawIndexedLayer(_renderable->numIndices, _renderable->numInstances, _renderable->startIndice, _renderable->startVertice, _renderable->startInstances, this->getLayer());
}
}
}
}
RenderQueue
Geometry::stringToRenderQueue(const std::string& techName) noexcept
{
if (techName == "Custom") return RenderQueue::RenderQueueCustom;
if (techName == "Shadow") return RenderQueue::RenderQueueShadow;
if (techName == "ReflectiveShadow") return RenderQueue::RenderQueueReflectiveShadow;
if (techName == "Opaque") return RenderQueue::RenderQueueOpaque;
if (techName == "OpaqueBatch") return RenderQueue::RenderQueueOpaqueBatch;
if (techName == "OpaqueSpecific") return RenderQueue::RenderQueueOpaqueSpecific;
if (techName == "OpaqueShading") return RenderQueue::RenderQueueOpaqueShading;
if (techName == "TransparentBack") return RenderQueue::RenderQueueTransparentBack;
if (techName == "TransparentBatchBack") return RenderQueue::RenderQueueTransparentBatchBack;
if (techName == "TransparentShadingBack") return RenderQueue::RenderQueueTransparentShadingBack;
if (techName == "TransparentSpecificBack") return RenderQueue::RenderQueueTransparentSpecificBack;
if (techName == "TransparentFront") return RenderQueue::RenderQueueTransparentFront;
if (techName == "TransparentBatchFront") return RenderQueue::RenderQueueTransparentBatchFront;
if (techName == "TransparentShadingFront") return RenderQueue::RenderQueueTransparentShadingFront;
if (techName == "TransparentSpecificFront") return RenderQueue::RenderQueueTransparentSpecificFront;
if (techName == "Lighting") return RenderQueue::RenderQueueLights;
if (techName == "Postprocess") return RenderQueue::RenderQueuePostprocess;
return RenderQueue::RenderQueueMaxEnum;
}
_NAME_END | 31.341637 | 213 | 0.726127 | [
"geometry"
] |
a2e9949a35b4d3cd376d57eb112458d0e33d1ef5 | 476 | cc | C++ | codechef/jan18/monster.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 506 | 2018-08-22T10:30:38.000Z | 2022-03-31T10:01:49.000Z | codechef/jan18/monster.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 13 | 2019-08-07T18:31:18.000Z | 2020-12-15T21:54:41.000Z | codechef/jan18/monster.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 234 | 2018-08-06T17:11:41.000Z | 2022-03-26T10:56:42.000Z | // https://www.codechef.com/JAN18/problems/MONSTER
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> vi;
int main() {
int n, q, x, y;
cin >> n;
vi h(n + 1);
for (int i = 0; i < n; i++) cin >> h[i];
cin >> q;
int c = n;
for (int i = 0; i < q; i++) {
cin >> x >> y;
for (int j = 0; j < n; j++) {
if ((j & x) == j && h[j] > 0) {
h[j] -= y;
if (h[j] <= 0) c--;
}
}
cout << c << endl;
}
}
| 17.62963 | 50 | 0.426471 | [
"vector"
] |
a2e9ba824e47515ac741e77759117fb9a4f396d1 | 31,512 | hpp | C++ | Drivers/ScanLabOIE/Headers/CppDynamic/libmcdriver_scanlaboie_dynamic.hpp | FabianSpangler/AutodeskMachineControlFramework | da257a4a609edbbdf3d7c5d834d61f8555c68e09 | [
"BSD-3-Clause"
] | null | null | null | Drivers/ScanLabOIE/Headers/CppDynamic/libmcdriver_scanlaboie_dynamic.hpp | FabianSpangler/AutodeskMachineControlFramework | da257a4a609edbbdf3d7c5d834d61f8555c68e09 | [
"BSD-3-Clause"
] | null | null | null | Drivers/ScanLabOIE/Headers/CppDynamic/libmcdriver_scanlaboie_dynamic.hpp | FabianSpangler/AutodeskMachineControlFramework | da257a4a609edbbdf3d7c5d834d61f8555c68e09 | [
"BSD-3-Clause"
] | null | null | null | /*++
Copyright (C) 2020 Autodesk Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Autodesk Inc. nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL AUTODESK INC. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This file has been generated by the Automatic Component Toolkit (ACT) version 1.7.0-develop.
Abstract: This is an autogenerated C++-Header file in order to allow an easy
use of MC Driver ScanLab Open Interface Extension
Interface version: 1.0.0
*/
#ifndef __LIBMCDRIVER_SCANLABOIE_CPPHEADER_DYNAMIC_CPP
#define __LIBMCDRIVER_SCANLABOIE_CPPHEADER_DYNAMIC_CPP
#include "libmcdriver_scanlaboie_types.hpp"
#include "libmcdriver_scanlaboie_dynamic.h"
#include "libmcdriverenv_dynamic.hpp"
#ifdef _WIN32
#include <windows.h>
#else // _WIN32
#include <dlfcn.h>
#endif // _WIN32
#include <string>
#include <memory>
#include <vector>
#include <exception>
namespace LibMCDriver_ScanLabOIE {
/*************************************************************************************************************************
Forward Declaration of all classes
**************************************************************************************************************************/
class CWrapper;
class CBase;
class CDriver;
class CDriver_ScanLab_OIE;
/*************************************************************************************************************************
Declaration of deprecated class types
**************************************************************************************************************************/
typedef CWrapper CLibMCDriver_ScanLabOIEWrapper;
typedef CBase CLibMCDriver_ScanLabOIEBase;
typedef CDriver CLibMCDriver_ScanLabOIEDriver;
typedef CDriver_ScanLab_OIE CLibMCDriver_ScanLabOIEDriver_ScanLab_OIE;
/*************************************************************************************************************************
Declaration of shared pointer types
**************************************************************************************************************************/
typedef std::shared_ptr<CWrapper> PWrapper;
typedef std::shared_ptr<CBase> PBase;
typedef std::shared_ptr<CDriver> PDriver;
typedef std::shared_ptr<CDriver_ScanLab_OIE> PDriver_ScanLab_OIE;
/*************************************************************************************************************************
Declaration of deprecated shared pointer types
**************************************************************************************************************************/
typedef PWrapper PLibMCDriver_ScanLabOIEWrapper;
typedef PBase PLibMCDriver_ScanLabOIEBase;
typedef PDriver PLibMCDriver_ScanLabOIEDriver;
typedef PDriver_ScanLab_OIE PLibMCDriver_ScanLabOIEDriver_ScanLab_OIE;
/*************************************************************************************************************************
classParam Definition
**************************************************************************************************************************/
template<class T> class classParam {
private:
const T* m_ptr;
public:
classParam(const T* ptr)
: m_ptr (ptr)
{
}
classParam(std::shared_ptr <T> sharedPtr)
: m_ptr (sharedPtr.get())
{
}
LibMCDriver_ScanLabOIEHandle GetHandle()
{
if (m_ptr != nullptr)
return m_ptr->handle();
return nullptr;
}
};
/*************************************************************************************************************************
Class ELibMCDriver_ScanLabOIEException
**************************************************************************************************************************/
class ELibMCDriver_ScanLabOIEException : public std::exception {
protected:
/**
* Error code for the Exception.
*/
LibMCDriver_ScanLabOIEResult m_errorCode;
/**
* Error message for the Exception.
*/
std::string m_errorMessage;
public:
/**
* Exception Constructor.
*/
ELibMCDriver_ScanLabOIEException(LibMCDriver_ScanLabOIEResult errorCode, const std::string & sErrorMessage)
: m_errorMessage("LibMCDriver_ScanLabOIE Error " + std::to_string(errorCode) + " (" + sErrorMessage + ")")
{
m_errorCode = errorCode;
}
/**
* Returns error code
*/
LibMCDriver_ScanLabOIEResult getErrorCode() const noexcept
{
return m_errorCode;
}
/**
* Returns error message
*/
const char* what() const noexcept
{
return m_errorMessage.c_str();
}
};
/*************************************************************************************************************************
Class CInputVector
**************************************************************************************************************************/
template <typename T>
class CInputVector {
private:
const T* m_data;
size_t m_size;
public:
CInputVector( const std::vector<T>& vec)
: m_data( vec.data() ), m_size( vec.size() )
{
}
CInputVector( const T* in_data, size_t in_size)
: m_data( in_data ), m_size(in_size )
{
}
const T* data() const
{
return m_data;
}
size_t size() const
{
return m_size;
}
};
// declare deprecated class name
template<typename T>
using CLibMCDriver_ScanLabOIEInputVector = CInputVector<T>;
/*************************************************************************************************************************
Class CWrapper
**************************************************************************************************************************/
class CWrapper {
public:
CWrapper(void* pSymbolLookupMethod)
{
CheckError(nullptr, initWrapperTable(&m_WrapperTable));
CheckError(nullptr, loadWrapperTableFromSymbolLookupMethod(&m_WrapperTable, pSymbolLookupMethod));
CheckError(nullptr, checkBinaryVersion());
}
CWrapper(const std::string &sFileName)
{
CheckError(nullptr, initWrapperTable(&m_WrapperTable));
CheckError(nullptr, loadWrapperTable(&m_WrapperTable, sFileName.c_str()));
CheckError(nullptr, checkBinaryVersion());
}
static PWrapper loadLibrary(const std::string &sFileName)
{
return std::make_shared<CWrapper>(sFileName);
}
static PWrapper loadLibraryFromSymbolLookupMethod(void* pSymbolLookupMethod)
{
return std::make_shared<CWrapper>(pSymbolLookupMethod);
}
~CWrapper()
{
releaseWrapperTable(&m_WrapperTable);
}
inline void CheckError(CBase * pBaseClass, LibMCDriver_ScanLabOIEResult nResult);
inline void GetVersion(LibMCDriver_ScanLabOIE_uint32 & nMajor, LibMCDriver_ScanLabOIE_uint32 & nMinor, LibMCDriver_ScanLabOIE_uint32 & nMicro);
inline bool GetLastError(classParam<CBase> pInstance, std::string & sErrorMessage);
inline void ReleaseInstance(classParam<CBase> pInstance);
inline void AcquireInstance(classParam<CBase> pInstance);
inline void InjectComponent(const std::string & sNameSpace, const LibMCDriver_ScanLabOIE_pvoid pSymbolAddressMethod);
inline LibMCDriver_ScanLabOIE_pvoid GetSymbolLookupMethod();
inline PDriver CreateDriver(const std::string & sName, const std::string & sType, classParam<LibMCDriverEnv::CDriverEnvironment> pDriverEnvironment);
private:
sLibMCDriver_ScanLabOIEDynamicWrapperTable m_WrapperTable;
// Injected Components
LibMCDriverEnv::PWrapper m_pLibMCDriverEnvWrapper;
LibMCDriver_ScanLabOIEResult checkBinaryVersion()
{
LibMCDriver_ScanLabOIE_uint32 nMajor, nMinor, nMicro;
GetVersion(nMajor, nMinor, nMicro);
if ( (nMajor != LIBMCDRIVER_SCANLABOIE_VERSION_MAJOR) || (nMinor < LIBMCDRIVER_SCANLABOIE_VERSION_MINOR) ) {
return LIBMCDRIVER_SCANLABOIE_ERROR_INCOMPATIBLEBINARYVERSION;
}
return LIBMCDRIVER_SCANLABOIE_SUCCESS;
}
LibMCDriver_ScanLabOIEResult initWrapperTable(sLibMCDriver_ScanLabOIEDynamicWrapperTable * pWrapperTable);
LibMCDriver_ScanLabOIEResult releaseWrapperTable(sLibMCDriver_ScanLabOIEDynamicWrapperTable * pWrapperTable);
LibMCDriver_ScanLabOIEResult loadWrapperTable(sLibMCDriver_ScanLabOIEDynamicWrapperTable * pWrapperTable, const char * pLibraryFileName);
LibMCDriver_ScanLabOIEResult loadWrapperTableFromSymbolLookupMethod(sLibMCDriver_ScanLabOIEDynamicWrapperTable * pWrapperTable, void* pSymbolLookupMethod);
friend class CBase;
friend class CDriver;
friend class CDriver_ScanLab_OIE;
};
/*************************************************************************************************************************
Class CBase
**************************************************************************************************************************/
class CBase {
public:
protected:
/* Wrapper Object that created the class. */
CWrapper * m_pWrapper;
/* Handle to Instance in library*/
LibMCDriver_ScanLabOIEHandle m_pHandle;
/* Checks for an Error code and raises Exceptions */
void CheckError(LibMCDriver_ScanLabOIEResult nResult)
{
if (m_pWrapper != nullptr)
m_pWrapper->CheckError(this, nResult);
}
public:
/**
* CBase::CBase - Constructor for Base class.
*/
CBase(CWrapper * pWrapper, LibMCDriver_ScanLabOIEHandle pHandle)
: m_pWrapper(pWrapper), m_pHandle(pHandle)
{
}
/**
* CBase::~CBase - Destructor for Base class.
*/
virtual ~CBase()
{
if (m_pWrapper != nullptr)
m_pWrapper->ReleaseInstance(this);
m_pWrapper = nullptr;
}
/**
* CBase::handle - Returns handle to instance.
*/
LibMCDriver_ScanLabOIEHandle handle() const
{
return m_pHandle;
}
/**
* CBase::wrapper - Returns wrapper instance.
*/
CWrapper * wrapper() const
{
return m_pWrapper;
}
friend class CWrapper;
};
/*************************************************************************************************************************
Class CDriver
**************************************************************************************************************************/
class CDriver : public CBase {
public:
/**
* CDriver::CDriver - Constructor for Driver class.
*/
CDriver(CWrapper* pWrapper, LibMCDriver_ScanLabOIEHandle pHandle)
: CBase(pWrapper, pHandle)
{
}
inline std::string GetName();
inline std::string GetType();
inline void GetVersion(LibMCDriver_ScanLabOIE_uint32 & nMajor, LibMCDriver_ScanLabOIE_uint32 & nMinor, LibMCDriver_ScanLabOIE_uint32 & nMicro, std::string & sBuild);
inline void GetHeaderInformation(std::string & sNameSpace, std::string & sBaseName);
};
/*************************************************************************************************************************
Class CDriver_ScanLab_OIE
**************************************************************************************************************************/
class CDriver_ScanLab_OIE : public CDriver {
public:
/**
* CDriver_ScanLab_OIE::CDriver_ScanLab_OIE - Constructor for Driver_ScanLab_OIE class.
*/
CDriver_ScanLab_OIE(CWrapper* pWrapper, LibMCDriver_ScanLabOIEHandle pHandle)
: CDriver(pWrapper, pHandle)
{
}
};
/**
* CWrapper::GetVersion - retrieves the binary version of this library.
* @param[out] nMajor - returns the major version of this library
* @param[out] nMinor - returns the minor version of this library
* @param[out] nMicro - returns the micro version of this library
*/
inline void CWrapper::GetVersion(LibMCDriver_ScanLabOIE_uint32 & nMajor, LibMCDriver_ScanLabOIE_uint32 & nMinor, LibMCDriver_ScanLabOIE_uint32 & nMicro)
{
CheckError(nullptr,m_WrapperTable.m_GetVersion(&nMajor, &nMinor, &nMicro));
}
/**
* CWrapper::GetLastError - Returns the last error recorded on this object
* @param[in] pInstance - Instance Handle
* @param[out] sErrorMessage - Message of the last error
* @return Is there a last error to query
*/
inline bool CWrapper::GetLastError(classParam<CBase> pInstance, std::string & sErrorMessage)
{
LibMCDriver_ScanLabOIEHandle hInstance = pInstance.GetHandle();
LibMCDriver_ScanLabOIE_uint32 bytesNeededErrorMessage = 0;
LibMCDriver_ScanLabOIE_uint32 bytesWrittenErrorMessage = 0;
bool resultHasError = 0;
CheckError(nullptr,m_WrapperTable.m_GetLastError(hInstance, 0, &bytesNeededErrorMessage, nullptr, &resultHasError));
std::vector<char> bufferErrorMessage(bytesNeededErrorMessage);
CheckError(nullptr,m_WrapperTable.m_GetLastError(hInstance, bytesNeededErrorMessage, &bytesWrittenErrorMessage, &bufferErrorMessage[0], &resultHasError));
sErrorMessage = std::string(&bufferErrorMessage[0]);
return resultHasError;
}
/**
* CWrapper::ReleaseInstance - Releases shared ownership of an Instance
* @param[in] pInstance - Instance Handle
*/
inline void CWrapper::ReleaseInstance(classParam<CBase> pInstance)
{
LibMCDriver_ScanLabOIEHandle hInstance = pInstance.GetHandle();
CheckError(nullptr,m_WrapperTable.m_ReleaseInstance(hInstance));
}
/**
* CWrapper::AcquireInstance - Acquires shared ownership of an Instance
* @param[in] pInstance - Instance Handle
*/
inline void CWrapper::AcquireInstance(classParam<CBase> pInstance)
{
LibMCDriver_ScanLabOIEHandle hInstance = pInstance.GetHandle();
CheckError(nullptr,m_WrapperTable.m_AcquireInstance(hInstance));
}
/**
* CWrapper::InjectComponent - Injects an imported component for usage within this component
* @param[in] sNameSpace - NameSpace of the injected component
* @param[in] pSymbolAddressMethod - Address of the SymbolAddressMethod of the injected component
*/
inline void CWrapper::InjectComponent(const std::string & sNameSpace, const LibMCDriver_ScanLabOIE_pvoid pSymbolAddressMethod)
{
CheckError(nullptr,m_WrapperTable.m_InjectComponent(sNameSpace.c_str(), pSymbolAddressMethod));
bool bNameSpaceFound = false;
if (sNameSpace == "LibMCDriverEnv") {
if (m_pLibMCDriverEnvWrapper != nullptr) {
throw ELibMCDriver_ScanLabOIEException(LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTLOADLIBRARY, "Library with namespace " + sNameSpace + " is already registered.");
}
m_pLibMCDriverEnvWrapper = LibMCDriverEnv::CWrapper::loadLibraryFromSymbolLookupMethod(pSymbolAddressMethod);
bNameSpaceFound = true;
}
if (!bNameSpaceFound)
throw ELibMCDriver_ScanLabOIEException(LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTLOADLIBRARY, "Unknown namespace " + sNameSpace);
}
/**
* CWrapper::GetSymbolLookupMethod - Returns the address of the SymbolLookupMethod
* @return Address of the SymbolAddressMethod
*/
inline LibMCDriver_ScanLabOIE_pvoid CWrapper::GetSymbolLookupMethod()
{
LibMCDriver_ScanLabOIE_pvoid resultSymbolLookupMethod = 0;
CheckError(nullptr,m_WrapperTable.m_GetSymbolLookupMethod(&resultSymbolLookupMethod));
return resultSymbolLookupMethod;
}
/**
* CWrapper::CreateDriver - Creates a driver instance with a specific name.
* @param[in] sName - Name of driver to be created.
* @param[in] sType - Type of driver to be created.
* @param[in] pDriverEnvironment - Environment of this driver.
* @return New Driver instance
*/
inline PDriver CWrapper::CreateDriver(const std::string & sName, const std::string & sType, classParam<LibMCDriverEnv::CDriverEnvironment> pDriverEnvironment)
{
LibMCDriverEnvHandle hDriverEnvironment = pDriverEnvironment.GetHandle();
LibMCDriver_ScanLabOIEHandle hInstance = nullptr;
CheckError(nullptr,m_WrapperTable.m_CreateDriver(sName.c_str(), sType.c_str(), hDriverEnvironment, &hInstance));
if (!hInstance) {
CheckError(nullptr,LIBMCDRIVER_SCANLABOIE_ERROR_INVALIDPARAM);
}
return std::make_shared<CDriver>(this, hInstance);
}
inline void CWrapper::CheckError(CBase * pBaseClass, LibMCDriver_ScanLabOIEResult nResult)
{
if (nResult != 0) {
std::string sErrorMessage;
if (pBaseClass != nullptr) {
GetLastError(pBaseClass, sErrorMessage);
}
throw ELibMCDriver_ScanLabOIEException(nResult, sErrorMessage);
}
}
inline LibMCDriver_ScanLabOIEResult CWrapper::initWrapperTable(sLibMCDriver_ScanLabOIEDynamicWrapperTable * pWrapperTable)
{
if (pWrapperTable == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_INVALIDPARAM;
pWrapperTable->m_LibraryHandle = nullptr;
pWrapperTable->m_Driver_GetName = nullptr;
pWrapperTable->m_Driver_GetType = nullptr;
pWrapperTable->m_Driver_GetVersion = nullptr;
pWrapperTable->m_Driver_GetHeaderInformation = nullptr;
pWrapperTable->m_GetVersion = nullptr;
pWrapperTable->m_GetLastError = nullptr;
pWrapperTable->m_ReleaseInstance = nullptr;
pWrapperTable->m_AcquireInstance = nullptr;
pWrapperTable->m_InjectComponent = nullptr;
pWrapperTable->m_GetSymbolLookupMethod = nullptr;
pWrapperTable->m_CreateDriver = nullptr;
return LIBMCDRIVER_SCANLABOIE_SUCCESS;
}
inline LibMCDriver_ScanLabOIEResult CWrapper::releaseWrapperTable(sLibMCDriver_ScanLabOIEDynamicWrapperTable * pWrapperTable)
{
if (pWrapperTable == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_INVALIDPARAM;
if (pWrapperTable->m_LibraryHandle != nullptr) {
#ifdef _WIN32
HMODULE hModule = (HMODULE) pWrapperTable->m_LibraryHandle;
FreeLibrary(hModule);
#else // _WIN32
dlclose(pWrapperTable->m_LibraryHandle);
#endif // _WIN32
return initWrapperTable(pWrapperTable);
}
return LIBMCDRIVER_SCANLABOIE_SUCCESS;
}
inline LibMCDriver_ScanLabOIEResult CWrapper::loadWrapperTable(sLibMCDriver_ScanLabOIEDynamicWrapperTable * pWrapperTable, const char * pLibraryFileName)
{
if (pWrapperTable == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_INVALIDPARAM;
if (pLibraryFileName == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_INVALIDPARAM;
#ifdef _WIN32
// Convert filename to UTF16-string
int nLength = (int)strlen(pLibraryFileName);
int nBufferSize = nLength * 2 + 2;
std::vector<wchar_t> wsLibraryFileName(nBufferSize);
int nResult = MultiByteToWideChar(CP_UTF8, 0, pLibraryFileName, nLength, &wsLibraryFileName[0], nBufferSize);
if (nResult == 0)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTLOADLIBRARY;
HMODULE hLibrary = LoadLibraryW(wsLibraryFileName.data());
if (hLibrary == 0)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTLOADLIBRARY;
#else // _WIN32
void* hLibrary = dlopen(pLibraryFileName, RTLD_LAZY);
if (hLibrary == 0)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTLOADLIBRARY;
dlerror();
#endif // _WIN32
#ifdef _WIN32
pWrapperTable->m_Driver_GetName = (PLibMCDriver_ScanLabOIEDriver_GetNamePtr) GetProcAddress(hLibrary, "libmcdriver_scanlaboie_driver_getname");
#else // _WIN32
pWrapperTable->m_Driver_GetName = (PLibMCDriver_ScanLabOIEDriver_GetNamePtr) dlsym(hLibrary, "libmcdriver_scanlaboie_driver_getname");
dlerror();
#endif // _WIN32
if (pWrapperTable->m_Driver_GetName == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
#ifdef _WIN32
pWrapperTable->m_Driver_GetType = (PLibMCDriver_ScanLabOIEDriver_GetTypePtr) GetProcAddress(hLibrary, "libmcdriver_scanlaboie_driver_gettype");
#else // _WIN32
pWrapperTable->m_Driver_GetType = (PLibMCDriver_ScanLabOIEDriver_GetTypePtr) dlsym(hLibrary, "libmcdriver_scanlaboie_driver_gettype");
dlerror();
#endif // _WIN32
if (pWrapperTable->m_Driver_GetType == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
#ifdef _WIN32
pWrapperTable->m_Driver_GetVersion = (PLibMCDriver_ScanLabOIEDriver_GetVersionPtr) GetProcAddress(hLibrary, "libmcdriver_scanlaboie_driver_getversion");
#else // _WIN32
pWrapperTable->m_Driver_GetVersion = (PLibMCDriver_ScanLabOIEDriver_GetVersionPtr) dlsym(hLibrary, "libmcdriver_scanlaboie_driver_getversion");
dlerror();
#endif // _WIN32
if (pWrapperTable->m_Driver_GetVersion == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
#ifdef _WIN32
pWrapperTable->m_Driver_GetHeaderInformation = (PLibMCDriver_ScanLabOIEDriver_GetHeaderInformationPtr) GetProcAddress(hLibrary, "libmcdriver_scanlaboie_driver_getheaderinformation");
#else // _WIN32
pWrapperTable->m_Driver_GetHeaderInformation = (PLibMCDriver_ScanLabOIEDriver_GetHeaderInformationPtr) dlsym(hLibrary, "libmcdriver_scanlaboie_driver_getheaderinformation");
dlerror();
#endif // _WIN32
if (pWrapperTable->m_Driver_GetHeaderInformation == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
#ifdef _WIN32
pWrapperTable->m_GetVersion = (PLibMCDriver_ScanLabOIEGetVersionPtr) GetProcAddress(hLibrary, "libmcdriver_scanlaboie_getversion");
#else // _WIN32
pWrapperTable->m_GetVersion = (PLibMCDriver_ScanLabOIEGetVersionPtr) dlsym(hLibrary, "libmcdriver_scanlaboie_getversion");
dlerror();
#endif // _WIN32
if (pWrapperTable->m_GetVersion == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
#ifdef _WIN32
pWrapperTable->m_GetLastError = (PLibMCDriver_ScanLabOIEGetLastErrorPtr) GetProcAddress(hLibrary, "libmcdriver_scanlaboie_getlasterror");
#else // _WIN32
pWrapperTable->m_GetLastError = (PLibMCDriver_ScanLabOIEGetLastErrorPtr) dlsym(hLibrary, "libmcdriver_scanlaboie_getlasterror");
dlerror();
#endif // _WIN32
if (pWrapperTable->m_GetLastError == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
#ifdef _WIN32
pWrapperTable->m_ReleaseInstance = (PLibMCDriver_ScanLabOIEReleaseInstancePtr) GetProcAddress(hLibrary, "libmcdriver_scanlaboie_releaseinstance");
#else // _WIN32
pWrapperTable->m_ReleaseInstance = (PLibMCDriver_ScanLabOIEReleaseInstancePtr) dlsym(hLibrary, "libmcdriver_scanlaboie_releaseinstance");
dlerror();
#endif // _WIN32
if (pWrapperTable->m_ReleaseInstance == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
#ifdef _WIN32
pWrapperTable->m_AcquireInstance = (PLibMCDriver_ScanLabOIEAcquireInstancePtr) GetProcAddress(hLibrary, "libmcdriver_scanlaboie_acquireinstance");
#else // _WIN32
pWrapperTable->m_AcquireInstance = (PLibMCDriver_ScanLabOIEAcquireInstancePtr) dlsym(hLibrary, "libmcdriver_scanlaboie_acquireinstance");
dlerror();
#endif // _WIN32
if (pWrapperTable->m_AcquireInstance == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
#ifdef _WIN32
pWrapperTable->m_InjectComponent = (PLibMCDriver_ScanLabOIEInjectComponentPtr) GetProcAddress(hLibrary, "libmcdriver_scanlaboie_injectcomponent");
#else // _WIN32
pWrapperTable->m_InjectComponent = (PLibMCDriver_ScanLabOIEInjectComponentPtr) dlsym(hLibrary, "libmcdriver_scanlaboie_injectcomponent");
dlerror();
#endif // _WIN32
if (pWrapperTable->m_InjectComponent == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
#ifdef _WIN32
pWrapperTable->m_GetSymbolLookupMethod = (PLibMCDriver_ScanLabOIEGetSymbolLookupMethodPtr) GetProcAddress(hLibrary, "libmcdriver_scanlaboie_getsymbollookupmethod");
#else // _WIN32
pWrapperTable->m_GetSymbolLookupMethod = (PLibMCDriver_ScanLabOIEGetSymbolLookupMethodPtr) dlsym(hLibrary, "libmcdriver_scanlaboie_getsymbollookupmethod");
dlerror();
#endif // _WIN32
if (pWrapperTable->m_GetSymbolLookupMethod == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
#ifdef _WIN32
pWrapperTable->m_CreateDriver = (PLibMCDriver_ScanLabOIECreateDriverPtr) GetProcAddress(hLibrary, "libmcdriver_scanlaboie_createdriver");
#else // _WIN32
pWrapperTable->m_CreateDriver = (PLibMCDriver_ScanLabOIECreateDriverPtr) dlsym(hLibrary, "libmcdriver_scanlaboie_createdriver");
dlerror();
#endif // _WIN32
if (pWrapperTable->m_CreateDriver == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
pWrapperTable->m_LibraryHandle = hLibrary;
return LIBMCDRIVER_SCANLABOIE_SUCCESS;
}
inline LibMCDriver_ScanLabOIEResult CWrapper::loadWrapperTableFromSymbolLookupMethod(sLibMCDriver_ScanLabOIEDynamicWrapperTable * pWrapperTable, void* pSymbolLookupMethod)
{
if (pWrapperTable == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_INVALIDPARAM;
if (pSymbolLookupMethod == nullptr)
return LIBMCDRIVER_SCANLABOIE_ERROR_INVALIDPARAM;
typedef LibMCDriver_ScanLabOIEResult(*SymbolLookupType)(const char*, void**);
SymbolLookupType pLookup = (SymbolLookupType)pSymbolLookupMethod;
LibMCDriver_ScanLabOIEResult eLookupError = LIBMCDRIVER_SCANLABOIE_SUCCESS;
eLookupError = (*pLookup)("libmcdriver_scanlaboie_driver_getname", (void**)&(pWrapperTable->m_Driver_GetName));
if ( (eLookupError != 0) || (pWrapperTable->m_Driver_GetName == nullptr) )
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
eLookupError = (*pLookup)("libmcdriver_scanlaboie_driver_gettype", (void**)&(pWrapperTable->m_Driver_GetType));
if ( (eLookupError != 0) || (pWrapperTable->m_Driver_GetType == nullptr) )
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
eLookupError = (*pLookup)("libmcdriver_scanlaboie_driver_getversion", (void**)&(pWrapperTable->m_Driver_GetVersion));
if ( (eLookupError != 0) || (pWrapperTable->m_Driver_GetVersion == nullptr) )
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
eLookupError = (*pLookup)("libmcdriver_scanlaboie_driver_getheaderinformation", (void**)&(pWrapperTable->m_Driver_GetHeaderInformation));
if ( (eLookupError != 0) || (pWrapperTable->m_Driver_GetHeaderInformation == nullptr) )
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
eLookupError = (*pLookup)("libmcdriver_scanlaboie_getversion", (void**)&(pWrapperTable->m_GetVersion));
if ( (eLookupError != 0) || (pWrapperTable->m_GetVersion == nullptr) )
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
eLookupError = (*pLookup)("libmcdriver_scanlaboie_getlasterror", (void**)&(pWrapperTable->m_GetLastError));
if ( (eLookupError != 0) || (pWrapperTable->m_GetLastError == nullptr) )
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
eLookupError = (*pLookup)("libmcdriver_scanlaboie_releaseinstance", (void**)&(pWrapperTable->m_ReleaseInstance));
if ( (eLookupError != 0) || (pWrapperTable->m_ReleaseInstance == nullptr) )
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
eLookupError = (*pLookup)("libmcdriver_scanlaboie_acquireinstance", (void**)&(pWrapperTable->m_AcquireInstance));
if ( (eLookupError != 0) || (pWrapperTable->m_AcquireInstance == nullptr) )
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
eLookupError = (*pLookup)("libmcdriver_scanlaboie_injectcomponent", (void**)&(pWrapperTable->m_InjectComponent));
if ( (eLookupError != 0) || (pWrapperTable->m_InjectComponent == nullptr) )
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
eLookupError = (*pLookup)("libmcdriver_scanlaboie_getsymbollookupmethod", (void**)&(pWrapperTable->m_GetSymbolLookupMethod));
if ( (eLookupError != 0) || (pWrapperTable->m_GetSymbolLookupMethod == nullptr) )
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
eLookupError = (*pLookup)("libmcdriver_scanlaboie_createdriver", (void**)&(pWrapperTable->m_CreateDriver));
if ( (eLookupError != 0) || (pWrapperTable->m_CreateDriver == nullptr) )
return LIBMCDRIVER_SCANLABOIE_ERROR_COULDNOTFINDLIBRARYEXPORT;
return LIBMCDRIVER_SCANLABOIE_SUCCESS;
}
/**
* Method definitions for class CBase
*/
/**
* Method definitions for class CDriver
*/
/**
* CDriver::GetName - returns the name identifier of the driver
* @return Name of the driver.
*/
std::string CDriver::GetName()
{
LibMCDriver_ScanLabOIE_uint32 bytesNeededName = 0;
LibMCDriver_ScanLabOIE_uint32 bytesWrittenName = 0;
CheckError(m_pWrapper->m_WrapperTable.m_Driver_GetName(m_pHandle, 0, &bytesNeededName, nullptr));
std::vector<char> bufferName(bytesNeededName);
CheckError(m_pWrapper->m_WrapperTable.m_Driver_GetName(m_pHandle, bytesNeededName, &bytesWrittenName, &bufferName[0]));
return std::string(&bufferName[0]);
}
/**
* CDriver::GetType - returns the type identifier of the driver
* @return Type of the driver.
*/
std::string CDriver::GetType()
{
LibMCDriver_ScanLabOIE_uint32 bytesNeededType = 0;
LibMCDriver_ScanLabOIE_uint32 bytesWrittenType = 0;
CheckError(m_pWrapper->m_WrapperTable.m_Driver_GetType(m_pHandle, 0, &bytesNeededType, nullptr));
std::vector<char> bufferType(bytesNeededType);
CheckError(m_pWrapper->m_WrapperTable.m_Driver_GetType(m_pHandle, bytesNeededType, &bytesWrittenType, &bufferType[0]));
return std::string(&bufferType[0]);
}
/**
* CDriver::GetVersion - returns the version identifiers of the driver
* @param[out] nMajor - Major version.
* @param[out] nMinor - Minor version.
* @param[out] nMicro - Micro version.
* @param[out] sBuild - Build identifier.
*/
void CDriver::GetVersion(LibMCDriver_ScanLabOIE_uint32 & nMajor, LibMCDriver_ScanLabOIE_uint32 & nMinor, LibMCDriver_ScanLabOIE_uint32 & nMicro, std::string & sBuild)
{
LibMCDriver_ScanLabOIE_uint32 bytesNeededBuild = 0;
LibMCDriver_ScanLabOIE_uint32 bytesWrittenBuild = 0;
CheckError(m_pWrapper->m_WrapperTable.m_Driver_GetVersion(m_pHandle, &nMajor, &nMinor, &nMicro, 0, &bytesNeededBuild, nullptr));
std::vector<char> bufferBuild(bytesNeededBuild);
CheckError(m_pWrapper->m_WrapperTable.m_Driver_GetVersion(m_pHandle, &nMajor, &nMinor, &nMicro, bytesNeededBuild, &bytesWrittenBuild, &bufferBuild[0]));
sBuild = std::string(&bufferBuild[0]);
}
/**
* CDriver::GetHeaderInformation - returns the header information
* @param[out] sNameSpace - NameSpace of the driver.
* @param[out] sBaseName - BaseName of the driver.
*/
void CDriver::GetHeaderInformation(std::string & sNameSpace, std::string & sBaseName)
{
LibMCDriver_ScanLabOIE_uint32 bytesNeededNameSpace = 0;
LibMCDriver_ScanLabOIE_uint32 bytesWrittenNameSpace = 0;
LibMCDriver_ScanLabOIE_uint32 bytesNeededBaseName = 0;
LibMCDriver_ScanLabOIE_uint32 bytesWrittenBaseName = 0;
CheckError(m_pWrapper->m_WrapperTable.m_Driver_GetHeaderInformation(m_pHandle, 0, &bytesNeededNameSpace, nullptr, 0, &bytesNeededBaseName, nullptr));
std::vector<char> bufferNameSpace(bytesNeededNameSpace);
std::vector<char> bufferBaseName(bytesNeededBaseName);
CheckError(m_pWrapper->m_WrapperTable.m_Driver_GetHeaderInformation(m_pHandle, bytesNeededNameSpace, &bytesWrittenNameSpace, &bufferNameSpace[0], bytesNeededBaseName, &bytesWrittenBaseName, &bufferBaseName[0]));
sNameSpace = std::string(&bufferNameSpace[0]);
sBaseName = std::string(&bufferBaseName[0]);
}
/**
* Method definitions for class CDriver_ScanLab_OIE
*/
} // namespace LibMCDriver_ScanLabOIE
#endif // __LIBMCDRIVER_SCANLABOIE_CPPHEADER_DYNAMIC_CPP
| 39.83818 | 213 | 0.72071 | [
"object",
"vector"
] |
a2ea6b22a5fd93d17504ecc2c9a928ba1795b459 | 23,673 | cpp | C++ | test/TestApp/AutoGenTests/AutoGenAnalyticsTests.cpp | jasonsandlin/PlayFabCoreCSdk | ecf51e9a7a90e579efed595bd1d76ec8f3a1ae19 | [
"Apache-2.0"
] | null | null | null | test/TestApp/AutoGenTests/AutoGenAnalyticsTests.cpp | jasonsandlin/PlayFabCoreCSdk | ecf51e9a7a90e579efed595bd1d76ec8f3a1ae19 | [
"Apache-2.0"
] | null | null | null | test/TestApp/AutoGenTests/AutoGenAnalyticsTests.cpp | jasonsandlin/PlayFabCoreCSdk | ecf51e9a7a90e579efed595bd1d76ec8f3a1ae19 | [
"Apache-2.0"
] | null | null | null | #include "TestAppPch.h"
#include "TestContext.h"
#include "TestApp.h"
#include "AutoGenAnalyticsTests.h"
#include "XAsyncHelper.h"
#include "playfab/PFAuthentication.h"
namespace PlayFabUnit
{
using namespace PlayFab::Wrappers;
AutoGenAnalyticsTests::AnalyticsTestData AutoGenAnalyticsTests::testData;
void AutoGenAnalyticsTests::Log(std::stringstream& ss)
{
TestApp::LogPut(ss.str().c_str());
ss.str(std::string());
ss.clear();
}
HRESULT AutoGenAnalyticsTests::LogHR(HRESULT hr)
{
if( TestApp::ShouldTrace(PFTestTraceLevel::Information) )
{
TestApp::Log("Result: 0x%0.8x", hr);
}
return hr;
}
void AutoGenAnalyticsTests::AddTests()
{
// Generated tests
AddTest("TestAnalyticsClientReportDeviceInfo", &AutoGenAnalyticsTests::TestAnalyticsClientReportDeviceInfo);
AddTest("TestAnalyticsClientWriteCharacterEvent", &AutoGenAnalyticsTests::TestAnalyticsClientWriteCharacterEvent);
AddTest("TestAnalyticsClientWritePlayerEvent", &AutoGenAnalyticsTests::TestAnalyticsClientWritePlayerEvent);
AddTest("TestAnalyticsClientWriteTitleEvent", &AutoGenAnalyticsTests::TestAnalyticsClientWriteTitleEvent);
AddTest("TestAnalyticsServerWriteCharacterEvent", &AutoGenAnalyticsTests::TestAnalyticsServerWriteCharacterEvent);
AddTest("TestAnalyticsServerWritePlayerEvent", &AutoGenAnalyticsTests::TestAnalyticsServerWritePlayerEvent);
AddTest("TestAnalyticsServerWriteTitleEvent", &AutoGenAnalyticsTests::TestAnalyticsServerWriteTitleEvent);
AddTest("TestAnalyticsGetDetails", &AutoGenAnalyticsTests::TestAnalyticsGetDetails);
AddTest("TestAnalyticsGetLimits", &AutoGenAnalyticsTests::TestAnalyticsGetLimits);
AddTest("TestAnalyticsGetOperationStatus", &AutoGenAnalyticsTests::TestAnalyticsGetOperationStatus);
AddTest("TestAnalyticsGetPendingOperations", &AutoGenAnalyticsTests::TestAnalyticsGetPendingOperations);
AddTest("TestAnalyticsSetPerformance", &AutoGenAnalyticsTests::TestAnalyticsSetPerformance);
AddTest("TestAnalyticsSetStorageRetention", &AutoGenAnalyticsTests::TestAnalyticsSetStorageRetention);
}
void AutoGenAnalyticsTests::ClassSetUp()
{
HRESULT hr = PFAdminInitialize(testTitleData.titleId.data(), testTitleData.developerSecretKey.data(), nullptr, &stateHandle);
assert(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
PFAuthenticationLoginWithCustomIDRequest request{};
request.customId = "CustomId";
request.createAccount = true;
PFGetPlayerCombinedInfoRequestParams combinedInfoRequestParams{};
combinedInfoRequestParams.getCharacterInventories = true;
combinedInfoRequestParams.getCharacterList = true;
combinedInfoRequestParams.getPlayerProfile = true;
combinedInfoRequestParams.getPlayerStatistics = true;
combinedInfoRequestParams.getTitleData = true;
combinedInfoRequestParams.getUserAccountInfo = true;
combinedInfoRequestParams.getUserData = true;
combinedInfoRequestParams.getUserInventory = true;
combinedInfoRequestParams.getUserReadOnlyData = true;
combinedInfoRequestParams.getUserVirtualCurrency = true;
request.infoRequestParameters = &combinedInfoRequestParams;
XAsyncBlock async{};
hr = PFAuthenticationClientLoginWithCustomIDAsync(stateHandle, &request, &async);
assert(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
// Synchronously wait for login to complete
hr = XAsyncGetStatus(&async, true);
assert(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
hr = PFAuthenticationClientLoginGetResult(&async, &titlePlayerHandle);
assert(SUCCEEDED(hr) && titlePlayerHandle);
hr = PFTitlePlayerGetEntityHandle(titlePlayerHandle, &entityHandle);
assert(SUCCEEDED(hr) && entityHandle);
}
}
request.customId = "CustomId2";
async = {};
hr = PFAuthenticationClientLoginWithCustomIDAsync(stateHandle, &request, &async);
assert(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
// Synchronously what for login to complete
hr = XAsyncGetStatus(&async, true);
assert(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
hr = PFAuthenticationClientLoginGetResult(&async, &titlePlayerHandle2);
assert(SUCCEEDED(hr) && titlePlayerHandle2);
hr = PFTitlePlayerGetEntityHandle(titlePlayerHandle2, &entityHandle2);
assert(SUCCEEDED(hr) && entityHandle2);
}
}
PFAuthenticationGetEntityTokenRequest titleTokenRequest{};
async = {};
hr = PFAuthenticationGetEntityTokenAsync(stateHandle, &titleTokenRequest, &async);
assert(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
// Synchronously wait for login to complete
hr = XAsyncGetStatus(&async, true);
assert(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
hr = PFAuthenticationGetEntityTokenGetResult(&async, &titleEntityHandle);
assert(SUCCEEDED(hr));
}
}
}
}
void AutoGenAnalyticsTests::ClassTearDown()
{
PFTitlePlayerCloseHandle(titlePlayerHandle);
PFEntityCloseHandle(entityHandle);
PFEntityCloseHandle(titleEntityHandle);
XAsyncBlock async{};
HRESULT hr = PFUninitializeAsync(stateHandle, &async);
assert(SUCCEEDED(hr));
hr = XAsyncGetStatus(&async, true);
assert(SUCCEEDED(hr));
UNREFERENCED_PARAMETER(hr);
}
void AutoGenAnalyticsTests::SetUp(TestContext& testContext)
{
if (!entityHandle)
{
testContext.Skip("Skipping test because login failed");
}
}
#pragma region ClientReportDeviceInfo
void AutoGenAnalyticsTests::TestAnalyticsClientReportDeviceInfo(TestContext& testContext)
{
auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext);
PFAnalyticsDeviceInfoRequestWrapper<> request;
FillDeviceInfoRequest(request);
LogDeviceInfoRequest(&request.Model(), "TestAnalyticsClientReportDeviceInfo");
HRESULT hr = PFAnalyticsClientReportDeviceInfoAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsClientReportDeviceInfoAsync", hr);
return;
}
async.release();
}
#pragma endregion
#pragma region ClientWriteCharacterEvent
void AutoGenAnalyticsTests::TestAnalyticsClientWriteCharacterEvent(TestContext& testContext)
{
struct ClientWriteCharacterEventResultHolder : public WriteEventResponseHolder
{
HRESULT Get(XAsyncBlock* async) override
{
size_t requiredBufferSize;
RETURN_IF_FAILED(LogHR(PFAnalyticsClientWriteCharacterEventGetResultSize(async, &requiredBufferSize)));
resultBuffer.resize(requiredBufferSize);
RETURN_IF_FAILED(LogHR(PFAnalyticsClientWriteCharacterEventGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr)));
LogPFAnalyticsWriteEventResponse(result);
return S_OK;
}
HRESULT Validate() override
{
return ValidatePFAnalyticsWriteEventResponse(result);
}
};
auto async = std::make_unique<XAsyncHelper<ClientWriteCharacterEventResultHolder>>(testContext);
PFAnalyticsWriteClientCharacterEventRequestWrapper<> request;
FillWriteClientCharacterEventRequest(request);
LogWriteClientCharacterEventRequest(&request.Model(), "TestAnalyticsClientWriteCharacterEvent");
HRESULT hr = PFAnalyticsClientWriteCharacterEventAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsClientWriteCharacterEventAsync", hr);
return;
}
async.release();
}
#pragma endregion
#pragma region ClientWritePlayerEvent
void AutoGenAnalyticsTests::TestAnalyticsClientWritePlayerEvent(TestContext& testContext)
{
struct ClientWritePlayerEventResultHolder : public WriteEventResponseHolder
{
HRESULT Get(XAsyncBlock* async) override
{
size_t requiredBufferSize;
RETURN_IF_FAILED(LogHR(PFAnalyticsClientWritePlayerEventGetResultSize(async, &requiredBufferSize)));
resultBuffer.resize(requiredBufferSize);
RETURN_IF_FAILED(LogHR(PFAnalyticsClientWritePlayerEventGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr)));
LogPFAnalyticsWriteEventResponse(result);
return S_OK;
}
HRESULT Validate() override
{
return ValidatePFAnalyticsWriteEventResponse(result);
}
};
auto async = std::make_unique<XAsyncHelper<ClientWritePlayerEventResultHolder>>(testContext);
PFAnalyticsWriteClientPlayerEventRequestWrapper<> request;
FillWriteClientPlayerEventRequest(request);
LogWriteClientPlayerEventRequest(&request.Model(), "TestAnalyticsClientWritePlayerEvent");
HRESULT hr = PFAnalyticsClientWritePlayerEventAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsClientWritePlayerEventAsync", hr);
return;
}
async.release();
}
#pragma endregion
#pragma region ClientWriteTitleEvent
void AutoGenAnalyticsTests::TestAnalyticsClientWriteTitleEvent(TestContext& testContext)
{
struct ClientWriteTitleEventResultHolder : public WriteEventResponseHolder
{
HRESULT Get(XAsyncBlock* async) override
{
size_t requiredBufferSize;
RETURN_IF_FAILED(LogHR(PFAnalyticsClientWriteTitleEventGetResultSize(async, &requiredBufferSize)));
resultBuffer.resize(requiredBufferSize);
RETURN_IF_FAILED(LogHR(PFAnalyticsClientWriteTitleEventGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr)));
LogPFAnalyticsWriteEventResponse(result);
return S_OK;
}
HRESULT Validate() override
{
return ValidatePFAnalyticsWriteEventResponse(result);
}
};
auto async = std::make_unique<XAsyncHelper<ClientWriteTitleEventResultHolder>>(testContext);
PFAnalyticsWriteTitleEventRequestWrapper<> request;
FillWriteTitleEventRequest(request);
LogWriteTitleEventRequest(&request.Model(), "TestAnalyticsClientWriteTitleEvent");
HRESULT hr = PFAnalyticsClientWriteTitleEventAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsClientWriteTitleEventAsync", hr);
return;
}
async.release();
}
#pragma endregion
#pragma region ServerWriteCharacterEvent
void AutoGenAnalyticsTests::TestAnalyticsServerWriteCharacterEvent(TestContext& testContext)
{
struct ServerWriteCharacterEventResultHolder : public WriteEventResponseHolder
{
HRESULT Get(XAsyncBlock* async) override
{
size_t requiredBufferSize;
RETURN_IF_FAILED(LogHR(PFAnalyticsServerWriteCharacterEventGetResultSize(async, &requiredBufferSize)));
resultBuffer.resize(requiredBufferSize);
RETURN_IF_FAILED(LogHR(PFAnalyticsServerWriteCharacterEventGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr)));
LogPFAnalyticsWriteEventResponse(result);
return S_OK;
}
HRESULT Validate() override
{
return ValidatePFAnalyticsWriteEventResponse(result);
}
};
auto async = std::make_unique<XAsyncHelper<ServerWriteCharacterEventResultHolder>>(testContext);
PFAnalyticsWriteServerCharacterEventRequestWrapper<> request;
FillWriteServerCharacterEventRequest(request);
LogWriteServerCharacterEventRequest(&request.Model(), "TestAnalyticsServerWriteCharacterEvent");
HRESULT hr = PFAnalyticsServerWriteCharacterEventAsync(stateHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsServerWriteCharacterEventAsync", hr);
return;
}
async.release();
}
#pragma endregion
#pragma region ServerWritePlayerEvent
void AutoGenAnalyticsTests::TestAnalyticsServerWritePlayerEvent(TestContext& testContext)
{
struct ServerWritePlayerEventResultHolder : public WriteEventResponseHolder
{
HRESULT Get(XAsyncBlock* async) override
{
size_t requiredBufferSize;
RETURN_IF_FAILED(LogHR(PFAnalyticsServerWritePlayerEventGetResultSize(async, &requiredBufferSize)));
resultBuffer.resize(requiredBufferSize);
RETURN_IF_FAILED(LogHR(PFAnalyticsServerWritePlayerEventGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr)));
LogPFAnalyticsWriteEventResponse(result);
return S_OK;
}
HRESULT Validate() override
{
return ValidatePFAnalyticsWriteEventResponse(result);
}
};
auto async = std::make_unique<XAsyncHelper<ServerWritePlayerEventResultHolder>>(testContext);
PFAnalyticsWriteServerPlayerEventRequestWrapper<> request;
FillWriteServerPlayerEventRequest(request);
LogWriteServerPlayerEventRequest(&request.Model(), "TestAnalyticsServerWritePlayerEvent");
HRESULT hr = PFAnalyticsServerWritePlayerEventAsync(stateHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsServerWritePlayerEventAsync", hr);
return;
}
async.release();
}
#pragma endregion
#pragma region ServerWriteTitleEvent
void AutoGenAnalyticsTests::TestAnalyticsServerWriteTitleEvent(TestContext& testContext)
{
struct ServerWriteTitleEventResultHolder : public WriteEventResponseHolder
{
HRESULT Get(XAsyncBlock* async) override
{
size_t requiredBufferSize;
RETURN_IF_FAILED(LogHR(PFAnalyticsServerWriteTitleEventGetResultSize(async, &requiredBufferSize)));
resultBuffer.resize(requiredBufferSize);
RETURN_IF_FAILED(LogHR(PFAnalyticsServerWriteTitleEventGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr)));
LogPFAnalyticsWriteEventResponse(result);
return S_OK;
}
HRESULT Validate() override
{
return ValidatePFAnalyticsWriteEventResponse(result);
}
};
auto async = std::make_unique<XAsyncHelper<ServerWriteTitleEventResultHolder>>(testContext);
PFAnalyticsWriteTitleEventRequestWrapper<> request;
FillWriteTitleEventRequest(request);
LogWriteTitleEventRequest(&request.Model(), "TestAnalyticsServerWriteTitleEvent");
HRESULT hr = PFAnalyticsServerWriteTitleEventAsync(stateHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsServerWriteTitleEventAsync", hr);
return;
}
async.release();
}
#pragma endregion
#pragma region GetDetails
void AutoGenAnalyticsTests::TestAnalyticsGetDetails(TestContext& testContext)
{
struct GetDetailsResultHolder : public InsightsGetDetailsResponseHolder
{
HRESULT Get(XAsyncBlock* async) override
{
size_t requiredBufferSize;
RETURN_IF_FAILED(LogHR(PFAnalyticsGetDetailsGetResultSize(async, &requiredBufferSize)));
resultBuffer.resize(requiredBufferSize);
RETURN_IF_FAILED(LogHR(PFAnalyticsGetDetailsGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr)));
LogPFAnalyticsInsightsGetDetailsResponse(result);
return S_OK;
}
HRESULT Validate() override
{
return ValidatePFAnalyticsInsightsGetDetailsResponse(result);
}
};
auto async = std::make_unique<XAsyncHelper<GetDetailsResultHolder>>(testContext);
PFAnalyticsInsightsEmptyRequestWrapper<> request;
FillInsightsEmptyRequest(request);
LogInsightsEmptyRequest(&request.Model(), "TestAnalyticsGetDetails");
HRESULT hr = PFAnalyticsGetDetailsAsync(entityHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsGetDetailsAsync", hr);
return;
}
async.release();
}
#pragma endregion
#pragma region GetLimits
void AutoGenAnalyticsTests::TestAnalyticsGetLimits(TestContext& testContext)
{
struct GetLimitsResultHolder : public InsightsGetLimitsResponseHolder
{
HRESULT Get(XAsyncBlock* async) override
{
size_t requiredBufferSize;
RETURN_IF_FAILED(LogHR(PFAnalyticsGetLimitsGetResultSize(async, &requiredBufferSize)));
resultBuffer.resize(requiredBufferSize);
RETURN_IF_FAILED(LogHR(PFAnalyticsGetLimitsGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr)));
LogPFAnalyticsInsightsGetLimitsResponse(result);
return S_OK;
}
HRESULT Validate() override
{
return ValidatePFAnalyticsInsightsGetLimitsResponse(result);
}
};
auto async = std::make_unique<XAsyncHelper<GetLimitsResultHolder>>(testContext);
PFAnalyticsInsightsEmptyRequestWrapper<> request;
FillInsightsEmptyRequest(request);
LogInsightsEmptyRequest(&request.Model(), "TestAnalyticsGetLimits");
HRESULT hr = PFAnalyticsGetLimitsAsync(entityHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsGetLimitsAsync", hr);
return;
}
async.release();
}
#pragma endregion
#pragma region GetOperationStatus
void AutoGenAnalyticsTests::TestAnalyticsGetOperationStatus(TestContext& testContext)
{
struct GetOperationStatusResultHolder : public InsightsGetOperationStatusResponseHolder
{
HRESULT Get(XAsyncBlock* async) override
{
size_t requiredBufferSize;
RETURN_IF_FAILED(LogHR(PFAnalyticsGetOperationStatusGetResultSize(async, &requiredBufferSize)));
resultBuffer.resize(requiredBufferSize);
RETURN_IF_FAILED(LogHR(PFAnalyticsGetOperationStatusGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr)));
LogPFAnalyticsInsightsGetOperationStatusResponse(result);
return S_OK;
}
HRESULT Validate() override
{
return ValidatePFAnalyticsInsightsGetOperationStatusResponse(result);
}
};
auto async = std::make_unique<XAsyncHelper<GetOperationStatusResultHolder>>(testContext);
PFAnalyticsInsightsGetOperationStatusRequestWrapper<> request;
FillInsightsGetOperationStatusRequest(request);
LogInsightsGetOperationStatusRequest(&request.Model(), "TestAnalyticsGetOperationStatus");
HRESULT hr = PFAnalyticsGetOperationStatusAsync(entityHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsGetOperationStatusAsync", hr);
return;
}
async.release();
}
#pragma endregion
#pragma region GetPendingOperations
void AutoGenAnalyticsTests::TestAnalyticsGetPendingOperations(TestContext& testContext)
{
struct GetPendingOperationsResultHolder : public InsightsGetPendingOperationsResponseHolder
{
HRESULT Get(XAsyncBlock* async) override
{
size_t requiredBufferSize;
RETURN_IF_FAILED(LogHR(PFAnalyticsGetPendingOperationsGetResultSize(async, &requiredBufferSize)));
resultBuffer.resize(requiredBufferSize);
RETURN_IF_FAILED(LogHR(PFAnalyticsGetPendingOperationsGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr)));
LogPFAnalyticsInsightsGetPendingOperationsResponse(result);
return S_OK;
}
HRESULT Validate() override
{
return ValidatePFAnalyticsInsightsGetPendingOperationsResponse(result);
}
};
auto async = std::make_unique<XAsyncHelper<GetPendingOperationsResultHolder>>(testContext);
PFAnalyticsInsightsGetPendingOperationsRequestWrapper<> request;
FillInsightsGetPendingOperationsRequest(request);
LogInsightsGetPendingOperationsRequest(&request.Model(), "TestAnalyticsGetPendingOperations");
HRESULT hr = PFAnalyticsGetPendingOperationsAsync(entityHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsGetPendingOperationsAsync", hr);
return;
}
async.release();
}
#pragma endregion
#pragma region SetPerformance
void AutoGenAnalyticsTests::TestAnalyticsSetPerformance(TestContext& testContext)
{
struct SetPerformanceResultHolder : public InsightsOperationResponseHolder
{
HRESULT Get(XAsyncBlock* async) override
{
size_t requiredBufferSize;
RETURN_IF_FAILED(LogHR(PFAnalyticsSetPerformanceGetResultSize(async, &requiredBufferSize)));
resultBuffer.resize(requiredBufferSize);
RETURN_IF_FAILED(LogHR(PFAnalyticsSetPerformanceGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr)));
LogPFAnalyticsInsightsOperationResponse(result);
return S_OK;
}
HRESULT Validate() override
{
return ValidatePFAnalyticsInsightsOperationResponse(result);
}
};
auto async = std::make_unique<XAsyncHelper<SetPerformanceResultHolder>>(testContext);
PFAnalyticsInsightsSetPerformanceRequestWrapper<> request;
FillInsightsSetPerformanceRequest(request);
LogInsightsSetPerformanceRequest(&request.Model(), "TestAnalyticsSetPerformance");
HRESULT hr = PFAnalyticsSetPerformanceAsync(entityHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsSetPerformanceAsync", hr);
return;
}
async.release();
}
#pragma endregion
#pragma region SetStorageRetention
void AutoGenAnalyticsTests::TestAnalyticsSetStorageRetention(TestContext& testContext)
{
struct SetStorageRetentionResultHolder : public InsightsOperationResponseHolder
{
HRESULT Get(XAsyncBlock* async) override
{
size_t requiredBufferSize;
RETURN_IF_FAILED(LogHR(PFAnalyticsSetStorageRetentionGetResultSize(async, &requiredBufferSize)));
resultBuffer.resize(requiredBufferSize);
RETURN_IF_FAILED(LogHR(PFAnalyticsSetStorageRetentionGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr)));
LogPFAnalyticsInsightsOperationResponse(result);
return S_OK;
}
HRESULT Validate() override
{
return ValidatePFAnalyticsInsightsOperationResponse(result);
}
};
auto async = std::make_unique<XAsyncHelper<SetStorageRetentionResultHolder>>(testContext);
PFAnalyticsInsightsSetStorageRetentionRequestWrapper<> request;
FillInsightsSetStorageRetentionRequest(request);
LogInsightsSetStorageRetentionRequest(&request.Model(), "TestAnalyticsSetStorageRetention");
HRESULT hr = PFAnalyticsSetStorageRetentionAsync(entityHandle, &request.Model(), &async->asyncBlock);
if (FAILED(hr))
{
testContext.Fail("PFAnalyticsAnalyticsSetStorageRetentionAsync", hr);
return;
}
async.release();
}
#pragma endregion
}
| 36.031963 | 150 | 0.717611 | [
"model"
] |
a2eedb41c0fe63b095febf9f14ebe87f6f402f4e | 7,052 | cpp | C++ | src/SFML-utils/map-editor/MapSelectionManager.cpp | Krozark/SFML-utils | c2f169faa7f3ce0aa6e23991d21796dca01944be | [
"BSD-2-Clause"
] | 23 | 2016-03-05T11:27:53.000Z | 2021-05-29T19:08:26.000Z | src/SFML-utils/map-editor/MapSelectionManager.cpp | Krozark/SFML-utils | c2f169faa7f3ce0aa6e23991d21796dca01944be | [
"BSD-2-Clause"
] | 11 | 2015-03-12T10:14:06.000Z | 2017-11-24T14:34:41.000Z | src/SFML-utils/map-editor/MapSelectionManager.cpp | Krozark/SFML-utils | c2f169faa7f3ce0aa6e23991d21796dca01944be | [
"BSD-2-Clause"
] | 9 | 2016-04-10T22:28:45.000Z | 2021-11-27T08:48:21.000Z | #include <SFML-utils/map-editor/MapSelectionManager.hpp>
#include <SFML-utils/map-editor/Editor.hpp>
#include <SFML-utils/map-editor/path.hpp>
#include <algorithm>
extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
#include <luabind/luabind.hpp>
#include <luabind/object.hpp>
#include <luabind/tag_function.hpp>
namespace sfutils
{
namespace editor
{
MapSelectionManager::MapSelectionManager(Editor& owner) :
_owner(owner),
_clickIndicator(sf::PrimitiveType::Lines,2),
_luaState(nullptr)
{
reset();
for(int i = 0; i < 2; ++i)
{
_clickIndicator[i].color = sf::Color(255,20,125);
}
}
MapSelectionManager::~MapSelectionManager()
{
if(_luaState != nullptr)
{
lua_close(_luaState);
}
}
void MapSelectionManager::reset()
{
_map = nullptr;
_cursorHighlight = nullptr;
_highlightLayer = nullptr;
_clickPressedCoord = sf::Vector2i(0,0);
_clickReleasedCoord = sf::Vector2i(0,0);
_isPressed = false;
_resetSelection();
}
bool MapSelectionManager::processEvent(const sf::Event& event)
{
const sfutils::map::MapViewer& viewer = _owner.getMapViewer();
if(event.type == sf::Event::MouseButtonPressed and event.mouseButton.button == sf::Mouse::Button::Left)
{
_clickPressedCoord = _clickReleasedCoord = viewer.mapScreenToCoords(sf::Vector2i(event.mouseButton.x,event.mouseButton.y));
_isPressed = true;
_updateSelectionArea();
}
else if(event.type == sf::Event::MouseButtonReleased and event.mouseButton.button == sf::Mouse::Button::Left)
{
_clickReleasedCoord = viewer.mapScreenToCoords(sf::Vector2i(event.mouseButton.x,event.mouseButton.y));
_updateSelectionArea();
_valideSelectedArea();
_isPressed = false;
}
else if(event.type == sf::Event::MouseMoved)
{
sf::Vector2i coord = viewer.mapScreenToCoords(sf::Vector2i(event.mouseMove.x,event.mouseMove.y));
sf::Vector2f pixels = viewer.mapCoordsToPixel(coord);
_cursorHighlight->setPosition(pixels);
if(_isPressed && (_clickReleasedCoord != coord))
{
_clickReleasedCoord = coord;
_updateSelectionArea();
}
}
return false;
}
void MapSelectionManager::render(sf::RenderTarget& target,sf::RenderStates states)
{
if(_isPressed)
{
target.draw(_clickIndicator,states);
}
}
void MapSelectionManager::setMap(sfutils::map::Map* map)
{
assert(map);
_map = map;
//special layers
_highlightLayer = new sfutils::map::Layer<sf::ConvexShape>("ConvexShape",100,false,true);
_cursorHighlight = _highlightLayer->add(_map->getGeometry().getShape(),false);
_cursorHighlight->setFillColor(sf::Color(0,255,0,127));
_map->addLayer(_highlightLayer);
}
int setLuaPath( lua_State* L, const std::string& path )
{
lua_getglobal( L, "package" );
lua_getfield( L, -1, "path" ); // get field "path" from table at top of stack (-1)
std::string cur_path = lua_tostring( L, -1 ); // grab path string from top of stack
cur_path.append( ";" ); // do your path magic here
cur_path.append( (path + "?.lua").c_str() );
lua_pop( L, 1 ); // get rid of the string on the stack we just pushed on line 5
lua_pushstring( L, cur_path.c_str() ); // push the new one
lua_setfield( L, -2, "path" ); // set the field "path" in table at -2 with value at top of stack
lua_pop( L, 1 ); // get rid of package table from top of stack
return 0; // all done!
}
bool MapSelectionManager::setSelectionBrush(const std::string& brush)
{
if(_luaState != nullptr)
{
lua_close(_luaState);
}
_luaState = luaL_newstate();
luaL_openlibs(_luaState);
luabind::open(_luaState);
luabind::module(_luaState)[
luabind::def("addToSelection",luabind::tag_function<void(int,int)>([this](int x,int y){
_addSelectedCood(sf::Vector2i(x,y));
}))
];
setLuaPath(_luaState,path::DIRECTORY_LUA);
if(luaL_dofile(_luaState,(path::DIRECTORY_BRUSH + brush).c_str()))
{
std::cerr<<"ERROR while loading \""<<path::DIRECTORY_BRUSH + brush<<"\" : "<<lua_tostring(_luaState, -1)<<std::endl;;
return false;
}
return true;
}
///////////////////////////// PRIVATE /////////////////////////////////
void MapSelectionManager::_updateSelectionArea()
{
assert(_luaState);
_resetSelection();
const sfutils::map::MapViewer& viewer = _owner.getMapViewer();
_clickIndicator[0].position = sf::Vector2f(viewer.mapCoordsToScreen(_clickPressedCoord));
_clickIndicator[1].position = sf::Vector2f(viewer.mapCoordsToScreen(_clickReleasedCoord));
luabind::call_function<void>(_luaState, "getSelection",
_clickPressedCoord.x,_clickPressedCoord.y,
_clickReleasedCoord.x,_clickReleasedCoord.y);
//_squareSelection(viewer);
_highlightLayer->sort();
}
void MapSelectionManager::_valideSelectedArea()
{
for(auto& coord : _selectedCoords)
{
_owner.fillTile(coord);
}
_resetSelection();
}
void MapSelectionManager::_resetSelection()
{
if(_highlightLayer != nullptr)
{
for(auto& ptr : _selectionHighlight)
{
_highlightLayer->remove(ptr,false);
}
}
_selectedCoords.clear();
}
void MapSelectionManager::_addSelectedCood(const sf::Vector2i& coord)
{
_selectedCoords.emplace_back(coord);
sf::Vector2f pixels = _owner.getMapViewer().mapCoordsToPixel(_selectedCoords.back());
sf::ConvexShape* ptr = _highlightLayer->add(_map->getGeometry().getShape(),false);
ptr->setFillColor(sf::Color(133,202,215,127));
ptr->setPosition(pixels);
_selectionHighlight.emplace_back(ptr);
}
}
}
| 31.623318 | 139 | 0.53928 | [
"render",
"object"
] |
a2f92ccdef8b49c21f1f61945bf34ff2aa73367c | 1,207 | hpp | C++ | spoki/libspoki/spoki/net/endpoint.hpp | inetrg/spoki | 599a19366e4cea70e2391471de6f6b745935cddf | [
"MIT"
] | 1 | 2022-02-03T15:35:16.000Z | 2022-02-03T15:35:16.000Z | spoki/libspoki/spoki/net/endpoint.hpp | inetrg/spoki | 599a19366e4cea70e2391471de6f6b745935cddf | [
"MIT"
] | null | null | null | spoki/libspoki/spoki/net/endpoint.hpp | inetrg/spoki | 599a19366e4cea70e2391471de6f6b745935cddf | [
"MIT"
] | null | null | null | /*
* This file is part of the CAF spoki driver.
*
* Copyright (C) 2018-2021
* Authors: Raphael Hiesgen
*
* All rights reserved.
*
* Report any bugs, questions or comments to raphael.hiesgen@haw-hamburg.de
*
*/
#pragma once
#include <functional>
#include <caf/ipv4_address.hpp>
#include "spoki/hashing.hpp"
namespace spoki::net {
struct SPOKI_CORE_EXPORT endpoint {
caf::ipv4_address daddr;
uint16_t dport;
};
/// Equality comparison operator for target_key.
SPOKI_CORE_EXPORT inline bool operator==(const endpoint& lhs,
const endpoint& rhs) {
return lhs.daddr == rhs.daddr && lhs.dport == rhs.dport;
}
/// Enable serialization by CAF.
template <class Inspector>
typename Inspector::result_type inspect(Inspector& f, endpoint& x) {
return f.object(x).fields(f.field("daddr", x.daddr),
f.field("dport", x.dport));
}
} // namespace spoki::net
namespace std {
template <>
struct hash<spoki::net::endpoint> {
size_t operator()(const spoki::net::endpoint& x) const {
size_t seed = 0;
spoki::hash_combine(seed, x.daddr);
spoki::hash_combine(seed, x.dport);
return seed;
}
};
} // namespace std
| 21.175439 | 75 | 0.657001 | [
"object"
] |
a2fd89a36576827301209e15c33a20c6cf95b08f | 488 | cpp | C++ | Cpp/1252.cells-with-odd-values-in-a-matrix.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | 1 | 2015-12-19T23:05:35.000Z | 2015-12-19T23:05:35.000Z | Cpp/1252.cells-with-odd-values-in-a-matrix.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | null | null | null | Cpp/1252.cells-with-odd-values-in-a-matrix.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | null | null | null | class Solution {
public:
int oddCells(int n, int m, vector<vector<int>>& indices) {
vector<bool> rows(n, false);
vector<bool> cols(m, false);
for (const auto& indice : indices) {
rows[indice[0]] = !rows[indice[0]];
cols[indice[1]] = !cols[indice[1]];
}
int r = 0, c = 0;
for (bool row : rows) r += row;
for (bool col : cols) c += col;
return r*m + c*n - 2*r*c;
}
}; | 27.111111 | 62 | 0.461066 | [
"vector"
] |
a2fe32b75f3de55363ef1942ceb156f79452af4f | 2,362 | cc | C++ | paddle/fluid/inference/tensorrt/convert/test_io_converter.cc | L-Net-1992/Paddle | 4d0ca02ba56760b456f3d4b42a538555b9b6c307 | [
"Apache-2.0"
] | 11 | 2016-08-29T07:43:26.000Z | 2016-08-29T07:51:24.000Z | paddle/fluid/inference/tensorrt/convert/test_io_converter.cc | L-Net-1992/Paddle | 4d0ca02ba56760b456f3d4b42a538555b9b6c307 | [
"Apache-2.0"
] | null | null | null | paddle/fluid/inference/tensorrt/convert/test_io_converter.cc | L-Net-1992/Paddle | 4d0ca02ba56760b456f3d4b42a538555b9b6c307 | [
"Apache-2.0"
] | 1 | 2021-12-09T08:59:17.000Z | 2021-12-09T08:59:17.000Z | /* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <gtest/gtest.h>
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/inference/tensorrt/convert/io_converter.h"
namespace paddle {
namespace inference {
namespace tensorrt {
void IOConverterTester(const platform::DeviceContext& ctx) {
cudaStream_t stream;
ASSERT_EQ(0, cudaStreamCreate(&stream));
// init fluid in_tensor
framework::LoDTensor in_tensor;
in_tensor.Resize({10, 10});
auto place = ctx.GetPlace();
in_tensor.mutable_data<float>(place);
std::vector<float> init;
for (int64_t i = 0; i < 10 * 10; ++i) {
init.push_back(i);
}
framework::TensorFromVector(init, ctx, &in_tensor);
// init tensorrt buffer
void* buffer;
size_t size = in_tensor.memory_size();
ASSERT_EQ(cudaMalloc(&buffer, size), 0);
// convert fluid in_tensor to tensorrt buffer
EngineIOConverter::ConvertInput("test", in_tensor, buffer, size, &stream);
// convert tensorrt buffer to fluid out_tensor
framework::LoDTensor out_tensor;
out_tensor.Resize({10, 10});
out_tensor.mutable_data<float>(place);
EngineIOConverter::ConvertOutput("test", buffer, &out_tensor, size, &stream);
// compare in_tensor and out_tensor
std::vector<float> result;
framework::TensorToVector(out_tensor, ctx, &result);
EXPECT_EQ(init.size(), result.size());
for (size_t i = 0; i < init.size(); i++) {
EXPECT_EQ(init[i], result[i]);
}
cudaStreamDestroy(stream);
}
TEST(EngineIOConverterTester, DefaultCPU) {
platform::CPUPlace place;
platform::CPUDeviceContext ctx(place);
IOConverterTester(ctx);
}
TEST(EngineIOConverterTester, DefaultGPU) {
platform::CUDAPlace place;
platform::CUDADeviceContext ctx(place);
IOConverterTester(ctx);
}
} // namespace tensorrt
} // namespace inference
} // namespace paddle
| 30.282051 | 79 | 0.740474 | [
"vector"
] |
0c136c0041b0d6710a622b8414f654fc642e3ebd | 7,739 | cpp | C++ | CompilerDev/Try-12/src/Vector3.cpp | Ashwin-Paudel/Tries | 91ea32d715eedca528d143cf5e9dfd9ba70804e3 | [
"Apache-2.0"
] | null | null | null | CompilerDev/Try-12/src/Vector3.cpp | Ashwin-Paudel/Tries | 91ea32d715eedca528d143cf5e9dfd9ba70804e3 | [
"Apache-2.0"
] | null | null | null | CompilerDev/Try-12/src/Vector3.cpp | Ashwin-Paudel/Tries | 91ea32d715eedca528d143cf5e9dfd9ba70804e3 | [
"Apache-2.0"
] | null | null | null | //
// Vector3.cpp
// Krim
//
// Created by आश्विन पौडेल on 2021-05-27.
//
#include <Vector3.h>
// Doing this will set the x, y, and z to 0
constexpr Vector3::Vector3()
{
x = 0;
y = 0;
z = 0;
}
// If the user gives a Vector3, we're going to set the x,y and z to the given vector
constexpr Vector3::Vector3(Vector3 const &v)
{
x = v.x;
y = v.y;
z = v.z;
}
// If the user gives a float, we're going to set the x,y and z to the given float
constexpr Vector3::Vector3(float scalar)
{
x = scalar;
y = scalar;
z = scalar;
}
// If the user manually types it in, we're going to set it to the data manually typed in
constexpr Vector3::Vector3(float a, float b, float c)
{
x = a;
y = b;
z = c;
}
// Our operators
// In the programming language, when a user does 5+10 with a vec3 data, we are going to call the vector struct to handle it for us
// When the user does '=' operation
// We're going to the our vector3 data to the given one
Vector3 &Vector3::operator=(const Vector3 &v)
{
x = v.x;
y = v.y;
z = v.z;
return *this;
}
// When the user does '+=' operation with a float
// We're going to increase all the vectors with the given number
Vector3 &Vector3::operator+=(float scalar)
{
x += scalar;
y += scalar;
z += scalar;
return *this;
}
// When the user does '+=' operation with a Vector3
// We're going to increase all the vectors with numbers of the given vector
Vector3 &Vector3::operator+=(const Vector3 &v)
{
x += v.x;
y += v.y;
z += v.z;
return *this;
}
// When the user does '-=' operation with a float
// We're going to decrease all the vectors with the float
Vector3 &Vector3::operator-=(float scalar)
{
x -= scalar;
y -= scalar;
z -= scalar;
return *this;
}
// When the user does '-=' operation with a Vector3
// We're going to decrease all the vectors with numbers of the given vector
Vector3 &Vector3::operator-=(const Vector3 &v)
{
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
// When the user does '*=' operation with a float
// We're going to multiply our vector with the given float
Vector3 &Vector3::operator*=(float scalar)
{
x *= scalar;
y *= scalar;
z *= scalar;
return *this;
}
// When the user does '*=' operation with a Vector3
// We're going to multiply all the vectors with numbers of the given vector
Vector3 &Vector3::operator*=(const Vector3 &v)
{
x *= v.x;
y *= v.y;
z *= v.z;
return *this;
}
// When the user does '/=' operation with a float
// We're going to divide our vector with the given float
Vector3 &Vector3::operator/=(float scalar)
{
x /= scalar;
y /= scalar;
z /= scalar;
return *this;
}
// When the user does '/=' operation with a Vector3
// We're going to divide all the vectors with numbers of the given vector
Vector3 &Vector3::operator/=(const Vector3 &v)
{
x /= v.x;
y /= v.y;
z /= v.z;
return *this;
}
// When the user does '++' operation
// We're going to increment all the vectors with 1
Vector3 &Vector3::operator++()
{
++x;
++y;
++z;
return *this;
}
// When the user does '++' operation with an integer
// We're going to increment this with 1 and multiply the integer
Vector3 Vector3::operator++(int)
{
Vector3 r(*this);
++*this;
return r;
}
// When the user does '--' operation
// We're going to decrease all the vectors with 1
Vector3 &Vector3::operator--()
{
--x;
--y;
--z;
return *this;
}
// When the user does '--' operation with an integer
// We're going to decrease all this with 1 and multiply the integer
Vector3 Vector3::operator--(int)
{
Vector3 r(*this);
--*this;
return r;
}
/// Addition
// When the user does '+' with vector
Vector3 operator+(Vector3 const &v)
{
return v;
}
// When the user does '+' with vector and float
// We're going to increase the given vector by the float
Vector3 operator+(Vector3 const &v, float scalar)
{
return Vector3(
v.x + scalar,
v.y + scalar,
v.z + scalar);
}
// When the user does '+' with vector and float
// We're going to increase the given vector by the float
Vector3 operator+(float scalar, Vector3 const &v)
{
return Vector3(
v.x + scalar,
v.y + scalar,
v.z + scalar);
}
// When the user does '+' with vector and another vector
// We're going to create a new vector3 and increase all the values
Vector3 operator+(Vector3 const &v1, Vector3 const &v2)
{
return Vector3(
v1.x + v2.x,
v1.y + v2.y,
v1.z + v2.z);
}
/// Subtraction
// When the user does '-' with vector
Vector3 operator-(Vector3 const &v)
{
return Vector3(-v.x, -v.y, -v.z);
}
// When the user does '-' with vector and float
// We're going to decrease the given vector by the float
Vector3 operator-(Vector3 const &v, float scalar)
{
return Vector3(
v.x - scalar,
v.y - scalar,
v.z - scalar);
}
// When the user does '-' with vector and float
// We're going to decrease the given vector by the float
Vector3 operator-(float scalar, Vector3 const &v)
{
return Vector3(
v.x - scalar,
v.y - scalar,
v.z - scalar);
}
// When the user does '-' with vector and another vector
// We're going to create a new vector3 and decrease all the values
Vector3 operator-(Vector3 const &v1, Vector3 const &v2)
{
return Vector3(
v1.x - v2.x,
v1.y - v2.y,
v1.z - v2.z);
}
/// Multiplication
// When the user does '*' with vector and float
// We're going to multiply the given vector by the float
Vector3 operator*(Vector3 const &v, float scalar)
{
return Vector3(
v.x * scalar,
v.y * scalar,
v.z * scalar);
}
// When the user does '*' with vector and float
// We're going to multiply the given vector by the float
Vector3 operator*(float scalar, Vector3 const &v)
{
return Vector3(
v.x * scalar,
v.y * scalar,
v.z * scalar);
}
// When the user does '*' with vector and another vector
// We're going to create a new vector3 and multiply all the values
Vector3 operator*(Vector3 const &v1, Vector3 const &v2)
{
return Vector3(
v1.x * v2.x,
v1.y * v2.y,
v1.z * v2.z);
}
/// Division
// When the user does '/' with vector and float
// We're going to divide the given vector by the float
Vector3 operator/(Vector3 const &v, float scalar)
{
return Vector3(
v.x / scalar,
v.y / scalar,
v.z / scalar);
}
// When the user does '/' with vector and float
// We're going to divide the given vector by the float
Vector3 operator/(float scalar, Vector3 const &v)
{
return Vector3(
v.x / scalar,
v.y / scalar,
v.z / scalar);
}
// When the user does '/' with vector and another vector
// We're going to create a new vector3 and devide all the values
Vector3 operator/(Vector3 const &v1, Vector3 const &v2)
{
return Vector3(
v1.x / v2.x,
v1.y / v2.y,
v1.z / v2.z);
}
/// Operations
// When the user does '==' with vector and another vector
// We're going to check the data of the first and second vector to see if each value is equal
bool operator==(Vector3 const &v1, Vector3 const &v2)
{
return v1.x == v2.x && v1.y == v2.y && v1.z == v2.z;
}
// When the user does '==' with vector and another vector
// We're going to check the data of the first and second vector to see if each value is not equal
bool operator!=(Vector3 const &v1, Vector3 const &v2)
{
return v1.x != v2.x || v1.y != v2.y || v1.z != v2.z;
}
// When the user wants print the data
// When the user does std::cout.
ostream &operator<<(ostream &os, Vector3 const &v)
{
return (os << v.x << ", " << v.y << ", " << v.z);
} | 24.964516 | 130 | 0.622819 | [
"vector"
] |
0c1d2d39ce83eb52b2e2260bcea04eee7f30ac34 | 1,155 | hpp | C++ | src/xpcc/ui/gui/widgets/numberfield.hpp | roboterclubaachen/xpcc | 010924901947381d20e83b838502880eb2ffea72 | [
"BSD-3-Clause"
] | 161 | 2015-01-13T15:52:06.000Z | 2020-02-13T01:26:04.000Z | src/xpcc/ui/gui/widgets/numberfield.hpp | salkinium/xpcc | 010924901947381d20e83b838502880eb2ffea72 | [
"BSD-3-Clause"
] | 281 | 2015-01-06T12:46:40.000Z | 2019-01-06T13:06:57.000Z | src/xpcc/ui/gui/widgets/numberfield.hpp | salkinium/xpcc | 010924901947381d20e83b838502880eb2ffea72 | [
"BSD-3-Clause"
] | 51 | 2015-03-03T19:56:12.000Z | 2020-03-22T02:13:36.000Z | // coding: utf-8
/* Copyright (c) 2014, Roboterclub Aachen e.V.
* All Rights Reserved.
*
* The file is part of the xpcc library and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC_GUI_NUMBERFIELD_HPP
#define XPCC_GUI_NUMBERFIELD_HPP
#include "widget.hpp"
namespace xpcc
{
namespace gui
{
/**
* @ingroup gui
* @author Daniel Krebs
*/
template<typename T>
class NumberField : public Widget
{
public:
NumberField(T default_value, Dimension d) :
Widget(d, false),
value(default_value)
{
}
void
render(View* view);
void
setValue(T value)
{
if(this->value == value)
return;
this->value = value;
this->markDirty();
}
T
getValue()
{
return this->value;
}
private:
T value;
};
typedef NumberField<int16_t> IntegerField;
class FloatField : public NumberField<float>
{
public:
FloatField(float value, Dimension d);
void
render(View* view);
};
} // namespace gui
} // namespace xpcc
#include "numberfield_impl.hpp"
#endif // XPCC_GUI_NUMBERFIELD_HPP
| 15.197368 | 79 | 0.651082 | [
"render"
] |
0c2c4c58aaff820269b0f99a4147134009544413 | 9,047 | cpp | C++ | applications/PfemFluidDynamicsApplication/custom_elements/three_step_second_order_pspg_updated_lagrangian_element.cpp | KlausBSautter/Kratos | 245b30e38497a242bbdf999278e9c1b6175a573a | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | applications/PfemFluidDynamicsApplication/custom_elements/three_step_second_order_pspg_updated_lagrangian_element.cpp | KlausBSautter/Kratos | 245b30e38497a242bbdf999278e9c1b6175a573a | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | applications/PfemFluidDynamicsApplication/custom_elements/three_step_second_order_pspg_updated_lagrangian_element.cpp | philbucher/Kratos | 1ceb900dbacfab344e27e32285250eafc52093ec | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | //
// Project Name: KratosFluidDynamicsApplication $
// Last modified by: $Author: AFranci $
// Date: $Date: June 2021 $
// Revision: $Revision: 0.0 $
//
// Implementation of the Gauss-Seidel two step Updated Lagrangian Velocity-Pressure element
// ( There is a ScalingConstant to multiply the mass balance equation for a number because i read it somewhere)
//
// System includes
// External includes
// Project includes
#include "custom_elements/three_step_second_order_pspg_updated_lagrangian_element.h"
#include "includes/cfd_variables.h"
namespace Kratos
{
template <unsigned int TDim>
Element::Pointer ThreeStepSecondOrderPspgUpdatedLagrangianElement<TDim>::Clone(IndexType NewId, NodesArrayType const &rThisNodes) const
{
KRATOS_TRY;
ThreeStepSecondOrderPspgUpdatedLagrangianElement NewElement(NewId, this->GetGeometry().Create(rThisNodes), this->pGetProperties());
NewElement.SetData(this->GetData());
NewElement.SetFlags(this->GetFlags());
return Element::Pointer(new ThreeStepSecondOrderPspgUpdatedLagrangianElement(NewElement));
KRATOS_CATCH("");
}
template <unsigned int TDim>
void ThreeStepSecondOrderPspgUpdatedLagrangianElement<TDim>::CalculateLocalSystem(MatrixType &rLeftHandSideMatrix,
VectorType &rRightHandSideVector,
const ProcessInfo &rCurrentProcessInfo)
{
KRATOS_TRY;
switch (rCurrentProcessInfo[FRACTIONAL_STEP])
{
case 1:
{
this->CalculateSecondVelocitySystem(rLeftHandSideMatrix, rRightHandSideVector, rCurrentProcessInfo);
break;
}
case 5:
{
this->CalculateFSplusPSPGPressureSystem(rLeftHandSideMatrix, rRightHandSideVector, rCurrentProcessInfo);
break;
}
default:
{
KRATOS_THROW_ERROR(std::logic_error, "Unexpected value for THREE_STEP_SECOND_ORDER_PSPG_UPDATED_LAGRANGIAN_ELEMENT index: ", rCurrentProcessInfo[FRACTIONAL_STEP]);
}
}
KRATOS_CATCH("");
}
template <unsigned int TDim>
void ThreeStepSecondOrderPspgUpdatedLagrangianElement<TDim>::CalculateFSplusPSPGPressureSystem(MatrixType &rLeftHandSideMatrix,
VectorType &rRightHandSideVector,
const ProcessInfo &rCurrentProcessInfo)
{
GeometryType &rGeom = this->GetGeometry();
const unsigned int NumNodes = rGeom.PointsNumber();
// Check sizes and initialize
if (rLeftHandSideMatrix.size1() != NumNodes)
rLeftHandSideMatrix.resize(NumNodes, NumNodes, false);
noalias(rLeftHandSideMatrix) = ZeroMatrix(NumNodes, NumNodes);
if (rRightHandSideVector.size() != NumNodes)
rRightHandSideVector.resize(NumNodes, false);
noalias(rRightHandSideVector) = ZeroVector(NumNodes);
// Shape functions and integration points
ShapeFunctionDerivativesArrayType DN_DX;
Matrix NContainer;
VectorType GaussWeights;
this->CalculateGeometryData(DN_DX, NContainer, GaussWeights);
const unsigned int NumGauss = GaussWeights.size();
double TimeStep = rCurrentProcessInfo[DELTA_TIME];
double ElemSize = this->ElementSize();
double Viscosity = 0;
double Density = 0;
double totalVolume = 0;
MatrixType DynamicStabilizationMatrix = ZeroMatrix(NumNodes, NumNodes);
// ElementalVariables rElementalVariables;
// this->InitializeElementalVariables(rElementalVariables);
// Loop on integration points
for (unsigned int g = 0; g < NumGauss; ++g)
{
const double GaussWeight = GaussWeights[g];
totalVolume += GaussWeight;
const ShapeFunctionsType &rN = row(NContainer, g);
const ShapeFunctionDerivativesType &rDN_DX = DN_DX[g];
this->EvaluateInPoint(Viscosity, DYNAMIC_VISCOSITY, rN);
this->EvaluateInPoint(Density, DENSITY, rN);
double PSPGweight = 0.1;
double Tau = 0;
this->CalculateTauPSPG(Tau, ElemSize, Density, Viscosity, rCurrentProcessInfo);
double StabilizedWeight = Tau * GaussWeight;
array_1d<double, TDim> OldPressureGradient = ZeroVector(TDim);
this->EvaluateGradientDifferenceInPoint(OldPressureGradient, PRESSURE, rDN_DX, PSPGweight);
double DivU = 0;
this->EvaluateDivergenceInPoint(DivU, VELOCITY, rDN_DX);
for (SizeType i = 0; i < NumNodes; ++i)
{
// LHS contribution
double dynamicRHSi = 0;
unsigned int freeSurfaceNodes = 0;
for (SizeType j = 0; j < NumNodes; ++j)
{
double Lij = 0.0;
for (SizeType d = 0; d < TDim; ++d)
Lij += (1.0 + PSPGweight) * rDN_DX(i, d) * rDN_DX(j, d);
Lij *= StabilizedWeight;
rLeftHandSideMatrix(i, j) += Lij;
dynamicRHSi += rDN_DX(i, 0) * rN[j] * (this->GetGeometry()[j].FastGetSolutionStepValue(VELOCITY_X, 0) - this->GetGeometry()[j].FastGetSolutionStepValue(VELOCITY_X, 1)) / TimeStep;
dynamicRHSi += rDN_DX(i, 1) * rN[j] * (this->GetGeometry()[j].FastGetSolutionStepValue(VELOCITY_Y, 0) - this->GetGeometry()[j].FastGetSolutionStepValue(VELOCITY_Y, 1)) / TimeStep;
if (TDim == 3)
{
dynamicRHSi += rDN_DX(i, 2) * rN[j] * (this->GetGeometry()[j].FastGetSolutionStepValue(VELOCITY_Z, 0) - this->GetGeometry()[j].FastGetSolutionStepValue(VELOCITY_Z, 1)) / TimeStep;
}
if (rGeom[j].Is(FREE_SURFACE) && rGeom[j].IsNot(INLET))
{
freeSurfaceNodes++;
}
}
if (freeSurfaceNodes >= TDim)
{
// bool computeElement = this->CalcCompleteStrainRate(rElementalVariables, rCurrentProcessInfo, rDN_DX, 1.0);
// VectorType deviatoricSpatialDefRate = rElementalVariables.SpatialDefRate;
// deviatoricSpatialDefRate[0] -= DivU / 3.0;
// deviatoricSpatialDefRate[1] -= DivU / 3.0;
const double lagMultiplier = TimeStep / (ElemSize * ElemSize * Density);
this->ComputeBoundaryTermsForPressureSystem(rLeftHandSideMatrix, rRightHandSideVector, rN, lagMultiplier);
}
// RHS contribution
rRightHandSideVector[i] += -PSPGweight * GaussWeight * Tau * Density * dynamicRHSi;
rRightHandSideVector[i] += -(1.0 + PSPGweight) * GaussWeight * rN[i] * DivU;
double laplacianRHSi = 0;
double bodyForceStabilizedRHSi = 0;
array_1d<double, 3> VolumeAcceleration = this->GetGeometry()[i].FastGetSolutionStepValue(VOLUME_ACCELERATION);
// // stored body force information for the closed domain test with analytical solution
// array_1d<double, 3> VolumeAcceleration = this->GetGeometry()[i].FastGetSolutionStepValue(VOLUME_ACCELERATION);
// double posX = (this->GetGeometry()[0].X() + this->GetGeometry()[1].X() + this->GetGeometry()[2].X()) / 3.0;
// double posY = (this->GetGeometry()[0].Y() + this->GetGeometry()[1].Y() + this->GetGeometry()[2].Y()) / 3.0;
// double coeffX = (12.0 - 24.0 * posY) * pow(posX, 4);
// coeffX += (-24.0 + 48.0 * posY) * pow(posX, 3);
// coeffX += (-48.0 * posY + 72.0 * pow(posY, 2) - 48.0 * pow(posY, 3) + 12.0) * pow(posX, 2);
// coeffX += (-2.0 + 24.0 * posY - 72.0 * pow(posY, 2) + 48.0 * pow(posY, 3)) * posX;
// coeffX += 1.0 - 4.0 * posY + 12.0 * pow(posY, 2) - 8.0 * pow(posY, 3);
// double coeffY = (8.0 - 48.0 * posY + 48.0 * pow(posY, 2)) * pow(posX, 3);
// coeffY += (-12.0 + 72.0 * posY - 72.0 * pow(posY, 2)) * pow(posX, 2);
// coeffY += (4.0 - 24.0 * posY + 48.0 * pow(posY, 2) - 48.0 * pow(posY, 3) + 24.0 * pow(posY, 4)) * posX;
// coeffY += -12.0 * pow(posY, 2) + 24.0 * pow(posY, 3) - 12.0 * pow(posY, 4);
// VolumeAcceleration[0] *= coeffX;
// VolumeAcceleration[1] *= coeffY;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
for (SizeType d = 0; d < TDim; ++d)
{
laplacianRHSi += -StabilizedWeight * rDN_DX(i, d) * OldPressureGradient[d];
bodyForceStabilizedRHSi += PSPGweight * StabilizedWeight * rDN_DX(i, d) * (Density * VolumeAcceleration[d]);
}
rRightHandSideVector[i] += laplacianRHSi + bodyForceStabilizedRHSi;
}
}
}
/*
* Template class definition (this should allow us to compile the desired template instantiations)
*/
template class ThreeStepSecondOrderPspgUpdatedLagrangianElement<2>;
template class ThreeStepSecondOrderPspgUpdatedLagrangianElement<3>;
} // namespace Kratos
| 43.495192 | 192 | 0.610368 | [
"shape"
] |
0c4e752541696aff7c82b9689304a4f5797bef18 | 2,501 | cpp | C++ | src/Helper.cpp | 3zcs/Cpider | 969c9d996a6cd9aff08430739d7c51cd6bcb8fda | [
"Unlicense"
] | null | null | null | src/Helper.cpp | 3zcs/Cpider | 969c9d996a6cd9aff08430739d7c51cd6bcb8fda | [
"Unlicense"
] | null | null | null | src/Helper.cpp | 3zcs/Cpider | 969c9d996a6cd9aff08430739d7c51cd6bcb8fda | [
"Unlicense"
] | null | null | null | #include "Helper.h"
std::promise<std::string> prms;
std::future<std::string> ftr = prms.get_future();
std::vector<std::future<void>> futures;
std::mutex mutexCheck, mutexInsert, mtx;
std::condition_variable _cond;
bool ready = false;
void start(std::string url, std::string path)
{
if (!path.empty())
{
if (path.find("http") == 0 || path.find("https") == 0)
{
url = path;
}
else
{
url = url + path;
}
}
// request
Requester requester(url.c_str());
// parse
Parser parser(requester.getBuffer(), url);
if (!parser.getLinks().empty())
{
std::lock_guard<std::mutex> lck(mutexInsert);
std::vector<Link> tmp;
tmp = parser.getLinks();
for (Link link : tmp)
{
if (linksMap.count(link.getPath()) == 0)
linksMap.insert(std::pair<std::string, Link>(link.getPath(), link));
}
}
}
void writeToFile(std::promise<std::string> &&prms, ResultHandler* handler, std::string domain)
{
if(handler->writeToFile(domain)){
prms.set_value(fileLocation+ domain+txt);
}else {
prms.set_value(errorfile);
}
//write after finish printing
std::unique_lock<std::mutex> lck(mtx);
while (!ready) _cond.wait(lck);
// print file name
std::cout << doubleNewLine<<ftr.get() << doubleNewLine<<std::endl;
}
void print(ResultHandler* handler)
{
std::unique_lock<std::mutex> lck(mtx);
ready = handler->print();
_cond.notify_all();
}
void parseLikes(int depth, std::string url)
{
for (int i = 0; i < depth; i++)
{
for (std::map<std::string, Link>::iterator i = linksMap.begin(); i != linksMap.end(); i++)
{
std::lock_guard<std::mutex> lck(mutexCheck);
if ((*i).second.isInternal() && !(*i).second.isVisted())
{
(*i).second.setVisited(true);
futures.emplace_back(std::async(start, url, (*i).second.getPath()));
}
}
}
// join all thread
for (auto &e : futures)
{
e.wait();
}
}
void handleResult(std::string domain){
std::unique_ptr<ResultHandler> Rhandler(new CustomResultHandler(linksMap));
// start thread and pass promise as argument
std::thread twrite(writeToFile, std::move(prms), Rhandler.get(),domain);
std::thread tprint(print, Rhandler.get());
// thread barrier
twrite.join();
tprint.join();
} | 25.01 | 98 | 0.569372 | [
"vector"
] |
0c50d4e54c0f2d2c9d9fa23bb8824efc3d7c900c | 8,399 | hxx | C++ | src/meanstdimage/meanstdimage.hxx | sderaedt/ITKTools | c1a0748bd9c09f9abd6ba4d1b88ce09fb2217df6 | [
"Apache-2.0"
] | 29 | 2015-03-14T07:13:00.000Z | 2021-12-16T13:01:44.000Z | src/meanstdimage/meanstdimage.hxx | sderaedt/ITKTools | c1a0748bd9c09f9abd6ba4d1b88ce09fb2217df6 | [
"Apache-2.0"
] | 6 | 2015-02-05T21:51:42.000Z | 2020-09-04T10:57:44.000Z | src/meanstdimage/meanstdimage.hxx | sderaedt/ITKTools | c1a0748bd9c09f9abd6ba4d1b88ce09fb2217df6 | [
"Apache-2.0"
] | 13 | 2015-07-02T14:35:22.000Z | 2021-05-27T08:46:37.000Z | /*=========================================================================
*
* Copyright Marius Staring, Stefan Klein, David Doria. 2011.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __meanstdimage_hxx_
#define __meanstdimage_hxx_
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
template< unsigned int VDimension, class TComponentType >
void
ITKToolsMeanStdImage< VDimension, TComponentType >
::MeanStdImage(
const std::vector<std::string> & inputFileNames,
const std::vector<std::string> & inputMaskFileNames,
const bool calc_mean,
const std::string & outputFileNameMean,
const bool calc_std,
const std::string & outputFileNameStd,
const bool population_std,
const bool use_compression)
{
/** TYPEDEF's. */
typedef typename InputImageType::Pointer ImagePointer;
typedef typename OutputImageType::Pointer OutImagePointer;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
typedef typename InputImageType::PixelType PixelType;
typedef typename ReaderType::Pointer ReaderPointer;
typedef typename WriterType::Pointer WriterPointer;
/** DECLARATION'S. */
const unsigned int nrInputs = inputFileNames.size();
const unsigned int nrMasks = inputMaskFileNames.size();
ReaderPointer inReader;
ReaderPointer inMaskReader;
WriterPointer writer_mean = WriterType::New();
WriterPointer writer_std = WriterType::New();
OutImagePointer mean = OutputImageType::New();
OutImagePointer sq_mean = OutputImageType::New();
OutImagePointer std = OutputImageType::New();
OutImagePointer nr_images = OutputImageType::New();
itk::ImageRegionConstIterator<InputImageType> input_iterator;
itk::ImageRegionConstIterator<InputImageType> mask_iterator;
itk::ImageRegionIterator<OutputImageType> mean_iterator;
itk::ImageRegionIterator<OutputImageType> sq_mean_iterator;
itk::ImageRegionIterator<OutputImageType> std_iterator;
itk::ImageRegionIterator<OutputImageType> nr_images_iterator;
/** Create temporary & output images */
inReader = ReaderType::New();
inReader->SetFileName( inputFileNames[0].c_str() );
inReader->Update();
mean->CopyInformation( inReader->GetOutput() );
sq_mean->CopyInformation( inReader->GetOutput() );
std->CopyInformation( inReader->GetOutput() );
mean->SetRegions( inReader->GetOutput()->GetLargestPossibleRegion().GetSize() );
sq_mean->SetRegions( inReader->GetOutput()->GetLargestPossibleRegion().GetSize() );
std->SetRegions( inReader->GetOutput()->GetLargestPossibleRegion().GetSize() );
mean->Allocate();
sq_mean->Allocate();
std->Allocate();
mean->FillBuffer( 0.0 );
sq_mean->FillBuffer( 0.0 );
std->FillBuffer( 0.0 );
mean_iterator = itk::ImageRegionIterator<OutputImageType>( mean, mean->GetRequestedRegion() );
sq_mean_iterator = itk::ImageRegionIterator<OutputImageType>( sq_mean, sq_mean->GetRequestedRegion() );
std_iterator = itk::ImageRegionIterator<OutputImageType>( std, std->GetRequestedRegion() );
/** Checking if there are masks and initialising the iterator*/
if (nrMasks != 0 )
{
inMaskReader = ReaderType::New();
inMaskReader->SetFileName( inputMaskFileNames[0].c_str() );
inMaskReader->Update();
nr_images->CopyInformation( inReader->GetOutput() );
nr_images->SetRegions( inReader->GetOutput()->GetLargestPossibleRegion().GetSize() );
nr_images->Allocate();
nr_images->FillBuffer(0);
nr_images_iterator = itk::ImageRegionIterator<OutputImageType>( nr_images, nr_images->GetRequestedRegion() );
}
/** Loop over all images and create sum(X) and sum(X^2) which is required for E(X) and E(X^2) */
for( unsigned int i = 0; i < nrInputs; ++i )
{
std::cout << "Reading image " << inputFileNames[ i ].c_str() << std::endl;
inReader = ReaderType::New();
inReader->SetFileName( inputFileNames[ i ].c_str() );
inReader->Update();
input_iterator = itk::ImageRegionConstIterator<InputImageType>(
inReader->GetOutput(), inReader->GetOutput()->GetRequestedRegion() );
input_iterator.GoToBegin();
mean_iterator.GoToBegin();
sq_mean_iterator.GoToBegin();
/** Reading the masks if needed*/
if (nrMasks != 0 )
{
std::cout << "Reading mask " << inputMaskFileNames[ i ].c_str() << std::endl;
inMaskReader = ReaderType::New();
inMaskReader->SetFileName( inputMaskFileNames[ i ].c_str() );
inMaskReader->Update();
mask_iterator = itk::ImageRegionConstIterator<InputImageType>(
inMaskReader->GetOutput(), inMaskReader->GetOutput()->GetRequestedRegion() );
mask_iterator.GoToBegin();
nr_images_iterator.GoToBegin();
}
/** Create two maps for calculating the mean and std: sum(X) and sum(X^2) */
for (; !mean_iterator.IsAtEnd(); ++mean_iterator, ++sq_mean_iterator, ++input_iterator)
{
/** Calculating the mean if there are no masks or if the mask is not zero in current voxel*/
if (nrMasks == 0 || mask_iterator.Get() !=0)
{
mean_iterator.Set( mean_iterator.Get() + input_iterator.Get() );
if( calc_std )
sq_mean_iterator.Set( sq_mean_iterator.Get() + (input_iterator.Get() * input_iterator.Get()) );
}
if (nrMasks != 0)
{
/** If masks are used, the number of the images used for the mean for each voxel is updated*/
if (mask_iterator.Get() != 0 )
{
nr_images_iterator.Set( nr_images_iterator.Get() + 1);
}
/** Update iterators if we are in fact using masks*/
++mask_iterator;
++nr_images_iterator;
}
}
}
/** Calculate mean and standard deviation using:
mean = ( SUM(X) / N )
std = sqrt( E(X^2) - (E(X))^2 ) for population standard deviation
std = sqrt(N / (N-1)) * sqrt( E(X^2) - (E(X))^2 ) for sample standard deviation
*/
mean_iterator.GoToBegin();
sq_mean_iterator.GoToBegin();
std_iterator.GoToBegin();
nr_images_iterator.GoToBegin();
/** Denominator for the 1/N calculations and sample_std_factor N/(N-1) to get sample std from population std */
float denominator( 1.0f / nrInputs );
float sample_std_factor = std::sqrt(((float) nrInputs) / ((float) nrInputs - 1));
for (; !mean_iterator.IsAtEnd(); ++mean_iterator, ++sq_mean_iterator, ++std_iterator)
{
if (nrMasks != 0)
{
if (nr_images_iterator.Get() > 1)
{
denominator = 1 / nr_images_iterator.Get();
sample_std_factor = std::sqrt(((float) nr_images_iterator.Get()) / ((float) nr_images_iterator.Get() - 1));
}
else
{
denominator = nr_images_iterator.Get();
sample_std_factor = 0;
}
++nr_images_iterator;
}
/** Calculate mean and mean of squares */
mean_iterator.Set( denominator * mean_iterator.Get() );
sq_mean_iterator.Set( denominator * sq_mean_iterator.Get() );
/** Calculate standard deviation */
if (calc_std)
{
if (population_std) // Calculate either sample or population standard deviation
{
std_iterator.Set( std::sqrt(
(float) std::abs( sq_mean_iterator.Get() - (mean_iterator.Get() * mean_iterator.Get() ) ) ) );
}
else
{
std_iterator.Set( sample_std_factor * std::sqrt(
(float) std::abs( sq_mean_iterator.Get() - (mean_iterator.Get() * mean_iterator.Get() ) ) ) );
}
}
}
/** Write the output images */
if( calc_mean )
{
writer_mean->SetFileName( outputFileNameMean.c_str() );
writer_mean->SetInput( mean );
writer_mean->SetUseCompression( use_compression );
writer_mean->Update();
}
if( calc_std )
{
writer_std->SetFileName( outputFileNameStd.c_str() );
writer_std->SetInput( std );
writer_std->SetUseCompression( use_compression );
writer_std->Update();
}
} // end MeanStdImage()
#endif // end #ifndef __meanstdimage_hxx_
| 36.202586 | 113 | 0.68401 | [
"vector"
] |
31c5f7e6d6cdb8725c575860912674657096b3aa | 2,642 | hpp | C++ | include/taskparts/rollforward.hpp | mikerainey/taskparts | 27d4bdda15a5c370c25df6ce8be1233362107cc8 | [
"MIT"
] | null | null | null | include/taskparts/rollforward.hpp | mikerainey/taskparts | 27d4bdda15a5c370c25df6ce8be1233362107cc8 | [
"MIT"
] | null | null | null | include/taskparts/rollforward.hpp | mikerainey/taskparts | 27d4bdda15a5c370c25df6ce8be1233362107cc8 | [
"MIT"
] | null | null | null | #pragma once
#include <utility>
#include <algorithm>
#include <vector>
#if defined(TASKPARTS_POSIX)
using register_type = greg_t;
#elif defined (TASKPARTS_NAUTILUS)
using register_type = ulong_t*;
#else
#error need to declare platform (e.g., TASKPARTS_POSIX)
#endif
/*---------------------------------------------------------------------*/
/* Rollforward table and lookup */
namespace taskparts {
using rollforward_edge_type = std::pair<register_type, register_type>;
using rollforward_lookup_table_type = std::vector<rollforward_edge_type>;
auto rollforward_edge_less = [] (const rollforward_edge_type& e1, const rollforward_edge_type& e2) {
return e1.first < e2.first;
};
template <typename L>
auto mk_rollforward_entry(L src, L dst) -> rollforward_edge_type {
return std::make_pair((register_type)src, (register_type)dst);
}
// returns the entry dst, if (src, dst) is in the rollforward table t, and src otherwise
static inline
auto lookup_rollforward_entry(const rollforward_lookup_table_type& t, register_type src)
-> register_type {
auto dst = src;
size_t n = t.size();
if (n == 0) {
return src;
}
static constexpr
int64_t not_found = -1;
int64_t k;
{
int64_t i = 0, j = (int64_t)n - 1;
while (i <= j) {
k = i + ((j - i) / 2);
if (t[k].first == src) {
goto exit;
} else if (t[k].first < src) {
i = k + 1;
} else {
j = k - 1;
}
}
k = not_found;
}
exit:
if (k != not_found) {
dst = t[k].second;
}
return dst;
}
// returns the entry src, if (src, dst) is in the rollforward table t, and dst otherwise
auto reverse_lookup_rollforward_entry(const rollforward_lookup_table_type& t, register_type dst)
-> register_type {
for (const auto& p : t) {
if (dst == p.second) {
return p.first;
}
}
return dst;
}
template <class T>
void try_to_initiate_rollforward(const T& t, register_type* rip) {
auto ip = *rip;
auto dst = lookup_rollforward_entry(t, ip);
if (dst != ip) {
*rip = dst;
}
}
rollforward_lookup_table_type rollforward_table;
auto reverse_lookup_rollforward_entry(void* dst) -> void* {
return (void*)reverse_lookup_rollforward_entry(rollforward_table, (register_type)dst);
}
auto initialize_rollfoward_table() {
std::sort(rollforward_table.begin(), rollforward_table.end(), rollforward_edge_less);
}
auto clear_rollforward_table() {
rollforward_table.clear();
}
} // end namespace
#if defined(TASKPARTS_POSIX)
#include "posix/rollforward.hpp"
#elif defined (TASKPARTS_NAUTILUS)
#include "nautilus/rollforward.hpp"
#else
#error need to declare platform (e.g., TASKPARTS_POSIX)
#endif
| 24.238532 | 100 | 0.676382 | [
"vector"
] |
31c9a7276b3fa9ab9c3dc6102565d5580c86330b | 3,157 | cpp | C++ | UI/UI/TrainerCreator.cpp | primetime00/CCCheat | 827fcfb0f06946ed9cde5a10dd489b4a677209ff | [
"Apache-2.0"
] | 16 | 2017-01-30T05:51:34.000Z | 2022-01-26T21:04:26.000Z | UI/UI/TrainerCreator.cpp | ps3lib/CCCheat | 827fcfb0f06946ed9cde5a10dd489b4a677209ff | [
"Apache-2.0"
] | 2 | 2016-06-24T15:15:44.000Z | 2018-10-16T15:10:36.000Z | UI/UI/TrainerCreator.cpp | ps3lib/CCCheat | 827fcfb0f06946ed9cde5a10dd489b4a677209ff | [
"Apache-2.0"
] | 3 | 2015-09-26T17:04:15.000Z | 2020-06-09T16:09:22.000Z | #include "TrainerCreator.h"
#include "Trainer/Trainer.h"
#include "TrainerSrc.h"
#include <vector>
#include <algorithm>
#include <fstream>
#if !defined(_WIN32) && !defined(WIN32)
#include <sys/stat.h>
#endif
using namespace std;
TrainerCreator::TrainerCreator()
{
m_title = "";
m_region = "";
m_gameTitle = "";
m_author = "";
m_info = "";
totalCodeSize = 0;
//lets find the locations
vector<unsigned char> s;
s.assign(trainSrc, trainSrc+sizeof(trainSrc));
auto it = search(s.begin(), s.end(), TITLE_TXT, TITLE_TXT+strlen(TITLE_TXT)); m_locationMap[TITLE_TXT] = rkPair(it - s.begin(), TITLELEN);
it = search(s.begin(), s.end(), AUTHOR_TXT, AUTHOR_TXT+strlen(AUTHOR_TXT)); m_locationMap[AUTHOR_TXT] = rkPair(it - s.begin(), AUTHORLEN);
it = search(s.begin(), s.end(), INFO_TXT, INFO_TXT+strlen(INFO_TXT)); m_locationMap[INFO_TXT] = rkPair(it - s.begin(), INFOLEN);
it = search(s.begin(), s.end(), CODES_TXT, CODES_TXT+strlen(CODES_TXT)); m_locationMap[CODES_TXT] = rkPair(it - s.begin(), CODESLEN);
it = search(s.begin(), s.end(), GAME_TITLE_TXT, GAME_TITLE_TXT+strlen(GAME_TITLE_TXT)); m_locationMap[GAME_TITLE_TXT] = rkPair(it - s.begin(), GAMETITLELEN);
it = search(s.begin(), s.end(), VERSION_TXT, VERSION_TXT+strlen(VERSION_TXT)); m_locationMap[VERSION_TXT] = rkPair(it - s.begin(), VERSIONLEN);
it = search(s.begin(), s.end(), REGION_TXT, REGION_TXT+strlen(REGION_TXT)); m_locationMap[REGION_TXT] = rkPair(it - s.begin(), REGIONLEN);
}
TrainerCreator::~TrainerCreator()
{
}
void TrainerCreator::setCodes(vector<rkTrainerCode> &codes)
{
int pos = 1;
codeBuffer[0] = codes.size();
for (auto it = codes.begin(); it != codes.end(); ++it)
{
pos += (*it)->write(&codeBuffer[pos]);
}
totalCodeSize = pos;
}
void TrainerCreator::inject(string findValue, string replaceValue)
{
if (m_locationMap.count(findValue) == 0)
return;
unsigned char *pt = &trainSrc[m_locationMap[findValue].location];
int size = m_locationMap[findValue].length;
memset(pt, 0, size);
memcpy(pt, replaceValue.c_str(), replaceValue.length());
}
void TrainerCreator::injectCode(char *buffer)
{
if (m_locationMap.count(CODES_TXT) == 0)
return;
unsigned char *pt = &trainSrc[m_locationMap[CODES_TXT].location];
int size = m_locationMap[CODES_TXT].length;
memset(pt, 0, size);
memcpy(pt, (unsigned char*)codeBuffer, totalCodeSize);
}
void TrainerCreator::exportTrainer(bool debug)
{
if (codeBuffer[0] == 0)
return;
#if defined(_WIN32) || defined(WIN32)
string fname = m_title + "-" + m_gameTitle + ".exe";
#else
string fname = m_title + "-" + m_gameTitle;
#endif
inject(TITLE_TXT, m_title);
inject(AUTHOR_TXT, m_author);
inject(INFO_TXT, m_info);
inject(GAME_TITLE_TXT, m_gameTitle);
inject(VERSION_TXT, m_version);
inject(REGION_TXT, m_region);
injectCode(codeBuffer);
ofstream outFile(fname.c_str(), ofstream::binary);
outFile.write((char*)trainSrc, sizeof(trainSrc));
outFile.close();
#if !defined(_WIN32) && !defined(WIN32)
chmod(fname.c_str(),755);
#endif
if (debug)
{
ofstream outDebugFile("dbg.dat", ofstream::binary);
outDebugFile.write((char*)codeBuffer, totalCodeSize);
outDebugFile.close();
}
}
| 32.214286 | 158 | 0.707634 | [
"vector"
] |
31cbee5f726e80de312e54af6f42df8a0c5900b6 | 14,307 | cpp | C++ | src/rpc_txn_client.cpp | thu-pacman/RisGraph | 2e36df68f1e88accf2f5f85669c532d3b7b5d7c3 | [
"Apache-2.0"
] | 13 | 2021-08-24T14:05:36.000Z | 2022-03-20T09:02:40.000Z | src/rpc_txn_client.cpp | thu-pacman/RisGraph | 2e36df68f1e88accf2f5f85669c532d3b7b5d7c3 | [
"Apache-2.0"
] | 1 | 2021-10-02T09:01:51.000Z | 2021-10-02T09:39:44.000Z | src/rpc_txn_client.cpp | thu-pacman/RisGraph | 2e36df68f1e88accf2f5f85669c532d3b7b5d7c3 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2020 Guanyu Feng, Tsinghua University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdio>
#include <cstdint>
#include <cassert>
#include <string>
#include <vector>
#include <utility>
#include <chrono>
#include <thread>
#include <fcntl.h>
#include <unistd.h>
#include <immintrin.h>
#include <omp.h>
#include "core/type.hpp"
#include "core/graph.hpp"
#include "core/io.hpp"
#include "core/ucx_stream.hpp"
#include "core/rpc.hpp"
int main(int argc, char** argv)
{
if(argc <= 7)
{
fprintf(stderr, "usage: %s graph timeout_ms clients queue_depth sleep_time_us updates_per_txn server", argv[0]);
exit(1);
}
std::pair<uint64_t, uint64_t> *raw_edges, *add_raw_edges, *del_raw_edges;
uint64_t raw_edges_len, add_raw_edges_len, del_raw_edges_len;
std::tie(raw_edges, raw_edges_len) = mmap_binary(argv[1]);
const uint32_t timeout_ms = std::stoi(argv[2]);
const uint64_t clients = std::stoull(argv[3]);
const uint32_t queue_depth = std::stoi(argv[4]);
const uint32_t sleep_time_us = std::stoi(argv[5]);
const uint32_t updates_per_txn = std::stoi(argv[6]);
uint64_t imported_edges = raw_edges_len*0.9;
if(argc > 9)
{
std::tie(add_raw_edges, add_raw_edges_len) = mmap_binary(argv[8]);
std::tie(del_raw_edges, del_raw_edges_len) = mmap_binary(argv[9]);
}
else
{
add_raw_edges = raw_edges + imported_edges;
add_raw_edges_len = raw_edges_len*0.1;
del_raw_edges = raw_edges;
del_raw_edges_len = raw_edges_len*0.1;
}
uint64_t num_vertices = 0;
{
auto start = std::chrono::system_clock::now();
#pragma omp parallel for
for(uint64_t i=0;i<raw_edges_len;i++)
{
const auto &e = raw_edges[i];
write_max(&num_vertices, e.first+1);
write_max(&num_vertices, e.second+1);
}
auto end = std::chrono::system_clock::now();
fprintf(stderr, "read: %.6lfs\n", 1e-6*(uint64_t)std::chrono::duration_cast<std::chrono::microseconds>(end-start).count());
fprintf(stderr, "|E|=%lu\n", raw_edges_len);
}
const uint64_t threads = omp_get_max_threads();
const uint64_t clients_per_thread = (clients+threads-1)/threads;
auto streams = UCXStream::make_ucx_stream(argv[7], 2333, threads, clients_per_thread);
const uint64_t time_offset_sync_times = 1024;
for(uint64_t i=0;i<time_offset_sync_times;i++)
{
ClientUpdateRequest request = {0, ClientUpdateRequest::Type::End, 0, 0, 0, std::chrono::high_resolution_clock::now()};
ClientUpdateResponse response;
streams[0].send(&request, sizeof(request), 0);
streams[0].recv(&response, sizeof(response), 0);
}
tbb::enumerable_thread_specific<std::vector<uint64_t>> all_latency;
tbb::enumerable_thread_specific<std::vector<uint64_t>> all_event_latency;
std::atomic_uint64_t num_timeouts = 0, num_updates = 0, sum_nanoseconds = 0, sum_event_nanoseconds = 0;
{
auto start = std::chrono::system_clock::now();
#pragma omp parallel
{
uint64_t tid = omp_get_thread_num();
uint64_t client_begin = clients_per_thread*tid;
uint64_t num_clients = std::min(clients_per_thread*(tid+1), clients)-client_begin;
if(client_begin >= clients) num_clients = 0;
uint64_t local_num_timeouts = 0, local_num_updates = 0, local_sum_nanoseconds = 0, local_sum_event_nanoseconds = 0;
uint64_t last_print_updates = 0;
uint64_t running_clients = num_clients;
std::vector<boost::fibers::fiber> fibers;
std::vector<uint64_t> wait_responses(num_clients);
std::vector<std::unique_ptr<boost::fibers::buffered_channel<std::pair<ClientTxnUpdateRequest, std::chrono::high_resolution_clock::time_point>>>> requests;
for(uint64_t fid=client_begin;fid<client_begin+num_clients;fid++)
{
requests.emplace_back(std::make_unique<boost::fibers::buffered_channel<std::pair<ClientTxnUpdateRequest, std::chrono::high_resolution_clock::time_point>>>(2)); //minimal size is 2
fibers.emplace_back([&, fid, lfid=fid-client_begin]()
{
std::pair<ClientTxnUpdateRequest, std::chrono::high_resolution_clock::time_point> channel_pair;
ClientTxnUpdateRequest &request = channel_pair.first;
auto &event_time = channel_pair.second;
uint64_t add = fid, del = fid;
event_time = std::chrono::high_resolution_clock::now();
while(add < add_raw_edges_len || del < del_raw_edges_len)
{
request.client_id = fid;
request.num_updates = 0;
for(bool is_add = true; add < add_raw_edges_len || del < del_raw_edges_len; is_add = !is_add)
{
if(is_add)
{
if(add >= add_raw_edges_len) continue;
const auto &e = add_raw_edges[add];
request.types[request.num_updates] = ClientTxnUpdateRequest::Type::Add;
request.srcs[request.num_updates] = e.first;
request.dsts[request.num_updates] = e.second;
request.datas[request.num_updates] = (e.first+e.second)%128;
add+=clients;
}
else
{
if(del >= del_raw_edges_len) continue;
const auto &e = del_raw_edges[del];
request.types[request.num_updates] = ClientTxnUpdateRequest::Type::Del;
request.srcs[request.num_updates] = e.first;
request.dsts[request.num_updates] = e.second;
request.datas[request.num_updates] = (e.first+e.second)%128;
del+=clients;
}
request.num_updates++;
if(request.num_updates >= updates_per_txn) break;
}
request.request_time = std::chrono::high_resolution_clock::now();
if(queue_depth != (uint32_t)-1 && request.request_time-event_time > queue_depth*std::chrono::microseconds(sleep_time_us))
{
fprintf(stderr, "Queue is full!\n");
throw std::runtime_error("Over Sustainable Throughput!");
}
requests[lfid]->push(channel_pair);
streams[tid].send(&request, sizeof(request), lfid);
wait_responses[lfid]++;
while(wait_responses[lfid]) boost::this_fiber::yield();
event_time += std::chrono::microseconds(sleep_time_us);
boost::this_fiber::sleep_until(event_time);
}
request = {(uint32_t)fid, 1, {ClientTxnUpdateRequest::Type::End}, {0}, {0}, {0}, std::chrono::high_resolution_clock::now()};
requests[lfid]->push(channel_pair);
streams[tid].send(&request, sizeof(request), lfid);
wait_responses[lfid]++;
});
fibers.emplace_back([&, fid, lfid=fid-client_begin]()
{
ClientTxnUpdateResponse response;
while(true)
{
if(wait_responses[lfid])
{
streams[tid].recv(&response, sizeof(response), lfid);
assert(fid == (uint64_t)response.client_id);
auto channel_pair = requests[lfid]->value_pop();
auto &request = channel_pair.first;
auto &event_time = channel_pair.second;
if(request.types[0] == ClientTxnUpdateRequest::Type::End)
{
running_clients --;
break;
}
auto now = std::chrono::high_resolution_clock::now();
if(now-request.request_time > std::chrono::milliseconds(timeout_ms)) local_num_timeouts ++;
uint64_t latency_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(now-request.request_time).count();
all_latency.local().emplace_back(latency_ns);
uint64_t event_latency_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(now-event_time).count();
all_event_latency.local().emplace_back(event_latency_ns);
local_num_updates ++;
local_sum_nanoseconds += latency_ns;
local_sum_event_nanoseconds += event_latency_ns;
wait_responses[lfid]--;
}
boost::this_fiber::yield();
}
});
}
while(num_clients && running_clients)
{
num_timeouts += local_num_timeouts;
num_updates += local_num_updates;
sum_nanoseconds += local_sum_nanoseconds;
sum_event_nanoseconds += local_sum_event_nanoseconds;
local_num_timeouts = 0;
local_num_updates = 0;
local_sum_nanoseconds = 0;
local_sum_event_nanoseconds = 0;
if(tid == 0 && num_updates - last_print_updates > 1000000)
{
fprintf(stderr, "timeouts: %lu/%lu = 1-%lf\n", num_timeouts.load(std::memory_order_relaxed), num_updates.load(std::memory_order_relaxed), 1-(double)num_timeouts.load(std::memory_order_relaxed)/num_updates.load(std::memory_order_relaxed));
last_print_updates = num_updates;
}
boost::this_fiber::yield();
}
for(auto &f : fibers) f.join();
}
auto end = std::chrono::system_clock::now();
fprintf(stderr, "exec: %.6lfs\n", 1e-6*(uint64_t)std::chrono::duration_cast<std::chrono::microseconds>(end-start).count());
fprintf(stderr, "Throughput: %lf\n", num_updates.load(std::memory_order_relaxed)/(1e-9*(end-start).count()));
fprintf(stderr, "Success: %lf\n", 1-(double)num_timeouts.load(std::memory_order_relaxed)/num_updates.load(std::memory_order_relaxed));
fprintf(stderr, "Mean: %lf us\n", (1e-3)*sum_nanoseconds/num_updates.load(std::memory_order_relaxed));
std::vector<uint64_t> latency;
for(auto &p : all_latency)
{
for(auto t : p) latency.emplace_back(t);
p.clear();
}
tbb::parallel_sort(latency.begin(), latency.end());
fprintf(stderr, "P25: %lf us\n", 1e-3*latency[latency.size()*0.25]);
fprintf(stderr, "P50: %lf us\n", 1e-3*latency[latency.size()*0.50]);
fprintf(stderr, "P75: %lf us\n", 1e-3*latency[latency.size()*0.75]);
fprintf(stderr, "P90: %lf us\n", 1e-3*latency[latency.size()*0.90]);
fprintf(stderr, "P99: %lf us\n", 1e-3*latency[latency.size()*0.99]);
fprintf(stderr, "P999: %lf us\n", 1e-3*latency[latency.size()*0.999]);
fprintf(stderr, "P9999: %lf us\n", 1e-3*latency[latency.size()*0.9999]);
fprintf(stderr, "P99999: %lf us\n", 1e-3*latency[latency.size()*0.99999]);
fprintf(stderr, "P999999: %lf us\n", 1e-3*latency[latency.size()*0.999999]);
fprintf(stderr, "P9999999: %lf us\n", 1e-3*latency[latency.size()*0.9999999]);
fprintf(stderr, "P99999999: %lf us\n", 1e-3*latency[latency.size()*0.99999999]);
fprintf(stderr, "Max: %lf us\n", 1e-3*latency[latency.size()-1]);
fprintf(stderr, "Event Mean: %lf us\n", (1e-3)*sum_event_nanoseconds/num_updates.load(std::memory_order_relaxed));
latency.clear();
for(auto &p : all_event_latency)
{
for(auto t : p) latency.emplace_back(t);
p.clear();
}
tbb::parallel_sort(latency.begin(), latency.end());
fprintf(stderr, "Event P25: %lf us\n", 1e-3*latency[latency.size()*0.25]);
fprintf(stderr, "Event P50: %lf us\n", 1e-3*latency[latency.size()*0.50]);
fprintf(stderr, "Event P75: %lf us\n", 1e-3*latency[latency.size()*0.75]);
fprintf(stderr, "Event P90: %lf us\n", 1e-3*latency[latency.size()*0.90]);
fprintf(stderr, "Event P99: %lf us\n", 1e-3*latency[latency.size()*0.99]);
fprintf(stderr, "Event P999: %lf us\n", 1e-3*latency[latency.size()*0.999]);
fprintf(stderr, "Event P9999: %lf us\n", 1e-3*latency[latency.size()*0.9999]);
fprintf(stderr, "Event P99999: %lf us\n", 1e-3*latency[latency.size()*0.99999]);
fprintf(stderr, "Event P999999: %lf us\n", 1e-3*latency[latency.size()*0.999999]);
fprintf(stderr, "Event P9999999: %lf us\n", 1e-3*latency[latency.size()*0.9999999]);
fprintf(stderr, "Event P99999999: %lf us\n", 1e-3*latency[latency.size()*0.99999999]);
fprintf(stderr, "Event Max: %lf us\n", 1e-3*latency[latency.size()-1]);
}
return 0;
}
| 52.793358 | 258 | 0.56364 | [
"vector"
] |
31d64324c216f5cb42b4b96eb1ebb7549bd20412 | 1,599 | cpp | C++ | src/guide/screenembeded.cpp | rzvdaniel/GUI- | 1501b54a038f7e3f66d683f125fa53d3ab73672c | [
"MIT"
] | 2 | 2017-06-16T19:27:55.000Z | 2020-04-05T02:18:07.000Z | src/guide/screenembeded.cpp | rzvdaniel/GUI- | 1501b54a038f7e3f66d683f125fa53d3ab73672c | [
"MIT"
] | null | null | null | src/guide/screenembeded.cpp | rzvdaniel/GUI- | 1501b54a038f7e3f66d683f125fa53d3ab73672c | [
"MIT"
] | 2 | 2019-09-03T19:23:20.000Z | 2020-08-29T21:46:17.000Z | #define N_IMPLEMENTS TScreenEmbeded
//-------------------------------------------------------------------
// screenembeded.cpp
// (C) 2003 R.Predescu
//-------------------------------------------------------------------
#include "guide/screenembeded.h"
#include "guide/skin.h"
#include "guide/debug.h"
//-------------------------------------------------------------------
// TScreenEmbeded()
// 01-Aug-2003 rzv created
//-------------------------------------------------------------------
TScreenEmbeded::TScreenEmbeded()
{
}
//-------------------------------------------------------------------
// ~TScreenEmbeded()
// 01-Aug-2003 rzv created
//-------------------------------------------------------------------
TScreenEmbeded::~TScreenEmbeded()
{
}
//-------------------------------------------------------------------
// Create()
// 01-Aug-2003 rzv created
//-------------------------------------------------------------------
bool TScreenEmbeded::Create(const TRect& Rect, const char* SkinFile)
{
TScreen::Create(Rect);
// Load the skin
if(!LoadSkin(SkinFile))
return false;
return true;
}
//-------------------------------------------------------------------
// Render()
// 04-Jan-2003 rzv created
//-------------------------------------------------------------------
void TScreenEmbeded::Render(void)
{
GetGfxServer()->BeginScene();
// Paint everything
CMPaint();
GetGfxServer()->EndScene();
}
//-------------------------------------------------------------------
// EOF
//-------------------------------------------------------------------
| 27.568966 | 69 | 0.3202 | [
"render"
] |
31d6cf5a2586b140a5a6b08fbb8d0155f1f70def | 3,539 | cpp | C++ | src/vcfaddinfo.cpp | timmassingham/vcflib | e0cb656cb0e224dc078ba1e06079a88a5ea7b6ab | [
"MIT"
] | 379 | 2016-01-29T00:01:51.000Z | 2022-03-21T21:07:03.000Z | src/vcfaddinfo.cpp | timmassingham/vcflib | e0cb656cb0e224dc078ba1e06079a88a5ea7b6ab | [
"MIT"
] | 245 | 2016-01-31T19:05:29.000Z | 2022-03-31T13:17:17.000Z | src/vcfaddinfo.cpp | timmassingham/vcflib | e0cb656cb0e224dc078ba1e06079a88a5ea7b6ab | [
"MIT"
] | 168 | 2016-02-11T19:30:52.000Z | 2022-02-10T09:20:34.000Z | /*
vcflib C++ library for parsing and manipulating VCF files
Copyright © 2010-2020 Erik Garrison
Copyright © 2020 Pjotr Prins
This software is published under the MIT License. See the LICENSE file.
*/
#include "Variant.h"
#include "split.h"
#include <string>
#include <iostream>
#include <set>
using namespace std;
using namespace vcflib;
// adds non-overlapping info fields from varB to varA
void addInfo(Variant& varA, Variant& varB) {
for (map<string, vector<string> >::iterator i = varB.info.begin(); i != varB.info.end(); ++i) {
if (varA.info.find(i->first) == varA.info.end()) {
varA.info[i->first] = i->second;
}
}
}
int main(int argc, char** argv) {
if (argc != 3) {
cerr << "usage: " << argv[0] << " <vcf file> <vcf file>" << endl << endl
<< "Adds info fields from the second file which are not present in the first vcf file." << endl;
cerr << endl << "Type: transformation" << endl << endl;
return 1;
}
string filenameA = argv[1];
string filenameB = argv[2];
if (filenameA == filenameB) {
cerr << "it won't help to add info data from the same file!" << endl;
return 1;
}
VariantCallFile variantFileA;
if (filenameA == "-") {
variantFileA.open(std::cin);
} else {
variantFileA.open(filenameA);
}
VariantCallFile variantFileB;
if (filenameB == "-") {
variantFileB.open(std::cin);
} else {
variantFileB.open(filenameB);
}
if (!variantFileA.is_open() || !variantFileB.is_open()) {
return 1;
}
Variant varA(variantFileA);
Variant varB(variantFileB);
// while the first file doesn't match the second positionally,
// step forward, annotating each genotype record with an empty genotype
// when the two match, iterate through the genotypes from the first file
// and get the genotypes reported in the second file
variantFileA.getNextVariant(varA);
variantFileB.getNextVariant(varB);
variantFileA.header = unionInfoHeaderLines(variantFileA.header, variantFileB.header);
cout << variantFileA.header << endl;
do {
while (!variantFileB.done()
&& (varB.sequenceName < varA.sequenceName
|| (varB.sequenceName == varA.sequenceName && varB.position < varA.position))
) {
variantFileB.getNextVariant(varB);
}
while (!variantFileA.done()
&& (varA.sequenceName < varB.sequenceName
|| (varA.sequenceName == varB.sequenceName && varA.position < varB.position))
) {
cout << varA << endl;
variantFileA.getNextVariant(varA);
}
while (!variantFileB.done()
&& (varB.sequenceName < varA.sequenceName
|| (varB.sequenceName == varA.sequenceName && varB.position < varA.position))
) {
variantFileB.getNextVariant(varB);
}
while (!variantFileA.done() && varA.sequenceName == varB.sequenceName && varA.position == varB.position) {
addInfo(varA, varB);
cout << varA << endl;
variantFileA.getNextVariant(varA);
variantFileB.getNextVariant(varB);
}
} while (!variantFileA.done() && !variantFileB.done());
if (!variantFileA.done()) {
cout << varA << endl;
while (variantFileA.getNextVariant(varA)) {
cout << varA << endl;
}
}
return 0;
}
| 29.247934 | 114 | 0.589715 | [
"vector"
] |
31f90081583afe036ac3f2b2e1b6deb8f0557f79 | 3,654 | cpp | C++ | src/services/pcn-dynmon/src/serializer/MetricConfigJsonObject.cpp | stefalbi/polycube | f7b65ece48505458796cb4969d41677e991fbdc8 | [
"ECL-2.0",
"Apache-2.0"
] | 337 | 2018-12-12T11:50:15.000Z | 2022-03-15T00:24:35.000Z | src/services/pcn-dynmon/src/serializer/MetricConfigJsonObject.cpp | l1b0k/polycube | 7af919245c131fa9fe24c5d39d10039cbb81e825 | [
"ECL-2.0",
"Apache-2.0"
] | 253 | 2018-12-17T21:36:15.000Z | 2022-01-17T09:30:42.000Z | src/services/pcn-dynmon/src/serializer/MetricConfigJsonObject.cpp | l1b0k/polycube | 7af919245c131fa9fe24c5d39d10039cbb81e825 | [
"ECL-2.0",
"Apache-2.0"
] | 90 | 2018-12-19T15:49:38.000Z | 2022-03-27T03:56:07.000Z | #include "MetricConfigJsonObject.h"
#include <regex>
namespace polycube {
namespace service {
namespace model {
MetricConfigJsonObject::MetricConfigJsonObject() {
m_nameIsSet = false;
m_mapNameIsSet = false;
m_extractionOptionsIsSet = false;
m_openMetricsMetadataIsSet = false;
}
MetricConfigJsonObject::MetricConfigJsonObject(const nlohmann::json &val) : JsonObjectBase(val) {
m_nameIsSet = false;
m_mapNameIsSet = false;
m_extractionOptionsIsSet = false;
m_openMetricsMetadataIsSet = false;
if (val.count("name"))
setName(val.at("name").get<std::string>());
if (val.count("map-name"))
setMapName(val.at("map-name").get<std::string>());
if (val.count("extraction-options"))
if (!val["extraction-options"].is_null()) {
ExtractionOptionsJsonObject newItem{val["extraction-options"]};
setExtractionOptions(newItem);
}
if (val.count("open-metrics-metadata"))
if (!val["open-metrics-metadata"].is_null()) {
OpenMetricsMetadataJsonObject newItem{val["open-metrics-metadata"]};
setOpenMetricsMetadata(newItem);
}
}
nlohmann::json MetricConfigJsonObject::toJson() const {
nlohmann::json val = nlohmann::json::object();
if (!getBase().is_null())
val.update(getBase());
if (m_nameIsSet)
val["name"] = m_name;
if (m_mapNameIsSet)
val["map-name"] = m_mapName;
if (m_extractionOptionsIsSet)
val["extraction-options"] = JsonObjectBase::toJson(m_extractionOptions);
if (m_openMetricsMetadataIsSet)
val["open-metrics-metadata"] = JsonObjectBase::toJson(m_openMetricsMetadata);
return val;
}
std::string MetricConfigJsonObject::getName() const {
return m_name;
}
void MetricConfigJsonObject::setName(std::string value) {
m_name = value;
m_nameIsSet = true;
}
bool MetricConfigJsonObject::nameIsSet() const {
return m_nameIsSet;
}
std::string MetricConfigJsonObject::getMapName() const {
return m_mapName;
}
void MetricConfigJsonObject::setMapName(std::string value) {
m_mapName = value;
m_mapNameIsSet = true;
}
bool MetricConfigJsonObject::mapNameIsSet() const {
return m_mapNameIsSet;
}
ExtractionOptionsJsonObject MetricConfigJsonObject::getExtractionOptions() const {
return m_extractionOptions;
}
void MetricConfigJsonObject::setExtractionOptions(ExtractionOptionsJsonObject value) {
m_extractionOptions = value;
m_extractionOptionsIsSet = true;
}
bool MetricConfigJsonObject::extractionOptionsIsSet() const {
return m_extractionOptionsIsSet;
}
void MetricConfigJsonObject::unsetExtractionOptions() {
m_extractionOptionsIsSet = false;
}
OpenMetricsMetadataJsonObject MetricConfigJsonObject::getOpenMetricsMetadata() const {
return m_openMetricsMetadata;
}
void MetricConfigJsonObject::setOpenMetricsMetadata(OpenMetricsMetadataJsonObject value) {
m_openMetricsMetadata = value;
m_openMetricsMetadataIsSet = true;
}
bool MetricConfigJsonObject::openMetricsMetadataIsSet() const {
return m_openMetricsMetadataIsSet;
}
void MetricConfigJsonObject::unsetOpenMetricsMetadata() {
m_openMetricsMetadataIsSet = false;
}
}// namespace model
}// namespace service
}// namespace polycube
| 32.336283 | 103 | 0.649973 | [
"object",
"model"
] |
31fc46e1e32370a62d03c520acb80e9c6a40f061 | 844 | cpp | C++ | leetcode/arrays101/Merge-Sorted-Array.cpp | leohr/competitive-programming | f97488e0cb777c1df78257ce2644ac4ff8191267 | [
"MIT"
] | 1 | 2020-10-08T19:28:40.000Z | 2020-10-08T19:28:40.000Z | leetcode/arrays101/Merge-Sorted-Array.cpp | leohr/competitive-programming | f97488e0cb777c1df78257ce2644ac4ff8191267 | [
"MIT"
] | null | null | null | leetcode/arrays101/Merge-Sorted-Array.cpp | leohr/competitive-programming | f97488e0cb777c1df78257ce2644ac4ff8191267 | [
"MIT"
] | 1 | 2020-10-24T02:32:27.000Z | 2020-10-24T02:32:27.000Z | class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
if (m == 0) {
nums1 = nums2;
return;
}
if (n == 0) {
return;
}
vector<int> nums;
int i = 0, j = 0;
while (i + j < n + m) {
if (i == m) {
nums.push_back(nums2[j]);
++j;
}
else if (j == n) {
nums.push_back(nums1[i]);
++i;
}
else if (nums1[i] < nums2[j]) {
nums.push_back(nums1[i]);
++i;
} else {
nums.push_back(nums2[j]);
++j;
}
}
for (int i = 0; i < n + m; ++i) {
nums1[i] = nums[i];
}
}
}; | 24.823529 | 70 | 0.308057 | [
"vector"
] |
ee038bdc8d91b410e3ebb4b341058969fc1d84cc | 4,141 | cpp | C++ | android-30/android/net/wifi/ScanResult.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-30/android/net/wifi/ScanResult.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/net/wifi/ScanResult.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../os/Parcel.hpp"
#include "../../../JString.hpp"
#include "../../../JString.hpp"
#include "./ScanResult.hpp"
namespace android::net::wifi
{
// Fields
JString ScanResult::BSSID()
{
return getObjectField(
"BSSID",
"Ljava/lang/String;"
);
}
jint ScanResult::CHANNEL_WIDTH_160MHZ()
{
return getStaticField<jint>(
"android.net.wifi.ScanResult",
"CHANNEL_WIDTH_160MHZ"
);
}
jint ScanResult::CHANNEL_WIDTH_20MHZ()
{
return getStaticField<jint>(
"android.net.wifi.ScanResult",
"CHANNEL_WIDTH_20MHZ"
);
}
jint ScanResult::CHANNEL_WIDTH_40MHZ()
{
return getStaticField<jint>(
"android.net.wifi.ScanResult",
"CHANNEL_WIDTH_40MHZ"
);
}
jint ScanResult::CHANNEL_WIDTH_80MHZ()
{
return getStaticField<jint>(
"android.net.wifi.ScanResult",
"CHANNEL_WIDTH_80MHZ"
);
}
jint ScanResult::CHANNEL_WIDTH_80MHZ_PLUS_MHZ()
{
return getStaticField<jint>(
"android.net.wifi.ScanResult",
"CHANNEL_WIDTH_80MHZ_PLUS_MHZ"
);
}
JObject ScanResult::CREATOR()
{
return getStaticObjectField(
"android.net.wifi.ScanResult",
"CREATOR",
"Landroid/os/Parcelable$Creator;"
);
}
JString ScanResult::SSID()
{
return getObjectField(
"SSID",
"Ljava/lang/String;"
);
}
jint ScanResult::WIFI_STANDARD_11AC()
{
return getStaticField<jint>(
"android.net.wifi.ScanResult",
"WIFI_STANDARD_11AC"
);
}
jint ScanResult::WIFI_STANDARD_11AX()
{
return getStaticField<jint>(
"android.net.wifi.ScanResult",
"WIFI_STANDARD_11AX"
);
}
jint ScanResult::WIFI_STANDARD_11N()
{
return getStaticField<jint>(
"android.net.wifi.ScanResult",
"WIFI_STANDARD_11N"
);
}
jint ScanResult::WIFI_STANDARD_LEGACY()
{
return getStaticField<jint>(
"android.net.wifi.ScanResult",
"WIFI_STANDARD_LEGACY"
);
}
jint ScanResult::WIFI_STANDARD_UNKNOWN()
{
return getStaticField<jint>(
"android.net.wifi.ScanResult",
"WIFI_STANDARD_UNKNOWN"
);
}
JString ScanResult::capabilities()
{
return getObjectField(
"capabilities",
"Ljava/lang/String;"
);
}
jint ScanResult::centerFreq0()
{
return getField<jint>(
"centerFreq0"
);
}
jint ScanResult::centerFreq1()
{
return getField<jint>(
"centerFreq1"
);
}
jint ScanResult::channelWidth()
{
return getField<jint>(
"channelWidth"
);
}
jint ScanResult::frequency()
{
return getField<jint>(
"frequency"
);
}
jint ScanResult::level()
{
return getField<jint>(
"level"
);
}
JString ScanResult::operatorFriendlyName()
{
return getObjectField(
"operatorFriendlyName",
"Ljava/lang/CharSequence;"
);
}
jlong ScanResult::timestamp()
{
return getField<jlong>(
"timestamp"
);
}
JString ScanResult::venueName()
{
return getObjectField(
"venueName",
"Ljava/lang/CharSequence;"
);
}
// QJniObject forward
ScanResult::ScanResult(QJniObject obj) : JObject(obj) {}
// Constructors
ScanResult::ScanResult()
: JObject(
"android.net.wifi.ScanResult",
"()V"
) {}
ScanResult::ScanResult(android::net::wifi::ScanResult &arg0)
: JObject(
"android.net.wifi.ScanResult",
"(Landroid/net/wifi/ScanResult;)V",
arg0.object()
) {}
// Methods
jint ScanResult::describeContents() const
{
return callMethod<jint>(
"describeContents",
"()I"
);
}
JObject ScanResult::getInformationElements() const
{
return callObjectMethod(
"getInformationElements",
"()Ljava/util/List;"
);
}
jint ScanResult::getWifiStandard() const
{
return callMethod<jint>(
"getWifiStandard",
"()I"
);
}
jboolean ScanResult::is80211mcResponder() const
{
return callMethod<jboolean>(
"is80211mcResponder",
"()Z"
);
}
jboolean ScanResult::isPasspointNetwork() const
{
return callMethod<jboolean>(
"isPasspointNetwork",
"()Z"
);
}
JString ScanResult::toString() const
{
return callObjectMethod(
"toString",
"()Ljava/lang/String;"
);
}
void ScanResult::writeToParcel(android::os::Parcel arg0, jint arg1) const
{
callMethod<void>(
"writeToParcel",
"(Landroid/os/Parcel;I)V",
arg0.object(),
arg1
);
}
} // namespace android::net::wifi
| 18.082969 | 74 | 0.671335 | [
"object"
] |
ee0558634bd6e89f5799e1991a0866b65e9f01df | 9,811 | cc | C++ | src/Population.cc | evolbio/design2 | 7f1856e682382e91e56569de2a6d64a61cc424cc | [
"CC-BY-4.0"
] | null | null | null | src/Population.cc | evolbio/design2 | 7f1856e682382e91e56569de2a6d64a61cc424cc | [
"CC-BY-4.0"
] | null | null | null | src/Population.cc | evolbio/design2 | 7f1856e682382e91e56569de2a6d64a61cc424cc | [
"CC-BY-4.0"
] | null | null | null | #include <cmath>
#include "Population.h"
#include "util.h"
Population::Population(Param& param)
{
static bool flag = true;
std::string showRec;
popSize = param.popsize;
ind = std::vector<Individual>(popSize);
indFitness = std::vector<double>(popSize);
hvec = std::vector<uint64_t>(popSize);
avec = std::vector<uint32_t>(popSize);
Individual::setParam(param); // static function to set static variables
for (int i = 0; i < popSize; i++){
ind[i].initialize();
indFitness[i] = ind[i].getFitness();
}
auto rec = param.recombination;
double logRec = -log2(rec);
ulong logRecRound = round<ulong>(logRec);
if (rec < 1e-7){
SetBaby = SetBabyGenotypeNoRec;
showRec = "Rec: no recombination\n";
param.rec = "None";
}
else if (abs(logRec - logRecRound) < 1e-2){
SetBaby = SetBabyGenotypeLogRec;
ind[0].setNegLog2Rec(logRecRound);
showRec = fmt::format("Rec: using Log = {} -> {}\n", logRec,logRecRound);
param.rec = fmt::format("Log {}", logRecRound);
}
else{
SetBaby = SetBabyGenotype;
showRec = fmt::format("Rec: using Uniform, Log = {}\n", logRec);
param.rec = "Uniform";
}
if (flag && showProgress){
flag=false;
std::cout << showRec;
}
}
void Population::setFitnessArray()
{
for (int i = 0; i < popSize; ++i){
indFitness[i] = ind[i].getFitness();
}
}
// Do everything on population in one loop
void Population::reproduceMutateCalcFit(Population& oldPop)
{
oldPop.createAliasTable();
for (int i = 0; i < popSize; ++i){
SetBaby(oldPop.chooseInd(), oldPop.chooseInd(), ind[i]);
ind[i].mutate();
indFitness[i] = ind[i].getFitness();
}
}
// Round of reproduction without mutation or recombination, useful for testing models in which final population for stats is a population formed after selection but before recombination or mutation
void Population::reproduceNoMutRec(Population& oldPop)
{
auto r = ind[0].getRecombination();
oldPop.createAliasTable();
for (int i = 0; i < popSize; ++i){
SetBaby(oldPop.chooseInd(), oldPop.chooseInd(), ind[i]);
indFitness[i] = ind[i].getFitness();
}
ind[0].setRecombination(r);
}
// If using stochastic loci for phenotypic variability, then simply double number of loci for allocation of vectors and matrix, and use 1..L for genotype and L+1,...,2L for stochastic alleles
void Population::calcStats(Param& param, SumStat& stats)
{
int i, j;
int loci = param.loci;
std::vector<std::vector<double>> gMatrix(loci,std::vector<double>(param.popsize));
std::vector<std::vector<double>> sMatrix;
if (param.stoch) sMatrix = std::vector<std::vector<double>>(loci,std::vector<double>(param.popsize));
for (i = 0; i < popSize; ++i){
auto& genotype = ind[i].getGenotype();
auto& stochast = ind[i].getStochast();
for (j = 0; j < loci; ++j){
gMatrix[j][i] = genotype[j];
if (param.stoch) sMatrix[j][i] = stochast[j];
}
}
auto& gMean = stats.getGMean();
auto& gSD = stats.getGSD();
auto& gCorr = stats.getGCorr();
auto& sMean = stats.getSMean();
auto& sSD = stats.getSSD();
auto& sCorr = stats.getSCorr();
auto& sgCorr = stats.getSGCorr();
for (i = 0; i < loci; ++i){
gMean[i] = vecMean<double>(gMatrix[i]);
gSD[i] = vecSD<double>(gMatrix[i], gMean[i]);
if (param.stoch){
sMean[i] = vecMean<double>(sMatrix[i]);
sSD[i] = vecSD<double>(sMatrix[i], sMean[i]);
}
}
for (i = 0; i < loci; ++i){
for (j = i; j < loci; ++j){
// corr of g loci
double cov = vecCov(gMatrix[i], gMatrix[j], gMean[i], gMean[j]);
double prodSD = gSD[i]*gSD[j];
gCorr[i][j] = gCorr[j][i] = (prodSD < 1e-10) ? 0.0 : cov/(prodSD);
if (param.stoch){
// corr of s loci
double covS = vecCov(sMatrix[i], sMatrix[j], sMean[i], sMean[j]);
double prodSDS = sSD[i]*sSD[j];
sCorr[i][j] = sCorr[j][i] = (prodSDS < 1e-10) ? 0.0 : covS/(prodSDS);
// cross corr of s[i] and g[j]
double covSG = vecCov(gMatrix[j], sMatrix[i], gMean[j], sMean[i]);
double prodSDSG = gSD[j]*sSD[i];
sgCorr[i][j] = (prodSDSG < 1e-10) ? 0.0 : covSG/(prodSDSG);
// cross corr of s[j] and g[i]
covSG = vecCov(gMatrix[i], sMatrix[j], gMean[i], sMean[j]);
prodSDSG = gSD[i]*sSD[j];
sgCorr[j][i] = (prodSDSG < 1e-10) ? 0.0 : covSG/(prodSDSG);
}
}
}
// distn of allelic values
std::vector<unsigned> ptiles(param.distnSteps);
std::iota(ptiles.begin(), ptiles.end(), 0); // assign [0..n-1] for distnSteps = n, use n = 101
auto& gDistn = stats.getGDistn();
auto& sDistn = stats.getSDistn();
for (i = 0; i < loci; ++i){
gDistn[i] = percentiles_interpol<std::vector<double>>(gMatrix[i], ptiles);
if (param.stoch) sDistn[i] = percentiles_interpol<std::vector<double>>(sMatrix[i], ptiles);
}
// fitness distn
double mean = vecMean<double>(indFitness);
stats.setAveFitness(mean);
stats.setSDFitness(vecSD<double>(indFitness, mean));
auto& fitnessDistn = stats.getFitnessDistn();
fitnessDistn = percentiles_interpol<std::vector<double>>(indFitness, ptiles);
// perf distn
std::vector<double> indPerf(popSize);
for (i = 0; i < popSize; ++i){
indPerf[i] = ind[i].calcJ();
}
double pmean = vecMean<double>(indPerf);
stats.setAvePerf(pmean);
stats.setSDPerf(vecSD<double>(indPerf, pmean));
auto& perfDistn = stats.getPerfDistn();
perfDistn = percentiles_interpol<std::vector<double>>(indPerf, ptiles);
// fitness repeatability of low-performing individuals
double fitnessThreshold = 0.9; // count individuals w/fitness <= cutoff
stats.setLowFitCutoff(fitnessThreshold);
int repeat = 100; // replicate calcFitness() for each individual in set
fullSortInd(); // sort full population
i = 0;
while((ind[i++].getFitness() <= fitnessThreshold) && (i < popSize));
if (i == 1){
stats.setLowFitPtile(0);
stats.setLowFitRepeat(0);
}
else if (i == popSize){
stats.setLowFitPtile(100);
stats.setLowFitRepeat(1);
}
else{
int thresholdIndex = i - 1;
double samples = thresholdIndex * repeat;
int numBelowThreshold = 0;
for (i = 0; i < thresholdIndex; ++i){
for (j = 0; j < repeat; ++j){
if (ind[i].calcFitness() < fitnessThreshold) ++numBelowThreshold;
}
}
stats.setLowFitPtile((100.0*thresholdIndex)/static_cast<double>(popSize));
stats.setLowFitRepeat(static_cast<double>(numBelowThreshold)/samples);
}
}
// Alias method for sampling from discrete distribution, see https://pandasthumb.org/archives/2012/08/lab-notes-the-a.html and https://en.wikipedia.org/wiki/Alias_method and http://www.keithschwarz.com/darts-dice-coins/
// Example code for testing in ~/sim/02_SmallTests/aliasMethod.cc
uint32_t Population::getRandIndex(){
uint64_t u = rnd.rawint();
uint32_t x = u % popSize;
return (u < hvec[x]) ? x : avec[x];
}
void Population::createAliasTable() {
const double *pp = indFitness.data();
uint64_t *h = hvec.data();
std::uint32_t *a = avec.data();
uint32_t n = popSize;
// normalize pp and copy into buffer
double f = 0.0;
std::vector<double> p(n);
for (uint32_t i = 0; i < n; ++i)
f += pp[i];
f = static_cast<double>(n) / f;
for (uint32_t i = 0; i < n; ++i)
p[i] = pp[i] * f;
// find starting positions, g => less than target, m greater than target
uint32_t g, m, mm;
for (g = 0; g < n && p[g] < 1.0; ++g)
/*noop*/;
for (m = 0; m < n && p[m] >= 1.0; ++m)
/*noop*/;
mm = m + 1;
// build alias table until we run out of large or small bars
while (g < n && m < n) {
// convert double to 64-bit integer, control for precision
// 9007... is max integer in double format w/53 bits, then shift by 11
h[m] = (static_cast<uint64_t>(ceil(p[m] * 9007199254740992.0)) << 11);
a[m] = g;
p[g] = (p[g] + p[m]) - 1.0;
if (p[g] >= 1.0 || mm <= g) {
for (m = mm; m < n && p[m] >= 1.0; ++m)
/*noop*/;
mm = m + 1;
} else
m = g;
for (; g < n && p[g] < 1.0; ++g)
/*noop*/;
}
// any bars that remain have no alias
for (; g < n; ++g) {
if (p[g] < 1.0)
continue;
h[g] = std::numeric_limits<uint64_t>::max();
a[g] = g;
}
if (m < n) {
h[m] = std::numeric_limits<uint64_t>::max();
a[m] = m;
for (m = mm; m < n; ++m) {
if (p[m] > 1.0)
continue;
h[m] = std::numeric_limits<uint64_t>::max();
a[m] = m;
}
}
}
// Sort individuals by fitness, sorting only lower end of fitness distribution. Used for working with set of lowest fitness individuals to test for "heritability" of disease.
void Population::partialSortInd(unsigned long sortToIndex){
std::partial_sort(ind.begin(), ind.begin() + sortToIndex, ind.end(),
[&](Individual& a, Individual& b){return a.getFitness() < b.getFitness();});
}
// Sort individuals by fitness
void Population::fullSortInd(){
std::sort(ind.begin(), ind.end(), [&](Individual& a, Individual& b){return a.getFitness() < b.getFitness();});
}
| 35.418773 | 219 | 0.568851 | [
"vector"
] |
ee0d17332c45d4118c37e69c185e0c052e2a03c1 | 411 | cpp | C++ | HackerRank-C++/HackerRank/HackerRank/BirthdayChocolate.cpp | domEnriquez/Algorithms | ec156f04f83463bcb320f55dc7234b558454c418 | [
"MIT"
] | null | null | null | HackerRank-C++/HackerRank/HackerRank/BirthdayChocolate.cpp | domEnriquez/Algorithms | ec156f04f83463bcb320f55dc7234b558454c418 | [
"MIT"
] | null | null | null | HackerRank-C++/HackerRank/HackerRank/BirthdayChocolate.cpp | domEnriquez/Algorithms | ec156f04f83463bcb320f55dc7234b558454c418 | [
"MIT"
] | null | null | null | #include "BirthdayChocolate.h"
using namespace HackerRank;
int BirthdayChocolate::CountPossiblePartitions(vector<int> s, int day, int month)
{
int barSize = s.size();
if (barSize < month)
return 0;
int count = 0;
for (int i = 0; i < barSize; i++) {
int sum = 0;
for (int j = i; j <= month - 1 + i && j < barSize; j++) {
sum += s[j];
}
if (sum == day)
count++;
}
return count;
}
| 15.222222 | 81 | 0.581509 | [
"vector"
] |
ee1a38ccfe23eb020ac6439761b7060d6b7fa263 | 7,551 | cpp | C++ | dod/DLLMain.cpp | matej0/source-engine-internals | c2d2014245e1ea901854280bf5f0b30f3c5aaa95 | [
"MIT"
] | 1 | 2021-11-14T17:29:05.000Z | 2021-11-14T17:29:05.000Z | dod/DLLMain.cpp | matej0/source-engine-internals | c2d2014245e1ea901854280bf5f0b30f3c5aaa95 | [
"MIT"
] | null | null | null | dod/DLLMain.cpp | matej0/source-engine-internals | c2d2014245e1ea901854280bf5f0b30f3c5aaa95 | [
"MIT"
] | 5 | 2021-09-18T01:13:24.000Z | 2021-12-18T22:20:53.000Z | #include "SDK.h"
#include "Client.h"
#include "Panels.h"
//doubt this will ever see the light of day ( unknowncheats ).
unsigned int Get(void* class_, unsigned int index) { return (unsigned int)(*(int**)class_)[index]; }
COffsets gOffsets;
CPlayerVariables gPlayerVars;
CInterfaces gInts;
CFriends gFriends;
CConvars gConvars;
CreateMoveFn bReturn = nullptr;
PanelsFn oPanel = nullptr;
FrameStageFn oFrameStage = nullptr;
OverrideViewFn oView = nullptr;
RunCommandFn oRunCommand = nullptr;
DrawModelExecuteFn oDrawModel = nullptr;
EnableWorldFogFn oWorldFog = nullptr;
ShouldDrawFogFn oFog = nullptr;
LevelInitPreEntity oLevelInit = nullptr;
LevelInitPostEntity oLevelPost = nullptr;
CreateInterface_t EngineFactory = NULL;
CreateInterface_t ClientFactory = NULL;
CreateInterface_t VGUIFactory = NULL;
CreateInterface_t VGUI2Factory = NULL;
CreateInterfaceFn MaterialSystemFactory = NULL;
CreateInterface_t CvarFactory = NULL;
//nanohack O.o
DECLVHOOK(void, SetViewAngles, (Vector &a))
{
if (gPlayerVars.bNoRecoil)
{
if (get_SI<CBaseEntity*>() == GetBaseEntity(me))
return;
}
oSetViewAngles(a);
}
DWORD WINAPI dwMainThread(HMODULE hInstance, LPVOID lpArguments )
{
if (gInts.Client == NULL) //Prevent repeat callings.
{
ClientFactory = ( CreateInterfaceFn ) GetProcAddress( gSignatures.GetModuleHandleSafe( "client.dll" ), "CreateInterface" );
gInts.Client = ( CHLClient* )ClientFactory( "VClient017", NULL);
gInts.EntList = ( CEntList* ) ClientFactory( "VClientEntityList003", NULL );
EngineFactory = ( CreateInterfaceFn ) GetProcAddress( gSignatures.GetModuleHandleSafe( "engine.dll" ), "CreateInterface" );
gInts.Engine = ( EngineClient* ) EngineFactory( "VEngineClient013", NULL );
VGUIFactory = ( CreateInterfaceFn ) GetProcAddress( gSignatures.GetModuleHandleSafe( "vguimatsurface.dll" ), "CreateInterface" );
gInts.Surface = ( ISurface* ) VGUIFactory( "VGUI_Surface030", NULL );
VGUI2Factory = (CreateInterfaceFn)GetProcAddress(gSignatures.GetModuleHandleSafe("vgui2.dll"), "CreateInterface");
gInts.Prediction = (CPrediction *)(ClientFactory("VClientPrediction001", NULL));
gInts.Panels = (IPanel*)VGUI2Factory("VGUI_Panel009", NULL);
gInts.DebugOverlay = (CDebugOverlay*)(EngineFactory("VDebugOverlay003", NULL));
gInts.Globals = *reinterpret_cast<CGlobals**>(gSignatures.GetEngineSignature("A1 ? ? ? ? 8B 11 68") + 8);
gInts.ModelInfo = (IVModelInfo*)EngineFactory("VModelInfoClient006", NULL);
MaterialSystemFactory = (CreateInterfaceFn)GetProcAddress(GetModuleHandleA("MaterialSystem.dll"), "CreateInterface");
gInts.MaterialSystem = (IMaterialSystem*)MaterialSystemFactory("VMaterialSystem080", NULL);
gInts.ModelRender = (IVModelRender*)EngineFactory("VEngineModel016", NULL);
CvarFactory = (CreateInterfaceFn)GetProcAddress(gSignatures.GetModuleHandleSafe("vstdlib.dll"), "CreateInterface");
gInts.Cvar = (ICvar*)CvarFactory("VEngineCvar004", NULL);
gInts.EngineTrace = (IEngineTrace*)EngineFactory("EngineTraceClient003", NULL);
gInts.RenderView = (IRenderView*)EngineFactory("VEngineRenderView014", NULL);
gPlayerVars.dwFogReturnAddress = gSignatures.GetClientSignature("8B 0D ? ? ? ? 8B 01 8B 40 3C FF D0 84 C0 74 16") + 0xD;
//grab clientmode.
uint32_t* pClientVFTable = *(uint32_t**)gInts.Client;
gInts.ClientMode = **(ClientModeShared***)(pClientVFTable[10] + 0x5);
//initialize netvars.
gNetvars = std::make_unique<NetvarTree>();
//initialize cvars.
gConvars.cl_interp = gInts.Cvar->FindVar("cl_interp");
gConvars.cl_interp_ratio = gInts.Cvar->FindVar("cl_interp_ratio");
gConvars.cl_updaterate = gInts.Cvar->FindVar("cl_updaterate");
gConvars.cl_cmdrate = gInts.Cvar->FindVar("cl_cmdrate");
gConvars.sv_showimpacts = gInts.Cvar->FindVar("sv_showimpacts");
gConvars.r_viewmodelfov = gInts.Cvar->FindVar("r_viewmodelfov");
//RemoveCommandLimitations();
//get targets.
PVOID pPaintTraverseTarget = reinterpret_cast<PVOID>(Get(gInts.Panels, 41));
PVOID pLevelInitTarget = reinterpret_cast<PVOID>(Get(gInts.Client, 5));
PVOID pLevelPostTarget = reinterpret_cast<PVOID>(Get(gInts.Client, 6));
PVOID pFrameStageTarget = reinterpret_cast<PVOID>(Get(gInts.Client, 35));
PVOID pSetViewAnglesTarget = reinterpret_cast<PVOID>(Get(gInts.Engine, 20));
PVOID pModelRenderTarget = reinterpret_cast<PVOID>(Get(gInts.ModelRender, 19));
PVOID pShouldDrawFogTarget = reinterpret_cast<PVOID>(Get(gInts.ClientMode, 15));
PVOID pOverrideViewTarget = reinterpret_cast<PVOID*>(Get(gInts.ClientMode, 16));
PVOID pCreateMoveTarget = reinterpret_cast<PVOID>(Get(gInts.ClientMode, 21));
PVOID pPostProcessTarget = reinterpret_cast<PVOID>(gSignatures.GetClientSignature("55 8B EC 81 EC ? ? ? ? 8B 0D ? ? ? ? 53 33"));
PVOID pFogTarget = reinterpret_cast<PVOID>(gSignatures.GetClientSignature("55 8B EC 8B 0D ? ? ? ? 83 EC 0C 8B 01 53"));
//causes retardation on some maps. IDK why.
//PVOID pFogTarget = reinterpret_cast<PVOID>(gSignatures.GetClientSignature("55 8B EC 8B 0D ? ? ? ? 83 EC 0C 8B 01 53"));
//PVOID pSkyboxFogTarget = reinterpret_cast<PVOID>(gSignatures.GetClientSignature("55 8B EC 83 EC 10 57 E8"));
//PVOID pViewmodelFOVTarget = reinterpret_cast<PVOID>(Get(gInts.ClientMode, 32));
if (MH_Initialize() != MH_OK)
{
return FALSE;
}
if (MH_CreateHook(pPaintTraverseTarget, &Hooked_PaintTraverse, reinterpret_cast<void**>(&oPanel)) != MH_OK)
{
return FALSE;
}
if (MH_CreateHook(pCreateMoveTarget, &Hooked_CreateMove, reinterpret_cast<void**>(&bReturn)) != MH_OK)
{
return FALSE;
}
if (MH_CreateHook(pModelRenderTarget, &Hooked_DrawModelExecute, reinterpret_cast<void**>(&oDrawModel)) != MH_OK)
{
return FALSE;
}
if (MH_CreateHook(pOverrideViewTarget, &Hooked_OverrideView, reinterpret_cast<void**>(&oView)) != MH_OK)
{
return FALSE;
}
if (MH_CreateHook(pSetViewAnglesTarget, &Hooked_SetViewAngles, reinterpret_cast<void**>(&oSetViewAngles)) != MH_OK)
{
return FALSE;
}
if (MH_CreateHook(pFrameStageTarget, &Hooked_FrameStageNotify, reinterpret_cast<void**>(&oFrameStage)) != MH_OK)
{
return FALSE;
}
if (MH_CreateHook(pLevelInitTarget, &Hooked_LevelInitPreEntity, reinterpret_cast<void**>(&oLevelInit)) != MH_OK)
{
return FALSE;
}
/*if (MH_CreateHook(pShouldDrawFogTarget, &Hooked_ShouldDrawFog, reinterpret_cast<void**>(&oFog)) != MH_OK)
{
return FALSE;
}*/
if (MH_CreateHook(pFogTarget, &Hooked_EnableWorldFog, reinterpret_cast<void**>(&oWorldFog)) != MH_OK)
{
return FALSE;
}
/*if (MH_CreateHook(pPostProcessTarget, &Hooked_DoEnginePostProcessing, nullptr) != MH_OK)
{
return FALSE;
}*/
if (MH_EnableHook(MH_ALL_HOOKS) != MH_OK)
{
return FALSE;
}
}
while (!GetAsyncKeyState(VK_END))
std::this_thread::sleep_for(std::chrono::milliseconds(50));
FreeLibraryAndExitThread(static_cast<HMODULE>(hInstance), 0);
}
DWORD WINAPI UnHook()
{
MH_Uninitialize();
MH_DisableHook(MH_ALL_HOOKS);
return TRUE;
}
BOOL APIENTRY DllMain(HMODULE hInstance, DWORD dwReason, LPVOID lpReserved)
{
DisableThreadLibraryCalls(hInstance);
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
if (HANDLE hCheatHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)dwMainThread, hInstance, 0, NULL))
CloseHandle(hCheatHandle);
break;
case DLL_PROCESS_DETACH:
UnHook();
break;
}
return true;
} | 37.381188 | 132 | 0.727851 | [
"vector"
] |
ee1e05699be86a433174de9c24eac52c528b27b1 | 13,636 | cpp | C++ | gui/regionwidget.cpp | klindworth/disparity_estimation | 74759d35f7635ff725629a1ae555d313f3e9fb29 | [
"BSD-2-Clause"
] | null | null | null | gui/regionwidget.cpp | klindworth/disparity_estimation | 74759d35f7635ff725629a1ae555d313f3e9fb29 | [
"BSD-2-Clause"
] | null | null | null | gui/regionwidget.cpp | klindworth/disparity_estimation | 74759d35f7635ff725629a1ae555d313f3e9fb29 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c) 2013, Kai Klindworth
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "regionwidget.h"
#include "ui_regionwidget.h"
#include "costmap_utils.h"
#include "disparity_toolkit/genericfunctions.h"
#include "disparity_toolkit/disparity_utils.h"
#include "disparity_region.h"
#include "disparity_region_algorithms.h"
#include <segmentation/intervals.h>
#include "region_optimizer.h"
#include "configrun.h"
#include <segmentation/intervals_algorithms.h>
#include "initial_disparity.h"
#include "disparity_toolkit/disparity_range.h"
#include <opencv2/highgui/highgui.hpp>
#include "manual_region_optimizer.h"
#include "ml_region_optimizer.h"
RegionWidget::RegionWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::RegionWidget)
{
ui->setupUi(this);
}
void RegionWidget::setInverted(bool inverted)
{
ui->plot->setInverted(inverted);
}
void RegionWidget::warpTree(int index, disparity_region& baseRegion, std::vector<disparity_region>& other_regions , QTreeWidget *tree, int dispMin, int currentDisparity)
{
tree->clear();
QStringList headers;
headers << "Nr" << "Disparity-Dev" << "Disparity" << "Pixelcount" << "% (base)" << "% (match)" << "stddev" << "e_base";
tree->setHeaderLabels(headers);
tree->setColumnCount(headers.size());
double disp_average = 0.0f;
double disp_lr_norm = 0.0f;
double disp_non_lr_average = 0.0f;
std::vector<std::pair<double,double>> non_lr_regions;
for(const corresponding_region& cregion : baseRegion.corresponding_regions[currentDisparity-dispMin])
{
disparity_region& matchRegion = other_regions[cregion.index];
double mutual_percent = cregion.percent;
disp_average += mutual_percent * matchRegion.disparity;
if(std::abs(matchRegion.disparity + currentDisparity) < 4)
disp_lr_norm += mutual_percent;
else
{
disp_non_lr_average += mutual_percent * matchRegion.disparity;
non_lr_regions.push_back(std::make_pair(mutual_percent, (double)matchRegion.disparity));
}
QStringList matchItem;
matchItem << QString::number(cregion.index);
matchItem << QString::number(std::abs(matchRegion.disparity + currentDisparity));
matchItem << QString::number(matchRegion.disparity);
matchItem << QString::number(matchRegion.m_size);
matchItem << QString::number(mutual_percent*100, 'f', 2) + "%";
matchItem << QString::number(matchRegion.get_corresponding_region(index, -currentDisparity- m_match->task.range.start()).percent*100, 'f', 2) + "%";
//matchItem << QString::number(matchRegion.stats.stddev/baseRegion.stats.stddev);
matchItem << "-";
if(matchRegion.optimization_energy.data)
matchItem << QString::number(matchRegion.optimization_energy(-currentDisparity-m_match->task.range.start()));
matchItem << "noop";
tree->addTopLevelItem(new QTreeWidgetItem(matchItem));
/*std::cout << regionsLeft[i].disparity_costs.at<float>(regionsLeft[i].disparity - dispMin) << " vs " << regionsRight[it->first].disparity_costs.at<float>(regionsRight[it->first].disparity) << std::endl; //TODO: dispMax*/
}
double mean_non_lr = disp_non_lr_average / (1.0f-disp_lr_norm);
double stddev = 0.0f;
for(std::pair<double,double> cpair : non_lr_regions)
stddev += cpair.first * std::abs(cpair.second-mean_non_lr);
ui->lblAverageDisparity->setText("Average: " + QString::number(disp_average) + ", L/R passed: " + QString::number(disp_lr_norm*100, 'f', 2) + "%, Non-LR-Average: " + QString::number(mean_non_lr) + " , stddev: " + QString::number(stddev) );
}
void RegionWidget::mutualDisparity(disparity_region& baseRegion, region_container& base, region_container& match, QTreeWidget *tree, int dispMin)
{
std::vector<disparity_region>& other_regions = match.regions;
tree->clear();
QStringList header;
header << "Disp" << "Other Disp" << "lr_pot" << "neigh_color_pot" << "costs" << "own_occ" << "warp_costs" << /*"E_base" <<*/ "E" << "E_own" << "E_Other";
tree->setColumnCount(header.size());
tree->setHeaderLabels(header);
int pot_trunc = 10;
std::vector<stat_t> other_stat(match.regions.size());
for(std::size_t i = 0; i < match.regions.size(); ++i)
generate_stats(match.regions[i], other_stat[i]);
manual_optimizer_feature_calculator dhv(base, match);
int dispMax = dispMin + baseRegion.corresponding_regions.size()-1;
disparity_range range(dispMin, dispMax);
dhv.update(pot_trunc, baseRegion, range);
stat_t cstat;
generate_stats(baseRegion, cstat);
int i = 0;
for(auto it = baseRegion.corresponding_regions.begin(); it != baseRegion.corresponding_regions.end(); ++it)
{
disparity_hypothesis hyp = dhv.get_disparity_hypothesis(i);
short currentDisp = i + dispMin;
float avg_disp = corresponding_regions_average(other_regions, *it, [](const disparity_region& cregion){return (float)cregion.disparity;});
float e_other = baseRegion.optimization_energy.data ? corresponding_regions_average(other_regions, *it, [&](const disparity_region& cregion){return cregion.optimization_energy(-currentDisp-m_match->task.range.start());}) : 0;
//ratings
//float stddev_dev = baseRegion.stats.stddev-stddev;
//float disp_dev = std::abs(currentDisp+avg_disp);
//float e_base = m_config->base_eval(hyp, current);
float e_base = baseRegion.optimization_energy.data ? baseRegion.optimization_energy(i) : 0;
//float rating = (disp_pot/5.0f -2.0f) * baseRegion.stats.stddev/stddev + e_base;
float rating = baseRegion.optimization_energy.data ? m_config->optimizer.prop_eval(baseRegion, base, match, currentDisp, cstat, other_stat) : 0;
//output
QStringList item;
item << QString::number(i+dispMin);
item << QString::number(avg_disp);
item << QString::number(hyp.lr_pot);
item << QString::number(hyp.neighbor_color_pot);
item << QString::number(hyp.costs);
item << QString::number(hyp.occ_avg);
item << QString::number(hyp.warp_costs);
if(!it->empty())
item << QString::number(rating);
else
item << QString::number(30.0f);
item << QString::number(e_base);
item << QString::number(e_other);
tree->addTopLevelItem(new QTreeWidgetItem(item));
i++;
}
}
void RegionWidget::optimizationViewer(disparity_region& baseRegion, region_container& base, region_container& match, QTreeWidget *tree, int dispMin)
{
//std::vector<disparity_region>& other_regions = match.regions;
tree->clear();
QStringList header;
header << "Disp";
for(int i = 0; i < ml_region_optimizer::vector_size_per_disp; ++i)
header << QString::number(i);
tree->setColumnCount(header.size());
tree->setHeaderLabels(header);
int pot_trunc = 15;
ml_feature_calculator dhv(base, match);
int dispMax = dispMin + baseRegion.corresponding_regions.size()-1;
disparity_range range(dispMin, dispMax);
//dhv.update(pot_trunc, baseRegion, range);
//void operator()(const disparity_region& baseRegion, short pot_trunc, const disparity_range& drange, std::vector<float>& result_vector);
//void update_result_vector(std::vector<float>& result_vector, const disparity_region& baseRegion, const disparity_range& drange);
std::vector<float> optimization_vector(ml_region_optimizer::vector_size_per_disp * range.size() + ml_region_optimizer::vector_size);
dhv.operator ()(baseRegion, pot_trunc, range, optimization_vector);
stat_t cstat;
generate_stats(baseRegion, cstat);
int i = 0;
for(auto it = baseRegion.corresponding_regions.begin(); it != baseRegion.corresponding_regions.end(); ++it)
{
QStringList item;
item << QString::number(i+dispMin);
for(int j = 0; j < ml_region_optimizer::vector_size_per_disp; ++j)
{
int idx = i*ml_region_optimizer::vector_size_per_disp+j;
item << QString::number(optimization_vector[idx]);
}
tree->addTopLevelItem(new QTreeWidgetItem(item));
i++;
}
}
void RegionWidget::neighborTree(std::vector<disparity_region>& regionsBase, int index, int /*dispMin*/)
{
ui->treeNeighbors->clear();
QStringList headers2;
headers2 << "Nr" << "Borderlength" << "Disparity" << "color_diff";
ui->treeNeighbors->setHeaderLabels(headers2);
for(const auto& cpair : regionsBase[index].neighbors)
{
int cidx = cpair.first;
QStringList item;
item << QString::number(cidx);
item << QString::number(cpair.second);
item << QString::number(regionsBase[cidx].disparity);
item << QString::number(cv::norm(regionsBase[index].average_color - regionsBase[cidx].average_color));
ui->treeNeighbors->addTopLevelItem(new QTreeWidgetItem(item));
}
}
void optimizeWidth(QTreeWidget *widget)
{
for(int i = 0; i < widget->columnCount(); ++i)
widget->resizeColumnToContents(i);
}
void RegionWidget::setData(std::shared_ptr<region_container>& base, std::shared_ptr<region_container>& match, int index, initial_disparity_config *config, bool delta)
{
m_config = config;
m_base = base;
m_match = match;
m_index = index;
int dispMin = m_base->task.range.start();
std::vector<disparity_region>& regionsBase = m_base->regions;
std::vector<disparity_region>& regionsMatch = m_match->regions;
stat_t cstat;
generate_stats(regionsBase[index], cstat);
QString info = QString("min: %1, max: %2, mean: %3, stddev: %4, range: %5,\n disparity: %6, confidence2: %7, \n confidence_range: %8, minima_variance: %9,base_disp: %10").arg(cstat.min).arg(cstat.max).arg(cstat.mean).arg(cstat.stddev).arg(cstat.max-cstat.min).arg(cstat.disparity_idx).arg(cstat.confidence2).arg(cstat.confidence_range).arg(cstat.confidence_variance).arg(regionsBase[index].base_disparity);
ui->stat->setText(info);
if(!delta)
ui->plot->setValues(regionsBase[index].disparity_costs.ptr<float>(0), cstat, regionsBase[index].disparity_costs.size[0], regionsBase[index].disparity_offset);
else
{
disparity_range drange = task_subrange(m_base->task, regionsBase[index].base_disparity, config->region_refinement_delta);
ui->plot->setValues(regionsBase[index].disparity_costs.ptr<float>(0), cstat, drange.size(), regionsBase[index].disparity_offset);
}
ui->lblIndex->setText("Index: " + QString::number(index));
ui->lblDisparity->setText("Disparity: " + QString::number(regionsBase[index].disparity));
ui->lblPixelcount->setText("Pixelcount: " + QString::number(regionsBase[index].m_size));
warpTree(index, regionsBase[index], regionsMatch, ui->treeConnected, dispMin, regionsBase[index].disparity);
mutualDisparity(regionsBase[index], *m_base, *m_match, ui->twMutualDisparity, dispMin);
optimizationViewer(regionsBase[index], *m_base, *m_match, ui->twOpt, dispMin);
neighborTree(regionsBase, index, dispMin);
//fill occlusion tree
ui->twOcc->clear();
/*for(unsigned int i = 0; i < regionsBase[index].occlusion.size(); ++i)
{
QStringList item;
item << QString::number(i);
item << QString::number(regionsBase[index].occlusion[i]);
ui->twOcc->addTopLevelItem(new QTreeWidgetItem(item));
}*/
//resize columns
optimizeWidth(ui->treeNeighbors);
optimizeWidth(ui->treeConnected);
optimizeWidth(ui->twOcc);
optimizeWidth(ui->twMutualDisparity);
optimizeWidth(ui->twOpt);
showResultHistory(regionsBase[index]);
}
RegionWidget::~RegionWidget()
{
delete ui;
}
void RegionWidget::on_twMutualDisparity_itemDoubleClicked(QTreeWidgetItem *item, int /*column*/)
{
warpTree(m_index, m_base->regions[m_index], m_match->regions, ui->treeConnected, m_base->task.range.start(), item->text(0).toInt());
}
void RegionWidget::on_treeConnected_itemDoubleClicked(QTreeWidgetItem *item, int /*column*/)
{
emit matchRegionSelected(item->text(0).toInt());
}
void RegionWidget::on_treeNeighbors_itemDoubleClicked(QTreeWidgetItem *item, int /*column*/)
{
emit baseRegionSelected(item->text(0).toInt());
}
void RegionWidget::showResultHistory(disparity_region& /*region*/)
{
ui->twResulthistory->clear();
QStringList header;
header << "costs" << "disp" << "start" << "end" << "base";
ui->twResulthistory->setHeaderLabels(header);
/*for(const EstimationStep& step : region.results)
{
QStringList item;
item << QString::number(step.costs) << QString::number(step.disparity) << QString::number(step.searchrange_start) << QString::number(step.searchrange_end) << QString::number(step.base_disparity);
ui->twResulthistory->addTopLevelItem(new QTreeWidgetItem(item));
}*/
optimizeWidth(ui->twResulthistory);
}
| 41.446809 | 408 | 0.729686 | [
"vector"
] |
ee210d59152aaffe20bed3972ed82aceed7e347d | 219 | h++ | C++ | mla/vector/all.h++ | ruimaciel/mla | b05f5913067af31a345cd2187de25871dbe31856 | [
"BSD-3-Clause"
] | null | null | null | mla/vector/all.h++ | ruimaciel/mla | b05f5913067af31a345cd2187de25871dbe31856 | [
"BSD-3-Clause"
] | null | null | null | mla/vector/all.h++ | ruimaciel/mla | b05f5913067af31a345cd2187de25871dbe31856 | [
"BSD-3-Clause"
] | null | null | null | #ifndef MLA_VECTOR_STORAGE_ALL_HPP
#define MLA_VECTOR_STORAGE_ALL_HPP
/**
* Convenience header used to include all MLA Vector classes
*/
#include <mla/vector/Dense.h++>
#include <mla/vector/SparseCS.h++>
#endif
| 14.6 | 60 | 0.753425 | [
"vector"
] |
ee22052f79623a49555218a5d5e36e465ac87a03 | 1,846 | hpp | C++ | src/org/apache/poi/hssf/eventusermodel/EventWorkbookBuilder.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/hssf/eventusermodel/EventWorkbookBuilder.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/hssf/eventusermodel/EventWorkbookBuilder.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/hssf/eventusermodel/EventWorkbookBuilder.java
#pragma once
#include <java/lang/fwd-POI.hpp>
#include <org/apache/poi/hssf/eventusermodel/fwd-POI.hpp>
#include <org/apache/poi/hssf/model/fwd-POI.hpp>
#include <org/apache/poi/hssf/record/fwd-POI.hpp>
#include <java/lang/Object.hpp>
template<typename ComponentType, typename... Bases> struct SubArray;
namespace poi
{
namespace hssf
{
namespace record
{
typedef ::SubArray< ::poi::hssf::record::RecordBase, ::java::lang::ObjectArray > RecordBaseArray;
typedef ::SubArray< ::poi::hssf::record::Record, RecordBaseArray > RecordArray;
typedef ::SubArray< ::poi::hssf::record::StandardRecord, RecordArray > StandardRecordArray;
typedef ::SubArray< ::poi::hssf::record::BoundSheetRecord, StandardRecordArray > BoundSheetRecordArray;
typedef ::SubArray< ::poi::hssf::record::ExternSheetRecord, StandardRecordArray > ExternSheetRecordArray;
} // record
} // hssf
} // poi
struct default_init_tag;
class poi::hssf::eventusermodel::EventWorkbookBuilder
: public virtual ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
static ::poi::hssf::model::InternalWorkbook* createStubWorkbook(::poi::hssf::record::ExternSheetRecordArray* externs, ::poi::hssf::record::BoundSheetRecordArray* bounds, ::poi::hssf::record::SSTRecord* sst);
static ::poi::hssf::model::InternalWorkbook* createStubWorkbook(::poi::hssf::record::ExternSheetRecordArray* externs, ::poi::hssf::record::BoundSheetRecordArray* bounds);
// Generated
EventWorkbookBuilder();
protected:
EventWorkbookBuilder(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
friend class EventWorkbookBuilder_SheetRecordCollectingListener;
};
| 36.196078 | 211 | 0.738353 | [
"object",
"model"
] |
ee2bf0b69c959d8b9f03815a75e39993cc5cbdd0 | 1,441 | cpp | C++ | src/Cheese.cpp | JRThimesch/Pizza-Shop | 55f2268d492e40750b4d79d83b12e1f0c3f8a899 | [
"MIT"
] | null | null | null | src/Cheese.cpp | JRThimesch/Pizza-Shop | 55f2268d492e40750b4d79d83b12e1f0c3f8a899 | [
"MIT"
] | null | null | null | src/Cheese.cpp | JRThimesch/Pizza-Shop | 55f2268d492e40750b4d79d83b12e1f0c3f8a899 | [
"MIT"
] | null | null | null | // File Name: Cheese.cpp
// Author: Jonathan Thimesch
// Student ID: D696H345
// Exam Number: 3
#include "Pizza.h"
#include "Cheese.hpp"
static const double PRICE_CHEESE_TOPPINGS = 1.0;
Cheese::Cheese() : Pizza()
{
initialized = false;
panSize = SMALL;
numberOfCheeseToppings = 0;
}
Cheese::Cheese(PanSize panSize, int numberOfCheeseToppings) : Pizza(panSize)
{
this->initialized = false;
// Init other pizza's attributes
this->panSize = panSize;
this->numberOfCheeseToppings = numberOfCheeseToppings + 1;
// Pizza now initialized
this->initialized = true;
}
/**
* Returns a pointer to a clone (copy) of the pizza object
*/
Pizza* Cheese::clone() const
{
Cheese* ptr = new Cheese;
*ptr = *this;
return ptr;
}
double Cheese::getCost() const
{
double cost = 0.0;
// Compute cost based on pan size
switch (panSize) {
case SMALL:
cost = getPriceSmall();
break;
case MEDIUM:
cost = getPriceMedium();
break;
case LARGE:
cost = getPriceLarge();
break;
default:
break;
}
// Add cost of cheese toppings
cost += (numberOfCheeseToppings - 1) * PRICE_CHEESE_TOPPINGS;
return cost;
}
std::string Cheese::toString() const
{
char str[200];
// Format string
sprintf(str, "%s cheese pizza with:\n %d cheese toppings\t\t%6.2f", panSizeToString(panSize).c_str(), numberOfCheeseToppings, getCost());
return std::string(str);
}
| 19.213333 | 141 | 0.657876 | [
"object"
] |
0c5f88003b25620429796f2f1f472a0a3731fa9f | 13,404 | cpp | C++ | FlyEngine/Source/Action.cpp | rogerta97/FlyEngine | 33abd70c5b4307cd552e2b6269b401772b4327ba | [
"MIT"
] | null | null | null | FlyEngine/Source/Action.cpp | rogerta97/FlyEngine | 33abd70c5b4307cd552e2b6269b401772b4327ba | [
"MIT"
] | null | null | null | FlyEngine/Source/Action.cpp | rogerta97/FlyEngine | 33abd70c5b4307cd552e2b6269b401772b4327ba | [
"MIT"
] | null | null | null | #include "Action.h"
#include "FlyObject.h"
#include "Application.h"
#include "ModuleImGui.h"
#include "Texture.h"
#include "ResourceManager.h"
#include "GlobalBlackboardDockPanel.h"
#include "Room.h"
#include "ModuleWorldManager.h"
#include "FlyVariable.h"
#include "ActionConditionVariable.h"
#include "ActionConditionHasItem.h"
#include "ActionCondition.h"
#include "mmgr.h"
Action::Action()
{
actionType = AT_null;
isSelected = false;
itemToClickWith = nullptr;
occ_SceneEnter = false;
occ_SceneLeave = false;
occ_ObjectClicked = false;
occ_blackboardValue = false;
occ_continuous = false;
occ_mouseOver = false;
isValidForCreator = true;
actionClass = ACTION_CLASS_DIRECT;
uid = RandomNumberGenerator::getInstance()->GenerateUID();
return;
}
Action::~Action()
{
}
void Action::Init()
{
}
void Action::Update(float dt)
{
}
void Action::Draw()
{
}
void Action::DrawDebugShapes()
{
}
void Action::CleanUp()
{
for (auto& currentCondition : actionConditions)
{
currentCondition->CleanUp();
delete currentCondition;
}
}
void Action::OnSceneEnter()
{
}
void Action::DrawUISettings()
{
}
void Action::DrawUISettingsSequential()
{
}
void Action::DrawUISettingsInButton()
{
}
bool Action::IsActionSequential()
{
if(actionClass == ActionClass::ACTION_CLASS_SEQUENTIAL)
return true;
return false;
}
int Action::GetOccurrencesMarkedAmount()
{
int occurrencesAmount = 0;
if (occ_blackboardValue) occurrencesAmount++;
if (occ_mouseOver) occurrencesAmount++;
if (occ_ObjectClicked) occurrencesAmount++;
if (occ_SceneEnter) occurrencesAmount++;
if (occ_SceneLeave) occurrencesAmount++;
return occurrencesAmount;
}
bool Action::PassAllOccurrenceConditions()
{
return true;
}
void Action::SaveAction(JSON_Object* jsonObject, std::string serializeObjectString, bool literalString, int actionPositionInObject)
{
json_object_dotset_string(jsonObject, string(serializeObjectString + "Name").c_str(), GetActionName().c_str());
json_object_dotset_number(jsonObject, string(serializeObjectString + "ActionType").c_str(), actionType);
json_object_dotset_number(jsonObject, string(serializeObjectString + "ActionClass").c_str(), actionClass);
SaveActionConditions(serializeObjectString, jsonObject);
}
void Action::SaveOccurrence(JSON_Object* jsonObject, string serializeObjectString)
{
string serializeObjectOccurrenceStr = serializeObjectString + "Occurrence.";
json_object_dotset_boolean(jsonObject, string(serializeObjectOccurrenceStr + "SceneEnter").c_str(), IsOccSceneEnter());
json_object_dotset_boolean(jsonObject, string(serializeObjectOccurrenceStr + "SceneLeave").c_str(), IsOccSceneLeave());
json_object_dotset_boolean(jsonObject, string(serializeObjectOccurrenceStr + "ObjectClicked").c_str(), IsOccObjectClicked());
if (itemToClickWith == nullptr)
{
json_object_dotset_number(jsonObject, string(serializeObjectOccurrenceStr + "ItemToClickWith").c_str(), 0);
}
else
{
json_object_dotset_number(jsonObject, string(serializeObjectOccurrenceStr + "ItemToClickWith").c_str(), itemToClickWith->GetUID());
}
json_object_dotset_boolean(jsonObject, string(serializeObjectOccurrenceStr + "BlackboardCondition").c_str(), IsOccCondition());
}
void Action::SaveActionConditions(std::string& serializeObjectString, JSON_Object* jsonObject)
{
int conditionsAmount = this->actionConditions.size();
json_object_dotset_number(jsonObject, string(serializeObjectString + "Conditions.ConditionsAmount").c_str(), conditionsAmount);
if (!actionConditions.empty())
{
string conditionsSaveStr = serializeObjectString + "Conditions.";
int count = 0;
for (auto& currentCondition : actionConditions)
{
currentCondition->SaveCondition(jsonObject, conditionsSaveStr, count++);
}
}
}
void Action::LoadOccurrence(JSON_Object* jsonObject, string serializeObjectString)
{
occ_SceneEnter = json_object_dotget_boolean(jsonObject, string(serializeObjectString + "SceneEnter").c_str());
occ_SceneLeave = json_object_dotget_boolean(jsonObject, string(serializeObjectString + "SceneLeave").c_str());
occ_blackboardValue = json_object_dotget_boolean(jsonObject, string(serializeObjectString + "BlackboardCondition").c_str());
occ_ObjectClicked = json_object_dotget_boolean(jsonObject, string(serializeObjectString + "ObjectClicked").c_str());
}
void Action::DoAction()
{
}
void Action::StopAction()
{
}
void Action::DrawActionConditionsList()
{
// Evalutation Criteria
ImGui::PushFont(App->moduleImGui->rudaBoldBig);
ImGui::Text("Evaluation Criteria:");
ImGui::PopFont();
int evaluationCritatiaComboInt = (int)evaluationCriteria;
if (ImGui::Combo("", &evaluationCritatiaComboInt, "All conditions must succed\0One condition must succed"))
{
switch (evaluationCritatiaComboInt)
{
case 0:
evaluationCriteria = ALL_SUCCED;
break;
case 1:
evaluationCriteria = ONE_SUCCED;
break;
}
}
ImGui::Spacing();
// Value Conditions List
ImGui::PushFont(App->moduleImGui->rudaBoldBig);
ImGui::Text("Conditions List:");
ImGui::PopFont();
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.12f, 0.14f, 0.17f, 1.00f));
ImGui::BeginChild("valueConditionsHolder", ImVec2(ImGui::GetContentRegionAvailWidth(), 250));
int count = 0;
for (auto& currentCondition : actionConditions)
{
currentCondition->DrawUIItem(count);
count++;
}
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::Spacing();
ImGui::Separator();
// Draw Condition Buttons
Texture* plusTexture = (Texture*)ResourceManager::getInstance()->GetResource("PlusIcon");
if (ImGui::ImageButton((ImTextureID)plusTexture->GetTextureID(), ImVec2(25, 25)))
{
ImGui::OpenPopup("SelectConditionType");
}
// Callback for when button Add is pressed
OnAddConditionButtonPressed();
ImGui::SameLine();
Texture* minusTexture = (Texture*)ResourceManager::getInstance()->GetResource("MinusIcon");
if (ImGui::ImageButton((ImTextureID)minusTexture->GetTextureID(), ImVec2(25, 25)))
{
}
}
void Action::OnAddConditionButtonPressed()
{
if (ImGui::BeginPopup("SelectConditionType"))
{
Texture* checkVariableIcon = (Texture*)ResourceManager::getInstance()->GetResource("CheckVariableIcon");
ImGui::Image((ImTextureID)checkVariableIcon->GetTextureID(), ImVec2(18, 18));
ImGui::SameLine();
if (ImGui::Selectable("Check Blackboard Variable"))
AddEmptyCondition(CONDITION_IS_VARIABLE);
Texture* checkInventoryItemIcon = (Texture*)ResourceManager::getInstance()->GetResource("CheckInventoryItemIcon");
ImGui::Image((ImTextureID)checkInventoryItemIcon->GetTextureID(), ImVec2(18, 18));
ImGui::SameLine();
if (ImGui::Selectable("Check Inventory Object"))
AddEmptyCondition(CONDITION_HAS_ITEM);
ImGui::EndPopup();
}
}
bool Action::IsValidForCreator()
{
return isValidForCreator;
}
std::string Action::GetActionName() const
{
return toolName;
}
void Action::SetActionName(std::string newName)
{
toolName = newName;
}
void Action::LoadConditions(JSON_Object* jsonObject, string serializeObjectString)
{
int conditionsAmount = json_object_dotget_number(jsonObject, string(serializeObjectString + "ConditionsAmount").c_str());
int count = 0;
while (count < conditionsAmount)
{
string serializeStr = serializeObjectString + "Condition_" + to_string(count);
int conditionType_tmp = json_object_dotget_number(jsonObject, string(serializeStr + ".ConditionType").c_str());
ActionConditionType actionConditionType = (ActionConditionType)conditionType_tmp;
ActionCondition* newCondition = nullptr;
switch (actionConditionType)
{
case CONDITION_IS_VARIABLE:
newCondition = LoadConditionVariable(jsonObject, serializeStr, parentObject->GetParentRoom()->GetBlackboard());
break;
case CONDITION_HAS_ITEM:
newCondition = LoadConditionHasItem(jsonObject, serializeStr);
break;
}
count++;
}
}
ActionConditionHasItem* Action::LoadConditionHasItem(JSON_Object* jsonObject, string serializeObjectString)
{
ActionConditionHasItem* newConditionHasItem = new ActionConditionHasItem();
newConditionHasItem->itemToCheckUID = json_object_dotget_number(jsonObject, string(serializeObjectString + ".ItemToCheckUID").c_str());
newConditionHasItem->itemToCheckName = json_object_dotget_string(jsonObject, string(serializeObjectString + ".ItemToCheckName").c_str());
actionConditions.push_back(newConditionHasItem);
return newConditionHasItem;
}
ActionConditionVariable* Action::LoadConditionVariable(JSON_Object* jsonObject, string serializeObjectString, Blackboard* currentBlackboard)
{
ActionConditionVariable* newConditionVariable = new ActionConditionVariable();
string targetVariableName = json_object_dotget_string(jsonObject, string(serializeObjectString + ".TargetVariableName").c_str());
newConditionVariable->targetVariable = currentBlackboard->GetVariable(targetVariableName);
if (newConditionVariable->targetVariable == nullptr)
{
newConditionVariable->targetVariable = App->moduleWorldManager->globalBlackboard->GetVariable(targetVariableName);
}
int conditionOperator_tmp = json_object_dotget_number(jsonObject, string(serializeObjectString + ".ConditionType").c_str());
newConditionVariable->actionConditionOperator = (ActionConditionOperator)conditionOperator_tmp;
newConditionVariable->targetValueInteger = json_object_dotget_number(jsonObject, string(serializeObjectString + ".TargetValueInteger").c_str());
newConditionVariable->targetValueBoolean = json_object_dotget_boolean(jsonObject, string(serializeObjectString + ".TargetValueBoolean").c_str());
actionConditions.push_back(newConditionVariable);
return newConditionVariable;
}
bool Action::PassConditionTest()
{
for (auto& currentCondition : actionConditions)
{
bool testResult = currentCondition->PassTestCondition();
if (testResult == true)
{
if(evaluationCriteria == ONE_SUCCED)
return true;
}
else
{
if (evaluationCriteria == ALL_SUCCED)
return false;
}
}
return true;
}
bool& Action::IsOccSceneEnter()
{
return occ_SceneEnter;
}
bool& Action::IsOccSceneLeave()
{
return occ_SceneLeave;
}
bool& Action::IsOccCondition()
{
return occ_blackboardValue;
}
bool& Action::IsOccMouseOver()
{
return occ_mouseOver;
}
bool& Action::IsOccObjectClicked()
{
return occ_ObjectClicked;
}
void Action::SetOccBlackboardValue(bool newValue)
{
occ_blackboardValue = newValue;
}
void Action::SetOccSceneEnter(bool newOccSceneEnter)
{
occ_SceneEnter = newOccSceneEnter;
}
void Action::SetOccSceneLeave(bool newOccSceneLeave)
{
occ_SceneLeave = newOccSceneLeave;
}
void Action::SetOccObjectClicked(bool newOccObjectClicked)
{
occ_ObjectClicked = newOccObjectClicked;
}
void Action::SetOccMouseOver(bool newValue)
{
occ_mouseOver = newValue;
}
ActionCondition* Action::AddEmptyCondition(ActionConditionType conditionType)
{
switch (conditionType)
{
case CONDITION_IS_VARIABLE:
{
ActionConditionVariable* conditionCheckVar = new ActionConditionVariable();
actionConditions.push_back(conditionCheckVar);
return conditionCheckVar;
}
case CONDITION_HAS_ITEM:
{
ActionConditionHasItem* conditionHasItem = new ActionConditionHasItem();
actionConditions.push_back(conditionHasItem);
return conditionHasItem;
}
case AC_NONE:
break;
}
return nullptr;
}
void Action::AddCondition(ActionCondition* newCondition)
{
actionConditions.push_back(newCondition);
}
FlyObject* Action::GetParentObject() const
{
return parentObject;
}
void Action::SetParentObject(FlyObject* newParentObject)
{
parentObject = newParentObject;
}
std::string Action::GetToolDescription() const
{
return toolDescription;
}
void Action::SetToolDescription(std::string newDescription)
{
toolDescription = newDescription;
}
ActionType Action::GetType() const
{
return actionType;
}
void Action::SetToolType(ActionType newToolType)
{
actionType = newToolType;
}
bool& Action::IsSelected()
{
return isSelected;
}
void Action::SetIsSelected(bool _isSelected)
{
isSelected = _isSelected;
}
bool& Action::IsInfoHolder()
{
return isHolderInfo;
}
void Action::SetIsInfoHolder(bool _isInfoHolder)
{
isHolderInfo = _isInfoHolder;
}
bool& Action::GetIsSequencial()
{
return isSequential;
}
void Action::SetIsSequencial(bool _isSequential)
{
isSequential = _isSequential;
}
void Action::SetSelected(bool newSelected)
{
isSelected = newSelected;
}
bool& Action::HasVisual()
{
return isVisual;
}
void Action::SetDrawIfSequential(bool _dis)
{
drawIfSequential = _dis;
}
bool& Action::GetDrawIfSequential()
{
return drawIfSequential;
}
void Action::SetVisible(bool isVisible)
{
this->isVisible = isVisible;
}
bool& Action::GetIsVisible()
{
return isVisible;
}
UID Action::GetUID()
{
return uid;
}
void Action::SetUID(UID newUID)
{
uid = newUID;
}
ActionClass Action::GetActionClass()
{
return actionClass;
}
void Action::SetActionClass(ActionClass _acSec)
{
actionClass = _acSec;
}
ActionSelectableInfo Action::GetActionSelectableInfo()
{
ActionSelectableInfo returnToolInfo;
returnToolInfo.actionName = toolName;
returnToolInfo.actionDescription = toolDescription;
returnToolInfo.actionType = actionType;
return returnToolInfo;
}
bool Action::IsActionFinished()
{
return actionFinished;
}
void Action::SetActionCompleted(bool isFinished)
{
if (isFinished == actionFinished)
return;
actionFinished = isFinished;
//flog("%s finished", this->GetActionName().c_str());
}
| 23.681979 | 146 | 0.770889 | [
"object"
] |
0c632d888ca69a5c1202464ce98f5fc2ceb8b1b7 | 8,230 | hpp | C++ | engine/src/Renderer.hpp | skryabiin/core | 13bcdd0c9f3ebcc4954b9ee05ea95db0f77e16f7 | [
"MIT"
] | null | null | null | engine/src/Renderer.hpp | skryabiin/core | 13bcdd0c9f3ebcc4954b9ee05ea95db0f77e16f7 | [
"MIT"
] | null | null | null | engine/src/Renderer.hpp | skryabiin/core | 13bcdd0c9f3ebcc4954b9ee05ea95db0f77e16f7 | [
"MIT"
] | null | null | null | #ifndef CORE_RENDERER_HPP
#define CORE_RENDERER_HPP
#include <algorithm>
#include <memory>
#include <GL/glew.h>
//include stdlib so glut can override exit()
#include <stdlib.h>
#include <glut.h>
#include <SDL.h>
#include "SDL_image.h"
#include "Templates.hpp"
#include "Config.hpp"
#include "Math.hpp"
#include "TextureManager.hpp"
#include "Animation.hpp"
#include "RuntimeContext.hpp"
#include "Texture.hpp"
#include "Drawable.hpp"
#include "DrawableChange.hpp"
#include "Event.hpp"
#include "Console.hpp"
#include "DebugEvent.hpp"
#include "ParticleField.hpp"
#include "LinearParticleField.hpp"
#include "RenderLayer.hpp"
#include "ShaderManager.hpp"
#include "VertexShader.hpp"
#include "FragmentShader.hpp"
#include "ShaderProgram.hpp"
#include "VertexArrayObject.hpp"
#include "SPSCQueue.hpp"
#include "FrameBuffer.hpp"
namespace core {
struct TextureFacet;
class Renderer : public updateable<Renderer, void, RuntimeContext>, public initializable<Renderer, void, void, void, void>, public pausable<Renderer> {
friend class Core;
public:
//initializable
//-------------
bool createImpl();
//-initializes sdl video
//-initializes open gl context attributes
//-creates the sdl window
//-generates gl contexts
//-initializes glew
//-checks for opengl debug flag in config
//-creates drawable change queues
//-creates rendering thread
//-creates vao and program for render layer drawing
//
//
bool initializeImpl();
//-initializes layers
//-clears drawable change queues
//-unpauses render thread
//
//
bool resetImpl();
//-resets and destroys layers
//-clears drawable change queues
//
//
bool destroyImpl();
//-signals render thread shutdown and waits
//-deletes drawable change queues
//-destroys sdl window
//pausable
//--------
void pauseImpl();
//locks the render thread
//
//
void resumeImpl();
//unlocks the render thread
//updateable
//----------
void updateImpl(float dt, RuntimeContext& context);
//switches the drawable change queue, and
//waits for changes to be consumed if the queue depth
//exceeds the threshhold defined at Config.graphics.maxWaitFreeQueueDepth
static int renderThread(void* data);
//the function sent to SDL_CreateThread, this runs the renderer when in multithreaded mode
bool isMultithreaded();
//returns true if this is in multithreaded rendering mode
void multithreadRender();
//the main loop for multithreaded rendering
//processes drawable changes, regulates frame rate, and calls render()
//this regulates the render thread when the renderer is first initialized
void render();
//this is the main render loop.
//either called by multithreadRender (if in multithreaded mode) or Core (in singlethreaded mode)
void start();
//initializes the opengl draw calls for this frame
void end();
//ends the opengl draw calls for this frame and swaps buffers
void applyDrawableChange(DrawableChange& dc);
//add a change to a drawable to the queue, to be processed by the render thread at next cycle
void createRenderLayer(short layerId, Camera* camera);
//creates a new render layer with the given id and camera, and sorts it into the render layer list
int getMinZIndex(short layerId) const;
//returns the z element of the closest (z-wise) drawable in the specified layer
void setTextureAtlas(Texture* atlas);
//sets the gl id for the atlas texture
void setBackgroundColor(Color& color);
//sets the clear color for the renderer
void setGlobalColorModulation(ColorTransform& transform);
//sets the color modulation matrix that is used on each render layer (including the interface)
ColorTransform getGlobalColorModulation();
//returns the color modulation matrix that is used on each render layer (including the interface)
void setDepthTestFunction(GLenum test);
//sets the opengl depth test function. This isnt used much since the renderer does its own
//depth sorting and thus can use easier transparency
Dimension windowDimensions() const;
//returns the dimensions of the sdl window
void hideWindow();
//hides the window using SDL_ShowWindow(false)
void showWindow();
//shows the window using SDL_ShowWindow(true)
//lua function bindings
//---------------------
static int getMinZIndex_bind(LuaState& lua);
//returns the z element of the closest drawable in the specified layer
//not used?
//
static int hideWindow_bind(LuaState& lua);
//hides the window using SDL_ShowWindow(false)
//see Renderer.hideWindow()
//
//
static int showWindow_bind(LuaState& lua);
//shows the window using SDL_ShowWindow(true)
//see Renderer.showWindow()
//
//
static int setBackgroundColor_bind(LuaState& lua);
//sets the clear color for the renderer.
//see Renderer.setBackgroundColor()
//
//
static int fadeWindow_bind(LuaState& lua);
//fades the global color modulation from the current matrix to a different one, over a duration of miliseconds
//Also registers a callback with the transition manager, if specified
//see Renderer.fadeWindow()
//
//
static int setGlobalColorModulation_bind(LuaState& lua);
//sets the color modulation matrix that is used on each render layer (including the interface)
//see Renderer.setGlobalColorModulation()
//
//
static int getGlobalColorModulation_bind(LuaState& lua);
//returns the color modulation matrix that is used on each render layer (including the interface)
//see Renderer.getGlobalColorModulation()
private:
//multithreading
SDL_Thread* _renderThread;
bool _renderMultithreaded;
SDL_SpinLock _drawableChangePtrLock;
SDL_SpinLock _renderThreadLock;
bool _doRenderThread;
//rendering calls for various types
void _drawPoly(Drawable& d);
void _drawPoly(std::vector<int>& points, Color& color, ColorTransform& colorTransform, bool filled);
void _drawPoly(GLfloat* v, unsigned numPoints, Color& color, ColorTransform& colorTransform, bool filled);
//layers
std::vector<RenderLayer> _layers;
//drawable changes
void _addDrawableChange(DrawableChange& dc);
void _processDrawableChanges();
void _addRenderLayer(short layerId, Camera* camera);
Drawable* _getDrawable(int facetId, short layerId);
SPSCQueue<DrawableChange>* _drawableChangeQueue1;
SPSCQueue<DrawableChange>* _drawableChangeQueue2;
SPSCQueue<DrawableChange>** _drawableChanges;
SPSCQueue<DrawableChange>** _drawablePending;
SPSCQueue<CreateLayerRequest>* _createRenderLayerQueue;
bool _writingToFirstQueue;
int _maxPendingQueueDepth;
//opengl things
bool _initGlObjects();
//-steals the context for the render thread
//-sets the initial clear color, depth test, blend function
//-creates default shader programs for primitive and texture drawing
//-creates the default shader program for render layer drawing
bool _didInitGlObjects;
bool _debugOpenGl; //set from Config.graphics.debugOpenGl
void _checkGlDebugLog();
//if _debugOpenGl is true:
//-checks opengl debug log
//-writes messages to console
//-quits if any fatal errors detected
//objects for render layer drawing
VertexArrayObject _finalPassVao;
VertexBufferObject<GLfloat> _finalPassVbo;
VertexBufferObject<GLfloat> _finalPassUvbo;
//the current texture atlas
Texture* _textureAtlas;
//gl contexts
SDL_GLContext _sdlInitContext;
SDL_GLContext _sdlGlContext;
GLenum _depthTestFunction; //current depth test function
Color _backgroundColor; //current clear color
bool _changeBackgroundColorFlag; //signals the render thread to set the clear color
ColorTransform _colorTransform; //current globlal color transform
ColorTransform _tempColorTransform; //used until the render thread sets the current transform
bool _changeColorTransform; //signals the render thread to set the current transform
SDL_Window* _sdlWindow; //the sdl window
bool _windowShown; //whether the window is shown
Dimension _windowDimensions; //the window dimensions
int _maxFramesPerSecond; //set in Config.graphics.maxFramesPerSecond
//pre-allocated objects for gl buffering work
VertexBufferObject<GLfloat> _textureVbo;
std::vector<GLfloat> _drawColor;
std::vector<GLfloat> _textureVertices;
std::vector<GLfloat> _drawVertices;
};
} //end namespace core
#endif
| 23.994169 | 151 | 0.760996 | [
"render",
"vector",
"transform"
] |
0c66786024a9db3ba6c7787c133d484da6c73a23 | 2,722 | cpp | C++ | cpp/example_code/s3/copy_object.cpp | iconara/aws-doc-sdk-examples | 52706b31b4fce8fb89468e56743edf5369e69628 | [
"Apache-2.0"
] | 1 | 2020-10-24T04:19:21.000Z | 2020-10-24T04:19:21.000Z | cpp/example_code/s3/copy_object.cpp | iconara/aws-doc-sdk-examples | 52706b31b4fce8fb89468e56743edf5369e69628 | [
"Apache-2.0"
] | 1 | 2021-04-09T21:17:09.000Z | 2021-04-09T21:17:09.000Z | cpp/example_code/s3/copy_object.cpp | iconara/aws-doc-sdk-examples | 52706b31b4fce8fb89468e56743edf5369e69628 | [
"Apache-2.0"
] | 27 | 2020-04-16T22:52:53.000Z | 2021-09-30T22:55:58.000Z | //snippet-sourcedescription:[copy_object.cpp demonstrates how to copy an object from one Amazon Simple Storage Service (Amazon S3) bucket to another.]
//snippet-keyword:[AWS SDK for C++]
//snippet-keyword:[Code Sample]
//snippet-service:[Amazon S3]
//snippet-sourcetype:[full-example]
//snippet-sourcedate:[12/15/2021]
//snippet-sourceauthor:[scmacdon - aws]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// snippet-start:[s3.cpp.copy_objects.inc]
#include <iostream>
#include <aws/core/Aws.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/CopyObjectRequest.h>
// snippet-end:[s3.cpp.copy_objects.inc]
/*
*
* Prerequisites: Two buckets. One of the buckets must contain the object to
* be copied to the other bucket.
*
* Inputs:
* - objectKey: The name of the object to copy.
* - fromBucket: The name of the bucket to copy the object from.
* - toBucket: The name of the bucket to copy the object to.
* - region: The AWS Region to create the bucket in.
*
* To run this C++ code example, ensure that you have setup your development environment, including your credentials.
* For information, see this documentation topic:
* https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/getting-started.html
*
*/
// snippet-start:[s3.cpp.copy_objects.code]
using namespace Aws;
int main()
{
Aws::SDKOptions options;
Aws::InitAPI(options);
{
//TODO: Name of object already in bucket.
Aws::String objectKey = "<enter object key>";
//TODO: Change from_bucket to the name of your bucket that already contains "my-file.txt".
Aws::String fromBucket = "<Enter bucket name>";
//TODO: Change to the name of another bucket in your account.
Aws::String toBucket = "<Enter bucket name>";
//TODO: Set to the AWS Region in which the bucket was created.
Aws::String region = "us-east-1";
Aws::Client::ClientConfiguration clientConfig;
if (!region.empty())
clientConfig.region = region;
S3::S3Client client(clientConfig);
S3::Model::CopyObjectRequest request;
request.WithCopySource(fromBucket + "/" + objectKey)
.WithKey(objectKey)
.WithBucket(toBucket);
S3::Model::CopyObjectOutcome outcome = client.CopyObject(request);
if (!outcome.IsSuccess())
{
auto err = outcome.GetError();
std::cout << "Error: CopyObject: " <<
err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
}
}
ShutdownAPI(options);
return 0;
}
// snippet-end:[s3.cpp.copy_objects.code]
| 33.604938 | 150 | 0.655768 | [
"object",
"model"
] |
0c68702e851f3448c2acf34d971f1a787b539f21 | 1,810 | cpp | C++ | src/tests/class_tests/tensorbase/source/TensorType_test.cpp | dmccloskey/TensorBase | fe947c079907ffcea81833e6d73e7b48704d093c | [
"MIT"
] | 1 | 2020-01-27T19:23:18.000Z | 2020-01-27T19:23:18.000Z | src/tests/class_tests/tensorbase/source/TensorType_test.cpp | dmccloskey/TensorBase | fe947c079907ffcea81833e6d73e7b48704d093c | [
"MIT"
] | 38 | 2019-04-13T07:42:11.000Z | 2019-11-03T14:10:54.000Z | src/tests/class_tests/tensorbase/source/TensorType_test.cpp | dmccloskey/TensorBase | fe947c079907ffcea81833e6d73e7b48704d093c | [
"MIT"
] | 1 | 2019-04-12T10:54:42.000Z | 2019-04-12T10:54:42.000Z | /**TODO: Add copyright*/
#define BOOST_TEST_MODULE TensorType test suite
#include <boost/test/included/unit_test.hpp>
#include <TensorBase/ml/TensorType.h>
#include <cassert>
using namespace TensorBase;
using namespace std;
BOOST_AUTO_TEST_SUITE(tensorType)
BOOST_AUTO_TEST_CASE(Int8Type1)
{
Int8Type tensorType;
// Check getters
BOOST_CHECK_EQUAL(tensorType.getId(), Type::INT8);
BOOST_CHECK_EQUAL(tensorType.getName(), "int8");
// Inheritance and type checks
static_assert(sizeof(Int8Type) != sizeof(int8_t), "The wrapper does not have overhead."); // It should have some overhead
static_assert(std::is_same<Int8Type::c_type, int8_t>::value, "Value type is not exposed.");
static_assert(std::is_base_of<TensorType, Int8Type>::value, "Int8Type is not the base of TensorType.");
static_assert(std::is_convertible<Int8Type::c_type*, int8_t*>::value, "Value types are not compatible.");
// Brief and incomplete set of basic operator checks
// to ensure that the fundamental type operators have been inherited
tensorType = 0; BOOST_CHECK(tensorType == 0);
tensorType += 1; BOOST_CHECK(tensorType == 1);
++tensorType; BOOST_CHECK(tensorType == 2);
BOOST_CHECK(tensorType < 3);
}
// TODO implement all other tests
BOOST_AUTO_TEST_CASE(HeteroVector1)
{
std::vector<std::shared_ptr<TensorType>> heteroVecT;
heteroVecT.push_back(std::shared_ptr<TensorType>(new BooleanType(true)));
heteroVecT.push_back(std::shared_ptr<TensorType>(new CharType('a')));
heteroVecT.push_back(std::shared_ptr<TensorType>(new UInt8Type(1)));
std::cout << heteroVecT[0]->getName() << heteroVecT[0] << std::endl;
std::cout << heteroVecT[1]->getName() << heteroVecT[1] << std::endl;
std::cout << heteroVecT[2]->getName() << heteroVecT[2] << std::endl;
}
BOOST_AUTO_TEST_SUITE_END() | 36.938776 | 123 | 0.738122 | [
"vector"
] |
0c858b34cbd96c11867ce756eb8a4239cabd92c7 | 6,476 | cpp | C++ | Systems/Engine/PropertyTrack.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 1 | 2022-03-26T21:08:19.000Z | 2022-03-26T21:08:19.000Z | Systems/Engine/PropertyTrack.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | Systems/Engine/PropertyTrack.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
///
/// \file PropertyTrack.cpp
///
///
/// Authors: Joshua Claeys, Chris Peters
/// Copyright 2011-2014, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#include "Precompiled.hpp"
namespace Zero
{
//******************************************************************************
template<typename type>
type LerpValue(type& a, type& b, float t)
{
return Interpolation::Lerp<type>::Interpolate(a, b, t);
}
//******************************************************************************
Resource* LerpValue(Resource*& a, Resource*& b, float t)
{
if(t == 1.0f)
return b;
return a;
}
//******************************************************************************
Quat LerpValue(Quat& a, Quat& b, float t)
{
return Quat::SlerpUnnormalized(a, b, t);
}
//******************************************************************************
bool LerpValue(bool& a, bool& b, float t)
{
if(t == 1.0f)
return b;
return a;
}
//******************************************************************************
template<typename KeyFrame>
void LerpKeyFrame(KeyFrame& out, KeyFrame& keyOne, KeyFrame& keyTwo, float t)
{
out.KeyValue = LerpValue(keyOne.KeyValue, keyTwo.KeyValue, t);
}
//******************************************************************************
template<typename keyFrames, typename keyFrameType>
void InterpolateKeyFrame(float time, uint& keyFrameIndex, keyFrames& mKeyFrames,
keyFrameType& keyFrame)
{
uint CurKey = keyFrameIndex;
float animTime = time;
// Since keys are not spaced at regular intervals we need to search
// for the keyframes that will be interpolated between. The track data is
// used to store what the last keyframe was to prevent searching the entire
// track.
if(mKeyFrames.Size() == 0)
return;
if(CurKey >= mKeyFrames.Size())
CurKey = 0;
// If it's to the left of the first frame, use the key value of the first frame
if(mKeyFrames.Front().Time > time)
{
keyFrame = mKeyFrames.Front();
return;
}
// Search Forward in the keyframes for the interval
while(CurKey!= mKeyFrames.Size() - 1 &&
mKeyFrames[ CurKey + 1 ].Time < animTime )
++CurKey;
// Search Backward in the keyframes for the interval
while(CurKey!= 0 && mKeyFrames[ CurKey ].Time > animTime )
--CurKey;
if(CurKey == mKeyFrames.Size() - 1)
{
// Past the last keyframe for this path so use the last frame and the
// transform data so the animation is clamped to the last frame
keyFrame = mKeyFrames[CurKey];
}
else
{
// Generate value by interpolating between the two keyframes
keyFrameType& KeyOne = mKeyFrames[ CurKey ];
keyFrameType& KeyTwo = mKeyFrames[ CurKey + 1 ];
float t1 = KeyOne.Time;
float t2 = KeyTwo.Time;
// Normalize the distance between the two keyframes
float segLen = t2 - t1;
float segStart = animTime - t1;
float segNormalizedT = segStart/segLen;
LerpKeyFrame(keyFrame, KeyOne, KeyTwo, segNormalizedT);
}
// Remember the last keyframe
keyFrameIndex = CurKey;
}
//******************************************************************************
BlendTrack* GetBlendTrack(StringParam name, BlendTracks& tracks, HandleParam instance, Property* prop)
{
BlendTrack* blendTrack = tracks.FindValue(name, nullptr);
if(blendTrack == nullptr)
{
blendTrack = new BlendTrack();
blendTrack->Index = (uint)tracks.Size();
blendTrack->Object = instance;
blendTrack->Property = prop;
tracks.Insert(name, blendTrack);
}
return blendTrack;
}
//******************************************************************************
bool ValidPropertyTrack(Property* property)
{
// Cannot animate read only properties
if(property->Set == nullptr)
return false;
// First check to see if it's a value type
Type* propertyType = property->PropertyType;
#define DoVariantType(type) \
if (propertyType == ZilchTypeId(type)) \
return true;
#include "Meta/VariantTypes.inl"
#undef DoVariantType
// Resources are also valid types
//MetaType* type = MetaDatabase::GetInstance()->FindType(property->TypeId);
//if(type && type->IsA(MetaTypeOf(Resource)))
//return true;
return false;
}
//******************************************************************************
PropertyTrack* MakePropertyTrack(StringParam componentName,
StringParam propertyName,
StringParam propertyTypeName)
{
// Get the type id from the given property type name
BoundType* propertyType = MetaDatabase::GetInstance()->FindType(propertyTypeName);
// Can't create the property track if the property type doesn't exist
if(propertyType == nullptr)
return nullptr;
return MakePropertyTrack(componentName, propertyName, propertyType);
}
//******************************************************************************
PropertyTrack* MakePropertyTrack(StringParam componentName,
StringParam propertyName,
BoundType* propertyTypeId)
{
// First check to see if it's a value type
#define DoVariantType(type) \
if (propertyTypeId == ZilchTypeId(type)) \
return new AnimatePropertyValueType<type>(componentName, propertyName);
#include "Meta/VariantTypes.inl"
#undef DoVariantType
// If it's a Resource, create a ref type track
//MetaType* type = MetaDatabase::GetInstance()->FindType(propertyTypeId);
//if(type && type->IsA(MetaTypeOf(Resource)))
//return new AnimatePropertyRefType<Resource>(componentName, propertyName);
return nullptr;
}
//******************************************************************************
PropertyTrack* MakePropertyTrack(BoundType* componentType, Property* property)
{
String componentName = componentType->Name;
String propertyName = property->Name;
String propertyTypeName = property->PropertyType->ToString();
return MakePropertyTrack(componentName, propertyName, propertyTypeName);
}
}//namespace Zero
| 32.542714 | 103 | 0.546634 | [
"object",
"transform"
] |
0c867a7e0ec1b260fca5f209fdd7517537d8aeea | 1,504 | cpp | C++ | src/application.cpp | vladislavmarkov/sketchthis | 0d494c9ed54846d759c3fad6a52aa23ae3aff4b8 | [
"MIT"
] | null | null | null | src/application.cpp | vladislavmarkov/sketchthis | 0d494c9ed54846d759c3fad6a52aa23ae3aff4b8 | [
"MIT"
] | null | null | null | src/application.cpp | vladislavmarkov/sketchthis | 0d494c9ed54846d759c3fad6a52aa23ae3aff4b8 | [
"MIT"
] | null | null | null | #include "application.hpp"
#include <tuple>
#include <SDL.h>
#include "fps_ctl.hpp"
#include "reactor.hpp"
#include "renderer.hpp"
#include "sdl2.hpp"
#include "texture.hpp"
#include "tlsm.hpp"
#include "window.hpp"
namespace sketchthis {
application_t::application_t(std::string_view title)
{
const auto [x, y, w, h] = sdl2::get_widest_bounds();
_pitch = w * sdl2::pixel_size;
_data = std::vector<uint8_t>(w * h * sdl2::pixel_size, 0);
_window = std::make_unique<sdl2::window_t>(title, sdl2::rect_t{x, y, w, h});
_renderer = std::make_unique<sdl2::renderer_t>(_window.get());
_texture =
std::make_unique<sdl2::texture_t>(_renderer.get(), sdl2::area_t{w, h});
sdl2::warp_mouse(_window.get(), sdl2::point_t{w / 2, h / 2});
// create state machine
_tlsm = std::make_unique<sm::tlsm_t>();
// associate state machine with application
_tlsm->set_app_ptr(this);
_tlsm->start();
}
application_t::~application_t() = default;
int
application_t::run()
{
// fps controller
fps_ctl_t fps_ctl;
// application loop
while (is_running()) {
handle_events(_reactor.get());
_reactor->on_draw_frame();
fps_ctl.update();
}
return EXIT_SUCCESS;
}
void
application_t::quit()
{
_running = false;
}
sm::tlsm_t*
application_t::tlsm()
{
return _tlsm.get();
}
void
application_t::set_reactor(std::unique_ptr<sdl2::reactor_t>&& reactor)
{
_reactor = std::move(reactor);
}
} // namespace sketchthis
| 20.324324 | 80 | 0.654255 | [
"vector"
] |
0c8d1ff310192ca57c0c371415a0801d4a3bf528 | 6,866 | cpp | C++ | Control/MV/mv.cpp | martinkro/tutorial-qt | 8685434520c6ab61691722aa06ca075f8ddbeacf | [
"MIT"
] | 2 | 2018-06-24T10:19:30.000Z | 2018-12-13T14:31:49.000Z | Control/MV/mv.cpp | martinkro/tutorial-qt | 8685434520c6ab61691722aa06ca075f8ddbeacf | [
"MIT"
] | null | null | null | Control/MV/mv.cpp | martinkro/tutorial-qt | 8685434520c6ab61691722aa06ca075f8ddbeacf | [
"MIT"
] | null | null | null | #include "mv.h"
#include <QStringListModel>
#include <QListView>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QLineEdit>
#include <QSlider>
#include <QInputDialog>
#include <QFileSystemModel>
#include <QTreeView>
#include <QStandardItemModel>
#include <QTableView>
#include <QProgressBar>
#include "spinboxdelegate.h"
#include "ProgressBarDelegate.h"
#include "gamelistitemview.h"
#include <QListWidget>
#include <QVBoxLayout>
MV::MV(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
//testQStringListModel();
//testQFileSystemModel();
//testSpinBoxDelegate();
testProgressBarDelegate();
//testQTableView();
//testQProgressBar();
//testQListViewWidget();
resize(300, 600);
}
void MV::testQListViewWidget()
{
QListWidget* list = new QListWidget(this);
QListWidgetItem *item = new QListWidgetItem();
item->setSizeHint(QSize(0, 65));
GameListItemView* myitem = new GameListItemView;
list->addItem(item);
list->setItemWidget(item, myitem);
QHBoxLayout* main = new QHBoxLayout;
main->addWidget(list);
setLayout(main);
}
void MV::testProgressBarDelegate()
{
QListView* listView = new QListView(this);
ProgressBarDelegate* pbDelegate = new ProgressBarDelegate(0);
QStandardItemModel* model = new QStandardItemModel(11, 1, listView);
model->setData(model->index(0, 0, QModelIndex()), 50);
model->setData(model->index(1, 0, QModelIndex()), 50);
model->setData(model->index(2, 0, QModelIndex()), 50);
model->setData(model->index(3, 0, QModelIndex()), 50);
model->setData(model->index(4, 0, QModelIndex()), 50);
model->setData(model->index(5, 0, QModelIndex()), 50);
model->setData(model->index(6, 0, QModelIndex()), 50);
model->setData(model->index(7, 0, QModelIndex()), 50);
model->setData(model->index(8, 0, QModelIndex()), 50);
model->setData(model->index(9, 0, QModelIndex()), 50);
model->setData(model->index(10, 0, QModelIndex()), 50);
listView->setModel(model);
listView->setItemDelegateForColumn(0, pbDelegate);
QSlider* slider = new QSlider(Qt::Horizontal, this);
connect(slider, &QSlider::valueChanged, [=](int value) {
model->setData(model->index(0, 0, QModelIndex()), value);
model->setData(model->index(1, 0, QModelIndex()), value);
model->setData(model->index(2, 0, QModelIndex()), value);
});
slider->setRange(0, 100);
slider->setValue(50);
QVBoxLayout* v = new QVBoxLayout;
v->addWidget(listView);
v->addWidget(slider);
setLayout(v);
}
void MV::testQProgressBar()
{
QProgressBar* x = new QProgressBar(this);
x->setFixedWidth(400);
x->setMaximum(100);
x->setMinimum(0);
x->setTextVisible(true);
x->setOrientation(Qt::Horizontal);
x->setValue(100);
x->setAlignment(Qt::AlignCenter);
x->setFormat("check %p%");
}
void MV::testQTableView()
{
// Create a new model
// QStandardItemModel(int rows, int columns, QObject * parent = 0)
auto model = new QStandardItemModel(4, 2, this);
// Attach the model to the view
QTableView* tableView = new QTableView(this);
tableView->setModel(model);
// Generate data
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 2; col++)
{
QModelIndex index
= model->index(row, col, QModelIndex());
// 0 for all data
model->setData(index, 0);
}
}
}
void MV::testQStringListModel()
{
QStringList data;
data << "Letter A" << "Letter B" << "Letter C";
auto model = new QStringListModel(this);
model->setStringList(data);
auto listView = new QListView(this);
listView->setModel(model);
QHBoxLayout *btnLayout = new QHBoxLayout;
QPushButton *insertBtn = new QPushButton(tr("insert"), this);
connect(insertBtn, &QPushButton::clicked, [=]() {
bool isOK;
QString text = QInputDialog::getText(this, "Insert",
"Please input new data:",
QLineEdit::Normal,
"You are inserting new data.",
&isOK);
if (isOK) {
QModelIndex currIndex = listView->currentIndex();
model->insertRows(currIndex.row(), 1);
model->setData(currIndex, text);
listView->edit(currIndex);
}
});
QPushButton *delBtn = new QPushButton(tr("Delete"), this);
connect(delBtn, &QPushButton::clicked, [=]() {
if (model->rowCount() > 1) {
model->removeRows(listView->currentIndex().row(), 1);
}
});
QPushButton *showBtn = new QPushButton(tr("Show"), this);
connect(showBtn, &QPushButton::clicked, [=]() {
QStringList data = model->stringList();
QString str;
foreach(QString s, data) {
str += s + "\n";
}
QMessageBox::information(this, "Data", str);
});
btnLayout->addWidget(insertBtn);
btnLayout->addWidget(delBtn);
btnLayout->addWidget(showBtn);
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(listView);
mainLayout->addLayout(btnLayout);
setLayout(mainLayout);
}
void MV::testQFileSystemModel()
{
auto model = new QFileSystemModel;
model->setRootPath(QDir::currentPath());
auto treeView = new QTreeView(this);
treeView->setModel(model);
treeView->setRootIndex(model->index(QDir::currentPath()));
QPushButton *mkdirButton = new QPushButton(tr("Make Directory..."), this);
QPushButton *rmButton = new QPushButton(tr("Remove"), this);
QHBoxLayout *buttonLayout = new QHBoxLayout;
buttonLayout->addWidget(mkdirButton);
buttonLayout->addWidget(rmButton);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(treeView);
layout->addLayout(buttonLayout);
setLayout(layout);
setWindowTitle("File System Model");
connect(mkdirButton, &QPushButton::clicked, [=]() {
QModelIndex index = treeView->currentIndex();
if (!index.isValid()) {
return;
}
QString dirName = QInputDialog::getText(this,
tr("Create Directory"),
tr("Directory name"));
if (!dirName.isEmpty()) {
if (!model->mkdir(index, dirName).isValid()) {
QMessageBox::information(this,
tr("Create Directory"),
tr("Failed to create the directory"));
}
}
});
connect(rmButton, &QPushButton::clicked, [=]() {
QModelIndex index = treeView->currentIndex();
if (!index.isValid()) {
return;
}
bool ok;
if (model->fileInfo(index).isDir()) {
ok = model->rmdir(index);
}
else {
ok = model->remove(index);
}
if (!ok) {
QMessageBox::information(this,
tr("Remove"),
tr("Failed to remove %1").arg(model->fileName(index)));
}
});
}
void MV::testSpinBoxDelegate()
{
QStringList data;
data << "0" << "1" << "2";
auto model = new QStringListModel(this);
model->setStringList(data);
auto listView = new QListView(this);
listView->setModel(model);
listView->setItemDelegate(new SpinBoxDelegate(listView));
QPushButton *btnShow = new QPushButton(tr("Show Model"), this);
//connect(btnShow, SIGNAL(clicked()),
// this, SLOT(showModel()));
QHBoxLayout *buttonLayout = new QHBoxLayout;
buttonLayout->addWidget(btnShow);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(listView);
layout->addLayout(buttonLayout);
setLayout(layout);
}
| 26.306513 | 75 | 0.692106 | [
"model"
] |
0c92c2791d0f0e8fd159050572c02d0e9e04a2d1 | 5,208 | cpp | C++ | test/lib/math/vector2_test.cpp | stuhacking/SGEngine-Cpp | bf531b7ba02a20a2c0d756f6422b68461095664a | [
"BSD-3-Clause"
] | 1 | 2015-12-17T15:13:53.000Z | 2015-12-17T15:13:53.000Z | test/lib/math/vector2_test.cpp | stuhacking/SGEngine-Cpp | bf531b7ba02a20a2c0d756f6422b68461095664a | [
"BSD-3-Clause"
] | null | null | null | test/lib/math/vector2_test.cpp | stuhacking/SGEngine-Cpp | bf531b7ba02a20a2c0d756f6422b68461095664a | [
"BSD-3-Clause"
] | null | null | null | //
// Vec2f Unit Tests
//
#include <gtest/gtest.h>
#include <cfloat>
#include "lib.h"
/*==========================
Vector property Tests
==========================*/
TEST (Vec2f_Test, Length) {
EXPECT_FLOAT_EQ(5.0f, Vec2f(3.0f, 4.0f).mag());
}
TEST (Vec2f_Test, Zero) {
Vec2f v = Vec2f(10.0f, 10.0f);
v.zero();
EXPECT_FLOAT_EQ(0.0f, v.mag());
}
TEST (Vec2f_Test, Normalize) {
Vec2f v = Vec2f(10.0f, 10.0f);
EXPECT_FLOAT_EQ(1.0f, v.normalize().mag());
v.normalizeSelf();
EXPECT_FLOAT_EQ(1.0f, v.mag());
}
TEST (Vec2f_Test, ClampLength) {
EXPECT_EQ(Vec2f(3.0f, 4.0f), Vec2f(6.0f, 8.0f).clampMag(5.0f));
EXPECT_EQ(Vec2f(3.0f, 4.0f), Vec2f(1.5f, 2.0f).clampMag(5.0f, 10.0f));
EXPECT_EQ(Vec2f(3.0f, 4.0f), Vec2f(3.0f, 4.0f).clampMag(2.0f, 8.0f));
Vec2f v = Vec2f(6.0f, 8.0f);
v.clampMagSelf(5.0f);
EXPECT_EQ(Vec2f(3.0f, 4.0f), v);
v = Vec2f(1.5f, 2.0f);
v.clampMagSelf(5.0f, 10.0f);
EXPECT_EQ(Vec2f(3.0f, 4.0f), v);
v = Vec2f(3.0f, 4.0f);
v.clampMagSelf(2.0f, 6.0f);
EXPECT_EQ(Vec2f(3.0f, 4.0f), v);
}
TEST (Vec2f_Test, Clamp) {
EXPECT_EQ(Vec2f(1.0f, 2.0f), Vec2f(2.0f, 2.0f).clamp(Vec2f(0.0f, 0.0f), Vec2f(1.0f, 10.0f)));
EXPECT_EQ(Vec2f(2.0f, 2.0f), Vec2f(1.0f, 1.0f).clamp(Vec2f(2.0f, 2.0f), Vec2f(4.0f, 5.0f)));
EXPECT_EQ(Vec2f(4.0f, 4.0f), Vec2f(4.0f, 4.0f).clamp(Vec2f(1.0f, 2.0f), Vec2f(6.0f, 7.0f)));
}
TEST (Vec2f_Test, ClampSelf) {
Vec2f v = Vec2f(2.0f, 2.0f);
v.clampSelf(Vec2f(0.0f, 0.0f), Vec2f(1.0f, 10.0f));
EXPECT_EQ(Vec2f(1.0f, 2.0f), v);
v = Vec2f(1.0f, 1.0f);
v.clampSelf(Vec2f(2.0f, 2.0f), Vec2f(4.0f, 5.0f));
EXPECT_EQ(Vec2f(2.0f, 2.0f), v);
v = Vec2f(4.0f, 4.0f);
v.clampSelf(Vec2f(1.0f, 2.0f), Vec2f(6.0f, 7.0f));
EXPECT_EQ(Vec2f(4.0f, 4.0f), v);
}
/*==========================
math Operator Tests
==========================*/
TEST (Vec2f_Test, Negate) {
EXPECT_EQ(Vec2f(-1.0f, 2.0f), -Vec2f(1.0f, -2.0f));
}
TEST (Vec2f_Test, Add) {
EXPECT_EQ(Vec2f(2.0f, 2.0f), Vec2f(2.0f, 2.0f) + Vec2f(0.0f, 0.0f));
EXPECT_EQ(Vec2f(2.0f, 2.0f), Vec2f(1.0f, 1.0f) + Vec2f(1.0f, 1.0f));
EXPECT_EQ(Vec2f(2.0f, 2.0f), Vec2f(3.0f, 1.0f) + Vec2f(-1.0f, 1.0f));
}
TEST (Vec2f_Test, Add_Equals) {
Vec2f v1 = Vec2f(2.0f, 1.0f);
v1 += Vec2f(1.0f, 1.0f);
EXPECT_EQ(Vec2f(3.0f, 2.0f), v1);
}
TEST (Vec2f_Test, Sub) {
EXPECT_EQ(Vec2f(2.0f, 2.0f), Vec2f(2.0f, 2.0f) - Vec2f(0.0f, 0.0f));
EXPECT_EQ(Vec2f(1.0f, 1.0f), Vec2f(2.0f, 2.0f) - Vec2f(1.0f, 1.0f));
EXPECT_EQ(Vec2f(2.0f, 2.0f), Vec2f(3.0f, 1.0f) - Vec2f(1.0f, -1.0f));
}
TEST (Vec2f_Test, Sub_Equals) {
Vec2f v1 = Vec2f(2.0f, 1.0f);
v1 -= Vec2f(1.0f, 1.0f);
EXPECT_EQ(Vec2f(1.0f, 0.0f), v1);
}
TEST (Vec2f_Test, Scale) {
EXPECT_EQ(Vec2f(0.0f, 0.0f), Vec2f(2.0f, 2.0f) * 0.0f);
EXPECT_EQ(Vec2f(2.0f, 2.0f), Vec2f(2.0f, 2.0f) * 1.0f);
EXPECT_EQ(Vec2f(4.0f, 3.0f), Vec2f(2.0f, 1.5f) * 2.0f);
EXPECT_EQ(Vec2f(-6.0f, 4.0f), Vec2f(3.0f, -2.0f) * -2.0f);
}
TEST (Vec2f_Test, Scale_Equals) {
Vec2f v1 = Vec2f(3.0f, 1.5f);
v1 *= 2.0f;
EXPECT_EQ(Vec2f(6.0f, 3.0f), v1);
}
TEST (Vec2f_Test, NonUniformScale) {
EXPECT_EQ(Vec2f(0.0f, 0.0f), Vec2f(2.0f, 2.0f) * Vec2f_Zero);
EXPECT_EQ(Vec2f(2.0f, 4.0f), Vec2f(2.0f, 2.0f) * Vec2f(1.0f, 2.0f));
EXPECT_EQ(Vec2f(4.0f, 2.0f), Vec2f(2.0f, 4.0f) * Vec2f(2.0f, 0.5f));
}
TEST (Vec2f_Test, NonUniformScale_Equals) {
Vec2f v1 = Vec2f(3.0f, 1.5f);
v1 *= Vec2f(1.5f, 2.0f);
EXPECT_EQ(Vec2f(4.5f, 3.0f), v1);
}
TEST (Vec2f_Test, Div) {
EXPECT_EQ(Vec2f(2.0f, 2.0f), Vec2f(2.0f, 2.0f) / 1.0f);
EXPECT_EQ(Vec2f(1.0f, 0.75f), Vec2f(2.0f, 1.5f) / 2.0f);
EXPECT_EQ(Vec2f(math::kInfty, math::kInfty), Vec2f(3.0f, 2.0f) / 0.0f);
EXPECT_EQ(Vec2f(math::kInfty, -math::kInfty), Vec2f(3.0f, -2.0f) / 0.0f);
}
TEST (Vec2f_Test, Div_Equals) {
Vec2f v1 = Vec2f(3.0f, 1.5f);
v1 /= 2.0f;
EXPECT_EQ(Vec2f(1.5f, 0.75f), v1);
}
TEST (Vec2f_Test, Dot) {
EXPECT_EQ(11.0f, Vec2f(1.0f, 2.0f).dot(Vec2f(3.0f, 4.0f)));
}
TEST (Vec2f_Test, Cross) {
EXPECT_EQ(27.0f, Vec2f(-1.0f, 7.0f).cross(Vec2f(-5.0f, 8.0f)));
}
TEST (Vec2f_Test, Mirror) {
EXPECT_EQ(Vec2f(0.0f, -1.0f), Vec2f(0.0f, 1.0f).mirror(Vec2f(1.0f, 0.0f)));
EXPECT_EQ(Vec2f(4.0f, -6.0f), Vec2f(-6.0f, 4.0f).mirror(Vec2f(0.5f, 0.5f).normalize()));
}
/*==========================
Convenience Tests
==========================*/
TEST (Vec2f_Test, Operator_Index) {
Vec2f v = Vec2f(10.0f, 5.0f);
EXPECT_FLOAT_EQ(10.0f, v[0]);
EXPECT_FLOAT_EQ(5.0f, v[1]);
}
TEST (Vec2f_Test, Operator_Index_Set) {
Vec2f v = Vec2f(10.0f, 5.0f);
v[0] = 2.0f;
v[1] = 3.0f;
EXPECT_FLOAT_EQ(2.0f, v[0]);
EXPECT_FLOAT_EQ(3.0f, v[1]);
}
TEST (Vec2f_Test, Comparison) {
EXPECT_TRUE(Vec2f(1.0f, 1.0f) == Vec2f(1.0f, 1.0f));
EXPECT_FALSE(Vec2f(1.0f, 2.0f) != Vec2f(1.0f, 2.0f));
EXPECT_TRUE(Vec2f(1.0f, 2.0f) != Vec2f(3.0f, 4.0f));
EXPECT_FALSE(Vec2f(1.0f, 2.0f) == Vec2f(3.0f, 4.0f));
EXPECT_TRUE(Vec2f(1.245f, 2.345f).compare(Vec2f(1.24f, 2.34f), 0.01f));
EXPECT_FALSE(Vec2f(1.245f, 2.345f).compare(Vec2f(1.24f, 2.34f), 0.001f));
}
| 25.782178 | 97 | 0.569508 | [
"vector"
] |
0c9570c12bfcd96154523bd84c2765bcf2daa1ab | 5,049 | hxx | C++ | include/nifty/graph/graph_maps.hxx | konopczynski/nifty | dc02ac60febaabfaf9b2ee5a854bb61436ebdc97 | [
"MIT"
] | 38 | 2016-06-29T07:42:50.000Z | 2021-12-09T09:25:25.000Z | include/nifty/graph/graph_maps.hxx | tbullmann/nifty | 00119fd4753817b931272d6d3120b6ebd334882a | [
"MIT"
] | 62 | 2016-07-27T16:07:53.000Z | 2022-03-30T17:24:36.000Z | include/nifty/graph/graph_maps.hxx | tbullmann/nifty | 00119fd4753817b931272d6d3120b6ebd334882a | [
"MIT"
] | 20 | 2016-01-25T21:21:52.000Z | 2021-12-09T09:25:16.000Z | #pragma once
#include "nifty/xtensor/xtensor.hxx"
namespace nifty{
namespace graph{
namespace graph_maps{
template<class G, class T>
struct NodeMap : public std::vector<T>{
NodeMap( const G & g, const T & val)
: std::vector<T>( g.nodeIdUpperBound()+1, val){
}
NodeMap( const G & g)
: std::vector<T>( g.nodeIdUpperBound()+1){
}
NodeMap( )
: std::vector<T>( ){
}
// graph has been modified
void insertedNodes(const uint64_t nodeId, const T & insertValue = T()){
if(nodeId == this->size()){
this->push_back(insertValue);
}
else if(nodeId > this->size()){
this->resize(nodeId + 1, insertValue);
}
}
};
/**
* @brief Multiband node map
* @details Sometimes we need to hold not a single scalar,
* but a fixed length vector for each node.
* The return type of operator[] is a tiny proxy
* object holding the vector.
*
*
* @tparam G GraphType4
* @tparam T ValueType
*/
template<class G, class T>
struct MultibandNodeMap
{
public:
class Proxy{
public:
Proxy(T * ptr, const std::size_t size)
: ptr_(ptr),
size_(size){
}
const T & operator[](const std::size_t i)const{
return ptr_[i];
}
T & operator[](const std::size_t i){
return ptr_[i];
}
private:
T * ptr_;
std::size_t size_;
};
class ConstProxy{
public:
ConstProxy(const T * ptr, const std::size_t size)
: ptr_(ptr),
size_(size){
}
const T & operator[](const std::size_t i)const{
return ptr_[i];
}
const T & operator[](const std::size_t i){
return ptr_[i];
}
private:
const T * ptr_;
std::size_t size_;
};
MultibandNodeMap( const G & g, const std::size_t nChannels)
: nChannels_(nChannels),
data_((g.nodeIdUpperBound()+1)*nChannels){
}
MultibandNodeMap( const G & g, const std::size_t nChannels, const T & val)
: nChannels_(nChannels),
data_((g.nodeIdUpperBound()+1)*nChannels, val){
}
Proxy operator[](const uint64_t nodeIndex){
return Proxy(data_.data() + nodeIndex*nChannels_, nChannels_);
}
ConstProxy operator[](const uint64_t nodeIndex)const{
return ConstProxy(data_.data() + nodeIndex*nChannels_, nChannels_);
}
const std::size_t numberOfChannels()const{
return nChannels_;
}
private:
std::vector<T> data_;
std::size_t nChannels_;
};
template<class ARRAY>
struct MultibandArrayViewNodeMap
{
public:
typedef typename ARRAY::value_type value_type;
typedef typename ARRAY::reference reference;
typedef typename ARRAY::const_reference const_reference;
class Proxy{
public:
Proxy(ARRAY & array, const uint64_t node)
: array_(&array),
node_(node){
}
const_reference operator[](const std::size_t i)const{
return array_->operator()(node_, i);
}
reference operator[](const std::size_t i){
return array_->operator()(node_, i);
}
std::size_t size()const{
return array_->shape(1);
}
private:
uint64_t node_;
ARRAY * array_;
};
class ConstProxy{
public:
ConstProxy(const ARRAY & array, const uint64_t node)
: array_(&array),
node_(node){
}
const_reference operator[](const std::size_t i)const{
return array_->operator()(node_, i);
}
const_reference operator[](const std::size_t i){
return array_->operator()(node_, i);
}
std::size_t size()const{
return array_->shape(1);
}
private:
uint64_t node_;
const ARRAY * array_;
};
MultibandArrayViewNodeMap(const ARRAY & array)
: nChannels_(array.shape()[1]),
array_(array){
}
Proxy operator[](const uint64_t nodeIndex){
return Proxy(array_, nodeIndex);
}
ConstProxy operator[](const uint64_t nodeIndex)const{
return ConstProxy(array_, nodeIndex);
}
const std::size_t numberOfChannels()const{
return nChannels_;
}
private:
const ARRAY & array_;
std::size_t nChannels_;
};
template<class G, class T>
struct EdgeMap : public std::vector<T>{
EdgeMap( const G & g, const T & val)
: std::vector<T>( g.edgeIdUpperBound()+1, val){
}
EdgeMap( const G & g)
: std::vector<T>( g.edgeIdUpperBound()+1){
}
EdgeMap( )
: std::vector<T>( ){
}
// graph has been modified
void insertedEdges(const uint64_t edgeId, const T & insertValue = T()){
if(edgeId == this->size()){
this->push_back(insertValue);
}
else if(edgeId > this->size()){
this->resize(edgeId + 1, insertValue);
}
}
};
} // namespace nifty::graph::graph_maps
} // namespace nifty::graph
} // namespace nifty
| 23.16055 | 78 | 0.574767 | [
"object",
"shape",
"vector"
] |
0ca779df613cd5eff861f62f4500763ad51f55d8 | 28,895 | cpp | C++ | src/hagglekernel/ProtocolManager.cpp | eebenson/haggle | c461667b079934fa03b1ebb472ca67641a3d1140 | [
"Apache-2.0"
] | null | null | null | src/hagglekernel/ProtocolManager.cpp | eebenson/haggle | c461667b079934fa03b1ebb472ca67641a3d1140 | [
"Apache-2.0"
] | null | null | null | src/hagglekernel/ProtocolManager.cpp | eebenson/haggle | c461667b079934fa03b1ebb472ca67641a3d1140 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2008-2009 Uppsala University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <libcpphaggle/Platform.h>
#include "ProtocolManager.h"
#include "Protocol.h"
#include "ProtocolUDP.h"
#include "ProtocolTCP.h"
#if defined(OS_UNIX)
#include "ProtocolLOCAL.h"
#endif
#if defined(ENABLE_MEDIA)
#include "ProtocolMedia.h"
#endif
#if defined(ENABLE_BLUETOOTH)
#include "ProtocolRFCOMM.h"
#endif
#include <haggleutils.h>
ProtocolManager::ProtocolManager(HaggleKernel * _kernel) :
Manager("ProtocolManager", _kernel), tcpServerPort(TCP_DEFAULT_PORT),
tcpBacklog(TCP_BACKLOG_SIZE), killer(NULL)
{
}
ProtocolManager::~ProtocolManager()
{
while (!protocol_registry.empty()) {
Protocol *p = (*protocol_registry.begin()).second;
protocol_registry.erase(p->getId());
delete p;
}
if (killer) {
killer->stop();
HAGGLE_DBG("Joined with protocol killer thread\n");
delete killer;
}
}
bool ProtocolManager::init_derived()
{
int ret;
#define __CLASS__ ProtocolManager
ret = setEventHandler(EVENT_TYPE_DATAOBJECT_SEND, onSendDataObject);
if (ret < 0) {
HAGGLE_ERR("Could not register event handler\n");
return false;
}
ret = setEventHandler(EVENT_TYPE_LOCAL_INTERFACE_UP, onLocalInterfaceUp);
if (ret < 0) {
HAGGLE_ERR("Could not register event handler\n");
return false;
}
ret = setEventHandler(EVENT_TYPE_LOCAL_INTERFACE_DOWN, onLocalInterfaceDown);
if (ret < 0) {
HAGGLE_ERR("Could not register event handler\n");
return false;
}
ret = setEventHandler(EVENT_TYPE_NEIGHBOR_INTERFACE_DOWN, onNeighborInterfaceDown);
if (ret < 0) {
HAGGLE_ERR("Could not register event handler\n");
return false;
}
ret = setEventHandler(EVENT_TYPE_NODE_UPDATED, onNodeUpdated);
if (ret < 0) {
HAGGLE_ERR("Could not register event handler\n");
return false;
}
delete_protocol_event = registerEventType("ProtocolManager protocol deletion event", onDeleteProtocolEvent);
add_protocol_event = registerEventType("ProtocolManager protocol addition event", onAddProtocolEvent);
send_data_object_actual_event = registerEventType("ProtocolManager send data object actual event", onSendDataObjectActual);
protocol_shutdown_timeout_event = registerEventType("ProtocolManager Protocol Shutdown Timeout Event", onProtocolShutdownTimeout);
if (protocol_shutdown_timeout_event < 0) {
HAGGLE_ERR("Could not register protocol shutdown timeout event\n");
return false;
}
#ifdef DEBUG
ret = setEventHandler(EVENT_TYPE_DEBUG_CMD, onDebugCmdEvent);
if (ret < 0) {
HAGGLE_ERR("Could not register event handler\n");
return false;
}
#endif
return true;
}
#ifdef DEBUG
void ProtocolManager::onDebugCmdEvent(Event *e)
{
if (e->getDebugCmd()->getType() != DBG_CMD_PRINT_PROTOCOLS)
return;
protocol_registry_t::iterator it;
for (it = protocol_registry.begin(); it != protocol_registry.end(); it++) {
Protocol *p = (*it).second;
printf("Protocol \'%s\':\n", p->getName());
printf("\tcommunication interfaces: %s <-> %s\n",
p->getLocalInterface() ? p->getLocalInterface()->getIdentifierStr() : "None",
p->getPeerInterface() ? p->getPeerInterface()->getIdentifierStr() : "None");
if (p->getQueue() && p->getQueue()->size()) {
printf("\tQueue:\n");
p->getQueue()->print();
} else {
printf("\tQueue: empty\n");
}
}
}
#endif /* DEBUG */
void ProtocolManager::onAddProtocolEvent(Event *e)
{
registerProtocol(static_cast<Protocol *>(e->getData()));
}
bool ProtocolManager::registerProtocol(Protocol *p)
{
protocol_registry_t::iterator it;
if (!p)
return false;
// We are in shutdown, so do not accept this protocol to keep running.
if (getState() > MANAGER_STATE_RUNNING) {
p->shutdown();
if (!p->isDetached()) {
p->join();
HAGGLE_DBG("Joined with protocol %s\n", p->getName());
}
return false;
}
if (protocol_registry.insert(make_pair(p->getId(), p)).second == false) {
HAGGLE_ERR("Protocol %s already registered!\n", p->getName());
return false;
}
p->setRegistered();
HAGGLE_DBG("Protocol %s registered\n", p->getName());
return true;
}
void ProtocolManager::onNodeUpdated(Event *e)
{
if (!e)
return;
NodeRef& node = e->getNode();
NodeRefList& nl = e->getNodeList();
if (!node)
return;
// Check if there are any protocols that are associated with the updated nodes.
for (NodeRefList::iterator it = nl.begin(); it != nl.end(); it++) {
NodeRef& old_node = *it;
old_node.lock();
for (InterfaceRefList::const_iterator it2 = old_node->getInterfaces()->begin();
it2 != old_node->getInterfaces()->end(); it2++) {
const InterfaceRef& iface = *it2;
for (protocol_registry_t::iterator it3 = protocol_registry.begin(); it3 != protocol_registry.end(); it3++) {
Protocol *p = (*it3).second;
if (p->isForInterface(iface)) {
HAGGLE_DBG("Setting peer node %s on protocol %s\n", node->getName().c_str(), p->getName());
p->setPeerNode(node);
}
}
}
old_node.unlock();
}
}
void ProtocolManager::onDeleteProtocolEvent(Event *e)
{
Protocol *p;
if (!e)
return;
p = static_cast < Protocol * >(e->getData());
if (!p)
return;
if (protocol_registry.find(p->getId()) == protocol_registry.end()) {
HAGGLE_ERR("Trying to unregister protocol %s, which is not registered\n", p->getName());
return;
}
protocol_registry.erase(p->getId());
HAGGLE_DBG("Removing protocol %s\n", p->getName());
/*
Either we join the thread here, or we detach it when we start it.
*/
if (!p->isDetached()) {
p->join();
HAGGLE_DBG("Joined with protocol %s\n", p->getName());
delete p;
}
if (getState() == MANAGER_STATE_SHUTDOWN) {
if (protocol_registry.empty()) {
unregisterWithKernel();
}
#if defined(DEBUG)
else {
for (protocol_registry_t::iterator it = protocol_registry.begin(); it != protocol_registry.end(); it++) {
Protocol *p = (*it).second;
HAGGLE_DBG("Protocol \'%s\' still registered\n", p->getName());
}
}
#endif
}
}
void ProtocolManager::onProtocolShutdownTimeout(Event *e)
{
HAGGLE_DBG("Checking for still registered protocols: num registered=%lu\n",
protocol_registry.size());
if (!protocol_registry.empty()) {
while (!protocol_registry.empty()) {
Protocol *p = (*protocol_registry.begin()).second;
protocol_registry.erase(p->getId());
HAGGLE_DBG("Protocol \'%s\' still registered after shutdown. Detaching it!\n", p->getName());
// We are not going to join with these threads, so we detach.
if (p->isRunning()) {
// In detached state, the protocol will delete itself
// once it stops running.
p->detach();
p->cancel();
// We have to clear the protocol's send queue as it may contain
// data objects whose send verdict managersa are
// waiting for. Clearing the queue will evict all data objects
// from its queue with a FAILURE verdict.
p->closeAndClearQueue();
} else {
delete p;
}
}
unregisterWithKernel();
}
}
/* Close all server protocols so that we cannot create new clients. */
void ProtocolManager::onPrepareShutdown()
{
HAGGLE_DBG("%lu protocols are registered, shutting down servers.\n", protocol_registry.size());
// Go through the registered protocols
protocol_registry_t::iterator it = protocol_registry.begin();
for (; it != protocol_registry.end(); it++) {
// Tell the server protocol to shutdown, with the exception of the
// application IPC protocol
if ((*it).second->isServer() && !((*it).second->isApplication())) {
(*it).second->shutdown();
}
}
signalIsReadyForShutdown();
}
/*
Do not stop protocols until we are in shutdown, because other managers
may rely on protocol services while they are preparing for shutdown.
*/
void ProtocolManager::onShutdown()
{
HAGGLE_DBG("%lu protocols are registered.\n", protocol_registry.size());
if (protocol_registry.empty()) {
unregisterWithKernel();
} else {
// Go through the registered protocols
protocol_registry_t::iterator it = protocol_registry.begin();
for (; it != protocol_registry.end(); it++) {
// Tell this protocol we're shutting down!
(*it).second->shutdown();
}
// In case some protocols refuse to shutdown, launch a thread that sleeps for a while
// before it schedules an event that forcefully kills the protocols.
// Note that we need to use this thread to implement a timeout because in shutdown
// the event queue executes as fast as it can, hence delayed events do not work.
killer = new ProtocolKiller(protocol_shutdown_timeout_event, 15000, kernel);
if (killer) {
killer->start();
}
}
}
#if defined(OS_WINDOWS_XP) && !defined(DEBUG)
// This is here to avoid a warning with catching the exception in the functions
// below.
#pragma warning( push )
#pragma warning( disable: 4101 )
#endif
class LocalByTypeCriteria : public InterfaceStore::Criteria
{
Interface::Type_t type;
public:
LocalByTypeCriteria(Interface::Type_t _type) : type(_type) {}
virtual bool operator() (const InterfaceRecord& ir) const
{
if (ir.iface->getType() == type && ir.iface->isLocal() && ir.iface->isUp())
return true;
return false;
}
};
class PeerParentCriteria : public InterfaceStore::Criteria
{
InterfaceRef parent;
InterfaceRef peerIface;
public:
PeerParentCriteria(const InterfaceRef& iface) : parent(NULL), peerIface(iface) {}
virtual bool operator() (const InterfaceRecord& ir)
{
if (parent && ir.iface && parent == ir.iface && ir.iface->isUp())
return true;
if (ir.iface == peerIface)
parent = ir.parent;
return false;
}
};
Protocol *ProtocolManager::getSenderProtocol(const ProtType_t type, const InterfaceRef& peerIface)
{
Protocol *p = NULL;
protocol_registry_t::iterator it = protocol_registry.begin();
InterfaceRef localIface = NULL;
InterfaceRefList ifl;
// Go through the list of current protocols until we find one:
for (; it != protocol_registry.end(); it++) {
p = (*it).second;
// Is this protocol the one we're interested in?
if (p->isSender() && type == p->getType() &&
p->isForInterface(peerIface) &&
!p->isGarbage() && !p->isDone()) {
break;
}
p = NULL;
}
// Did we find a protocol?
if (p == NULL) {
// Nope. Find a suitable local interface to associate with the protocol
kernel->getInterfaceStore()->retrieve(PeerParentCriteria(peerIface), ifl);
// Parent interface found?
if (ifl.size() != 0) {
// Create a new one:
switch (type) {
#if defined(ENABLE_BLUETOOTH)
case Protocol::TYPE_RFCOMM:
// We always grab the first local Bluetooth interface
p = new ProtocolRFCOMMSender(ifl.pop(), peerIface, RFCOMM_DEFAULT_CHANNEL, this);
break;
#endif
case Protocol::TYPE_TCP:
// TODO: should retrieve local interface by querying for the parent interface of the peer.
p = new ProtocolTCPSender(ifl.pop(), peerIface, TCP_DEFAULT_PORT, this);
break;
case Protocol::TYPE_LOCAL:
// FIXME: shouldn't be able to get here!
HAGGLE_DBG("No local sender protocol running!\n");
break;
case Protocol::TYPE_UDP:
// FIXME: shouldn't be able to get here!
HAGGLE_DBG("No UDP sender protocol running!\n");
break;
#if defined(ENABLE_MEDIA)
case Protocol::TYPE_MEDIA:
p = new ProtocolMedia(NULL, peerIface, this);
break;
#endif
default:
HAGGLE_DBG("Unable to create client sender protocol for type %ld\n", type);
break;
}
}
// Were we successful?
if (p) {
if (!p->init() || !registerProtocol(p)) {
HAGGLE_ERR("Could not initialize protocol %s\n", p->getName());
delete p;
p = NULL;
}
}
}
// Return any found or created protocol:
return p;
}
// FIXME: seems to be unused. Delete?
Protocol *ProtocolManager::getReceiverProtocol(const ProtType_t type, const InterfaceRef& iface)
{
Protocol *p = NULL;
protocol_registry_t::iterator it = protocol_registry.begin();
// For an explanation of how this function works, see getSenderProtocol
for (; it != protocol_registry.end(); it++) {
p = (*it).second;
if (p->isReceiver() && type == p->getType() && p->isForInterface(iface) && !p->isGarbage() && !p->isDone()) {
if (type == Protocol::TYPE_UDP || type == Protocol::TYPE_LOCAL)
break;
else if (p->isConnected())
break;
}
p = NULL;
}
if (p == NULL) {
switch (type) {
#if defined(ENABLE_BLUETOOTH)
case Protocol::TYPE_RFCOMM:
// FIXME: write a correct version of this line:
p = NULL;//new ProtocolRFCOMMReceiver(0, iface, RFCOMM_DEFAULT_CHANNEL, this);
break;
#endif
case Protocol::TYPE_TCP:
// FIXME: write a correct version of this line:
p = NULL;//new ProtocolTCPReceiver(0, (struct sockaddr *) NULL, iface, this);
break;
#if defined(ENABLE_MEDIA)
case Protocol::TYPE_MEDIA:
// does not apply to protocol media
break;
#endif
default:
HAGGLE_DBG("Unable to create client receiver protocol for type %ld\n", type);
break;
}
if (p) {
if (!p->init() || !registerProtocol(p)) {
HAGGLE_ERR("Could not initialize or register protocol %s\n", p->getName());
delete p;
p = NULL;
}
}
}
return p;
}
Protocol *ProtocolManager::getServerProtocol(const ProtType_t type, const InterfaceRef& iface)
{
Protocol *p = NULL;
protocol_registry_t::iterator it = protocol_registry.begin();
// For an explanation of how this function works, see getSenderProtocol
for (; it != protocol_registry.end(); it++) {
p = (*it).second;
// Assume that we are only looking for a specific type of server
// protocol, i.e., there is only one server for multiple interfaces
// of the same type
if (p->isServer() && type == p->getType())
break;
p = NULL;
}
if (p == NULL) {
switch (type) {
#if defined(ENABLE_BLUETOOTH)
case Protocol::TYPE_RFCOMM:
p = new ProtocolRFCOMMServer(iface, this);
break;
#endif
case Protocol::TYPE_TCP:
p = new ProtocolTCPServer(iface, this, tcpServerPort, tcpBacklog);
break;
#if defined(ENABLE_MEDIA)
case Protocol::TYPE_MEDIA:
/*
if (!strstr(iface->getMacAddrStr(), "00:00:00:00")) {
p = new ProtocolMediaServer(iface, this);
}
*/
break;
#endif
default:
HAGGLE_DBG("Unable to create server protocol for type %ld\n", type);
break;
}
if (p) {
if (!p->init() || !registerProtocol(p)) {
HAGGLE_ERR("Could not initialize or register protocol %s\n", p->getName());
delete p;
p = NULL;
}
}
}
return p;
}
#if defined(OS_WINDOWS_XP) && !defined(DEBUG)
#pragma warning( pop )
#endif
void ProtocolManager::onWatchableEvent(const Watchable& wbl)
{
protocol_registry_t::iterator it = protocol_registry.begin();
HAGGLE_DBG("Receive on %s\n", wbl.getStr());
// Go through each protocol in turn:
for (; it != protocol_registry.end(); it++) {
Protocol *p = (*it).second;
// Did the Watchable belong to this protocol
if (p->hasWatchable(wbl)) {
// Let the protocol handle whatever happened.
p->handleWatchableEvent(wbl);
return;
}
}
HAGGLE_DBG("Was asked to handle a socket no protocol knows about!\n");
// Should not happen, but needs to be dealt with because if it isn't,
// the kernel will call us again in an endless loop!
kernel->unregisterWatchable(wbl);
CLOSE_SOCKET(wbl.getSocket());
}
void ProtocolManager::onLocalInterfaceUp(Event *e)
{
if (!e)
return;
InterfaceRef iface = e->getInterface();
if (!iface)
return;
const Addresses *adds = iface->getAddresses();
for (Addresses::const_iterator it = adds->begin() ; it != adds->end() ; it++) {
switch((*it)->getType()) {
case Address::TYPE_IPV4:
#if defined(ENABLE_IPv6)
case Address::TYPE_IPV6:
#endif
getServerProtocol(Protocol::TYPE_TCP, iface);
return;
#if defined(ENABLE_BLUETOOTH)
case Address::TYPE_BLUETOOTH:
getServerProtocol(Protocol::TYPE_RFCOMM, iface);
return;
#endif
#if defined(ENABLE_MEDIA)
// FIXME: should probably separate loop interfaces from media interfaces somehow...
case Address::TYPE_FILEPATH:
getServerProtocol(Protocol::TYPE_MEDIA, iface);
return;
#endif
default:
break;
}
}
HAGGLE_DBG("Interface with no known address type - no server started\n");
}
void ProtocolManager::onLocalInterfaceDown(Event *e)
{
InterfaceRef& iface = e->getInterface();
if (!iface)
return;
HAGGLE_DBG("Local interface [%s] went down, checking for associated protocols\n", iface->getIdentifierStr());
// Go through the protocol list
protocol_registry_t::iterator it = protocol_registry.begin();
for (;it != protocol_registry.end(); it++) {
Protocol *p = (*it).second;
/*
Never bring down our application IPC protocol when
application interfaces go down (i.e., applications deregister).
*/
if (p->getLocalInterface()->getType() == Interface::TYPE_APPLICATION_PORT) {
continue;
}
// Is the associated with this protocol?
if (p->isForInterface(iface)) {
/*
NOTE: I am unsure about how this should be done. Either:
p->handleInterfaceDown();
or:
protocol_list_mutex->unlock();
p->handleInterfaceDown();
return;
or:
protocol_list_mutex->unlock();
p->handleInterfaceDown();
protocol_list_mutex->lock();
(*it) = protocol_registry.begin();
The first has the benefit that it doesn't assume that there is
only one protocol per interface, but causes the deletion of the
interface to happen some time in the future (as part of event
queue processing), meaning the protocol will still be around,
and may be given instructions before being deleted, even when
it is incapable of handling instructions, because it should
have been deleted.
The second has the benefit that if the protocol tries to have
itself deleted, it happens immediately (because there is no
deadlock), but also assumes that there is only one protocol per
interface, which may or may not be true.
The third is a mix, and has the pros of both the first and the
second, but has the drawback that it repeatedly locks and
unlocks the mutex, and also needs additional handling so it
won't go into an infinite loop (a set of protocols that have
already handled the interface going down, for instance).
For now, I've chosen the first solution.
*/
// Tell the protocol to handle this:
HAGGLE_DBG("Shutting down protocol %s because local interface [%s] went down\n",
p->getName(), iface->getIdentifierStr());
p->handleInterfaceDown(iface);
}
}
}
void ProtocolManager::onNeighborInterfaceDown(Event *e)
{
InterfaceRef& iface = e->getInterface();
if (!iface)
return;
HAGGLE_DBG("Neighbor interface [%s] went away, checking for associated protocols\n", iface->getIdentifierStr());
// Go through the protocol list
protocol_registry_t::iterator it = protocol_registry.begin();
for (;it != protocol_registry.end(); it++) {
Protocol *p = (*it).second;
/*
Never bring down our application IPC protocol when
application interfaces go down (i.e., applications deregister).
*/
if (p->getLocalInterface()->getType() == Interface::TYPE_APPLICATION_PORT) {
continue;
}
// Is the associated with this protocol?
if (p->isClient() && p->isForInterface(iface)) {
HAGGLE_DBG("Shutting down protocol %s because neighbor interface [%s] went away\n",
p->getName(), iface->getIdentifierStr());
p->handleInterfaceDown(iface);
}
}
}
void ProtocolManager::onSendDataObject(Event *e)
{
/*
Since other managers might want to modify the data object before it is
actually sent, we delay the actual send processing by sending a private
event to ourselves, effectively rescheduling our own processing of this
event to occur just after this event.
*/
kernel->addEvent(new Event(send_data_object_actual_event, e->getDataObject(), e->getNodeList()));
}
void ProtocolManager::onSendDataObjectActual(Event *e)
{
int numTx = 0;
if (!e || !e->hasData())
return;
// Get a copy to work with
DataObjectRef dObj = e->getDataObject();
// Get target list:
NodeRefList *targets = (e->getNodeList()).copy();
if (!targets) {
HAGGLE_ERR("no targets in data object when sending\n");
return;
}
unsigned int numTargets = targets->size();
// Go through all targets:
while (!targets->empty()) {
// A current target reference
NodeRef targ = targets->pop();
if (!targ) {
HAGGLE_ERR("Target num %u is NULL!\n",
numTargets);
numTargets--;
continue;
}
HAGGLE_DBG("Sending to target %s \n",
targ->getName().c_str());
// If we are going to loop through the node's interfaces, we need to lock the node.
targ.lock();
const InterfaceRefList *interfaces = targ->getInterfaces();
// Are there any interfaces here?
if (interfaces == NULL || interfaces->size() == 0) {
// No interfaces for target, so we generate a
// send failure event and skip the target
HAGGLE_DBG("Target %s has no interfaces\n", targ->getName().c_str());
targ.unlock();
kernel->addEvent(new Event(EVENT_TYPE_DATAOBJECT_SEND_FAILURE, dObj, targ));
numTargets--;
continue;
}
/*
Find the target interface that suits us best
(we assume that for any remote target
interface we have a corresponding local interface).
*/
InterfaceRef peerIface = NULL;
bool done = false;
InterfaceRefList::const_iterator it = interfaces->begin();
//HAGGLE_DBG("Target node %s has %lu interfaces\n", targ->getName().c_str(), interfaces->size());
for (; it != interfaces->end() && done == false; it++) {
InterfaceRef iface = *it;
// If this interface is up:
if (iface->isUp()) {
if (iface->getAddresses()->empty()) {
HAGGLE_DBG("Interface %s:%s has no addresses - IGNORING.\n",
iface->getTypeStr(), iface->getIdentifierStr());
continue;
}
switch (iface->getType()) {
#if defined(ENABLE_BLUETOOTH)
case Interface::TYPE_BLUETOOTH:
/*
Select Bluetooth only if there are no Ethernet or WiFi
interfaces.
*/
if (!iface->getAddress<BluetoothAddress>()) {
HAGGLE_DBG("Interface %s:%s has no Bluetooth address - IGNORING.\n",
iface->getTypeStr(), iface->getIdentifierStr());
break;
}
if (!peerIface)
peerIface = iface;
else if (peerIface->getType() != Interface::TYPE_ETHERNET &&
peerIface->getType() != Interface::TYPE_WIFI)
peerIface = iface;
break;
#endif
#if defined(ENABLE_ETHERNET)
case Interface::TYPE_ETHERNET:
/*
Let Ethernet take priority over the other types.
*/
if (!iface->getAddress<IPv4Address>()
#if defined(ENABLE_IPv6)
&& !iface->getAddress<IPv6Address>()
#endif
) {
HAGGLE_DBG("Interface %s:%s has no IPv4 or IPv6 addresses - IGNORING.\n",
iface->getTypeStr(), iface->getIdentifierStr());
break;
}
if (!peerIface)
peerIface = iface;
else if (peerIface->getType() == Interface::TYPE_BLUETOOTH ||
peerIface->getType() == Interface::TYPE_WIFI)
peerIface = iface;
break;
case Interface::TYPE_WIFI:
if (!iface->getAddress<IPv4Address>()
#if defined(ENABLE_IPv6)
&& !iface->getAddress<IPv6Address>()
#endif
) {
HAGGLE_DBG("Interface %s:%s has no IPv4 or IPv6 addresses - IGNORING.\n",
iface->getTypeStr(), iface->getIdentifierStr());
break;
}
if (!peerIface)
peerIface = iface;
else if (peerIface->getType() == Interface::TYPE_BLUETOOTH &&
peerIface->getType() != Interface::TYPE_ETHERNET)
peerIface = iface;
break;
#endif // ENABLE_ETHERNET
case Interface::TYPE_APPLICATION_PORT:
case Interface::TYPE_APPLICATION_LOCAL:
if (!iface->getAddress<IPv4Address>()
#if defined(ENABLE_IPv6)
&& !iface->getAddress<IPv6Address>()
#endif
) {
HAGGLE_DBG("Interface %s:%s has no IPv4 or IPv6 addresses - IGNORING.\n",
iface->getTypeStr(), iface->getIdentifierStr());
break;
}
// Not much choise here.
if (targ->getType() == Node::TYPE_APPLICATION) {
peerIface = iface;
done = true;
} else {
HAGGLE_DBG("ERROR: Node %s is not application, but its interface is\n",
targ->getName().c_str());
}
break;
#if defined(ENABLE_MEDIA)
case Interface::TYPE_MEDIA:
break;
#endif
case Interface::TYPE_UNDEFINED:
default:
break;
}
} else {
//HAGGLE_DBG("Send interface %s was down, ignoring...\n", iface->getIdentifierStr());
}
}
// We are done looking for a suitable send interface
// among the node's interface list, so now we unlock
// the node.
targ.unlock();
if (!peerIface) {
HAGGLE_DBG("No send interface found for target %s. Aborting send of data object!!!\n",
targ->getName().c_str());
// Failed to send to this target, send failure event:
kernel->addEvent(new Event(EVENT_TYPE_DATAOBJECT_SEND_FAILURE, dObj, targ));
numTargets--;
continue;
}
// Ok, we now have a target and a suitable interface,
// now we must figure out a protocol to use when we
// transmit to that interface
Protocol *p = NULL;
// We make a copy of the addresses list here so that we do not
// have to lock the peer interface while we call getSenderProtocol().
// getSenderProtocol() might do a lookup in the interface store in order
// to find the local interface which is parent of the peer interface.
// This might cause a deadlock in case another thread also does a lookup
// in the interface store while we hold the interface lock.
const Addresses *adds = peerIface->getAddresses()->copy();
// Figure out a suitable protocol given the addresses associated
// with the selected interface
for (Addresses::const_iterator it = adds->begin(); p == NULL && it != adds->end(); it++) {
switch ((*it)->getType()) {
#if defined(ENABLE_BLUETOOTH)
case Address::TYPE_BLUETOOTH:
p = getSenderProtocol(Protocol::TYPE_RFCOMM, peerIface);
break;
#endif
case Address::TYPE_IPV4:
#if defined(ENABLE_IPv6)
case Address::TYPE_IPV6:
#endif
if (peerIface->isApplication()) {
#ifdef USE_UNIX_APPLICATION_SOCKET
p = getSenderProtocol(Protocol::TYPE_LOCAL, peerIface);
#else
p = getSenderProtocol(Protocol::TYPE_UDP, peerIface);
#endif
}
else
p = getSenderProtocol(Protocol::TYPE_TCP, peerIface);
break;
#if defined(ENABLE_MEDIA)
case Address::TYPE_FILEPATH:
p = getSenderProtocol(Protocol::TYPE_MEDIA, peerIface);
break;
#endif
default:
break;
}
}
delete adds;
// Send data object to the found protocol:
if (p) {
if (p->sendDataObject(dObj, targ, peerIface)) {
numTx++;
} else {
// Failed to send to this target, send failure event:
kernel->addEvent(new Event(EVENT_TYPE_DATAOBJECT_SEND_FAILURE, dObj, targ));
}
} else {
HAGGLE_DBG("No suitable protocol found for interface %s:%s!\n",
peerIface->getTypeStr(), peerIface->getIdentifierStr());
// Failed to send to this target, send failure event:
kernel->addEvent(new Event(EVENT_TYPE_DATAOBJECT_SEND_FAILURE, dObj, targ));
}
numTargets--;
}
/* HAGGLE_DBG("Scheduled %d data objects\n", numTx); */
delete targets;
}
void ProtocolManager::onConfig(Metadata *m)
{
Metadata *pm = m->getMetadata("TCPServer");
if (pm) {
const char *param = pm->getParameter("port");
if (param) {
char *endptr = NULL;
unsigned short port = (unsigned short)strtoul(param, &endptr, 10);
if (endptr && endptr != param) {
tcpServerPort = port;
LOG_ADD("# %s: setting TCP server port to %u\n", getName(), tcpServerPort);
}
}
param = pm->getParameter("backlog");
if (param) {
char *endptr = NULL;
int backlog = (int)strtol(param, &endptr, 10);
if (endptr && endptr != param && backlog > 0) {
tcpBacklog = backlog;
LOG_ADD("# %s: setting TCP backlog to %d\n", getName(), tcpBacklog);
}
}
}
}
| 28.162768 | 131 | 0.665859 | [
"object"
] |
0ca8a0b5fbdfac2997883a9730dab671a290ce41 | 22,302 | hpp | C++ | utility/PtrVector.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 82 | 2016-04-18T03:59:06.000Z | 2019-02-04T11:46:08.000Z | utility/PtrVector.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 265 | 2016-04-19T17:52:43.000Z | 2018-10-11T17:55:08.000Z | utility/PtrVector.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 68 | 2016-04-18T05:00:34.000Z | 2018-10-30T12:41:02.000Z | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
**/
#ifndef QUICKSTEP_UTILITY_PTR_VECTOR_HPP_
#define QUICKSTEP_UTILITY_PTR_VECTOR_HPP_
#include <iterator>
#include <vector>
#include "utility/Macros.hpp"
#include "glog/logging.h"
namespace quickstep {
/** \addtogroup Utility
* @{
*/
/**
* @brief A vector of pointers to objects, which are automatically deleted when
* the PtrVector goes out of scope.
**/
template <typename T, bool null_allowed = false>
class PtrVector {
public:
// TODO(chasseur): Attempt some template magic to get rid of the duplicated
// code between iterator classes.
/**
* @brief Iterator over the contents of a PtrVector.
* @warning If null_allowed is true, then always check that isNull() is false
* before attempting to dereference.
**/
class PtrVectorIterator : public std::iterator<std::random_access_iterator_tag, T> {
public:
typedef typename std::iterator<std::random_access_iterator_tag, T>::difference_type difference_type;
PtrVectorIterator() {
}
PtrVectorIterator(const PtrVectorIterator& other)
: internal_iterator_(other.internal_iterator_) {
}
PtrVectorIterator& operator=(const PtrVectorIterator& other) {
if (this != &other) {
internal_iterator_ = other.internal_iterator_;
}
return *this;
}
// Comparisons.
inline bool operator==(const PtrVectorIterator& other) const {
return internal_iterator_ == other.internal_iterator_;
}
inline bool operator!=(const PtrVectorIterator& other) const {
return internal_iterator_ != other.internal_iterator_;
}
inline bool operator<(const PtrVectorIterator& other) const {
return internal_iterator_ < other.internal_iterator_;
}
inline bool operator<=(const PtrVectorIterator& other) const {
return internal_iterator_ <= other.internal_iterator_;
}
inline bool operator>(const PtrVectorIterator& other) const {
return internal_iterator_ > other.internal_iterator_;
}
inline bool operator>=(const PtrVectorIterator& other) const {
return internal_iterator_ >= other.internal_iterator_;
}
// Increment/decrement.
inline PtrVectorIterator& operator++() {
++internal_iterator_;
return *this;
}
PtrVectorIterator operator++(int) {
PtrVectorIterator result(*this);
++(*this);
return result;
}
inline PtrVectorIterator& operator--() {
--internal_iterator_;
return *this;
}
PtrVectorIterator operator--(int) {
PtrVectorIterator result(*this);
--(*this);
return result;
}
// Compound assignment.
inline PtrVectorIterator& operator+=(difference_type n) {
internal_iterator_ += n;
return *this;
}
inline PtrVectorIterator& operator-=(difference_type n) {
internal_iterator_ -= n;
return *this;
}
// Note: + operator with difference_type on the left is defined out-of-line.
PtrVectorIterator operator+(difference_type n) const {
return PtrVectorIterator(internal_iterator_ + n);
}
PtrVectorIterator operator-(difference_type n) const {
return PtrVectorIterator(internal_iterator_ - n);
}
difference_type operator-(const PtrVectorIterator &other) const {
return PtrVectorIterator(internal_iterator_ - other.internal_iterator_);
}
// Dereference.
/**
* @brief Check whether the element at the current iterator position is
* NULL.
* @return Whether the element at the current iterator position is NULL.
**/
inline bool isNull() const {
return (null_allowed && (*internal_iterator_ == nullptr));
}
/**
* @brief Delete the element at the current iterator position and replace
* it with a new value.
*
* @param value_ptr The new value to place at the current position. The
* PtrVector takes ownership of the pointed-to value.
**/
void replaceValue(T *value_ptr) {
if (!null_allowed) {
DCHECK(value_ptr != nullptr);
}
if (!null_allowed || (*internal_iterator_ != nullptr)) {
delete *internal_iterator_;
}
*internal_iterator_ = value_ptr;
}
/**
* @brief Replace the element at the current iterator position, and
* release ownership and return the original value.
*
* @param value_ptr The new value to place at the current position. The
* PtrVector takes ownership of the pointed-to value.
* @return A pointer to the original value at the current position. The
* PtrVector no longer owns the pointed-to object, which should now
* be managed by the caller.
**/
T* releaseAndReplaceElement(T *value_ptr) {
if (!null_allowed) {
DCHECK(value_ptr != nullptr);
}
T *original_value = *internal_iterator_;
*internal_iterator_ = value_ptr;
return original_value;
}
inline T& operator*() const {
if (null_allowed) {
DCHECK(!isNull());
}
return **internal_iterator_;
}
inline T* operator->() const {
if (null_allowed) {
DCHECK(!isNull());
}
return *internal_iterator_;
}
// Offset dereference. Potentially unsafe if null_allowed.
T& operator[](difference_type n) const {
if (null_allowed) {
DCHECK(internal_iterator_[n] != nullptr);
}
return *(internal_iterator_[n]);
}
private:
explicit PtrVectorIterator(const typename std::vector<T*>::iterator &internal_iterator)
: internal_iterator_(internal_iterator) {
}
typename std::vector<T*>::iterator internal_iterator_;
friend class PtrVector;
friend class PtrVectorConstIterator;
};
/**
* @brief Const iterator over the contents of a PtrVector.
* @warning If null_allowed is true, then always check that isNull() is false
* before attempting to dereference.
**/
class PtrVectorConstIterator : public std::iterator<std::input_iterator_tag, const T> {
public:
typedef typename std::iterator<std::input_iterator_tag, T>::difference_type difference_type;
PtrVectorConstIterator() {
}
PtrVectorConstIterator(const PtrVectorConstIterator& other)
: internal_iterator_(other.internal_iterator_) {
}
PtrVectorConstIterator(const PtrVectorIterator& other) // NOLINT(runtime/explicit) - allow implicit conversion
: internal_iterator_(other.internal_iterator_) {
}
PtrVectorConstIterator& operator=(const PtrVectorConstIterator& other) {
if (this != &other) {
internal_iterator_ = other.internal_iterator_;
}
return *this;
}
PtrVectorConstIterator& operator=(const PtrVectorIterator& other) {
internal_iterator_ = other.internal_iterator_;
return *this;
}
// Comparisons.
inline bool operator==(const PtrVectorConstIterator& other) const {
return internal_iterator_ == other.internal_iterator_;
}
inline bool operator!=(const PtrVectorConstIterator& other) const {
return internal_iterator_ != other.internal_iterator_;
}
inline bool operator<(const PtrVectorConstIterator& other) const {
return internal_iterator_ < other.internal_iterator_;
}
inline bool operator<=(const PtrVectorConstIterator& other) const {
return internal_iterator_ <= other.internal_iterator_;
}
inline bool operator>(const PtrVectorConstIterator& other) const {
return internal_iterator_ > other.internal_iterator_;
}
inline bool operator>=(const PtrVectorConstIterator& other) const {
return internal_iterator_ >= other.internal_iterator_;
}
// Increment/decrement.
inline PtrVectorConstIterator& operator++() {
++internal_iterator_;
return *this;
}
PtrVectorConstIterator operator++(int) {
PtrVectorConstIterator result(*this);
++(*this);
return result;
}
inline PtrVectorConstIterator& operator--() {
--internal_iterator_;
return *this;
}
PtrVectorConstIterator operator--(int) {
PtrVectorConstIterator result(*this);
--(*this);
return result;
}
// Compound assignment.
inline PtrVectorConstIterator& operator+=(difference_type n) {
internal_iterator_ += n;
return *this;
}
inline PtrVectorConstIterator& operator-=(difference_type n) {
internal_iterator_ -= n;
return *this;
}
// Note: + operator with difference_type on the left is defined out-of-line.
PtrVectorConstIterator operator+(difference_type n) const {
return PtrVectorConstIterator(internal_iterator_ + n);
}
PtrVectorConstIterator operator-(difference_type n) const {
return PtrVectorConstIterator(internal_iterator_ - n);
}
difference_type operator-(const PtrVectorConstIterator &other) const {
return PtrVectorConstIterator(internal_iterator_ - other.internal_iterator_);
}
// Dereference.
/**
* @brief Check whether the element at the current iterator position is
* NULL.
* @return Whether the element at the current iterator position is NULL.
**/
inline bool isNull() const {
return (null_allowed && (*internal_iterator_ == nullptr));
}
inline const T& operator*() const {
if (null_allowed) {
DCHECK(!isNull());
}
return **internal_iterator_;
}
inline const T* operator->() const {
if (null_allowed) {
DCHECK(!isNull());
}
return *internal_iterator_;
}
// Offset dereference. Potentially unsafe if null_allowed.
const T& operator[](difference_type n) const {
if (null_allowed) {
DCHECK(internal_iterator_[n] != nullptr);
}
return *(internal_iterator_[n]);
}
private:
explicit PtrVectorConstIterator(const typename std::vector<T*>::const_iterator &internal_iterator)
: internal_iterator_(internal_iterator) {
}
typename std::vector<T*>::const_iterator internal_iterator_;
friend class PtrVector;
};
/**
* @brief Input iterator over the contents of a PtrVector which automatically
* skips over NULL entries.
**/
class PtrVectorConstSkipIterator : public std::iterator<std::input_iterator_tag, const T> {
public:
typedef typename std::iterator<std::input_iterator_tag, T>::difference_type difference_type;
PtrVectorConstSkipIterator()
: parent_vector_(nullptr) {
}
PtrVectorConstSkipIterator(const PtrVectorConstSkipIterator& other)
: internal_iterator_(other.internal_iterator_),
parent_vector_(other.parent_vector_) {
}
PtrVectorConstSkipIterator& operator=(const PtrVectorConstSkipIterator& other) {
if (this != &other) {
internal_iterator_ = other.internal_iterator_;
parent_vector_ = other.parent_vector_;
}
return *this;
}
// Comparisons.
inline bool operator==(const PtrVectorConstSkipIterator& other) const {
return internal_iterator_ == other.internal_iterator_;
}
inline bool operator!=(const PtrVectorConstSkipIterator& other) const {
return internal_iterator_ != other.internal_iterator_;
}
inline bool operator<(const PtrVectorConstSkipIterator& other) const {
return internal_iterator_ < other.internal_iterator_;
}
inline bool operator<=(const PtrVectorConstSkipIterator& other) const {
return internal_iterator_ <= other.internal_iterator_;
}
inline bool operator>(const PtrVectorConstSkipIterator& other) const {
return internal_iterator_ > other.internal_iterator_;
}
inline bool operator>=(const PtrVectorConstSkipIterator& other) const {
return internal_iterator_ >= other.internal_iterator_;
}
// Increment/decrement.
inline PtrVectorConstSkipIterator& operator++() {
++internal_iterator_;
DCHECK(parent_vector_ != nullptr);
while (internal_iterator_ != parent_vector_->end()) {
if (*internal_iterator_ != nullptr) {
break;
}
++internal_iterator_;
}
return *this;
}
PtrVectorConstSkipIterator operator++(int) {
PtrVectorConstSkipIterator result(*this);
++(*this);
return result;
}
inline const T& operator*() const {
return **internal_iterator_;
}
inline const T* operator->() const {
return *internal_iterator_;
}
private:
explicit PtrVectorConstSkipIterator(const typename std::vector<T*>::const_iterator &internal_iterator,
const std::vector<T*> *parent_vector)
: internal_iterator_(internal_iterator), parent_vector_(parent_vector) {
DCHECK(parent_vector_ != nullptr);
while ((internal_iterator_ != parent_vector_->end()) && (*internal_iterator_ == nullptr)) {
++internal_iterator_;
}
}
typename std::vector<T*>::const_iterator internal_iterator_;
const std::vector<T*> *parent_vector_;
friend class PtrVector;
};
typedef typename std::vector<T*>::size_type size_type;
typedef T value_type;
typedef PtrVectorIterator iterator;
typedef PtrVectorConstIterator const_iterator;
typedef PtrVectorConstSkipIterator const_skip_iterator;
PtrVector() {
}
~PtrVector() {
for (typename std::vector<T*>::iterator it = internal_vector_.begin();
it != internal_vector_.end();
++it) {
if (!null_allowed || (*it != nullptr)) {
delete *it;
}
}
}
inline size_type size() const {
return internal_vector_.size();
}
inline size_type max_size() const {
return internal_vector_.max_size();
}
inline size_type capacity() const {
return internal_vector_.capacity();
}
inline bool empty() const {
return internal_vector_.empty();
}
/**
* @brief Check whether this vector contains any actual objects. Unlike
* empty(), this returns true if the vector has some elements, but
* they are all NULL.
*
* @return Whether this PtrVector is empty of actual objects.
**/
bool emptyNullCheck() const {
if (null_allowed) {
for (typename std::vector<T*>::const_iterator it = internal_vector_.begin();
it != internal_vector_.end();
++it) {
if (*it != nullptr) {
return false;
}
}
return true;
} else {
return empty();
}
}
inline void reserve(size_type n) {
internal_vector_.reserve(n);
}
// Iterators
iterator begin() {
return iterator(internal_vector_.begin());
}
iterator end() {
return iterator(internal_vector_.end());
}
const_iterator begin() const {
return const_iterator(internal_vector_.begin());
}
const_iterator end() const {
return const_iterator(internal_vector_.end());
}
/**
* @brief Get an iterator at the beginning of this PtrVector which
* automatically skips over NULL entries.
*
* @return An iterator at the beginning of this PtrVector which automatically
* skips over NULL entries.
**/
const_skip_iterator begin_skip() const {
return const_skip_iterator(internal_vector_.begin(), &internal_vector_);
}
/**
* @brief Get an iterator at one past the end of this PtrVector which
* automatically skips over NULL entries.
*
* @return An iterator at one past the end of this PtrVector which
* automatically skips over NULL entries.
**/
const_skip_iterator end_skip() const {
return const_skip_iterator(internal_vector_.end(), &internal_vector_);
}
/**
* @brief Check whether the element at the specified position is NULL.
*
* @param n The position in this PtrVector to check.
* @return Whether the element at position n is NULL.
**/
inline bool elementIsNull(const size_type n) const {
if (null_allowed && (internal_vector_[n] == nullptr)) {
return true;
} else {
return false;
}
}
/**
* @brief Check whether the element at the specified position is NULL.
* @note This is similar to elementIsNull(), but uses std::vector::at(),
* which throws std::out_of_range exceptions.
*
* @param n The position in this PtrVector to check.
* @return Whether the element at position n is NULL.
**/
inline bool elementIsNullAt(const size_type n) const {
if (null_allowed && (internal_vector_.at(n) == nullptr)) {
return true;
} else {
return false;
}
}
inline T& front() {
if (null_allowed) {
typename std::vector<T*>::iterator it = internal_vector_.begin();
while ((it != internal_vector_.end()) && (*it == nullptr)) {
++it;
}
return **it;
} else {
return *(internal_vector_.front());
}
}
inline const T& front() const {
if (null_allowed) {
typename std::vector<T*>::const_iterator it = internal_vector_.begin();
while ((it != internal_vector_.end()) && (*it == nullptr)) {
++it;
}
return **it;
} else {
return *(internal_vector_.front());
}
}
inline T& back() {
if (null_allowed) {
typename std::vector<T*>::reverse_iterator it = internal_vector_.rbegin();
while ((it != internal_vector_.rend()) && (*it == nullptr)) {
++it;
}
return **it;
} else {
return *(internal_vector_.back());
}
}
inline const T& back() const {
if (null_allowed) {
typename std::vector<T*>::const_reverse_iterator it = internal_vector_.rbegin();
while ((it != internal_vector_.rend()) && (*it == nullptr)) {
++it;
}
return **it;
} else {
return *(internal_vector_.back());
}
}
inline T& operator[](const size_type n) {
if (null_allowed) {
DCHECK(!elementIsNull(n));
}
return *(internal_vector_[n]);
}
inline const T& operator[](const size_type n) const {
if (null_allowed) {
DCHECK(!elementIsNull(n));
}
return *(internal_vector_[n]);
}
inline T& at(const size_type n) {
if (null_allowed) {
DCHECK(!elementIsNullAt(n));
}
return *(internal_vector_.at(n));
}
inline const T& at(const size_type n) const {
if (null_allowed) {
DCHECK(!elementIsNullAt(n));
}
return *(internal_vector_.at(n));
}
inline void push_back(T *value_ptr) {
if (!null_allowed) {
DCHECK(value_ptr != nullptr);
}
internal_vector_.push_back(value_ptr);
}
/**
* @brief Delete an element at the specified index and replace it with a new
* value.
*
* @param n The position of the element to replace.
* @param value_ptr The new value to place at position n. This PtrVector
* takes ownership of the pointed-to value.
**/
void replaceElement(const size_type n, T *value_ptr) {
if (!null_allowed) {
DCHECK(value_ptr != nullptr);
}
if (!null_allowed || (internal_vector_[n] != nullptr)) {
delete internal_vector_[n];
}
internal_vector_[n] = value_ptr;
}
/**
* @brief Replace an element at the specified index with a new value, and
* release ownership and return the original value.
*
* @param n The position of the element to replace.
* @param value_ptr The new value to place at position n. This PtrVector
* takes ownership of the pointed-to value.
* @return A pointer to the original value at position n. This PtrVector no
* longer owns the pointed-to object, which should now be managed
* by the caller.
**/
T* releaseAndReplaceElement(const size_type n, T *value_ptr) {
if (!null_allowed) {
DCHECK(value_ptr != nullptr);
}
T *original_value = internal_vector_[n];
internal_vector_[n] = value_ptr;
return original_value;
}
/**
* @brief Delete an element and set it to null. Only usable if null_allowed
* is true.
*
* @param n The position of the element to delete.
**/
void deleteElement(const size_type n) {
DCHECK(null_allowed);
if (internal_vector_[n] != nullptr) {
delete internal_vector_[n];
internal_vector_[n] = nullptr;
}
}
/**
* @brief Delete the last element and truncate the vector. Only usable if
* null_allowed is false.
**/
void removeBack() {
DCHECK(!null_allowed);
DCHECK(!internal_vector_.empty());
delete internal_vector_.back();
internal_vector_.resize(internal_vector_.size() - 1);
}
/**
* @brief Get a const reference to the internal vector of pointers.
*
* @return A const reference to the internal vector of pointers.
**/
const std::vector<T*>& getInternalVector() const {
return internal_vector_;
}
/**
* @brief Get a mutable pointer to the internal vector of pointers.
* @warning Only call this if you really know what you are doing.
*
* @return A mutable pointer to the internal vector of pointers.
**/
std::vector<T*>* getInternalVectorMutable() {
return &internal_vector_;
}
private:
std::vector<T*> internal_vector_;
DISALLOW_COPY_AND_ASSIGN(PtrVector);
};
template <typename T>
typename PtrVector<T>::PtrVectorIterator operator+(
const typename PtrVector<T>::PtrVectorIterator::difference_type n,
const typename PtrVector<T>::PtrVectorIterator &it) {
return it + n;
}
/** @} */
} // namespace quickstep
#endif // QUICKSTEP_UTILITY_PTR_VECTOR_HPP_
| 28.888601 | 115 | 0.658416 | [
"object",
"vector"
] |
0cad017bc33de62519daf8cc09d0e7b56a6db4cc | 4,057 | hpp | C++ | external/opencv3.4.1/include/opencv2/face/face_alignment.hpp | Keneyr/Tracking | 412b288c5f7401b69b4eb3813bdd178e894ad104 | [
"MIT"
] | 33 | 2018-12-10T10:54:35.000Z | 2022-01-17T11:35:00.000Z | external/opencv3.4.1/include/opencv2/face/face_alignment.hpp | Keneyr/Tracking | 412b288c5f7401b69b4eb3813bdd178e894ad104 | [
"MIT"
] | 2 | 2018-07-26T10:36:24.000Z | 2019-03-08T12:38:49.000Z | external/opencv3.4.1/include/opencv2/face/face_alignment.hpp | Keneyr/Tracking | 412b288c5f7401b69b4eb3813bdd178e894ad104 | [
"MIT"
] | 8 | 2018-07-05T06:46:55.000Z | 2020-07-24T19:23:59.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef __OPENCV_FACE_ALIGNMENT_HPP__
#define __OPENCV_FACE_ALIGNMENT_HPP__
#include "facemark.hpp"
namespace cv{
namespace face{
class CV_EXPORTS_W FacemarkKazemi : public Algorithm
{
public:
struct CV_EXPORTS Params
{
/**
* \brief Constructor
*/
Params();
/// cascade_depth This stores the deapth of cascade used for training.
unsigned long cascade_depth;
/// tree_depth This stores the max height of the regression tree built.
unsigned long tree_depth;
/// num_trees_per_cascade_level This stores number of trees fit per cascade level.
unsigned long num_trees_per_cascade_level;
/// learning_rate stores the learning rate in gradient boosting, also reffered as shrinkage.
float learning_rate;
/// oversampling_amount stores number of initialisations used to create training samples.
unsigned long oversampling_amount;
/// num_test_coordinates stores number of test coordinates.
unsigned long num_test_coordinates;
/// lambda stores a value to calculate probability of closeness of two coordinates.
float lambda;
/// num_test_splits stores number of random test splits generated.
unsigned long num_test_splits;
/// configfile stores the name of the file containing the values of training parameters
String configfile;
};
static Ptr<FacemarkKazemi> create(const FacemarkKazemi::Params ¶meters = FacemarkKazemi::Params());
virtual ~FacemarkKazemi();
/// @brief training the facemark model, input are the file names of image list and landmark annotation
virtual void training(String imageList, String groundTruth)=0;
/** @brief This function is used to train the model using gradient boosting to get a cascade of regressors
*which can then be used to predict shape.
*@param images A vector of type cv::Mat which stores the images which are used in training samples.
*@param landmarks A vector of vectors of type cv::Point2f which stores the landmarks detected in a particular image.
*@param scale A size of type cv::Size to which all images and landmarks have to be scaled to.
*@param configfile A variable of type std::string which stores the name of the file storing parameters for training the model.
*@param modelFilename A variable of type std::string which stores the name of the trained model file that has to be saved.
*@returns A boolean value. The function returns true if the model is trained properly or false if it is not trained.
*/
virtual bool training(std::vector<Mat>& images, std::vector< std::vector<Point2f> >& landmarks,std::string configfile,Size scale,std::string modelFilename = "face_landmarks.dat")=0;
/** @brief This function is used to load the trained model..
*@param filename A variable of type cv::String which stores the name of the file in which trained model is stored.
*/
virtual void loadModel(String filename)=0;
/** @brief This functions retrieves a centered and scaled face shape, according to the bounding rectangle.
*@param image A variable of type cv::InputArray which stores the image whose landmarks have to be found
*@param faces A variable of type cv::InputArray which stores the bounding boxes of faces found in a given image.
*@param landmarks A variable of type cv::InputOutputArray which stores the landmarks of all the faces found in the image
*/
virtual bool fit( InputArray image, InputArray faces, InputOutputArray landmarks )=0;//!< from many ROIs
/// set the custom face detector
virtual bool setFaceDetector(bool(*f)(InputArray , OutputArray, void*), void* userData)=0;
/// get faces using the custom detector
virtual bool getFaces(InputArray image, OutputArray faces)=0;
};
}} // namespace
#endif
| 56.347222 | 185 | 0.731575 | [
"shape",
"vector",
"model"
] |
0cb60f49e4980515bd33a8dcea6e3eed51f6da2a | 10,023 | cpp | C++ | src/gvt/render/data/reader/ObjReader.cpp | TACC/GravIT | 0a79dc74036c11669075198e01b30a92a8150693 | [
"BSD-3-Clause"
] | 24 | 2015-08-13T20:16:11.000Z | 2020-03-02T17:03:17.000Z | src/gvt/render/data/reader/ObjReader.cpp | TACC/GravIT | 0a79dc74036c11669075198e01b30a92a8150693 | [
"BSD-3-Clause"
] | 16 | 2015-10-16T03:42:37.000Z | 2019-08-07T21:54:47.000Z | src/gvt/render/data/reader/ObjReader.cpp | TACC/GravIT | 0a79dc74036c11669075198e01b30a92a8150693 | [
"BSD-3-Clause"
] | 8 | 2015-08-25T15:07:35.000Z | 2019-03-10T11:00:32.000Z | /* =======================================================================================
This file is released as part of GraviT - scalable, platform independent ray tracing
tacc.github.io/GraviT
Copyright 2013-2015 Texas Advanced Computing Center, The University of Texas at Austin
All rights reserved.
Licensed under the BSD 3-Clause License, (the "License"); you may not use this file
except in compliance with the License.
A copy of the License is included with this software in the file LICENSE.
If your copy does not contain the License, you may obtain a copy of the License at:
http://opensource.org/licenses/BSD-3-Clause
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
limitations under the License.
GraviT is funded in part by the US National Science Foundation under awards ACI-1339863,
ACI-1339881 and ACI-1339840
======================================================================================= */
/*
* File: ObjReader.cpp
* Author: jbarbosa
*
* Created on January 22, 2015, 1:36 PM
*/
#include <gvt/render/data/reader/ObjReader.h>
#include <gvt/core/Debug.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <tiny_obj_loader.h>
using namespace gvt::render::data::domain::reader;
using namespace gvt::render::data::primitives;
namespace gvt {
namespace render {
namespace data {
namespace domain {
namespace reader {
gvt::core::Vector<std::string> split(const std::string &s, char delim, gvt::core::Vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
if (item.length() > 0) {
elems.push_back(item);
}
}
return elems;
}
}
}
}
}
} // namespace reader} namespace domain} namespace data} namespace render} namespace gvt}
ObjReader::ObjReader(const std::string filename, int material_type) : computeNormals(false) {
// GVT_ASSERT(filename.size() > 0, "Invalid filename");
// std::fstream file;
// file.open(filename.c_str());
// GVT_ASSERT(file.good(), "Error loading obj file " << filename);
// Material *m = new Material();
// m->type = LAMBERT;
// //m->type = EMBREE_MATERIAL_MATTE;
// m->kd = glm::vec3(1.0,1.0, 1.0);
// m->ks = glm::vec3(1.0,1.0,1.0);
// m->alpha = 0.5;
//
// //m->type = EMBREE_MATERIAL_METAL;
// //copper metal
// m->eta = glm::vec3(.19,1.45, 1.50);
// m->k = glm::vec3(3.06,2.40, 1.88);
// m->roughness = 0.05;
// objMesh = new Mesh(m);
// while (file.good()) {
// std::string line;
// std::getline(file, line);
//
// if (line.find("#") == 0) continue;
//
// if (line.find("v") == 0) {
// parseVertex(line);
// continue;
// }
// if (line.find("vn") == 0) {
// parseVertexNormal(line);
// continue;
// }
// if (line.find("vt") == 0) {
// parseVertexTexture(line);
// continue;
// }
// if (line.find("f") == 0) {
// parseFace(line);
// continue;
// }
// }
std::size_t found = filename.find_last_of("/");
std::string path = filename.substr(0, found + 1);
gvt::core::Vector<tinyobj::shape_t> shapes;
gvt::core::Vector<tinyobj::material_t> materials;
// gvt::core::Vector<pathtr::math::vec3<float> > vertices;
// gvt::core::Vector<pathtr::math::vec3<int> > faces;
// gvt::core::Vector<pathtr::math::vec3<float> > normals;
// gvt::core::Vector<size_t> cindex;
// gvt::core::Vector<pathtr::material> color;
// gvt::core::Vector<size_t> lfaces;
// bbox bb;
std::string err;
if (!tinyobj::LoadObj(shapes, materials, err, filename.c_str(), path.c_str())) {
std::cerr << err << std::endl;
exit(1);
}
// color.resize(materials.size());
// ;
// for (size_t i = 0; i < materials.size(); i++) {
// pathtr::material &m = color[i];
// if (materials[i].name.find("light") != std::string::npos) {
// m._light = true;
// }
//
// m.illum = materials[i].illum;
//
// m.ambient = pathtr::rgb(materials[i].ambient[0], materials[i].ambient[1], materials[i].ambient[2]);
// m.diffuse = pathtr::rgb(materials[i].diffuse[0], materials[i].diffuse[1], materials[i].diffuse[2]);
// m.specular = pathtr::rgb(materials[i].specular[0], materials[i].specular[1], materials[i].specular[2]);
// m.transmittance =
// pathtr::rgb(materials[i].transmittance[0], materials[i].transmittance[1], materials[i].transmittance[2]);
// m.emission = pathtr::rgb(materials[i].emission[0], materials[i].emission[1], materials[i].emission[2]);
// m.shininess = materials[i].shininess;
// m.ior = materials[i].ior;
// m.dissolve = materials[i].dissolve;
// }
if (materials.size()) {
objMesh = new Mesh(nullptr);
objMesh->materials.reserve(materials.size());
for (std::size_t i = 0; i < materials.size(); ++i) {
Material *m = new Material;
objMesh->materials.push_back(m);
const tinyobj::material_t &mat = materials[i];
m->ka = glm::vec3(mat.ambient[0], mat.ambient[1], mat.ambient[2]);
m->kd = glm::vec3(mat.diffuse[0], mat.diffuse[1], mat.diffuse[2]);
m->ks = glm::vec3(mat.specular[0], mat.specular[1], mat.specular[2]);
m->type = material_type;
}
} else {
objMesh = new Mesh(new Material);
}
size_t vertices_offset = 0;
for (size_t i = 0; i < shapes.size(); i++) {
for (size_t v = 0; v < shapes[i].mesh.positions.size() / 3; v++) {
objMesh->vertices.push_back(glm::vec3(shapes[i].mesh.positions[3 * v + 0], shapes[i].mesh.positions[3 * v + 1],
shapes[i].mesh.positions[3 * v + 2]));
objMesh->boundingBox.expand(objMesh->vertices[objMesh->vertices.size() - 1]);
if (!shapes[i].mesh.normals.empty()) {
glm::vec3 n(shapes[i].mesh.normals[3 * v + 0], shapes[i].mesh.normals[3 * v + 1],
shapes[i].mesh.normals[3 * v + 2]);
n = glm::normalize(n);
objMesh->normals.push_back(n);
}
}
for (size_t f = 0; f < shapes[i].mesh.indices.size() / 3; f++) {
objMesh->faces.push_back(Mesh::Face(vertices_offset + shapes[i].mesh.indices[3 * f + 0],
vertices_offset + shapes[i].mesh.indices[3 * f + 1],
vertices_offset + shapes[i].mesh.indices[3 * f + 2]));
if (materials.size()) {
Material *mat = objMesh->materials[shapes[i].mesh.material_ids[f]];
objMesh->faces_to_materials.push_back(mat);
}
// size_t midx = shapes[i].mesh.material_ids[f];
// cindex.push_back(midx);
// if (color[midx].light()) {
// lfaces.push_back(faces.size() - 1);
// }
}
vertices_offset += shapes[i].mesh.positions.size() / 3;
}
computeNormals = (objMesh->normals.size() == objMesh->vertices.size());
std::cout << "Found : " << objMesh->vertices.size() << " vertices" << std::endl;
std::cout << "Found : " << objMesh->normals.size() << " normals" << std::endl;
std::cout << "Found : " << objMesh->faces.size() << " normals" << std::endl;
std::cout << "Bound : " << objMesh->boundingBox.bounds_min << " x " << objMesh->boundingBox.bounds_max << std::endl;
std::cout << "Center : " << ((objMesh->boundingBox.bounds_min + objMesh->boundingBox.bounds_max) * .5f) << std::endl;
if (computeNormals) objMesh->generateNormals();
objMesh->computeBoundingBox();
}
void ObjReader::parseVertex(std::string line) {
gvt::core::Vector<std::string> elems;
split(line, ' ', elems);
GVT_ASSERT(elems.size() == 4, "Error parsing vertex");
objMesh->addVertex(glm::vec3(std::atof(elems[1].c_str()), std::atof(elems[2].c_str()), std::atof(elems[3].c_str())));
}
void ObjReader::parseVertexNormal(std::string line) {
gvt::core::Vector<std::string> elems;
split(line, ' ', elems);
GVT_ASSERT(elems.size() == 4, "Error parsing vertex normal");
objMesh->addNormal(glm::vec3(std::atof(elems[1].c_str()), std::atof(elems[2].c_str()), std::atof(elems[3].c_str())));
}
void ObjReader::parseVertexTexture(std::string line) {
gvt::core::Vector<std::string> elems;
split(line, ' ', elems);
GVT_ASSERT(elems.size() == 3, "Error parsing texture map");
objMesh->addTexUV(glm::vec3(std::atof(elems[1].c_str()), std::atof(elems[2].c_str()), 0));
}
void ObjReader::parseFace(std::string line) {
gvt::core::Vector<std::string> elems;
split(line, ' ', elems);
GVT_ASSERT(elems.size() == 4, "Error parsing face");
int v1, n1, t1;
int v2, n2, t2;
int v3, n3, t3;
v1 = n1 = t1 = 0;
v2 = n2 = t2 = 0;
v3 = n3 = t3 = 0;
/* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
if (std::strstr(elems[1].c_str(), "//")) {
std::sscanf(elems[1].c_str(), "%d//%d", &v1, &n1);
std::sscanf(elems[2].c_str(), "%d//%d", &v2, &n2);
std::sscanf(elems[3].c_str(), "%d//%d", &v3, &n3);
objMesh->addFaceToNormals(Mesh::FaceToNormals(n1 - 1, n2 - 1, n3 - 1));
} else if (std::sscanf(elems[1].c_str(), "%d/%d/%d", &v1, &t1, &n1) == 3) {
/* v/t/n */
std::sscanf(elems[2].c_str(), "%d/%d/%d", &v2, &t2, &n2);
std::sscanf(elems[3].c_str(), "%d/%d/%d", &v3, &t3, &n3);
objMesh->addFace(v1, v2, v3);
objMesh->addFaceToNormals(Mesh::FaceToNormals(n1 - 1, n2 - 1, n3 - 1));
} else if (std::sscanf(elems[1].c_str(), "%d/%d", &v1, &t1) == 2) {
/* v/t */
std::sscanf(elems[2].c_str(), "%d/%d", &v2, &t2);
std::sscanf(elems[3].c_str(), "%d/%d", &v3, &t3);
objMesh->addFace(v1, v2, v3);
computeNormals = true;
} else {
/* v */
std::sscanf(elems[1].c_str(), "%d", &v1);
std::sscanf(elems[2].c_str(), "%d", &v2);
std::sscanf(elems[3].c_str(), "%d", &v3);
computeNormals = true;
}
objMesh->addFace(v1, v2, v3);
}
ObjReader::~ObjReader() {}
| 35.045455 | 119 | 0.587648 | [
"mesh",
"render",
"vector"
] |
0cbf6095ec5df23fde9a5ba609437fbaba505a47 | 45,063 | cpp | C++ | src/mongo/unittest/dbclient_test.cpp | amidvidy/mongo-cxx-driver | e13b3e30547cd611c4a9bb723a2b4003c7bd2a4c | [
"Apache-2.0"
] | null | null | null | src/mongo/unittest/dbclient_test.cpp | amidvidy/mongo-cxx-driver | e13b3e30547cd611c4a9bb723a2b4003c7bd2a4c | [
"Apache-2.0"
] | null | null | null | src/mongo/unittest/dbclient_test.cpp | amidvidy/mongo-cxx-driver | e13b3e30547cd611c4a9bb723a2b4003c7bd2a4c | [
"Apache-2.0"
] | null | null | null | /* Copyright 2014 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mongo/platform/basic.h"
#include <boost/scoped_ptr.hpp>
#include <algorithm>
#include <functional>
#include <list>
#include <string>
#include <vector>
#include "mongo/stdx/functional.h"
#include "mongo/unittest/integration_test.h"
#include "mongo/util/fail_point_service.h"
#include "mongo/util/log.h"
#include "mongo/util/stringutils.h"
#include "mongo/bson/bson.h"
#include "mongo/client/dbclient.h"
#include "boost/thread.hpp"
using std::auto_ptr;
using std::list;
using std::string;
using std::vector;
using namespace mongo::unittest;
using namespace mongo;
namespace {
const string TEST_NS = "test.dbclient";
const string TEST_DB = "test";
const string TEST_COLL = "dbclient";
class DBClientTest : public ::testing::Test {
public:
DBClientTest() {
c.connect(string("localhost:") + integrationTestParams.port);
c.dropCollection(TEST_NS);
}
DBClientConnection c;
};
bool serverGTE(DBClientBase* c, int major, int minor) {
BSONObj result;
c->runCommand("admin", BSON("buildinfo" << true), result);
std::vector<BSONElement> version = result.getField("versionArray").Array();
int serverMajor = version[0].Int();
int serverMinor = version[1].Int();
return (serverMajor >= major && serverMinor >= minor);
}
/* Query Class */
TEST(QueryTest, Explain) {
Query q;
q.explain();
ASSERT_TRUE(q.isComplex());
ASSERT_TRUE(q.isExplain());
}
TEST(QueryTest, Snapshot) {
Query q;
q.snapshot();
ASSERT_TRUE(q.isComplex());
ASSERT_TRUE(q.obj.hasField("$snapshot"));
ASSERT_TRUE(q.obj.getBoolField("$snapshot"));
}
TEST(QueryTest, Sort) {
Query q;
q.sort(BSON("a" << 1));
ASSERT_TRUE(q.isComplex());
BSONObj sort = q.getSort();
ASSERT_TRUE(sort.hasField("a"));
ASSERT_EQUALS(sort.getIntField("a"), 1);
}
TEST(QueryTest, Hint) {
Query q;
q.hint(BSON("a" << 1));
BSONObj hint = q.getHint().Obj();
ASSERT_TRUE(hint.hasField("a"));
ASSERT_EQUALS(hint.getIntField("a"), 1);
}
TEST(QueryTest, MinKey) {
Query q;
BSONObj minobj;
q.minKey(minobj);
ASSERT_TRUE(q.isComplex());
ASSERT_TRUE(q.obj.hasField("$min"));
ASSERT_EQUALS(q.obj["$min"].Obj(), minobj);
}
TEST(QueryTest, MaxKey) {
Query q;
BSONObj maxobj;
q.maxKey(maxobj);
ASSERT_TRUE(q.isComplex());
ASSERT_TRUE(q.obj.hasField("$max"));
ASSERT_EQUALS(q.obj["$max"].Obj(), maxobj);
}
TEST(QueryTest, ReadPreferencePrimary) {
Query q("{}");
q.readPref(mongo::ReadPreference_PrimaryOnly, BSONArray());
ASSERT_TRUE(q.obj.hasField(Query::ReadPrefField.name()));
BSONElement read_pref_elem = q.obj[Query::ReadPrefField.name()];
ASSERT_TRUE(read_pref_elem.isABSONObj());
BSONObj read_pref_obj = read_pref_elem.Obj();
ASSERT_EQUALS(read_pref_obj[Query::ReadPrefModeField.name()].String(), "primary");
ASSERT_FALSE(read_pref_obj.hasField(Query::ReadPrefTagsField.name()));
}
TEST(QueryTest, ReadPreferencePrimaryPreferred) {
Query q("{}");
q.readPref(mongo::ReadPreference_PrimaryPreferred, BSONArray());
ASSERT_TRUE(q.obj.hasField(Query::ReadPrefField.name()));
BSONElement read_pref_elem = q.obj[Query::ReadPrefField.name()];
ASSERT_TRUE(read_pref_elem.isABSONObj());
BSONObj read_pref_obj = read_pref_elem.Obj();
ASSERT_EQUALS(read_pref_obj[Query::ReadPrefModeField.name()].String(), "primaryPreferred");
ASSERT_FALSE(read_pref_obj.hasField(Query::ReadPrefTagsField.name()));
}
TEST(QueryTest, ReadPreferenceSecondary) {
Query q("{}");
q.readPref(mongo::ReadPreference_SecondaryOnly, BSONArray());
ASSERT_TRUE(q.obj.hasField(Query::ReadPrefField.name()));
BSONElement read_pref_elem = q.obj[Query::ReadPrefField.name()];
ASSERT_TRUE(read_pref_elem.isABSONObj());
BSONObj read_pref_obj = read_pref_elem.Obj();
ASSERT_EQUALS(read_pref_obj[Query::ReadPrefModeField.name()].String(), "secondary");
ASSERT_FALSE(read_pref_obj.hasField(Query::ReadPrefTagsField.name()));
}
TEST(QueryTest, ReadPreferenceSecondaryPreferred) {
Query q("{}");
q.readPref(mongo::ReadPreference_SecondaryPreferred, BSONArray());
ASSERT_TRUE(q.obj.hasField(Query::ReadPrefField.name()));
BSONElement read_pref_elem = q.obj[Query::ReadPrefField.name()];
ASSERT_TRUE(read_pref_elem.isABSONObj());
BSONObj read_pref_obj = read_pref_elem.Obj();
ASSERT_EQUALS(read_pref_obj[Query::ReadPrefModeField.name()].String(), "secondaryPreferred");
ASSERT_FALSE(read_pref_obj.hasField(Query::ReadPrefTagsField.name()));
}
TEST(QueryTest, ReadPreferenceNearest) {
Query q("{}");
q.readPref(mongo::ReadPreference_Nearest, BSONArray());
ASSERT_TRUE(q.obj.hasField(Query::ReadPrefField.name()));
BSONElement read_pref_elem = q.obj[Query::ReadPrefField.name()];
ASSERT_TRUE(read_pref_elem.isABSONObj());
BSONObj read_pref_obj = read_pref_elem.Obj();
ASSERT_EQUALS(read_pref_obj[Query::ReadPrefModeField.name()].String(), "nearest");
ASSERT_FALSE(read_pref_obj.hasField(Query::ReadPrefTagsField.name()));
}
TEST(QueryTest, ReadPreferenceTagSets) {
Query q("{}");
BSONObj tag_set1 = BSON("datacenter" << "nyc");
BSONObj tag_set2 = BSON("awesome" << "yeah");
BSONObjBuilder bob;
BSONArrayBuilder bab;
bab.append(tag_set1);
bab.append(tag_set2);
q.readPref(mongo::ReadPreference_SecondaryOnly, bab.arr());
ASSERT_TRUE(q.obj.hasField(Query::ReadPrefField.name()));
BSONElement read_pref_elem = q.obj[Query::ReadPrefField.name()];
ASSERT_TRUE(read_pref_elem.isABSONObj());
BSONObj read_pref_obj = read_pref_elem.Obj();
ASSERT_EQUALS(read_pref_obj[Query::ReadPrefModeField.name()].String(), "secondary");
ASSERT_TRUE(read_pref_obj.hasField(Query::ReadPrefTagsField.name()));
vector<BSONElement> tag_sets = read_pref_obj[Query::ReadPrefTagsField.name()].Array();
ASSERT_EQUALS(tag_sets[0].Obj(), tag_set1);
ASSERT_EQUALS(tag_sets[1].Obj(), tag_set2);
}
/* Connection String */
TEST(ConnectionString, SameLogicalEndpoint) {
string err1;
string err2;
ConnectionString cs1;
ConnectionString cs2;
// INVALID -- default non parsed state
ASSERT_TRUE(cs1.sameLogicalEndpoint(cs2));
cs2 = ConnectionString::parse("mongodb://host1,host2,host3", err1);
ASSERT_TRUE(cs1.sameLogicalEndpoint(cs2));
// MASTER
cs1 = ConnectionString::parse("mongodb://localhost:1234", err1);
cs2 = ConnectionString::parse("mongodb://localhost:1234", err2);
ASSERT_TRUE(cs1.sameLogicalEndpoint(cs2));
// PAIR -- compares the host + port even in swapped order
cs1 = cs1.parse("mongodb://localhost:1234,localhost:5678", err1);
cs2 = cs2.parse("mongodb://localhost:1234,localhost:5678", err2);
ASSERT_TRUE(cs1.sameLogicalEndpoint(cs2));
cs2 = cs2.parse("mongodb://localhost:5678,localhost:1234", err2);
ASSERT_TRUE(cs1.sameLogicalEndpoint(cs2));
// SET -- compares the set name only
cs1 = cs1.parse("mongodb://localhost:1234,localhost:5678/?replicaSet=testset", err1);
cs2 = cs2.parse("mongodb://localhost:5678,localhost:1234/?replicaSet=testset", err2);
ASSERT_TRUE(cs1.sameLogicalEndpoint(cs2));
// Different parsing methods
cs1 = cs1.parseDeprecated("testset/localhost:1234,localhost:5678", err1);
cs2 = cs2.parse("mongodb://localhost:5678,localhost:1234", err2);
ASSERT_FALSE(cs1.sameLogicalEndpoint(cs2));
}
TEST(ConnectionString, TypeToString) {
ASSERT_EQUALS(
ConnectionString::typeToString(ConnectionString::INVALID),
"invalid"
);
ASSERT_EQUALS(
ConnectionString::typeToString(ConnectionString::MASTER),
"master"
);
ASSERT_EQUALS(
ConnectionString::typeToString(ConnectionString::PAIR),
"pair"
);
ASSERT_EQUALS(
ConnectionString::typeToString(ConnectionString::SET),
"set"
);
ASSERT_EQUALS(
ConnectionString::typeToString(ConnectionString::CUSTOM),
"custom"
);
}
/* DBClient Tests */
TEST_F(DBClientTest, Save) {
// Save a doc with autogenerated id
c.save(TEST_NS, BSON("hello" << "world"));
BSONObj result = c.findOne(TEST_NS, Query());
BSONElement id = result.getField("_id");
ASSERT_EQUALS(id.type(), jstOID);
// Save a doc with explicit id
c.save(TEST_NS, BSON("_id" << "explicit_id" << "hello" << "bar"));
BSONObj doc = c.findOne(TEST_NS, MONGO_QUERY("_id" << "explicit_id"));
ASSERT_EQUALS(doc.getStringField("_id"), std::string("explicit_id"));
ASSERT_EQUALS(doc.getStringField("hello"), std::string("bar"));
// Save docs with _id field already present (shouldn't create new docs)
ASSERT_EQUALS(c.count(TEST_NS), 2U);
c.save(TEST_NS, BSON("_id" << id.OID() << "hello" << "world"));
ASSERT_EQUALS(c.count(TEST_NS), 2U);
c.save(TEST_NS, BSON("_id" << "explicit_id" << "hello" << "baz"));
ASSERT_EQUALS(c.count(TEST_NS), 2U);
ASSERT_EQUALS(
c.findOne(TEST_NS, MONGO_QUERY("_id" << "explicit_id")).getStringField("hello"),
std::string("baz")
);
}
TEST_F(DBClientTest, FindAndModify) {
c.insert(TEST_NS, BSON("_id" << 1 << "i" << 1));
BSONObj result = c.findAndModify(
TEST_NS,
BSON("i" << 1),
BSON("$inc" << BSON("i" << 1)),
false
);
ASSERT_EQUALS(result.getIntField("_id"), 1);
ASSERT_EQUALS(result.getIntField("i"), 1);
ASSERT_EQUALS(c.count(TEST_NS), 1U);
}
TEST_F(DBClientTest, FindAndModifyNoMatch) {
c.insert(TEST_NS, BSON("_id" << 1 << "i" << 1));
BSONObj result = c.findAndModify(
TEST_NS,
BSON("i" << 2),
BSON("$inc" << BSON("i" << 1)),
false
);
ASSERT_TRUE(result.isEmpty());
ASSERT_EQUALS(c.count(TEST_NS), 1U);
}
TEST_F(DBClientTest, FindAndModifyNoMatchUpsert) {
c.insert(TEST_NS, BSON("_id" << 1 << "i" << 1));
BSONObj result = c.findAndModify(
TEST_NS,
BSON("i" << 2),
BSON("$inc" << BSON("i" << 1)),
true
);
ASSERT_TRUE(result.isEmpty());
ASSERT_EQUALS(c.count(TEST_NS), 2U);
}
TEST_F(DBClientTest, FindAndModifyReturnNew) {
c.insert(TEST_NS, BSON("_id" << 1 << "i" << 1));
BSONObj result = c.findAndModify(
TEST_NS,
BSON("i" << 1),
BSON("$inc" << BSON("i" << 1)),
false,
true
);
ASSERT_EQUALS(result.getIntField("_id"), 1);
ASSERT_EQUALS(result.getIntField("i"), 2);
ASSERT_EQUALS(c.count(TEST_NS), 1U);
}
TEST_F(DBClientTest, FindAndModifyNoMatchUpsertReturnNew) {
c.insert(TEST_NS, BSON("_id" << 1 << "i" << 1));
BSONObj result = c.findAndModify(
TEST_NS,
BSON("i" << 2),
BSON("$inc" << BSON("i" << 1)),
true,
true
);
ASSERT_TRUE(result.hasField("_id"));
ASSERT_EQUALS(result.getIntField("i"), 3);
ASSERT_EQUALS(c.count(TEST_NS), 2U);
}
TEST_F(DBClientTest, FindAndModifySort) {
c.insert(TEST_NS, BSON("_id" << 1 << "i" << 1));
c.insert(TEST_NS, BSON("_id" << 2 << "i" << 2));
BSONObj result = c.findAndModify(
TEST_NS,
BSONObj(),
BSON("$inc" << BSON("i" << 1)),
false,
false,
BSON("i" << -1)
);
ASSERT_EQUALS(result.getIntField("_id"), 2);
ASSERT_EQUALS(result.getIntField("i"), 2);
ASSERT_EQUALS(c.count(TEST_NS, BSON("_id" << 2 << "i" << 3)), 1U);
}
TEST_F(DBClientTest, FindAndModifyProjection) {
c.insert(TEST_NS, BSON("_id" << 1 << "i" << 1));
BSONObj result = c.findAndModify(
TEST_NS,
BSON("i" << 1),
BSON("$inc" << BSON("i" << 1)),
false,
false,
BSONObj(),
BSON("_id" << 0)
);
ASSERT_FALSE(result.hasField("_id"));
ASSERT_TRUE(result.hasField("i"));
}
TEST_F(DBClientTest, FindAndModifyDuplicateKeyError) {
c.insert(TEST_NS, BSON("_id" << 1 << "i" << 1));
c.createIndex(TEST_NS, IndexSpec().addKey("i").unique());
ASSERT_THROWS(
c.findAndModify(
TEST_NS,
BSON("i" << 1 << "j" << 1),
BSON("$set" << BSON("k" << 1)),
true
),
OperationException
);
}
TEST_F(DBClientTest, FindAndRemove) {
c.insert(TEST_NS, BSON("_id" << 1 << "i" << 1));
BSONObj result = c.findAndRemove(
TEST_NS,
BSON("i" << 1)
);
ASSERT_EQUALS(result.getIntField("_id"), 1);
ASSERT_EQUALS(result.getIntField("i"), 1);
ASSERT_EQUALS(c.count(TEST_NS), 0U);
}
TEST_F(DBClientTest, FindAndRemoveNoMatch) {
c.insert(TEST_NS, BSON("_id" << 1 << "i" << 1));
BSONObj result = c.findAndRemove(
TEST_NS,
BSON("i" << 2)
);
ASSERT_TRUE(result.isEmpty());
ASSERT_EQUALS(c.count(TEST_NS), 1U);
}
TEST_F(DBClientTest, FindAndRemoveSort) {
c.insert(TEST_NS, BSON("_id" << 1 << "i" << 1));
c.insert(TEST_NS, BSON("_id" << 2 << "i" << 2));
BSONObj result = c.findAndRemove(
TEST_NS,
BSONObj(),
BSON("i" << -1)
);
ASSERT_EQUALS(result.getIntField("_id"), 2);
ASSERT_EQUALS(result.getIntField("i"), 2);
ASSERT_EQUALS(c.count(TEST_NS), 1U);
ASSERT_EQUALS(c.count(TEST_NS, BSON("_id" << 1)), 1U);
}
TEST_F(DBClientTest, FindAndRemoveProjection) {
c.insert(TEST_NS, BSON("_id" << 1 << "i" << 1));
BSONObj result = c.findAndRemove(
TEST_NS,
BSON("i" << 1),
BSONObj(),
BSON("_id" << 0)
);
ASSERT_FALSE(result.hasField("_id"));
ASSERT_TRUE(result.hasField("i"));
ASSERT_EQUALS(c.count(TEST_NS), 0U);
}
TEST_F(DBClientTest, ManualGetMore) {
// Ported from dbtests/querytests.cpp
for(int i = 0; i < 3; ++i) {
c.insert(TEST_NS, BSON("num" << i));
}
auto_ptr<DBClientCursor> cursor = c.query(TEST_NS, Query("{}"), 0, 0, 0, 0, 2);
uint64_t cursor_id = cursor->getCursorId();
cursor->decouple();
cursor.reset();
cursor = c.getMore(TEST_NS, cursor_id);
ASSERT_TRUE(cursor->more());
ASSERT_EQUALS(cursor->next().getIntField("num"), 2);
}
TEST_F(DBClientTest, Distinct) {
c.insert(TEST_NS, BSON("a" << 1));
c.insert(TEST_NS, BSON("a" << 2));
c.insert(TEST_NS, BSON("a" << 2));
c.insert(TEST_NS, BSON("a" << 2));
c.insert(TEST_NS, BSON("a" << 3));
BSONObj result = c.distinct(TEST_NS, "a");
std::vector<BSONElement> results;
BSONObjIterator iter(result);
while (iter.more())
results.push_back(iter.next());
std::sort(results.begin(), results.end());
ASSERT_EQUALS(results[0].Int(), 1);
ASSERT_EQUALS(results[1].Int(), 2);
ASSERT_EQUALS(results[2].Int(), 3);
}
TEST_F(DBClientTest, DistinctWithQuery) {
c.insert(TEST_NS, BSON("a" << 1));
c.insert(TEST_NS, BSON("a" << 2));
c.insert(TEST_NS, BSON("a" << 2));
c.insert(TEST_NS, BSON("a" << 2));
c.insert(TEST_NS, BSON("a" << 3));
BSONObj result = c.distinct(TEST_NS, "a", BSON("a" << GT << 1));
std::vector<BSONElement> results;
BSONObjIterator iter(result);
while (iter.more())
results.push_back(iter.next());
std::sort(results.begin(), results.end());
ASSERT_EQUALS(results[0].Int(), 2);
ASSERT_EQUALS(results[1].Int(), 3);
}
TEST_F(DBClientTest, DistinctDotted) {
c.insert(TEST_NS, BSON("a" << BSON("b" << "a") << "c" << 12));
c.insert(TEST_NS, BSON("a" << BSON("b" << "b") << "c" << 12));
c.insert(TEST_NS, BSON("a" << BSON("b" << "c") << "c" << 12));
c.insert(TEST_NS, BSON("a" << BSON("b" << "c") << "c" << 12));
BSONObj result = c.distinct(TEST_NS, "a.b");
std::vector<BSONElement> results;
BSONObjIterator iter(result);
while (iter.more())
results.push_back(iter.next());
std::sort(results.begin(), results.end());
ASSERT_EQUALS(results[0].String(), std::string("a"));
ASSERT_EQUALS(results[1].String(), std::string("b"));
ASSERT_EQUALS(results[2].String(), std::string("c"));
}
/* DBClient free functions */
TEST_F(DBClientTest, ServerAlive) {
ASSERT_TRUE(serverAlive("localhost:" + integrationTestParams.port));
ASSERT_FALSE(serverAlive("mongo.example:27017"));
}
TEST_F(DBClientTest, ErrField) {
ASSERT_FALSE(hasErrField(BSONObj()));
ASSERT_TRUE(hasErrField(BSON("$err" << true)));
}
/* Connection level functions */
TEST_F(DBClientTest, InsertVector) {
vector<BSONObj> v;
v.push_back(BSON("num" << 1));
v.push_back(BSON("num" << 2));
c.insert(TEST_NS, v);
ASSERT_EQUALS(c.count(TEST_NS), 2U);
}
TEST_F(DBClientTest, SimpleGroup) {
c.insert(TEST_NS, BSON("a" << 1 << "color" << "green"));
c.insert(TEST_NS, BSON("a" << 2 << "color" << "green"));
c.insert(TEST_NS, BSON("a" << 3 << "color" << "green"));
c.insert(TEST_NS, BSON("a" << 1 << "color" << "blue"));
std::string reduce = "function(current, aggregate) {"
"if (current.color === 'green') { aggregate.green++; }"
"if (current.a) { aggregate.a += current.a; }"
"}";
BSONObj initial = BSON("a" << 0 << "green" << 0);
BSONObj cond = BSON("a" << LT << 3);
BSONObj key = BSON("color" << 1);
std::string finalize = "function(result) {"
"result.combined = result.green + result.a;"
"}";
vector<BSONObj> results;
c.group(TEST_NS, reduce, &results, initial, cond, key, finalize);
vector<BSONObj>::const_iterator it = results.begin();
while (it != results.end()) {
BSONObj current = *it;
if (current.getStringField("color") == std::string("green")) {
ASSERT_EQUALS(current.getField("a").Double(), 3.0);
ASSERT_EQUALS(current.getField("green").Double(), 2.0);
ASSERT_EQUALS(current.getField("combined").Double(), 5.0);
} else {
ASSERT_EQUALS(current.getField("a").Double(), 1.0);
ASSERT_EQUALS(current.getField("green").Double(), 0.0);
ASSERT_EQUALS(current.getField("combined").Double(), 1.0);
}
++it;
}
}
TEST_F(DBClientTest, GroupWithKeyFunction) {
c.insert(TEST_NS, BSON("a" << 1 << "color" << "green"));
c.insert(TEST_NS, BSON("a" << 2 << "color" << "green"));
c.insert(TEST_NS, BSON("a" << 3 << "color" << "green"));
c.insert(TEST_NS, BSON("a" << 1 << "color" << "blue"));
std::string reduce = "function(current, aggregate) {"
"if (current.color === 'green') { aggregate.green++; }"
"if (current.a) { aggregate.a += current.a; }"
"}";
BSONObj initial = BSON("a" << 0 << "green" << 0);
BSONObj cond = BSON("a" << LT << 3);
std::string key = "function(doc) {"
"return { 'color': doc.color }"
"}";
std::string finalize = "function(result) {"
"result.combined = result.green + result.a;"
"}";
vector<BSONObj> results;
c.groupWithKeyFunction(TEST_NS, reduce, &results, initial, cond, key, finalize);
vector<BSONObj>::const_iterator it = results.begin();
while (it != results.end()) {
BSONObj current = *it;
if (current.getStringField("color") == std::string("green")) {
ASSERT_EQUALS(current.getField("a").Double(), 3.0);
ASSERT_EQUALS(current.getField("green").Double(), 2.0);
ASSERT_EQUALS(current.getField("combined").Double(), 5.0);
} else {
ASSERT_EQUALS(current.getField("a").Double(), 1.0);
ASSERT_EQUALS(current.getField("green").Double(), 0.0);
ASSERT_EQUALS(current.getField("combined").Double(), 1.0);
}
++it;
}
}
void getResults(DBClientCursor* cursor, std::vector<int>* results, boost::mutex* mut) {
while (cursor->more()) {
boost::lock_guard<boost::mutex> lock(*mut);
results->push_back(cursor->next().getIntField("_id"));
}
}
DBClientBase* makeNewConnection(DBClientBase* originalConnection,
std::vector<DBClientBase*>* connectionAccumulator) {
DBClientConnection* newConn = new DBClientConnection();
newConn->connect(originalConnection->getServerAddress());
connectionAccumulator->push_back(newConn);
return newConn;
}
TEST_F(DBClientTest, ParallelCollectionScanUsingNewConnections) {
bool supported = serverGTE(&c, 2, 6);
if (supported) {
const size_t numItems = 8000;
const size_t seriesSum = (numItems * (numItems - 1)) / 2;
for (size_t i = 0; i < numItems; ++i)
c.insert(TEST_NS, BSON("_id" << static_cast<int>(i)));
std::vector<DBClientBase*> connections;
std::vector<DBClientCursor*> cursors;
stdx::function<DBClientBase* ()> factory = stdx::bind(&makeNewConnection, &c, &connections);
c.parallelScan(TEST_NS, 3, &cursors, factory);
std::vector<int> results;
boost::mutex resultsMutex;
std::vector<boost::thread*> threads;
// We can get up to 3 cursors back here but the server might give us back less
for (size_t i = 0; i < cursors.size(); ++i)
threads.push_back(new boost::thread(getResults, cursors[i], &results, &resultsMutex));
// Ensure all the threads have completed their scans
for (size_t i = 0; i < threads.size(); ++i) {
threads[i]->join();
delete threads[i];
}
// Cleanup the cursors that parallel scan created
for (size_t i = 0; i < cursors.size(); ++i)
delete cursors[i];
// Cleanup the connections our connection factory created
for (size_t i = 0; i < connections.size(); ++i)
delete connections[i];
size_t sum = 0;
for (size_t i = 0; i < results.size(); ++i)
sum += results[i];
ASSERT_EQUALS(sum, seriesSum);
}
}
DBClientBase* makeSketchyConnection(DBClientBase* originalConnection,
std::vector<DBClientBase*>* connectionAccumulator) {
static int connectionCount = 0;
// Fail creating the second connection
DBClientConnection* newConn;
if (connectionCount != 1)
newConn = new DBClientConnection();
else
throw OperationException(BSONObj());
newConn->connect(originalConnection->getServerAddress());
connectionAccumulator->push_back(newConn);
connectionCount++;
return newConn;
}
TEST_F(DBClientTest, ParallelCollectionScanBadConnections) {
bool supported = serverGTE(&c, 2, 6);
if (supported) {
const size_t numItems = 8000;
for (size_t i = 0; i < numItems; ++i)
c.insert(TEST_NS, BSON("_id" << static_cast<int>(i)));
std::vector<DBClientBase*> connections;
std::vector<DBClientCursor*> cursors;
stdx::function<DBClientBase* ()> factory = stdx::bind(&makeSketchyConnection, &c, &connections);
ASSERT_THROWS(
c.parallelScan(TEST_NS, 3, &cursors, factory),
OperationException
);
ASSERT_EQUALS(cursors.size(), 1U);
ASSERT_EQUALS(connections.size(), 1U);
// Cleanup the cursors that parallel scan created
for (size_t i = 0; i < cursors.size(); ++i)
delete cursors[i];
// Cleanup the connections our connection factory created
for (size_t i = 0; i < connections.size(); ++i)
delete connections[i];
}
}
TEST_F(DBClientTest, InsertVectorContinueOnError) {
vector<BSONObj> v;
v.push_back(BSON("_id" << 1));
v.push_back(BSON("_id" << 1));
v.push_back(BSON("_id" << 2));
ASSERT_THROWS(
c.insert(TEST_NS, v, InsertOption_ContinueOnError),
OperationException
);
ASSERT_EQUALS(c.count(TEST_NS), 2U);
}
TEST_F(DBClientTest, GetIndexes) {
auto_ptr<DBClientCursor> cursor = c.getIndexes(TEST_NS);
ASSERT_FALSE(cursor->more());
c.insert(TEST_NS, BSON("test" << true));
cursor = c.getIndexes(TEST_NS);
ASSERT_EQUALS(cursor->itcount(), 1);
c.createIndex(TEST_NS, BSON("test" << 1));
cursor = c.getIndexes(TEST_NS);
vector<BSONObj> v;
while(cursor->more())
v.push_back(cursor->next());
ASSERT_EQUALS(v.size(), 2U);
ASSERT_EQUALS(v[0]["name"].String(), "_id_");
ASSERT_EQUALS(v[1]["name"].String(), "test_1");
}
TEST_F(DBClientTest, DropIndexes) {
c.createIndex(TEST_NS, BSON("test" << 1));
unsigned index_count = c.getIndexes(TEST_NS)->itcount();
ASSERT_EQUALS(index_count, 2U);
c.dropIndexes(TEST_NS);
index_count = c.getIndexes(TEST_NS)->itcount();
ASSERT_EQUALS(index_count, 1U);
}
TEST_F(DBClientTest, DropIndex) {
c.createIndex(TEST_NS, BSON("test" << 1));
c.createIndex(TEST_NS, BSON("test2" << -1));
unsigned index_count = c.getIndexes(TEST_NS)->itcount();
ASSERT_EQUALS(index_count, 3U);
// Interface that takes an index key obj
c.dropIndex(TEST_NS, BSON("test" << 1));
index_count = c.getIndexes(TEST_NS)->itcount();
ASSERT_EQUALS(index_count, 2U);
// Interface that takes an index name
c.dropIndex(TEST_NS, "test2_-1");
index_count = c.getIndexes(TEST_NS)->itcount();
ASSERT_EQUALS(index_count, 1U);
// Drop of unknown index should throw an error
ASSERT_THROWS(c.dropIndex(TEST_NS, "test3_1"), DBException);
}
TEST_F(DBClientTest, ReIndex) {
c.createIndex(TEST_NS, BSON("test" << 1));
c.createIndex(TEST_NS, BSON("test2" << -1));
unsigned index_count = c.getIndexes(TEST_NS)->itcount();
ASSERT_EQUALS(index_count, 3U);
c.reIndex(TEST_NS);
index_count = c.getIndexes(TEST_NS)->itcount();
ASSERT_EQUALS(index_count, 3U);
}
TEST_F(DBClientTest, Aggregate) {
if (serverGTE(&c, 2, 2)) {
BSONObj doc = BSON("hello" << "world");
BSONObj pipeline = BSON("0" << BSON("$match" << doc));
c.insert(TEST_NS, doc);
c.insert(TEST_NS, doc);
std::auto_ptr<DBClientCursor> cursor = c.aggregate(TEST_NS, pipeline);
ASSERT_TRUE(cursor.get());
for (int i = 0; i < 2; i++) {
ASSERT_TRUE(cursor->more());
BSONObj result = cursor->next();
ASSERT_TRUE(result.valid());
ASSERT_EQUALS(result["hello"].String(), "world");
}
ASSERT_FALSE(cursor->more());
}
}
TEST_F(DBClientTest, CreateCollection) {
ASSERT_FALSE(c.exists(TEST_NS));
ASSERT_TRUE(c.createCollection(TEST_NS));
ASSERT_FALSE(c.createCollection(TEST_NS));
ASSERT_TRUE(c.exists(TEST_NS));
BSONObj info;
ASSERT_TRUE(c.runCommand(TEST_DB, BSON("collstats" << TEST_COLL), info));
bool server26plus = serverGTE(&c, 2, 6);
if (serverGTE(&c, 2, 2)) {
ASSERT_EQUALS(info.getIntField("userFlags"), server26plus ? 1 : 0);
}
ASSERT_EQUALS(info.getIntField("nindexes"), 1);
}
TEST_F(DBClientTest, CreateCollectionAdvanced) {
BSONObjBuilder opts;
opts.append("usePowerOf2Sizes", 0);
opts.append("autoIndexId", false);
c.createCollectionWithOptions(TEST_NS, 1, true, 1, opts.obj());
BSONObj info;
ASSERT_TRUE(c.runCommand(TEST_DB, BSON("collstats" << TEST_COLL), info));
if (serverGTE(&c, 2, 2)) {
ASSERT_EQUALS(info.getIntField("userFlags"), 0);
}
ASSERT_EQUALS(info.getIntField("nindexes"), 0);
}
TEST_F(DBClientTest, CountWithHint) {
c.insert(TEST_NS, BSON("a" << 1));
c.insert(TEST_NS, BSON("a" << 2));
IndexSpec normal_spec;
normal_spec.addKey("a");
c.createIndex(TEST_NS, normal_spec);
ASSERT_EQUALS(c.count(TEST_NS, Query("{'a': 1}").hint("_id_")), 1U);
ASSERT_EQUALS(c.count(TEST_NS, Query().hint("_id_")), 2U);
IndexSpec sparse_spec;
sparse_spec.addKey("b").sparse(true);
c.createIndex(TEST_NS, sparse_spec);
Query good = Query("{'a': 1}").hint("b_1");
Query bad = Query("{'a': 1}").hint("badhint");
if (serverGTE(&c, 2, 6)) {
ASSERT_EQUALS(c.count(TEST_NS, good), 0U);
ASSERT_THROWS(c.count(TEST_NS, bad), DBException);
} else {
ASSERT_EQUALS(c.count(TEST_NS, good), 1U);
ASSERT_NO_THROW(c.count(TEST_NS, bad));
}
ASSERT_EQUALS(c.count(TEST_NS, Query().hint("b_1")), 2U);
}
TEST_F(DBClientTest, CopyDatabase) {
c.dropDatabase("copy");
c.insert(TEST_NS, BSON("test" << true));
ASSERT_TRUE(c.copyDatabase(TEST_DB, "copy"));
string copy_ns = string("copy.") + TEST_COLL;
c.exists(copy_ns);
BSONObj doc = c.findOne(copy_ns, Query("{}"));
ASSERT_TRUE(doc["test"].boolean());
}
TEST_F(DBClientTest, DBProfilingLevel) {
DBClientWithCommands::ProfilingLevel level;
ASSERT_TRUE(c.setDbProfilingLevel(TEST_DB, c.ProfileAll));
ASSERT_TRUE(c.getDbProfilingLevel(TEST_DB, level, 0));
ASSERT_EQUALS(level, c.ProfileAll);
ASSERT_TRUE(c.setDbProfilingLevel(TEST_DB, c.ProfileSlow));
ASSERT_TRUE(c.getDbProfilingLevel(TEST_DB, level, 0));
ASSERT_EQUALS(level, c.ProfileSlow);
ASSERT_TRUE(c.setDbProfilingLevel(TEST_DB, c.ProfileOff));
ASSERT_TRUE(c.getDbProfilingLevel(TEST_DB, level, 0));
ASSERT_EQUALS(level, c.ProfileOff);
}
TEST_F(DBClientTest, QueryJSON) {
Query q(string("{name: 'Tyler'}"));
BSONObj filter = q.getFilter();
ASSERT_TRUE(filter.hasField("name"));
ASSERT_EQUALS(filter["name"].String(), "Tyler");
}
// Used to test exhaust via query below
void nop(const BSONObj &) { /* nop */ }
// This also excercises availableOptions (which is protected)
TEST_F(DBClientTest, Exhaust) {
for(int i=0; i<1000; ++i)
c.insert(TEST_NS, BSON("num" << i));
stdx::function<void(const BSONObj &)> f = nop;
c.query(f, TEST_NS, Query("{}"));
}
TEST_F(DBClientTest, GetPrevError) {
c.insert(TEST_NS, BSON("_id" << 1));
ASSERT_THROWS(
c.insert(TEST_NS, BSON("_id" << 1)),
OperationException
);
c.insert(TEST_NS, BSON("_id" << 2));
ASSERT_TRUE(c.getLastError().empty());
ASSERT_FALSE(c.getPrevError().isEmpty());
}
TEST_F(DBClientTest, MaxScan) {
for(int i = 0; i < 100; ++i) {
c.insert(TEST_NS, fromjson("{}"));
}
vector<BSONObj> results;
c.findN(results, TEST_NS, Query("{}"), 100);
ASSERT_EQUALS(results.size(), 100U);
results.clear();
c.findN(results, TEST_NS, Query("{$query: {}, $maxScan: 50}"), 100);
ASSERT_EQUALS(results.size(), 50U);
}
TEST_F(DBClientTest, ReturnKey) {
c.insert(TEST_NS, BSON("a" << true << "b" << true));
BSONObj result;
result = c.findOne(TEST_NS, Query("{$query: {a: true}}"));
ASSERT_TRUE(result.hasField("a"));
ASSERT_TRUE(result.hasField("b"));
result = c.findOne(TEST_NS, Query("{$query: {a: true}, $returnKey: true}"));
ASSERT_FALSE(result.hasField("a"));
ASSERT_FALSE(result.hasField("b"));
c.createIndex(TEST_NS, BSON("a" << 1));
result = c.findOne(TEST_NS, Query("{$query: {a: true}, $returnKey: true}"));
ASSERT_TRUE(result.hasField("a"));
ASSERT_FALSE(result.hasField("b"));
}
TEST_F(DBClientTest, ShowDiskLoc) {
c.insert(TEST_NS, BSON("a" << true));
BSONObj result;
result = c.findOne(TEST_NS, Query("{$query: {}}"));
ASSERT_FALSE(result.hasField("$diskLoc"));
result = c.findOne(TEST_NS, Query("{$query: {}, $showDiskLoc: true}"));
ASSERT_TRUE(result.hasField("$diskLoc"));
}
TEST_F(DBClientTest, MaxTimeMS) {
// Requires --setParameter=enableTestCommands=1
c.insert(TEST_NS, BSON("a" << true));
BSONObj result;
if (serverGTE(&c, 2, 6)) {
c.runCommand("admin", BSON(
"configureFailPoint" << "maxTimeAlwaysTimeOut" <<
"mode" << BSON("times" << 2)
), result);
// First test with a query
ASSERT_NO_THROW(c.findOne(TEST_NS, Query("{}")););
ASSERT_THROWS(c.findOne(TEST_NS, Query("{}").maxTimeMs(1)), DBException);
// Then test with a command
ASSERT_NO_THROW(c.count(TEST_NS, Query("{}")));
ASSERT_THROWS(c.count(TEST_NS, Query("{}").maxTimeMs(1)), DBException);
} else {
// we are not connected to MongoDB >= 2.6, skip
SUCCEED();
}
}
TEST_F(DBClientTest, Comment) {
c.insert(TEST_NS, BSON("a" << true));
string profile_coll = TEST_DB + ".system.profile";
c.dropCollection(profile_coll);
c.setDbProfilingLevel(TEST_DB, c.ProfileAll);
c.findOne(TEST_NS, Query("{$query: {a: 'z'}, $comment: 'wow'})"));
c.setDbProfilingLevel(TEST_DB, c.ProfileOff);
BSONObj result = c.findOne(profile_coll, BSON(
"ns" << TEST_NS <<
"op" << "query" <<
"query.$comment" << "wow"
));
ASSERT_FALSE(result.isEmpty());
}
TEST_F(DBClientTest, LazyCursor) {
c.insert(TEST_NS, BSON("test" << true));
DBClientCursor cursor(&c, TEST_NS, Query("{}").obj, 0, 0, 0, 0, 0);
bool is_retry = false;
cursor.initLazy(is_retry);
ASSERT_TRUE(cursor.initLazyFinish(is_retry));
vector<BSONObj> docs;
while(cursor.more())
docs.push_back(cursor.next());
ASSERT_EQUALS(docs.size(), 1U);
ASSERT_TRUE(docs.front()["test"].value());
}
void nop_hook(BSONObjBuilder* bob) { (void)bob; }
void nop_hook_post(BSONObj, string) { }
TEST_F(DBClientTest, LazyCursorCommand) {
c.setRunCommandHook(nop_hook);
c.setPostRunCommandHook(nop_hook_post);
DBClientCursor cursor(&c, TEST_DB + ".$cmd", Query("{dbStats: 1}").obj, 1, 0, 0, 0, 0);
bool is_retry = false;
cursor.initLazy(is_retry);
ASSERT_TRUE(cursor.initLazyFinish(is_retry));
ASSERT_TRUE(cursor.more());
ASSERT_TRUE(cursor.next().hasField("db"));
ASSERT_FALSE(cursor.more());
}
TEST_F(DBClientTest, InitCommand) {
DBClientCursor cursor(&c, TEST_DB + ".$cmd", Query("{dbStats: 1}").obj, 1, 0, 0, 0, 0);
ASSERT_TRUE(cursor.initCommand());
ASSERT_TRUE(cursor.more());
ASSERT_TRUE(cursor.next().hasField("db"));
ASSERT_FALSE(cursor.more());
}
TEST_F(DBClientTest, GetMoreLimit) {
c.insert(TEST_NS, BSON("num" << 1));
c.insert(TEST_NS, BSON("num" << 2));
c.insert(TEST_NS, BSON("num" << 3));
c.insert(TEST_NS, BSON("num" << 4));
// set nToReturn to 3 but batch size to 1
// This verifies:
// * we can manage with multiple batches
// * we can correctly upgrade batchSize 1 to 2 to avoid automatic
// cursor closing when nReturn = 1 (wire protocol edge case)
auto_ptr<DBClientCursor> cursor = c.query(TEST_NS, Query("{}"), 3, 0, 0, 0, 1);
vector<BSONObj> docs;
while(cursor->more())
docs.push_back(cursor->next());
ASSERT_EQUALS(docs.size(), 3U);
}
TEST_F(DBClientTest, NoGetMoreLimit) {
c.insert(TEST_NS, BSON("num" << 1));
c.insert(TEST_NS, BSON("num" << 2));
c.insert(TEST_NS, BSON("num" << 3));
c.insert(TEST_NS, BSON("num" << 4));
// set nToReturn to 2 but batch size to 4
// check to see if a limit of 2 takes despite the larger batch
auto_ptr<DBClientCursor> cursor = c.query(TEST_NS, Query("{}"), 2, 0, 0, 0, 4);
vector<BSONObj> docs;
while(cursor->more())
docs.push_back(cursor->next());
ASSERT_EQUALS(docs.size(), 2U);
}
TEST_F(DBClientTest, PeekError) {
BSONObj result;
c.runCommand("admin", BSON("buildinfo" << true), result);
// TODO: figure out if we can come up with query that produces $err on 2.4.x
if (versionCmp(result["version"].toString(), "2.5.3") >= 0) {
auto_ptr<DBClientCursor> cursor = c.query(TEST_NS, Query("{'$fake': true}"));
ASSERT_TRUE(cursor->peekError());
} else {
SUCCEED();
}
}
TEST_F(DBClientTest, DefaultWriteConcernInsert) {
c.insert(TEST_NS, BSON("_id" << 1));
ASSERT_THROWS(
c.insert(TEST_NS, BSON("_id" << 1)),
OperationException
);
ASSERT_EQUALS(c.count(TEST_NS, BSON("_id" << 1)), 1U);
}
TEST_F(DBClientTest, DefaultWriteConcernUpdate) {
c.insert(TEST_NS, BSON("a" << true));
ASSERT_THROWS(
c.update(TEST_NS, BSON("a" << true), BSON("$badOp" << "blah")),
OperationException
);
ASSERT_EQUALS(c.count(TEST_NS, BSON("a" << true)), 1U);
}
TEST_F(DBClientTest, DefaultWriteConcernRemove) {
ASSERT_THROWS(
c.remove("BAD.$NS", BSON("a" << true)),
OperationException
);
}
TEST_F(DBClientTest, UnacknowledgedInsert) {
c.insert(TEST_NS, BSON("_id" << 1));
ASSERT_NO_THROW(
c.insert(
TEST_NS,
BSON("_id" << 1),
0,
&WriteConcern::unacknowledged
)
);
ASSERT_EQUALS(c.count(TEST_NS, BSON("_id" << 1)), 1U);
}
TEST_F(DBClientTest, UnacknowledgedUpdate) {
c.insert(TEST_NS, BSON("a" << true));
ASSERT_NO_THROW(
c.update(
TEST_NS,
BSON("a" << true),
BSON("$badOp" << "blah"),
false,
false,
&WriteConcern::unacknowledged
)
);
ASSERT_EQUALS(c.count(TEST_NS, BSON("a" << true)), 1U);
}
TEST_F(DBClientTest, UnacknowledgedRemove) {
ASSERT_NO_THROW(
c.remove(
"BAD.$NS",
BSON("a" << true),
false,
&WriteConcern::unacknowledged
)
);
}
TEST_F(DBClientTest, AcknowledgeMultipleNodesNonReplicated) {
WriteConcern wc = WriteConcern().nodes(2).timeout(3000);
ASSERT_THROWS(
c.insert(TEST_NS, BSON("_id" << 1), 0, &wc),
OperationException
);
}
TEST_F(DBClientTest, CreateSimpleV0Index) {
c.createIndex(TEST_NS, IndexSpec()
.addKey("aField")
.version(0));
}
TEST_F(DBClientTest, CreateSimpleNamedV0Index) {
c.createIndex(TEST_NS, IndexSpec()
.addKey("aField")
.version(0)
.name("aFieldV0Index"));
}
TEST_F(DBClientTest, CreateCompoundNamedV0Index) {
c.createIndex(TEST_NS, IndexSpec()
.addKey("aField")
.addKey("bField", IndexSpec::kIndexTypeDescending)
.version(0)
.name("aFieldbFieldV0Index"));
}
TEST_F(DBClientTest, CreateSimpleV1Index) {
c.createIndex(TEST_NS, IndexSpec()
.addKey("aField")
.version(1));
}
TEST_F(DBClientTest, CreateSimpleNamedV1Index) {
c.createIndex(TEST_NS, IndexSpec()
.addKey("aField")
.version(1)
.name("aFieldV1Index"));
}
TEST_F(DBClientTest, CreateCompoundNamedV1Index) {
c.createIndex(TEST_NS, IndexSpec()
.addKey("aField")
.addKey("bField", IndexSpec::kIndexTypeDescending)
.version(1)
.name("aFieldbFieldV1Index"));
}
TEST_F(DBClientTest, CreateUniqueSparseDropDupsIndexInBackground) {
c.createIndex(TEST_NS,
IndexSpec()
.addKey("aField")
.background()
.unique()
.sparse()
.dropDuplicatesDeprecated());
}
TEST_F(DBClientTest, CreateComplexTextIndex) {
if (!serverGTE(&c, 2, 6)) {
BSONObj result;
c.runCommand("admin",
BSON("setParameter" << 1 << "textSearchEnabled" << true),
result);
}
c.createIndex(TEST_NS,
IndexSpec()
.addKey("aField", IndexSpec::kIndexTypeText)
.addKey("bField", IndexSpec::kIndexTypeText)
.textWeights(BSON("aField" << 100))
.textDefaultLanguage("spanish")
.textLanguageOverride("lang")
.textIndexVersion(serverGTE(&c, 2, 6) ? 2 : 1));
}
TEST_F(DBClientTest, Create2DIndex) {
c.createIndex(TEST_NS,
IndexSpec()
.addKey("aField", IndexSpec::kIndexTypeGeo2D)
.geo2DBits(20)
.geo2DMin(-120.0)
.geo2DMax(120.0));
}
TEST_F(DBClientTest, CreateHaystackIndex) {
c.createIndex(TEST_NS,
IndexSpec()
.addKey("aField", IndexSpec::kIndexTypeGeoHaystack)
.addKey("otherField", IndexSpec::kIndexTypeDescending)
.geoHaystackBucketSize(1.0));
}
TEST_F(DBClientTest, Create2DSphereIndex) {
c.createIndex(TEST_NS,
IndexSpec()
.addKey("aField", IndexSpec::kIndexTypeGeo2DSphere)
.geo2DSphereIndexVersion(serverGTE(&c, 2, 6) ? 2 : 1));
}
TEST_F(DBClientTest, CreateHashedIndex) {
c.createIndex(TEST_NS,
IndexSpec()
.addKey("aField", IndexSpec::kIndexTypeHashed));
}
} // namespace
| 34.690531 | 108 | 0.561281 | [
"vector"
] |
7b487604590ad1784bbeceb52714e4d72131229f | 4,075 | cpp | C++ | src/storage/storage_service_class.cpp | Telecominfraproject/wlan-cloud-owprov | 6d29c8e5ce6af7b4f4f4e4ad2a5332d78dc520aa | [
"BSD-3-Clause"
] | null | null | null | src/storage/storage_service_class.cpp | Telecominfraproject/wlan-cloud-owprov | 6d29c8e5ce6af7b4f4f4e4ad2a5332d78dc520aa | [
"BSD-3-Clause"
] | null | null | null | src/storage/storage_service_class.cpp | Telecominfraproject/wlan-cloud-owprov | 6d29c8e5ce6af7b4f4f4e4ad2a5332d78dc520aa | [
"BSD-3-Clause"
] | null | null | null | //
// Created by stephane bourque on 2022-04-06.
//
#include "storage_service_class.h"
//
// License type: BSD 3-Clause License
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
//
// Created by Stephane Bourque on 2021-03-04.
// Arilia Wireless Inc.
//
#include "storage_entity.h"
#include "framework/OpenWifiTypes.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h"
#include "StorageService.h"
#include "framework/MicroService.h"
namespace OpenWifi {
static ORM::FieldVec ServiceClassDB_Fields{
// object info
ORM::Field{"id",64, true},
ORM::Field{"name",ORM::FieldType::FT_TEXT},
ORM::Field{"description",ORM::FieldType::FT_TEXT},
ORM::Field{"notes",ORM::FieldType::FT_TEXT},
ORM::Field{"created",ORM::FieldType::FT_BIGINT},
ORM::Field{"modified",ORM::FieldType::FT_BIGINT},
ORM::Field{"operatorId",ORM::FieldType::FT_TEXT},
ORM::Field{"managementPolicy",ORM::FieldType::FT_TEXT},
ORM::Field{"cost",ORM::FieldType::FT_REAL},
ORM::Field{"currency",ORM::FieldType::FT_TEXT},
ORM::Field{"period",ORM::FieldType::FT_TEXT},
ORM::Field{"billingCode",ORM::FieldType::FT_TEXT},
ORM::Field{"variables",ORM::FieldType::FT_TEXT},
ORM::Field{"defaultService",ORM::FieldType::FT_BOOLEAN}
};
static ORM::IndexVec ServiceClassDB_Indexes{
{ std::string("service_class_name_index"),
ORM::IndexEntryVec{
{std::string("name"),
ORM::Indextype::ASC} } }
};
ServiceClassDB::ServiceClassDB( OpenWifi::DBType T, Poco::Data::SessionPool & P, Poco::Logger &L) :
DB(T, "service_classes", ServiceClassDB_Fields, ServiceClassDB_Indexes, P, L, "scl") {
}
bool ServiceClassDB::Upgrade([[maybe_unused]] uint32_t from, uint32_t &to) {
to = Version();
std::vector<std::string> Script{
};
RunScript(Script);
return true;
}
std::string ServiceClassDB::DefaultForOperator(const std::string & OperatorId) {
try {
std::vector<ProvObjects::ServiceClass> SC;
StorageService()->ServiceClassDB().GetRecords(0,1,SC,fmt::format(" operatorId='{}' and defaultService=true ", OperatorId));
if(SC.size()==1)
return SC[0].info.id;
} catch (...) {
}
return "";
}
}
template<> void ORM::DB< OpenWifi::ServiceClassDBRecordType, OpenWifi::ProvObjects::ServiceClass>::Convert(const OpenWifi::ServiceClassDBRecordType &In, OpenWifi::ProvObjects::ServiceClass &Out) {
Out.info.id = In.get<0>();
Out.info.name = In.get<1>();
Out.info.description = In.get<2>();
Out.info.notes = OpenWifi::RESTAPI_utils::to_object_array<OpenWifi::SecurityObjects::NoteInfo>(In.get<3>());
Out.info.created = In.get<4>();
Out.info.modified = In.get<5>();
Out.operatorId = In.get<6>();
Out.managementPolicy = In.get<7>();
Out.cost = In.get<8>();
Out.currency = In.get<9>();
Out.period = In.get<10>();
Out.billingCode = In.get<11>();
Out.variables = OpenWifi::RESTAPI_utils::to_object_array<OpenWifi::ProvObjects::Variable>(In.get<12>());
Out.defaultService = In.get<13>();
}
template<> void ORM::DB< OpenWifi::ServiceClassDBRecordType, OpenWifi::ProvObjects::ServiceClass>::Convert(const OpenWifi::ProvObjects::ServiceClass &In, OpenWifi::ServiceClassDBRecordType &Out) {
Out.set<0>(In.info.id);
Out.set<1>(In.info.name);
Out.set<2>(In.info.description);
Out.set<3>(OpenWifi::RESTAPI_utils::to_string(In.info.notes));
Out.set<4>(In.info.created);
Out.set<5>(In.info.modified);
Out.set<6>(In.operatorId);
Out.set<7>(In.managementPolicy);
Out.set<8>(In.cost);
Out.set<9>(In.currency);
Out.set<10>(In.period);
Out.set<11>(In.billingCode);
Out.set<12>(OpenWifi::RESTAPI_utils::to_string(In.variables));
Out.set<13>(In.defaultService);
}
| 38.084112 | 199 | 0.630429 | [
"object",
"vector"
] |
7b4fdd5755e69e6eb688896b917507f02afdb4d4 | 1,547 | cpp | C++ | native/PCefRenderHandler.cpp | tseylerd/pcef | a9267eb54935fffeee66193814ce8f03afe18073 | [
"BSD-3-Clause"
] | null | null | null | native/PCefRenderHandler.cpp | tseylerd/pcef | a9267eb54935fffeee66193814ce8f03afe18073 | [
"BSD-3-Clause"
] | null | null | null | native/PCefRenderHandler.cpp | tseylerd/pcef | a9267eb54935fffeee66193814ce8f03afe18073 | [
"BSD-3-Clause"
] | null | null | null | //
// PCefRenderHandler.cpp
//
// Created by Dmitriy Tseyler on 20.07.2020.
//
#include "PCefRenderHandler.h"
void PCefRenderHandler::GetViewRect(CefRefPtr<CefBrowser> browser, CefRect& rect) {
auto result = _rect(_context, browsers::get_id(browser));
rect.x = result.x;
rect.y = result.y;
rect.width = result.width;
rect.height = result.height;
}
void PCefRenderHandler::OnPaint(CefRefPtr<CefBrowser> browser, PaintElementType type, const RectList &dirtyRects, const void *buffer, int width, int height) {
log("On paint");
BrowserId client_id = browsers::get_id(browser);
BrowserRect rects[dirtyRects.size()];
for (size_t i = 0; i < dirtyRects.size(); i++) {
const CefRect& oneRect = dirtyRects.at(i);
rects[i] = {
oneRect.x,
oneRect.y,
oneRect.width,
oneRect.height
};
}
_render(_context, client_id, false, dirtyRects.size(), rects, (const uint8_t*)buffer, width, height);
}
bool PCefRenderHandler::GetScreenInfo(CefRefPtr<CefBrowser> browser, CefScreenInfo &screen_info) {
const ScreenInfo& info = _screen_info(_context, browsers::get_id(browser));
screen_info.device_scale_factor = info.scale_factor;
return true;
}
PCefRenderHandler::PCefRenderHandler(const void* context,
PaintFn render,
RectFn rect,
ScreenInfoFn screen_info_fn) {
this->_render = render;
this->_rect = rect;
this->_screen_info = screen_info_fn;
this->_context = context;
}
| 32.229167 | 158 | 0.663219 | [
"render"
] |
7b52f8f25e63efca07683b1b9669a9a1ed7ed572 | 1,597 | cc | C++ | SummingPieces/main.cc | wuxingyu1983/HackerRank | c42da8506fc65eca9bf6015b62c4446f9ab2af14 | [
"MIT"
] | null | null | null | SummingPieces/main.cc | wuxingyu1983/HackerRank | c42da8506fc65eca9bf6015b62c4446f9ab2af14 | [
"MIT"
] | null | null | null | SummingPieces/main.cc | wuxingyu1983/HackerRank | c42da8506fc65eca9bf6015b62c4446f9ab2af14 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <map>
using namespace std;
#define DEBUG 0
#define MOD 1000000007
int main()
{
#if DEBUG
ifstream inFile;
inFile.open("input.txt");
#endif
int n;
#if DEBUG
inFile >> n;
#else
cin >> n;
#endif
long long sum;
long long half1 = 0;
long long half2 = 0;
long long cnt1 = 0;
long long cnt2 = 0;
long long cnt = 0;
for (size_t i = 0; i < n; i++)
{
int a;
#if DEBUG
inFile >> a;
#else
cin >> a;
#endif
if (0 == i)
{
sum = a;
}
else if (1 == i)
{
half1 = a + (sum + a);
sum = sum + a + (sum + a) * 2;
cnt = 2;
cnt1 = 2;
half2 = 5;
cnt2 = 2;
}
else
{
long long tmp = sum + half1 + (half2 * a % MOD);
tmp %= MOD;
sum += (cnt * a % MOD) + tmp;
half1 += cnt1 * a % MOD + cnt * a % MOD;
half1 %= MOD;
cnt1 += cnt;
cnt1 %= MOD;
half2 += cnt2 + cnt * 2;
half2 %= MOD;
cnt2 += cnt;
cnt2 %= MOD;
cnt *= 2;
cnt %= MOD;
}
sum %= MOD;
}
cout << sum << endl;
#if DEBUG
inFile.close();
#endif
return 0;
}
| 17.172043 | 60 | 0.39449 | [
"vector"
] |
7b594847bfdc85d57d0c5cda2fa65c560ee9b61f | 1,669 | cc | C++ | arcane/extras/coverity/ArcaneModel.cc | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 16 | 2021-09-20T12:37:01.000Z | 2022-03-18T09:19:14.000Z | arcane/extras/coverity/ArcaneModel.cc | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 66 | 2021-09-17T13:49:39.000Z | 2022-03-30T16:24:07.000Z | arcane/extras/coverity/ArcaneModel.cc | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 11 | 2021-09-27T16:48:55.000Z | 2022-03-23T19:06:56.000Z | // -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
// Coverity Models For Arcane
// ///////////////////////
//
// These models suppress a few common false positives, mostly relating to
// asserts, or assert-like functions and macros.
//
// 1. Build the models with cov-make-library (i.e. build this file)
// 2. Use the compiled user model file when running cov-analyze, using
// the --user-model-file <filename> option.
//
namespace Arcane
{
// You need to get the namespace exactly right, or the model won't match
// and won't be used.
// We don't care about the contents of TraceMessage, but we have to
// define it or we can't declare the member function we really care about.
class TraceMessage {};
class TraceAccessor
{
public:
// Treat calling this member like an assert, using the Coverity
// primitive, __coverity_panic__().
TraceMessage fatal() const { __coverity_panic__(); }
TraceMessage pfatal() const { __coverity_panic__(); }
};
// Do exactly the same thing for this class
class ITraceMng
{
public:
TraceMessage fatal() { __coverity_panic__(); }
TraceMessage pfatal() { __coverity_panic__(); }
};
// Pointer p will be free 'later'
// TODO: A corriger proprement plus tard (contourne une fuite mémoire dans la construction des services générés)
class IServiceFactory2 { };
class IServiceFactoryInfo { };
class ServiceInfo {
public:
virtual void addFactory(IServiceFactory2 *p) { __coverity_escape__(p); }
void setFactoryInfo(IServiceFactoryInfo* p) { __coverity_escape__(p); }
};
void _doAssert(const char*,const char*,const char*,size_t)
{
__coverity_panic__();
}
} // End namespace Arcane
| 30.345455 | 112 | 0.714799 | [
"model"
] |
7b666d4d6a33f5be7288ca5b4733c3de27d0c3e1 | 205 | cpp | C++ | programmers/source/1-23.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | 7 | 2019-06-26T07:03:32.000Z | 2020-11-21T16:12:51.000Z | programmers/source/1-23.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | null | null | null | programmers/source/1-23.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | 9 | 2019-02-28T03:34:54.000Z | 2020-12-18T03:02:40.000Z | //자연수 뒤집어 배열로 만들기
// 2019.03.08
#include<vector>
using namespace std;
vector<int> solution(long long n)
{
vector<int> answer;
while (n>0)
{
answer.push_back(n % 10);
n /= 10;
}
return answer;
}
| 12.058824 | 33 | 0.639024 | [
"vector"
] |
7b6cbea9668b65953a2efb2ddadf9389665a40e0 | 11,758 | cpp | C++ | src/server.cpp | samkreter/bare-bones-socket-chat | 50360ff885e75dffa3482630b2af9870dca30958 | [
"MIT"
] | 2 | 2016-11-11T16:07:20.000Z | 2019-07-05T12:32:10.000Z | src/server.cpp | samkreter/bare-bones-socket-chat | 50360ff885e75dffa3482630b2af9870dca30958 | [
"MIT"
] | null | null | null | src/server.cpp | samkreter/bare-bones-socket-chat | 50360ff885e75dffa3482630b2af9870dca30958 | [
"MIT"
] | null | null | null | /*
** Sam Kreter
** 11/1/16
** This is the server for a chat application. One client will connect to the
** server interact over sockets
*/
#include <iostream>
#include <string>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <vector>
#include <fstream>
#include <string>
#include <algorithm>
#define PORT "3491" // the port users will be connecting to
#define BACKLOG 10 // how many pending connections queue will hold
#define MAXDATASIZE 256
#define RECIEVE_MAX 15 //
// Program error codes, basicly useless for this but thought i'd add them
#define USER_EXISTS -1
#define UP_NOT_IN_BOUNDS -2
using namespace std;
//structre to hold all the current users
using User = struct {
string username;
string password;
};
//prototypes for all the functions
int newUser(string cmd, int socket_fd);
int login(string cmd, int socket_fd, string* currUser);
int sendMessage(string cmd, int sock_fd, const string& currUser);
vector<User> getUsers();
string* getCommand(int sock_fd);
void *get_in_addr(struct sockaddr *sa);
int main(){
//the thousand of varibles needed to run these sockets
int sockfd, new_fd, numbytes; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
struct sigaction sa;
int yes=1;
char s[INET6_ADDRSTRLEN];
int rv;
char buffer[MAXDATASIZE];
string* cmd;
string currUser;
//zero out the address space of the strucutre for safty
memset(&hints, 0, sizeof hints);
// like client this allows for IPV4 and IPV6
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
//use same ip address as return address
hints.ai_flags = AI_PASSIVE;
//get the info to create the socket
if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
cerr << "getaddrinfo: " << gai_strerror(rv) << endl;
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("server: socket");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
//bind to the socket address
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("server: bind");
continue;
}
break;
}
freeaddrinfo(servinfo); // all done with this structure
if (p == NULL) {
cerr << "server: failed to bind" << endl;
exit(1);
}
//start listening on the socket
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
cout << ("My chat room server. Version One. ") << endl;
//needed flags for user flow
bool loginFlag = false;
bool acceptingNew = true;
while(1){
loginFlag = false;
//accept a new connection
if(acceptingNew){
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
}
//turn the address from binary to family friendly G rated words
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
//cout << "server: got connection from " << s << endl;
acceptingNew = false;
}
//Send login notice
if (send(new_fd, "Use Command Login To Login:", 28, 0) == -1)
perror("send");
while(1){
//don't let anyone past unless they got that login
while(!loginFlag){
cmd = getCommand(new_fd);
//if the getCommand function returns null it means connection was lost
if(cmd == NULL){
acceptingNew = true;
break;
}
//if they are all logged in set it all up
if(cmd[0] == string("login") && login(cmd[1],new_fd,&currUser)){
loginFlag = true;
}
else{
send(new_fd, "Server: Denied. Please login first.", 40, 0);
}
}
//start looping through recieving and sending messages
if(loginFlag){
string* cmd = getCommand(new_fd);
//connection to the socket was lost
if(cmd == NULL){
acceptingNew = true;
break;
}
//user flow to activate functions for each command
if(cmd[0] == string("newuser")){
newUser(cmd[1],new_fd);
}
else if (cmd[0] == string("send")){
sendMessage(cmd[1],new_fd,currUser);
}
else if (cmd[0] == string("logout")){
if (send(new_fd, "Server: Tom left.", 20, 0) == -1)
perror("send");
cout << currUser << " logout" << endl;
loginFlag = false;
acceptingNew = true;
break;
}
else {
if(send((new_fd),"Invalid Command",20,0) == -1)
perror("send");
continue;
}
}
}
}
//tity up everyting
delete[] cmd;
close(sockfd);
close(new_fd);
return 0;
}
//used to send a message with the username of the connected user back to themselves
int sendMessage(string cmd, int socket_fd, const string& currUser){
cout << currUser + ": " + cmd << endl;
if(send(socket_fd,(currUser + ": " + cmd).c_str(), MAXDATASIZE -1, 0) == -1)
perror("send");
return 1;
}
//add a new user to the users.txt file
int newUser(string cmd, int socket_fd){
//splits everything up
size_t spacePos = cmd.find(" ");
string username = cmd.substr(0,spacePos);
string password = cmd.substr(spacePos+1);
//open the user file
ofstream usersFile("../users.txt", std::ios_base::app);
//make sure the file is open
if(!usersFile.is_open()){
cerr << "Could not open user.txt file" << endl;
return -1;
}
//get the list of current users
vector<User> users = getUsers();
//check that everything is gucci
if(username.length() < 32 && password.length() > 3 && password.length() < 9){
//search the currently added users
auto it = find_if(users.begin(),users.end(),[username](User u){
return (u.username == username);
});
//if it was not found, add the user
if(it == users.end()){
//add the new user to the file
usersFile << endl << "(" << username << ", " << password << ")";
//send confirmation to client that everythings good
if(send(socket_fd,"User successfully added!", 30, 0) == -1)
perror("send");
//server note
cout << "User "<< username << " successfully added" << endl;
return 1;
}
//the user already exists
if(send(socket_fd, "User already Exists",25,0) == -1)
perror("send");
cout << "User " << username << " already exists" << endl;
//return the error
return USER_EXISTS;
}
if(send(socket_fd, "User/password not in bounds",30,0) == -1)
perror("send");
cout << "User " << username << "out of bounds" << endl;
//return the specific error code
return UP_NOT_IN_BOUNDS;
}
//validates the user's username and password for login status
int login(string cmd, int socket_fd, string* currUser){
string username;
string password;
char command[MAXDATASIZE];
int numbytes = 0;
//get the current user's usernames and passwords from the userfile
vector<User> users = getUsers();
//parse the command string given to the function
//if no sername or password this step will catch that and not error out
size_t spacePos = cmd.find(" ");
username = cmd.substr(0,spacePos);
password = cmd.substr(spacePos+1);
//search through all the users and check for usersname and password
auto it = find_if(users.begin(),users.end(),[username,password](User u){
return (u.username == username && u.password == password);
});
//if the find function found a match, then add the users name and
// send confirmation
if(it != users.end()){
if(send(socket_fd, ("Server: "+ it->username+" joins").c_str(),MAXDATASIZE - 1,0) == -1)
perror("send");
*currUser = it->username;
cout << *currUser << " login." << endl;
return 1;
}
//otherwise error
if(send(socket_fd, "Invalid Username or Password",40,0) == -1)
perror("send");
cout << "Invalid username or password" << endl;
return 0;
}
// get sockaddr, IPv4 or IPv6, this is an amazing function I found that works great:
void *get_in_addr(struct sockaddr *sa){
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
//used to parse input from the users and parsing out the current command
string* getCommand(int socket_fd){
char command[MAXDATASIZE];
string cmdString;
int numbytes = 0;
string* returns = new string[2];
//keep count of number of empty data recieved,
// if more than max number was recieved, we know that the client has
// been disconnected
size_t count = 0;
while(cmdString.length() == 0){
//zero out the command just in case
bzero(command,MAXDATASIZE);
if ((numbytes = recv(socket_fd, command, MAXDATASIZE - 1, 0)) == -1) {
perror("recv");
exit(1);
}
//add null terminator to the received string
command[numbytes] = '\0';
//convert to c++ string
cmdString = string(command);
//check for the client disconnect
count++;
if(count > RECIEVE_MAX)
return NULL;
}
//finish parsing input and return
size_t spacePos = cmdString.find(" ");
returns[0] = cmdString.substr(0,spacePos);
returns[1] = cmdString.substr(spacePos + 1);
return returns;
}
//helper function to parse username and password from file and return in struct
vector<User> getUsers(){
string line;
vector<User> users;
ifstream myfile ("../users.txt");
if(myfile.is_open()){
while(getline(myfile,line)){
//get pos of comma
int commaPos = line.find(",");
users.push_back(User());
//username if everything before comma and after (
users.back().username = line.substr(1,commaPos-1);
//password is evertyhign after the comma and space and before the )
users.back().password = line.substr(commaPos+2,line.length() - commaPos - 3);
}
myfile.close();
}
else{
cerr << "couldn't open file";
exit(-1);
}
return users;
}
// http://beej.us/guide/bgnet/output/html/multipage/clientserver.html | 27.217593 | 96 | 0.566763 | [
"vector"
] |
7b70a66ebc669d1a466eaaa2221cddf52fcc6b96 | 892 | cpp | C++ | source/write_output/Write_Stoichiometry_Matrix_For_Opt.cpp | DetlevCM/chemical-kinetics-solver | 7010fd6c72c29a0d912ad0c353ff13a5b643cc04 | [
"MIT"
] | 3 | 2015-07-03T20:14:00.000Z | 2021-02-02T13:45:31.000Z | source/write_output/Write_Stoichiometry_Matrix_For_Opt.cpp | DetlevCM/chemical-kinetics-solver | 7010fd6c72c29a0d912ad0c353ff13a5b643cc04 | [
"MIT"
] | null | null | null | source/write_output/Write_Stoichiometry_Matrix_For_Opt.cpp | DetlevCM/chemical-kinetics-solver | 7010fd6c72c29a0d912ad0c353ff13a5b643cc04 | [
"MIT"
] | 4 | 2017-11-09T19:49:18.000Z | 2020-08-04T18:29:28.000Z | /*
* WriteMechanism.cpp
*
* Created on: 21.11.2012
* Author: DetlevCM
*/
#include "../headers/Headers.hpp"
void Write_Stoichiometric_Matrix_For_Opt
(
string filename ,
const vector< SingleReactionData >& Reactions
)
{
size_t i, j;
ofstream Output (filename.c_str(),ios::out);
if (Output.is_open())
{
size_t Number_Reactions = 0;
Number_Reactions = Reactions.size();
size_t Number_Species = 0;
Number_Species = Reactions[0].Reactants.size();
Output << " ";
for(i=0;i<Number_Species;i++)
{
Output << i+1 << " ";
}
Output << "\n";
for(i=0;i<Number_Reactions;i++)
{
Output << i+1 << " ";
for(j=0;j<Number_Species;j++)
{
Output << Reactions[i].Products[j] - Reactions[i].Reactants[j] << " ";
}
Output << "\n";
}
Output.close();
}
else cout << "Unable to open file";
printf("File %s written. \n",filename.c_str());
}
| 18.583333 | 75 | 0.607623 | [
"vector"
] |
7b7ee4193b3a62304e294d7267e428abd1b1992f | 527 | hpp | C++ | ares/msx/vdp/vdp.hpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | ares/msx/vdp/vdp.hpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | ares/msx/vdp/vdp.hpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | struct VDP : TMS9918, V9938, Thread {
Node::Object node;
Node::Video::Screen screen;
//vdp.cpp
auto load(Node::Object) -> void;
auto unload() -> void;
auto step(u32 clocks) -> void override;
auto irq(bool line) -> void override;
auto frame() -> void override;
auto power() -> void;
auto read(n2 port) -> n8;
auto write(n2 port, n8 data) -> void;
//color.cpp
auto colorMSX(n32) -> n64;
auto colorMSX2(n32) -> n64;
//serialization.cpp
auto serialize(serializer&) -> void;
};
extern VDP vdp;
| 20.269231 | 41 | 0.635674 | [
"object"
] |
7b8158f6aba58ffcfcf07a209ead9c9ad6f2fdf3 | 5,436 | hpp | C++ | inc/Application/Buffer.hpp | barne856/3DSWMM | 60dd2702c82857dcf4358b8d42a1fb430a568e90 | [
"MIT"
] | null | null | null | inc/Application/Buffer.hpp | barne856/3DSWMM | 60dd2702c82857dcf4358b8d42a1fb430a568e90 | [
"MIT"
] | null | null | null | inc/Application/Buffer.hpp | barne856/3DSWMM | 60dd2702c82857dcf4358b8d42a1fb430a568e90 | [
"MIT"
] | null | null | null | #ifndef BUFFER
#define BUFFER
#include <GL/glew.h>
#include <vector>
#include <string>
enum class ShaderDataType
{
None = 0,
Float,
Float2,
Float3,
Float4,
Mat3,
Mat4,
Int,
Int2,
Int3,
Int4,
Bool
};
struct BufferFormatElement
{
std::string m_name;
GLuint m_size;
GLuint m_offset;
ShaderDataType m_type;
bool m_normalized;
BufferFormatElement() {}
BufferFormatElement(ShaderDataType type, std::string name, bool normalized = false)
: m_name(name), m_type(type), m_size(ShaderDataTypeSize(type)), m_offset(0), m_normalized(normalized) {}
static GLuint ShaderDataTypeSize(ShaderDataType type)
{
switch (type)
{
case ShaderDataType::Float:
return 4;
case ShaderDataType::Float2:
return 4 * 2;
case ShaderDataType::Float3:
return 4 * 3;
case ShaderDataType::Float4:
return 4 * 4;
case ShaderDataType::Mat3:
return 4 * 3 * 3;
case ShaderDataType::Mat4:
return 4 * 4 * 4;
case ShaderDataType::Int:
return 4;
case ShaderDataType::Int2:
return 4 * 2;
case ShaderDataType::Int3:
return 4 * 3;
case ShaderDataType::Int4:
return 4 * 4;
case ShaderDataType::Bool:
return 1;
}
return 0;
}
GLuint component_count() const
{
switch (m_type)
{
case ShaderDataType::Float:
return 1;
case ShaderDataType::Float2:
return 2;
case ShaderDataType::Float3:
return 3;
case ShaderDataType::Float4:
return 4;
case ShaderDataType::Mat3:
return 3 * 3;
case ShaderDataType::Mat4:
return 4 * 4;
case ShaderDataType::Int:
return 1;
case ShaderDataType::Int2:
return 2;
case ShaderDataType::Int3:
return 3;
case ShaderDataType::Int4:
return 4;
case ShaderDataType::Bool:
return 1;
}
return 0;
}
GLenum gl_type() const
{
switch (m_type)
{
case ShaderDataType::Float:
return GL_FLOAT;
case ShaderDataType::Float2:
return GL_FLOAT;
case ShaderDataType::Float3:
return GL_FLOAT;
case ShaderDataType::Float4:
return GL_FLOAT;
case ShaderDataType::Mat3:
return GL_FLOAT;
case ShaderDataType::Mat4:
return GL_FLOAT;
case ShaderDataType::Int:
return GL_INT;
case ShaderDataType::Int2:
return GL_INT;
case ShaderDataType::Int3:
return GL_INT;
case ShaderDataType::Int4:
return GL_INT;
case ShaderDataType::Bool:
return GL_BOOL;
}
return 0;
}
};
class BufferFormat
{
public:
BufferFormat() {}
BufferFormat(const std::initializer_list<BufferFormatElement> &elements)
: m_elements(elements)
{
m_stride = 0;
uint32_t offset = 0;
for (auto &e : m_elements)
{
e.m_offset = offset;
offset += e.m_size;
m_stride += e.m_size;
}
}
~BufferFormat() {}
inline const std::vector<BufferFormatElement> &elements() const { return m_elements; }
inline const GLuint stride() const { return m_stride; }
std::vector<BufferFormatElement>::iterator begin() { return m_elements.begin(); }
std::vector<BufferFormatElement>::iterator end() { return m_elements.end(); }
std::vector<BufferFormatElement>::const_iterator begin() const { return m_elements.begin(); }
std::vector<BufferFormatElement>::const_iterator end() const { return m_elements.end(); }
private:
std::vector<BufferFormatElement> m_elements;
GLuint m_stride = 0;
};
template <typename T>
class Buffer
{
public:
Buffer();
~Buffer();
void set_format(const BufferFormat &format);
void create(std::vector<T> &data);
void update(std::vector<T> &data, GLuint offset);
inline const GLuint count() const { return m_count; }
inline GLuint name() { return m_buffer_ID; }
inline const BufferFormat &format() const { return m_format; }
GLuint m_buffer_ID;
BufferFormat m_format;
GLuint m_count;
GLuint m_data_size;
};
template <typename T>
Buffer<T>::Buffer()
: m_buffer_ID(0), m_format(BufferFormat()), m_count(0), m_data_size(0)
{
}
template <typename T>
void Buffer<T>::create(std::vector<T> &data)
{
glDeleteBuffers(1, &m_buffer_ID);
glCreateBuffers(1, &m_buffer_ID);
glNamedBufferData(m_buffer_ID, sizeof(T) * data.size(), &data[0], GL_DYNAMIC_DRAW);
m_data_size = sizeof(T) * data.size();
if (!m_format.stride())
{
m_count = data.size();
}
else
{
m_count = m_data_size / m_format.stride();
}
}
template <typename T>
void Buffer<T>::update(std::vector<T> &data, GLuint offset)
{
glNamedBufferSubData(m_buffer_ID, offset * sizeof(T), sizeof(T) * data.size(), &data[0]);
}
template <typename T>
Buffer<T>::~Buffer()
{
glDeleteBuffers(1, &m_buffer_ID);
}
template <typename T>
void Buffer<T>::set_format(const BufferFormat &format)
{
m_format = format;
m_count = m_data_size / format.stride();
}
#endif | 25.641509 | 112 | 0.592347 | [
"vector"
] |
7b8a9f0eedcbb5386f9f9a9746c5c3f87964863c | 1,141 | cpp | C++ | dataStruct/cpp/LevelTraversal.cpp | FreezeSnail/LeetCode-Problems | 9754af9193b03fd2235c4ef8ec508f004ddf023f | [
"MIT"
] | null | null | null | dataStruct/cpp/LevelTraversal.cpp | FreezeSnail/LeetCode-Problems | 9754af9193b03fd2235c4ef8ec508f004ddf023f | [
"MIT"
] | null | null | null | dataStruct/cpp/LevelTraversal.cpp | FreezeSnail/LeetCode-Problems | 9754af9193b03fd2235c4ef8ec508f004ddf023f | [
"MIT"
] | null | null | null | /**102. Binary Tree Level Order Traversal
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
/*Runtime: 4 ms, faster than 91.61% of C++ online submissions for Binary Tree Level Order Traversal.
Memory Usage: 13.6 MB, less than 11.60% of C++ online submissions for Binary Tree Level Order Traversal.
*/
void bfs(int depth, TreeNode * root, vector<vector<int>> & levels){
if(root != nullptr){
if(levels.size() <= depth)
levels.push_back({});
levels[depth].push_back(root->val);
bfs(depth+1, root->left, levels);
bfs(depth+1, root->right, levels);
}
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> levels;
bfs(0, root, levels);
return levels;
}
}; | 33.558824 | 108 | 0.581946 | [
"vector"
] |
7b8bb8eadeac30176f6a2ccef3d854be96546ca5 | 63,778 | cpp | C++ | src/raven_src/src/CommonFunctions.cpp | Okanagan-Basin-Water-Board/obwb-hydro-modelling | 91ee6b914e344de65a495093c3b9427986182ef2 | [
"Artistic-2.0"
] | null | null | null | src/raven_src/src/CommonFunctions.cpp | Okanagan-Basin-Water-Board/obwb-hydro-modelling | 91ee6b914e344de65a495093c3b9427986182ef2 | [
"Artistic-2.0"
] | null | null | null | src/raven_src/src/CommonFunctions.cpp | Okanagan-Basin-Water-Board/obwb-hydro-modelling | 91ee6b914e344de65a495093c3b9427986182ef2 | [
"Artistic-2.0"
] | null | null | null | //////////////////////////////////////////////////////////////////
/// Raven Library Source Code
/// Copyright (c) 2008-2020 the Raven Development Team
//////////////////////////////////////////////////////////////////
#include <time.h>
#include "RavenInclude.h"
//////////////////////////////////////////////////////////////////
/// \brief Returns a string describing the process corresponding to the enumerated process type passed
///
/// \param p [in] Type of proceses
/// \return String equivalent of the process_type identifier
//
string GetProcessName(process_type p)
{
static string name;
switch(p)
{
case(NULL_PROCESS_TYPE): {name="NULL"; break;}
case(FLUSH): {name="Flush"; break;}
case(SPLIT): {name="Split"; break;}
case(OVERFLOW_PROC): {name="Overflow"; break;}
case(EXCHANGE_FLOW): {name="Exchange Flow"; break;}
case(PRECIPITATION): {name="Precipitation"; break;}
case(BASEFLOW): {name="Baseflow"; break;}
case(INFILTRATION): {name="Infiltration"; break;}
case(INTERFLOW): {name="Interflow"; break;}
//case(REDISTRIBUTION): {name="Soil Moisture Redistribution"; break;}
case(PERCOLATION): {name="Percolation"; break;}
case(SOIL_EVAPORATION): {name="Soil Evaporation"; break;}
case(CAPILLARY_RISE): {name="Capillary Rise"; break;}
case(CANOPY_EVAPORATION): {name="Canopy Evaporation"; break;}
case(CANOPY_SNOW_EVAPORATION):{name="Canopy Snow Evaporation";break;}
case(CANOPY_DRIP): {name="Canopy Drip"; break;}
case(OPEN_WATER_EVAPORATION):{name="Open Water Evaporation";break;}
case(LAKE_EVAPORATION): {name="Lake Evaporation"; break;}
case(LAKE_RELEASE): {name="Lake Release"; break;}
case(DEPRESSION_OVERFLOW):{name="Depression Overflow"; break;}
case(SEEPAGE): {name="Seepage from Depression"; break;}
case(RECHARGE): {name="Recharge"; break;}
case(DRAIN): {name="Drain"; break;}
case(SNOWMELT): {name="Snow Melt"; break;}
case(SNOWSQUEEZE): {name="Liquid snow release"; break;}
case(REFREEZE): {name="Snow Refreeze"; break;}
case(SUBLIMATION): {name="Sublimation"; break;}
case(SNOW_BALANCE): {name="Snow Melt & Refreeze"; break;}
case(GLACIER_MELT): {name="Glacier Melt"; break;}
case(GLACIER_RELEASE): {name="Glacier Release"; break;}
case(GLACIER_INFIL): {name="Glacier Infiltration"; break;}
case(SNOW_ALBEDO_EVOLVE): {name="Snow Albedo Evolution"; break;}
case(BLOWING_SNOW): {name="Blowing Snow"; break;}
case(CROP_HEAT_UNIT_EVOLVE):{name="Crop Heat Unit Evolution";break;}
case(ABSTRACTION): {name="Abstraction"; break;}
case(SNOWTEMP_EVOLVE): {name="Snow Temp. Evolution"; break;}
case(CONVOLVE): {name="Convolution"; break;}
case(PROCESS_GROUP): {name="Process Group"; break;}
case(ADVECTION): {name="Advection"; break;}
case(LAT_ADVECTION): {name="Lateral Advection"; break;}
case(LAT_FLUSH): {name="Lateral Flush"; break;}
case(DECAY): {name="Decay"; break;}
case(TRANSFORMATION): {name="Transformation"; break;}
//..
default: {
name="Unknown Hydrological Process";
ExitGracefully("GetProcessName: Unknown Hydrological Process",RUNTIME_ERR);//STRICT
break;
}
}
return name;
}
///////////////////////////////////////////////////////////////////////////
/// \brief Determines if parameter value is to be autocalculated
/// \remark Used in override of parameter/property values with defaults (in AutoCalculate routines)
///
/// \param &val [out] Parameter value to be determined
/// \param set_val [in] Parameter value specified, or USE_TEMPLATE_VALUE if the template is to be applied
/// \param template_val [in] Parameter value if the default template is to be applied
/// \return Boolean indicating if the parameter value is to be autocalculated
//
bool SetCalculableValue(double &val, double set_val, double template_val)
{
// preferred approach if master parameter list is complete
if ((template_val==NOT_NEEDED) || (template_val==NOT_NEEDED_AUTO)){
val=template_val; //even if value specified, overriden, because it is not needed
return false; //autocalculation not needed
}
//approach needed to account for the fact that master parameter list may be incomplete
if (template_val==NOT_NEEDED_AUTO){
template_val=AUTO_COMPUTE;
}
val =set_val;
if (val==USE_TEMPLATE_VALUE){val=template_val;} //override with default
return (val==AUTO_COMPUTE); //returns true if the parameter value is to be autocalculated
}
///////////////////////////////////////////////////////////////////////////
/// \brief Sets the value of a non-autocalculable model parameter
/// \remark Used in override of parameter/property values with defaults (in AutoCalculate routines)
///
/// \param &val [out] Parameter value to be specified
/// \param set_val [in] Parameter value specified, or USE_TEMPLATE_VALUE if the template is to be applied
/// \param template_val [in] Parameter value if the default template is to be applied
/// \param needed [in] Indicates if parameter value is needed
/// \return Boolean indicating if the parameter value is not specified but required by model
/// \note this is only used for non-autogeneratable parameters
/// \todo [QA/QC] this routine should take in parameter name and class for better warnings to be produced
//
bool SetSpecifiedValue(double &val, double set_val, double template_val, bool needed, string pname)
{
val =set_val;
if (val==USE_TEMPLATE_VALUE){val=template_val;} //override with template
if ((val==USE_TEMPLATE_VALUE) && (template_val==AUTO_COMPUTE))
{
string errmsg;
errmsg = "SetSpecifiedValue::Cannot specify _AUTO as the template value for any parameter that cannot be autocomputed. A required parameter "+pname+"is missing from the .rvp file.";
ExitGracefully(errmsg.c_str(),BAD_DATA_WARN);
}
if (val==AUTO_COMPUTE)
{
string errmsg;
errmsg = "SetSpecifiedValue::Cannot specify _AUTO as the default value for any parameter that cannot be autocomputed. A required parameter " + pname + "is missing from the .rvp file";
ExitGracefully(errmsg.c_str(),BAD_DATA_WARN);
}
return ((val==NOT_SPECIFIED) && (needed)); //returns true (bad) if the parameter value is not specified, but needed
}
///////////////////////////////////////////////////////////////////////////
/// \brief Determines default parameter value
/// \remark Default template values depend upon whether the parameter is autocalculable
/// \docminor Parameters could be better described
///
/// \param is_template [in] true if the default value being set is for the template class
/// \param is_computable [in] true if the value is autocalculable
/// \return default parameter value for the parameter
//
double DefaultParameterValue(bool is_template, bool is_computable)
{
if (!is_template){return USE_TEMPLATE_VALUE;} //this is the default value for all parameters
else //default template values depend upon whether the parameter is autocalculable
{
//if (is_computable){return AUTO_COMPUTE;}
//else {return NOT_SPECIFIED;}
if (is_computable){return NOT_NEEDED_AUTO;}
else {return NOT_NEEDED;}
}
}
///////////////////////////////////////////////////////////////////////////
/// \brief Dynamically append pointer to array
/// \details Dynamically adds additional pointer (*xptr) onto array of pointers (**pArr) of
/// initial size indicated by parameter. Increments size by 1
///
/// \param **&pArr [out] Array of pointers to which *xptr will be added
/// \param *xptr [in] Pointer to be added to array
/// \param &size [in & out] Integer size of array
/// \return Boolean indicating success of method
//
bool DynArrayAppend(void **& pArr, void *xptr,int &size)
{
void **tmp=NULL;
if (xptr==NULL){return false;}
if ((pArr==NULL) && (size>0)) {return false;}
size=size+1; //increment size
tmp=new void *[size+1]; //allocate memory
if (tmp==NULL){ExitGracefully("DynArrayAppend::Out of memory",OUT_OF_MEMORY);}
for (int i=0; i<(size-1); i++){ //copy array
#if _STRICTCHECK_
if (pArr[i]==NULL){ExitGracefully("DynArrayAppend::Bad existing array",RUNTIME_ERR);}
#endif
tmp[i]=pArr[i];
}
tmp[size-1]=xptr; //add new pointer
if (size>1){delete [] pArr; pArr=NULL;} //delete old array of pointers
pArr=tmp; //redirect pointer
return true;
}
/**************************************************************************
Threshold Smoothing functions
---------------------------------------------------------------------------
From Kavetski & Kuczera, 2007
**************************************************************************/
///////////////////////////////////////////////////////////////////////////
/// \brief Enforces positivity of input value \cite Kavetski2007WRR
/// \todo [funct] Work needed here if smoothing is to be used
///
/// \param &val [in] input value on which positivity is enforced
/// \return Returns the value itself if it is greater than 0.0, otherwise returns 0.0.
//
double threshPositive(const double &val)
{
return max(val,0.0);
//return threshMax(val,0.0,0.01);
}
////////////////////////////////////////////////////////////////////////////
/// \brief Implementation of Chen-Harker-Kanzow-Smale max function \cite Chen2000JRSOJ
/// \remark Result is normalized: deviation from actual max does not exceed smooth_coeff (@ v1-v2=0)
/// \param &v1 [in] First input value to function
/// \param &v2 [in] Second input value to function
/// \param &smooth_coeff [in] Smoothing coefficient parameter
/// \return Double output of function
double threshMax(const double &v1, const double &v2, const double &smooth_coeff)
{
double x=(v2-v1);
if (smooth_coeff==0.0) {return max(v1,v2);}
else if (fabs(x)/smooth_coeff>100.0){return max(v1,v2 );}//avoids numerical errors
else{
return v1 + 0.5*(x + sqrt(x*x + 4.0*smooth_coeff*smooth_coeff));
}
}
////////////////////////////////////////////////////////////////////////////
/// \brief Implementation of Chen-Harker-Kanzow-Smale min function \cite Chen2000JRSOJ
/// \remark Result is normalized: deviation from actual min does not exceed smooth_coeff (@ v1-v2=0)
///
/// \param &v1 [in] First input value to function
/// \param &v2 [in] Second input value to function
/// \param &smooth_coeff [in] Smoothing coefficient parameter
/// \return Double output of function
//
double threshMin(const double &v1, const double &v2, const double &smooth_coeff)
{
double x=(v2-v1);
if (smooth_coeff==0.0) {return min(v1,v2);}
else if (fabs(x)/smooth_coeff>100.0){return min(v1,v2);}//avoids numerical errors
else{
return v2 - 0.5 * (x + sqrt(x*x + 4.0*smooth_coeff*smooth_coeff));
}
}
////////////////////////////////////////////////////////////////////////////
/// \brief Returns boolean value indicating if year passed is a leap year
/// \note Only valid until ~4000 AD
///
/// \param year [in] Integer year
/// \param calendar [in] enum int of calendar used
/// \return Boolean value indicating if year passed is a leap year
bool IsLeapYear(const int year, const int calendar)
{
bool leap = false;
// handle default CALENDAR_PROLEPTIC_GREGORIAN first for code efficiency
if (calendar == CALENDAR_PROLEPTIC_GREGORIAN){
leap = (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)); //valid until ~4000 AD:)
return leap;
}
if(calendar==CALENDAR_365_DAY){return false;}
if(calendar==CALENDAR_366_DAY){return true; }
// other calendars
if ((calendar == CALENDAR_JULIAN ||
calendar == CALENDAR_STANDARD ||
calendar == CALENDAR_GREGORIAN ) &&
(year % 4 == 0)) {
leap = true;
if ((calendar == CALENDAR_STANDARD ||
calendar == CALENDAR_GREGORIAN) &&
(year % 100 == 0) && (year % 400 != 0) && (year > 1583)) {
leap = false;
}
}
return leap;
}
///////////////////////////////////////////////////////////////////////////
/// \brief Fills time structure tt
/// \details Converts Julian decimal date to string and returns day of month, month,
/// and year in time_struct. \n If dec_date >365/366, then year is incremented. Accounts for leap years
///
/// \param &model_time [in] Time elapsed since start of simulation
/// \param start_date [in] double simulation start date (Julian date)
/// \param start_year [in] Integer simulation start year
/// \param calendar [in] enum int of calendar used
/// \param &tt [out] Time structure to house date information
//
void JulianConvert(double model_time, const double start_date, const int start_year, const int calendar, time_struct &tt)
{
int leap(0);
string mon;
double sum,days,ddate;
double dday;
int dmonth,dyear;
//handles daily roundoff error, (e.g., t=4.999873->t=5.0)
if( (model_time-floor(model_time)) > (1-TIME_CORRECTION))
{
model_time = floor(model_time+TIME_CORRECTION);
}
double dec_date=start_date+model_time; //decimal date calculated from start_date,start year
dyear=start_year;
ddate=dec_date;
if (IsLeapYear(dyear,calendar)){leap=1;}
while (ddate>=(365+leap)) //correct for years
{
ddate-=(365.0+leap);
dyear++;
leap=0;if (IsLeapYear(dyear,calendar)){leap=1;}
}
//ddate is now decimal julian date from Jan 1 0:00:00 of current dyear
dmonth=1; days=31;sum=31-TIME_CORRECTION; mon="Jan";
if (ddate>=sum){dmonth+=1;days=28+leap;sum+=days;mon="Feb";}//Feb
if (ddate>=sum){dmonth+=1;days=31; sum+=days;mon="Mar";}//Mar
if (ddate>=sum){dmonth+=1;days=30; sum+=days;mon="Apr";}//Apr
if (ddate>=sum){dmonth+=1;days=31; sum+=days;mon="May";}//May
if (ddate>=sum){dmonth+=1;days=30; sum+=days;mon="Jun";}//Jun
if (ddate>=sum){dmonth+=1;days=31; sum+=days;mon="Jul";}//Jul
if (ddate>=sum){dmonth+=1;days=31; sum+=days;mon="Aug";}//Aug
if (ddate>=sum){dmonth+=1;days=30; sum+=days;mon="Sep";}//Sep
if (ddate>=sum){dmonth+=1;days=31; sum+=days;mon="Oct";}//Oct
if (ddate>=sum){dmonth+=1;days=30; sum+=days;mon="Nov";}//Nov
if (ddate>=sum){dmonth+=1;days=31; sum+=days;mon="Dec";}//Dec
dday=ddate-sum+days; //decimal days since 0:00 on first of month
tt.model_time=model_time;
tt.julian_day=ddate;
tt.day_of_month=(int)(ceil(dday+REAL_SMALL)); //real_small to handle dday=1.0
if (tt.day_of_month==0){tt.day_of_month=1;}
tt.month =dmonth;
tt.year=dyear;
tt.day_changed = false;
if((model_time <= PRETTY_SMALL) || (tt.julian_day-floor(tt.julian_day+TIME_CORRECTION)<PRETTY_SMALL)) { tt.day_changed = true; }
static char out[50];
sprintf(out,"%4.4d-%2.2i-%2.2d",dyear,tt.month,tt.day_of_month); //2006-02-28 (ISO Standard)
tt.date_string=string(out);
tt.leap_yr=IsLeapYear(tt.year,calendar);
}
////////////////////////////////////////////////////////////////////////////
/// \brief Returns time-of-day string for decimal date (e.g., day=124.3-->"07:12",day=1.5 -->"12:00")
///
/// \param dec_date [in] Decimal date
/// \return String hours of day in 00:00:00.00 format
//
string DecDaysToHours(const double dec_date, const bool truncate)
{
double hours=(dec_date-floor(dec_date))*24.0;
double mind =(hours -floor(hours ))*60.0;
double sec =(mind -floor(mind ))*60.0;
int hr=(int)(floor(hours));
int min=(int)(floor(mind));
if (sec>=59.995){min++;sec=0.0;} //to account for case where time is rounded up to 60 sec
if (min==60) {hr++; min=0;}
if (hr==24) {hr=0;}
static char out[12];
if (truncate){sprintf(out,"%2.2d:%2.2d:%2.2d",hr,min,(int)(sec));}
else {sprintf(out,"%2.2d:%2.2d:%05.2f",hr,min,sec);}
return string(out);
}
////////////////////////////////////////////////////////////////////////////
/// \brief returns time struct corresponding to string in the following format
/// \param sDate [in] date string in ISO standard format yyyy-mm-dd or yyyy/mm/dd
/// \param calendar [in] Enum int of calendar used
/// \param sTime [in] time string in ISO standard format hh:mm:ss.00
/// \return Time structure equivalent of passed date and time
//
time_struct DateStringToTimeStruct(const string sDate, string sTime, const int calendar)
{
static time_struct tt;
if (sDate.length()!=10){
string errString = "DateStringToTimeStruct: Invalid date format used: "+sDate;
ExitGracefully(errString.c_str(),BAD_DATA);
}
if (sTime.length()<7) {
string errString = "DateStringToTimeStruct: Invalid time format used (hourstamp): "+sTime;
ExitGracefully(errString.c_str(),BAD_DATA);
}
tt.date_string=sDate;
tt.year =s_to_i(sDate.substr(0,4).c_str());
tt.month =s_to_i(sDate.substr(5,2).c_str());
if (tt.month>12) {
string errString = "DateStringToTimeStruct: Invalid time format used (month>12): "+sDate;
ExitGracefully(errString.c_str(),BAD_DATA);
}
tt.day_of_month=s_to_i(sDate.substr(8,2).c_str());
tt.model_time =0.0;//unspecified
tt.leap_yr =IsLeapYear(tt.year,calendar);
tt.julian_day =tt.day_of_month-1;
if (tt.month>= 2){tt.julian_day+=31;}
if (tt.month>= 3){tt.julian_day+=28;}
if (tt.month>= 4){tt.julian_day+=31;}
if (tt.month>= 5){tt.julian_day+=30;}
if (tt.month>= 6){tt.julian_day+=31;}
if (tt.month>= 7){tt.julian_day+=30;}
if (tt.month>= 8){tt.julian_day+=31;}
if (tt.month>= 9){tt.julian_day+=31;}
if (tt.month>=10){tt.julian_day+=30;}
if (tt.month>=11){tt.julian_day+=31;}
if (tt.month==12){tt.julian_day+=30;}
if ((tt.leap_yr ) && (tt.month> 2)){tt.julian_day+= 1;}
int hr, min;
double sec;
if (sTime.substr(1,1)==":"){sTime="0"+sTime;} //for h:mm:ss.00 format to hh:mm:ss.00
ExitGracefullyIf((sTime.substr(2,1)!=":"),"DateStringToTimeStruct: Invalid time format used",BAD_DATA);
ExitGracefullyIf((sTime.substr(5,1)!=":"),"DateStringToTimeStruct: Invalid time format used",BAD_DATA);
hr =s_to_i(sTime.substr(0,2).c_str());
min =s_to_i(sTime.substr(3,2).c_str());
sec =s_to_d(sTime.substr(6,6).c_str());
tt.julian_day+=(double)(hr )/HR_PER_DAY;
tt.julian_day+=(double)(min)/MIN_PER_DAY;
tt.julian_day+=(double)(sec)/SEC_PER_DAY;
//Below reprocesses date string (optional)
JulianConvert(0.0, tt.julian_day, tt.year, calendar, tt);
return tt;
}
////////////////////////////////////////////////////////////////////////////
/// \brief returns true if julian date is between two julian days (days inclusive)
/// \param julian_day [in] julian date from 0.0 to 365.0
/// \param julian_start [in] integer start day of date range (0=Jan 1, 364=Dec 31 in non-leap)
/// \param julian_end [in] integer end day of date range (0=Jan 1, 364=Dec 31 in non-leap)
//
bool IsInDateRange(const double &julian_day,const int &julian_start,const int &julian_end)
{
if(julian_start<julian_end) {
return ((julian_day>=julian_start) && (julian_day<=julian_end));
}
else {
return ((julian_day>=julian_start) || (julian_day<=julian_end)); //wraps around Dec 31-Jan 1
}
}
////////////////////////////////////////////////////////////////////////////
/// \brief returns time struct corresponding to string in the following format
/// \param unit_t_str [in] full time string from NetCDF file (e.g., 'days since YYYY-MM-dd 00:00:00+0000')
/// \param timestr [in] first word of string (e.g., 'days')
/// \param calendar [in] enumerated calendar type
/// \param timezone [out] time shift from GMT, in days
/// \return Raven Time structure equivalent of passed date and time, time shift if applicable
//
time_struct TimeStructFromNetCDFString(const string unit_t_str,const string timestr,const int calendar,double &timezone)
{
string dash,colon,tmp;
tmp=unit_t_str;
timezone=0.0;
int start=(int)strlen(timestr.c_str());
start+=7; //first char of year YYYY (7=length(' since '))
// ---------------------------
// check if format is hours since YYYY-MM-DD HH:MM:SS, fill with leading zeros if necessary
// Y Y Y Y - M M - d d _ 0 0 : 0 0 : 0 0 . 0 + 0 0 0 0
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// ---------------------------
dash = tmp.substr(start+4,1); // first dash in date
if(!strstr(dash.c_str(),"-"))
{
printf("time unit string: %s\n",tmp.c_str());
ExitGracefully("CommonFunctions:TimeStructFromNetCDFString: time unit string has weird format!",BAD_DATA);
}
if(!strstr(tmp.substr(start+7 ,1).c_str(),"-")) { tmp.insert(start+5,"0"); } // second dash in date - fixes YYYY-M-dd
bool date_only=false;
if (strlen(tmp.c_str())<=start+10+2){date_only=true;} //00:00:00 +0000 not included in string
if(!date_only) {
if(!strstr(tmp.substr(start+10,1).c_str()," ")) { tmp.insert(start+8,"0"); } // second dash in date - fixes YYYY-MM-d
if(!strstr(tmp.substr(start+13,1).c_str(),":")) { tmp.insert(start+11,"0"); } // first colon in time - fixes 1:00:00
if(!strstr(tmp.substr(start+16,1).c_str(),":")) { tmp.insert(start+14,"0"); } // second colon in time - fixes 11:0:00 (?)
}
else {
if(strlen(tmp.c_str())==start+9) { tmp.insert(start+8,"0"); } // second dash in date - fixes YYYY-MM-d
}
string sTime,sDate;
sDate = tmp.substr(start,10); //YYYY-MM-DD
if(!date_only) { sTime = tmp.substr(start+11,8); } //HH:MM:SS
else { sTime = "00:00:00"; } // assumes start of day if no timestamp given
//cout<<"sTime"<<sTime<<" sDate"<< sDate<<" "<<unit_t_str<<" "<<date_only<<" "<<tmp<<endl;
timezone=0;
if((strlen(tmp.c_str())-start)==26) {
if(!strcmp(tmp.substr(start+22,1).c_str(),"+")) {
timezone=(double)(s_to_i(tmp.substr(start+23,4).c_str()))/HR_PER_DAY/100; //time zone, in days
}
else if(!strcmp(tmp.substr(start+22,1).c_str(),"-")) {
timezone=-(double)(s_to_i(tmp.substr(start+23,4).c_str()))/HR_PER_DAY/100; //time zone, in days
}
}
return DateStringToTimeStruct(sDate,sTime,calendar);
}
////////////////////////////////////////////////////////////////////////////
/// \brief returns time zone string in format " +0700" or " -1200"
/// \param tz [in] time zone as integer - hours from GMT
/// \return time zone as string in format " +0600" or "" if tz is zero
//
string TimeZoneToString(const int tz) {
string ends="";
if(tz<0) {
if(tz<-9) { ends=" -"+to_string(-tz)+"00"; }
else { ends=" -0"+to_string(-tz)+"00"; }
}
else if(tz>0) {
if(tz>9) { ends=" +"+to_string(tz)+"00"; }
else { ends=" +0"+to_string(tz)+"00"; }
}
return ends;
}
////////////////////////////////////////////////////////////////////////////
/// \brief returns time struct corresponding to string in the following format
/// \param unit_t_str [in] full time string from NetCDF file (e.g., '[days/minutes/hours] since YYYY-MM-dd 00:00:00{+0000}' or '[days/minutes/hours] since YYYY-MM-dd' )
/// \return true if string is valid
//
bool IsValidNetCDFTimeString(const string time_string)
{
int att_len=(int)strlen(time_string.c_str());
bool isvalid = true;
bool hastimestamp=true;
if (att_len<15) {return false;}
int subtract=0;
size_t pos=time_string.find("since",0);
if(pos==string::npos) { return false; } //no "since" in string
pos+=6;
string date_string=time_string.substr(pos,10);
if (!strstr(date_string.substr(4,1).c_str(),"-")){isvalid=false;}//properly located dashes in date string
if (!strstr(date_string.substr(7,1).c_str(),"-")){isvalid=false;}
if(time_string.length()<(pos+19)) { return isvalid; } //no time stamp
string hr_string =time_string.substr(pos+11,8);
//cout<<"TIME STRING: "<<time_string<<" "<<pos<<" "<<date_string<<" "<<hr_string<<endl;
if(!strstr(hr_string.substr(2,1).c_str(),":")) { isvalid=false; }//properly located dashes in date string
if(!strstr(hr_string.substr(5,1).c_str(),":")) { isvalid=false; }
return isvalid;
}
///////////////////////////////////////////////////////////////////
/// \brief calculates time difference, in days, between two specified dates
/// \details positive if day 2 is after day 1
///
/// \param jul_day1 [in] Julian day of date 1 (measured from Jan 1 of year @ 00:00:00)
/// \param year1 [in] year of date 1
/// \param jul_day2 [in] Julian day of date 2 (measured from Jan 1 of year @ 00:00:00)
/// \param year1 [in] year of date 2
/// \param calendar [in] enum int of calendar used
double TimeDifference(const double jul_day1,const int year1,const double jul_day2,const int year2, const int calendar)
{
int leap,yr;
double diff= jul_day2 - jul_day1;
yr=year2-1;
while (yr >= year1)
{
leap=0; if (IsLeapYear(yr,calendar)){ leap = 1; }
diff += (365+leap);
yr--;
}
yr=year2;
while (yr<year1)
{
leap=0; if (IsLeapYear(yr,calendar)){ leap = 1; }
diff -= (365+leap);
yr++;
}
return diff;
}
///////////////////////////////////////////////////////////////////
/// \brief adds specified number of days to julian date and returns resultant julian date
///
/// \param jul_day1 [in] Julian day of date 1 (measured from Jan 1 of year @ 00:00:00)
/// \param year1 [in] year of date 1
/// \param daysadded [in] positive or negative number of days (can be fractional days) added to date 1
/// \param &Options [in] Global model options information
/// \param jul_day_out [out] Julian day of output date (measured from Jan 1 of year @ 00:00:00)
/// \param year_out [out] year of output date
//
void AddTime(const double &jul_day1,const int &year1,const double &daysadded,const int calendar, double &jul_day_out,int &year_out)
{
int yr;
double leap;
double daysleft;
yr=year1;
jul_day_out=jul_day1;
if(daysadded>=0)
{
daysleft=daysadded;
do {
leap=0; if(IsLeapYear(yr,calendar)) { leap=1; }
if((jul_day_out+daysleft)<(365.0+leap)) {
jul_day_out+=daysleft;
year_out=yr;
break;
}
else {
yr++;
daysleft-=(365.0+leap-jul_day_out);
jul_day_out=0.0;
}
ExitGracefullyIf(daysleft<0.0,"Invalid input to AddTime routine (negative julian day?)",RUNTIME_ERR);
} while(true);
}
else
{ //if daysadded<0
daysleft=-daysadded;
do {
if((jul_day_out-daysleft)>=0.0) { //99% of cases
jul_day_out-=daysleft;
year_out=yr;
return;
}
else {
yr--;
leap=0; if(IsLeapYear(yr,calendar)) { leap=1; }
daysleft-=jul_day_out;
if(daysleft<(365+leap)){ jul_day_out=(365+leap)-daysleft;year_out=yr;break; }
else { jul_day_out=0.0;daysleft-=(365+leap); }//skip whole year
}
ExitGracefullyIf(daysleft<0.0,"Invalid input to AddTime routine (negative julian day?)",RUNTIME_ERR);
} while(true);
}
// if calendar is STANDARD or GREGORIAN and the original time is before 4 October 1582
// while the final time is after, one has to add additional 10 days
// because in this calendar the day following 4 October 1582 is 15 October 1582 (there are 10 days missing)
// --> THIS is why people usually use the Proleptic Gregorian calendar :)
if ((calendar == CALENDAR_STANDARD || calendar == CALENDAR_GREGORIAN) &&
((year1 == 1582 && jul_day1 <= 277) || (year1 < 1582)) &&
((year_out > 1582) || ((year_out == 1582) && (jul_day_out >= 278)))) {
double tmp_day;
int tmp_yr;
tmp_yr = year_out;
tmp_day = jul_day_out;
AddTime(tmp_day,tmp_yr,10.0,calendar,jul_day_out,year_out);
return;
}
return;
}
///////////////////////////////////////////////////////////////////
/// \brief Parse chars of calendar and return calendar integer
///
/// \param cal_chars [in] String conatining calendar name, e.g., "PROLEPTIC_GREGORIAN"
/// \param StringToCalendar [out] enum integer representing calendar
//
int StringToCalendar(string cal_chars)
{
string str=StringToUppercase(cal_chars);
if (strcmp("STANDARD", str.c_str()) == 0) {
return CALENDAR_STANDARD;
}
else if (strcmp("GREGORIAN", str.c_str()) == 0) {
return CALENDAR_GREGORIAN;
}
else if (strcmp("PROLEPTIC_GREGORIAN", str.c_str()) == 0) {
return CALENDAR_PROLEPTIC_GREGORIAN;
}
else if ((strcmp("NOLEAP", str.c_str()) == 0) || (strcmp("NO_LEAP", str.c_str()) == 0)) {
return CALENDAR_365_DAY;
}
else if (strcmp("365_DAY", str.c_str()) == 0) {
return CALENDAR_365_DAY;
}
else if (strcmp("360_DAY", str.c_str()) == 0) {
ExitGracefully("CommonFunctions: StringToCalendar: Raven does not support 360_DAY calendars!", BAD_DATA);
return CALENDAR_360_DAY;
}
else if (strcmp("JULIAN", str.c_str()) == 0) {
return CALENDAR_JULIAN;
}
else if (strcmp("ALL_LEAP", str.c_str()) == 0) {
return CALENDAR_366_DAY;
}
else if (strcmp("366_DAY", str.c_str()) == 0) {
return CALENDAR_366_DAY;
}
else {
printf("Calendar used: %s", str.c_str());
ExitGracefully("CommonFunctions: StringToCalendar: Unknown calendar specified!", BAD_DATA);
}
return -1; // just to avoid compiler warning of void function return
}
////////////////////////////////////////////////////// /////////////////////
/// \brief Round the timestep to the nearest fractional day
/// \return improved timestep
double FixTimestep(double tstep)
{
double tmp = round(1.0/tstep);
ExitGracefullyIf(fabs(tstep*tmp-1.0)>0.1,
"CommonFunctions::FixTimestep: timesteps and time intervals must evenly divide into one day",BAD_DATA);
return 1.0/tmp;
}
////////////////////////////////////////////////////// /////////////////////
/// \brief True if string is proper iso date (e.g., yyyy-mm-dd or yyyy/mm/dd)
/// \return true if valid date string
//
bool IsValidDateString(const string sDate)
{
return ((sDate.length()==10) &&
((sDate.substr(4,1)=="/") || (sDate.substr(4,1)=="-")) &&
((sDate.substr(7,1)=="/") || (sDate.substr(7,1)=="-")));
}
////////////////////////////////////////////////////// /////////////////////
/// \brief Get the current system date/time
/// \return "now" as an ISO formatted string
string GetCurrentTime(void)
{
// Get the current wall clock time
time_t now;
time(&now);
struct tm *curTime = localtime(&now);
// generate the ISO string
char s[20];
sprintf(s,"%4i-%02i-%02i %02i:%02i:%02i",
curTime->tm_year+1900, curTime->tm_mon+1, curTime->tm_mday,
curTime->tm_hour, curTime->tm_min, curTime->tm_sec);
return string(s);
}
///////////////////////////////////////////////////////////////////////////
/// \brief Interpolates monthly data stored in array aVal during year based on specified time
/// \remark Model time, t[days] is specified
///
/// \param aVal [in] Array of doubles representing monthly data
/// \param &tt [in] Time structure which specifies interpolation
/// \param &Options [in] Global model options information
/// \return Interpolated value at time denoted by &tt
double InterpolateMo(const double aVal[12],
const time_struct &tt,
const optStruct &Options)
{
double wt;
int leap(0),mo,nextmo;
int day, month, year;
day =tt.day_of_month;
month =tt.month;
year =tt.year;
if (Options.month_interp==MONTHINT_UNIFORM)//uniform over month
{
return aVal[month-1];
}
else if (Options.month_interp==MONTHINT_LINEAR_FOM)//linear from first of month
{
mo=month-1;
nextmo=mo+1;
if (nextmo==12){nextmo=0;}
leap=0;if ((IsLeapYear(year,Options.calendar)) && (mo==1)){leap=1;}
wt=1.0-(double)(day)/(DAYS_PER_MONTH[mo]+leap);
return wt*aVal[mo]+(1-wt)*aVal[nextmo];
}
else if ((Options.month_interp==MONTHINT_LINEAR_21) ||
(Options.month_interp==MONTHINT_LINEAR_MID))
//linear from 21st of month to 21st of next month (e.g., UBC_WM) or other day
{
double pivot=0.0;
if (Options.month_interp==MONTHINT_LINEAR_21){pivot=21;}
else if (Options.month_interp==MONTHINT_LINEAR_MID){
pivot=0.5*DAYS_PER_MONTH[month-1];
if ((IsLeapYear(year,Options.calendar)) && (month==2)){pivot+=0.5;}
}
if (day<=pivot)
{
mo=month-2;
nextmo=mo+1;
if (mo==-1){mo=11;nextmo=0;}
leap=0;if ((IsLeapYear(year,Options.calendar)) && (mo==1)){leap=1;}
wt=1.0-(double)((day+DAYS_PER_MONTH[mo]+leap-pivot)/(DAYS_PER_MONTH[mo]+leap));
}
else{
mo=month-1;
nextmo=mo+1;
if (nextmo==12){nextmo=0;}
leap=0;if ((IsLeapYear(year,Options.calendar)) && (mo==1)){leap=1;}
wt=1.0-(double)((day-pivot)/(DAYS_PER_MONTH[mo]+leap));
}
//\math \f$ wt=0.5-0.5*cos(wt*PI) \f$ ; //Useful smoothing function
return wt*aVal[mo]+(1-wt)*aVal[nextmo];
}
return 0.0;
}
//////////////////////////////////////////////////////////////////
/// \brief Calculates saturation vapor pressure [KPa] \cite Murray1966JAM
/// \remark Uses Dingman equation 7.4 \cite Dingman1994
// (Murray, Applied Meteorol 6:203, 1967)
///
/// \param &T [in] Temperature in Celsius
/// \return Saturated vapor pressure [kPa] corresponding to passed temperature
//
double GetSaturatedVaporPressure(const double &T)//[C]
{
const double A1=0.61078;
const double A2=17.26939;
const double A3=237.3;
const double A4=21.87456;
const double A5=265.5;
//0.61115*exp(22.452*T/(T+ZERO_CELSIUS)); //MESH
if (T>=0){return A1*exp(A2*T/(T+A3));} // Dingman/Brook90 version (Murray, 1967)
else {return A1*exp(A4*T/(T+A5));}
}
//////////////////////////////////////////////////////////////////
/// \brief Calculates saturation vapor pressure slope [de/dT]
/// \remark Uses Dingman equation 7.4 \cite Dingman1994 (Murray, Applied Meteorol 6:203, 1967) \cite Murray1966JAM
///
/// \param &T [in] Temperature in Celsius
/// \param &satvap [in] Saturated vapour pressure [kpa]
/// \return Saturated vapor pressure corresponding to passed temperature
//
double GetSatVapSlope(const double &T, const double &satvap)
{
const double A2=17.26939;
const double A3=237.3;
const double A4=21.87456;
const double A5=265.5;
//calculate d(sat_vap)/dT - Dingman 7.6 , SWAT 1:2.3.4
if (T>0){return A2*A3/pow(T+A3,2)*satvap;}
else {return A4*A5/pow(T+A5,2)*satvap;}
//from CRHM routine ClassCRHMCanopyClearingGap::delta
//if(T>0) { return(2504.0*exp(17.27 * T/(T+237.3)) / sqrt(T+237.3)); }
//else { return(3549.0*exp(21.88 * T/(T+265.5)) / sqrt(T+265.5)); }
}
//////////////////////////////////////////////////////////////////
/// \brief Calculates latent heat of vaporization [MJ/kg]
/// \remark Uses Dingman equation 7-8 (Harrison, 1963) \cite Dingman1994 \cite Harrison1963HaM
///
/// \param &T [in] Temperature in Celsius
/// \return Latent heat of vaporization [MJ/kg]
//
double GetLatentHeatVaporization(const double &T)
{
return 2.495-0.002361*T;//[MJ/kg]
}
//////////////////////////////////////////////////////////////////
/// \brief Returns latent psychometric constant [kPa/K] \cite Brunt1952
/// \remark Uses Dingman eqn. 7-13 \cite Dingman1994, SWAT 1:2.3.7\cite Neitsch2005 (Brunt, 1952)
///
/// \param &P [in] Atmospheric pressure [kPa]
/// \param &LH_vapor [in] Latent heat of vaporization [MJ/kg]
/// \return Psychometric constant [kPa/K]
//
double GetPsychometricConstant (const double &P,const double &LH_vapor)
{
return SPH_AIR/AIR_H20_MW_RAT*P/LH_vapor;//[kPa/K];
}
//////////////////////////////////////////////////////////////////
/// \brief Returns air density [kg/m3]
/// \remark From CLM Manual, pg. 12 \cite Oleson2012
///
/// \param &T [in] Temperature in Celsius
/// \param &P [in] Atmospheric pressure [kPa]
/// \return Air density [kg/m3]
//
double GetAirDensity(const double &T, const double &P)
{
double e=GetSaturatedVaporPressure(T);
return (P-0.378*e)/(DRY_GAS_CONST*(T+ZERO_CELSIUS))*GRAMS_PER_KG;
}
//////////////////////////////////////////////////////////////////
/// \brief Converts relative humidity to specific humidity
///
/// \param rel_hum [in] relative humidity [0-1]
/// \param air_press [in] Air pressure [kPa]
/// \param T [in] Air temperature [Celsius]
/// \return specific humidity, [kg/kg]
//
double GetSpecificHumidity(const double &rel_hum,const double &air_press,const double &T)
{
double e_a=rel_hum*GetSaturatedVaporPressure(T);
//simplified:
//return AIR_H20_MW_RAT*e_a/air_press;
return AIR_H20_MW_RAT*e_a/(air_press- e_a*(1-AIR_H20_MW_RAT));
}
//////////////////////////////////////////////////////////////////
/// \brief Converts passed temperature from Celsius to Farenheit
///
/// \param &T [in] Temperature in Celsius
/// \return Double temperature in Fahrenheit
//
double CelsiusToFarenheit(const double &T)
{
return 1.8*T+32.0;
}
//////////////////////////////////////////////////////////////////
/// \brief Calculates vertical transport efficiency of water vapor by turbulent eddies
/// \remark From Dingman pg. 273 \cite Dingman1994
///
/// \param &P [in] air pressure [kPa]
/// \param &ref_ht [in] Measurement height [m]
/// \param &zero_pl [in] Zero plane displacement [m]
/// \param &z0 [in] Coefficient of roughness
/// \return Vertical transport efficiency [m s^2/kg]
//
double GetVerticalTransportEfficiency(const double &P,
const double &ref_ht,
const double &zero_pl,
const double &z0)
{
double numer,denom;
numer = AIR_H20_MW_RAT*DENSITY_AIR;
denom = P*DENSITY_WATER*(1.0/pow(VON_KARMAN,2)*(pow((log((ref_ht - zero_pl)/z0)),2)));
return numer/denom; //[m s^2 Kg^-1]
}
//////////////////////////////////////////////////////////////////
/// \brief Calculates atmospheric conductivity [mm/s] for ET calculations
/// \ref From Dingman eqn. 7-49 \cite Dingman1994, Howell, T.A and Evett, S.R., USDA-ARS \cite Howell2004
///
/// \param &wind_vel [in] Wind velocity [m/d]
/// \param &meas_ht [in] Measurement height of wind vel [m] - must be greater than zero plane displacement
/// \param &zero_pl [in] Zero plane displacement [m]
/// \param &rough_ht [in] Roughness height [m]
/// \param &vap_rough_ht [in] Vapour roughness height [m]
/// \return Atmospheric conductivity [mm/s]
//
double CalcAtmosphericConductance(const double &wind_vel, //[m/d]
const double &meas_ht, //[m]
const double &zero_pl, //[m]
const double &rough_ht, //[m]
const double &vap_rough_ht) //[m]
{
double atmos_cond;
if (zero_pl==0.0){return 0.0;}
//'6.25' from Dingman equation 7-49 is roughly 1/VK^2 (~6)
atmos_cond=(wind_vel*MM_PER_METER*pow(VON_KARMAN,2));
atmos_cond/=(log((meas_ht-zero_pl)/rough_ht)*log((meas_ht-zero_pl)/vap_rough_ht));
return atmos_cond;//[mm/s]
}
//////////////////////////////////////////////////////////////////
/// \brief Calculates dew point temperature, in celsius
///
/// \param &Ta [in] Air temperature in Celsius
/// \param &rel_hum [in] Relative humidity [0..1]
/// \ref Magnus-Tetens approximation, Murray, F. W., On the computation of saturation vapor pressure, J. Appl. Meteorol., 6, 203-204, 1967. \cite Murray1966JAM
/// \return Dew point temperature [C]
//
double GetDewPointTemp(const double &Ta, //air temp, [C]
const double &rel_hum)//relative humidity [0..1]
{
const double a=17.27;
const double b=237.7;//[C]
double tmp=(a*Ta/(b+Ta))+log(rel_hum);
return b*tmp/(a-tmp);
}
//////////////////////////////////////////////////////////////////
/// \brief Calculates dew point temperature
/// \ref from Dingman eqn D-11 \cite Dingman1994; can also be used to estimate rain temperature
///
/// \param &e [in] vapour pressure [kPa]
/// \return Dew point temperature [C]
//
double GetDewPointTemp(const double &e)
{
double numer,denom;
numer= log(e)+0.4926;
denom= 0.0708 - 0.00421*log(e);
return numer/denom; //[C]
}
//////////////////////////////////////////////////////////////////
/// \brief converts volumetric enthalpy of water/ice only [MJ/m3 water] to temperature
///
/// \param hv [in] volumetric enthapy [MJ/m3 water]
/// \return water temperature [C]
//
double ConvertVolumetricEnthalpyToTemperature(const double &hv)
{
if (hv>0 ){return hv/SPH_WATER/DENSITY_WATER;}
else if (hv>-LH_FUSION*DENSITY_WATER){return 0.0;}
else {return (hv+LH_FUSION*DENSITY_WATER)/SPH_ICE/DENSITY_ICE; }
}
double ConvertTemperatureToVolumetricEnthalpy(const double &T,const double &pctfroz)
{
if (fabs(T)<REAL_SMALL) { return -pctfroz*LH_FUSION*DENSITY_WATER;} //along zero line
else if (T>0 ) { return T*SPH_WATER*DENSITY_WATER; }
else { return T*SPH_ICE *DENSITY_ICE-LH_FUSION*DENSITY_WATER;}
}
double ConvertVolumetricEnthalpyToIceContent(const double &hv)
{
if (hv>0 ){return 0;}
else if (hv>-LH_FUSION*DENSITY_WATER){return -hv/LH_FUSION/DENSITY_WATER;}
else {return 1.0; }
}
//////////////////////////////////////////////////////////////////
/// \brief Converts any lowercase characters in a string to uppercase, returning the converted string
/// \param &s [in] String to be converted to uppercase
/// \return &s converted to uppercase
//
string StringToUppercase(const string &s)
{
string ret(s.size(), char());
for(int i = 0; i < (int)(s.size()); ++i)
{
if ((s[i] <= 'z' && s[i] >= 'a')){ret[i] = s[i]-('a'-'A');}
else {ret[i] = s[i];}
}
return ret;
}
//////////////////////////////////////////////////////////////////
/// \brief Simple and fast atof (ascii to float) function.
/// \notes Executes about 5x faster than standard MSCRT library atof().
///
/// \notes ported from 09-May-2009 Tom Van Baak (tvb) www.LeapSecond.com
//
#define white_space(c) ((c) == ' ' || (c) == '\t')
#define valid_digit(c) ((c) >= '0' && (c) <= '9')
double fast_s_to_d (const char *p)
{
int frac;
double sign, value, scale;
// Skip leading white space, if any.
while (white_space(*p) ) {
p += 1;
}
// Get sign, if any.
sign = 1.0;
if (*p == '-') {
sign = -1.0;
p += 1;
} else if (*p == '+') {
p += 1;
}
// Get digits before decimal point or exponent, if any.
for (value = 0.0; valid_digit(*p); p += 1) {
value = value * 10.0 + (*p - '0');
}
// Get digits after decimal point, if any.
if (*p == '.') {
double pow10 = 10.0;
p += 1;
while (valid_digit(*p)) {
value += (*p - '0') / pow10;
pow10 *= 10.0;
p += 1;
}
}
// Handle exponent, if any.
frac = 0;
scale = 1.0;
if ((*p == 'e') || (*p == 'E')) {
unsigned int expon;
// Get sign of exponent, if any.
p += 1;
if (*p == '-') {
frac = 1;
p += 1;
} else if (*p == '+') {
p += 1;
}
// Get digits of exponent, if any.
for (expon = 0; valid_digit(*p); p += 1) {
expon = expon * 10 + (*p - '0');
}
if (expon > 308) expon = 308;
// Calculate scaling factor.
while (expon >= 50) { scale *= 1E50; expon -= 50; }
while (expon >= 8) { scale *= 1E8; expon -= 8; }
while (expon > 0) { scale *= 10.0; expon -= 1; }
}
// Return signed and scaled floating point result.
return sign * (frac ? (value / scale) : (value * scale));
}
//////////////////////////////////////////////////////////////////
/// \brief Converts any string to corresponding HRU Type
/// \param &s [in] String to be converted to uppercase
/// \return type, defaults to standard (doesn't complain)
//
HRU_type StringToHRUType(const string s)
{
string sup;
sup=StringToUppercase(s);
if (!s.compare("GLACIER" )){return HRU_GLACIER;}
else if (!s.compare("LAKE" )){return HRU_LAKE;}
else if (!s.compare("ROCK" )){return HRU_ROCK;}
else if (!s.compare("WETLAND" )){return HRU_WETLAND;}
else if (!s.compare("STANDARD")){return HRU_STANDARD;}
#ifdef _STRICTCHECK_
ExitGracefully("StringToHRUType: unrecognized hru type code",BAD_DATA);
#endif
return HRU_INVALID_TYPE;
}
//////////////////////////////////////////////////////////////////
/// \brief returns true if line is empty, begins with '#' or '*'
/// \param &s [in] first string token in file line
/// \param Len length of line
/// \return true if line is empty or a comment
//
bool IsComment(const char *s, const int Len)
{
if ((Len==0) || (s[0]=='#') || (s[0]=='*')){return true;}
return false;
}
//////////////////////////////////////////////////////////////////
/// \brief replaces all instances of substring 'from' with string 'to in string str
/// \param &str [in/out] string subjected to modification
/// \param &from [in] substring to be replaced
/// \param &to [in] substring to replace it with
/// from solution by Michael Mrozek in https://stackoverflow.com/questions/3418231/replace-part-of-a-string-with-another-string
//
void SubstringReplace(string &str,const string &from,const string &to)
{
if(from.empty()) { return; }
size_t start_pos = 0;
while((start_pos = str.find(from,start_pos)) != std::string::npos) {
str.replace(start_pos,from.length(),to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
/////////////////////////////////////////////////////////////////
/// \brief writes warning to screen and to Raven_errors.txt file
/// \param warn [in] warning message printed
//
void WriteWarning(const string warn, bool noisy)
{
if (!g_suppress_warnings){
ofstream WARNINGS;
WARNINGS.open((g_output_directory+"Raven_errors.txt").c_str(),ios::app);
if (noisy){cout<<"WARNING!: "<<warn<<endl;}
WARNINGS<<"WARNING : "<<warn<<endl;
WARNINGS.close();
}
}
/////////////////////////////////////////////////////////////////
/// \brief writes advisory to screen and to Raven_errors.txt file
/// \param warn [in] warning message printed
//
void WriteAdvisory(const string warn, bool noisy)
{
if (!g_suppress_warnings){
ofstream WARNINGS;
WARNINGS.open((g_output_directory+"Raven_errors.txt").c_str(),ios::app);
if (noisy){cout<<"ADVISORY: "<<warn<<endl;}
WARNINGS<<"ADVISORY : "<<warn<<endl;
WARNINGS.close();
}
}
///////////////////////////////////////////////////////////////////
/// \brief NetCDF error handling
/// \return Error string and NetCDF exit code
//
void HandleNetCDFErrors(int error_code){
#ifdef _RVNETCDF_
if(error_code==0){ return; }
else{
string warn;
warn="NetCDF error ["+ to_string(nc_strerror(error_code))+"] occured.";
ExitGracefully(warn.c_str(),BAD_DATA);
}
#endif
}
///////////////////////////////////////////////////////////////////
/// \brief Return AUTO_COMPUTE tag if passed string is tagged, otherwise convert to double
/// \param s [in] Input string
/// \return AUTO_COMPUTE or USE_TEMPLATE_VALUE tag if string is tagged, otherwise double conversion of string
//
double AutoOrDouble(const string s)
{
if (!s.compare("_AUTO" )){return AUTO_COMPUTE;}
if (!s.compare("AUTO" )){return AUTO_COMPUTE;}
if (!s.compare("_DEFAULT")){return USE_TEMPLATE_VALUE;}
if (!s.compare("_DEF" )){return USE_TEMPLATE_VALUE;}
return s_to_d(s.c_str());
}
///////////////////////////////////////////////////////////////////
/// \brief Returns same number unless really small and g_suppress_zeros is true, then zeros out
/// \param d [in] Input double
/// \return d or zero, if d is near zero
//
double FormatDouble(const double &d)
{
if((g_suppress_zeros) && (fabs(d)<REAL_SMALL)){return 0.0;}
return d;
}
//////////////////////////////////////////////////////////////////
/// \brief Determines the complementary error of passed double &x (i.e., erfc(x))
/// \remark From Charbeneau, Groundwater Hydraulics and Pollutant Transport, 2000\cite Charbeneau2002AMR
/// \param &x [in] Double input into the function
/// \return Complementary error of &x, erfc(x)
//
double rvn_erfc(const double &x)
{
double tmp(fabs(x)); //take abs so that we are always in positive quadrant.
static double fun;
static double f1;
static double tmp2;
static double tmp3;
if(tmp > 3.0){
f1 = (1.0 - 1.0/(2.0 * tmp * tmp)
+ 3.0/(4.0 * pow(tmp,4))
- 5.0/(6.0 * pow(tmp,6)));
fun = f1 * exp(-tmp * tmp) / (tmp * sqrt(PI));
}
else{
tmp2 = 1.0 / (1.0 + (0.3275911 * tmp));
tmp3 = 0.254829592 * tmp2 //5th order polynomial interpolation
- (0.284496736 * tmp2 * tmp2)
+ (1.421413741 * pow(tmp2,3))
- (1.453152027 * pow(tmp2,4))
+ (1.061405429 * pow(tmp2,5));
fun = tmp3 * exp(-tmp * tmp);
}
if (tmp == x) {return fun;}
else{return (2-fun);}
}
//////////////////////////////////////////////////////////////////
/// \brief Calculates the error function of passed value x
/// \details Uses pre-defined complementary error function to define error function
///
/// \param &x [in] Double input into the funciton
/// \return Error of &x, erf(x)
//
double rvn_erf(const double &x)
{
return 1-rvn_erfc(x);
}
////////////////////////////////////////////////////////////////////
/// \brief Returns the value of the lognormal distribution function f_x(x) for the specified value x
/// \param &x [in] Double whose lognormal probability distribution value is to be returned
/// \param &mu [in] Mean of transformed function Y = ln(x)
/// \param &sig [in] Standard deviation of transformed distribution Y = ln(x)
/// \return Lognormal probability distribution value at x
//
double log_pdf(const double &x, const double &mu, const double &sig)
{
if (x<=0){return 0.0;}
return 1.0/x/sig/sqrt(2.0*PI)*exp(-0.5*(pow((log(x)-mu)/sig,2)));
}
/////////////////////////////////////////////////////////////////
/// \brief returns Nth recursive approximation of Lambert W_{-1} function
/// \remark From D.A. Barry et al. Used in some Green Ampt infiltration schemes \cite Barry2005AiWR.
//
double LambertN(const double &x, const int N)
{
double sigma,tmp;
sigma=pow(-2.0-2.0*log(-x),0.5);
if (N<=2){tmp=-1.0-0.5*sigma*sigma-sigma/(1.0+sigma/6.3);}
else {tmp=LambertN(x,N-1);}
return (1+log(-x)-log(-tmp))*tmp/(1+tmp);
}
/////////////////////////////////////////////////////////////////
/// \brief Returns gamma function of argument x
/// \note Returns 1e308 if argument is a negative integer or 0, or if argument exceeds 171.
///
/// \param x [in] Argument whose gamma function will be determined
/// \return Gamma function of argument x
//
double gamma2(double x)
{
int i,k,m;
double ga=0,gr,r=0,z;
static double g[] = {
1.0, 0.5772156649015329, -0.6558780715202538,
-0.420026350340952e-1, 0.1665386113822915, -0.421977345555443e-1,
-0.9621971527877e-2, 0.7218943246663e-2, -0.11651675918591e-2,
-0.2152416741149e-3, 0.1280502823882e-3, -0.201348547807e-4,
-0.12504934821e-5, 0.1133027232e-5, -0.2056338417e-6,
0.6116095e-8, 0.50020075e-8, -0.11812746e-8,
0.1043427e-9, 0.77823e-11, -0.36968e-11,
0.51e-12, -0.206e-13, -0.54e-14,
0.14e-14};
if (x > 171.0){return 0.0;} // This value is an overflow flag.
if (x == (int)x)
{
if (x > 0.0) {
ga = 1.0; // use factorial
for (i=2;i<x;i++) {ga *= i;}
}
else{
ga=0.0;
ExitGracefully("Gamma:negative integer values not allowed",RUNTIME_ERR);
}
}
else
{
z=x;
r=1.0;
if (fabs(x) > 1.0) {
z = fabs(x);
m = (int)(z);
r = 1.0;
for (k=1;k<=m;k++) {r *= (z-k);}
z -= m;
}
gr = g[24];
for (k=23;k>=0;k--) {gr = gr*z+g[k];}
ga = 1.0/(gr*z);
if (fabs(x) > 1.0) {
ga *= r;
if (x < 0.0) {ga = -PI/(x*ga*sin(PI*x));}
}
}
return ga;
}
/////////////////////////////////////////////////////////////////
/// \brief returns value of incomplete gamma function with parameter a for input x
/// incomplete Gamma is g(x,a)=int_0^x of t^a-1 exp(-t) dt
/// \param &x [in] upper limit of integral
/// \param &a [in] shape parameter
/// \return Incomplete gamma function g(x,a)
//
double IncompleteGamma(const double &x, const double &a)
{
//cumulative distribution
/// \ref from http://algolist.manual.ru/maths/count_fast/gamma_function.php
const int N=100;
if (x==0){return 0.0;}
double num=1;
double sum=0.0;
double prod=1.0;
for (int n=0;n<N;n++){
if (n>0){num*=x;}
prod*=(a+n);
sum+=num/prod;
}
return sum*pow(x,a)*exp(-x);
}
/////////////////////////////////////////////////////////////////
/// \brief returns value of Gamma distribution for argument x, with parameters alpha and beta
/// gamma(x,a,b)=b^a/Gamma(x)*x^(a-1)*exp(-b*x)
///
/// \param &x [in] Argument x whose Gamma distribution value will be determined
/// \param &alpha [in] shape parameter
/// \param &beta [in] scale parameter
/// \return Gamma distribution value
//
double GammaDist(const double &x, const double &alpha, const double &beta)
{
//mean=alpha/beta
double bx=beta*x;
return pow(bx,alpha)/x/gamma2(x)*exp(-bx);
}
//////////////////////////////////////////////////////////////////
/// \brief Calculates cumulative two parameter cumulative gamma distribution \cite Clark2008WRR
///
/// \param &t [in] time
/// \param &alpha [in] shape parameter
/// \param &beta [in] scaling parameter
/// \return integrated gamma distribution from 0..t
//
double GammaCumDist(const double &t, const double &alpha,const double &beta)
{
return IncompleteGamma(beta*t,alpha)/gamma2(alpha);
}
//////////////////////////////////////////////////////////////////
/// \brief Calculates cumulative triangular distribution
/// \remark Area under=1.0-->peak=2/tp
///
/// \param &t [in] argument of triangular distribution
/// \param &tc [in] End of triangle
/// \param &tp [in] Peak of triangle
/// \return Cumulative triangular distribution value for input t
//
double TriCumDist(const double &t, const double &tc, const double &tp)
{
double b=2.0/tc;
double m;
if (t<0.0){return 0.0;}
if (t<=tp){
m=(b/tp);
return 0.5*m*t*t;
}
else if (t<=tc){
m=-b/(tc-tp);
return tp/tc+b*(t-tp)+0.5*m*(t-tp)*(t-tp);
}
else{
return 1.0;
}
}
//////////////////////////////////////////////////////////////////
/// \brief Returns the cumulative distribution function at input t for a sequence of linear reservoirs
/// \remark Basically the Gamma distribution for integer shape parameters. A common unit hydrograph format \n
/// - \math \f$ PDF(t)/UH(t)=t^{N-1}k^{N}e^{-kt} \f$
/// - \math \f$ CDF(t)/cum UH(t)=1-e^{-kt}\sum_{n=0}^{N-1}t^n/n! \f$
///
/// \param &t [in] The input value whose CDF is to be determined
/// \param &k [in] CDF Parameter (linear storage coeff)
/// \param &NR [in] Integer number of reservoirs
/// \return CDF at point t
//
double NashCumDist(const double &t, const double &k, const int &NR)
{
if (t<0.0){return 0.0;}
double fact=1.0;
double prod=1.0;
double sum =1.0;
for (int n=1; n<NR; n++){
fact=fact*n;
prod=prod*(k*t);
sum+=prod/fact;
}
return 1.0-exp(-k*t)*sum;
}
//////////////////////////////////////////////////////////////////
/// \brief Calculates cumulative kinematic wave solution distribution
/// \docminor These parameters need to be described
///
/// \param &t
/// \param &L
/// \param &v
/// \param &D
/// \return Returns cumulative kinematic wave solution distribution
//
//int_0^time L/2/t^(3/2)/sqrt(pi*D)*exp(-(v*t-L)^2/(4*D*t)) dt
// extreme case (D->0): =1 for v*t<L, 0 otherwise
double ADRCumDist(const double &t, const double &L, const double &v, const double &D)
{
ExitGracefullyIf(D<=0,"ADRCumDist: Invalid diffusivity",RUNTIME_ERR);
double term =L/2.0*pow(PI*D,-0.5);
double beta =L/sqrt(D);
double alpha=v/sqrt(D);
double dt =t/5000.0; //t in [day] (5000.0 is # of integral divisions)
double integ=0.0;
for (double tt=0.5*dt;tt<t;tt+=dt)
{
// D: unit = m2 / day
// [m]/[day]^1.5/[m]/[day]^0.5 * exp([m/day]*[day]-[m])^2/([m]^2)/[day])
integ+=pow(tt,-1.5)*exp(-((alpha*tt-beta)*(alpha*tt-beta))/4.0/tt);
// equivalent to (old) version, but more stable since alpha, beta ~1-10 whereas both v^2 and D can be very large
//integ+=pow(tt,-1.5)*exp(-((v*tt-L)*(v*tt-L))/4.0/D/tt); //old version
}
//analytical (unstable due to exp*erf term):
//term=term*pow(PI,0.5)/2.0/beta;
//double integ2=erf((beta-alpha*t)/pow(t,0.5))-1.0+exp(4*alpha*beta)*(erf((alpha*t+beta)/pow(t,0.5))-1.0+1.0 )+1.0;
// cout<<integ<<" "<<term*integ2<<endl;
return integ*term*dt;
}
//////////////////////////////////////////////////////////////////
/// \brief Quicksort algorithm
/// \author coded by Ayman Khedr, 3A Environmental University of Waterloo
///
/// \param arr[] [in & out] Unordered array of doubles to be sorted
/// \param left [in] Left bound of sort
/// \param right [in] Right bound of sort
//
void quickSort(double arr[], int left, int right)
{
if (right<=left){return;}//e.g., if array size==0
int i = left, j = right;
double tmp;
double pivot = arr[(left + right) / 2];
// partition
while (i <= j) {
while (arr[i] < pivot){i++;}
while (arr[j] > pivot){j--;}
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
// recursion
if (left < j){quickSort(arr, left, j);}
if (i < right){quickSort(arr, i, right);}
}
///////////////////////////////////////////////////////////////////////////
/// \brief identifies index location of value in uneven continuous list of value ranges
///
/// \param &x [in] value for which the interval index is to be found
/// \param *ax [in] array of consecutive values from ax[0] to ax[N-1] indicating interval boundaries
/// \param N [in] size of array ax
/// \param iguess [in] best guess as to which interval x is in
/// \return interval index value (index refers to lower bound of interval, i.e., i indicates x is between ax[i] and ax[i+1]
/// \note returns -1 if outside of range
//
int SmartIntervalSearch(const double &x,const double *ax,const int N,const int iguess)
{
int i=iguess;
if((iguess>N-1) || (iguess<0)) { i=0; }
if((x>=ax[i]) && (x<ax[i+1])) { return i; }
int plus,plus2;
for(int d=1;d<(int)(trunc(N/2)+1);d++)
{
plus =i+d; if(plus >N-1) { plus -=N; } //wrap
plus2=i+d+1; if(plus2>N-1) { plus2-=N; } //wrap
if((x>=ax[plus]) && (x<ax[plus2])) { return plus; }
plus =i-d; if(plus <0) { plus +=N; } //wrap
plus2=i-d+1; if(plus2<0) { plus2+=N; } //wrap
if((x>=ax[plus]) && (x<ax[plus2])) { return plus; }
}
return DOESNT_EXIST;
}
///////////////////////////////////////////////////////////////////
/// \brief returns index of bin that lookup_val is contained in, where array aVals of size 'size'
/// \param lookup_val [in] value to be looked up
/// \param nguess [in] guess for bin index (0<=nguess<=size-2)
/// \param *aVals [in] ordered array of bin values (size = nBins)
/// \param nBins [in] size of aVals[]
/// \return index of bin, or DOESNT_EXIST
/// \note all values less than aVals[1] are in bin 0, \n
/// all between aVals[n] and aVals[n+1] are in bin n, \n
/// all values greater than aVals[nBins-2] are in bin nBins-2 \n
//
int SmartLookup(const double lookup_val, const int nguess, const double *aVals, const int nBins)
{
int i,n;
if ((lookup_val>aVals[nguess]) && (lookup_val<=aVals[nguess+1])){return nguess;} //most likely choice
if (lookup_val<aVals[0] ){return 0;}
if (lookup_val>aVals[nBins-2]){return nBins-2;}
for (i=1;i<(nBins/2+2);i++)
{
n=nguess+i;
if (n>nBins-2){n-=nBins-1;}//wraparound
if ((lookup_val>aVals[n]) && (lookup_val<=aVals[n+1])){ return n;}///second most likely case
n=nguess-i;
if (n<0 ){n+=nBins-1;}//wraparound
if ((lookup_val>aVals[n]) && (lookup_val<=aVals[n+1])){return n;}
}
cout<<i<<" tries NOT FOUND"<<endl;
return DOESNT_EXIST;
}
//////////////////////////////////////////////////////////////////
/// \brief interpolates value from rating curve
/// \param x [in] interpolation location
/// \param xx [in] array (size:N) of vertices ordinates of interpolant
/// \param y [in] array (size:N) of values corresponding to array points xx
/// \param N size of arrays x and y
/// \returns y value corresponding to interpolation point
/// \note does not assume regular spacing between min and max x value
/// \note if below minimum xx, either extrapolates (if extrapbottom=true), or uses minimum value
/// \note if above maximum xx, always extrapolates
//
double Interpolate2(const double x,const double *xx,const double *y,int N,bool extrapbottom)
{
static int ilast=0;
if(x<=xx[0])
{
if(extrapbottom) { return y[0]+(y[1]-y[0])/(xx[1]-xx[0])*(x-xx[0]); }
return y[0];
}
else if(x>=xx[N-1])
{
return y[N-1]+(y[N-1]-y[N-2])/(xx[N-1]-xx[N-2])*(x-xx[N-1]);//extrapolation-may wish to revisit
//return y[N-1];
}
else
{
//int i=0; while ((x>xx[i+1]) && (i<(N-2))){i++;}//Dumb Search
int i=SmartIntervalSearch(x,xx,N,ilast);
if(i==DOESNT_EXIST) { return 0.0; }
ExitGracefullyIf(i==DOESNT_EXIST,"Interpolate2::mis-ordered list or infinite x",RUNTIME_ERR);
ilast=i;
return y[i]+(y[i+1]-y[i])/(xx[i+1]-xx[i])*(x-xx[i]);
}
} | 38.513285 | 188 | 0.575904 | [
"mesh",
"shape",
"model"
] |
7b8cc48379726cfc0b318b84502522eb52faeea0 | 914 | cpp | C++ | UserLiteralExample.cpp | TheMaverickProgrammer/UniformDieCast | 466b2c8445b259c1d0162cc21479baf10b61d560 | [
"Zlib"
] | 16 | 2018-12-01T12:46:00.000Z | 2021-09-05T01:50:51.000Z | UserLiteralExample.cpp | TheMaverickProgrammer/UniformDieCast | 466b2c8445b259c1d0162cc21479baf10b61d560 | [
"Zlib"
] | null | null | null | UserLiteralExample.cpp | TheMaverickProgrammer/UniformDieCast | 466b2c8445b259c1d0162cc21479baf10b61d560 | [
"Zlib"
] | null | null | null | #include "DieCast.h"
#include <iostream>
// die::literal namespace exports a literal "# of rolls"_D(int sides)
// returns a facade to the die_cast object that can be concatenated.
int main() {
using namespace die::literal;
die::die_cast res = 4_D(6)+5 << 3_D(8) << 10_D(2)-30 << 1_D(6);
for(auto& i : res) {
std::cout << "Rolled a " << i.sides << " sided die ";
std::cout << i.roll << ((i.roll == 1)? " time " : " times");
if(i.modifier != 0) {
std::cout << " with a modifier of " << i.modifier << "!";
} else {
std::cout << "!";
}
std::cout << " => " << i.result << std::endl;
}
std::cout << "\nResults only:" << std::endl;
// Dissolve into integer result set only
// if you just want the final value
for(auto& i : res) {
std::cout << "Final value: " << i << std::endl;
}
}
| 28.5625 | 69 | 0.504376 | [
"object"
] |
7b90dfdf113960a314b092ea8439c1fa4e13a7ee | 2,170 | cpp | C++ | src/VectorViewTest.cpp | maxxboehme/BlockStorage | c539841d2ec66ab6fc4d71c2fa2e6dada707d799 | [
"MIT"
] | null | null | null | src/VectorViewTest.cpp | maxxboehme/BlockStorage | c539841d2ec66ab6fc4d71c2fa2e6dada707d799 | [
"MIT"
] | null | null | null | src/VectorViewTest.cpp | maxxboehme/BlockStorage | c539841d2ec66ab6fc4d71c2fa2e6dada707d799 | [
"MIT"
] | null | null | null | #include <catch.hpp>
#include "BlockStorage.h"
#include "RecordStorage.h"
TEST_CASE("Create VectorView", "[VectorView]") {
std::unique_ptr<ISharedMemory> memory = std::make_unique<FakeSharedMemory>(0U);
BlockStorage<1028> storage(std::move(memory));
REQUIRE(storage.size() == 0U);
Block<1028> block = storage.create();
VectorView<uint64_t, 1028> vector = VectorView<uint64_t, 1028>::createVectorView(block);
REQUIRE(vector.id() == block.id());
REQUIRE(vector.capacity() > 0U);
REQUIRE(vector.size() == 0U);
}
TEST_CASE("Push and pop back VectorView", "[VectorView]") {
std::unique_ptr<ISharedMemory> memory = std::make_unique<FakeSharedMemory>(0U);
BlockStorage<1028> storage(std::move(memory));
REQUIRE(storage.size() == 0U);
Block<1028> block = storage.create();
VectorView<uint64_t, 1028> vector = VectorView<uint64_t, 1028>::createVectorView(block);
vector.push_back(1234);
REQUIRE(vector.size() == 1U);
uint64_t back = vector.pop_back();
REQUIRE(back == 1234);
REQUIRE(vector.size() == 0U);
uint64_t numItemsForNewBlock = vector.capacity() + 1;
for (size_t i = 0; i < numItemsForNewBlock; ++i) {
vector.push_back(i);
}
REQUIRE(vector.size() == numItemsForNewBlock);
REQUIRE(vector.numBlocks() == 2U);
back = vector.pop_back();
REQUIRE(back == (numItemsForNewBlock - 1));
REQUIRE(vector.size() == numItemsForNewBlock - 1);
REQUIRE(vector.numBlocks() == 1U);
}
TEST_CASE("Index VectorView", "[VectorView]") {
std::unique_ptr<ISharedMemory> memory = std::make_unique<FakeSharedMemory>(0U);
BlockStorage<1028> storage(std::move(memory));
REQUIRE(storage.size() == 0U);
Block<1028> block = storage.create();
VectorView<uint64_t, 1028> vector = VectorView<uint64_t, 1028>::createVectorView(block);
uint64_t numItemsForNewBlock = vector.capacity() + 1;
for (size_t i = 0; i < numItemsForNewBlock; ++i) {
vector.push_back(i);
}
REQUIRE(vector.size() == numItemsForNewBlock);
REQUIRE(vector.numBlocks() == 2U);
for (size_t i = 0; i < vector.size(); ++i) {
REQUIRE(vector[i] == i);
}
}
| 33.90625 | 92 | 0.659908 | [
"vector"
] |
7b99b48b0337eeb87d7f638be17efe8d7fa642dc | 2,982 | cpp | C++ | ImportantExample/QTableViewDemo/booleandelegate.cpp | xiaohaijin/Qt | 54d961c6a8123d8e4daf405b7996aba4be9ab7ed | [
"MIT"
] | 3 | 2018-12-24T19:35:52.000Z | 2022-02-04T14:45:59.000Z | ImportantExample/QTableViewDemo/booleandelegate.cpp | xiaohaijin/Qt | 54d961c6a8123d8e4daf405b7996aba4be9ab7ed | [
"MIT"
] | null | null | null | ImportantExample/QTableViewDemo/booleandelegate.cpp | xiaohaijin/Qt | 54d961c6a8123d8e4daf405b7996aba4be9ab7ed | [
"MIT"
] | 1 | 2019-05-09T02:42:40.000Z | 2019-05-09T02:42:40.000Z | #include <QStyle>
#include <QApplication>
#include "booleandelegate.h"
BooleanDelegate::BooleanDelegate(QObject *parent, bool defaultValue)
: QStyledItemDelegate(parent)
, defaultValue(defaultValue)
{
}
void BooleanDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QVariant value = index.data();
if (!value.isValid() || value.canConvert<bool>())
{
bool boolVal = value.isValid() ? value.toBool() : defaultValue;
QStyle *style = qApp->style();
QRect checkBoxRect = style->subElementRect(QStyle::SE_CheckBoxIndicator, &option);
int chkWidth = checkBoxRect.width();
int chkHeight = checkBoxRect.height();
int centerX = option.rect.left() + qMax(option.rect.width()/2-chkWidth/2, 0);
int centerY = option.rect.top() + qMax(option.rect.height()/2-chkHeight/2, 0);
QStyleOptionViewItem modifiedOption(option);
modifiedOption.rect.moveTo(centerX, centerY);
modifiedOption.rect.setSize(QSize(chkWidth, chkHeight));
if(boolVal)
{
modifiedOption.state |= QStyle::State_On;
}
style->drawPrimitive(QStyle::PE_IndicatorItemViewItemCheck, &modifiedOption, painter);
}
return QStyledItemDelegate::paint(painter, option, index);
}
QWidget *BooleanDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &/* option */,
const QModelIndex &/* index */) const
{
CenteredCheckBoxWidget *editor = new CenteredCheckBoxWidget(parent);
editor->checkBox()->setChecked(defaultValue);
return editor;
}
void BooleanDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
QVariant data = index.model()->data(index, Qt::EditRole);
bool value;
if(!data.isNull())
{
value = data.toBool();
}
else
{
value = defaultValue;
}
CenteredCheckBoxWidget *checkBoxWidget = static_cast<CenteredCheckBoxWidget*>(editor);
checkBoxWidget->checkBox()->setChecked(value);
}
void BooleanDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
CenteredCheckBoxWidget *checkBoxWidget = static_cast<CenteredCheckBoxWidget*>(editor);
bool value = checkBoxWidget->checkBox()->isChecked();
model->setData(index, value, Qt::EditRole);
}
void BooleanDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
CenteredCheckBoxWidget *checkBoxWidget = static_cast<CenteredCheckBoxWidget*>(editor);
QSize size = checkBoxWidget->sizeHint();
editor->setMinimumHeight(size.height());
editor->setMinimumWidth(size.width());
editor->setGeometry(option.rect);
}
| 32.064516 | 116 | 0.65057 | [
"model"
] |
7b9ba31a850ba3928fed356fb103ce9e4698344c | 900 | cpp | C++ | math/leetcode_math/246_strobogrammatic_number.cpp | Hadleyhzy/data_structure_and_algorithm | 0e610ba78dcb216323d9434a0f182756780ce5c0 | [
"MIT"
] | 1 | 2020-10-12T19:18:19.000Z | 2020-10-12T19:18:19.000Z | math/leetcode_math/246_strobogrammatic_number.cpp | Hadleyhzy/data_structure_and_algorithm | 0e610ba78dcb216323d9434a0f182756780ce5c0 | [
"MIT"
] | null | null | null | math/leetcode_math/246_strobogrammatic_number.cpp | Hadleyhzy/data_structure_and_algorithm | 0e610ba78dcb216323d9434a0f182756780ce5c0 | [
"MIT"
] | 1 | 2020-10-12T19:18:04.000Z | 2020-10-12T19:18:04.000Z | //
// 246_strobogrammatic_number.cpp
// leetcode_math
//
// Created by Hadley on 12.08.20.
// Copyright © 2020 Hadley. All rights reserved.
//
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <stack>
#include <cstring>
#include <queue>
#include <functional>
#include <numeric>
using namespace std;
class Solution {
public:
bool isStrobogrammatic(string num) {
auto n=num.length();
string temp=num;
unordered_map<char, char>r;
r['6']='9';
r['9']='6';
r['8']='8';
r['1']='1';
r['0']='0';
r['2']='*';
r['3']='*';
r['4']='*';
r['5']='*';
r['7']='*';
for(int i=0;i<n;i++){
temp[i]=r[temp[i]];
}
reverse(temp.begin(), temp.end());
return temp==num;
}
};
| 19.565217 | 49 | 0.508889 | [
"vector"
] |
7b9bcd19fc1da8822c016e59101094866c58165e | 58,574 | cpp | C++ | ad_map_access/impl/tests/generated/ad/map/match/ObjectValidInputRangeTests.cpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | null | null | null | ad_map_access/impl/tests/generated/ad/map/match/ObjectValidInputRangeTests.cpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | null | null | null | ad_map_access/impl/tests/generated/ad/map/match/ObjectValidInputRangeTests.cpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | null | null | null | /*
* ----------------- BEGIN LICENSE BLOCK ---------------------------------
*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
* ----------------- END LICENSE BLOCK -----------------------------------
*/
/*
* Generated file
*/
#include <gtest/gtest.h>
#include <limits>
#include "ad/map/match/ObjectValidInputRange.hpp"
TEST(ObjectValidInputRangeTests, testValidInputRange)
{
::ad::map::match::Object value;
::ad::map::match::ENUObjectPosition valueEnuPosition;
::ad::map::point::ENUPoint valueEnuPositionCenterPoint;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointX(-16384);
valueEnuPositionCenterPoint.x = valueEnuPositionCenterPointX;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointY(-16384);
valueEnuPositionCenterPoint.y = valueEnuPositionCenterPointY;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointZ(-16384);
valueEnuPositionCenterPoint.z = valueEnuPositionCenterPointZ;
valueEnuPosition.centerPoint = valueEnuPositionCenterPoint;
::ad::map::point::ENUHeading valueEnuPositionHeading(-3.141592655);
valueEnuPosition.heading = valueEnuPositionHeading;
::ad::map::point::GeoPoint valueEnuPositionEnuReferencePoint;
::ad::map::point::Longitude valueEnuPositionEnuReferencePointLongitude(-180);
valueEnuPositionEnuReferencePoint.longitude = valueEnuPositionEnuReferencePointLongitude;
::ad::map::point::Latitude valueEnuPositionEnuReferencePointLatitude(-90);
valueEnuPositionEnuReferencePoint.latitude = valueEnuPositionEnuReferencePointLatitude;
::ad::map::point::Altitude valueEnuPositionEnuReferencePointAltitude(-11000);
valueEnuPositionEnuReferencePoint.altitude = valueEnuPositionEnuReferencePointAltitude;
valueEnuPosition.enuReferencePoint = valueEnuPositionEnuReferencePoint;
::ad::physics::Dimension3D valueEnuPositionDimension;
::ad::physics::Distance valueEnuPositionDimensionLength(-1e9);
valueEnuPositionDimension.length = valueEnuPositionDimensionLength;
::ad::physics::Distance valueEnuPositionDimensionWidth(-1e9);
valueEnuPositionDimension.width = valueEnuPositionDimensionWidth;
::ad::physics::Distance valueEnuPositionDimensionHeight(-1e9);
valueEnuPositionDimension.height = valueEnuPositionDimensionHeight;
valueEnuPosition.dimension = valueEnuPositionDimension;
value.enuPosition = valueEnuPosition;
::ad::map::match::MapMatchedObjectBoundingBox valueMapMatchedBoundingBox;
::ad::map::match::LaneOccupiedRegionList valueMapMatchedBoundingBoxLaneOccupiedRegions;
::ad::map::match::LaneOccupiedRegion valueMapMatchedBoundingBoxLaneOccupiedRegionsElement;
::ad::map::lane::LaneId valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLaneId(1);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.laneId
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLaneId;
::ad::physics::ParametricRange valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMinimum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMinimum;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMaximum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMaximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.longitudinalRange
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange;
::ad::physics::ParametricRange valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMinimum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMinimum;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMaximum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMaximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.lateralRange
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange;
valueMapMatchedBoundingBoxLaneOccupiedRegions.resize(1, valueMapMatchedBoundingBoxLaneOccupiedRegionsElement);
valueMapMatchedBoundingBox.laneOccupiedRegions = valueMapMatchedBoundingBoxLaneOccupiedRegions;
::ad::map::match::MapMatchedObjectReferencePositionList valueMapMatchedBoundingBoxReferencePointPositions;
::ad::map::match::MapMatchedPositionConfidenceList valueMapMatchedBoundingBoxReferencePointPositionsElement;
::ad::map::match::MapMatchedPosition valueMapMatchedBoundingBoxReferencePointPositionsElementElement;
::ad::map::match::LanePoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint;
::ad::map::point::ParaPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint;
::ad::map::lane::LaneId valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointLaneId(1);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint.laneId
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointLaneId;
::ad::physics::ParametricValue
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointParametricOffset(0.);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint.parametricOffset
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointParametricOffset;
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.paraPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint;
::ad::physics::RatioValue valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLateralT(
std::numeric_limits<::ad::physics::RatioValue>::lowest());
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.lateralT
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLateralT;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneLength(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.laneLength
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneLength;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneWidth(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.laneWidth
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneWidth;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.lanePoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint;
::ad::map::match::MapMatchedPositionType valueMapMatchedBoundingBoxReferencePointPositionsElementElementType(
::ad::map::match::MapMatchedPositionType::INVALID);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.type
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementType;
::ad::map::point::ECEFPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointX(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.x
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointX;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointY(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.y
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointY;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointZ(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.z
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointZ;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.matchedPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint;
::ad::physics::Probability valueMapMatchedBoundingBoxReferencePointPositionsElementElementProbability(0.);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.probability
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementProbability;
::ad::map::point::ECEFPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointX(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.x
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointX;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointY(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.y
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointY;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointZ(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.z
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointZ;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.queryPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointDistance(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.matchedPointDistance
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointDistance;
valueMapMatchedBoundingBoxReferencePointPositionsElement.resize(
1, valueMapMatchedBoundingBoxReferencePointPositionsElementElement);
valueMapMatchedBoundingBoxReferencePointPositions.resize(1, valueMapMatchedBoundingBoxReferencePointPositionsElement);
valueMapMatchedBoundingBox.referencePointPositions = valueMapMatchedBoundingBoxReferencePointPositions;
::ad::physics::Distance valueMapMatchedBoundingBoxSamplingDistance(-1e9);
valueMapMatchedBoundingBox.samplingDistance = valueMapMatchedBoundingBoxSamplingDistance;
::ad::physics::Distance valueMapMatchedBoundingBoxMatchRadius(-1e9);
valueMapMatchedBoundingBox.matchRadius = valueMapMatchedBoundingBoxMatchRadius;
value.mapMatchedBoundingBox = valueMapMatchedBoundingBox;
ASSERT_TRUE(withinValidInputRange(value));
}
TEST(ObjectValidInputRangeTests, testValidInputRangeEnuPositionTooSmall)
{
::ad::map::match::Object value;
::ad::map::match::ENUObjectPosition valueEnuPosition;
::ad::map::point::ENUPoint valueEnuPositionCenterPoint;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointX(-16384);
valueEnuPositionCenterPoint.x = valueEnuPositionCenterPointX;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointY(-16384);
valueEnuPositionCenterPoint.y = valueEnuPositionCenterPointY;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointZ(-16384);
valueEnuPositionCenterPoint.z = valueEnuPositionCenterPointZ;
valueEnuPosition.centerPoint = valueEnuPositionCenterPoint;
::ad::map::point::ENUHeading valueEnuPositionHeading(-3.141592655);
valueEnuPosition.heading = valueEnuPositionHeading;
::ad::map::point::GeoPoint valueEnuPositionEnuReferencePoint;
::ad::map::point::Longitude valueEnuPositionEnuReferencePointLongitude(-180);
valueEnuPositionEnuReferencePoint.longitude = valueEnuPositionEnuReferencePointLongitude;
::ad::map::point::Latitude valueEnuPositionEnuReferencePointLatitude(-90);
valueEnuPositionEnuReferencePoint.latitude = valueEnuPositionEnuReferencePointLatitude;
::ad::map::point::Altitude valueEnuPositionEnuReferencePointAltitude(-11000);
valueEnuPositionEnuReferencePoint.altitude = valueEnuPositionEnuReferencePointAltitude;
valueEnuPosition.enuReferencePoint = valueEnuPositionEnuReferencePoint;
::ad::physics::Dimension3D valueEnuPositionDimension;
::ad::physics::Distance valueEnuPositionDimensionLength(-1e9);
valueEnuPositionDimension.length = valueEnuPositionDimensionLength;
::ad::physics::Distance valueEnuPositionDimensionWidth(-1e9);
valueEnuPositionDimension.width = valueEnuPositionDimensionWidth;
::ad::physics::Distance valueEnuPositionDimensionHeight(-1e9);
valueEnuPositionDimension.height = valueEnuPositionDimensionHeight;
valueEnuPosition.dimension = valueEnuPositionDimension;
value.enuPosition = valueEnuPosition;
::ad::map::match::MapMatchedObjectBoundingBox valueMapMatchedBoundingBox;
::ad::map::match::LaneOccupiedRegionList valueMapMatchedBoundingBoxLaneOccupiedRegions;
::ad::map::match::LaneOccupiedRegion valueMapMatchedBoundingBoxLaneOccupiedRegionsElement;
::ad::map::lane::LaneId valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLaneId(1);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.laneId
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLaneId;
::ad::physics::ParametricRange valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMinimum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMinimum;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMaximum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMaximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.longitudinalRange
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange;
::ad::physics::ParametricRange valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMinimum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMinimum;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMaximum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMaximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.lateralRange
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange;
valueMapMatchedBoundingBoxLaneOccupiedRegions.resize(1, valueMapMatchedBoundingBoxLaneOccupiedRegionsElement);
valueMapMatchedBoundingBox.laneOccupiedRegions = valueMapMatchedBoundingBoxLaneOccupiedRegions;
::ad::map::match::MapMatchedObjectReferencePositionList valueMapMatchedBoundingBoxReferencePointPositions;
::ad::map::match::MapMatchedPositionConfidenceList valueMapMatchedBoundingBoxReferencePointPositionsElement;
::ad::map::match::MapMatchedPosition valueMapMatchedBoundingBoxReferencePointPositionsElementElement;
::ad::map::match::LanePoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint;
::ad::map::point::ParaPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint;
::ad::map::lane::LaneId valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointLaneId(1);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint.laneId
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointLaneId;
::ad::physics::ParametricValue
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointParametricOffset(0.);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint.parametricOffset
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointParametricOffset;
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.paraPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint;
::ad::physics::RatioValue valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLateralT(
std::numeric_limits<::ad::physics::RatioValue>::lowest());
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.lateralT
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLateralT;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneLength(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.laneLength
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneLength;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneWidth(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.laneWidth
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneWidth;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.lanePoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint;
::ad::map::match::MapMatchedPositionType valueMapMatchedBoundingBoxReferencePointPositionsElementElementType(
::ad::map::match::MapMatchedPositionType::INVALID);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.type
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementType;
::ad::map::point::ECEFPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointX(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.x
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointX;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointY(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.y
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointY;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointZ(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.z
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointZ;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.matchedPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint;
::ad::physics::Probability valueMapMatchedBoundingBoxReferencePointPositionsElementElementProbability(0.);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.probability
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementProbability;
::ad::map::point::ECEFPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointX(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.x
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointX;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointY(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.y
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointY;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointZ(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.z
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointZ;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.queryPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointDistance(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.matchedPointDistance
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointDistance;
valueMapMatchedBoundingBoxReferencePointPositionsElement.resize(
1, valueMapMatchedBoundingBoxReferencePointPositionsElementElement);
valueMapMatchedBoundingBoxReferencePointPositions.resize(1, valueMapMatchedBoundingBoxReferencePointPositionsElement);
valueMapMatchedBoundingBox.referencePointPositions = valueMapMatchedBoundingBoxReferencePointPositions;
::ad::physics::Distance valueMapMatchedBoundingBoxSamplingDistance(-1e9);
valueMapMatchedBoundingBox.samplingDistance = valueMapMatchedBoundingBoxSamplingDistance;
::ad::physics::Distance valueMapMatchedBoundingBoxMatchRadius(-1e9);
valueMapMatchedBoundingBox.matchRadius = valueMapMatchedBoundingBoxMatchRadius;
value.mapMatchedBoundingBox = valueMapMatchedBoundingBox;
// override member with data type value below input range minimum
::ad::map::match::ENUObjectPosition invalidInitializedMember;
::ad::map::point::ENUPoint invalidInitializedMemberCenterPoint;
::ad::map::point::ENUCoordinate invalidInitializedMemberCenterPointX(-16384 * 1.1);
invalidInitializedMemberCenterPoint.x = invalidInitializedMemberCenterPointX;
invalidInitializedMember.centerPoint = invalidInitializedMemberCenterPoint;
value.enuPosition = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(ObjectValidInputRangeTests, testValidInputRangeEnuPositionTooBig)
{
::ad::map::match::Object value;
::ad::map::match::ENUObjectPosition valueEnuPosition;
::ad::map::point::ENUPoint valueEnuPositionCenterPoint;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointX(-16384);
valueEnuPositionCenterPoint.x = valueEnuPositionCenterPointX;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointY(-16384);
valueEnuPositionCenterPoint.y = valueEnuPositionCenterPointY;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointZ(-16384);
valueEnuPositionCenterPoint.z = valueEnuPositionCenterPointZ;
valueEnuPosition.centerPoint = valueEnuPositionCenterPoint;
::ad::map::point::ENUHeading valueEnuPositionHeading(-3.141592655);
valueEnuPosition.heading = valueEnuPositionHeading;
::ad::map::point::GeoPoint valueEnuPositionEnuReferencePoint;
::ad::map::point::Longitude valueEnuPositionEnuReferencePointLongitude(-180);
valueEnuPositionEnuReferencePoint.longitude = valueEnuPositionEnuReferencePointLongitude;
::ad::map::point::Latitude valueEnuPositionEnuReferencePointLatitude(-90);
valueEnuPositionEnuReferencePoint.latitude = valueEnuPositionEnuReferencePointLatitude;
::ad::map::point::Altitude valueEnuPositionEnuReferencePointAltitude(-11000);
valueEnuPositionEnuReferencePoint.altitude = valueEnuPositionEnuReferencePointAltitude;
valueEnuPosition.enuReferencePoint = valueEnuPositionEnuReferencePoint;
::ad::physics::Dimension3D valueEnuPositionDimension;
::ad::physics::Distance valueEnuPositionDimensionLength(-1e9);
valueEnuPositionDimension.length = valueEnuPositionDimensionLength;
::ad::physics::Distance valueEnuPositionDimensionWidth(-1e9);
valueEnuPositionDimension.width = valueEnuPositionDimensionWidth;
::ad::physics::Distance valueEnuPositionDimensionHeight(-1e9);
valueEnuPositionDimension.height = valueEnuPositionDimensionHeight;
valueEnuPosition.dimension = valueEnuPositionDimension;
value.enuPosition = valueEnuPosition;
::ad::map::match::MapMatchedObjectBoundingBox valueMapMatchedBoundingBox;
::ad::map::match::LaneOccupiedRegionList valueMapMatchedBoundingBoxLaneOccupiedRegions;
::ad::map::match::LaneOccupiedRegion valueMapMatchedBoundingBoxLaneOccupiedRegionsElement;
::ad::map::lane::LaneId valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLaneId(1);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.laneId
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLaneId;
::ad::physics::ParametricRange valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMinimum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMinimum;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMaximum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMaximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.longitudinalRange
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange;
::ad::physics::ParametricRange valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMinimum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMinimum;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMaximum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMaximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.lateralRange
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange;
valueMapMatchedBoundingBoxLaneOccupiedRegions.resize(1, valueMapMatchedBoundingBoxLaneOccupiedRegionsElement);
valueMapMatchedBoundingBox.laneOccupiedRegions = valueMapMatchedBoundingBoxLaneOccupiedRegions;
::ad::map::match::MapMatchedObjectReferencePositionList valueMapMatchedBoundingBoxReferencePointPositions;
::ad::map::match::MapMatchedPositionConfidenceList valueMapMatchedBoundingBoxReferencePointPositionsElement;
::ad::map::match::MapMatchedPosition valueMapMatchedBoundingBoxReferencePointPositionsElementElement;
::ad::map::match::LanePoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint;
::ad::map::point::ParaPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint;
::ad::map::lane::LaneId valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointLaneId(1);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint.laneId
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointLaneId;
::ad::physics::ParametricValue
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointParametricOffset(0.);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint.parametricOffset
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointParametricOffset;
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.paraPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint;
::ad::physics::RatioValue valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLateralT(
std::numeric_limits<::ad::physics::RatioValue>::lowest());
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.lateralT
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLateralT;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneLength(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.laneLength
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneLength;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneWidth(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.laneWidth
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneWidth;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.lanePoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint;
::ad::map::match::MapMatchedPositionType valueMapMatchedBoundingBoxReferencePointPositionsElementElementType(
::ad::map::match::MapMatchedPositionType::INVALID);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.type
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementType;
::ad::map::point::ECEFPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointX(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.x
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointX;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointY(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.y
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointY;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointZ(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.z
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointZ;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.matchedPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint;
::ad::physics::Probability valueMapMatchedBoundingBoxReferencePointPositionsElementElementProbability(0.);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.probability
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementProbability;
::ad::map::point::ECEFPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointX(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.x
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointX;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointY(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.y
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointY;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointZ(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.z
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointZ;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.queryPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointDistance(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.matchedPointDistance
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointDistance;
valueMapMatchedBoundingBoxReferencePointPositionsElement.resize(
1, valueMapMatchedBoundingBoxReferencePointPositionsElementElement);
valueMapMatchedBoundingBoxReferencePointPositions.resize(1, valueMapMatchedBoundingBoxReferencePointPositionsElement);
valueMapMatchedBoundingBox.referencePointPositions = valueMapMatchedBoundingBoxReferencePointPositions;
::ad::physics::Distance valueMapMatchedBoundingBoxSamplingDistance(-1e9);
valueMapMatchedBoundingBox.samplingDistance = valueMapMatchedBoundingBoxSamplingDistance;
::ad::physics::Distance valueMapMatchedBoundingBoxMatchRadius(-1e9);
valueMapMatchedBoundingBox.matchRadius = valueMapMatchedBoundingBoxMatchRadius;
value.mapMatchedBoundingBox = valueMapMatchedBoundingBox;
// override member with data type value above input range maximum
::ad::map::match::ENUObjectPosition invalidInitializedMember;
::ad::map::point::ENUPoint invalidInitializedMemberCenterPoint;
::ad::map::point::ENUCoordinate invalidInitializedMemberCenterPointX(16384 * 1.1);
invalidInitializedMemberCenterPoint.x = invalidInitializedMemberCenterPointX;
invalidInitializedMember.centerPoint = invalidInitializedMemberCenterPoint;
value.enuPosition = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(ObjectValidInputRangeTests, testValidInputRangeMapMatchedBoundingBoxTooSmall)
{
::ad::map::match::Object value;
::ad::map::match::ENUObjectPosition valueEnuPosition;
::ad::map::point::ENUPoint valueEnuPositionCenterPoint;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointX(-16384);
valueEnuPositionCenterPoint.x = valueEnuPositionCenterPointX;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointY(-16384);
valueEnuPositionCenterPoint.y = valueEnuPositionCenterPointY;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointZ(-16384);
valueEnuPositionCenterPoint.z = valueEnuPositionCenterPointZ;
valueEnuPosition.centerPoint = valueEnuPositionCenterPoint;
::ad::map::point::ENUHeading valueEnuPositionHeading(-3.141592655);
valueEnuPosition.heading = valueEnuPositionHeading;
::ad::map::point::GeoPoint valueEnuPositionEnuReferencePoint;
::ad::map::point::Longitude valueEnuPositionEnuReferencePointLongitude(-180);
valueEnuPositionEnuReferencePoint.longitude = valueEnuPositionEnuReferencePointLongitude;
::ad::map::point::Latitude valueEnuPositionEnuReferencePointLatitude(-90);
valueEnuPositionEnuReferencePoint.latitude = valueEnuPositionEnuReferencePointLatitude;
::ad::map::point::Altitude valueEnuPositionEnuReferencePointAltitude(-11000);
valueEnuPositionEnuReferencePoint.altitude = valueEnuPositionEnuReferencePointAltitude;
valueEnuPosition.enuReferencePoint = valueEnuPositionEnuReferencePoint;
::ad::physics::Dimension3D valueEnuPositionDimension;
::ad::physics::Distance valueEnuPositionDimensionLength(-1e9);
valueEnuPositionDimension.length = valueEnuPositionDimensionLength;
::ad::physics::Distance valueEnuPositionDimensionWidth(-1e9);
valueEnuPositionDimension.width = valueEnuPositionDimensionWidth;
::ad::physics::Distance valueEnuPositionDimensionHeight(-1e9);
valueEnuPositionDimension.height = valueEnuPositionDimensionHeight;
valueEnuPosition.dimension = valueEnuPositionDimension;
value.enuPosition = valueEnuPosition;
::ad::map::match::MapMatchedObjectBoundingBox valueMapMatchedBoundingBox;
::ad::map::match::LaneOccupiedRegionList valueMapMatchedBoundingBoxLaneOccupiedRegions;
::ad::map::match::LaneOccupiedRegion valueMapMatchedBoundingBoxLaneOccupiedRegionsElement;
::ad::map::lane::LaneId valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLaneId(1);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.laneId
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLaneId;
::ad::physics::ParametricRange valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMinimum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMinimum;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMaximum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMaximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.longitudinalRange
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange;
::ad::physics::ParametricRange valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMinimum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMinimum;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMaximum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMaximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.lateralRange
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange;
valueMapMatchedBoundingBoxLaneOccupiedRegions.resize(1, valueMapMatchedBoundingBoxLaneOccupiedRegionsElement);
valueMapMatchedBoundingBox.laneOccupiedRegions = valueMapMatchedBoundingBoxLaneOccupiedRegions;
::ad::map::match::MapMatchedObjectReferencePositionList valueMapMatchedBoundingBoxReferencePointPositions;
::ad::map::match::MapMatchedPositionConfidenceList valueMapMatchedBoundingBoxReferencePointPositionsElement;
::ad::map::match::MapMatchedPosition valueMapMatchedBoundingBoxReferencePointPositionsElementElement;
::ad::map::match::LanePoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint;
::ad::map::point::ParaPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint;
::ad::map::lane::LaneId valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointLaneId(1);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint.laneId
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointLaneId;
::ad::physics::ParametricValue
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointParametricOffset(0.);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint.parametricOffset
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointParametricOffset;
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.paraPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint;
::ad::physics::RatioValue valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLateralT(
std::numeric_limits<::ad::physics::RatioValue>::lowest());
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.lateralT
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLateralT;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneLength(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.laneLength
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneLength;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneWidth(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.laneWidth
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneWidth;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.lanePoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint;
::ad::map::match::MapMatchedPositionType valueMapMatchedBoundingBoxReferencePointPositionsElementElementType(
::ad::map::match::MapMatchedPositionType::INVALID);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.type
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementType;
::ad::map::point::ECEFPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointX(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.x
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointX;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointY(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.y
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointY;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointZ(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.z
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointZ;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.matchedPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint;
::ad::physics::Probability valueMapMatchedBoundingBoxReferencePointPositionsElementElementProbability(0.);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.probability
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementProbability;
::ad::map::point::ECEFPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointX(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.x
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointX;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointY(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.y
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointY;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointZ(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.z
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointZ;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.queryPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointDistance(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.matchedPointDistance
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointDistance;
valueMapMatchedBoundingBoxReferencePointPositionsElement.resize(
1, valueMapMatchedBoundingBoxReferencePointPositionsElementElement);
valueMapMatchedBoundingBoxReferencePointPositions.resize(1, valueMapMatchedBoundingBoxReferencePointPositionsElement);
valueMapMatchedBoundingBox.referencePointPositions = valueMapMatchedBoundingBoxReferencePointPositions;
::ad::physics::Distance valueMapMatchedBoundingBoxSamplingDistance(-1e9);
valueMapMatchedBoundingBox.samplingDistance = valueMapMatchedBoundingBoxSamplingDistance;
::ad::physics::Distance valueMapMatchedBoundingBoxMatchRadius(-1e9);
valueMapMatchedBoundingBox.matchRadius = valueMapMatchedBoundingBoxMatchRadius;
value.mapMatchedBoundingBox = valueMapMatchedBoundingBox;
// override member with data type value below input range minimum
::ad::map::match::MapMatchedObjectBoundingBox invalidInitializedMember;
::ad::physics::Distance invalidInitializedMemberSamplingDistance(-1e9 * 1.1);
invalidInitializedMember.samplingDistance = invalidInitializedMemberSamplingDistance;
value.mapMatchedBoundingBox = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(ObjectValidInputRangeTests, testValidInputRangeMapMatchedBoundingBoxTooBig)
{
::ad::map::match::Object value;
::ad::map::match::ENUObjectPosition valueEnuPosition;
::ad::map::point::ENUPoint valueEnuPositionCenterPoint;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointX(-16384);
valueEnuPositionCenterPoint.x = valueEnuPositionCenterPointX;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointY(-16384);
valueEnuPositionCenterPoint.y = valueEnuPositionCenterPointY;
::ad::map::point::ENUCoordinate valueEnuPositionCenterPointZ(-16384);
valueEnuPositionCenterPoint.z = valueEnuPositionCenterPointZ;
valueEnuPosition.centerPoint = valueEnuPositionCenterPoint;
::ad::map::point::ENUHeading valueEnuPositionHeading(-3.141592655);
valueEnuPosition.heading = valueEnuPositionHeading;
::ad::map::point::GeoPoint valueEnuPositionEnuReferencePoint;
::ad::map::point::Longitude valueEnuPositionEnuReferencePointLongitude(-180);
valueEnuPositionEnuReferencePoint.longitude = valueEnuPositionEnuReferencePointLongitude;
::ad::map::point::Latitude valueEnuPositionEnuReferencePointLatitude(-90);
valueEnuPositionEnuReferencePoint.latitude = valueEnuPositionEnuReferencePointLatitude;
::ad::map::point::Altitude valueEnuPositionEnuReferencePointAltitude(-11000);
valueEnuPositionEnuReferencePoint.altitude = valueEnuPositionEnuReferencePointAltitude;
valueEnuPosition.enuReferencePoint = valueEnuPositionEnuReferencePoint;
::ad::physics::Dimension3D valueEnuPositionDimension;
::ad::physics::Distance valueEnuPositionDimensionLength(-1e9);
valueEnuPositionDimension.length = valueEnuPositionDimensionLength;
::ad::physics::Distance valueEnuPositionDimensionWidth(-1e9);
valueEnuPositionDimension.width = valueEnuPositionDimensionWidth;
::ad::physics::Distance valueEnuPositionDimensionHeight(-1e9);
valueEnuPositionDimension.height = valueEnuPositionDimensionHeight;
valueEnuPosition.dimension = valueEnuPositionDimension;
value.enuPosition = valueEnuPosition;
::ad::map::match::MapMatchedObjectBoundingBox valueMapMatchedBoundingBox;
::ad::map::match::LaneOccupiedRegionList valueMapMatchedBoundingBoxLaneOccupiedRegions;
::ad::map::match::LaneOccupiedRegion valueMapMatchedBoundingBoxLaneOccupiedRegionsElement;
::ad::map::lane::LaneId valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLaneId(1);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.laneId
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLaneId;
::ad::physics::ParametricRange valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMinimum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMinimum;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMaximum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRangeMaximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange.maximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.longitudinalRange
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLongitudinalRange;
::ad::physics::ParametricRange valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMinimum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMinimum;
::ad::physics::ParametricValue valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMaximum(0.);
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRangeMaximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.minimum
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange.maximum;
valueMapMatchedBoundingBoxLaneOccupiedRegionsElement.lateralRange
= valueMapMatchedBoundingBoxLaneOccupiedRegionsElementLateralRange;
valueMapMatchedBoundingBoxLaneOccupiedRegions.resize(1, valueMapMatchedBoundingBoxLaneOccupiedRegionsElement);
valueMapMatchedBoundingBox.laneOccupiedRegions = valueMapMatchedBoundingBoxLaneOccupiedRegions;
::ad::map::match::MapMatchedObjectReferencePositionList valueMapMatchedBoundingBoxReferencePointPositions;
::ad::map::match::MapMatchedPositionConfidenceList valueMapMatchedBoundingBoxReferencePointPositionsElement;
::ad::map::match::MapMatchedPosition valueMapMatchedBoundingBoxReferencePointPositionsElementElement;
::ad::map::match::LanePoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint;
::ad::map::point::ParaPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint;
::ad::map::lane::LaneId valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointLaneId(1);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint.laneId
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointLaneId;
::ad::physics::ParametricValue
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointParametricOffset(0.);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint.parametricOffset
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPointParametricOffset;
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.paraPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointParaPoint;
::ad::physics::RatioValue valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLateralT(
std::numeric_limits<::ad::physics::RatioValue>::lowest());
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.lateralT
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLateralT;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneLength(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.laneLength
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneLength;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneWidth(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint.laneWidth
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePointLaneWidth;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.lanePoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementLanePoint;
::ad::map::match::MapMatchedPositionType valueMapMatchedBoundingBoxReferencePointPositionsElementElementType(
::ad::map::match::MapMatchedPositionType::INVALID);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.type
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementType;
::ad::map::point::ECEFPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointX(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.x
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointX;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointY(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.y
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointY;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointZ(
-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint.z
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointZ;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.matchedPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPoint;
::ad::physics::Probability valueMapMatchedBoundingBoxReferencePointPositionsElementElementProbability(0.);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.probability
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementProbability;
::ad::map::point::ECEFPoint valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointX(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.x
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointX;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointY(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.y
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointY;
::ad::map::point::ECEFCoordinate valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointZ(-6400000);
valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint.z
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPointZ;
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.queryPoint
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementQueryPoint;
::ad::physics::Distance valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointDistance(-1e9);
valueMapMatchedBoundingBoxReferencePointPositionsElementElement.matchedPointDistance
= valueMapMatchedBoundingBoxReferencePointPositionsElementElementMatchedPointDistance;
valueMapMatchedBoundingBoxReferencePointPositionsElement.resize(
1, valueMapMatchedBoundingBoxReferencePointPositionsElementElement);
valueMapMatchedBoundingBoxReferencePointPositions.resize(1, valueMapMatchedBoundingBoxReferencePointPositionsElement);
valueMapMatchedBoundingBox.referencePointPositions = valueMapMatchedBoundingBoxReferencePointPositions;
::ad::physics::Distance valueMapMatchedBoundingBoxSamplingDistance(-1e9);
valueMapMatchedBoundingBox.samplingDistance = valueMapMatchedBoundingBoxSamplingDistance;
::ad::physics::Distance valueMapMatchedBoundingBoxMatchRadius(-1e9);
valueMapMatchedBoundingBox.matchRadius = valueMapMatchedBoundingBoxMatchRadius;
value.mapMatchedBoundingBox = valueMapMatchedBoundingBox;
// override member with data type value above input range maximum
::ad::map::match::MapMatchedObjectBoundingBox invalidInitializedMember;
::ad::physics::Distance invalidInitializedMemberSamplingDistance(1e9 * 1.1);
invalidInitializedMember.samplingDistance = invalidInitializedMemberSamplingDistance;
value.mapMatchedBoundingBox = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
| 78.307487 | 120 | 0.882012 | [
"object"
] |
7b9c9e6b2dea4eab83a8542b6e5ac678bfc18850 | 2,642 | hpp | C++ | RobotCode/src/objects/lcdCode/Gimmicks.hpp | ajcarney/VexCode2021-2022 | d17a29ff2533046c283c12a6bff31f719565c3a6 | [
"MIT"
] | null | null | null | RobotCode/src/objects/lcdCode/Gimmicks.hpp | ajcarney/VexCode2021-2022 | d17a29ff2533046c283c12a6bff31f719565c3a6 | [
"MIT"
] | null | null | null | RobotCode/src/objects/lcdCode/Gimmicks.hpp | ajcarney/VexCode2021-2022 | d17a29ff2533046c283c12a6bff31f719565c3a6 | [
"MIT"
] | null | null | null | /**
* @file: ./RobotCode/src/objects/lcdCode/Gimmicks.hpp
* @author: Aiden Carney
* @reviewed_on: 10/15/2019
* @reviewed_by: Aiden Carney
* TODO: fix loading screen, it sometimes does not work
*
* contains lcd gimmicks that are used to enhance interface
*
*/
#ifndef __GIMMICKS_HPP__
#define __GIMMICKS_HPP__
#include <string>
#include "../../../include/main.h"
#include "Styles.hpp"
/**
* @see: Styles.hpp
* @see: ./lcdCode
*
* used to display warning box
*/
class WarningMessage : virtual Styles
{
protected:
/**
* @param: lv_obj_t* mbox -> message box object
* @param: const char* txt -> text for message box
* @return: LV_RES_OK -> if finishes successfully
*
* @see: Styles.hpp
* @see: ./lcdCode
*
* sets static int option to positive or negative based on feedback
*
*/
static lv_res_t mbox_apply_action(lv_obj_t * mbox, const char * txt);
static const char* buttons[];
static int option;
lv_obj_t *warn_box;
public:
WarningMessage();
virtual ~WarningMessage();
/**
* @param: std::string warn_msg -> message that will appear as option
* @param: lv_obj_t* parent -> the parent that the message box will appear on
* @return: bool -> if user selected yes or no
*
* returns true or false based on what user selects
* implementation of this is up to user
*
*/
bool warn(std::string warn_msg, lv_obj_t *parent);
};
/**
* @see: Styles.hpp
* @see: ./lcdCode
*
* methods and objects for a loading bar
*/
class Loading : virtual Styles
{
protected:
lv_obj_t *loader;
public:
Loading();
~Loading();
/**
* @param: int estimated_duration -> duration that loading should take used to set speed of bar
* @param: lv_obj_t* parent -> parent object that loading bar will go on
* @param: int x -> x position of loading bar relative to parent
* @param int y -> y position of loading bar relative to parent
* @return: None
*
* shows the loader and starts the action of it moving
*
*/
void show_load(int estimated_duration, lv_obj_t *parent, int x, int y); //starts the loader
/**
* @return: None
*
* hides the loader
* this should be about when the loader is finished
* Used to keep a smooth transition
*
*/
void hide_load(); //ends the loader and hides it
};
#endif
| 23.589286 | 103 | 0.582513 | [
"object"
] |
7b9f3ecfed48eaf0028e5c90b46f208f374be320 | 3,506 | cpp | C++ | src/win32/tools/scsilist.cpp | tech-niche-biz/bacula-9.4.4 | 5e74458b612354f6838652dac9ddff94be1bbce6 | [
"BSD-2-Clause"
] | null | null | null | src/win32/tools/scsilist.cpp | tech-niche-biz/bacula-9.4.4 | 5e74458b612354f6838652dac9ddff94be1bbce6 | [
"BSD-2-Clause"
] | null | null | null | src/win32/tools/scsilist.cpp | tech-niche-biz/bacula-9.4.4 | 5e74458b612354f6838652dac9ddff94be1bbce6 | [
"BSD-2-Clause"
] | null | null | null | /*
* scsilist.cpp - Outputs the contents of a ScsiDeviceList.
*
* Author: Robert Nelson, August, 2006 <robertn@the-nelsons.org>
*
* Version $Id$
*
* This file was contributed to the Bacula project by Robert Nelson.
*
* Robert Nelson has been granted a perpetual, worldwide,
* non-exclusive, no-charge, royalty-free, irrevocable copyright
* license to reproduce, prepare derivative works of, publicly
* display, publicly perform, sublicense, and distribute the original
* work contributed by Robert Nelson to the Bacula project in source
* or object form.
*
* If you wish to license contributions from Robert Nelson
* under an alternate open source license please contact
* Robert Nelson <robertn@the-nelsons.org>.
*/
/*
Bacula® - The Network Backup Solution
Copyright (C) 2006-2006 Free Software Foundation Europe e.V.
The main author of Bacula is Kern Sibbald, with contributions from
many others, a complete list can be found in the file AUTHORS.
This program is Free Software; you can redistribute it and/or
modify it under the terms of version three of the GNU Affero General Public
License as published by the Free Software Foundation and included
in the file LICENSE.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
Bacula® is a registered trademark of Kern Sibbald.
The licensor of Bacula is the Free Software Foundation Europe
(FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
Switzerland, email:ftf@fsfeurope.org.
*/
#if defined(_MSC_VER) && defined(_DEBUG)
#include <afx.h>
#else
#include <windows.h>
#endif
#include <stdio.h>
#include <tchar.h>
#include <conio.h>
#include "ScsiDeviceList.h"
#if defined(_MSC_VER) && defined(_DEBUG)
#define new DEBUG_NEW
#endif
int _tmain(int argc, _TCHAR* argv[])
{
#if defined(_MSC_VER) && defined(_DEBUG)
CMemoryState InitialMemState, FinalMemState, DiffMemState;
InitialMemState.Checkpoint();
{
#endif
CScsiDeviceList DeviceList;
if (!DeviceList.Populate())
{
DeviceList.PrintLastError();
return 1;
}
#define HEADING \
_T("Device Type Physical Name\n") \
_T("====== ==== ======== ====\n")
_fputts(HEADING, stdout);
for (DWORD index = 0; index < DeviceList.size(); index++) {
CScsiDeviceListEntry &entry = DeviceList[index];
if (entry.GetType() != CScsiDeviceListEntry::Disk) {
_tprintf(_T("%-28s %-7s %-11s %-27s\n"),
entry.GetIdentifier(),
entry.GetTypeName(),
entry.GetDevicePath(),
entry.GetDeviceName());
}
}
#if defined(_MSC_VER) && defined(_DEBUG)
}
InitialMemState.DumpAllObjectsSince();
FinalMemState.Checkpoint();
DiffMemState.Difference(InitialMemState, FinalMemState);
DiffMemState.DumpStatistics();
#endif
if (argc > 1 && _tcsnicmp(argv[1], _T("/pause"), sizeof(_T("/pause")) - sizeof(TCHAR)) == 0) {
_fputts(_T("\nPress any key to continue\n"), stderr);
_getch();
}
return 0;
}
| 29.216667 | 97 | 0.678266 | [
"object"
] |
7ba5cbf4ca6d7c523ec945a5a11cf4a20a625672 | 4,139 | cpp | C++ | LTBL2/src/Sprite.cpp | Alia5/FSE | e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1 | [
"MIT"
] | 17 | 2017-04-02T00:17:47.000Z | 2021-11-23T21:42:48.000Z | LTBL2/src/Sprite.cpp | Alia5/FSE | e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1 | [
"MIT"
] | null | null | null | LTBL2/src/Sprite.cpp | Alia5/FSE | e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1 | [
"MIT"
] | 5 | 2017-08-06T12:47:18.000Z | 2020-08-14T14:16:22.000Z | #include "Sprite.hpp"
#include "LightSystem.hpp"
namespace ltbl
{
Sprite::Sprite()
: BaseLight()
, mTexture(nullptr)
, mNormalsTexture(nullptr)
, mSpecularTexture(nullptr)
, light_system_(nullptr)
, mNormalsTarget(nullptr)
, mSpecularTarget(nullptr)
, mRenderNormals(false)
, mRenderSpecular(false)
{
}
Sprite::Sprite(ltbl::LightSystem* light_system) : BaseLight()
, mTexture(nullptr)
, mNormalsTexture(nullptr)
, mSpecularTexture(nullptr)
, light_system_(light_system)
, mNormalsTarget(&light_system->getNormalTexture())
, mSpecularTarget(&light_system->getSpecularTexture())
, mRenderNormals(true)
, mRenderSpecular(true)
{
}
Sprite::~Sprite()
{
}
void Sprite::setTexture(sf::Texture& texture, bool resetRect)
{
// Recompute the texture area if requested, or if there was no valid texture & rect before
if (resetRect || (!mTexture && (m_texture_rect == sf::IntRect())))
setTextureRect(sf::IntRect(0, 0, texture.getSize().x, texture.getSize().y));
mTexture = &texture;
}
void Sprite::setNormalsTexture(sf::Texture& normalsTexture)
{
mNormalsTexture = &normalsTexture;
}
const sf::Texture* Sprite::getNormalsTexture() const
{
return mNormalsTexture;
}
void Sprite::setSpecularTexture(sf::Texture& specularTexture)
{
mSpecularTexture = &specularTexture;
}
const sf::Texture* Sprite::getSpecularTexture() const
{
return mSpecularTexture;
}
void Sprite::render(sf::RenderTarget& target, sf::RenderStates states) const
{
if (mTexture)
{
states.transform *= getTransform();
states.texture = mTexture;
target.draw(m_vertices_[0], 4, sf::TriangleStrip, states);
}
}
void Sprite::renderNormals(sf::RenderTarget& target, sf::RenderStates states) const
{
if (mNormalsTexture != nullptr && mRenderNormals)
{
states.transform *= getTransform();
states.texture = mNormalsTexture;
target.draw(m_vertices_[1], 4, sf::TriangleStrip, states);
}
}
void Sprite::renderSpecular(sf::RenderTarget& target, sf::RenderStates states) const
{
if (mSpecularTexture != nullptr && mRenderSpecular)
{
states.transform *= getTransform();
states.texture = mSpecularTexture;
target.draw(m_vertices_[2], 4, sf::TriangleStrip, states);
}
}
void Sprite::setTextureRect(const sf::IntRect& rect)
{
m_texture_rect = rect;
sf::FloatRect bounds = getLocalBounds();
float left, right, top, bottom;
for (int i = 0; i < 3; i++)
{
m_vertices_[i][0].position = sf::Vector2f(0, 0);
m_vertices_[i][1].position = sf::Vector2f(0, bounds.height);
m_vertices_[i][2].position = sf::Vector2f(bounds.width, 0);
m_vertices_[i][3].position = sf::Vector2f(bounds.width, bounds.height);
left = static_cast<float>(m_texture_rect.left);
right = left + m_texture_rect.width;
top = static_cast<float>(m_texture_rect.top);
bottom = top + m_texture_rect.height;
m_vertices_[i][0].texCoords = sf::Vector2f(left, top);
m_vertices_[i][1].texCoords = sf::Vector2f(left, bottom);
m_vertices_[i][2].texCoords = sf::Vector2f(right, top);
m_vertices_[i][3].texCoords = sf::Vector2f(right, bottom);
}
}
void Sprite::setColor(const sf::Color& color)
{
m_vertices_[0][0].color = color;
m_vertices_[0][1].color = color;
m_vertices_[0][2].color = color;
m_vertices_[0][3].color = color;
}
void Sprite::setAlphaNormals(uint32_t alpha)
{
sf::Color color(255, 255, 255, alpha);
m_vertices_[1][0].color = color;
m_vertices_[1][1].color = color;
m_vertices_[1][2].color = color;
m_vertices_[1][3].color = color;
}
void Sprite::setColorSpecular(const sf::Color& color)
{
m_vertices_[2][0].color = color;
m_vertices_[2][1].color = color;
m_vertices_[2][2].color = color;
m_vertices_[2][3].color = color;
}
sf::FloatRect Sprite::getLocalBounds() const
{
float width = static_cast<float>(std::abs(m_texture_rect.width));
float height = static_cast<float>(std::abs(m_texture_rect.height));
return sf::FloatRect(0.f, 0.f, width, height);
}
sf::FloatRect Sprite::getGlobalBounds() const
{
return getTransform().transformRect(getLocalBounds());
}
} // namespace ltbl | 25.708075 | 92 | 0.695579 | [
"render",
"transform"
] |
7bafe794dc2fc3e617de3d83cfe05a35e87e2494 | 1,511 | cpp | C++ | examples/pxScene2d/external/libdash/libdash/libdash/source/mpd/BaseUrl.cpp | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 46 | 2017-09-07T14:59:22.000Z | 2020-10-31T20:34:12.000Z | examples/pxScene2d/external/libdash/libdash/libdash/source/mpd/BaseUrl.cpp | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1,432 | 2017-06-21T04:08:48.000Z | 2020-08-25T16:21:15.000Z | examples/pxScene2d/external/libdash/libdash/libdash/source/mpd/BaseUrl.cpp | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 317 | 2017-06-20T19:57:17.000Z | 2020-09-16T10:28:30.000Z | /*
* BaseUrl.cpp
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: libdash-dev@vicky.bitmovin.net
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "BaseUrl.h"
using namespace dash::mpd;
BaseUrl::BaseUrl () :
url(""),
serviceLocation(""),
byteRange("")
{
}
BaseUrl::~BaseUrl ()
{
}
const std::string& BaseUrl::GetUrl () const
{
return this->url;
}
void BaseUrl::SetUrl (const std::string& url)
{
this->url = url;
}
const std::string& BaseUrl::GetServiceLocation () const
{
return this->serviceLocation;
}
void BaseUrl::SetServiceLocation (const std::string& serviceLocation)
{
this->serviceLocation = serviceLocation;
}
const std::string& BaseUrl::GetByteRange () const
{
return this->byteRange;
}
void BaseUrl::SetByteRange (const std::string& byteRange)
{
this->byteRange = byteRange;
}
ISegment* BaseUrl::ToMediaSegment (const std::vector<IBaseUrl *>& baseurls) const
{
Segment *seg = new Segment();
if(seg->Init(baseurls, this->url, this->byteRange, dash::metrics::MediaSegment))
return seg;
delete(seg);
return NULL;
}
| 24.770492 | 95 | 0.555923 | [
"vector"
] |
7bb279cd728b8cee26302e219ba958ed4f248e48 | 821 | cpp | C++ | CodeChef/FROGV.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | 1 | 2020-10-16T18:14:30.000Z | 2020-10-16T18:14:30.000Z | CodeChef/FROGV.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | null | null | null | CodeChef/FROGV.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | 1 | 2021-01-06T04:45:38.000Z | 2021-01-06T04:45:38.000Z | //I've been expecting you <3
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define ll long long int
#define lb lower_bound
#define fr(i,n) for(int i=0; i<n; i++)
int main(){
int n,k,p;
cin>>n>>k>>p;
vector<int> vo(n),vd(n);
fr(i,n){
cin>>vo[i];
vd[i]=vo[i];
}
sort(vd.begin(),vd.end(), greater<int>());
map<int, int> m;
m[vd[0]]=vd[0]+k;
for(int i=1;i<n;i++){
if(vd[i-1]-vd[i]<=k){
m[vd[i]]=m[vd[i-1]];
}
else m[vd[i]]=vd[i]+k;
}
fr(i,p){
int a,b;
cin>>a>>b;
// auto it1=lb(vd.begin(),vd.end(),vo[a-1]);
// auto it2=lb(vd.begin(),vd.end(),vo[b-1]);
if(m[vo[--a]]==m[vo[--b]]){
cout<<"Yes";
}
else cout<<"No";
cout<<endl;
}
} | 22.805556 | 52 | 0.443362 | [
"vector"
] |
7bb6111723a1b5691a4aff04be5aaa4c925f9c01 | 9,870 | cpp | C++ | four-russian-optimization.cpp | hsiam261/LCS-with-Four-Russian-Optimization | e8a8146a828ca3c227849d1f6db94e485abd3ff6 | [
"MIT"
] | null | null | null | four-russian-optimization.cpp | hsiam261/LCS-with-Four-Russian-Optimization | e8a8146a828ca3c227849d1f6db94e485abd3ff6 | [
"MIT"
] | null | null | null | four-russian-optimization.cpp | hsiam261/LCS-with-Four-Russian-Optimization | e8a8146a828ca3c227849d1f6db94e485abd3ff6 | [
"MIT"
] | null | null | null | /**
*
* MIT License
*
* Copyright (c) [2021] [Siam Habib]
*
* 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.))
*
* author: Siam Habib <hsiam261@gmail.com>
*
*
* Four Russian Optimization to find a LCS between two strings
* usage: ./four-russian-optimization.out
* enter the two strings in two lines (string can not have any white spaces between them)
*
*/
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
// block_size of the four russian algorithm
// precompute memory requirement =
// (|ALPHABET|+1)^(2*block_size)*4^block_size*size_of(pre_compute_dp_block)
// for block_size=4 and alphabet size = 4 (one byte characters) and using pair of
// integers as index rep size
// 9.6 GiB
const int block_size = 3;
// change here to add more symbols
// two different sentinals are necessary for
// making the sizes of the two strings divisible by block_size
namespace Alphabet {
vector<char> symbol = {'A','C','G','T'};
vector<char> sentinals = {'0','1'};
}
//precompute tasks are here
namespace Precompute {
//maps all strings of length block_size using alphabet
//and appropriate centinals to integers
unordered_map<string,int> block_strings0;
unordered_map<string,int> block_strings1;
//global variable used for block_string generation
string str(block_size,Alphabet::sentinals[0]);
//generates block_strings using recursion and backtracking
void recurse(int at,int &cnt,unordered_map<string,int> &block_strings) {
block_strings[str]=cnt;
cnt++;
if(at==block_size) return;
auto temp = str[at];
for(auto c:Alphabet::symbol) {
str[at]=c;
recurse(at+1,cnt,block_strings);
}
str[at] = temp;
}
/**
* generates all the strings of length block_size
* with the with the alphabet symbols that can only have
* trailing sentinal characters
*/
void init_block_strings() {
for(auto &c: str) c= Alphabet::sentinals[0];
int cnt=0;
recurse(0,cnt,block_strings0);
for(auto &c: str) c= Alphabet::sentinals[1];
cnt=0;
recurse(0,cnt,block_strings1);
}
// store indecies using bitwise will speed this up
// Most optimal size of INDEX_REP_SIZE = floor(lg(block_size*2+1))+1
/**
* datastructure to store the dp values of a block
* worst case Memory Complexity:
* 2*block_size*(WORD_SIZE+2*INDEX_REP_SIZE) + 2*WORD_SIZE
*/
struct pre_compute_dp_block{
/**
* strores the length of the lcs of the bottom
* and right boundary cells
*/
vector<int> bottom;
vector<int> right;
/**
* stores lcs of the bottom and right boundary
* cells as string
*/
vector<string> bottom_lcs;
vector<string> right_lcs;
/**
* stores the (row,column) in the dp table that
* the path to the cell starts from
*/
vector<pair<int,int>> bottom_src;
vector<pair<int,int>> right_src;
pre_compute_dp_block() : bottom(block_size,0), right(block_size,0),
bottom_lcs(block_size), right_lcs(block_size),
bottom_src(block_size,{-1,-1}), right_src(block_size,{-1,-1}) {}
};
/**
* dp table
*
* 0 _ _ _ _ -----> mask generated row
* _ x x x x \
* _ x x x x |
* _ x x x x |------> x marked squares[i][j] has the dp value of matching the prefix s0[:i]
* _ x x x x / and s1[:j] for given top and and left values, right index non-inclusive
* |
* |
* |
* mask generated column
*/
pre_compute_dp_block solve_block_dp(int row_mask, int column_mask,string s0,string s1) {
int dp[block_size+1][block_size+1];
char path[block_size+1][block_size+1];
dp[0][0] = 0;
path[0][0] = 0;
//init_top_row
for(int i=1;i<=block_size;i++) {
dp[0][i]=dp[0][i-1]+(((1<<(i-1))&row_mask)>>(i-1));
path[0][i]=0;
}
//init_left_column
for(int i=1;i<=block_size;i++) {
dp[i][0]=dp[i-1][0]+(((1<<(i-1))&column_mask)>>(i-1));
path[i][0]=0;
}
for(int i=1;i<=block_size;i++) {
for(int j=1;j<=block_size;j++) {
if(s0[i-1]==s1[j-1]) {
path[i][j]='D';
dp[i][j] = dp[i-1][j-1]+1;
} else if(dp[i-1][j]>dp[i][j-1]) {
dp[i][j] = dp[i-1][j];
path[i][j] = 'U';
} else {
dp[i][j] = dp[i][j-1];
path[i][j] = 'L';
}
}
}
pre_compute_dp_block blk;
for(int i=0;i<block_size;i++) blk.bottom[i] = dp[block_size][i+1];
for(int i=0;i<block_size;i++) blk.right[i] = dp[i+1][block_size];
//getting the path for the bottom row
for(int i=0;i<block_size;i++) {
int row = block_size;
int col = i+1;
while(path[row][col]!=0) {
if(path[row][col]=='D') {
row--;
col--;
blk.bottom_lcs[i]+=s0[row];
} else if (path[row][col]=='U') row--;
else col--;
}
std::reverse(blk.bottom_lcs[i].begin(), blk.bottom_lcs[i].end());
blk.bottom_src[i] = {row,col};
}
//getting the path for the right column
for(int i=0;i<block_size;i++) {
int row = i+1;
int col = block_size;
while(path[row][col]!=0) {
if(path[row][col]=='D') {
row--;
col--;
blk.right_lcs[i]+=s0[row];
} else if (path[row][col]=='U') row--;
else col--;
}
std::reverse(blk.right_lcs[i].begin(),blk.right_lcs[i].end());
blk.right_src[i] = {row,col};
}
return blk;
}
/**
* Array storing all the precomputed lcs between block strings while masks
* are in consideration
* May consider storing in file or database
* For block_size=4 and alphabet.size()=4, required >14GiB of data
*/
vector<vector<pre_compute_dp_block>> pre[1<<block_size][1<<block_size];
/**
* Function that fills up pre
*/
void precompute() {
for(auto &t1:pre) {
for(auto &t2:t1) {
t2.resize(block_strings0.size(),vector<pre_compute_dp_block>(block_strings1.size()));
}
}
for(int row_mask=0;row_mask<(1<<block_size);row_mask++) {
for(int col_mask=0;col_mask<(1<<block_size);col_mask++) {
for(auto &t0:block_strings0) {
for(auto &t1:block_strings1) {
pre[row_mask][col_mask][t0.second][t1.second] =
solve_block_dp(row_mask,col_mask,t0.first,t1.first);
}
}
}
}
}
}
/**
* Takes a string and fills a vetctor with strings of size block_size
* May add sentinal in the end of the string if string size is not divisible
* by block_size
*/
void make_block_arr(string s,vector<string> &block_arr,char sentinal) {
if(s.size()%block_size) {
int new_size = (s.size()+block_size-1)/block_size*block_size;
s.resize(new_size,sentinal);
}
for(int i=0;i<s.size();i+=block_size) block_arr.push_back(s.substr(i,block_size));
}
/**
* Generates row/column mask using the dp values computed in a previous iteration
*/
int make_mask(int ref,const vector<int>& v) {
int mask = 0;
for(int i=0;i<v.size();i++) {
if(ref<v[i]) {
mask|=(1<<i);
ref=v[i];
}
}
return mask;
}
/**
* the dp table for the block level dp
* the size of this table is a bottle neck
* might want to consider using memory optimized
* lcs here
*/
Precompute::pre_compute_dp_block dp[400][400];
/**
* computes lcs
*/
string lcs(string s0,string s1) {
vector<string> block_arr0,block_arr1;
make_block_arr(s0,block_arr0,Alphabet::sentinals[0]);
make_block_arr(s1,block_arr1,Alphabet::sentinals[1]);
//Precompute::pre_compute_dp_block dp[block_arr0.size()+1][block_arr1.size()+1];
for(int i=1;i<=block_arr0.size();i++) {
for(int j=1;j<=block_arr1.size();j++) {
int ref = dp[i-1][j-1].bottom[block_size-1];
int row_mask = make_mask(ref,dp[i-1][j].bottom);
int col_mask = make_mask(ref,dp[i][j-1].right);
dp[i][j] = Precompute::pre[row_mask][col_mask][Precompute::block_strings0[block_arr0[i-1]]][Precompute::block_strings1[block_arr1[j-1]]];
for(auto& x:dp[i][j].bottom) x+=ref;
for(auto& x:dp[i][j].right) x+=ref;
}
}
int row=block_arr0.size();
int col=block_arr1.size();
bool is_row = true;
int idx = block_size-1;
vector<string> block_lcs;
while ((is_row?dp[row][col].bottom_src[idx]:dp[row][col].right_src[idx])!=make_pair(-1,-1)) {
pair<int,int> src;
if(is_row) {
block_lcs.push_back(dp[row][col].bottom_lcs[idx]);
src = dp[row][col].bottom_src[idx];
} else {
block_lcs.push_back(dp[row][col].right_lcs[idx]);
src = dp[row][col].right_src[idx];
}
if(src.first==0 && src.second==0) {
row--;
col--;
is_row=true;
idx = block_size-1;
} else if(src.first==0) {
row--;
is_row=true;
idx=src.second-1;
} else {
col--;
is_row=false;
idx = src.first-1;
}
}
string s="";
for(int i=block_lcs.size()-1;i>=0;i--) {
s+=block_lcs[i];
}
return s;
}
/**
* reads two strings from stdin
* writes size of lcs and lcs in two separate lines
*/
int main() {
Precompute::init_block_strings();
Precompute::precompute();
string s0,s1;
cin >> s0 >> s1;
string l = lcs(s0,s1);
cout << l.size() << "\n";
cout << l << endl;
return 0;
}
| 25.703125 | 140 | 0.649341 | [
"vector"
] |
dcf4447ce3a4aef345b2bfe315f5986f73b49562 | 13,503 | cpp | C++ | src/AFQMC/Hamiltonians/THCHamiltonian.cpp | prckent/qmcpack | 127caf219ee99c2449b803821fcc8b1304b66ee1 | [
"NCSA"
] | null | null | null | src/AFQMC/Hamiltonians/THCHamiltonian.cpp | prckent/qmcpack | 127caf219ee99c2449b803821fcc8b1304b66ee1 | [
"NCSA"
] | null | null | null | src/AFQMC/Hamiltonians/THCHamiltonian.cpp | prckent/qmcpack | 127caf219ee99c2449b803821fcc8b1304b66ee1 | [
"NCSA"
] | null | null | null | #include<cstdlib>
#include<algorithm>
#include<complex>
#include<iostream>
#include<fstream>
#include<map>
#include<utility>
#include<vector>
#include<numeric>
#include "Configuration.h"
#include "io/hdf_archive.h"
#include "AFQMC/config.h"
#include "AFQMC/Utilities/Utils.hpp"
#include "AFQMC/Hamiltonians/THCHamiltonian.h"
#include "AFQMC/Hamiltonians/rotateHamiltonian.hpp"
#include "AFQMC/Matrix/mpi3_shared_ma_proxy.hpp"
#include "AFQMC/HamiltonianOperations/THCOpsIO.hpp"
namespace qmcplusplus
{
namespace afqmc
{
// Right now, cutvn, cutvn2, TGprop and TGwfn are completely ignored.
// Note: addCoulomb only has meaning on the sparse hamiltonians, not in THC
HamiltonianOperations THCHamiltonian::getHamiltonianOperations(bool pureSD, bool addCoulomb,
WALKER_TYPES type,std::vector<PsiT_Matrix>& PsiT, double cutvn,
double cutv2,TaskGroup_& TGprop, TaskGroup_& TGwfn, hdf_archive& hdf_restart)
{
// hack until parallel hdf is in place
bool write_hdf = false;
if(TGwfn.Global().root()) write_hdf = !hdf_restart.closed();
// if(TGwfn.Global().root()) write_hdf = (hdf_restart.file_id != hdf_archive::is_closed);
TGwfn.Global().broadcast_value(write_hdf);
if(type==COLLINEAR)
assert(PsiT.size()%2 == 0);
int ndet = ((type!=COLLINEAR)?(PsiT.size()):(PsiT.size()/2));
bool test_Luv = not useHalfRotatedMuv;
//std::cout<<" test_Luv: " <<std::boolalpha <<test_Luv <<std::endl;
if(ndet > 1)
APP_ABORT("Error: ndet > 1 not yet implemented in THCHamiltonian::getHamiltonianOperations.\n");
size_t gnmu,grotnmu,nmu,rotnmu,nmu0,nmuN,rotnmu0,rotnmuN;
hdf_archive dump(TGwfn.Global());
// right now only Node.root() reads
if( TG.Node().root() ) {
if(!dump.open(fileName,H5F_ACC_RDONLY)) {
app_error()<<" Error opening integral file in THCHamiltonian. \n";
APP_ABORT("");
}
if(!dump.push("Hamiltonian",false)) {
app_error()<<" Error in THCHamiltonian::getHamiltonianOperations():"
<<" Group not Hamiltonian found. \n";
APP_ABORT("");
}
if(!dump.push("THC",false)) {
app_error()<<" Error in THCHamiltonian::getHamiltonianOperations():"
<<" Group not THC found. \n";
APP_ABORT("");
}
}
if( TG.Global().root() ) {
std::vector<int> Idata(3);
if(!dump.readEntry(Idata,"dims")) {
app_error()<<" Error in THCHamiltonian::getHamiltonianOperations():"
<<" Problems reading dims. \n";
APP_ABORT("");
}
if(Idata[0] != NMO) {
app_error()<<" ERROR: NMO differs from value in integral file. \n";
APP_ABORT(" Error: NMO differs from value in integral file. \n");
}
gnmu = size_t(Idata[1]);
grotnmu = size_t(Idata[2]);
}
TG.Global().broadcast_value(gnmu);
TG.Global().broadcast_value(grotnmu);
if(test_Luv)
grotnmu = gnmu;
// setup partition, in general matrices are partitioned asize_t 'u'
{
int node_number = TGwfn.getLocalGroupNumber();
int nnodes_prt_TG = TGwfn.getNGroupsPerTG();
std::tie(rotnmu0,rotnmuN) = FairDivideBoundary(size_t(node_number),grotnmu,size_t(nnodes_prt_TG));
rotnmu = rotnmuN-rotnmu0;
node_number = TGprop.getLocalGroupNumber();
nnodes_prt_TG = TGprop.getNGroupsPerTG();
std::tie(nmu0,nmuN) = FairDivideBoundary(size_t(node_number),gnmu,size_t(nnodes_prt_TG));
nmu = nmuN-nmu0;
}
using shm_Vmatrix = mpi3_shared_ma_proxy<ValueType>;
using shm_Cmatrix = mpi3_shared_ma_proxy<ComplexType>;
// INCONSISTENT IN REAL BUILD!!!!!! FIX FIX FIX
// Until I figure something else, rotPiu and rotcPua are not distributed because a full copy is needed
size_t nel_ = PsiT[0].size(0) + ((type==CLOSED)?0:(PsiT[1].size(0)));
shm_Vmatrix rotMuv(TG.Node(),{rotnmu,grotnmu},{grotnmu,grotnmu},{rotnmu0,0});
shm_Cmatrix rotPiu(TG.Node(),{size_t(NMO),grotnmu});
std::vector<shm_Cmatrix> rotcPua;
rotcPua.reserve(ndet);
for(int i=0; i<ndet; i++)
rotcPua.emplace_back(shm_Cmatrix(TG.Node(),{grotnmu,nel_}));
shm_Cmatrix Piu(TG.Node(),{size_t(NMO),nmu},{size_t(NMO),gnmu},{0,nmu0});
shm_Vmatrix Luv(TG.Node(),{nmu,gnmu},{gnmu,gnmu},{nmu0,0});
// right now only 1 reader. Use hyperslabs and parallel io later
// read Half transformed first
if(TG.Node().root()) {
using ma::conj;
if(not test_Luv) {
/***************************************/
// read full matrix, not distributed for now
auto piu_ = rotPiu.get();
if(!dump.readEntry(piu_,"HalfTransformedFullOrbitals")) {
app_error()<<" Error in THCHamiltonian::getHamiltonianOperations():"
<<" Problems reading HalfTransformedFullOrbitals. \n";
APP_ABORT("");
}
/***************************************/
typename shm_Vmatrix::ma_type muv_(rotMuv.get());
hyperslab_proxy<typename shm_Vmatrix::ma_type,2> hslab(muv_,
rotMuv.global_size(),
rotMuv.shape(),
rotMuv.global_offset());
if(!dump.readEntry(hslab,"HalfTransformedMuv")) {
app_error()<<" Error in THCHamiltonian::getHamiltonianOperations():"
<<" Problems reading HalfTransformedMuv. \n";
APP_ABORT("");
}
/***************************************/
}
}
TG.global_barrier();
if(TG.Node().root()) {
/***************************************/
typename shm_Cmatrix::ma_type piu_(Piu.get());
hyperslab_proxy<typename shm_Cmatrix::ma_type,2> hslab(piu_,
Piu.global_size(),
Piu.shape(),
Piu.global_offset());
if(!dump.readEntry(hslab,"Orbitals")) {
app_error()<<" Error in THCHamiltonian::getHamiltonianOperations():"
<<" Problems reading Orbitals. \n";
APP_ABORT("");
}
/***************************************/
typename shm_Vmatrix::ma_type luv_(Luv.get());
hyperslab_proxy<typename shm_Vmatrix::ma_type,2> hslab2(luv_,
Luv.global_size(),
Luv.shape(),
Luv.global_offset());
if(!dump.readEntry(hslab2,"Luv")) {
app_error()<<" Error in THCHamiltonian::getHamiltonianOperations():"
<<" Problems reading Luv. \n";
APP_ABORT("");
}
/***************************************/
}
TG.global_barrier();
boost::multi::array<ComplexType,2> v0({Piu.size(0),Piu.size(0)});
if(TGprop.getNGroupsPerTG() > 1)
{
// TOO MUCH MEMORY, FIX FIX FIX!!!
shm_Cmatrix Piu__(TG.Node(),{size_t(NMO),gnmu});
shm_Vmatrix Luv__(TG.Node(),{gnmu,gnmu});
if(TG.Node().root()) {
auto luv_ = Luv__.get();
if(!dump.readEntry(luv_,"Luv")) {
app_error()<<" Error in THCHamiltonian::getHamiltonianOperations():"
<<" Problems reading Orbitals. \n";
APP_ABORT("");
}
auto piu_ = Piu__.get();
if(!dump.readEntry(piu_,"Orbitals")) {
app_error()<<" Error in THCHamiltonian::getHamiltonianOperations():"
<<" Problems reading Orbitals. \n";
APP_ABORT("");
}
}
TG.Node().barrier();
using ma::H;
using ma::T;
using ma::conj;
size_t c0,cN,nc;
std::tie(c0,cN) = FairDivideBoundary(size_t(TG.Global().rank()),gnmu,size_t(TG.Global().size()));
nc = cN-c0;
boost::multi::array<ComplexType,2> Tuv({gnmu,nc});
boost::multi::array<ValueType,2> Muv({gnmu,nc});
// Muv = Luv * H(Luv)
// This can benefit from 2D split of work
ma::product(Luv__.get(),H(Luv__.get().sliced(c0,cN)),Muv);
if(test_Luv) {
for(int i=0; i<gnmu; ++i)
std::copy_n(Muv[i].origin(),nc,rotMuv.get()[i].origin()+c0);
TG.Node().barrier();
if(TG.Node().root())
TG.Cores().all_reduce_in_place_n(rotMuv.origin(),rotMuv.num_elements(),std::plus<>());
}
// since generating v0 takes some effort and temporary space,
// v0(i,l) = -0.5*sum_j <i,j|j,l>
// = -0.5 sum_j,u,v ma::conj(Piu(i,u)) ma::conj(Piu(j,v)) Muv Piu(j,u) Piu(l,v)
// = -0.5 sum_u,v ma::conj(Piu(i,u)) W(u,v) Piu(l,u), where
// W(u,v) = Muv(u,v) * sum_j Piu(j,u) ma::conj(Piu(j,v))
ma::product(H(Piu__.get()),Piu__.get()({0,long(NMO)},{long(c0),long(cN)}),Tuv);
auto itM = Muv.origin();
auto itT = Tuv.origin();
for(size_t i=0; i<Muv.num_elements(); ++i, ++itT, ++itM)
*(itT) = ma::conj(*itT)*(*itM);
boost::multi::array<ComplexType,2> T_({Tuv.size(1),size_t(NMO)});
ma::product(T(Tuv),H(Piu__.get()),T_);
ma::product(-0.5,T(T_),T(Piu__.get()({0,long(NMO)},{long(c0),long(cN)})),0.0,v0);
// reduce over Global
TG.Global().all_reduce_in_place_n(v0.origin(),v0.num_elements(),std::plus<>());
} else {
// very simple partitioning until something more sophisticated is in place!!!
using ma::H;
using ma::T;
using ma::conj;
size_t c0,cN,nc;
std::tie(c0,cN) = FairDivideBoundary(size_t(TG.Global().rank()),nmu,size_t(TG.Global().size()));
nc = cN-c0;
boost::multi::array<ComplexType,2> Tuv({gnmu,nc});
boost::multi::array<ValueType,2> Muv({gnmu,nc});
// Muv = Luv * H(Luv)
// This can benefit from 2D split of work
ma::product(Luv.get(),H(Luv.get().sliced(c0,cN)),Muv);
if(test_Luv) {
for(int i=0; i<gnmu; ++i)
std::copy_n(Muv[i].origin(),nc,rotMuv.get()[i].origin()+c0);
TG.Node().barrier();
if(TG.Node().root())
TG.Cores().all_reduce_in_place_n(rotMuv.origin(),rotMuv.num_elements(),std::plus<>());
}
// since generating v0 takes some effort and temporary space,
// v0(i,l) = -0.5*sum_j <i,j|j,l>
// = -0.5 sum_j,u,v ma::conj(Piu(i,u)) ma::conj(Piu(j,v)) Muv Piu(j,u) Piu(l,v)
// = -0.5 sum_u,v ma::conj(Piu(i,u)) W(u,v) Piu(l,u), where
// W(u,v) = Muv(u,v) * sum_j Piu(j,u) ma::conj(Piu(j,v))
ma::product(H(Piu.get()),Piu.get()({0,long(NMO)},{long(c0),long(cN)}),Tuv);
auto itM = Muv.origin();
auto itT = Tuv.origin();
for(size_t i=0; i<Muv.num_elements(); ++i, ++itT, ++itM)
*(itT) = ma::conj(*itT)*(*itM);
boost::multi::array<ComplexType,2> T_({Tuv.size(1),size_t(NMO)});
ma::product(T(Tuv),H(Piu.get()),T_);
ma::product(-0.5,T(T_),T(Piu.get()({0,long(NMO)},{long(c0),long(cN)})),0.0,v0);
// reduce over Global
TG.Global().all_reduce_in_place_n(v0.origin(),v0.num_elements(),std::plus<>());
}
TG.global_barrier();
long naea_ = PsiT[0].size(0);
long naeb_ = PsiT.back().size(0);
// half-rotated Pia
std::vector<shm_Cmatrix> cPua;
cPua.reserve(ndet);
for(int i=0; i<ndet; i++)
cPua.emplace_back(shm_Cmatrix(TG.Node(),{nmu,nel_},{gnmu,nel_},{nmu0,0}));
if(TG.Node().root()) {
// simple
using ma::H;
if(type==COLLINEAR) {
boost::multi::array<ComplexType,2> A({NMO,naea_});
boost::multi::array<ComplexType,2> B({NMO,naeb_});
for(int i=0; i<ndet; i++) {
// cPua = H(Piu) * ma::conj(A)
csr::CSR2MA('T',PsiT[2*i],A);
ma::product(H(Piu.get()),A,
cPua[i].get()({0,long(nmu)},{0,long(naea_)}));
if(not test_Luv)
ma::product(H(rotPiu.get()),A,
rotcPua[i].get()({0,long(grotnmu)},{0,long(naea_)}));
csr::CSR2MA('T',PsiT[2*i+1],B);
ma::product(H(Piu.get()),B,
cPua[i].get()({0,long(nmu)},{naea_,long(nel_)}));
if(not test_Luv)
ma::product(H(rotPiu.get()),B,
rotcPua[i].get()({0,long(grotnmu)},{naea_,long(nel_)}));
}
} else {
boost::multi::array<ComplexType,2> A({PsiT[0].size(1),PsiT[0].size(0)});
for(int i=0; i<ndet; i++) {
csr::CSR2MA('T',PsiT[i],A);
// cPua = H(Piu) * ma::conj(A)
ma::product(H(Piu.get()),A,cPua[i].get());
if(not test_Luv)
ma::product(H(rotPiu.get()),A,rotcPua[i].get());
}
}
if(test_Luv) {
std::copy_n(Piu.origin(),Piu.num_elements(),rotPiu.origin());
for(int i=0; i<ndet; i++)
std::copy_n(cPua[i].origin(),cPua[i].num_elements(),rotcPua[i].origin());
}
}
TG.node_barrier();
ValueType E0 = OneBodyHamiltonian::NuclearCoulombEnergy +
OneBodyHamiltonian::FrozenCoreEnergy;
std::vector<boost::multi::array<ComplexType,1>> hij;
hij.reserve(ndet);
int skp=((type==COLLINEAR)?1:0);
for(int n=0, nd=0; n<ndet; ++n, nd+=(skp+1)) {
check_wavefunction_consistency(type,&PsiT[nd],&PsiT[nd+skp],NMO,naea_,naeb_);
hij.emplace_back(rotateHij(type,&PsiT[nd],&PsiT[nd+skp],OneBodyHamiltonian::H1));
}
// dense one body hamiltonian
auto H1 = getH1();
//std::cout<<" nmu: " <<Luv.size(0) <<" " <<rotMuv.size(0) <<std::endl;
if(write_hdf)
writeTHCOps(hdf_restart,type,NMO,naea_,naeb_,ndet,TGprop,TGwfn,H1,
rotPiu,rotMuv,Piu,Luv,v0,E0);
return HamiltonianOperations(THCOps<ValueType>(TGwfn.TG_local(),NMO,naea_,naeb_,type,std::move(H1),
std::move(hij),std::move(rotMuv),std::move(rotPiu),
std::move(rotcPua),std::move(Luv),
std::move(Piu),std::move(cPua),std::move(v0),E0));
}
}
}
| 38.58 | 104 | 0.574095 | [
"shape",
"vector"
] |
0d092398ea16ee216c18ba798efb45aca43139ab | 1,644 | hpp | C++ | SummonEngine/CommonUtilities/Include/Camera.hpp | Raboni/SummonEngine | 2a1078d60b604a918b920d098f3f0e60e5ce35bc | [
"MIT"
] | 1 | 2020-03-27T15:22:17.000Z | 2020-03-27T15:22:17.000Z | SummonEngine/CommonUtilities/Include/Camera.hpp | Raboni/SummonEngine | 2a1078d60b604a918b920d098f3f0e60e5ce35bc | [
"MIT"
] | null | null | null | SummonEngine/CommonUtilities/Include/Camera.hpp | Raboni/SummonEngine | 2a1078d60b604a918b920d098f3f0e60e5ce35bc | [
"MIT"
] | 1 | 2021-01-22T03:49:01.000Z | 2021-01-22T03:49:01.000Z | #pragma once
#include "GrowingArray.hpp"
#include "Vector.hpp"
#include "Transform.hpp"
#include "PlaneVolume.hpp"
#include "Intersection.hpp"
namespace CU
{
class Camera
{
public:
Camera();
~Camera();
Camera& operator=(const Camera& aCamera);
const Matrix4x4f& GetSpace() const;
const Matrix4x4f& GetProjectionMatrix() const;
const Matrix4x4f GetViewMatrix() const;
void Move(const Vector3f& aMovement);
void Rotate(const Vector3f& aRotationInRadians);
void SetProjectionMatrix(const Matrix4x4f& aProjection);
void SetTransformMatrix(const Matrix4x4f& aTransform);
void SetPosition(const Vector3f& aPosition);
void SetRotation(const Vector3f& aRotationInRadians);
void SetFoV(const float aRadianFoV);
void SetAspectRatio(const float aAspectRatio);
void SetNearPlane(const float aNearPlane);
void SetFarPlane(const float aFarPlane);
void SetOrthographic(const bool aUseOrthographic);
virtual Vector4f ProjectToScreen(const Vector4f& aVector);
virtual GrowingArray<Vector4f> ProjectArrayToScreen(const GrowingArray<Vector4f>& aArray);
const Vector3f& GetPosition() const;
const Vector3f& GetDirection() const;
CU::Intersection::LineRay3D GetRay(float aRange = 0.0f, const CU::Vector2f& aOffset = CU::Vector2f::Zero);
bool InsideFrustum(const Vector3f& aPoint) const;
bool InsideFrustum(Intersection::Sphere aSphere) const;
protected:
void UpdateProjection();
Transform myTransform;
Matrix4x4f myProjectionMatrix;
Matrix4x4f myProjectionMatrixInverse;
PlaneVolume myFrustum;
float myFoV;
float myAspectRatio;
float myNear;
float myFar;
bool myUseOrthographic;
};
} | 28.842105 | 108 | 0.773723 | [
"vector",
"transform"
] |
0d11730dbb016fa45cf1da4dc4a80b881abf7278 | 2,010 | cpp | C++ | 17/day02/main.cpp | jakergrossman/aoc21 | 786444622b1d20b2c3a640f19f0bc24d3d48db34 | [
"Unlicense"
] | null | null | null | 17/day02/main.cpp | jakergrossman/aoc21 | 786444622b1d20b2c3a640f19f0bc24d3d48db34 | [
"Unlicense"
] | null | null | null | 17/day02/main.cpp | jakergrossman/aoc21 | 786444622b1d20b2c3a640f19f0bc24d3d48db34 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <vector>
#include <climits>
#include <sstream>
#include "common.h"
using std::vector;
int part_one(vector<vector<int> > input) {
vector<int> differences(input.size());
for (unsigned int i = 0; i < input.size(); i++) {
int min = INT_MAX, max = INT_MIN;
for (unsigned int j = 0; j < input[i].size(); j++) {
if (input[i][j] < min) min = input[i][j];
if (input[i][j] > max) max = input[i][j];
}
differences.push_back(max - min);
}
int sum = 0;
for (unsigned int i = 0; i < differences.size(); i++) {
sum += differences[i];
}
return sum;
}
int part_two(vector<vector<int> > input) {
vector<int> quotients(input.size());
unsigned int i, j, k;
unsigned int dividend, divisor;
for (i = 0; i < input.size(); i++) {
for (j = 0; j < input[i].size(); j++) {
for (k = 0; k < input[i].size(); k++) {
dividend = input[i][j];
divisor = input[i][k];
if (j != k && divisor != 0 && dividend % divisor == 0) {
quotients.push_back(dividend / divisor);
break;
}
}
}
}
int sum = 0;
for (unsigned int i = 0; i < quotients.size(); i++) {
sum += quotients[i];
}
return sum;
}
int main() {
vector<std::string> lines = AOC::get_lines("input.txt");
vector<vector<int> > input;
for (unsigned int i = 0; i < lines.size(); i++) {
std::stringstream stream(lines[i]);
vector<int> line_elements;
int buf;
while (stream >> buf) {
line_elements.push_back(buf);
}
input.push_back(line_elements);
}
int part_one_result, part_two_result;
AOC::Timer::start();
part_one_result = part_one(input);
part_two_result = part_two(input);
AOC::Timer::stop();
AOC::output_result(part_one_result, part_two_result, AOC::Timer::elapsed());
}
| 26.103896 | 80 | 0.521891 | [
"vector"
] |
0d1358a9312e40f6fe4455ff85d751237b698c0b | 814 | cc | C++ | CPP/No717.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | CPP/No717.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | CPP/No717.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | /**
* Created by Xiaozhong on 2020/11/23.
* Copyright (c) 2020/11/23 Xiaozhong. All rights reserved.
*/
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
bool isOneBitCharacter(vector<int> &bits) {
for (int i = 0; i < bits.size(); ++i) {
// 如果到了倒数第二个字符,而且还等于 1 ,
// 那么就说明最后一个 0 要和这个 1 附在一起解码了
if (bits[i] == 1 && i == bits.size() - 2) return false;
// 遇到 1 ,就可以直接跳过去下面一个字符了
else if (bits[i] == 1) i++;
// 遇到 0 ,只能跳过当前这个字符
else if (bits[i] == 0) continue;
}
return true;
}
};
int main() {
Solution s;
vector<int> bits = {1, 0, 0};
cout << s.isOneBitCharacter(bits) << endl;
bits = {1, 1, 1, 0};
cout << s.isOneBitCharacter(bits) << endl;
} | 25.4375 | 67 | 0.528256 | [
"vector"
] |
0d1aec28e01e1ccbf6e6e057bd37c688cdbb6da8 | 5,302 | cpp | C++ | OpenTESArena/src/Interface/ChooseNamePanel.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | OpenTESArena/src/Interface/ChooseNamePanel.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | OpenTESArena/src/Interface/ChooseNamePanel.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | #include <unordered_map>
#include "SDL.h"
#include "ChooseClassPanel.h"
#include "ChooseGenderPanel.h"
#include "ChooseNamePanel.h"
#include "CursorAlignment.h"
#include "RichTextString.h"
#include "TextAlignment.h"
#include "TextBox.h"
#include "TextEntry.h"
#include "../Assets/ExeData.h"
#include "../Assets/MiscAssets.h"
#include "../Game/Game.h"
#include "../Game/Options.h"
#include "../Math/Vector2.h"
#include "../Media/Color.h"
#include "../Media/FontManager.h"
#include "../Media/FontName.h"
#include "../Media/PaletteFile.h"
#include "../Media/PaletteName.h"
#include "../Media/TextureFile.h"
#include "../Media/TextureManager.h"
#include "../Media/TextureName.h"
#include "../Rendering/Renderer.h"
#include "../Rendering/Surface.h"
#include "components/utilities/String.h"
const int ChooseNamePanel::MAX_NAME_LENGTH = 25;
ChooseNamePanel::ChooseNamePanel(Game &game, const CharacterClass &charClass)
: Panel(game), charClass(charClass)
{
this->parchment = Texture::generate(Texture::PatternType::Parchment, 300, 60,
game.getTextureManager(), game.getRenderer());
this->titleTextBox = [&game, &charClass]()
{
const int x = 26;
const int y = 82;
const auto &exeData = game.getMiscAssets().getExeData();
std::string text = exeData.charCreation.chooseName;
text = String::replace(text, "%s", charClass.getName());
const RichTextString richText(
text,
FontName::A,
Color(48, 12, 12),
TextAlignment::Left,
game.getFontManager());
return std::make_unique<TextBox>(x, y, richText, game.getRenderer());
}();
this->nameTextBox = [&game]()
{
const int x = 61;
const int y = 101;
const RichTextString richText(
std::string(),
FontName::A,
Color(48, 12, 12),
TextAlignment::Left,
game.getFontManager());
return std::make_unique<TextBox>(x, y, richText, game.getRenderer());
}();
this->backToClassButton = []()
{
auto function = [](Game &game)
{
SDL_StopTextInput();
game.setPanel<ChooseClassPanel>(game);
};
return Button<Game&>(function);
}();
this->acceptButton = []()
{
auto function = [](Game &game, const CharacterClass &charClass,
const std::string &name)
{
SDL_StopTextInput();
game.setPanel<ChooseGenderPanel>(game, charClass, name);
};
return Button<Game&, const CharacterClass&, const std::string&>(function);
}();
// Activate SDL text input (handled in handleEvent()).
SDL_StartTextInput();
}
Panel::CursorData ChooseNamePanel::getCurrentCursor() const
{
auto &game = this->getGame();
auto &renderer = game.getRenderer();
auto &textureManager = game.getTextureManager();
const auto &texture = textureManager.getTexture(
TextureFile::fromName(TextureName::SwordCursor),
PaletteFile::fromName(PaletteName::Default), renderer);
return CursorData(&texture, CursorAlignment::TopLeft);
}
void ChooseNamePanel::handleEvent(const SDL_Event &e)
{
const auto &inputManager = this->getGame().getInputManager();
const bool escapePressed = inputManager.keyPressed(e, SDLK_ESCAPE);
const bool enterPressed = inputManager.keyPressed(e, SDLK_RETURN) ||
inputManager.keyPressed(e, SDLK_KP_ENTER);
const bool backspacePressed = inputManager.keyPressed(e, SDLK_BACKSPACE) ||
inputManager.keyPressed(e, SDLK_KP_BACKSPACE);
if (escapePressed)
{
this->backToClassButton.click(this->getGame());
}
else if (enterPressed && (this->name.size() > 0))
{
// Accept the given name.
this->acceptButton.click(this->getGame(), this->charClass, this->name);
}
else
{
// Listen for SDL text input and changes in text. Only letters and spaces are allowed.
auto charIsAllowed = [](char c)
{
return (c == ' ') || ((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z'));
};
const bool textChanged = TextEntry::updateText(this->name, e,
backspacePressed, charIsAllowed, ChooseNamePanel::MAX_NAME_LENGTH);
if (textChanged)
{
// Update the displayed name.
this->nameTextBox = [this]()
{
const int x = 61;
const int y = 101;
auto &game = this->getGame();
const RichTextString &oldRichText = this->nameTextBox->getRichText();
const RichTextString richText(
this->name,
oldRichText.getFontName(),
oldRichText.getColor(),
oldRichText.getAlignment(),
game.getFontManager());
return std::make_unique<TextBox>(x, y, richText, game.getRenderer());
}();
}
}
}
void ChooseNamePanel::render(Renderer &renderer)
{
// Clear full screen.
renderer.clear();
// Set palette.
auto &textureManager = this->getGame().getTextureManager();
textureManager.setPalette(PaletteFile::fromName(PaletteName::Default));
// Draw background.
const auto &background = textureManager.getTexture(
TextureFile::fromName(TextureName::CharacterCreation),
PaletteFile::fromName(PaletteName::BuiltIn), renderer);
renderer.drawOriginal(background);
// Draw parchment: title.
renderer.drawOriginal(this->parchment,
(Renderer::ORIGINAL_WIDTH / 2) - (this->parchment.getWidth() / 2),
(Renderer::ORIGINAL_HEIGHT / 2) - (this->parchment.getHeight() / 2));
// Draw text: title, name.
renderer.drawOriginal(this->titleTextBox->getTexture(),
this->titleTextBox->getX(), this->titleTextBox->getY());
renderer.drawOriginal(this->nameTextBox->getTexture(),
this->nameTextBox->getX(), this->nameTextBox->getY());
}
| 28.202128 | 88 | 0.69785 | [
"render"
] |
0d1b4bacbfd50e950526d25ae0980d592d6c3099 | 1,408 | hpp | C++ | sources/Notebook.hpp | Shlomi-Lantser/Ex2-CPP | 74ec0a2e89c5568268400b93edc0fed1679eae21 | [
"MIT"
] | null | null | null | sources/Notebook.hpp | Shlomi-Lantser/Ex2-CPP | 74ec0a2e89c5568268400b93edc0fed1679eae21 | [
"MIT"
] | null | null | null | sources/Notebook.hpp | Shlomi-Lantser/Ex2-CPP | 74ec0a2e89c5568268400b93edc0fed1679eae21 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include "Direction.hpp"
using namespace std;
using ariel::Direction;
namespace ariel{
class Notebook{
private:
vector<vector<string>> pages; //Datastructure to hold the notebook
uint maxCols = 100;
public:
Notebook(){ //Initilize the notebook
uint pages = 100;
uint rows = 100;
for (int i = 0; i < pages; i++){
vector<string> page;
for (int j = 0; j < rows; j++){
string row;
for (int k = 0; k < maxCols; k++){
row += "_";
}
page.push_back(row);
}
this->pages.push_back(page);
}
}
void update(uint page){ // Adding new row to the given page
string row;
for (int i = 0; i < maxCols; i++){
row+= "_";
}
pages[(uint)page].push_back(row);
}
~Notebook(){
this->pages.clear();
}
void write(int page ,int row ,int col , ariel::Direction dir , string const &input);
string read(int page ,int row , int col , ariel::Direction dir , int len);
void erase(int page , int row , int col , ariel::Direction dir , int len);
void show(int page);
};
}
| 29.333333 | 92 | 0.473722 | [
"vector"
] |
0d1e3a46c9b0329d9c88d68728b0294f717a20d5 | 59,919 | hpp | C++ | include/GlobalNamespace/LocalNetworkPlayerModel.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/LocalNetworkPlayerModel.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/LocalNetworkPlayerModel.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: BaseNetworkPlayerModel
#include "GlobalNamespace/BaseNetworkPlayerModel.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: LocalNetworkDiscoveryManager
class LocalNetworkDiscoveryManager;
// Forward declaring type: IPlatformUserModel
class IPlatformUserModel;
// Forward declaring type: INetworkConfig
class INetworkConfig;
// Skipping declaration: INetworkPlayerModel because it is already included!
// Forward declaring type: BasicConnectionRequestHandler
class BasicConnectionRequestHandler;
// Forward declaring type: INetworkPlayer
class INetworkPlayer;
// Forward declaring type: LiteNetLibConnectionManager
class LiteNetLibConnectionManager;
// Skipping declaration: BeatmapLevelSelectionMask because it is already included!
// Skipping declaration: GameplayServerConfiguration because it is already included!
// Forward declaring type: IConnectedPlayer
class IConnectedPlayer;
// Forward declaring type: ConnectionFailedReason
struct ConnectionFailedReason;
// Forward declaring type: INetworkPlayerModelPartyConfig`1<T>
template<typename T>
class INetworkPlayerModelPartyConfig_1;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
// Forward declaring type: IEnumerable`1<T>
template<typename T>
class IEnumerable_1;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
}
// Forward declaring namespace: System::Net
namespace System::Net {
// Forward declaring type: IPAddress
class IPAddress;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: LocalNetworkPlayerModel
class LocalNetworkPlayerModel;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::LocalNetworkPlayerModel);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::LocalNetworkPlayerModel*, "", "LocalNetworkPlayerModel");
// Type namespace:
namespace GlobalNamespace {
// Size: 0xF8
#pragma pack(push, 1)
// Autogenerated type: LocalNetworkPlayerModel
// [TokenAttribute] Offset: FFFFFFFF
class LocalNetworkPlayerModel : public ::GlobalNamespace::BaseNetworkPlayerModel {
public:
// Nested type: ::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer
class LocalNetworkPlayer;
// Nested type: ::GlobalNamespace::LocalNetworkPlayerModel::CreatePartyConfig
class CreatePartyConfig;
// Nested type: ::GlobalNamespace::LocalNetworkPlayerModel::$Start$d__41
struct $Start$d__41;
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private LocalNetworkDiscoveryManager _discoveryManager
// Size: 0x8
// Offset: 0x90
::GlobalNamespace::LocalNetworkDiscoveryManager* discoveryManager;
// Field size check
static_assert(sizeof(::GlobalNamespace::LocalNetworkDiscoveryManager*) == 0x8);
// [InjectAttribute] Offset: 0x124D9D4
// private readonly IPlatformUserModel _platformUserModel
// Size: 0x8
// Offset: 0x98
::GlobalNamespace::IPlatformUserModel* platformUserModel;
// Field size check
static_assert(sizeof(::GlobalNamespace::IPlatformUserModel*) == 0x8);
// [InjectAttribute] Offset: 0x124D9E4
// private readonly INetworkConfig _networkConfig
// Size: 0x8
// Offset: 0xA0
::GlobalNamespace::INetworkConfig* networkConfig;
// Field size check
static_assert(sizeof(::GlobalNamespace::INetworkConfig*) == 0x8);
// private readonly System.Collections.Generic.List`1<LocalNetworkPlayerModel/LocalNetworkPlayer> _partyPlayers
// Size: 0x8
// Offset: 0xA8
::System::Collections::Generic::List_1<::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*>* partyPlayers;
// Field size check
static_assert(sizeof(::System::Collections::Generic::List_1<::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*>*) == 0x8);
// private readonly System.Collections.Generic.List`1<LocalNetworkPlayerModel/LocalNetworkPlayer> _otherPlayers
// Size: 0x8
// Offset: 0xB0
::System::Collections::Generic::List_1<::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*>* otherPlayers;
// Field size check
static_assert(sizeof(::System::Collections::Generic::List_1<::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*>*) == 0x8);
// private LocalNetworkPlayerModel/LocalNetworkPlayer _localPlayer
// Size: 0x8
// Offset: 0xB8
::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer* localPlayer;
// Field size check
static_assert(sizeof(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*) == 0x8);
// private System.Boolean _networkingFailed
// Size: 0x1
// Offset: 0xC0
bool networkingFailed;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _partyEnabled
// Size: 0x1
// Offset: 0xC1
bool partyEnabled;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: partyEnabled and: partyManager
char __padding7[0x6] = {};
// private INetworkPlayerModel _partyManager
// Size: 0x8
// Offset: 0xC8
::GlobalNamespace::INetworkPlayerModel* partyManager;
// Field size check
static_assert(sizeof(::GlobalNamespace::INetworkPlayerModel*) == 0x8);
// private readonly BasicConnectionRequestHandler _connectionRequestHandler
// Size: 0x8
// Offset: 0xD0
::GlobalNamespace::BasicConnectionRequestHandler* connectionRequestHandler;
// Field size check
static_assert(sizeof(::GlobalNamespace::BasicConnectionRequestHandler*) == 0x8);
// private System.Action`1<System.Int32> partySizeChangedEvent
// Size: 0x8
// Offset: 0xD8
::System::Action_1<int>* partySizeChangedEvent;
// Field size check
static_assert(sizeof(::System::Action_1<int>*) == 0x8);
// private System.Action`1<INetworkPlayerModel> partyChangedEvent
// Size: 0x8
// Offset: 0xE0
::System::Action_1<::GlobalNamespace::INetworkPlayerModel*>* partyChangedEvent;
// Field size check
static_assert(sizeof(::System::Action_1<::GlobalNamespace::INetworkPlayerModel*>*) == 0x8);
// private System.Action`1<INetworkPlayer> joinRequestedEvent
// Size: 0x8
// Offset: 0xE8
::System::Action_1<::GlobalNamespace::INetworkPlayer*>* joinRequestedEvent;
// Field size check
static_assert(sizeof(::System::Action_1<::GlobalNamespace::INetworkPlayer*>*) == 0x8);
// private System.Action`1<INetworkPlayer> inviteRequestedEvent
// Size: 0x8
// Offset: 0xF0
::System::Action_1<::GlobalNamespace::INetworkPlayer*>* inviteRequestedEvent;
// Field size check
static_assert(sizeof(::System::Action_1<::GlobalNamespace::INetworkPlayer*>*) == 0x8);
public:
// Get instance field reference: private LocalNetworkDiscoveryManager _discoveryManager
::GlobalNamespace::LocalNetworkDiscoveryManager*& dyn__discoveryManager();
// Get instance field reference: private readonly IPlatformUserModel _platformUserModel
::GlobalNamespace::IPlatformUserModel*& dyn__platformUserModel();
// Get instance field reference: private readonly INetworkConfig _networkConfig
::GlobalNamespace::INetworkConfig*& dyn__networkConfig();
// Get instance field reference: private readonly System.Collections.Generic.List`1<LocalNetworkPlayerModel/LocalNetworkPlayer> _partyPlayers
::System::Collections::Generic::List_1<::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*>*& dyn__partyPlayers();
// Get instance field reference: private readonly System.Collections.Generic.List`1<LocalNetworkPlayerModel/LocalNetworkPlayer> _otherPlayers
::System::Collections::Generic::List_1<::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*>*& dyn__otherPlayers();
// Get instance field reference: private LocalNetworkPlayerModel/LocalNetworkPlayer _localPlayer
::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*& dyn__localPlayer();
// Get instance field reference: private System.Boolean _networkingFailed
bool& dyn__networkingFailed();
// Get instance field reference: private System.Boolean _partyEnabled
bool& dyn__partyEnabled();
// Get instance field reference: private INetworkPlayerModel _partyManager
::GlobalNamespace::INetworkPlayerModel*& dyn__partyManager();
// Get instance field reference: private readonly BasicConnectionRequestHandler _connectionRequestHandler
::GlobalNamespace::BasicConnectionRequestHandler*& dyn__connectionRequestHandler();
// Get instance field reference: private System.Action`1<System.Int32> partySizeChangedEvent
::System::Action_1<int>*& dyn_partySizeChangedEvent();
// Get instance field reference: private System.Action`1<INetworkPlayerModel> partyChangedEvent
::System::Action_1<::GlobalNamespace::INetworkPlayerModel*>*& dyn_partyChangedEvent();
// Get instance field reference: private System.Action`1<INetworkPlayer> joinRequestedEvent
::System::Action_1<::GlobalNamespace::INetworkPlayer*>*& dyn_joinRequestedEvent();
// Get instance field reference: private System.Action`1<INetworkPlayer> inviteRequestedEvent
::System::Action_1<::GlobalNamespace::INetworkPlayer*>*& dyn_inviteRequestedEvent();
// private System.Boolean get_canInvitePlayers()
// Offset: 0x152B950
bool get_canInvitePlayers();
// private System.Boolean get_hasConnectedPeers()
// Offset: 0x152B9E8
bool get_hasConnectedPeers();
// public System.Collections.Generic.IEnumerable`1<INetworkPlayer> get_otherPlayers()
// Offset: 0x152C008
::System::Collections::Generic::IEnumerable_1<::GlobalNamespace::INetworkPlayer*>* get_otherPlayers();
// public LiteNetLibConnectionManager get_liteNetLibConnectionManager()
// Offset: 0x152C020
::GlobalNamespace::LiteNetLibConnectionManager* get_liteNetLibConnectionManager();
// private System.Boolean TryGetPlayer(System.String userId, out LocalNetworkPlayerModel/LocalNetworkPlayer player)
// Offset: 0x152C64C
bool TryGetPlayer(::StringW userId, ByRef<::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*> player);
// private LocalNetworkPlayerModel/LocalNetworkPlayer GetPlayer(System.String userId)
// Offset: 0x152C7A4
::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer* GetPlayer(::StringW userId);
// private System.Void RefreshLocalPlayer(System.Boolean forcePlayersChanged)
// Offset: 0x152C368
void RefreshLocalPlayer(bool forcePlayersChanged);
// private System.Void HandlePeerUpdate(System.String userId, System.Net.IPAddress ipAddress, System.String encryptedUserName, System.Int32 currentPartySize, System.Boolean isPartyOwner, BeatmapLevelSelectionMask selectionMask, GameplayServerConfiguration configuration)
// Offset: 0x152C95C
void HandlePeerUpdate(::StringW userId, ::System::Net::IPAddress* ipAddress, ::StringW encryptedUserName, int currentPartySize, bool isPartyOwner, ::GlobalNamespace::BeatmapLevelSelectionMask selectionMask, ::GlobalNamespace::GameplayServerConfiguration configuration);
// private System.Void SendJoinRequest(LocalNetworkPlayerModel/LocalNetworkPlayer player)
// Offset: 0x152CB88
void SendJoinRequest(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer* player);
// private System.Void HandleJoinRequest(System.String userId, System.Net.IPAddress ipAddress, System.String encryptedUserName)
// Offset: 0x152CC00
void HandleJoinRequest(::StringW userId, ::System::Net::IPAddress* ipAddress, ::StringW encryptedUserName);
// private System.Void SendJoinResponse(LocalNetworkPlayerModel/LocalNetworkPlayer player, System.Boolean allowJoin)
// Offset: 0x152CDF0
void SendJoinResponse(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer* player, bool allowJoin);
// private System.Void HandleJoinResponse(System.String id, System.String secret, System.Int32 multiplayerPort, System.Boolean blocked, System.Boolean isPartyOwner, BeatmapLevelSelectionMask selectionMask, GameplayServerConfiguration configuration)
// Offset: 0x152D154
void HandleJoinResponse(::StringW id, ::StringW secret, int multiplayerPort, bool blocked, bool isPartyOwner, ::GlobalNamespace::BeatmapLevelSelectionMask selectionMask, ::GlobalNamespace::GameplayServerConfiguration configuration);
// private System.Void SendInviteRequest(LocalNetworkPlayerModel/LocalNetworkPlayer player)
// Offset: 0x152D2F4
void SendInviteRequest(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer* player);
// private System.Void HandleInviteRequest(System.String userId, System.Net.IPAddress ipAddress, System.String encryptedUserName, System.String secret, System.Int32 multiplayerPort, System.Boolean isPartyOwner, BeatmapLevelSelectionMask selectionMask, GameplayServerConfiguration configuration)
// Offset: 0x152D444
void HandleInviteRequest(::StringW userId, ::System::Net::IPAddress* ipAddress, ::StringW encryptedUserName, ::StringW secret, int multiplayerPort, bool isPartyOwner, ::GlobalNamespace::BeatmapLevelSelectionMask selectionMask, ::GlobalNamespace::GameplayServerConfiguration configuration);
// private System.Void SendInviteResponse(LocalNetworkPlayerModel/LocalNetworkPlayer player, System.Boolean acceptInvite)
// Offset: 0x152D6C4
void SendInviteResponse(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer* player, bool acceptInvite);
// private System.Void HandleInviteResponse(System.String userId, System.Boolean accepted, System.Boolean blocked)
// Offset: 0x152D778
void HandleInviteResponse(::StringW userId, bool accepted, bool blocked);
// private System.Void ConnectToPeer(LocalNetworkPlayerModel/LocalNetworkPlayer player)
// Offset: 0x152D86C
void ConnectToPeer(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer* player);
// private System.Void DisconnectPeer(LocalNetworkPlayerModel/LocalNetworkPlayer player)
// Offset: 0x152E330
void DisconnectPeer(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer* player);
// private System.Void HandlePlayersChanged()
// Offset: 0x152C8C4
void HandlePlayersChanged();
// private System.Void TryStartServer()
// Offset: 0x152CFD0
void TryStartServer();
// public override System.Int32 get_currentPartySize()
// Offset: 0x152BA40
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Int32 BaseNetworkPlayerModel::get_currentPartySize()
int get_currentPartySize();
// public override System.Boolean get_discoveryEnabled()
// Offset: 0x152BA90
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Boolean BaseNetworkPlayerModel::get_discoveryEnabled()
bool get_discoveryEnabled();
// public override System.Void set_discoveryEnabled(System.Boolean value)
// Offset: 0x152BAAC
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::set_discoveryEnabled(System.Boolean value)
void set_discoveryEnabled(bool value);
// public override System.Boolean get_localPlayerIsPartyOwner()
// Offset: 0x152BFEC
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Boolean BaseNetworkPlayerModel::get_localPlayerIsPartyOwner()
bool get_localPlayerIsPartyOwner();
// public override System.Boolean get_hasNetworkingFailed()
// Offset: 0x152C018
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Boolean BaseNetworkPlayerModel::get_hasNetworkingFailed()
bool get_hasNetworkingFailed();
// public override System.Void add_partySizeChangedEvent(System.Action`1<System.Int32> value)
// Offset: 0x152BACC
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::add_partySizeChangedEvent(System.Action`1<System.Int32> value)
void add_partySizeChangedEvent(::System::Action_1<int>* value);
// public override System.Void remove_partySizeChangedEvent(System.Action`1<System.Int32> value)
// Offset: 0x152BB70
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::remove_partySizeChangedEvent(System.Action`1<System.Int32> value)
void remove_partySizeChangedEvent(::System::Action_1<int>* value);
// public override System.Void add_partyChangedEvent(System.Action`1<INetworkPlayerModel> value)
// Offset: 0x152BC14
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::add_partyChangedEvent(System.Action`1<INetworkPlayerModel> value)
void add_partyChangedEvent(::System::Action_1<::GlobalNamespace::INetworkPlayerModel*>* value);
// public override System.Void remove_partyChangedEvent(System.Action`1<INetworkPlayerModel> value)
// Offset: 0x152BCB8
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::remove_partyChangedEvent(System.Action`1<INetworkPlayerModel> value)
void remove_partyChangedEvent(::System::Action_1<::GlobalNamespace::INetworkPlayerModel*>* value);
// public override System.Void add_joinRequestedEvent(System.Action`1<INetworkPlayer> value)
// Offset: 0x152BD5C
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::add_joinRequestedEvent(System.Action`1<INetworkPlayer> value)
void add_joinRequestedEvent(::System::Action_1<::GlobalNamespace::INetworkPlayer*>* value);
// public override System.Void remove_joinRequestedEvent(System.Action`1<INetworkPlayer> value)
// Offset: 0x152BE00
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::remove_joinRequestedEvent(System.Action`1<INetworkPlayer> value)
void remove_joinRequestedEvent(::System::Action_1<::GlobalNamespace::INetworkPlayer*>* value);
// public override System.Void add_inviteRequestedEvent(System.Action`1<INetworkPlayer> value)
// Offset: 0x152BEA4
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::add_inviteRequestedEvent(System.Action`1<INetworkPlayer> value)
void add_inviteRequestedEvent(::System::Action_1<::GlobalNamespace::INetworkPlayer*>* value);
// public override System.Void remove_inviteRequestedEvent(System.Action`1<INetworkPlayer> value)
// Offset: 0x152BF48
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::remove_inviteRequestedEvent(System.Action`1<INetworkPlayer> value)
void remove_inviteRequestedEvent(::System::Action_1<::GlobalNamespace::INetworkPlayer*>* value);
// public System.Void .ctor()
// Offset: 0x152E518
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::.ctor()
// Base method: System.Void StandaloneMonobehavior::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static LocalNetworkPlayerModel* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::LocalNetworkPlayerModel::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<LocalNetworkPlayerModel*, creationType>()));
}
// protected override System.Void Start()
// Offset: 0x152C078
// Implemented from: StandaloneMonobehavior
// Base method: System.Void StandaloneMonobehavior::Start()
void Start();
// protected override System.Void Update()
// Offset: 0x152C138
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::Update()
void Update();
// protected override System.Void OnDestroy()
// Offset: 0x152C478
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::OnDestroy()
void OnDestroy();
// protected override System.Collections.Generic.IEnumerable`1<INetworkPlayer> GetPartyPlayers()
// Offset: 0x152C63C
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Collections.Generic.IEnumerable`1<INetworkPlayer> BaseNetworkPlayerModel::GetPartyPlayers()
::System::Collections::Generic::IEnumerable_1<::GlobalNamespace::INetworkPlayer*>* GetPartyPlayers();
// protected override System.Collections.Generic.IEnumerable`1<INetworkPlayer> GetOtherPlayers()
// Offset: 0x152C644
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Collections.Generic.IEnumerable`1<INetworkPlayer> BaseNetworkPlayerModel::GetOtherPlayers()
::System::Collections::Generic::IEnumerable_1<::GlobalNamespace::INetworkPlayer*>* GetOtherPlayers();
// protected override System.Void PlayerConnected(IConnectedPlayer connectedPlayer)
// Offset: 0x152DA1C
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::PlayerConnected(IConnectedPlayer connectedPlayer)
void PlayerConnected(::GlobalNamespace::IConnectedPlayer* connectedPlayer);
// protected override System.Void ConnectionFailed(ConnectionFailedReason reason)
// Offset: 0x152DEA0
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::ConnectionFailed(ConnectionFailedReason reason)
void ConnectionFailed(::GlobalNamespace::ConnectionFailedReason reason);
// protected override System.Void PlayerDisconnected(IConnectedPlayer connectedPlayer)
// Offset: 0x152DFDC
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::PlayerDisconnected(IConnectedPlayer connectedPlayer)
void PlayerDisconnected(::GlobalNamespace::IConnectedPlayer* connectedPlayer);
// protected override System.Void PartySizeChanged(System.Int32 currentPartySize)
// Offset: 0x152E430
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::PartySizeChanged(System.Int32 currentPartySize)
void PartySizeChanged(int currentPartySize);
// public override System.Boolean CreatePartyConnection(INetworkPlayerModelPartyConfig`1<T> createConfig)
// Offset: 0xFFFFFFFFFFFFFFFF
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Boolean BaseNetworkPlayerModel::CreatePartyConnection(INetworkPlayerModelPartyConfig`1<T> createConfig)
template<class T>
bool CreatePartyConnection(::GlobalNamespace::INetworkPlayerModelPartyConfig_1<T>* createConfig) {
static_assert(std::is_convertible_v<std::remove_pointer_t<T>, ::GlobalNamespace::INetworkPlayerModel>);
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::LocalNetworkPlayerModel::CreatePartyConnection");
auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CreatePartyConnection", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(createConfig)})));
auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___generic__method, createConfig);
}
// public override System.Void DestroyPartyConnection()
// Offset: 0x152E470
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::DestroyPartyConnection()
void DestroyPartyConnection();
// protected override System.Void ConnectedPlayerManagerChanged()
// Offset: 0x152E510
// Implemented from: BaseNetworkPlayerModel
// Base method: System.Void BaseNetworkPlayerModel::ConnectedPlayerManagerChanged()
void ConnectedPlayerManagerChanged();
}; // LocalNetworkPlayerModel
#pragma pack(pop)
static check_size<sizeof(LocalNetworkPlayerModel), 240 + sizeof(::System::Action_1<::GlobalNamespace::INetworkPlayer*>*)> __GlobalNamespace_LocalNetworkPlayerModelSizeCheck;
static_assert(sizeof(LocalNetworkPlayerModel) == 0xF8);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::get_canInvitePlayers
// Il2CppName: get_canInvitePlayers
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::get_canInvitePlayers)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "get_canInvitePlayers", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::get_hasConnectedPeers
// Il2CppName: get_hasConnectedPeers
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::get_hasConnectedPeers)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "get_hasConnectedPeers", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::get_otherPlayers
// Il2CppName: get_otherPlayers
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::Generic::IEnumerable_1<::GlobalNamespace::INetworkPlayer*>* (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::get_otherPlayers)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "get_otherPlayers", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::get_liteNetLibConnectionManager
// Il2CppName: get_liteNetLibConnectionManager
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::LiteNetLibConnectionManager* (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::get_liteNetLibConnectionManager)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "get_liteNetLibConnectionManager", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::TryGetPlayer
// Il2CppName: TryGetPlayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::LocalNetworkPlayerModel::*)(::StringW, ByRef<::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*>)>(&GlobalNamespace::LocalNetworkPlayerModel::TryGetPlayer)> {
static const MethodInfo* get() {
static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* player = &::il2cpp_utils::GetClassFromName("", "LocalNetworkPlayerModel/LocalNetworkPlayer")->this_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "TryGetPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId, player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::GetPlayer
// Il2CppName: GetPlayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer* (GlobalNamespace::LocalNetworkPlayerModel::*)(::StringW)>(&GlobalNamespace::LocalNetworkPlayerModel::GetPlayer)> {
static const MethodInfo* get() {
static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "GetPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::RefreshLocalPlayer
// Il2CppName: RefreshLocalPlayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(bool)>(&GlobalNamespace::LocalNetworkPlayerModel::RefreshLocalPlayer)> {
static const MethodInfo* get() {
static auto* forcePlayersChanged = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "RefreshLocalPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{forcePlayersChanged});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::HandlePeerUpdate
// Il2CppName: HandlePeerUpdate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::StringW, ::System::Net::IPAddress*, ::StringW, int, bool, ::GlobalNamespace::BeatmapLevelSelectionMask, ::GlobalNamespace::GameplayServerConfiguration)>(&GlobalNamespace::LocalNetworkPlayerModel::HandlePeerUpdate)> {
static const MethodInfo* get() {
static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* ipAddress = &::il2cpp_utils::GetClassFromName("System.Net", "IPAddress")->byval_arg;
static auto* encryptedUserName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* currentPartySize = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* isPartyOwner = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* selectionMask = &::il2cpp_utils::GetClassFromName("", "BeatmapLevelSelectionMask")->byval_arg;
static auto* configuration = &::il2cpp_utils::GetClassFromName("", "GameplayServerConfiguration")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "HandlePeerUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId, ipAddress, encryptedUserName, currentPartySize, isPartyOwner, selectionMask, configuration});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::SendJoinRequest
// Il2CppName: SendJoinRequest
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*)>(&GlobalNamespace::LocalNetworkPlayerModel::SendJoinRequest)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "LocalNetworkPlayerModel/LocalNetworkPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "SendJoinRequest", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::HandleJoinRequest
// Il2CppName: HandleJoinRequest
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::StringW, ::System::Net::IPAddress*, ::StringW)>(&GlobalNamespace::LocalNetworkPlayerModel::HandleJoinRequest)> {
static const MethodInfo* get() {
static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* ipAddress = &::il2cpp_utils::GetClassFromName("System.Net", "IPAddress")->byval_arg;
static auto* encryptedUserName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "HandleJoinRequest", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId, ipAddress, encryptedUserName});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::SendJoinResponse
// Il2CppName: SendJoinResponse
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*, bool)>(&GlobalNamespace::LocalNetworkPlayerModel::SendJoinResponse)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "LocalNetworkPlayerModel/LocalNetworkPlayer")->byval_arg;
static auto* allowJoin = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "SendJoinResponse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player, allowJoin});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::HandleJoinResponse
// Il2CppName: HandleJoinResponse
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::StringW, ::StringW, int, bool, bool, ::GlobalNamespace::BeatmapLevelSelectionMask, ::GlobalNamespace::GameplayServerConfiguration)>(&GlobalNamespace::LocalNetworkPlayerModel::HandleJoinResponse)> {
static const MethodInfo* get() {
static auto* id = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* secret = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* multiplayerPort = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* blocked = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* isPartyOwner = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* selectionMask = &::il2cpp_utils::GetClassFromName("", "BeatmapLevelSelectionMask")->byval_arg;
static auto* configuration = &::il2cpp_utils::GetClassFromName("", "GameplayServerConfiguration")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "HandleJoinResponse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{id, secret, multiplayerPort, blocked, isPartyOwner, selectionMask, configuration});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::SendInviteRequest
// Il2CppName: SendInviteRequest
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*)>(&GlobalNamespace::LocalNetworkPlayerModel::SendInviteRequest)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "LocalNetworkPlayerModel/LocalNetworkPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "SendInviteRequest", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::HandleInviteRequest
// Il2CppName: HandleInviteRequest
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::StringW, ::System::Net::IPAddress*, ::StringW, ::StringW, int, bool, ::GlobalNamespace::BeatmapLevelSelectionMask, ::GlobalNamespace::GameplayServerConfiguration)>(&GlobalNamespace::LocalNetworkPlayerModel::HandleInviteRequest)> {
static const MethodInfo* get() {
static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* ipAddress = &::il2cpp_utils::GetClassFromName("System.Net", "IPAddress")->byval_arg;
static auto* encryptedUserName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* secret = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* multiplayerPort = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* isPartyOwner = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* selectionMask = &::il2cpp_utils::GetClassFromName("", "BeatmapLevelSelectionMask")->byval_arg;
static auto* configuration = &::il2cpp_utils::GetClassFromName("", "GameplayServerConfiguration")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "HandleInviteRequest", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId, ipAddress, encryptedUserName, secret, multiplayerPort, isPartyOwner, selectionMask, configuration});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::SendInviteResponse
// Il2CppName: SendInviteResponse
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*, bool)>(&GlobalNamespace::LocalNetworkPlayerModel::SendInviteResponse)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "LocalNetworkPlayerModel/LocalNetworkPlayer")->byval_arg;
static auto* acceptInvite = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "SendInviteResponse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player, acceptInvite});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::HandleInviteResponse
// Il2CppName: HandleInviteResponse
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::StringW, bool, bool)>(&GlobalNamespace::LocalNetworkPlayerModel::HandleInviteResponse)> {
static const MethodInfo* get() {
static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* accepted = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* blocked = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "HandleInviteResponse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId, accepted, blocked});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::ConnectToPeer
// Il2CppName: ConnectToPeer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*)>(&GlobalNamespace::LocalNetworkPlayerModel::ConnectToPeer)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "LocalNetworkPlayerModel/LocalNetworkPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "ConnectToPeer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::DisconnectPeer
// Il2CppName: DisconnectPeer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::GlobalNamespace::LocalNetworkPlayerModel::LocalNetworkPlayer*)>(&GlobalNamespace::LocalNetworkPlayerModel::DisconnectPeer)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "LocalNetworkPlayerModel/LocalNetworkPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "DisconnectPeer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::HandlePlayersChanged
// Il2CppName: HandlePlayersChanged
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::HandlePlayersChanged)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "HandlePlayersChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::TryStartServer
// Il2CppName: TryStartServer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::TryStartServer)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "TryStartServer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::get_currentPartySize
// Il2CppName: get_currentPartySize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::get_currentPartySize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "get_currentPartySize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::get_discoveryEnabled
// Il2CppName: get_discoveryEnabled
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::get_discoveryEnabled)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "get_discoveryEnabled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::set_discoveryEnabled
// Il2CppName: set_discoveryEnabled
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(bool)>(&GlobalNamespace::LocalNetworkPlayerModel::set_discoveryEnabled)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "set_discoveryEnabled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::get_localPlayerIsPartyOwner
// Il2CppName: get_localPlayerIsPartyOwner
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::get_localPlayerIsPartyOwner)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "get_localPlayerIsPartyOwner", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::get_hasNetworkingFailed
// Il2CppName: get_hasNetworkingFailed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::get_hasNetworkingFailed)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "get_hasNetworkingFailed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::add_partySizeChangedEvent
// Il2CppName: add_partySizeChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::System::Action_1<int>*)>(&GlobalNamespace::LocalNetworkPlayerModel::add_partySizeChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Int32")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "add_partySizeChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::remove_partySizeChangedEvent
// Il2CppName: remove_partySizeChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::System::Action_1<int>*)>(&GlobalNamespace::LocalNetworkPlayerModel::remove_partySizeChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Int32")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "remove_partySizeChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::add_partyChangedEvent
// Il2CppName: add_partyChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::System::Action_1<::GlobalNamespace::INetworkPlayerModel*>*)>(&GlobalNamespace::LocalNetworkPlayerModel::add_partyChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "INetworkPlayerModel")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "add_partyChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::remove_partyChangedEvent
// Il2CppName: remove_partyChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::System::Action_1<::GlobalNamespace::INetworkPlayerModel*>*)>(&GlobalNamespace::LocalNetworkPlayerModel::remove_partyChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "INetworkPlayerModel")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "remove_partyChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::add_joinRequestedEvent
// Il2CppName: add_joinRequestedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::System::Action_1<::GlobalNamespace::INetworkPlayer*>*)>(&GlobalNamespace::LocalNetworkPlayerModel::add_joinRequestedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "INetworkPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "add_joinRequestedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::remove_joinRequestedEvent
// Il2CppName: remove_joinRequestedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::System::Action_1<::GlobalNamespace::INetworkPlayer*>*)>(&GlobalNamespace::LocalNetworkPlayerModel::remove_joinRequestedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "INetworkPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "remove_joinRequestedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::add_inviteRequestedEvent
// Il2CppName: add_inviteRequestedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::System::Action_1<::GlobalNamespace::INetworkPlayer*>*)>(&GlobalNamespace::LocalNetworkPlayerModel::add_inviteRequestedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "INetworkPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "add_inviteRequestedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::remove_inviteRequestedEvent
// Il2CppName: remove_inviteRequestedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::System::Action_1<::GlobalNamespace::INetworkPlayer*>*)>(&GlobalNamespace::LocalNetworkPlayerModel::remove_inviteRequestedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "INetworkPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "remove_inviteRequestedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::Start
// Il2CppName: Start
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::Start)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::Update
// Il2CppName: Update
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::Update)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::OnDestroy
// Il2CppName: OnDestroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::OnDestroy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::GetPartyPlayers
// Il2CppName: GetPartyPlayers
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::Generic::IEnumerable_1<::GlobalNamespace::INetworkPlayer*>* (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::GetPartyPlayers)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "GetPartyPlayers", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::GetOtherPlayers
// Il2CppName: GetOtherPlayers
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::Generic::IEnumerable_1<::GlobalNamespace::INetworkPlayer*>* (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::GetOtherPlayers)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "GetOtherPlayers", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::PlayerConnected
// Il2CppName: PlayerConnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::LocalNetworkPlayerModel::PlayerConnected)> {
static const MethodInfo* get() {
static auto* connectedPlayer = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "PlayerConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{connectedPlayer});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::ConnectionFailed
// Il2CppName: ConnectionFailed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::GlobalNamespace::ConnectionFailedReason)>(&GlobalNamespace::LocalNetworkPlayerModel::ConnectionFailed)> {
static const MethodInfo* get() {
static auto* reason = &::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "ConnectionFailed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reason});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::PlayerDisconnected
// Il2CppName: PlayerDisconnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(::GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::LocalNetworkPlayerModel::PlayerDisconnected)> {
static const MethodInfo* get() {
static auto* connectedPlayer = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "PlayerDisconnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{connectedPlayer});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::PartySizeChanged
// Il2CppName: PartySizeChanged
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)(int)>(&GlobalNamespace::LocalNetworkPlayerModel::PartySizeChanged)> {
static const MethodInfo* get() {
static auto* currentPartySize = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "PartySizeChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{currentPartySize});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::CreatePartyConnection
// Il2CppName: CreatePartyConnection
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::DestroyPartyConnection
// Il2CppName: DestroyPartyConnection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::DestroyPartyConnection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "DestroyPartyConnection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::LocalNetworkPlayerModel::ConnectedPlayerManagerChanged
// Il2CppName: ConnectedPlayerManagerChanged
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::LocalNetworkPlayerModel::*)()>(&GlobalNamespace::LocalNetworkPlayerModel::ConnectedPlayerManagerChanged)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LocalNetworkPlayerModel*), "ConnectedPlayerManagerChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 71.673445 | 353 | 0.769155 | [
"object",
"vector"
] |
0d2170ae7dc94cf9a0141f945ae4c1d7d4826df1 | 702 | cpp | C++ | leetcode/leetcode_912.cpp | xufor/dsa-hustle | 00ca691ddc4794a5a7b4439a59c463c4f0444a7a | [
"MIT"
] | null | null | null | leetcode/leetcode_912.cpp | xufor/dsa-hustle | 00ca691ddc4794a5a7b4439a59c463c4f0444a7a | [
"MIT"
] | null | null | null | leetcode/leetcode_912.cpp | xufor/dsa-hustle | 00ca691ddc4794a5a7b4439a59c463c4f0444a7a | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define nl '\n'
#define sp " "
#define limit 1000000007
typedef long long ll;
using namespace std;
vector<int> sortArray(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int ntc;
cin >> ntc;
while(ntc--) {
int n, x;
cin >> n;
vector<int> v;
while(n--) {
cin >> x;
v.push_back(x);
}
for(int x: sortArray(v)) {
cout << x << sp;
}
}
return 0;
} | 19.5 | 43 | 0.505698 | [
"vector"
] |
0d277dbf717388e7bc6c2bf9f9e43221f0a6cdfc | 7,525 | cpp | C++ | Game/DefRenderTestScene.cpp | NinjaDanz3r/NinjaOctopushBurgersOfDoom | 3b89f02d13504e4790fd655889b0cba261d4dbc6 | [
"MIT"
] | 1 | 2016-05-23T18:31:29.000Z | 2016-05-23T18:31:29.000Z | Game/DefRenderTestScene.cpp | NinjaDanz3r/NinjaOctopushBurgersOfDoom | 3b89f02d13504e4790fd655889b0cba261d4dbc6 | [
"MIT"
] | 25 | 2015-01-03T01:17:45.000Z | 2015-03-23T09:37:52.000Z | Game/DefRenderTestScene.cpp | NinjaDanz3r/NinjaOctopushBurgersOfDoom | 3b89f02d13504e4790fd655889b0cba261d4dbc6 | [
"MIT"
] | null | null | null | #include "DefRenderTestScene.h"
#include <gl/glew.h>
#include <Texture2D.h>
#include "settings.h"
#include <Shader.h>
#include <ShaderProgram.h>
#include "Player.h"
#include "Camera.h"
#include <Geometry.h>
#include "GeometryObject.h"
#include "Square.h"
#include "Cube.h"
#include "ShadowMap.h"
#include "input.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#define BUFFER_OFFSET(i) ((char *)nullptr + (i))
DefRenderTestScene::DefRenderTestScene() {
texture = new Texture2D("Resources/Textures/kaleido.tga");
shadowVertexShader = new Shader("shadow_vertex.glsl", GL_VERTEX_SHADER);
shadowFragmentShader = new Shader("shadow_fragment.glsl", GL_FRAGMENT_SHADER);
shadowGeometryShader = new Shader("shadow_geometry.glsl", GL_GEOMETRY_SHADER);
shadowShaderProgram = new ShaderProgram({ shadowVertexShader, shadowGeometryShader, shadowFragmentShader });
vertexShader = new Shader("default_vertex.glsl", GL_VERTEX_SHADER);
geometryShader = new Shader("default_geometry.glsl", GL_GEOMETRY_SHADER);
fragmentShader = new Shader("default_fragment.glsl", GL_FRAGMENT_SHADER);
shaderProgram = new ShaderProgram({ vertexShader, geometryShader, fragmentShader });
deferredVertexShader = new Shader("deferred_vertex.glsl", GL_VERTEX_SHADER);
deferredFragmentShader = new Shader("deferred_fragment.glsl", GL_FRAGMENT_SHADER);
deferredShaderProgram = new ShaderProgram({ deferredVertexShader, deferredFragmentShader });
geometry = new Cube();
geometryObject = new GeometryObject(geometry);
geometryGround = new GeometryObject(geometry);
geometryObject->move(glm::vec3(0.f, 0.f, -0.1f));
geometryGround->setScale(5.0, 5.0, 5.0);
geometryGround->setPosition(0.5, -3.0, -2.0);
player = new Player();
player->setMovementSpeed(2.0f);
multipleRenderTargets = new FrameBufferObjects(deferredShaderProgram, settings::displayWidth(), settings::displayHeight());
shadowMap = new ShadowMap(settings::displayWidth(), settings::displayHeight());
}
DefRenderTestScene::~DefRenderTestScene() {
delete texture;
delete multipleRenderTargets;
delete shadowMap;
delete deferredShaderProgram;
delete shadowShaderProgram;
delete shaderProgram;
delete shadowVertexShader;
delete shadowGeometryShader;
delete shadowFragmentShader;
delete deferredVertexShader;
delete deferredFragmentShader;
delete vertexShader;
delete geometryShader;
delete fragmentShader;
delete geometryObject;
delete geometryGround;
delete geometry;
delete player;
}
Scene::SceneEnd* DefRenderTestScene::update(double time) {
player->update(time);
shadowTime += time;
multipleRenderTargets->light.position = glm::vec4(5.f * sin(shadowTime), 3.f, 3.f + 5.f * cos(shadowTime), 1.f);
if (input::triggered(input::NEW_SCENE))
return new Scene::SceneEnd(SceneEnd::NEW_SCENE);
return nullptr;
}
void DefRenderTestScene::render(int width, int height) {
multipleRenderTargets->bindForWriting();
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shaderProgram->use();
// Texture unit 0 is for base images.
glUniform1i(shaderProgram->uniformLocation("baseImage"), 0);
glBindVertexArray(geometryObject->geometry()->vertexArray());
// Base image texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture->textureID());
// Model matrix, unique for each model.
glm::mat4 model = geometryObject->modelMatrix();
// Send the matrices to the shader.
glm::mat4 view = player->camera()->view();
glm::mat4 MV = view * model;
glm::mat4 N = glm::transpose(glm::inverse(MV));
glUniformMatrix4fv(shaderProgram->uniformLocation("modelViewMatrix"), 1, GL_FALSE, &MV[0][0]);
glUniformMatrix3fv(shaderProgram->uniformLocation("normalMatrix"), 1, GL_FALSE, &glm::mat3(N)[0][0]);
glUniformMatrix4fv(shaderProgram->uniformLocation("projectionMatrix"), 1, GL_FALSE, &player->camera()->projection(width, height)[0][0]);
// Draw the triangles
glDrawElements(GL_TRIANGLES, geometryObject->geometry()->indexCount(), GL_UNSIGNED_INT, (void*)0);
// Model matrix, unique for each model.
model = geometryGround->modelMatrix();
MV = view * model;
glUniformMatrix4fv(shaderProgram->uniformLocation("modelViewMatrix"), 1, GL_FALSE, &MV[0][0]);
// Draw the triangles
glDrawElements(GL_TRIANGLES, geometryObject->geometry()->indexCount(), GL_UNSIGNED_INT, (void*)0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
//Geometry rendering complete.
renderShadows(width, height);
//Shadow map rendering complete.
multipleRenderTargets->render(player->camera(), width, height);
//Lighting render pass complete.
}
void DefRenderTestScene::renderShadows(int width, int height) {
shadowMap->bindForWriting();
shadowShaderProgram->use();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindVertexArray(geometryObject->geometry()->vertexArray());
// Model matrix, unique for each model.
glm::mat4 model = geometryObject->modelMatrix();
glm::vec3 position = glm::vec3(multipleRenderTargets->light.position);
// Send the matrices to the shader.
glm::mat4 viewMatrix = glm::lookAt(position, geometryObject->position(), glm::vec3(0, 1, 0));
glm::mat4 perspectiveMatrix = glm::perspective(45.0f, 1.0f, 2.0f, 50.0f);
glm::mat4 modelView = viewMatrix * model;
glm::mat4 normalMatrix = glm::transpose(glm::inverse(modelView));
glUniformMatrix4fv(shadowShaderProgram->uniformLocation("lightModelMatrix"), 1, GL_FALSE, &model[0][0]);
glUniformMatrix4fv(shadowShaderProgram->uniformLocation("lightViewMatrix"), 1, GL_FALSE, &viewMatrix[0][0]);
glUniformMatrix4fv(shadowShaderProgram->uniformLocation("lightProjectionMatrix"), 1, GL_FALSE, &perspectiveMatrix[0][0]);
glUniformMatrix3fv(shadowShaderProgram->uniformLocation("normalMatrix"), 1, GL_FALSE, &glm::mat3(normalMatrix)[0][0]);
// Draw the triangles
glDrawElements(GL_TRIANGLES, geometryObject->geometry()->indexCount(), GL_UNSIGNED_INT, (void*)0);
// Model matrix, unique for each model.
model = geometryGround->modelMatrix();
modelView = viewMatrix * model;
normalMatrix = glm::transpose(glm::inverse(modelView));
glUniformMatrix3fv(shadowShaderProgram->uniformLocation("normalMatrix"), 1, GL_FALSE, &glm::mat3(normalMatrix)[0][0]);
glUniformMatrix4fv(shadowShaderProgram->uniformLocation("lightModelMatrix"), 1, GL_FALSE, &model[0][0]);
// Draw the triangles
glDrawElements(GL_TRIANGLES, geometryObject->geometry()->indexCount(), GL_UNSIGNED_INT, (void*)0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
//shadow map render call complete.
//Now Bind uniform for sampling the shadow map in lighting pass.
deferredShaderProgram->use();
glm::mat4 uVTransformMatrix(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);
// Send the matrices to the shader.
glm::mat4 view = player->camera()->view();
glm::mat4 viewInverse = glm::inverse(view);
glUniformMatrix4fv(deferredShaderProgram->uniformLocation("lightViewMatrix"), 1, GL_FALSE, &viewMatrix[0][0]);
glUniformMatrix4fv(deferredShaderProgram->uniformLocation("lightProjectionMatrix"), 1, GL_FALSE, &perspectiveMatrix[0][0]);
glUniformMatrix4fv(deferredShaderProgram->uniformLocation("inverseViewMatrix"), 1, GL_FALSE, &viewInverse[0][0]);
glUniformMatrix4fv(deferredShaderProgram->uniformLocation("UVtransformMatrix"), 1, GL_FALSE, &uVTransformMatrix[0][0]);
glUniform1i(deferredShaderProgram->uniformLocation("tShadowMap"), FrameBufferObjects::NUM_TEXTURES + 1);
shadowMap->bindForReading(GL_TEXTURE0 + FrameBufferObjects::NUM_TEXTURES + 1);
} | 36.352657 | 137 | 0.761329 | [
"geometry",
"render",
"model",
"transform"
] |
0d349aeebb7ad453fee902d4e48ec74fd202a5dd | 8,619 | cpp | C++ | utility.cpp | KevinLADLee/LiDARCamOdomCalib | 50f16619e0eb7088ba45677d64dafdf841406896 | [
"MIT"
] | null | null | null | utility.cpp | KevinLADLee/LiDARCamOdomCalib | 50f16619e0eb7088ba45677d64dafdf841406896 | [
"MIT"
] | null | null | null | utility.cpp | KevinLADLee/LiDARCamOdomCalib | 50f16619e0eb7088ba45677d64dafdf841406896 | [
"MIT"
] | null | null | null | #include "utility.h"
ostream& operator<<(ostream& os, const _6dof& dof)
{
os << dof.rx << ',' << dof.ry << ',' << dof.rz << ','<< dof.x << ','<< dof.y << ','<< dof.z;
return os;
}
bool headString(string line,string chara){
if(line.find(chara)==0)return true;
else return false;
}
double getDist2(POINT_3D a,POINT_3D b){
return (float)((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)+(a.z-b.z)*(a.z-b.z));
}
double getDist(POINT_3D a, POINT_3D b) {
return sqrt(getDist2(a,b));
}
Vector4d dcm2q(Matrix3d& dcm){
Vector4d q;
if(dcm.trace()>0){
double sr=sqrt(1+dcm.trace());
double sr2=sr*2;
q(0)=(dcm(1,2)-dcm(2,1))/sr2;
q(1)=(dcm(2,0)-dcm(0,2))/sr2;
q(2)=(dcm(0,1)-dcm(1,0))/sr2;
q(3)=0.5*sr;
}else{
if(dcm(0,0)>dcm(1,1) && dcm(0,0)>dcm(2,2)){
double sr=sqrt(1+(dcm(0,0)-(dcm(1,1)+dcm(2,2))));
double sr2=sr*2;
q(3)=(dcm(1,2)-dcm(2,1))/sr2;
q(2)=(dcm(2,0)+dcm(0,2))/sr2;
q(1)=(dcm(0,1)+dcm(1,0))/sr2;
q(0)=0.5*sr;
}else if(dcm(1,1)>dcm(2,2)){
double sr = sqrt( 1 + (dcm(1,1) - ( dcm(2,2) + dcm(0,0) )) );
double sr2 = 2*sr;
q(0) = ( dcm(1,0) + dcm(0,1) ) / sr2;
q(1) = 0.5 * sr;
q(2) = ( dcm(1,2) + dcm(2,1) ) / sr2;
q(3) = ( dcm(2,0) - dcm(0,2) ) / sr2;
}else{
double sr = sqrt( 1 + (dcm(2,2) - ( dcm(0,0) + dcm(1,1) )) );
double sr2 = 2*sr;
q(0) = ( dcm(2,0) + dcm(0,2) ) / sr2;
q(1) = ( dcm(1,2) + dcm(2,1) ) / sr2;
q(2) = 0.5 * sr;
q(3) = ( dcm(0,1) - dcm(1,0) ) / sr2;
}
}
return q;
}
Matrix3d q2dcm(Vector4d& q){
Matrix3d R;
// Build quaternion element products
double q1q1=q(0)*q(0);
double q1q2=q(0)*q(1);
double q1q3=q(0)*q(2);
double q1q4=q(0)*q(3);
double q2q2=q(1)*q(1);
double q2q3=q(1)*q(2);
double q2q4=q(1)*q(3);
double q3q3=q(2)*q(2);
double q3q4=q(2)*q(3);
double q4q4=q(3)*q(3);
// Build DCM
R(0,0) = q1q1 - q2q2 - q3q3 + q4q4;
R(0,1) = 2*(q1q2 + q3q4);
R(0,2) = 2*(q1q3 - q2q4);
R(1,0) = 2*(q1q2 - q3q4);
R(1,1) = -q1q1 + q2q2 - q3q3 + q4q4;
R(1,2) = 2*(q2q3 + q1q4);
R(2,0) = 2*(q1q3 + q2q4);
R(2,1) = 2*(q2q3 - q1q4);
R(2,2) = -q1q1 - q2q2 + q3q3 + q4q4;
return R;
}
Matrix3d axisRot2R(double rx,double ry,double rz){
Matrix4d R,rotx,roty,rotz;
double sinv,cosv;
sinv=sin(rx),cosv=cos(rx);
rotx<<1,0,0,0,0,cosv,-sinv,0,0,sinv,cosv,0,0,0,0,1;
sinv=sin(ry);cosv=cos(ry);
roty<<cosv,0,sinv,0,0,1,0,0,-sinv,0,cosv,0,0,0,0,1;
sinv=sin(rz);cosv=cos(rz);
rotz<<cosv,-sinv,0,0,sinv,cosv,0,0,0,0,1,0,0,0,0,1;
R=rotx*roty*rotz;
Matrix3d retMat=R.block(0,0,3,3);
return retMat;
}
void R2axisRot(Matrix3d R,double& rx,double& ry,double& rz){
ry=asin(R(0,2));
rx=-atan2(R(1,2),R(2,2));
rz=-atan2(R(0,1),R(0,0));
}
Matrix4d _6dof2m(_6dof dof){
Matrix4d ret;
ret.block(0,0,3,3)=axisRot2R(dof.rx,dof.ry,dof.rz);
ret(0,3)=dof.x;
ret(1,3)=dof.y;
ret(2,3)=dof.z;
ret.block(3,0,1,4)<<0,0,0,1;
return ret;
};
_6dof m2_6dof(Matrix4d& m){
Matrix3d r=m.block(0,0,3,3);
_6dof dof;
R2axisRot(r,dof.rx,dof.ry,dof.rz);
dof.x=m(0,3);
dof.y=m(1,3);
dof.z=m(2,3);
return dof;
};
void int2rgba(int color,unsigned char& r,unsigned char& g,unsigned char& b,unsigned char& a){
r=(color&0x0000ff);
g=(color&0x00ff00)>>8;
b=(color&0xff0000)>>16;
a=(color&0xff000000)>>24;
}
void rgba2int(int& color,unsigned char r,unsigned char g,unsigned char b,unsigned char a){
color=((a&0x0000ff)<<24)|((b&0x0000ff)<<16)|((g&0x0000ff)<<8)|((r&0x0000ff));
}
int getSubpixelColor(int topLeftColor,int topRightColor,int bottomLeftColor,int bottomRightColor,double dx,double dy){
unsigned char rs[4],gs[4],bs[4],as[4];
unsigned char r,g,b,a;
int2rgba(topLeftColor,rs[0],gs[0],bs[0],as[0]);
int2rgba(topRightColor,rs[1],gs[1],bs[1],as[1]);
int2rgba(bottomLeftColor,rs[2],gs[2],bs[2],as[2]);
int2rgba(bottomRightColor,rs[3],gs[3],bs[3],as[3]);
r=rs[0]*(1-dx)*(1-dy)+rs[1]*dx*(1-dy)+rs[2]*(1-dx)*(dy)+rs[3]*dx*dy;
g=gs[0]*(1-dx)*(1-dy)+gs[1]*dx*(1-dy)+gs[2]*(1-dx)*(dy)+gs[3]*dx*dy;
b=bs[0]*(1-dx)*(1-dy)+bs[1]*dx*(1-dy)+bs[2]*(1-dx)*(dy)+bs[3]*dx*dy;
a=as[0]*(1-dx)*(1-dy)+as[1]*dx*(1-dy)+as[2]*(1-dx)*(dy)+as[3]*dx*dy;
int color;
rgba2int(color,r,g,b,a);
return color;
}
void getSubpixelColor(unsigned char* topLeftColor,unsigned char* topRightColor,unsigned char* bottomLeftColor,unsigned char* bottomRightColor,double dx,double dy,unsigned char* rgb){
unsigned char rs[4],gs[4],bs[4],as[4];
rgb[0]=topLeftColor[0]*(1-dx)*(1-dy)+topRightColor[0]*dx*(1-dy)+bottomLeftColor[0]*(1-dx)*(dy)+bottomRightColor[0]*dx*dy;
rgb[1]=topLeftColor[1]*(1-dx)*(1-dy)+topRightColor[1]*dx*(1-dy)+bottomLeftColor[1]*(1-dx)*(dy)+bottomRightColor[1]*dx*dy;
rgb[2]=topLeftColor[2]*(1-dx)*(1-dy)+topRightColor[2]*dx*(1-dy)+bottomLeftColor[2]*(1-dx)*(dy)+bottomRightColor[2]*dx*dy;
int color;
}
Matrix4d getMatrixFlomPly(string fn){
ifstream ifs(fn,ios::binary);
string line;
Matrix4d globalPose=Matrix4d::Identity();
int n=0;
while(getline(ifs,line)){
if(headString(line,"matrix")){
float f[4];
int i;
for(i=0;i<5;i++){
if(i!=0)f[i-1]=stof(line.substr(0,line.find_first_of(" ")));
line.erase(0,line.find_first_of(" ")+1);
}
globalPose(0,n)=f[0];
globalPose(1,n)=f[1];
globalPose(2,n)=f[2];
globalPose(3,n)=f[3];
n++;
}
if(headString(line,"end_header"))break;
}
ifs.close();
return globalPose;
}
//p_3d=M*p_2d: cam->3D scanner translation
Matrix4d readCPara(string fileName){
ifstream ifs(fileName,ios::binary);
string line;
int n=0;
getline(ifs,line);
getline(ifs,line);
float position[3];
for(int i=0;i<3;i++){
if(i!=2)position[i]=stof(line.substr(0,line.find_first_of(" ")));
else position[i]=stof(line);
line.erase(0,line.find_first_of(" ")+1);
}
getline(ifs,line);
getline(ifs,line);
float pose[4];
for(int i=0;i<4;i++){
if(i!=3)pose[i]=stof(line.substr(0,line.find_first_of(" ")));
else pose[i]=stof(line);
line.erase(0,line.find_first_of(" ")+1);
}
ifs.close();
Vector4d q;
q<<pose[0],pose[1],pose[2],pose[3];
Matrix4d P;
P.block(0,0,3,3)=q2dcm(q);
P.block(0,3,3,1)<<position[0],position[1],position[2];
P.block(3,0,1,4)<<0,0,0,1;
return P;
}
void omniTrans(double x,double y, double z,double& phi,double& theta){
double r=sqrt(x*x+y*y+z*z);
theta=atan2(y,x);
phi=acos(z/r);
};
void omniTrans(double x,double y, double z,double& phi_pix,double& theta_pix,int height){
double r=sqrt(x*x+y*y+z*z);
double theta=atan2(y,x);
double phi=acos(z/r);
int width=height*2;
theta_pix=(-theta+M_PI)*width/(M_PI*2);
phi_pix=phi/M_PI*height;
};
void rev_omniTrans(double x2d,double y2d,int width,int height,Vector3d& ret){
double theta=-(x2d*(M_PI*2)/width-M_PI);
double phi=y2d/height*M_PI;
ret<<sin(phi)*cos(theta),sin(phi)*sin(theta),cos(phi);
}
bool makeFolder(string folderPath){
struct stat info;
if (info.st_mode & S_IFDIR) {
cout<<"succeeded."<<endl;
return true;
} else {
cout<<"failed"<<endl;
return false;
}
}
Vector3d cubic_spline(Vector3d& p0,Vector3d& p1,Vector3d& p2,Vector3d& p3,double t0,double t1,double t2,double t3,double t){
Vector3d a1=(t1-t)/(t1-t0)*p0+(t-t0)/(t1-t0)*p1;
Vector3d a2=(t2-t)/(t2-t1)*p1+(t-t1)/(t2-t1)*p2;
Vector3d a3=(t3-t)/(t3-t2)*p2+(t-t2)/(t3-t2)*p3;
Vector3d b1=(t2-t)/(t2-t0)*a1+(t-t0)/(t2-t0)*a2;
Vector3d b2=(t3-t)/(t3-t1)*a2+(t-t1)/(t3-t1)*a3;
return (t2-t)/(t2-t1)*b1+(t-t1)/(t2-t1)*b2;
};
Vector3d cubic_spline(Vector3d& p0,Vector3d& p1,Vector3d& p2,Vector3d& p3,double t){return cubic_spline(p0,p1,p2,p3,0,1/3.0,2/3.0,1,t);}
double get2Line_Distance(Vector3d& p1,Vector3d& v1,Vector3d& p2,Vector3d& v2){
Vector3d prod=v1.cross(v2);
double prod_d=prod.norm();
Vector3d p1p2=p2-p1;
if(prod_d==0){
return v1.cross(p1p2).norm()/v1.norm();
}else{
return abs(prod.dot(p1p2)/prod_d);
}
}
//
double get2Line_Distance(Vector3d& p1,Vector3d& v1,Vector3d& p2,Vector3d& v2,Vector3d& r1,Vector3d& r2){
Vector3d nv1=v1.normalized();
Vector3d nv2=v2.normalized();
Vector3d p1p2=p1-p2;
double d=1-nv1.dot(nv2)*nv1.dot(nv2);
double alpha=(nv1.dot(nv2)*(nv2.dot(p1p2))-nv1.dot(p1p2))/d;
double beta=(-nv1.dot(nv2)*(nv1.dot(p1p2))+nv2.dot(p1p2))/d;
r1=p1+alpha*nv1;
r2=p2+beta*nv2;
return (r2-r1).norm();
}
double get_point2lineDistance(Vector3d& p1,Vector3d& v1,Vector3d& p2){
return (p2-p1).cross(v1).norm()/v1.norm();
}
string getTimeStamp() {
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, "%y%m%d_%H%M%S", timeinfo);
string ts(buffer);
return ts;
} | 26.850467 | 182 | 0.611556 | [
"3d"
] |
0d36b99d73cf317dec3dba6adbf6bf2fc5ab72ca | 1,425 | cpp | C++ | src/flexcl_info.cpp | grisu48/FlexCL | abaf126ab362628820fd537b5bdf46fe476f759e | [
"MIT"
] | null | null | null | src/flexcl_info.cpp | grisu48/FlexCL | abaf126ab362628820fd537b5bdf46fe476f759e | [
"MIT"
] | null | null | null | src/flexcl_info.cpp | grisu48/FlexCL | abaf126ab362628820fd537b5bdf46fe476f759e | [
"MIT"
] | null | null | null |
/* =============================================================================
*
* Title:
* Author:
* License:
* Description:
*
*
* =============================================================================
*/
#include <iostream>
#include "FlexCL.hpp"
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif
using namespace std;
using namespace flexCL;
int main(int argc, char** argv) {
cout << "FlexCL info program | 2014, Felix Niederwanger" << endl << endl;
cout << " FlexCL Version " << OpenCL::VERSION() << endl;
cout << " FlexCL Build " << OpenCL::BUILD() << endl;
cout.flush();
OpenCL opencl;
/* Query platforms */
{
unsigned int platform_count = opencl.plattform_count();
cout << "Available platforms on this computer: " << platform_count << endl;
vector<PlatformInfo> platforms = opencl.get_platforms();
int i = 1;
for(vector<PlatformInfo>::iterator it=platforms.begin(); it!=platforms.end(); it++) {
PlatformInfo platform = *it;
cout << " " << i++ << ":\t" << platform.name() << endl;
cout << " " << platform.vendor() << endl;
cout << " Profile : " << platform.profile() << endl;
cout << " Extensions : " << platform.extensions() << endl;
cout << " OpenCL Version : " << platform.version() << endl;
cout << endl;
}
}
return EXIT_SUCCESS;
}
| 25.909091 | 87 | 0.502456 | [
"vector"
] |
0d3aeb4f1aa7b3c57cf4bf4de070d6f27f872e66 | 4,583 | cpp | C++ | tests/demo/src/cpu_multithreading_get_partitions.cpp | wuxun-zhang/mkl-dnn | 00a239ad2c932b967234ffb528069800ffcc0334 | [
"Apache-2.0"
] | null | null | null | tests/demo/src/cpu_multithreading_get_partitions.cpp | wuxun-zhang/mkl-dnn | 00a239ad2c932b967234ffb528069800ffcc0334 | [
"Apache-2.0"
] | null | null | null | tests/demo/src/cpu_multithreading_get_partitions.cpp | wuxun-zhang/mkl-dnn | 00a239ad2c932b967234ffb528069800ffcc0334 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2021 Intel Corporation
*
* 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.
*******************************************************************************/
/// @example cpu_multithreading_get_partitions.cpp
/// @copybrief cpu_multithreading_get_partitions_cpp
/// Annotated version: @ref cpu_multithreading_get_partitions_cpp
/// @page cpu_multithreading_get_partitions_cpp CPU example for multithread matmul+relu pattern
///
/// > Example code: @ref cpu_multithreading_get_partitions.cpp
#include <assert.h>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
#include <unordered_map>
#include "oneapi/dnnl/dnnl_graph.hpp"
#include "common/execution_context.hpp"
#include "common/helpers_any_layout.hpp"
#include "common/utils.hpp"
#define assertm(exp, msg) assert(((void)msg, exp))
using namespace dnnl::graph;
using data_type = logical_tensor::data_type;
using layout_type = logical_tensor::layout_type;
// digraph G {
// Wildcard -> MatMul;
// MatMul -> ReLU;
// }
// Test matmul relu different shape compile and execute
int main(int argc, char **argv) {
std::cout << "========Example: MatMul+ReLU========\n";
engine::kind engine_kind = parse_engine_kind(argc, argv);
if (engine_kind == engine::kind::gpu) {
std::cout << "Don't support gpu now\n";
return -1;
}
// Step 2: Construct several graphs
size_t num_graphs = 20; // this is also the thread num
auto thread_func = [&](size_t tid) {
std::cout << "Start thread " << tid << std::endl;
graph g(engine_kind);
std::vector<int64_t> input0_dims {1, 64};
std::vector<int64_t> input1_dims {64, 1};
std::vector<int64_t> dst_dims {1, 1};
logical_tensor matmul_input0_desc {
7 * tid, data_type::f32, input0_dims, layout_type::strided};
logical_tensor matmul_input1_desc {
7 * tid + 1, data_type::f32, input1_dims, layout_type::strided};
logical_tensor matmul_dst_desc {
7 * tid + 2, data_type::f32, dst_dims, layout_type::strided};
op wildcard {7 * tid + 3, op::kind::Wildcard, {},
{matmul_input0_desc, matmul_input1_desc}, "wildcard"};
op matmul {7 * tid + 4, op::kind::MatMul,
{matmul_input0_desc, matmul_input1_desc}, {matmul_dst_desc},
"matmul"};
logical_tensor relu_dst_desc {
7 * tid + 5, data_type::f32, dst_dims, layout_type::strided};
op relu {7 * tid + 6, op::kind::ReLU, {matmul_dst_desc},
{relu_dst_desc}, "relu"};
/// Add OP
std::cout << "thread " << tid
<< ": Add op to graph--------------------------------";
g.add_op(wildcard);
g.add_op(matmul);
g.add_op(relu);
// Step 3: Filter partitions
/// Graph will be filtered into 1 partitions: `matmul+relu`
/// `export DNNL_GRAPH_DUMP=1` can save internal graphs before/after graph fusion into dot files
std::cout << "thread " << tid
<< ": Filter partitions------------------------------";
auto partitions = g.get_partitions();
std::cout << "thread " << tid
<< ": Number of returned partitions: " << partitions.size()
<< "\n";
for (size_t i = 0; i < partitions.size(); ++i) {
std::cout << "Partition[" << partitions[i].get_id()
<< "]'s supporting status: "
<< (partitions[i].is_supported() ? "true" : "false")
<< "\n";
}
};
std::vector<std::thread> workers;
for (size_t t_num = 0; t_num < num_graphs; t_num++) {
workers.emplace_back(thread_func, t_num);
}
for (size_t t_num = 0; t_num < num_graphs; t_num++) {
workers[t_num].join();
}
std::cout << "============Run Example Successfully===========\n";
return 0;
}
| 35.253846 | 104 | 0.586515 | [
"shape",
"vector"
] |
0d5d4d1b1274784bb37399f2c609f9fbc1ecb6c1 | 7,271 | cpp | C++ | ToneArmEngine/RenderableModel.cpp | Mertank/ToneArm | 40c62b0de89ac506bea6674e43578bf4e2631f93 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | ToneArmEngine/RenderableModel.cpp | Mertank/ToneArm | 40c62b0de89ac506bea6674e43578bf4e2631f93 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | ToneArmEngine/RenderableModel.cpp | Mertank/ToneArm | 40c62b0de89ac506bea6674e43578bf4e2631f93 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | /*
========================
Copyright (c) 2014 Vinyl Games Studio
RenderableModel
Created by: Karl Merten
Created on: 06/05/2014
========================
*/
#include "RenderableModel.h"
#include "OpenGLMesh.h"
#include "CachedResourceLoader.h"
#include "BinaryFileResource.h"
#include "Log.h"
#include "MeshStructs.h"
#include "RenderMessages.h"
#include "RenderableMesh.h"
#include "Animator.h"
#include "RenderModule.h"
#include "Animation.h"
namespace vgs {
IMPLEMENT_RTTI( RenderableModel, Renderable )
/*
========
RenderableModel::RenderableModel
RenderableModel default constructor
========
*/
RenderableModel::RenderableModel( void ) :
m_meshCount( 0 ),
m_meshes( NULL ),
m_animator( NULL ),
m_matchBoneHash( 0 )
{}
/*
========
RenderableModel::RenderableModel
RenderableModel destructor
========
*/
RenderableModel::~RenderableModel( void ) {
for ( unsigned int i = 0; i < m_meshCount; ++i ) {
delete m_meshes[i];
}
delete[] m_meshes;
delete m_animator;
}
/*
========
OpenGLModel::AttachMesh
Attachs a mesh to the model
========
*/
void RenderableModel::AttachMesh( RenderableMesh* mesh ) {
m_meshes[GetNextMeshIndex()] = mesh;
glm::vec3 minVert;
glm::vec3 maxVert;
for ( unsigned int i = 0; i < m_meshCount; ++i ) {
if ( m_meshes[i] == NULL ) { continue; }
glm::vec3 boxMin = m_meshes[i]->GetBoxOffset() - ( ( ( BoxShape& )m_meshes[i]->GetBoundingBox() ).GetBoundingDimensions() * 0.5f );
glm::vec3 boxMax = m_meshes[i]->GetBoxOffset() + ( ( ( BoxShape& )m_meshes[i]->GetBoundingBox() ).GetBoundingDimensions() * 0.5f );
if ( boxMin.x < minVert.x ) {
minVert.x = boxMin.x;
} else if ( boxMax.x < minVert.x ) {
minVert.x = boxMax.x;
}
if ( boxMin.x > maxVert.x ) {
maxVert.x = boxMin.x;
} else if ( boxMax.x > maxVert.x ) {
maxVert.x = boxMax.x;
}
if ( boxMin.y < minVert.y ) {
minVert.y = boxMin.y;
} else if ( boxMax.y < minVert.y ) {
minVert.y = boxMax.y;
}
if ( boxMin.y > maxVert.y ) {
maxVert.y = boxMin.y;
} else if ( boxMax.y > maxVert.y ) {
maxVert.y = boxMax.y;
}
if ( boxMin.z < minVert.z ) {
minVert.z = boxMin.z;
} else if ( boxMax.z < minVert.z ) {
minVert.z = boxMax.z;
}
if ( boxMin.z > maxVert.z ) {
maxVert.z = boxMin.z;
} else if ( boxMax.z > maxVert.z ) {
maxVert.z = boxMax.z;
}
}
m_boxOffset = ( minVert + maxVert ) * 0.5f;
m_boundingBox.SetDimensions( maxVert - minVert );
}
/*
========
OpenGLModel::AttachTexture
Attachs a texture to the model
========
*/
void RenderableModel::AttachTexture( Texture* tex, unsigned int meshIndex ) {
if ( m_meshes[meshIndex] ) {
m_meshes[meshIndex]->AttachTexture( tex );
if ( tex->HasAlphaChannel() ) {
m_attachedPass = PassType::TRANSPARENCY;
}
} else {
delete tex;
}
}
/*
========
OpenGLModel::IsLit
Sets if the model is lit.
Passes value to all meshes.
========
*/
void RenderableModel::IsLit( bool lit ) {
Renderable::IsLit( lit );
for ( unsigned int i = 0; i < m_meshCount; ++i ) {
if (m_meshes[i] == nullptr)
{
continue;
}
m_meshes[i]->IsLit( lit );
}
}
/*
========
OpenGLModel::SetDrawingOutlineOnly
Sets if the model is only drawing its outline.
Passes value to all meshes.
========
*/
void RenderableModel::SetDrawingOutlineOnly( bool outline ) {
Renderable::SetDrawingOutlineOnly( outline );
for ( unsigned int i = 0; i < m_meshCount; ++i ) {
if (m_meshes[i] == nullptr)
{
continue;
}
m_meshes[i]->SetDrawingOutlineOnly( outline );
}
}
/*
========
OpenGLModel::SetDiffuseColor
Sets the diffuse color
========
*/
void RenderableModel::SetDiffuseColor( const glm::vec3& diffColor ) {
for ( unsigned int i = 0; i < m_meshCount; ++i ) {
if (m_meshes[i] == nullptr)
{
continue;
}
m_meshes[i]->SetDiffuseColor( diffColor );
}
}
/*
========
RenderableModel::SetOpacity
Sets the opacity.
========
*/
void RenderableModel::SetOpacity( float alpha ) {
for ( unsigned int i = 0; i < m_meshCount; ++i ) {
if ( m_meshes[i] == nullptr ) {
continue;
}
m_meshes[i]->SetOpacity( alpha );
}
if ( GetOpacity() < ( 1.0f - FLOAT_EPSILON ) ) {
if ( m_attachedPass & PassType::DIFFUSE ) {
m_attachedPass = ( PassType::Value )( m_attachedPass & ~PassType::DIFFUSE );
m_attachedPass = ( PassType::Value )( m_attachedPass | PassType::TRANSPARENCY );
}
} else {
if ( m_attachedPass & PassType::TRANSPARENCY ) {
m_attachedPass = ( PassType::Value )( m_attachedPass & ~PassType::TRANSPARENCY );
m_attachedPass = ( PassType::Value )( m_attachedPass | PassType::DIFFUSE );
}
}
}
/*
========
RenderableModel::GetOpacity
Gets the opacity.
========
*/
float RenderableModel::GetOpacity( void ) {
float opacity = 1.0f;
for ( unsigned int i = 0; i < m_meshCount; ++i ) {
if ( m_meshes[i] ) {
opacity = std::min( opacity, m_meshes[i]->GetOpacity() );
}
}
return opacity;
}
/*
========
RenderableModel::GetMesh
Returns the mesh at index
========
*/
RenderableMesh* RenderableModel::GetMesh( unsigned int index ) {
if ( m_meshes ) {
return m_meshes[index];
} else {
return NULL;
}
}
/*
========
RenderableModel::UpdateTransform
Update the transform
========
*/
void RenderableModel::UpdateTransform( TransformMessage* msg ) {
UpdateTransform( msg->rotationMatrix, msg->position );
}
/*
========
RenderableModel::UpdateTransform
Update the transform
========
*/
void RenderableModel::UpdateTransform( const glm::mat3& rot, const glm::vec3& loc ) {
Renderable::UpdateTransform( rot, loc );
UpdatedCompositeMatrix();
}
/*
========
RenderableModel::AddAnimation
Adds a animation.
========
*/
void RenderableModel::AddAnimation( Animation* anim ) {
if ( !m_animator ) {
m_animator = m_renderer->CreateAnimator( anim->GetJointCount() );
}
m_animator->AddAvailableAnimation( anim );
}
/*
========
RenderableModel::SetBindMatricies
Adds a animation.
========
*/
void RenderableModel::SetBindMatricies( glm::mat4* matricies, unsigned int count ) {
if ( !m_animator ) {
m_animator = m_renderer->CreateAnimator( count );
}
m_animator->SetBindMatricies( matricies );
}
/*
========
RenderableModel::Update
Updates the animator.
========
*/
void RenderableModel::Update( float dt ) {
if ( m_animator ) {
m_animator->UpdateAnimation( dt );
}
if ( m_matchBoneHash > 0 ) {
if ( m_parent ) {
Animator* parentAnimator = ( ( RenderableModel* )m_parent )->GetAnimator();
if ( parentAnimator ) {
const SkeletonJoint* boneInfo = parentAnimator->GetJointNamed( m_matchBoneHash );
if ( boneInfo ) {
UpdateTransform( glm::toMat3( boneInfo->orientation ), boneInfo->position );
} else {
UpdateTransform( glm::mat3( 1.0 ), glm::vec3( 0.0 ) );
}
}
}
}
Renderable::Update( dt );
}
void RenderableModel::UpdatedCompositeMatrix( void ) {
if ( DidTransformChange() ) {
GetCompositeMatrix();
float angle = glm::degrees( atan2(m_compositeMatrix[0][2], m_compositeMatrix[0][0] ) );
m_boundingBox.SetRotation( glm::vec3( 0.0f, angle, 0.0f ) );
m_boundingBox.SetPosition( glm::vec3( m_compositeMatrix[3] ) + m_boxOffset );
}
}
unsigned int RenderableModel::GetNextMeshIndex( void ) {
unsigned int nextMesh = 0;
while ( nextMesh < m_meshCount ) {
if ( m_meshes[nextMesh] == NULL ) { break; }
++nextMesh;
}
return nextMesh;
}
} | 21.511834 | 133 | 0.642965 | [
"mesh",
"model",
"transform"
] |
0d6c7c36549763f8e9b8d41873d799b1c9b5e51b | 3,715 | cpp | C++ | src/main/cpp/JavaStringArray.cpp | emesz761/JniHelpers | ebe62e780156b65c4b614323836b01929178d6e7 | [
"Apache-2.0"
] | 565 | 2015-01-05T12:12:24.000Z | 2022-03-30T07:55:03.000Z | src/main/cpp/JavaStringArray.cpp | emesz761/JniHelpers | ebe62e780156b65c4b614323836b01929178d6e7 | [
"Apache-2.0"
] | 9 | 2015-02-23T10:01:45.000Z | 2021-02-04T10:43:14.000Z | src/main/cpp/JavaStringArray.cpp | emesz761/JniHelpers | ebe62e780156b65c4b614323836b01929178d6e7 | [
"Apache-2.0"
] | 120 | 2015-02-01T14:08:16.000Z | 2022-03-19T10:09:16.000Z | /*
* Copyright (c) 2014 Spotify AB
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "JavaStringArray.h"
#include "JavaExceptionUtils.h"
#include "JavaString.h"
#include <stdlib.h>
namespace spotify {
namespace jni {
JavaStringArray::JavaStringArray() : _data(NULL), _num_elements(0) {}
JavaStringArray::JavaStringArray(JavaString **data, const size_t numElements, bool copyData) :
_data(NULL), _num_elements(0) {
// In the rare (but possible) event that this constructor is called with
// NULL but non-zero length data, correct the elements count so as to avoid
// segfaults later on.
if (data == NULL && numElements > 0) {
_num_elements = 0;
} else if (data != NULL && numElements > 0) {
set(data, numElements, copyData);
}
}
JavaStringArray::JavaStringArray(JNIEnv *env, jobjectArray data) :
_data(NULL), _num_elements(0) {
set(env, data);
}
JavaStringArray::~JavaStringArray() {
freeData();
}
JavaString **JavaStringArray::leak() {
JavaString **result = _data;
_data = NULL;
_num_elements = 0;
return result;
}
JniLocalRef<jobjectArray> JavaStringArray::toJavaStringArray(JNIEnv *env) const {
jclass stringClass = env->FindClass(kTypeString);
JniLocalRef<jobjectArray> result = env->NewObjectArray((jsize)_num_elements, stringClass, 0);
JavaExceptionUtils::checkException(env);
if (_num_elements == 0 || _data == NULL) {
return result;
}
for(size_t i = 0; i < _num_elements; i++) {
// This might be a potential problem as it's not entirely
// certain who owns these.
env->SetObjectArrayElement(result.get(), i, _data[i]->toJavaString(env));
}
return result.leak();
}
void JavaStringArray::set(JavaString **data, const size_t numElements, bool copyData) {
if (data == NULL && numElements > 0) {
JNIEnv *env = JavaThreadUtils::getEnvForCurrentThread();
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalArgumentException,
"Cannot set data with non-zero size and NULL object");
return;
}
// Make sure not to leak the old data if it exists
freeData();
if (copyData) {
_data = (JavaString **)malloc(numElements * sizeof(JavaString *));
for (size_t i = 0; i < numElements; i++) {
_data[i] = data[i];
}
} else {
_data = data;
}
_num_elements = numElements;
}
void JavaStringArray::set(JNIEnv *env, jobjectArray data) {
freeData();
if (data != NULL) {
_num_elements = env->GetArrayLength(data);
if (_num_elements == 0) {
_data = NULL;
} else {
_data = (JavaString **)malloc(_num_elements * sizeof(JavaString *));
for (size_t i = 0; i < _num_elements; i++) {
_data[i] = new JavaString(env, (jstring) env->GetObjectArrayElement(data, i));
}
}
}
}
void JavaStringArray::freeData() {
if (_data != NULL) {
for (size_t i = 0; i < size(); i++) {
free(_data[i]);
}
free(_data);
_data = NULL;
}
}
} // namespace jni
} // namespace spotify
| 29.72 | 95 | 0.684253 | [
"object"
] |
0d7fe0d8b37ce1287021960354d7052ee2d2da78 | 1,954 | cpp | C++ | CSES/Advanced Techniques/Meet in the Middle.cpp | Harry-kp/Cp | 94e687a3a5256913467f50d8f757b12640529513 | [
"MIT"
] | 2 | 2020-11-19T19:21:24.000Z | 2021-04-22T10:53:16.000Z | CSES/Advanced Techniques/Meet in the Middle.cpp | Harry-kp/Cp | 94e687a3a5256913467f50d8f757b12640529513 | [
"MIT"
] | null | null | null | CSES/Advanced Techniques/Meet in the Middle.cpp | Harry-kp/Cp | 94e687a3a5256913467f50d8f757b12640529513 | [
"MIT"
] | 1 | 2021-12-02T06:03:17.000Z | 2021-12-02T06:03:17.000Z | #include <bits/stdc++.h>
using namespace std;
#define fastio \
ios_base::sync_with_stdio(0); \
cin.tie(0)
#define MP make_pair
#define EB emplace_back
#define MOD 1000000007
#define int long long int
#define S second
#define F first
#define debug1 cout << "debug1" << '\n'
#define debug2 cout << "debug2" << '\n'
#define debug3 cout << "debug3" << '\n'
// int dr[] = {0,-1,0,1,-1,-1,1,1};
// int dc[] = {-1,0,1,0,-1,1,1,-1};
// Maths Utils
int binExp(int a, int b, int m)
{
int r = 1;
while (b)
{
if (b % 2 == 1)
r = (r * a) % m;
a = (a * a) % m;
b = b / 2;
}
return r;
}
vector<int> subset(int A[], int n)
{
int j, k, sum1;
vector<int> ans;
for (int i = 0; i < (1 << n); i++)
{
sum1 = 0;
j = i;
k = 0;
while (j)
{
if (j & 1)
sum1 += A[k];
k++;
j >>= 1;
}
ans.EB(sum1);
}
return ans;
}
// Using hashing for frequency count is leading to TLE.Don't know why
// Hence I used lower_bound and upper_bound
int32_t main()
{
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
fastio;
int t = 1;
// cin >> t;
while (t--)
{
int n, n1, n2, x, j, k;
cin >> n >> x;
n1 = n >> 1;
n2 = n - n1;
int A[n1], B[n2];
vector<int> l1(1 << n1), l2(1 << n2);
for (int i = 0; i < n; i++)
{
if (i < n1)
cin >> A[i];
else
cin >> B[i - n1];
}
l1 = subset(A, n1);
l2 = subset(B, n2);
sort(l1.begin(), l1.end());
sort(l2.begin(), l2.end());
int cnt = 0;
for (auto u : l1)
{
cnt += (upper_bound(l2.begin(), l2.end(), x - u) - lower_bound(l2.begin(), l2.end(), x - u));
}
cout << cnt << '\n';
}
}
| 20.568421 | 105 | 0.420164 | [
"vector"
] |
0d80d3d72e0f18bd8d3e5c8c67c42e18cfded6a9 | 57,244 | cxx | C++ | nff_search_node.cxx | miquelramirez/t1 | 6696db1d1e12f93811dc17b8d921a19a75b549b5 | [
"Apache-2.0"
] | null | null | null | nff_search_node.cxx | miquelramirez/t1 | 6696db1d1e12f93811dc17b8d921a19a75b549b5 | [
"Apache-2.0"
] | null | null | null | nff_search_node.cxx | miquelramirez/t1 | 6696db1d1e12f93811dc17b8d921a19a75b549b5 | [
"Apache-2.0"
] | null | null | null | /*
Alexandre Albore, Miguel Ramirez, Hector Geffner
T1 conformant planner
Copyright (C) UPF 2010
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "nff_search_node.hxx"
#include <algorithm>
#include "nff.hxx"
#include "hash_table.hxx"
#include "nff_planner_stats.hxx"
#include "global_options.hxx"
#include "nff_options.hxx"
#include "nff_mutexes.hxx"
#include "nff_dijkstra.hxx"
#define DEBUG_SAT 0
namespace NFF
{
PDDL::Task& SearchNode::sm_task = PDDL::Task::instance();
SearchNode::SearchNode()
: b(NULL), gn(0), hn(0), hS(0), hX(0), tb(0), father(NULL), op(0), timestep(0), theory_step(NULL),
num_dead_models(0)
{
m_hS_HA_set = new PDDL::Fluent_Set( sm_task.prototype_ops().size() + 1 );
m_hX_HA_set = new PDDL::Fluent_Set( sm_task.prototype_ops().size() + 1 );
}
SearchNode::~SearchNode()
{
if ( b )
delete b;
if ( theory_step )
delete theory_step;
// if ( models )
// delete models;
}
unsigned SearchNode::size()
{
unsigned numBytes = sizeof(b);
numBytes += sizeof(gn);
numBytes += sizeof(hn);
numBytes += sizeof(hS);
numBytes += sizeof(hX);
numBytes += sizeof(tb);
numBytes += sizeof(queue);
numBytes += sizeof(fn);
numBytes += sizeof(father);
numBytes += sizeof(op);
numBytes += sizeof(timestep);
// numBytes += sizeof(models);
numBytes += sizeof(theory_step);
numBytes += sizeof(potentially_known);
// numBytes += sizeof(dead_model);
numBytes += sizeof(num_dead_models);
numBytes += sizeof(m_hS_HA);
numBytes += sizeof(m_hS_HA_set);
numBytes += sizeof(m_hX_HA);
numBytes += sizeof(m_hX_HA_set);
numBytes += sizeof( sm_task );
numBytes += sizeof( m_hash_key );
numBytes += potentially_known.size()*sizeof(bool);
// numBytes += dead_model.size()*sizeof(bool);
numBytes += b->size();
if ( theory_step != NULL )
numBytes += theory_step->size();
numBytes += m_hS_HA.size()*sizeof(unsigned);
numBytes += m_hX_HA.size()*sizeof(unsigned);
numBytes += m_hS_HA_set->bits().npacks()*sizeof(unsigned);
numBytes += m_hX_HA_set->bits().npacks()*sizeof(unsigned);
// for ( unsigned k = 0; k < models.size(); k++ )
// {
// numBytes += sizeof(models[k]);
// numBytes += models[k].size()*sizeof(unsigned);
// }
return numBytes;
}
SearchNode* SearchNode::root()
{
SearchNode* n = new SearchNode;
n->b = Belief::make_initial_belief();
n->theory_step = new Theory_Fragment();
n->potentially_known.resize( sm_task.fluent_count() );
Planner_Stats& stats = Planner_Stats::instance();
if ( !stats.is_width_1() )
n->make_root_clauses();
#ifdef DEBUG
MiniSAT solver(n);
if ( !stats.is_width_1() )
assert( solver.solve() );
#endif
n->gn = 0;
n->father = NULL;
n->op = 0;
//n->hS = n->hX = n->hn = 0;
n->timestep = 0;
return n;
}
/** Calculates the heuristic value *
* returns INFTY if the lit is not reachable in all the models */
unsigned SearchNode::evaluate( Dijkstra* heuristic, std::vector< std::vector<int> >&models )
{
NFF_Options& opt = NFF_Options::instance();
Planner_Stats& stats = Planner_Stats::instance();
stats.notify_heuristic_computation();
heuristic->pre_compute(*this, models);
//AA: For BFS, we can only compute one of the 2 heuristics
if ( opt.search_strategy() != "bfs" || opt.ehc_heuristic() != OPT_EHC_USES_HX )
{
m_hS_HA.assign( heuristic->hS_helpful().begin(), heuristic->hS_helpful().end() );
for ( unsigned k = 0; k < m_hS_HA.size(); k++ )
m_hS_HA_set->set( m_hS_HA[k] );
hS = heuristic->hS_value();
}
if ( opt.search_strategy() != "bfs" || opt.ehc_heuristic() != OPT_EHC_USES_HS )
{
m_hX_HA.assign( heuristic->hX_helpful().begin(), heuristic->hX_helpful().end() );
for ( unsigned k = 0; k < m_hX_HA.size(); k++ )
m_hX_HA_set->set( m_hX_HA[k] );
hX = heuristic->hX_value();
}
tb = heuristic->h_value(heuristic->goal_state());//tie_breaking();
//AA: once used for diameter heuristic
// heuristics = heuristic;
return heuristic->hS_value();
}
/** Calculates the heuristic value *
* returns INFTY if the lit is not reachable in all the models */
// unsigned SearchNode::evaluate( Dijkstra* heuristic )
// {
// Planner_Stats& stats = Planner_Stats::instance();
// stats.notify_heuristic_computation();
// heuristic->pre_compute(*this);
// m_hS_HA.assign( heuristic->hS_helpful().begin(), heuristic->hS_helpful().end() );
// for ( unsigned k = 0; k < m_hS_HA.size(); k++ )
// m_hS_HA_set->set( m_hS_HA[k] );
// hS = heuristic->hS_value();
// m_hX_HA.assign( heuristic->hX_helpful().begin(), heuristic->hX_helpful().end() );
// for ( unsigned k = 0; k < m_hX_HA.size(); k++ )
// m_hX_HA_set->set( m_hX_HA[k] );
// hX = heuristic->hX_value();
// tb = heuristic->h_value(heuristic->goal_state());//tie_breaking();
// //AA: once used for diameter heuristic
// // heuristics = heuristic;
// return heuristic->hS_value();
// }
// bool SearchNode::condition_holds_in_sample( Atom_Vec& cond )
// {
// for ( unsigned j = 0; j < models.size(); j++ )
// {
// bool holds = true;
// for ( unsigned k = 0; k < cond.size(); k++ )
// if ( models[j][ cond[k] ] < 0 )
// {
// holds = false;
// break;
// }
// if ( holds ) return true;
// }
// return false;
// }
// void SearchNode::update_models( std::vector< PDDL::Operator* >& op_effs )
// {
// // assert( father->models.size() > 0 );
// models = father->models;
// #ifdef DEBUG
// std::vector<bool> changed(models.size());
// #endif
// for ( unsigned i = 0; i < op_effs.size(); i++ )
// {
// // std::cout << "Applying operator to models: ";
// // sm_task.print_operator_full_notab( op_effs[i], std::cout );
// for ( unsigned j = 0; j < father->models.size(); j++ )
// {
// bool applicable = true;
// for ( unsigned k = 0; k < op_effs[i]->prec_vec().size(); k++ )
// if ( father->models[j][ op_effs[i]->prec_vec()[k] ] < 0 )
// {
// applicable = false;
// break;
// }
// if ( !applicable ) continue;
// #ifdef DEBUG
// changed[j] = true;
// // sm_task.print_operator_full_notab( op_effs[i], std::cout );
// // std::cout << std::endl;
// #endif
// for ( unsigned k = 0; k < op_effs[i]->add_vec().size(); k++ )
// models[j][ op_effs[i]->add_vec()[k] ] = op_effs[i]->add_vec()[k] ;
// for ( unsigned k = 0; k < op_effs[i]->del_vec().size(); k++ )
// models[j][ op_effs[i]->del_vec()[k] ] = -op_effs[i]->del_vec()[k];
// }
// }
// #ifdef DEBUG
// std::cout << "MODELS changed by the action:" << std::endl;
// for ( unsigned j = 0; j < models.size(); j++ )
// if ( changed[j] )
// {
// std::cout << "s_" << j << ": ";
// for ( unsigned l = 1; l < models[j].size(); l++ )
// {
// std::cout << models[j][l] << " " << (models[j][l] > 0 ? " " : " -");
// sm_task.print_fluent( models[j][l] > 0 ? models[j][l] : (unsigned)abs(models[j][l]) );
// std::cout << ", ";
// }
// std::cout << std::endl;
// }
// #endif
// }
void SearchNode::update_single_model ( std::vector< PDDL::Operator* >& op_effs,
std::vector< int >& lmodel )
{
std::vector<int> father_model = lmodel;
for ( unsigned i = 0; i < op_effs.size(); i++ )
{
// std::cout << "Applying operator to models: ";
// sm_task.print_operator_full_notab( op_effs[i], std::cout );
bool applicable = true;
for ( unsigned k = 0; k < op_effs[i]->prec_vec().size(); k++ )
if ( father_model[ op_effs[i]->prec_vec()[k] ] < 0 )
{
applicable = false;
break;
}
if ( !applicable ) continue;
for ( unsigned k = 0; k < op_effs[i]->add_vec().size(); k++ )
lmodel[ op_effs[i]->add_vec()[k] ] = op_effs[i]->add_vec()[k] ;
for ( unsigned k = 0; k < op_effs[i]->del_vec().size(); k++ )
lmodel[ op_effs[i]->del_vec()[k] ] = -op_effs[i]->del_vec()[k];
}
}
void SearchNode::update_models( std::vector< PDDL::Operator* >& op_effs,
std::vector< std::vector< int > >& lmodels)
{
/*
#ifdef DEBUG
std::vector<bool> changed(lmodels.size());
#endif
*/
std::vector< std::vector< int > > father_models = lmodels;
for ( unsigned i = 0; i < op_effs.size(); i++ )
{
// std::cout << "Applying operator to models: ";
// sm_task.print_operator_full_notab( op_effs[i], std::cout );
for ( unsigned j = 0; j < father_models.size(); j++ )
{
bool applicable = true;
for ( unsigned k = 0; k < op_effs[i]->prec_vec().size(); k++ )
if ( father_models[j][ op_effs[i]->prec_vec()[k] ] < 0 )
{
applicable = false;
break;
}
if ( !applicable ) continue;
/*
#ifdef DEBUG
changed[j] = true;
// sm_task.print_operator_full_notab( op_effs[i], std::cout );
// std::cout << std::endl;
#endif
*/
for ( unsigned k = 0; k < op_effs[i]->add_vec().size(); k++ )
lmodels[j][ op_effs[i]->add_vec()[k] ] = op_effs[i]->add_vec()[k] ;
for ( unsigned k = 0; k < op_effs[i]->del_vec().size(); k++ )
lmodels[j][ op_effs[i]->del_vec()[k] ] = -op_effs[i]->del_vec()[k];
}
}
/*
#ifdef DEBUG
std::cout << "MODELS changed by the action:" << std::endl;
for ( unsigned j = 0; j < lmodels.size(); j++ )
if ( changed[j] )
{
std::cout << "s_" << j << ": ";
for ( unsigned l = 1; l < lmodels[j].size(); l++ )
{
std::cout << lmodels[j][l] << " " << (lmodels[j][l] > 0 ? " " : " -");
sm_task.print_fluent( lmodels[j][l] > 0 ? lmodels[j][l] : (unsigned)abs(lmodels[j][l]) );
std::cout << ", ";
}
std::cout << std::endl;
}
#endif
*/
}
void SearchNode::action_compilation_rule( std::vector< PDDL::Operator* >& effs )
{
std::vector<unsigned> lits_becoming_known;
/*
#ifdef DEBUG
std::cout << "Action Compilation through op: ";
sm_task.print_operator( effs[0], std::cout );
std::cout << std::endl;
#endif
*/
for ( unsigned k = 0; k < effs.size(); k++ )
{
Atom_Vec eff_cond;
for ( unsigned i = 0; i < effs[k]->prec_vec().size(); i++ )
if ( !effs[k]->hard_preconds().isset( effs[k]->prec_vec()[i] ) )
eff_cond.push_back( effs[k]->prec_vec()[i] );
if ( effs[k]->del_vec().empty() ) continue;
bool can_execute = true;
std::vector<unsigned> unknown;
for ( unsigned i = 0; i < eff_cond.size(); i++ )
{
unsigned pi = eff_cond[i];
if ( !b->known_set().isset(pi) && !b->unknown_set().isset(pi) )
{
can_execute = false;
break;
}
if ( b->unknown_set().isset(pi) )
unknown.push_back(pi);
}
if ( !can_execute || unknown.size() > 1 || unknown.empty() ) continue;
unsigned candidate = unknown[0];
if ( !effs[k]->dels().isset(candidate) ) continue;
/*
#ifdef DEBUG
std::cout << "Found candidate ";
sm_task.print_fluent( candidate, std::cout );
std::cout << std::endl;
#endif
*/
std::vector<unsigned> adding;
for ( unsigned j = 0; j < effs.size(); j++ )
if ( effs[j]->adds().isset(candidate) )
adding.push_back( j );
/*
#ifdef DEBUG
std::cout << "\t" << adding.size() << " rules adding candidate found" << std::endl;
#endif
*/
bool all_rules_comply = true;
for ( unsigned j = 0; j < adding.size(); j++ )
{
if ( adding[j] == k ) continue;
Atom_Vec& dj_cond = effs[adding[j]]->prec_vec();
/*
#ifdef DEBUG
std::cout << "\tChecking deleting rule condition: ";
for ( unsigned i = 0; i < dj_cond.size(); i++ )
{
sm_task.print_fluent( dj_cond[i], std::cout );
std::cout << " ";
}
std::cout << std::endl;
#endif
*/
bool at_least_one_false = false;
for (unsigned i = 0; i < dj_cond.size(); i++ )
{
if ( !b->known_set().isset( dj_cond[i] )
&& !b->unknown_set().isset( dj_cond[i] ) )
{
at_least_one_false = true;
/*
#ifdef DEBUG
std::cout << "\t\tFluent ";
sm_task.print_fluent( dj_cond[i], std::cout );
std::cout << " found in K~L" << std::endl;
#endif
*/
break;
}
}
if ( !at_least_one_false )
{
/*
#ifdef DEBUG
std::cout << "\t\tNo fluent found in K~L!" << std::endl;
#endif
*/
all_rules_comply = false;
break;
}
}
if ( all_rules_comply )
{
/*
#ifdef DEBUG
std::cout << "\tLit is going to be known" << std::endl;
#endif
*/
lits_becoming_known.push_back( candidate );
}
}
for ( unsigned i = 0; i < lits_becoming_known.size(); i++ )
{
unsigned p = lits_becoming_known[i];
unsigned neg_p = sm_task.not_equivalent(p);
b->remove_unknown_lit( p );
if ( neg_p != 0 )
{
b->add_known_lit( neg_p );
b->remove_unknown_lit( neg_p );
}
}
if ( !lits_becoming_known.empty() )
{
b->unknown_vec().clear();
unsigned p = b->unknown_set().first();
while ( p != 0 )
{
b->unknown_vec().push_back(p);
p = b->unknown_set().next(p);
}
}
/*
#ifdef DEBUG
std::cout << "Belief after Action Compilation" << std::endl;
b->print();
#endif
*/
}
void SearchNode::compute_persist_set( Belief& b,
std::vector< PDDL::Operator*>& effs,
PDDL::Fluent_Set& not_affected )
{
for ( unsigned p = 1; p < (unsigned)(sm_task.fluent_count()-1); p++ )
{
if ( not_affected.isset(p) ) continue;
std::vector<unsigned> affecting;
for ( unsigned k = 0; k < effs.size(); k++ )
{
if ( effs[k]->adds().isset(p) )
affecting.push_back(k);
if ( effs[k]->dels().isset(p) )
affecting.push_back(k);
}
if ( affecting.empty() )
not_affected.set(p);
else
{
bool none_executes = true;
for ( unsigned k = 0; k < affecting.size(); k++ )
if ( condition_may_execute( b, effs[ affecting[k] ]->prec_vec() ) )
{
none_executes = false;
break;
}
if ( none_executes )
not_affected.set(p);
}
}
}
void SearchNode::preserve_persisting_lits( Belief& b, Belief& bp,
PDDL::Fluent_Set& persist,
PDDL::Fluent_Set& processed )
{
for ( unsigned k = 0; k < b.known_vec().size(); k++ )
{
unsigned p = b.known_vec()[k];
if ( persist.isset(p) )
{
/*
#ifdef DEBUG
std::cout << "[NOT AFFECTED] ";
std::cout << "Known ";
sm_task.print_fluent(p);
std::cout << " in b -> Known ";
sm_task.print_fluent(p);
std::cout << " in b'" << std::endl;
#endif
*/
bp.add_known_lit(p);
processed.set(p);
}
}
for ( unsigned k = 0; k < b.unknown_vec().size(); k++ )
{
unsigned p = b.unknown_vec()[k];
if ( persist.isset(p) )
{
/*
#ifdef DEBUG
std::cout << "[NOT AFFECTED] ";
std::cout << "Unknown ";
sm_task.print_fluent(p);
std::cout << " in b -> Unknown ";
sm_task.print_fluent(p);
std::cout << " in b'" << std::endl;
#endif
*/ bp.add_unknown_lit(p);
processed.set(p);
}
}
}
void SearchNode::retrieve_effect_conditions( std::vector<PDDL::Operator*>& effs,
std::vector<Atom_Vec>& conds )
{
for ( unsigned k = 0; k < effs.size(); k++ )
{
Atom_Vec eff_cond;
for ( unsigned i = 0; i < effs[k]->prec_vec().size(); i++ )
if ( !effs[k]->hard_preconds().isset( effs[k]->prec_vec()[i] ) )
eff_cond.push_back( effs[k]->prec_vec()[i] );
conds.push_back( eff_cond );
}
}
void SearchNode::check_support_rule( Belief& b,
std::vector<Atom_Vec>& conds,
std::vector<bool>& results )
{
for ( unsigned k = 0; k < conds.size(); k++ )
{
bool support_rule_holds = true;
for ( unsigned i = 0; i < conds[k].size(); i++ )
{
if ( !b.known_set().isset(conds[k][i]) )
{
support_rule_holds = false;
break;
}
}
results[k] = support_rule_holds;
}
}
void SearchNode::check_cancellation_rule( Belief& b,
std::vector<Atom_Vec>& conds,
std::vector<bool>& results )
{
for ( unsigned k = 0; k < conds.size(); k++ )
{
bool cancellation_rule_holds = true;
for ( unsigned i = 0; i < conds[k].size(); i++ )
{
unsigned neg_ci = sm_task.not_equivalent(conds[k][i]);
assert( neg_ci != 0 );
if ( !b.unknown_set().isset( neg_ci ) )
{
cancellation_rule_holds = false;
break;
}
}
results[k] = cancellation_rule_holds;
}
}
bool SearchNode::condition_may_execute( Belief& b,
Atom_Vec& cond )
{
for ( unsigned i = 0; i < cond.size(); i++ )
if ( !b.known_set().isset(cond[i])
&& !b.unknown_set().isset( cond[i] ) )
return false;
return true;
}
void SearchNode::check_action_compilation( Belief& b,
std::vector<Atom_Vec>& conds,
std::vector<PDDL::Operator*>& effs,
std::vector<bool>& result,
std::vector<unsigned>& result_lit )
{
for ( unsigned k = 0; k < effs.size(); k++ )
{
bool can_execute = true;
std::vector<unsigned> unknown;
for ( unsigned i = 0; i < conds[k].size(); i++ )
{
unsigned ci = conds[k][i];
if ( !b.known_set().isset(ci) && !b.unknown_set().isset(ci) )
{
can_execute = false;
break;
}
if ( b.unknown_set().isset(ci) )
unknown.push_back( ci );
}
if ( !can_execute || unknown.size() > 1 || unknown.empty() ) continue;
unsigned not_L = unknown[0];
/*
#ifdef DEBUG
std::cout << "Found candidate for action compilation!" << std::endl;
sm_task.print_fluent( not_L, std::cout );
std::cout << std::endl;
#endif
*/
unsigned L = sm_task.not_equivalent(not_L);
//assert( L != 0 );
if ( L != 0 )
{
if ( !effs[k]->adds().isset(L) )
{
result[k] = false;
result_lit[k] = 0;
/*
#ifdef DEBUG
std::cout << "\t rule doesn't comply with C & ~L -> L" << std::endl;
#endif
*/
continue;
}
std::vector<unsigned> adding;
for ( unsigned j = 0; j < effs.size(); j++ )
{
if ( j == k ) continue;
if ( effs[j]->adds().isset(not_L) )
adding.push_back(j);
}
bool act_comp_holds = true;
for ( unsigned i = 0; i < adding.size(); i++ )
if ( condition_may_execute( b, conds[adding[i]] ) )
{
act_comp_holds = false;
break;
}
if ( act_comp_holds )
{
result[k] = true;
result_lit[k] = L;
/*
#ifdef DEBUG
std::cout << "Atom "; sm_task.print_fluent( L, std::cout );
std::cout << " should become known because of action compilation!" << std::endl;
std::cout << std::endl;
#endif
*/
}
else
{
result[k] = false;
result_lit[k] = 0;
}
continue;
}
else
{
result[k] = false;
result_lit[k] = 0;
}
}
}
void SearchNode::k0_projection( std::vector< PDDL::Operator* >& effs )
{
if (father == NULL) return; // Don't project Root
Belief& b = *(father->b); // Father belief
Belief& bp = *(this->b); // successor belief
/*#ifdef DEBUG
std::cout << "K0 projection" << std::endl;
std::cout << "Through operator: ";
sm_task.print_operator( effs[0], std::cout );
std::cout << std::endl;
std::cout << "Parent belief: " << std::endl;
b.print( std::cout );
std::cout << std::endl;
#endif
*/
PDDL::Fluent_Set not_affected( sm_task.fluent_count()+1 );
PDDL::Fluent_Set processed( sm_task.fluent_count() + 1 );
// MRJ: TODO: This can be precomputed
compute_persist_set( b, effs, not_affected );
// MRJ: preserve KL and ~KL lits
/*
#ifdef DEBUG
std::cout << "Preserving atoms not affected by action" << std::endl;
#endif
*/
preserve_persisting_lits( b, bp, not_affected, processed );
/*
#ifdef DEBUG
std::cout << "Checking effects" << std::endl;
#endif
*/
std::vector< Atom_Vec > eff_conds;
retrieve_effect_conditions( effs, eff_conds );
std::vector<bool> support_holds( eff_conds.size(), false );
std::vector<bool> cancellation_holds( eff_conds.size(), false );
std::vector<bool> act_comp_holds( eff_conds.size(), false );
std::vector<unsigned> act_comp_lit( eff_conds.size() );
check_support_rule( b, eff_conds, support_holds );
check_cancellation_rule( b, eff_conds, cancellation_holds );
check_action_compilation( b, eff_conds, effs, act_comp_holds, act_comp_lit );
PDDL::Fluent_Set potentially_unknown( sm_task.fluent_count()+1 );
for ( int p = 1; p < sm_task.fluent_count()-1; p++ )
{
if ( processed.isset(p) ) continue; // Nothing to do here
//if ( !sm_task.fluents()[p]->is_pos() ) continue;
/*
#ifdef DEBUG
std::cout << "Processing fluent "; sm_task.print_fluent(p, std::cout);
std::cout << std::endl;
#endif
*/
std::vector<unsigned> adding_p;
for ( unsigned k = 0; k < effs.size(); k++ )
if ( effs[k]->adds().isset( p ) )
adding_p.push_back(k);
bool support_applies = false;
bool cancellation_applies = false;
for ( unsigned k = 0; k < adding_p.size(); k++ )
{
if ( support_holds[adding_p[k]] )
{
support_applies = true;
/*
#ifdef DEBUG
std::cout << "Effect: Condition: " << std::endl;
for ( unsigned i = 0; i < eff_conds[adding_p[k]].size(); i++ )
{
sm_task.print_fluent( eff_conds[adding_p[k]][i], std::cout );
if ( i < eff_conds[adding_p[k]].size()-1 )
std::cout << " ";
}
std::cout << " KC holds" << std::endl;
#endif
*/
continue;
}
if ( cancellation_holds[k] )
{
cancellation_applies = true;
/*
#ifdef DEBUG
std::cout << "Effect: Condition: " << std::endl;
for ( unsigned i = 0; i < eff_conds[adding_p[k]].size(); i++ )
{
sm_task.print_fluent( eff_conds[adding_p[k]][i], std::cout );
if ( i < eff_conds[adding_p[k]].size()-1 )
std::cout << " ";
}
std::cout << " ~K~C holds" << std::endl;
#endif
*/
continue;
}
}
// Check if p is the resulting lit for some action compilation effect
bool act_comp_effect = false;
for ( unsigned i = 0; i < act_comp_lit.size(); i++ )
{
if ( act_comp_lit[i] == p )
{
act_comp_effect = true;
break;
}
}
if ( !support_applies && !cancellation_applies && !act_comp_effect )
{
/*
#ifdef DEBUG
std::cout << "Atom "; sm_task.print_fluent(p, std::cout );
std::cout << " becomes POTENTIALLY-UNKNOWN because no rule applying it" << std::endl;
#endif
*/
if ( !not_affected.isset(p) )
potentially_unknown.set(p);
}
else if ( ( !support_applies && !cancellation_applies && act_comp_effect )
|| ( support_applies && !cancellation_applies && !act_comp_effect)
|| ( support_applies && !cancellation_applies && act_comp_effect ) )
{
#ifdef DEBUG
std::cout << "Atom "; sm_task.print_fluent(p, std::cout );
std::cout << " becomes KNOWN because of ";
if ( support_applies ) std::cout << "SUPPORT ";
if ( act_comp_effect ) std::cout << "ACTION COMPILATION ";
std::cout << "rule" << std::endl;
#endif
bp.add_known_lit(p);
processed.set(p);
}
else if ( !support_applies && cancellation_applies && !act_comp_effect )
{
/*
#ifdef DEBUG
std::cout << "Atom "; sm_task.print_fluent(p, std::cout );
std::cout << " becomes POTENTIALLY-UNKNOWN because of CANCELLATION" << std::endl;
#endif
*/
potentially_unknown.set(p);
}
else
{
/*
#ifdef DEBUG
std::cout << "Support & cancellation rules applying for atom ";
sm_task.print_fluent( p, std::cout );
std::cout << " which will considered KNOWN" << std::endl;
#endif
*/
bp.add_known_lit( p );
processed.set(p);
}
}
for ( unsigned p = 1; p < sm_task.fluent_count()-1; p++ )
{
if ( processed.isset(p) ) continue;
if ( potentially_unknown.isset(p) )
{
std::vector<unsigned> deleting_p;
for ( unsigned k = 0; k < effs.size(); k++ )
if ( effs[k]->dels().isset( p ) )
deleting_p.push_back(k);
bool is_false = false;
for ( unsigned k = 0; k < deleting_p.size(); k++ )
if ( support_holds[deleting_p[k]] )
{
is_false = true;
break;
}
if (is_false) continue;
unsigned not_p = sm_task.not_equivalent(p);
if ( not_p == 0 )
{
/*
#ifdef DEBUG
std::cout << "Atom "; sm_task.print_fluent(p,std::cout);
std::cout << " becomes UNKNOWN" << std::endl;
#endif
*/
/*
std::vector<unsigned> rel_oofs;
for ( unsigned i = 0; i < sm_task.oneofs().size(); i++ )
{
Atom_Vec& one_ofs = sm_task.oneofs()[i];
if ( std::find( one_ofs.begin(), one_ofs.end(), p )
!= one_ofs.end() )
rel_oofs.push_back( i );
}
bool one_of_is_known = false;
for ( unsigned i = 0; i < rel_oofs.size(); i++ )
{
Atom_Vec& one_ofs = sm_task.oneofs()[rel_oofs[i]];
for ( unsigned k = 0; k < one_ofs.size(); k++ )
if ( bp.known_set().isset( one_ofs[k] ) )
{
one_of_is_known = true;
break;
}
if ( one_of_is_known ) break;
}
if ( !one_of_is_known )
*/
bp.add_unknown_lit(p);
}
else
{
if ( bp.known_set().isset( not_p ) )
{
/*
#ifdef DEBUG
std::cout << "Atom "; sm_task.print_fluent(p,std::cout);
std::cout << " known to be FALSE" << std::endl;
#endif
*/
}
else if ( bp.unknown_set().isset( not_p ) )
{
/*
#ifdef DEBUG
std::cout << "Atom "; sm_task.print_fluent(p,std::cout);
std::cout << " becomes UNKNOWN" << std::endl;
#endif
*/
bp.add_unknown_lit(p);
}
else if ( potentially_unknown.isset( not_p ) )
{
/*
#ifdef DEBUG
std::cout << "Atom "; sm_task.print_fluent(p,std::cout);
std::cout << " becomes UNKNOWN" << std::endl;
#endif
*/
/*
std::vector<unsigned> rel_oofs;
for ( unsigned i = 0; i < sm_task.oneofs().size(); i++ )
{
Atom_Vec& one_ofs = sm_task.oneofs()[i];
if ( std::find( one_ofs.begin(), one_ofs.end(), not_p )
!= one_ofs.end() )
rel_oofs.push_back( i );
}
bool one_of_is_known = false;
for ( unsigned i = 0; i < rel_oofs.size(); i++ )
{
Atom_Vec& one_ofs = sm_task.oneofs()[rel_oofs[i]];
for ( unsigned k = 0; k < one_ofs.size(); k++ )
if ( bp.known_set().isset( one_ofs[k] ) )
{
one_of_is_known = true;
break;
}
if ( one_of_is_known ) break;
}
if ( !one_of_is_known )
*/
bp.add_unknown_lit(p);
}
else
{
/*
#ifdef DEBUG
std::cout << "Atom "; sm_task.print_fluent(not_p,std::cout);
std::cout << " known to be false, but "; sm_task.print_fluent(p, std::cout);
std::cout << "is unknown!" << std::endl;
assert( false );
#endif
*/
}
}
}
else
{
/*
#ifdef DEBUG
std::cout << "Atom "; sm_task.print_fluent(p,std::cout);
std::cout << " known to be FALSE" << std::endl;
#endif
*/
}
}
if ( bp.check_consistency() )
{
/*
#ifdef DEBUG
std::cout << "K0 projection returned inconsistent state!" << std::endl;
bp.print();
#endif
*/ assert(false);
}
}
/** Generates the successors node.
* We suppose that the op is applicable in
* the current belief state. **/
SearchNode* SearchNode::successor( unsigned op )
{
SearchNode* succ = new SearchNode;
/* NB: Assumes that op is executable in father */
succ->b = new Belief::Belief();
succ->gn = gn + sm_task.op_cost( op );
succ->op = op;
succ->father = this;
succ->timestep = timestep+1;
//hS = hX = hn = 0;
return succ;
}
// void SearchNode::check_dead_models()
// {
// Planner_Stats& stats = Planner_Stats::instance();
// num_dead_models = 0;
// if ( father != NULL )
// {
// for ( unsigned k = 0; k < models.size(); k++ )
// {
// dead_model[k] = father->dead_model[k];
// if ( dead_model[k] ) num_dead_models++;
// }
// }
// for ( unsigned k = 0; k < models.size(); k++ )
// {
// if ( dead_model[k] )
// continue;
// std::vector<int>& k_model = models[k];
// for ( unsigned j = k+1; j < models.size(); j++ )
// {
// if ( dead_model[j] )
// continue;
// std::vector<int>& j_model = models[j];
// bool are_equal = true;
// for ( int f = 1; f < sm_task.fluent_count()-1; f++ )
// {
// if ( std::sgn(k_model[f]) != std::sgn(j_model[f]) )
// {
// are_equal = false;
// break;
// }
// }
// if ( are_equal )
// {
// num_dead_models++;
// dead_model[j] = true;
// }
// }
// }
// stats.notify_num_dead_models( num_dead_models );
// }
void SearchNode::determine_testable_precs( std::vector<PDDL::Operator*>& ops )
{
for ( unsigned i = 0; i < sm_task.prototype_ops().size(); i++ )
{
PDDL::Operator* o = sm_task.prototype_ops()[i];
bool testable = true;
Atom_Vec& prec = o->hard_prec_vec();
for ( unsigned k = 0; k < prec.size(); k++ )
{
if ( !b->known_set().isset(prec[k])
&& !b->unknown_set().isset(prec[k]) )
{
testable = false;
break;
}
if ( !potentially_known[prec[k]] )
{
testable = false;
break;
}
}
if ( !testable ) continue;
for ( unsigned k = 0; k < prec.size(); k++ )
if ( b->unknown_set().isset(prec[k]) )
{
ops.push_back( o );
break;
}
}
}
void SearchNode::determine_testable_goals( Atom_Vec& tG )
{
Atom_Vec& G = sm_task.goal_state();
for ( unsigned i = 0; i < G.size(); i++ )
{
if ( !b->known_set().isset(G[i]) && !b->unknown_set().isset(G[i] ) )
continue;
if ( b->known_set().isset(G[i]) )
continue;
if ( potentially_known[G[i]] )
tG.push_back( G[i] );
}
}
void SearchNode::test_conjunction( MiniSAT& solver, Atom_Vec& atoms )
{
Atom_Vec atoms_to_test;
for ( unsigned k = 0; k < atoms.size(); k++ )
{
if ( !b->unknown_set().isset(atoms[k]) && ! b->known_set().isset(atoms[k]) )
continue;
if ( b->known_set().isset(atoms[k] ) )
continue;
atoms_to_test.push_back( atoms[k] );
}
if ( atoms_to_test.empty() ) return;
std::vector<int> lits;
for ( unsigned k = 0; k < atoms_to_test.size(); k++ )
{
unsigned p = atoms_to_test[k];
if ( sm_task.fluents().at(p)->is_pos() )
lits.push_back( -theory_step->fluent_var(p) );
else
lits.push_back( theory_step->fluent_var(p) );
}
solver.add_clause( lits );
if ( solver.solve( ) )
solver.retract_last_clause();
else
{
for ( unsigned k = 0; k < atoms_to_test.size(); k++ )
{
unsigned p = atoms_to_test[k];
unsigned neg_p = sm_task.not_equivalent( atoms_to_test[k] );
b->add_known_lit( p );
b->remove_unknown_lit( p );
if ( neg_p )
b->remove_unknown_lit( neg_p );
}
for ( unsigned k = 0; k < lits.size(); k++ )
{
solver.add_fact( -lits[k] );
theory_step->add_fact( -lits[k] );
}
}
}
/** In case the width of the problem is <= 1 an atom is true in the belief
* if it is true in all the models.
**/
void SearchNode::check_known_atoms_from_samples(std::vector<std::vector<int> >& samples)
{
unsigned count_pos;
unsigned count_neg;
/*
#ifdef DEBUG
std::cout << "Projected Models\n";
std::cout << "States in b' ( " << samples.size() << " ) " << std::endl;
for ( unsigned k = 0; k < samples.size(); k++ )
{
std::cout << "s_" << k << ": ";
for ( unsigned l = 1; l < samples[k].size(); l++ )
{
unsigned f = std::abs( samples[k][l] );
int fsgn = std::sgn( samples[k][l] );
if ( sm_task.fluents()[f]->is_pos() )
{
std::cout << ( fsgn > 0 ? " " : " -" );
sm_task.print_fluent(f, std::cout );
std::cout << std::endl;
}
}
std::cout << std::endl;
}
}
#endif
*/
for ( unsigned f = 1; f < (unsigned)(sm_task.fluent_count()-1); f++ )
{
if (!potentially_known[f ]) continue;
if (b->known_set().isset( f ) )
continue;
count_pos = 0;
count_neg = 0;
unsigned neg_f = sm_task.not_equivalent( f );
for ( unsigned j = 0; j < samples.size(); j++ )
{
if ( samples[j][f] > 0 )
count_pos++;
else
{
count_neg++;
break;
}
}
if ( count_neg == 0) // Lit is true
{
#ifdef DEBUG
std::cout << "Adding known fluent";
sm_task.print_fluent(f);
std::cout << std::endl;
#endif
b->add_known_lit( f );
b->remove_unknown_lit( f );
if ( neg_f )
{
b->remove_known_lit( neg_f );
b->remove_unknown_lit( neg_f );
}
}
else if ( count_pos == 0 ) // Lit is false
{
if ( neg_f )
{
b->add_known_lit( neg_f );
b->remove_unknown_lit( neg_f );
}
b->remove_known_lit( f );
b->remove_unknown_lit( f );
}
}
}
void SearchNode::belief_tracking_with_sat()
{
theory_step = new Theory_Fragment( op, father->theory_step );
if ( b->unknown_vec().empty() )
return;
make_clauses();
std::vector<PDDL::Operator*> testable_actions;
Atom_Vec testable_goals;
determine_testable_precs(testable_actions);
determine_testable_goals(testable_goals);
if ( testable_actions.empty() && testable_goals.empty() )
return;
MiniSAT solver(this);
#ifdef DEBUG
if ( !solver.solve() )
{
std::cout << "INCONSISTENT Belief!!!" << std::endl;
describe();
assert( false );
}
#endif
/*
// Check action preconditions
for ( unsigned i = 0; i < testable_actions.size(); i++ )
{
PDDL::Operator* o = testable_actions[i];
Atom_Vec& precs = o->hard_prec_vec();
for ( unsigned j = 0; j < precs.size(); j++ )
if ( !is_literal_known( solver, precs[j] ) )
break;
//test_conjunction( solver, precs );
}
// Check goals
for ( unsigned j = 0; j < testable_goals.size(); j++ )
if ( !is_literal_known( solver, testable_goals[j] ) )
break;
//test_conjunction( solver, testable_goals );
*/
for ( unsigned i = 0; i < sm_task.prototype_ops().size(); i++ )
{
PDDL::Operator* o = sm_task.prototype_ops()[i];
#ifdef DEBUG
std::cout << "Testing ";
sm_task.print_operator( o, std::cout );
std::cout << " operator preconditions" << std::endl;
#endif
Atom_Vec& precs = o->hard_prec_vec();
for ( unsigned j = 0; j < precs.size(); j++ )
{
#ifdef DEBUG
std::cout << "\t Precondition: ";
sm_task.print_fluent( precs[j], std::cout );
#endif
if ( !is_literal_known( solver, precs[j] ) )
{
#ifdef DEBUG
std::cout << " remains unknown!" << std::endl;
#endif
break;
}
#ifdef DEBUG
std::cout << " is known!" << std::endl;
#endif
}
}
// Check goal
Atom_Vec& G = sm_task.goal_state();
for ( unsigned i = 0; i < G.size(); i++ )
{
#ifdef DEBUG
std::cout << "Checking goal: ";
sm_task.print_fluent( G[i], std::cout );
#endif
if ( !is_literal_known( solver, G[i] ) )
{
#ifdef DEBUG
std::cout << " is unknown!" << std::endl;
#endif
break;
}
#ifdef DEBUG
std::cout << " is known!" << std::endl;
#endif
}
}
void SearchNode::do_belief_tracking(std::vector< std::vector<int> >& models)
{
Planner_Stats& stats = Planner_Stats::instance();
std::vector<unsigned> prefix;
SearchNode * n = this;
// builds the plan prefix
while( n != NULL )
{
prefix.push_back(n->op);
n = n->father;
}
n = this;
#ifdef DEBUG
std::cout << "Printing the prefix in order we've it "<< std::endl;
for (unsigned o = 0; o < prefix.size(); o++)
{
std::cout <<"(" << o << ". ";
sm_task.print_operator( prefix[o], std::cout );
std::cout <<")";
}
std::cout << std::endl;
#endif
potentially_known.resize( sm_task.fluent_count() );
for (int o = (prefix.size()-1); o >= 0; o--)
{
std::vector<PDDL::Operator*>& ops = sm_task.useful_ops()[prefix[o]]->same_op_vec();
update_models(ops, models);
// dead_model = father->dead_model;
} // end (for prefix)
#ifdef DEBUG
std::cout << "Local MODELS changed by the action:" << std::endl;
for ( unsigned j = 0; j < models.size(); j++ )
{
std::cout << "s_" << j << ": ";
for ( unsigned l = 1; l < models[j].size(); l++ )
{
std::cout << models[j][l] << " " << (models[j][l] > 0 ? " " : " -");
sm_task.print_fluent( models[j][l] > 0 ? models[j][l] : (unsigned)abs(models[j][l]) );
std::cout << ", ";
}
std::cout << std::endl;
}
std::cout << std::endl;
#endif
std::vector<PDDL::Operator*>& ops = sm_task.useful_ops()[n->op]->same_op_vec();
k0_projection(ops);
compute_hash( models );
if ( stats.is_width_1() )
check_known_atoms_from_samples( models );
else
belief_tracking_with_sat();
// Rebuilds Unknown Atoms List
b->unknown_vec().clear();
for (unsigned i = 1; i < sm_task.fluents().size()-1; i++)
if ( b->unknown_set().isset( i ) )
{
if( b->known_set().isset(i) )
{
std::cout << "Inconsistent belief!" << std::endl;
std::cout << "Atom: ";
sm_task.print_fluent( i, std::cout );
std::cout << " both in K and ~K" << std::endl;
b->print(std::cout);
assert(false);
}
if ( sm_task.not_equivalent(i)
&& b->known_set().isset( sm_task.not_equivalent(i)) )
{
std::cout << "Inconsistent belief!" << std::endl;
std::cout << "Atom: ";
sm_task.print_fluent( i, std::cout );
std::cout << " both in K and ~K" << std::endl;
b->print(std::cout);
assert(false);
}
b->unknown_vec().push_back( i );
}
}
// void SearchNode::replace_dead_sample( std::vector<int>& model )
// {
// if ( num_dead_models == 0 ) return; // No room for new models
// // Complete model
// for ( int x = theory_step->fluent_var(1); x < theory_step->nVars(); x++ )
// {
// if ( model[x] == 0 )
// {
// int f = theory_step->recover_fluent(x);
// if ( f == 0 ) continue;
// model[x] = -model[ theory_step->fluent_var( sm_task.not_equivalent(f) ) ];
// }
// }
// // Check that the model returned by solver is not already in our
// // sample set
// for ( unsigned k = 0; k < models.size(); k++ )
// {
// if ( dead_model[k] )
// continue;
// std::vector<int>& k_model = models[k];
// bool are_equal = true;
// for ( int f = 1; f < sm_task.fluent_count()-1; f++ )
// {
// if ( std::sgn(k_model[f]) != std::sgn(model[theory_step->fluent_var(f)]) )
// {
// are_equal = false;
// break;
// }
// }
// if ( are_equal )
// return;
// }
// // Replace first dead model
// for ( unsigned k = 0; k < dead_model.size(); k++ )
// {
// if ( dead_model[k] )
// {
// num_dead_models--;
// for ( int f = 1; f < sm_task.fluent_count()-1; f++ )
// models[k][f] = model[theory_step->fluent_var(f)];
// dead_model[k] = false;
// Planner_Stats& stats = Planner_Stats::instance();
// stats.notify_dead_sample_replaced();
// return;
// }
// }
// }
bool SearchNode::is_literal_known( MiniSAT& solver, unsigned p )
{
unsigned neg_p = sm_task.not_equivalent( p );
std::vector<int> model;
NFF_Options& opt = NFF_Options::instance();
if ( !b->unknown_set().isset(p) )
{
#ifdef DEBUG
std::cout << "\t\t Wasn't in the unknown set!" << std::endl;
#endif
return true;
}
if ( !potentially_known[p] )
{
#ifdef DEBUG
std::cout << "\t\t Wasn't potentially known!" << std::endl;
#endif
return false;
}
int test_literal = 0;
/* Adding the fact to be checked */
if ( sm_task.fluents().at(p)->is_pos() )
//test_literal = (int)-(p + next_offset);
test_literal = -theory_step->fluent_var(p);
else
{
assert( neg_p != 0 );
test_literal = theory_step->fluent_var(neg_p);
}
solver.add_fact( test_literal );
if ( solver.solve( model ) )
{
#ifdef DEBUG
std::cout << "\t\tTheory is SAT. (Fluent remains unknown) ";
sm_task.print_fluent( p );
std::cout << std::endl;
#endif
// if ( opt.dynamic_samples() )
// replace_dead_sample( model );
solver.retract_last_fact();
potentially_known[p] = false;
return false;
/*
// We don't know the atom to be true, let's see if we know
// it to be false
test_literal = -test_literal;
solver.add_fact( test_literal );
if ( solver.solve( model ) )
{
#ifdef DEBUG
std::cout << "\t\tTheory is SAT. (Fluent remains unknown) ~";
sm_task.print_fluent( p );
std::cout << std::endl;
#endif
if ( opt.dynamic_samples() )
replace_dead_sample( model );
solver.retract_last_fact();
potentially_known[p] = false;
return false;
}
#ifdef DEBUG
std::cout << "\t\tTheory is UNSAT! (Fluent is known) ~";
sm_task.print_fluent( p );
std::cout << std::endl;
#endif
b->remove_unknown_lit(p);
if ( neg_p )
{
b->remove_unknown_lit(neg_p);
b->add_known_lit(neg_p);
}
*/
}
else
{
#ifdef DEBUG
std::cout << "\t\tTheory is UNSAT! (Fluent is known)";
sm_task.print_fluent( p );
std::cout << std::endl;
#endif
// Adds literal to Belief
b->add_known_lit( p );
b->remove_unknown_lit( p );
b->remove_unknown_lit( neg_p);
}
solver.retract_last_fact();
if ( test_literal )
{
solver.add_fact( -test_literal );
theory_step->add_fact( -test_literal );
}
return true;
}
void SearchNode::print_clauses()
{
std::cout << "PRINTING THE THEORY STEP..... " << std::endl;
std::cout << "::FACTS " << std::endl;
assert( theory_step != NULL );
for ( unsigned k = 0; k < theory_step->unit_clauses().size(); k++ )
{
Minisat::Lit l =theory_step->unit_clauses()[k];
Minisat::Var x = Minisat::var(l);
bool is_cond_var = false;
int fluent_index = theory_step->recover_fluent(x);
int cond_index = theory_step->recover_cond_index(x);
int timestep;
if ( fluent_index > 0 || cond_index >= 0 )
{
if ( fluent_index == 0 )
is_cond_var = true;
timestep = this->timestep;
}
else
{
fluent_index = father->theory_step->recover_fluent(x);
timestep = father->timestep;
}
bool sgn = Minisat::sign(l);
std::cout << ( sgn ? "~" : "" );
if ( is_cond_var )
std::cout << "(EFF_CON_" << fluent_index << ")";
else
sm_task.print_fluent( fluent_index, std::cout );
std::cout << "_" << timestep;
std::cout << std::endl;
}
std::cout << "::CLAUSES " << std::endl;
for ( unsigned k = 0; k < theory_step->clauses().size(); k++ )
{
Minisat::Clause& c = theory_step->get_clause(k);
for ( unsigned i = 0; i < c.size(); i++ )
{
Minisat::Lit l = c[i];
Minisat::Var x = Minisat::var(l);
bool is_cond_var = false;
int fluent_index = theory_step->recover_fluent(x);
int cond_index = theory_step->recover_cond_index(x);
int timestep;
if ( fluent_index > 0 || cond_index >= 0 )
{
if ( fluent_index == 0 )
is_cond_var = true;
timestep = this->timestep;
}
else
{
fluent_index = father->theory_step->recover_fluent(x);
timestep = father->timestep;
}
bool sgn = Minisat::sign(l);
std::cout << ( sgn ? "~" : "" );
if ( is_cond_var )
std::cout << "(EFF_CON_" << fluent_index << ")";
else
sm_task.print_fluent( fluent_index, std::cout );
std::cout << "_" << timestep;
if ( i < c.size() -1 )
std::cout << " v ";
}
std::cout << std::endl;
}
}
void SearchNode::make_root_clauses()
{
Theory_Fragment* current = theory_step;
for(std::vector<unsigned>::iterator it = b->known_vec().begin();
it!= b->known_vec().end(); it++)
{
theory_step->add_fact( sm_task.fluents()[*it]->is_pos() ?
current->fluent_var(*it) :
-current->fluent_var( sm_task.not_equivalent(*it) ) );
}
for ( unsigned p = 1; p < sm_task.fluent_count()-1; p++ )
{
if ( b->known_set().isset(p) ) continue;
if ( b->unknown_set().isset(p) ) continue;
theory_step->add_fact( sm_task.fluents()[p]->is_pos() ?
-current->fluent_var(p) :
current->fluent_var( sm_task.not_equivalent(p) ) );
}
// In case we are at Init, add the clauses of the problem
for(std::vector<std::vector<unsigned> >::iterator cl = b->clauses_vec().begin();
cl != b->clauses_vec().end(); cl++)
{
bool absorbed = false;
for ( std::vector<unsigned>::iterator it = (*cl).begin(); it != (*cl).end(); it++)
{
int lit = sm_task.fluents()[*it]->is_pos() ?
current->fluent_var(*it) :
-current->fluent_var( sm_task.not_equivalent(*it) );
if ( !theory_step->add_lit( lit ) )
{
absorbed = true;
break;
}
}
if (!absorbed)
theory_step->finish_clause();
}
/*
#ifdef DEBUG
print_clauses();
#endif
*/
return;
}
void SearchNode::make_clauses()
{
PDDL::Operator* op_ptr = sm_task.useful_ops()[op];
Theory_Fragment* current = NULL;
Theory_Fragment* next = NULL;
current = father->theory_step;
next = theory_step;
for(std::vector<unsigned>::iterator it = b->known_vec().begin();
it!= b->known_vec().end(); it++)
{
theory_step->add_fact( sm_task.fluents()[*it]->is_pos() ?
next->fluent_var(*it) :
-next->fluent_var( sm_task.not_equivalent(*it) ) );
}
for ( unsigned p = 1; p < (unsigned)(sm_task.fluent_count()-1); p++ )
{
if ( b->known_set().isset(p) ) continue;
if ( b->unknown_set().isset(p) ) continue;
theory_step->add_fact( sm_task.fluents()[p]->is_pos() ?
-next->fluent_var(p) :
next->fluent_var( sm_task.not_equivalent(p) ) );
}
std::vector<PDDL::Operator*>& effects = op_ptr->same_op_vec();
/* Effect axioms */
for(std::vector<PDDL::Operator*>::iterator it = effects.begin(); it!= effects.end(); it++)
{
std::vector<unsigned>& precs = (*it)->prec_vec();
std::vector<unsigned>& dels = (*it)->del_vec();
std::vector<unsigned>& adds = (*it)->add_vec();
/* Added literals */
for (std::vector<unsigned>::iterator a = adds.begin(); a != adds.end(); a++ )
{
/* Optimization: if lit == not-lit, then we have the same clause
* as a del one */
if ( !( (sm_task.fluents())[ *a ])->is_pos() )
continue;
int p1 = next->fluent_var(*a);
if ( !theory_step->add_lit(p1) )
{
continue; // clause is absorbed
}
/* If action is executable, we don't need preconditions */
/* Conditions */
bool absorbed = false;
for (std::vector<unsigned>::iterator c = precs.begin();
c != precs.end(); c++ )
{
int lit = sm_task.fluents()[ *c ]->is_pos() ?
-current->fluent_var(*c) :
current->fluent_var( sm_task.not_equivalent(*c) );
if ( !theory_step->add_lit(lit) )
{
absorbed = true;
break;
}
}
if ( !absorbed )
theory_step->finish_clause();
}
/* Deleted literals */
for (std::vector<unsigned>::iterator d = dels.begin(); d != dels.end(); d++ )
{
/* Optimization: if lit == not-lit, then we have the same clause
* as an add one */
if ( !sm_task.fluents()[ *d ]->is_pos() )
continue;
int p1 = next->fluent_var( *d );
if( !theory_step->add_lit( -p1 ) )
continue;
/* Preconditions */
/* Conditions */
bool absorbed = false;
for (std::vector<unsigned>::iterator c = precs.begin(); c != precs.end(); c++ )
{
int lit = sm_task.fluents()[*c]->is_pos() ?
-current->fluent_var(*c) :
current->fluent_var( sm_task.not_equivalent(*c) );
if (! theory_step->add_lit(lit) )
{
absorbed = true;
break;
}
}
if (!absorbed)
theory_step->finish_clause();
} // end for dels
}
// Positive Frame Axioms for p
std::vector<bool> cond_eq_required(effects.size());
for ( int p = 1; p < (int)sm_task.fluent_count()-1; p++ )
{
if ( !sm_task.fluents()[p]->is_pos() ) continue;
int p0 = current->fluent_var(p);
int p1 = next->fluent_var(p);
if ( !theory_step->add_lit(-p0) )
continue; // absorbed
if ( !theory_step->add_lit(p1) )
continue; // absorbed;
std::vector<int> relevant_dels_vars;
for( unsigned k = 0; k < effects.size(); k++)
{
if ( effects[k]->dels().isset(p) )
{
relevant_dels_vars.push_back( theory_step->cond_var(k) );
cond_eq_required[k] = true;
}
}
for ( unsigned k = 0; k < relevant_dels_vars.size(); k++ )
theory_step->add_lit( relevant_dels_vars[k] );
theory_step->finish_clause();
}
// Negative Frame Axioms for p
for ( int p = 1; p < (int)sm_task.fluent_count()-1; p++ )
{
if ( !sm_task.fluents()[p]->is_pos() ) continue;
int p0 = current->fluent_var(p);
int p1 = next->fluent_var(p);
if (!theory_step->add_lit(p0))
continue; // absorbed
if (!theory_step->add_lit(-p1))
continue; // absorbed
std::vector<int> relevant_adds_vars;
for( unsigned k = 0; k < effects.size(); k++)
{
if ( effects[k]->adds().isset(p) )
{
relevant_adds_vars.push_back( theory_step->cond_var(k) );
cond_eq_required[k] = true;
}
}
for ( unsigned k = 0; k < relevant_adds_vars.size(); k++ )
theory_step->add_lit( relevant_adds_vars[k] );
theory_step->finish_clause();
}
// Introduce Condition equality clauses
for ( unsigned k = 0; k < effects.size(); k++ )
{
if ( !cond_eq_required[k] ) continue;
Atom_Vec& precs = effects[k]->prec_vec();
int cond_var = theory_step->cond_var(k);
if (!theory_step->add_lit(cond_var))
continue; // absorbed
bool absorbed = false;
for ( unsigned i = 0; i < precs.size(); i++ )
{
int ci = precs[i];
int lit_ci = sm_task.fluents()[ci]->is_pos() ?
-current->fluent_var(ci)
: current->fluent_var( sm_task.not_equivalent(ci) );
if (!theory_step->add_lit(lit_ci))
{
absorbed = true;
break;
}
}
if (!absorbed)
theory_step->finish_clause();
for ( unsigned i = 0; i < precs.size(); i++ )
{
int ci = precs[i];
int lit_ci = sm_task.fluents()[ci]->is_pos() ?
current->fluent_var(ci)
: -current->fluent_var( sm_task.not_equivalent(ci) );
if (!theory_step->add_lit(lit_ci))
continue;
if (!theory_step->add_lit(-cond_var))
continue;
theory_step->finish_clause();
}
}
/*
#ifdef DEBUG
print_clauses();
#endif
*/
}
void SearchNode::describe()
{
std::cout << "Node description:" << std::endl;
std::cout << "\tg(n)=" << gn << std::endl;
// std::cout << "\t# dead models =" << num_dead_models << std::endl;
std::cout << "\th_S(n)=" << hS << std::endl;
std::cout << "\th_X(n)=" << hX << std::endl;
std::cout << "\th(n)=" << hn << std::endl;
std::cout << "\ttb(n)=" << tb << std::endl;
std::cout << "\tHA_{S}(n)={";
for ( unsigned k = 0; k < m_hS_HA.size(); k++ )
{
sm_task.print_operator( sm_task.prototype_ops()[m_hS_HA[k]]->get_idx(), std::cout );
if ( k < m_hS_HA.size()-1 ) std::cout << ", ";
}
std::cout << "}" << std::endl;
std::cout << "\tHA_{X}(n)={";
for ( unsigned k = 0; k < m_hX_HA.size(); k++ )
{
sm_task.print_operator( sm_task.prototype_ops()[m_hX_HA[k]]->get_idx(), std::cout );
if ( k < m_hX_HA.size()-1 ) std::cout << ", ";
}
std::cout << "}" << std::endl;
std::cout << "\t\\pi={";
sm_task.print_operator( op, std::cout );
SearchNode* tmp = father;
while ( tmp != NULL )
{
sm_task.print_operator( tmp->op, std::cout );
tmp = tmp->father;
}
std::cout << "}" << std::endl;
b->print( std::cout );
std::cout << std::endl;
for ( int i = 0; i < 10; i++ )
std::cout << "=";
std::cout << std::endl;
}
// void SearchNode::compute_hash()
// {
// Hash_Key k;
// for ( unsigned f = 1; f < sm_task.fluent_count()-1; f++ )
// {
// k.add( f );
// unsigned count_pos = 0;
// unsigned count_neg = 0;
// for ( unsigned j = 0; j < models.size(); j++ )
// {
// if ( models[j][f] > 0 )
// count_pos++;
// else
// count_neg++;
// }
// k.add( count_pos );
// k.add( count_neg );
// if ( count_pos == 0 || count_neg == 0 )
// {
// #ifdef DEBUG
// std::cout << "Fluent: ";
// sm_task.print_fluent(f, std::cout );
// std::cout << " is potentially known " << (count_pos ? "to be TRUE":"to be FALSE") << std::endl;
// #endif
// potentially_known[f] = true;
// }
// else
// potentially_known[f] = false;
// }
// m_hash_key = k;
// }
void SearchNode::compute_hash(std::vector<std::vector<int> >& models)
{
Hash_Key k;
for ( unsigned f = 1; f < sm_task.fluent_count()-1; f++ )
{
k.add( f );
unsigned count_pos = 0;
unsigned count_neg = 0;
for ( unsigned j = 0; j < models.size(); j++ )
{
if ( models[j][f] > 0 )
count_pos++;
else
count_neg++;
}
k.add( count_pos );
k.add( count_neg );
if ( count_pos == 0 || count_neg == 0 )
{
#ifdef DEBUG
std::cout << "Fluent: ";
sm_task.print_fluent(f, std::cout );
std::cout << " is potentially known " << (count_pos ? "to be TRUE":"to be FALSE") << std::endl;
#endif
potentially_known[f] = true;
}
else
potentially_known[f] = false;
}
m_hash_key = k;
}
bool SearchNode::same_models( SearchNode& o, std::vector<std::vector<int> >& models )
{
std::vector<unsigned> prefix_1;
std::vector<unsigned> prefix_2;
SearchNode * n = this;
// 1. gets the two prefixes
while( n != NULL )
{
prefix_1.push_back(n->op);
n = n->father;
}
n = &o;
while( n != NULL )
{
prefix_2.push_back(n->op);
n = n->father;
}
for ( unsigned k = 0; k < models.size(); k++ )
{
// 2. progress the 2 models and
std::vector<int> model_1 = models[k];
std::vector<int> model_2 = models[k];
for (int p = (prefix_1.size()-1); p >= 0; p--)
{
std::vector<PDDL::Operator*>& ops =
sm_task.useful_ops()[prefix_1[p]]->same_op_vec();
update_single_model(ops, model_1 );
}
for (int p = (prefix_2.size()-1); p >= 0; p--)
{
std::vector<PDDL::Operator*>& ops =
sm_task.useful_ops()[prefix_2[p]]->same_op_vec();
update_single_model(ops, model_2 );
}
// 3. compare them
for ( unsigned f = 1; f < (unsigned)(sm_task.fluent_count()-1); f++ )
{
if ( std::sgn(model_1[f]) != std::sgn(model_2[f]) )
return false;
}
}
return true;
}
bool SearchNode::is_equal( SearchNode& o, std::vector< std::vector<int> >& models )
{
Planner_Stats& stats = Planner_Stats::instance();
//AA: no SAT calls to check entailment
if ( NO_SAT_CALLS && !stats.is_width_1())
return false;
if ( *b != *(o.b) ) return false;
if ( !same_models( o, models ) ) return false;
if ( stats.is_width_1() ) return true;
return check_entailment(o);
}
// bool SearchNode::same_models( SearchNode& o )
// {
// for ( unsigned k = 0; k < models.size(); k++ )
// {
// for ( unsigned f = 1; f < (unsigned)(sm_task.fluent_count()-1); f++ )
// {
// if ( std::sgn(models[k][f]) != std::sgn(o.models[k][f]) )
// return false;
// }
// }
// return true;
// }
bool SearchNode::check_entailment( SearchNode& o )
{
#ifdef DEBUG
std::cout << "CHECKING ENTAILMENT to AVOID repeated STATES" << std::endl;
#endif
if ( gn == 0 && o.gn == 0 ) return true;
Planner_Stats& stats = Planner_Stats::instance();
MiniSAT solver( this, &o );
stats.notify_entailment_test();
if ( solver.solve() ) return false;
return true;
}
}
| 27.233111 | 118 | 0.554521 | [
"vector",
"model"
] |
0d845bda8db934b7f425ff42d3eebe8755ac71b2 | 15,042 | cpp | C++ | src/ukf.cpp | olbedo/CarND-Unscented-Kalman-Filter | caa4582bec1fc00534f258c60ca98073c4adda35 | [
"MIT"
] | null | null | null | src/ukf.cpp | olbedo/CarND-Unscented-Kalman-Filter | caa4582bec1fc00534f258c60ca98073c4adda35 | [
"MIT"
] | null | null | null | src/ukf.cpp | olbedo/CarND-Unscented-Kalman-Filter | caa4582bec1fc00534f258c60ca98073c4adda35 | [
"MIT"
] | null | null | null | #include "ukf.h"
#include "Eigen/Dense"
#include <iostream>
using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::vector;
/**
* Initializes Unscented Kalman filter
* This is scaffolding, do not modify
*/
UKF::UKF() {
// if this is false, laser measurements will be ignored (except during init)
use_laser_ = true;
// if this is false, radar measurements will be ignored (except during init)
use_radar_ = true;
// initial state vector
x_ = VectorXd(5);
// initial covariance matrix
P_ = MatrixXd(5, 5);
// Process noise standard deviation longitudinal acceleration in m/s^2
std_a_ = 1;
// Process noise standard deviation yaw acceleration in rad/s^2
std_yawdd_ = 1;
//DO NOT MODIFY measurement noise values below these are provided by the sensor manufacturer.
// Laser measurement noise standard deviation position1 in m
std_laspx_ = 0.15;
// Laser measurement noise standard deviation position2 in m
std_laspy_ = 0.15;
// Radar measurement noise standard deviation radius in m
std_radr_ = 0.3;
// Radar measurement noise standard deviation angle in rad
std_radphi_ = 0.03;
// Radar measurement noise standard deviation radius change in m/s
std_radrd_ = 0.3;
//DO NOT MODIFY measurement noise values above these are provided by the sensor manufacturer.
/**
TODO:
Complete the initialization. See ukf.h for other member properties.
Hint: one or more values initialized above might be wildly off...
*/
///* initially set to false, set to true in first call of ProcessMeasurement
is_initialized_ = false;
///* time when the state is true, in us
time_us_ = 0;
///* State dimension
n_x_ = x_.size();
///* Augmented state dimension
n_aug_ = 7;
///* Number of sigma points
n_sig_ = 2 * n_aug_ + 1;
///* Sigma point spreading parameter
lambda_ = 3 - n_aug_;
///* predicted sigma points matrix
Xsig_pred_ = MatrixXd(n_x_, n_sig_);
///* Weights of sigma points
weights_ = VectorXd(n_sig_);
///* Normalized Innovation Squared (NIS)
nis_lidar_ = 0.0;
nis_radar_ = 0.0;
}
UKF::~UKF() {}
/**
* @param {MeasurementPackage} meas_package The latest measurement data of
* either radar or laser.
*/
void UKF::ProcessMeasurement(MeasurementPackage meas_package) {
/**
TODO:
Complete this function! Make sure you switch between lidar and radar
measurements.
*/
/*****************************************************************************
* Initialization
****************************************************************************/
if (!is_initialized_) {
// first measurement
//cout << "Initialization: " << endl;
double var_px = 1.0;
double var_py = 1.0;
double var_v = 0.35;
double var_psi = 0.01;
double var_psidot = 0.40;
if (meas_package.sensor_type_ == MeasurementPackage::RADAR) {
/**
Convert radar from polar to cartesian coordinates and initialize state.
*/
float rho = meas_package.raw_measurements_[0];
float phi = meas_package.raw_measurements_[1];
float rho_dot = meas_package.raw_measurements_[2];
//float vx = rho_dot * cos(phi);
//float vy = rho_dot * sin(phi);
x_[0] = rho * cos(phi); // px
x_[1] = rho * sin(phi); // py
x_[2] = 5; // v
x_[3] = 0; // psi
x_[4] = 0; // psi_dot
// variance
var_px = std_laspx_ * std_laspx_;
var_py = std_laspy_ * std_laspy_;
}
else if (meas_package.sensor_type_ == MeasurementPackage::LASER) {
/**
Initialize state.
*/
//set the state with the initial location and zero velocity
x_ << meas_package.raw_measurements_[0], meas_package.raw_measurements_[1], 5, 0, 0;
// variance
var_px = std_radr_ * std_radr_; //cos(std_radphi_);
var_py = std_radr_ * std_radr_; //sin(std_radphi_);
}
//state covariance matrix P
P_ << var_px, 0, 0, 0, 0,
0, var_py, 0, 0, 0,
0, 0, var_v, 0, 0,
0, 0, 0, var_psi, 0,
0, 0, 0, 0, var_psidot;
//store time stamp of measurement in micro seconds
time_us_ = meas_package.timestamp_;
// done initializing, no need to predict or update
is_initialized_ = true;
return;
}
/*****************************************************************************
* Prediction
****************************************************************************/
//compute the time elapsed between the current and previous measurements
double delta_t = (meas_package.timestamp_ - time_us_) / 1000000.0; //dt - expressed in seconds
time_us_ = meas_package.timestamp_;
//predict
//cout << "Predict: " << endl;
Prediction(delta_t);
/*****************************************************************************
* Update
****************************************************************************/
//cout << "Update: " << endl;
if (meas_package.sensor_type_ == MeasurementPackage::RADAR) {
// Radar updates
if (use_radar_) {
UpdateRadar(meas_package);
}
} else {
// Laser updates
if (use_laser_) {
UpdateLidar(meas_package);
}
}
// print the output
cout << "x_ = " << x_ << endl;
cout << "P_ = " << P_ << endl;
}
/**
* Predicts sigma points, the state, and the state covariance matrix.
* @param {double} delta_t the change in time (in seconds) between the last
* measurement and this one.
*/
void UKF::Prediction(double delta_t) {
/**
TODO:
Complete this function! Estimate the object's location. Modify the state
vector, x_. Predict sigma points, the state, and the state covariance matrix.
*/
/* Generate sigma points
****************************************************************************/
//cout << "Generate sigma points: " << endl;
//create augmented mean state
VectorXd x_aug = VectorXd(n_aug_);
x_aug.head(5) = x_;
x_aug(5) = 0;
x_aug(6) = 0;
//create augmented covariance matrix
MatrixXd P_aug = MatrixXd(n_aug_, n_aug_);
P_aug.fill(0.0);
P_aug.topLeftCorner(n_x_,n_x_) = P_;
P_aug(5,5) = std_a_ * std_a_;
P_aug(6,6) = std_yawdd_ * std_yawdd_;
//create square root matrix
MatrixXd L = P_aug.llt().matrixL();
//create augmented sigma points
MatrixXd Xsig_aug = MatrixXd(n_aug_, n_sig_);
Xsig_aug.col(0) = x_aug;
//set remaining sigma points
for (int j = 0; j < n_aug_; j++) {
Xsig_aug.col(j+1) = x_aug + sqrt(lambda_+n_aug_) * L.col(j);
Xsig_aug.col(j+1+n_aug_) = x_aug - sqrt(lambda_+n_aug_) * L.col(j);
}
/* Predict augmented sigma points
****************************************************************************/
//cout << "Predict augmented sigma points: " << endl;
VectorXd noise = VectorXd(n_x_);
// iterate over sigma points
for (int j = 0; j < n_sig_; j++) {
// get current sigma point
double p_x = Xsig_aug(0,j);
double p_y = Xsig_aug(1,j);
double v = Xsig_aug(2,j);
double psi = Xsig_aug(3,j);
double psi_dot = Xsig_aug(4,j);
double ny_a = Xsig_aug(5,j);
double ny_psi_dot = Xsig_aug(6,j);
// do some pre-calculations
double sin_psi = sin(psi);
double cos_psi = cos(psi);
double half_dt_squared = 0.5 * delta_t * delta_t;
double t1 = half_dt_squared * ny_a;
// calculate noise
noise(0) = t1 * cos_psi;
noise(1) = t1 * sin_psi;
noise(2) = delta_t * ny_a;
noise(3) = half_dt_squared * ny_psi_dot;
noise(4) = delta_t * ny_psi_dot;
// predict sigma points - avoid division by zero
if (fabs(psi_dot) >= 0.00001) {
double t2 = v/psi_dot;
double psi_dot_dt = psi_dot * delta_t;
double t3 = psi + psi_dot_dt;
Xsig_pred_(0,j) = p_x + t2 * (sin(t3) - sin_psi) + noise(0);
Xsig_pred_(1,j) = p_y + t2 * (cos_psi - cos(t3)) + noise(1);
Xsig_pred_(2,j) = v + noise(2);
Xsig_pred_(3,j) = psi + psi_dot_dt + noise(3);
Xsig_pred_(4,j) = psi_dot + noise(4);
} else {
Xsig_pred_(0,j) = p_x + v * cos_psi * delta_t + noise(0);
Xsig_pred_(1,j) = p_y + v * sin_psi * delta_t + noise(1);
Xsig_pred_(2,j) = v + noise(2);
Xsig_pred_(3,j) = psi + noise(3);
Xsig_pred_(4,j) = noise(4);
}
}
/* Predict mean and covariance
****************************************************************************/
//cout << "Predict mean and covariance: " << endl;
//set weights
weights_(0) = lambda_ / (lambda_ + n_aug_);
weights_(1) = 0.5 / (lambda_ + n_aug_);
for (int j = 2; j < n_sig_; j++) {
weights_(j) = weights_(1);
}
//predict state mean
x_ = weights_(0) * Xsig_pred_.col(0);
//iterate over sigma points
for (int j = 1; j < n_sig_; j++) {
x_ += weights_(j) * Xsig_pred_.col(j);
}
//predict state covariance matrix
P_.fill(0.0);
//iterate over sigma points
for (int j = 0; j < n_sig_; j++) {
// state difference
VectorXd x_diff = Xsig_pred_.col(j) - x_;
//angle normalization
while ( x_diff(3) > M_PI ) x_diff(3) -= 2. * M_PI;
while ( x_diff(3) < -M_PI ) x_diff(3) += 2. * M_PI;
//predict state covariance
P_ += weights_(j) * x_diff * x_diff.transpose() ;
}
}
/**
* Updates the state and the state covariance matrix using a laser measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateLidar(MeasurementPackage meas_package) {
/**
TODO:
Complete this function! Use lidar data to update the belief about the object's
position. Modify the state vector, x_, and covariance, P_.
You'll also need to calculate the lidar NIS.
*/
int n_z = 2;
/* Predict measurement
****************************************************************************/
//create matrix for sigma points in measurement space
MatrixXd Zsig = MatrixXd(n_z, n_sig_);
Zsig = Xsig_pred_.topRows(n_z); // px & py
//calculate mean predicted measurement
VectorXd z_pred = VectorXd(n_z);
z_pred = Zsig * weights_;
//calculate innovation covariance matrix S
MatrixXd S = MatrixXd(n_z,n_z);
S.fill(0.);
//iterate over sigma points
for (int j = 0; j < n_sig_; j++) {
// residual
VectorXd z_diff = Zsig.col(j) - z_pred;
//calculate innovation covariance
S += weights_(j) * z_diff * z_diff.transpose();
}
// determine measurement noise covariance
MatrixXd R = MatrixXd(n_z,n_z);
R.fill(0.0);
R(0,0) = std_laspx_ * std_laspx_;
R(1,1) = std_laspy_ * std_laspy_;
S += R;
/* Update state
****************************************************************************/
//calculate cross correlation matrix
MatrixXd Tc = MatrixXd(n_x_, n_z);
Tc.fill(0.0);
//iterate over sigma points
for (int j = 0; j < n_sig_; j++) {
// residual
VectorXd z_diff = Zsig.col(j) - z_pred;
// state difference
VectorXd x_diff = Xsig_pred_.col(j) - x_;
//angle normalization
while ( x_diff(3) > M_PI ) x_diff(3) -= 2. * M_PI;
while ( x_diff(3) < -M_PI ) x_diff(3) += 2. * M_PI;
//calculate cross correlation
Tc += weights_(j) * x_diff * z_diff.transpose();
}
//calculate Kalman gain K;
MatrixXd S_inv = S.inverse();
MatrixXd K = Tc * S_inv;
//update state mean and covariance matrix
// residual
VectorXd z_diff = meas_package.raw_measurements_ - z_pred;
x_ += K * z_diff;
P_ -= K * S * K.transpose();
/* Calculate Normalized Innovation Squared (NIS)
****************************************************************************/
nis_lidar_ = z_diff.transpose() * S_inv * z_diff;
//cout << "NIS_lidar: " << nis_lidar_ << endl;
}
/**
* Updates the state and the state covariance matrix using a radar measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateRadar(MeasurementPackage meas_package) {
/**
TODO:
Complete this function! Use radar data to update the belief about the object's
position. Modify the state vector, x_, and covariance, P_.
You'll also need to calculate the radar NIS.
*/
int n_z = 3;
/* Predict measurement
****************************************************************************/
//create matrix for sigma points in measurement space
MatrixXd Zsig = MatrixXd(n_z, n_sig_);
//transform sigma points into measurement space
//iterate over sigma points
for (int j = 0; j < n_sig_; j++) {
double px = Xsig_pred_(0,j);
double py = Xsig_pred_(1,j);
double v = Xsig_pred_(2,j);
double psi = Xsig_pred_(3,j);
// convert to polar coordinates
double rho = sqrt(px * px + py * py);
Zsig(0,j) = rho;
Zsig(1,j) = atan2(py, px); // phi
if (fabs(rho) < 0.0001) {
Zsig(2,j) = 0; // rho_dot
} else {
Zsig(2,j) = (px * cos(psi) * v + py * sin(psi) * v) / rho;
}
}
//calculate mean predicted measurement
VectorXd z_pred = VectorXd(n_z);
z_pred = Zsig * weights_;
//calculate innovation covariance matrix S
MatrixXd S = MatrixXd(n_z,n_z);
S.fill(0.);
//iterate over sigma points
for (int j = 0; j < n_sig_; j++) {
// residual
VectorXd z_diff = Zsig.col(j) - z_pred;
//angle normalization
while ( z_diff(1) > M_PI ) z_diff(1) -= 2.*M_PI;
while ( z_diff(1) < -M_PI ) z_diff(1) += 2.*M_PI;
//calculate innovation covariance
S += weights_(j) * z_diff * z_diff.transpose();
}
// determine measurement noise covariance
MatrixXd R = MatrixXd(n_z,n_z);
R.fill(0.0);
R(0,0) = std_radr_ * std_radr_;
R(1,1) = std_radphi_ * std_radphi_;
R(2,2) = std_radrd_ * std_radrd_;
S += R;
/* Update state
****************************************************************************/
//calculate cross correlation matrix
MatrixXd Tc = MatrixXd(n_x_, n_z);
Tc.fill(0.0);
//iterate over sigma points
for (int j = 0; j < n_sig_; j++) {
// residual
VectorXd z_diff = Zsig.col(j) - z_pred;
//angle normalization
while ( z_diff(1) > M_PI ) z_diff(1) -= 2. * M_PI;
while ( z_diff(1) < -M_PI ) z_diff(1) += 2. * M_PI;
// state difference
VectorXd x_diff = Xsig_pred_.col(j) - x_;
//angle normalization
while ( x_diff(3) > M_PI ) x_diff(3) -= 2. * M_PI;
while ( x_diff(3) < -M_PI ) x_diff(3) += 2. * M_PI;
//calculate cross correlation
Tc += weights_(j) * x_diff * z_diff.transpose();
}
//calculate Kalman gain K;
MatrixXd S_inv = S.inverse();
MatrixXd K = Tc * S_inv;
//update state mean and covariance matrix
// residual
VectorXd z_diff = meas_package.raw_measurements_ - z_pred;
//angle normalization
while ( z_diff(1) > M_PI ) z_diff(1) -= 2. * M_PI;
while ( z_diff(1) < -M_PI ) z_diff(1) += 2. * M_PI;
x_ += K * z_diff;
P_ -= K * S * K.transpose();
/* Calculate Normalized Innovation Squared (NIS)
****************************************************************************/
nis_radar_ = z_diff.transpose() * S_inv * z_diff;
//cout << "NIS_radar: " << nis_radar_ << endl;
}
| 29.727273 | 96 | 0.576785 | [
"object",
"vector",
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.