<commit_before>#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <libaws/aws.h>

using namespace aws;

bool
listQueues (SQSConnectionPtr aSQS, std::string aQueueNamePrefix = "") {
  try {
      ListQueuesResponsePtr lRes = aSQS->listQueues (aQueueNamePrefix);
      std::cout << "queues listed sucessfully" << std::endl;
      lRes->open();
      std::string lQueueURL;
      while (lRes->next (lQueueURL)) {
        std::cout << "   Queue Name: " << lQueueURL << "\n";
        }
      lRes->close();
    } catch (CreateBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool createQueue (SQSConnectionPtr aSQS, std::string aQueueName, int aVisibilityTimeout) {
  try {
      CreateQueueResponsePtr lRes = aSQS->createQueue (aQueueName, aVisibilityTimeout);
      std::cout << "queue created successfully" << std::endl;
      std::cout << "   url: "  << lRes->getQueueUrl() << std::endl;
    } catch (CreateBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteQueue (SQSConnectionPtr aSQS, std::string aQueueName) {
  try {
      DeleteQueueResponsePtr lRes = aSQS->deleteQueue (aQueueName);
      std::cout << "queue deleted successfully" << std::endl;
    } catch (CreateBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteAllQueues (SQSConnectionPtr aSQS) {
  try {
      std::cout << "start deleting queues:" << std::endl;
      ListQueuesResponsePtr lListQueues = aSQS->listQueues();
      lListQueues->open();
      std::string lQueueURL;
      while (lListQueues->next (lQueueURL)) {
          DeleteQueueResponsePtr lDelete = aSQS->deleteQueue (lQueueURL);
          std::cout << "    deleted queue: " << lQueueURL << std::endl;
        }
      lListQueues->close();
      std::cout << "all queues successfully deleted." << std::endl;
    } catch (ListBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool sendMessage (SQSConnectionPtr aSQS, std::string aQueueName, std::string aMessage) {
  try {
      SendMessageResponsePtr lRes = aSQS->sendMessage (aQueueName, aMessage);
      std::cout << "send message successfully" << std::endl;
      std::cout << "   url: ["  << lRes->getMessageId() << std::endl;
      std::cout << "   md5: ["  << lRes->getMD5OfMessageBody() << std::endl;
    } catch (CreateBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool receiveMessage (SQSConnectionPtr aSQS, std::string aQueueName,  int aMaxNbMessages, int aVisibilityTimeout) {
  try {
      ReceiveMessageResponsePtr lReceiveMessages = aSQS->receiveMessage (aQueueName, aMaxNbMessages, aVisibilityTimeout);
      lReceiveMessages->open();
      ReceiveMessageResponse::Message lMessage;
      std::cout << "received messages:" << std::endl;
      int lNb = 0;
      while (lReceiveMessages->next (lMessage)) {
          std::cout << "  Message Nb. " << lNb++ << std::endl;
          std::cout << "    message-id: [" << lMessage.message_id << "]" << std::endl;
          std::cout << "    message-handle: [" << lMessage.receipt_handle << "]"<< std::endl;
          std::cout << "    message-md5: [" << lMessage.message_md5 << "]" << std::endl;
          std::cout << "    message-size: [" << lMessage.message_size << "]" << std::endl;
          std::cout << "    message-content: [";
          std::cout.write (lMessage.message_body, lMessage.message_size);
          std::cout << "]" << std::endl;
        }
      lReceiveMessages->close();
    } catch (ListBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteMessage (SQSConnectionPtr aSQS, std::string aQueueName, std::string aReceiptHandle) {
  try {
      DeleteMessageResponsePtr lRes = aSQS->deleteMessage (aQueueName, aReceiptHandle);
      std::cout << "deleted message successfully" << std::endl;
    } catch (CreateBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteAllMessages (SQSConnectionPtr aSQS, std::string aQueueName) {
  try {
      bool lMessagesReceived = true;
      ReceiveMessageResponse::Message lMessage;
      ReceiveMessageResponsePtr lReceiveMessages;

      while (lMessagesReceived) {
          lMessagesReceived = false;
          lReceiveMessages = aSQS->receiveMessage (aQueueName);
          lReceiveMessages->open();
          std::cout << "start deleting messages:" << std::endl;
          while (lReceiveMessages->next (lMessage)) {
              lMessagesReceived = true;
              std::cout << "   message-id: [" << lMessage.message_id  << "]" << std::endl;
              DeleteMessageResponsePtr lDelRes = aSQS->deleteMessage (aQueueName, lMessage.receipt_handle);
            }
          lReceiveMessages->close();
        }

      std::cout << "deleted messages successfully" << std::endl;
    } catch (CreateBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

int
main (int argc, char** argv) {
  char* lAction = 0;
  char* lQueueName = 0;
  char* lPrefix = 0;
  int   lMaxNbMessages = -1;
  char* lMessage = 0;
  int   lVisibilityTimeOut = -1;
  char* lAccessKeyId = 0;
  char* lSecretAccessKey = 0;
  char* lReceiptHandle = 0;
  char* lHost = 0;

  int c;
  opterr = 0;

  AWSConnectionFactory* lFactory = AWSConnectionFactory::getInstance();

  while ( (c = getopt (argc, argv, "hi:s:a:n:p:x:m:r:")) != -1)
    switch (c) {
      case 'i':
        lAccessKeyId = optarg;
        break;
      case 's':
        lSecretAccessKey = optarg;
        break;
      case 'a':
        lAction = optarg;
        break;
      case 'o':
      	lHost = optarg;
      	break;
      case 'n':
        lQueueName = optarg;
        break;
      case 'p':
        lPrefix = optarg;
        break;
      case 'x':
        lMaxNbMessages = atoi (optarg);
        break;
      case 'm':
        lMessage = optarg;
        break;
      case 'v':
        lVisibilityTimeOut = atoi (optarg);
        break;
      case 'r':
        lReceiptHandle = optarg;
        break;
      case 'h': {
          std::cout << "libaws version " << lFactory->getVersion() << std::endl;
          std::cout << "Usage: sqs <options>" << std::endl;
          std::cout << "  -i: AWS Access Key Id"  << std::endl;
          std::cout << "  -s: AWS Secret Access Key"  << std::endl;
          std::cout << "  -a action: Action to perform" << std::endl;
          std::cout << "             list-queues: List all queues" << std::endl;
          std::cout << "             create-queue: Create a queue" << std::endl;
          std::cout << "             delete-queue: Delete a queue" << std::endl;
          std::cout << "             delete-all-queues: Delete all queues" << std::endl;
          std::cout << "             send-message: Send a message" << std::endl;
          std::cout << "             list-message: Receive messages" << std::endl;
          std::cout << "             delete-message: Delete messages" << std::endl;
          std::cout << "             delete-all-messages: Delete all messages retrieved" << std::endl;
          std::cout << "  -o: host name"  << std::endl;
          std::cout << "  -n name: A Queue Name/URL"  << std::endl;
          std::cout << "  -p prefix: Prefix for listing queues"  << std::endl;
          std::cout << "  -x #messages: Number of messages to return"  << std::endl;
          std::cout << "  -m message: the message to send" << std::endl;
          std::cout << "  -v visibility timeout: the visibility timeout" << std::endl;
          std::cout << "  -r receipt-handle: the receipt-handle" << std::endl;
          std::cout << "  -h help: display help" << std::endl;
          exit (1);
        }
      case '?':
        if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        exit (1);
      default:
        exit (1);
      }

  if (!lAccessKeyId) {
    lAccessKeyId = getenv ("AWS_ACCESS_KEY");
  }

  if (!lSecretAccessKey) {
    lSecretAccessKey = getenv ("AWS_SECRET_ACCESS_KEY");
  }

  if (!lHost) {
  	lHost = getenv ("SQS_HOST");
  }

  if (!lAccessKeyId) {
		std::cerr << "No Access Key given" << std::endl;
		std::cerr << "Either use -i as a command line argument or set AWS_ACCESS_KEY as an environmental variable" << std::endl;
		exit (1);
	}

  if (!lSecretAccessKey) {
		std::cerr << "No Secret Access Key given" << std::endl;
		std::cerr << "Either use -s as a command line argument or set AWS_SECRET_ACCESS_KEY as an environmental variable" << std::endl;
		exit (1);
	}

  SQSConnectionPtr lSQSRest;
  if (!lHost) {
  	lSQSRest = lFactory->createSQSConnection (lAccessKeyId, lSecretAccessKey);
  }
  else {
    // aPort = -1 -> we have specified our own
    // aIsSecure = false -> we would like http instead of https
  	lSQSRest = lFactory->createSQSConnection(lAccessKeyId, lSecretAccessKey, lHost, -1, false);
  }

  if (!lAction) {
      std::cerr << "No Action parameter specified." << std::endl;
      std::cerr << "Use -a as a command line argument" << std::endl;
      exit (1);
    }
  std::string lActionString (lAction);

  if (lActionString.compare ("list-queues") == 0) {
      listQueues (lSQSRest, lPrefix == 0 ? "" : lPrefix);
    } else if (lActionString.compare ("create-queue") == 0) {
      if (!lQueueName) {
          std::cerr << "No queue name parameter specified." << std::endl;
          std::cerr << "Use -n as a command line argument" << std::endl;
          exit (1);
        }
      createQueue (lSQSRest, lQueueName, lVisibilityTimeOut);
    } else if (lActionString.compare ("delete-queue") == 0) {
      if (!lQueueName) {
          std::cerr << "No queue name parameter specified." << std::endl;
          std::cerr << "Use -n as a command line argument" << std::endl;
          exit (1);
        }
        deleteQueue (lSQSRest, lQueueName);
    } else if (lActionString.compare ("delete-all-queues") == 0) {
      deleteAllQueues (lSQSRest);
    } else if (lActionString.compare ("send-message") == 0) {
      if (!lQueueName) {
          std::cerr << "No queue name parameter specified." << std::endl;
          std::cerr << "Use -n as a command line argument" << std::endl;
          exit (1);
        }
      if (!lMessage) {
          std::cerr << "No message parameter specified." << std::endl;
          std::cerr << "Use -m as a command line argument" << std::endl;
          exit (1);
        }
      sendMessage (lSQSRest, lQueueName, lMessage);
    } else if (lActionString.compare ("list-messages") == 0 || lActionString.compare ("list-message") == 0) {
      if (!lQueueName) {
          std::cerr << "No queue name parameter specified." << std::endl;
          std::cerr << "Use -n as a command line argument" << std::endl;
          exit (1);
        }
      receiveMessage (lSQSRest, lQueueName, lMaxNbMessages, lVisibilityTimeOut);
    } else if (lActionString.compare ("delete-message") == 0) {
      if (!lQueueName) {
          std::cerr << "No queue name parameter specified." << std::endl;
          std::cerr << "Use -n as a command line argument" << std::endl;
          exit (1);
        }
      if (!lReceiptHandle) {
          std::cerr << "No receipt handle parameter specified." << std::endl;
          std::cerr << "Use -r as a command line argument" << std::endl;
          exit (1);
        }
      deleteMessage (lSQSRest, lQueueName, lReceiptHandle);
    } else if (lActionString.compare ("delete-all-messages") == 0) {
      if (!lQueueName) {
          std::cerr << "No queue name parameter specified." << std::endl;
          std::cerr << "Use -n as a command line argument" << std::endl;
          exit (1);
        }
      deleteAllMessages (lSQSRest, lQueueName);
    } else {
      std::cerr << "Command not recognized." << std::endl;
      exit(1);
    }

}

<commit_msg>fixed typo in help<commit_after>#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <libaws/aws.h>

using namespace aws;

bool
listQueues (SQSConnectionPtr aSQS, std::string aQueueNamePrefix = "") {
  try {
      ListQueuesResponsePtr lRes = aSQS->listQueues (aQueueNamePrefix);
      std::cout << "queues listed sucessfully" << std::endl;
      lRes->open();
      std::string lQueueURL;
      while (lRes->next (lQueueURL)) {
        std::cout << "   Queue Name: " << lQueueURL << "\n";
        }
      lRes->close();
    } catch (CreateBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool createQueue (SQSConnectionPtr aSQS, std::string aQueueName, int aVisibilityTimeout) {
  try {
      CreateQueueResponsePtr lRes = aSQS->createQueue (aQueueName, aVisibilityTimeout);
      std::cout << "queue created successfully" << std::endl;
      std::cout << "   url: "  << lRes->getQueueUrl() << std::endl;
    } catch (CreateBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteQueue (SQSConnectionPtr aSQS, std::string aQueueName) {
  try {
      DeleteQueueResponsePtr lRes = aSQS->deleteQueue (aQueueName);
      std::cout << "queue deleted successfully" << std::endl;
    } catch (CreateBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteAllQueues (SQSConnectionPtr aSQS) {
  try {
      std::cout << "start deleting queues:" << std::endl;
      ListQueuesResponsePtr lListQueues = aSQS->listQueues();
      lListQueues->open();
      std::string lQueueURL;
      while (lListQueues->next (lQueueURL)) {
          DeleteQueueResponsePtr lDelete = aSQS->deleteQueue (lQueueURL);
          std::cout << "    deleted queue: " << lQueueURL << std::endl;
        }
      lListQueues->close();
      std::cout << "all queues successfully deleted." << std::endl;
    } catch (ListBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool sendMessage (SQSConnectionPtr aSQS, std::string aQueueName, std::string aMessage) {
  try {
      SendMessageResponsePtr lRes = aSQS->sendMessage (aQueueName, aMessage);
      std::cout << "send message successfully" << std::endl;
      std::cout << "   url: ["  << lRes->getMessageId() << std::endl;
      std::cout << "   md5: ["  << lRes->getMD5OfMessageBody() << std::endl;
    } catch (CreateBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool receiveMessage (SQSConnectionPtr aSQS, std::string aQueueName,  int aMaxNbMessages, int aVisibilityTimeout) {
  try {
      ReceiveMessageResponsePtr lReceiveMessages = aSQS->receiveMessage (aQueueName, aMaxNbMessages, aVisibilityTimeout);
      lReceiveMessages->open();
      ReceiveMessageResponse::Message lMessage;
      std::cout << "received messages:" << std::endl;
      int lNb = 0;
      while (lReceiveMessages->next (lMessage)) {
          std::cout << "  Message Nb. " << lNb++ << std::endl;
          std::cout << "    message-id: [" << lMessage.message_id << "]" << std::endl;
          std::cout << "    message-handle: [" << lMessage.receipt_handle << "]"<< std::endl;
          std::cout << "    message-md5: [" << lMessage.message_md5 << "]" << std::endl;
          std::cout << "    message-size: [" << lMessage.message_size << "]" << std::endl;
          std::cout << "    message-content: [";
          std::cout.write (lMessage.message_body, lMessage.message_size);
          std::cout << "]" << std::endl;
        }
      lReceiveMessages->close();
    } catch (ListBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteMessage (SQSConnectionPtr aSQS, std::string aQueueName, std::string aReceiptHandle) {
  try {
      DeleteMessageResponsePtr lRes = aSQS->deleteMessage (aQueueName, aReceiptHandle);
      std::cout << "deleted message successfully" << std::endl;
    } catch (CreateBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteAllMessages (SQSConnectionPtr aSQS, std::string aQueueName) {
  try {
      bool lMessagesReceived = true;
      ReceiveMessageResponse::Message lMessage;
      ReceiveMessageResponsePtr lReceiveMessages;

      while (lMessagesReceived) {
          lMessagesReceived = false;
          lReceiveMessages = aSQS->receiveMessage (aQueueName);
          lReceiveMessages->open();
          std::cout << "start deleting messages:" << std::endl;
          while (lReceiveMessages->next (lMessage)) {
              lMessagesReceived = true;
              std::cout << "   message-id: [" << lMessage.message_id  << "]" << std::endl;
              DeleteMessageResponsePtr lDelRes = aSQS->deleteMessage (aQueueName, lMessage.receipt_handle);
            }
          lReceiveMessages->close();
        }

      std::cout << "deleted messages successfully" << std::endl;
    } catch (CreateBucketException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

int
main (int argc, char** argv) {
  char* lAction = 0;
  char* lQueueName = 0;
  char* lPrefix = 0;
  int   lMaxNbMessages = -1;
  char* lMessage = 0;
  int   lVisibilityTimeOut = -1;
  char* lAccessKeyId = 0;
  char* lSecretAccessKey = 0;
  char* lReceiptHandle = 0;
  char* lHost = 0;

  int c;
  opterr = 0;

  AWSConnectionFactory* lFactory = AWSConnectionFactory::getInstance();

  while ( (c = getopt (argc, argv, "hi:s:a:n:p:x:m:r:")) != -1)
    switch (c) {
      case 'i':
        lAccessKeyId = optarg;
        break;
      case 's':
        lSecretAccessKey = optarg;
        break;
      case 'a':
        lAction = optarg;
        break;
      case 'o':
      	lHost = optarg;
      	break;
      case 'n':
        lQueueName = optarg;
        break;
      case 'p':
        lPrefix = optarg;
        break;
      case 'x':
        lMaxNbMessages = atoi (optarg);
        break;
      case 'm':
        lMessage = optarg;
        break;
      case 'v':
        lVisibilityTimeOut = atoi (optarg);
        break;
      case 'r':
        lReceiptHandle = optarg;
        break;
      case 'h': {
          std::cout << "libaws version " << lFactory->getVersion() << std::endl;
          std::cout << "Usage: sqs <options>" << std::endl;
          std::cout << "  -i: AWS Access Key Id"  << std::endl;
          std::cout << "  -s: AWS Secret Access Key"  << std::endl;
          std::cout << "  -a action: Action to perform" << std::endl;
          std::cout << "             list-queues: List all queues" << std::endl;
          std::cout << "             create-queue: Create a queue" << std::endl;
          std::cout << "             delete-queue: Delete a queue" << std::endl;
          std::cout << "             delete-all-queues: Delete all queues" << std::endl;
          std::cout << "             send-message: Send a message" << std::endl;
          std::cout << "             list-message: Receive messages" << std::endl;
          std::cout << "             delete-message: Delete messages" << std::endl;
          std::cout << "             delete-all-messages: Delete all messages retrieved" << std::endl;
          std::cout << "  -o host name"  << std::endl;
          std::cout << "  -n name: A Queue Name/URL"  << std::endl;
          std::cout << "  -p prefix: Prefix for listing queues"  << std::endl;
          std::cout << "  -x #messages: Number of messages to return"  << std::endl;
          std::cout << "  -m message: the message to send" << std::endl;
          std::cout << "  -v visibility timeout: the visibility timeout" << std::endl;
          std::cout << "  -r receipt-handle: the receipt-handle" << std::endl;
          std::cout << "  -h help: display help" << std::endl;
          exit (1);
        }
      case '?':
        if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        exit (1);
      default:
        exit (1);
      }

  if (!lAccessKeyId) {
    lAccessKeyId = getenv ("AWS_ACCESS_KEY");
  }

  if (!lSecretAccessKey) {
    lSecretAccessKey = getenv ("AWS_SECRET_ACCESS_KEY");
  }

  if (!lHost) {
  	lHost = getenv ("SQS_HOST");
  }

  if (!lAccessKeyId) {
		std::cerr << "No Access Key given" << std::endl;
		std::cerr << "Either use -i as a command line argument or set AWS_ACCESS_KEY as an environmental variable" << std::endl;
		exit (1);
	}

  if (!lSecretAccessKey) {
		std::cerr << "No Secret Access Key given" << std::endl;
		std::cerr << "Either use -s as a command line argument or set AWS_SECRET_ACCESS_KEY as an environmental variable" << std::endl;
		exit (1);
	}

  SQSConnectionPtr lSQSRest;
  if (!lHost) {
  	lSQSRest = lFactory->createSQSConnection (lAccessKeyId, lSecretAccessKey);
  }
  else {
    // aPort = -1 -> we have specified our own
    // aIsSecure = false -> we would like http instead of https
  	lSQSRest = lFactory->createSQSConnection(lAccessKeyId, lSecretAccessKey, lHost, -1, false);
  }

  if (!lAction) {
      std::cerr << "No Action parameter specified." << std::endl;
      std::cerr << "Use -a as a command line argument" << std::endl;
      exit (1);
    }
  std::string lActionString (lAction);

  if (lActionString.compare ("list-queues") == 0) {
      listQueues (lSQSRest, lPrefix == 0 ? "" : lPrefix);
    } else if (lActionString.compare ("create-queue") == 0) {
      if (!lQueueName) {
          std::cerr << "No queue name parameter specified." << std::endl;
          std::cerr << "Use -n as a command line argument" << std::endl;
          exit (1);
        }
      createQueue (lSQSRest, lQueueName, lVisibilityTimeOut);
    } else if (lActionString.compare ("delete-queue") == 0) {
      if (!lQueueName) {
          std::cerr << "No queue name parameter specified." << std::endl;
          std::cerr << "Use -n as a command line argument" << std::endl;
          exit (1);
        }
        deleteQueue (lSQSRest, lQueueName);
    } else if (lActionString.compare ("delete-all-queues") == 0) {
      deleteAllQueues (lSQSRest);
    } else if (lActionString.compare ("send-message") == 0) {
      if (!lQueueName) {
          std::cerr << "No queue name parameter specified." << std::endl;
          std::cerr << "Use -n as a command line argument" << std::endl;
          exit (1);
        }
      if (!lMessage) {
          std::cerr << "No message parameter specified." << std::endl;
          std::cerr << "Use -m as a command line argument" << std::endl;
          exit (1);
        }
      sendMessage (lSQSRest, lQueueName, lMessage);
    } else if (lActionString.compare ("list-messages") == 0 || lActionString.compare ("list-message") == 0) {
      if (!lQueueName) {
          std::cerr << "No queue name parameter specified." << std::endl;
          std::cerr << "Use -n as a command line argument" << std::endl;
          exit (1);
        }
      receiveMessage (lSQSRest, lQueueName, lMaxNbMessages, lVisibilityTimeOut);
    } else if (lActionString.compare ("delete-message") == 0) {
      if (!lQueueName) {
          std::cerr << "No queue name parameter specified." << std::endl;
          std::cerr << "Use -n as a command line argument" << std::endl;
          exit (1);
        }
      if (!lReceiptHandle) {
          std::cerr << "No receipt handle parameter specified." << std::endl;
          std::cerr << "Use -r as a command line argument" << std::endl;
          exit (1);
        }
      deleteMessage (lSQSRest, lQueueName, lReceiptHandle);
    } else if (lActionString.compare ("delete-all-messages") == 0) {
      if (!lQueueName) {
          std::cerr << "No queue name parameter specified." << std::endl;
          std::cerr << "Use -n as a command line argument" << std::endl;
          exit (1);
        }
      deleteAllMessages (lSQSRest, lQueueName);
    } else {
      std::cerr << "Command not recognized." << std::endl;
      exit(1);
    }

}

<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXQt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2012 Razor team
 * Authors:
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "lxqtthemeconfig.h"
#include "ui_lxqtthemeconfig.h"
#include <QTreeWidget>
#include <QDebug>
#include <QProcess>

LxQtThemeConfig::LxQtThemeConfig(LxQt::Settings *settings, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LxQtThemeConfig),
    mSettings(settings)
{
    ui->setupUi(this);

    connect(ui->lxqtThemeList, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
            this, SLOT(lxqtThemeSelected(QTreeWidgetItem*,int)));

    QList<LxQt::LxQtTheme> themes = LxQt::LxQtTheme::allThemes();
    foreach(LxQt::LxQtTheme theme, themes)
    {
        QTreeWidgetItem *item = new QTreeWidgetItem(QStringList(theme.name()));
        if (!theme.previewImage().isEmpty())
        {
            item->setIcon(0, QIcon(theme.previewImage()));
        }
        item->setSizeHint(0, QSize(42,42)); // make icons non-cropped
        item->setData(0, Qt::UserRole, theme.name());
        ui->lxqtThemeList->addTopLevelItem(item);
    }

    initControls();
}

LxQtThemeConfig::~LxQtThemeConfig()
{
    delete ui;
}

void LxQtThemeConfig::initControls()
{
    QString currentTheme = mSettings->value("theme").toString();

    QTreeWidgetItemIterator it(ui->lxqtThemeList);
    while (*it) {
        if ((*it)->data(0, Qt::UserRole).toString() == currentTheme)
        {
            ui->lxqtThemeList->setCurrentItem((*it));
            break;
        }
        ++it;
    }

    update();
}

void LxQtThemeConfig::lxqtThemeSelected(QTreeWidgetItem* item, int column)
{
    Q_UNUSED(column);
    if (!item)
        return;

    QVariant themeName = item->data(0, Qt::UserRole);
    mSettings->setValue("theme", themeName);

    LxQt::LxQtTheme theme(themeName.toString());
    if(theme.isValid()) {
		QString wallpaper = theme.desktopBackground();
		if(!wallpaper.isEmpty()) {
			// call pcmanfm-qt to update wallpaper
			QProcess process;
			QStringList args;
			args << "--set-wallpaper" << wallpaper;
			process.start("pcmanfm-qt", args, QIODevice::NotOpen);
			process.waitForFinished();
		}
	}
}
<commit_msg>Capitalize themes' names<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXQt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2012 Razor team
 * Authors:
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "lxqtthemeconfig.h"
#include "ui_lxqtthemeconfig.h"
#include <QTreeWidget>
#include <QDebug>
#include <QProcess>

LxQtThemeConfig::LxQtThemeConfig(LxQt::Settings *settings, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LxQtThemeConfig),
    mSettings(settings)
{
    ui->setupUi(this);

    connect(ui->lxqtThemeList, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
            this, SLOT(lxqtThemeSelected(QTreeWidgetItem*,int)));

    QList<LxQt::LxQtTheme> themes = LxQt::LxQtTheme::allThemes();
    foreach(LxQt::LxQtTheme theme, themes)
    {
        QString themeName = theme.name();
        themeName[0] = themeName[0].toTitleCase();
        QTreeWidgetItem *item = new QTreeWidgetItem(QStringList(themeName));
        if (!theme.previewImage().isEmpty())
        {
            item->setIcon(0, QIcon(theme.previewImage()));
        }
        item->setSizeHint(0, QSize(42,42)); // make icons non-cropped
        item->setData(0, Qt::UserRole, theme.name());
        ui->lxqtThemeList->addTopLevelItem(item);
    }

    initControls();
}

LxQtThemeConfig::~LxQtThemeConfig()
{
    delete ui;
}

void LxQtThemeConfig::initControls()
{
    QString currentTheme = mSettings->value("theme").toString();

    QTreeWidgetItemIterator it(ui->lxqtThemeList);
    while (*it) {
        if ((*it)->data(0, Qt::UserRole).toString() == currentTheme)
        {
            ui->lxqtThemeList->setCurrentItem((*it));
            break;
        }
        ++it;
    }

    update();
}

void LxQtThemeConfig::lxqtThemeSelected(QTreeWidgetItem* item, int column)
{
    Q_UNUSED(column);
    if (!item)
        return;

    QVariant themeName = item->data(0, Qt::UserRole);
    mSettings->setValue("theme", themeName);

    LxQt::LxQtTheme theme(themeName.toString());
    if(theme.isValid()) {
		QString wallpaper = theme.desktopBackground();
		if(!wallpaper.isEmpty()) {
			// call pcmanfm-qt to update wallpaper
			QProcess process;
			QStringList args;
			args << "--set-wallpaper" << wallpaper;
			process.start("pcmanfm-qt", args, QIODevice::NotOpen);
			process.waitForFinished();
		}
	}
}
<|endoftext|>


<commit_before>#include <ctime>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include "camera.hpp"

static const int WIDTH = 800;
static const int HEIGHT = 600;
static const int FPS = 10;
static const int DEVICE = 0;
static const std::string DIRECTORY_PATH = "/home/pi/Pictures/";//pathの先頭
static const std::string FILE_EXTENTION = ".jpg";//拡張子

static const int AOV = 62.2;//ANGLE OF VIEW
//明度について
static const int MAX_VALUE = 255;//明るさ最大
static const int NO_VALUE = 0;//明るさ最小

Camera::Camera()
{
	capture.open(DEVICE);
	if (!capture.isOpened())
	{
		std::cout<<"capture is note opened"<<std::endl;
	}
	capture.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH);
	capture.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT);
	capture.set(CV_CAP_PROP_FPS,FPS);
}

Camera::~Camera()
{
	capture.release();
}

int Camera::takePhoto()
{
	makeTimePath();
	cv::Mat frame;
	do
	{
		capture>>frame;
	} while(frame.empty());
	input = frame;
	imwrite(timePath+FILE_EXTENTION,input);
	return 0;
}

//時間を元にtimePathを作る
int Camera::makeTimePath(void)
{
	time_t timer;//時刻を受け取る変数
	struct tm *timeptr;//日時を集めた構造体ポインタ
	char buffer[80];
	time(&timer);//現在時刻の取得
	timeptr = localtime(&timer);//ポインタ
	strftime(buffer, sizeof(buffer), "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してｓに代入
	std::string str(buffer);
	timePath = DIRECTORY_PATH+str;
  return 0;
}

//ノイズ除去
cv::Mat Camera::rmNoize(cv::Mat src)
{
	cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理
	cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理
	cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理
	return src;
}

int Camera::binarize()
{
	cv::Mat hsv;
	cv::Mat hsv_filtered15 ;//画像の初期化
	cv::Mat hsv_filtered180;//画像の初期化
	cv::cvtColor(input, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
	//inRange(入力画像,下界画像,上界画像,出力画像)
	//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
	cv::inRange(hsv, cv::Scalar(0, 70, 60), cv::Scalar(2, 255, MAX_VALUE), hsv_filtered15);
	cv::inRange(hsv, cv::Scalar(160, 70, 60), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);
	cv::add(hsv_filtered15,hsv_filtered180,hsv);
	output = rmNoise(hsv);
	imwrite(timePath+"BINARY"+FILE_EXTENTION,output);
	return 0;
}

//二値化した画像から1の面積を抽出
double Camera::countArea()
{

	double Area = output.rows*output.cols;//全ピクセル数
	double redCount = 0; //赤色を認識したピクセルの数
	redCount = cv::countNonZero(output);//赤色部分の面積を計算
	double percentage = 0; //割合
	percentage = (redCount / Area)*100;//割合を計算
	std::cout<<"面積のPercentageは%"<<percentage<<std::endl;
	return percentage;
}

//二値化画像のcenterを角度で返す
double Camera::getCenter()
{
	cv::Moments mu = cv::moments(output, false);//重心の計算結果をmuに代入
	double mc = mu.m10 / mu.m00;//重心のx座標
	double center = (mc - output.cols / 2) * AOV / output.cols;//正規化
	std::cout<<"重心の位置は"<<center<<std::endl;
	return center;
}
<commit_msg>dbeug<commit_after>#include <ctime>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include "camera.hpp"

static const int WIDTH = 800;
static const int HEIGHT = 600;
static const int FPS = 10;
static const int DEVICE = 0;
static const std::string DIRECTORY_PATH = "/home/pi/Pictures/";//pathの先頭
static const std::string FILE_EXTENTION = ".jpg";//拡張子

static const int AOV = 62.2;//ANGLE OF VIEW
//明度について
static const int MAX_VALUE = 255;//明るさ最大
static const int NO_VALUE = 0;//明るさ最小

Camera::Camera()
{
	capture.open(DEVICE);
	if (!capture.isOpened())
	{
		std::cout<<"capture is note opened"<<std::endl;
	}
	capture.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH);
	capture.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT);
	capture.set(CV_CAP_PROP_FPS,FPS);
}

Camera::~Camera()
{
	capture.release();
}

int Camera::takePhoto()
{
	makeTimePath();
	cv::Mat frame;
	do
	{
		capture>>frame;
	} while(frame.empty());
	input = frame;
	imwrite(timePath+FILE_EXTENTION,input);
	return 0;
}

//時間を元にtimePathを作る
int Camera::makeTimePath(void)
{
	time_t timer;//時刻を受け取る変数
	struct tm *timeptr;//日時を集めた構造体ポインタ
	char buffer[80];
	time(&timer);//現在時刻の取得
	timeptr = localtime(&timer);//ポインタ
	strftime(buffer, sizeof(buffer), "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してｓに代入
	std::string str(buffer);
	timePath = DIRECTORY_PATH+str;
  return 0;
}

//ノイズ除去
cv::Mat Camera::rmNoize(cv::Mat src)
{
	cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理
	cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理
	cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理
	return src;
}

int Camera::binarize()
{
	cv::Mat hsv;
	cv::Mat hsv_filtered15 ;//画像の初期化
	cv::Mat hsv_filtered180;//画像の初期化
	cv::cvtColor(input, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
	//inRange(入力画像,下界画像,上界画像,出力画像)
	//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
	cv::inRange(hsv, cv::Scalar(0, 70, 60), cv::Scalar(2, 255, MAX_VALUE), hsv_filtered15);
	cv::inRange(hsv, cv::Scalar(160, 70, 60), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);
	cv::add(hsv_filtered15,hsv_filtered180,hsv);
	output = Camera::rmNoise(hsv);
	imwrite(timePath+"BINARY"+FILE_EXTENTION,output);
	return 0;
}

//二値化した画像から1の面積を抽出
double Camera::countArea()
{

	double Area = output.rows*output.cols;//全ピクセル数
	double redCount = 0; //赤色を認識したピクセルの数
	redCount = cv::countNonZero(output);//赤色部分の面積を計算
	double percentage = 0; //割合
	percentage = (redCount / Area)*100;//割合を計算
	std::cout<<"面積のPercentageは%"<<percentage<<std::endl;
	return percentage;
}

//二値化画像のcenterを角度で返す
double Camera::getCenter()
{
	cv::Moments mu = cv::moments(output, false);//重心の計算結果をmuに代入
	double mc = mu.m10 / mu.m00;//重心のx座標
	double center = (mc - output.cols / 2) * AOV / output.cols;//正規化
	std::cout<<"重心の位置は"<<center<<std::endl;
	return center;
}
<|endoftext|>


<commit_before>/*
    DOS support for Crystal Space 3D library
    Copyright (C) 1998 by Jorrit Tyberghein
    Written by David N. Arnold <derek_arnold@fuse.net>
    Written by Andrew Zabolotny <bit@eltech.ru>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

/*
 * Written by David N. Arnold. <derek_arnold@fuse.net>
 * 13-07-98:  Andrew Zabolotny <bit@eltech.ru>
 *   - Rewritten video driver; no changes to Allegro support though
 *   - Rewritten keyboard handler
 *   - Rewritten mouse handler
 *   - Did I forgot to rewrite something? :-)
 */

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <dpmi.h>
#include <go32.h>
#include <pc.h>
#include <time.h>
#include <sys/timeb.h>
#include <sys/nearptr.h>
#include <sys/farptr.h>

#include "sysdef.h"
#include "djgpp.h"
#include "csutil/inifile.h"
#include "isystem.h"
#include "inputq.h"
#include "djkeysys.h"
#include "djmousys.h"

static KeyboardHandler KH;
static MouseHandler MH;

static unsigned short ScanCodeToChar[128] =
{
  0,        CSKEY_ESC,'1',      '2',      '3',      '4',      '5',      '6',    // 00..07
  '7',      '8',      '9',      '0',      '-',      '=',      '\b',     '\t',   // 08..0F
  'q',      'w',      'e',      'r',      't',      'y',      'u',      'i',    // 10..17
  'o',      'p',      '[',      ']',      '\n',     CSKEY_CTRL,'a',     's',    // 18..1F
  'd',      'f',      'g',      'h',      'j',      'k',      'l',      ';',    // 20..27
  39,       '`',      CSKEY_SHIFT,'\\',   'z',      'x',      'c',      'v',    // 28..2F
  'b',      'n',      'm',      ',',      '.',      '/',      CSKEY_SHIFT,'*',  // 30..37
  CSKEY_ALT,' ',      0,        CSKEY_F1, CSKEY_F2, CSKEY_F3, CSKEY_F4, CSKEY_F5,// 38..3F
  CSKEY_F6,  CSKEY_F7, CSKEY_F8, CSKEY_F9, CSKEY_F10,0,       0,        CSKEY_HOME,// 40..47
  CSKEY_UP,  CSKEY_PGUP,'-',    CSKEY_LEFT,CSKEY_CENTER,CSKEY_RIGHT,'+',CSKEY_END,// 48..4F
  CSKEY_DOWN,CSKEY_PGDN,CSKEY_INS,CSKEY_DEL,0,      0,        0,        CSKEY_F11,// 50..57
  CSKEY_F12,0,        0,        0,        0,        0,        0,        0,      // 58..5F
  0,        0,        0,        0,        0,        0,        0,        0,      // 60..67
  0,        0,        0,        0,        0,        0,        0,        0,      // 68..6F
  0,        0,        0,        0,        0,        0,        0,        0,      // 70..77
  0,        0,        0,        0,        0,        0,        0,        0       // 78..7F
};

//================================================================== System ====

IMPLEMENT_IBASE (SysSystemDriver)
  IMPLEMENTS_INTERFACE (iSystem)
  IMPLEMENTS_INTERFACE (iDosSystemDriver)
IMPLEMENT_IBASE_END

SysSystemDriver::SysSystemDriver () : csSystemDriver ()
{
  CONSTRUCT_IBASE (NULL);
  // Sanity check
  if (sizeof (event_queue [0]) != 12)
  {
    Printf (MSG_FATAL_ERROR, "ERROR! Your compiler does not handle packed structures!\n");
    Printf (MSG_FATAL_ERROR, "sizeof (event_queue [0]) == %d instead of 12!\n", sizeof (event_queue [0]));
    exit (-1);
  }
}

void SysSystemDriver::Loop ()
{
  while (!Shutdown && !ExitLoop)
  {
    static long prev_time = -1;
    long new_prev_time = Time ();
    NextFrame ((prev_time == -1) ? 0 : new_prev_time - prev_time, Time ());
    prev_time = new_prev_time;

    // Fill in events ...
    while (event_queue_tail != event_queue_head)
    {
      unsigned long time = Time ();
      switch (event_queue [event_queue_tail].Type)
      {
        case 1:
        {
          int ScanCode = event_queue [event_queue_tail].Keyboard.ScanCode;
          bool Down = (ScanCode < 0x80);

          ScanCode = ScanCodeToChar [ScanCode & 0x7F];
          if (ScanCode)
            if (Down)
              Keyboard->do_keypress (time, ScanCode);
            else
              Keyboard->do_keyrelease (time, ScanCode);
          break;
        }
        case 2:
        {
          int Button = event_queue [event_queue_tail].Mouse.Button;
          bool Down = event_queue [event_queue_tail].Mouse.Down;
          int x = event_queue [event_queue_tail].Mouse.x;
          int y = event_queue [event_queue_tail].Mouse.y;

          if (Button == 0)
            Mouse->do_mousemotion (time, x, y);
          else if (Down)
            Mouse->do_buttonpress (time, Button, x, y, Keyboard->Key.shift,
              Keyboard->Key.alt, Keyboard->Key.ctrl);
          else
            Mouse->do_buttonrelease (time, Button, x, y);
          break;
        }
      } /* endswitch */
      event_queue_tail = (event_queue_tail + 1) & EVENT_QUEUE_MASK;
    } /* endwhile */
  } // while (!Shutdown && !ExitLoop)
}

void SysSystemDriver::EnablePrintf (bool Enable)
{
  extern void console_Enable (bool Enable);
  console_Enable (Enable);
}

bool SysSystemDriver::SetMousePosition (int x, int y)
{
  return ((SysMouseDriver *)Mouse)->SetMousePosition (x, y);
}

//================================================================ Keyboard ====

SysKeyboardDriver::SysKeyboardDriver() : csKeyboardDriver ()
{
  KeyboardOpened = false;
}

SysKeyboardDriver::~SysKeyboardDriver(void)
{
  Close();
}

bool SysKeyboardDriver::Open(csEventQueue* EvQueue)
{
  csKeyboardDriver::Open (EvQueue);

  // Initialize keyboard handler
  if (KH.install ())
    return false;
  // Give us exclusive access of the keyboard.
  KH.chain (0);

  KeyboardOpened = true;
  return true;
}

void SysKeyboardDriver::Close(void)
{
  if (KeyboardOpened)
  {
    KH.uninstall ();
    KeyboardOpened = false;
  }
}

//=================================================================== Mouse ====

SysMouseDriver::SysMouseDriver () : csMouseDriver ()
{
  __dpmi_regs regs;
  regs.x.ax = 0x0000;
  __dpmi_int (0x33, &regs);
  MouseExists = !!(regs.x.ax);
  MouseOpened = false;

  SensivityFactor = System->Config->GetFloat ("MouseDriver", "MouseSensivity", 1.0);
}

SysMouseDriver::~SysMouseDriver ()
{
  Close ();
}

bool SysMouseDriver::Open (iSystem* System, csEventQueue *EvQueue)
{
  if (!csMouseDriver::Open (System, EvQueue))
    return false;
  if (MH.install ())
    return false;

  // Query screen size from System object
  int FrameWidth, FrameHeight, Depth;
  bool FullScreen;
  System->GetSettings (FrameWidth, FrameHeight, Depth, FullScreen);

  // Query mouse sensivity
  __dpmi_regs regs;
  regs.x.ax = 0x1B;
  __dpmi_int (0x33, &regs);
  mouse_sensivity_x = regs.x.bx;
  mouse_sensivity_y = regs.x.cx;
  mouse_sensivity_threshold = regs.x.dx;

  // Compute mouse sensivity
  regs.x.cx = 8;
  regs.x.dx = 8;
  regs.x.ax = 0x0F;
  __dpmi_int (0x33, &regs);
  regs.x.bx = (int) ((50 + FrameWidth / 32) * SensivityFactor);
  regs.x.cx = (int) ((50 + FrameHeight / 24) * SensivityFactor);
  regs.x.dx = MAX (regs.x.bx, regs.x.cx); // ? not sure about this
  regs.x.ax = 0x1A;
  __dpmi_int (0x33, &regs);

  // Set mouse range to full-screen
  regs.x.ax = 0x07;
  regs.x.cx = 0;
  regs.x.dx = FrameWidth - 1;
  __dpmi_int (0x33, &regs);
  regs.x.ax = 0x08;
  regs.x.cx = 0;
  regs.x.dx = FrameHeight - 1;
  __dpmi_int (0x33, &regs);

  // Set mouse to (0, 0)
  regs.x.ax = 0x04;
  regs.x.cx = 0;
  regs.x.dx = 0;
  __dpmi_int (0x33, &regs);

  MouseOpened = true;
  return true;
}

void SysMouseDriver::Close ()
{
  if (!MouseOpened)
    return;

  MH.uninstall ();

  // Restore mouse sensivity
  __dpmi_regs regs;
  regs.x.cx = 8;
  regs.x.dx = 16;
  regs.x.ax = 0x0F;
  __dpmi_int (0x33, &regs);
  regs.x.ax = 0x1A;
  regs.x.bx = mouse_sensivity_x;
  regs.x.cx = mouse_sensivity_y;
  regs.x.dx = mouse_sensivity_threshold;
  __dpmi_int (0x33, &regs);

  MouseOpened = false;
}

bool SysMouseDriver::SetMousePosition (int x, int y)
{
  if (!MouseOpened)
    return false;

  __dpmi_regs regs;
  regs.x.cx = x;
  regs.x.dx = y;
  regs.x.ax = 0x04;
  __dpmi_int (0x33, &regs);
  return true;
}
<commit_msg>Changed Key.something into GetKeyState (something)<commit_after>/*
    DOS support for Crystal Space 3D library
    Copyright (C) 1998 by Jorrit Tyberghein
    Written by David N. Arnold <derek_arnold@fuse.net>
    Written by Andrew Zabolotny <bit@eltech.ru>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

/*
 * Written by David N. Arnold. <derek_arnold@fuse.net>
 * 13-07-98:  Andrew Zabolotny <bit@eltech.ru>
 *   - Rewritten video driver; no changes to Allegro support though
 *   - Rewritten keyboard handler
 *   - Rewritten mouse handler
 *   - Did I forgot to rewrite something? :-)
 */

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <dpmi.h>
#include <go32.h>
#include <pc.h>
#include <time.h>
#include <sys/timeb.h>
#include <sys/nearptr.h>
#include <sys/farptr.h>

#include "sysdef.h"
#include "djgpp.h"
#include "csutil/inifile.h"
#include "isystem.h"
#include "inputq.h"
#include "djkeysys.h"
#include "djmousys.h"

static KeyboardHandler KH;
static MouseHandler MH;

static unsigned short ScanCodeToChar[128] =
{
  0,        CSKEY_ESC,'1',      '2',      '3',      '4',      '5',      '6',    // 00..07
  '7',      '8',      '9',      '0',      '-',      '=',      '\b',     '\t',   // 08..0F
  'q',      'w',      'e',      'r',      't',      'y',      'u',      'i',    // 10..17
  'o',      'p',      '[',      ']',      '\n',     CSKEY_CTRL,'a',     's',    // 18..1F
  'd',      'f',      'g',      'h',      'j',      'k',      'l',      ';',    // 20..27
  39,       '`',      CSKEY_SHIFT,'\\',   'z',      'x',      'c',      'v',    // 28..2F
  'b',      'n',      'm',      ',',      '.',      '/',      CSKEY_SHIFT,'*',  // 30..37
  CSKEY_ALT,' ',      0,        CSKEY_F1, CSKEY_F2, CSKEY_F3, CSKEY_F4, CSKEY_F5,// 38..3F
  CSKEY_F6,  CSKEY_F7, CSKEY_F8, CSKEY_F9, CSKEY_F10,0,       0,        CSKEY_HOME,// 40..47
  CSKEY_UP,  CSKEY_PGUP,'-',    CSKEY_LEFT,CSKEY_CENTER,CSKEY_RIGHT,'+',CSKEY_END,// 48..4F
  CSKEY_DOWN,CSKEY_PGDN,CSKEY_INS,CSKEY_DEL,0,      0,        0,        CSKEY_F11,// 50..57
  CSKEY_F12,0,        0,        0,        0,        0,        0,        0,      // 58..5F
  0,        0,        0,        0,        0,        0,        0,        0,      // 60..67
  0,        0,        0,        0,        0,        0,        0,        0,      // 68..6F
  0,        0,        0,        0,        0,        0,        0,        0,      // 70..77
  0,        0,        0,        0,        0,        0,        0,        0       // 78..7F
};

//================================================================== System ====

IMPLEMENT_IBASE (SysSystemDriver)
  IMPLEMENTS_INTERFACE (iSystem)
  IMPLEMENTS_INTERFACE (iDosSystemDriver)
IMPLEMENT_IBASE_END

SysSystemDriver::SysSystemDriver () : csSystemDriver ()
{
  CONSTRUCT_IBASE (NULL);
  // Sanity check
  if (sizeof (event_queue [0]) != 12)
  {
    Printf (MSG_FATAL_ERROR, "ERROR! Your compiler does not handle packed structures!\n");
    Printf (MSG_FATAL_ERROR, "sizeof (event_queue [0]) == %d instead of 12!\n", sizeof (event_queue [0]));
    exit (-1);
  }
}

void SysSystemDriver::Loop ()
{
  while (!Shutdown && !ExitLoop)
  {
    static long prev_time = -1;
    long new_prev_time = Time ();
    NextFrame ((prev_time == -1) ? 0 : new_prev_time - prev_time, Time ());
    prev_time = new_prev_time;

    // Fill in events ...
    while (event_queue_tail != event_queue_head)
    {
      unsigned long time = Time ();
      switch (event_queue [event_queue_tail].Type)
      {
        case 1:
        {
          int ScanCode = event_queue [event_queue_tail].Keyboard.ScanCode;
          bool Down = (ScanCode < 0x80);

          ScanCode = ScanCodeToChar [ScanCode & 0x7F];
          if (ScanCode)
            if (Down)
              Keyboard->do_keypress (time, ScanCode);
            else
              Keyboard->do_keyrelease (time, ScanCode);
          break;
        }
        case 2:
        {
          int Button = event_queue [event_queue_tail].Mouse.Button;
          bool Down = event_queue [event_queue_tail].Mouse.Down;
          int x = event_queue [event_queue_tail].Mouse.x;
          int y = event_queue [event_queue_tail].Mouse.y;

          if (Button == 0)
            Mouse->do_mousemotion (time, x, y);
          else if (Down)
            Mouse->do_buttonpress (time, Button, x, y,
              Keyboard->GetKeyState (CSKEY_SHIFT),
              Keyboard->GetKeyState (CSKEY_ALT),
              Keyboard->GetKeyState (CSKEY_CTRL));
          else
            Mouse->do_buttonrelease (time, Button, x, y);
          break;
        }
      } /* endswitch */
      event_queue_tail = (event_queue_tail + 1) & EVENT_QUEUE_MASK;
    } /* endwhile */
  } // while (!Shutdown && !ExitLoop)
}

void SysSystemDriver::EnablePrintf (bool Enable)
{
  extern void console_Enable (bool Enable);
  console_Enable (Enable);
}

bool SysSystemDriver::SetMousePosition (int x, int y)
{
  return ((SysMouseDriver *)Mouse)->SetMousePosition (x, y);
}

//================================================================ Keyboard ====

SysKeyboardDriver::SysKeyboardDriver() : csKeyboardDriver ()
{
  KeyboardOpened = false;
}

SysKeyboardDriver::~SysKeyboardDriver(void)
{
  Close();
}

bool SysKeyboardDriver::Open(csEventQueue* EvQueue)
{
  csKeyboardDriver::Open (EvQueue);

  // Initialize keyboard handler
  if (KH.install ())
    return false;
  // Give us exclusive access of the keyboard.
  KH.chain (0);

  KeyboardOpened = true;
  return true;
}

void SysKeyboardDriver::Close(void)
{
  if (KeyboardOpened)
  {
    KH.uninstall ();
    KeyboardOpened = false;
  }
}

//=================================================================== Mouse ====

SysMouseDriver::SysMouseDriver () : csMouseDriver ()
{
  __dpmi_regs regs;
  regs.x.ax = 0x0000;
  __dpmi_int (0x33, &regs);
  MouseExists = !!(regs.x.ax);
  MouseOpened = false;

  SensivityFactor = System->Config->GetFloat ("MouseDriver", "MouseSensivity", 1.0);
}

SysMouseDriver::~SysMouseDriver ()
{
  Close ();
}

bool SysMouseDriver::Open (iSystem* System, csEventQueue *EvQueue)
{
  if (!csMouseDriver::Open (System, EvQueue))
    return false;
  if (MH.install ())
    return false;

  // Query screen size from System object
  int FrameWidth, FrameHeight, Depth;
  bool FullScreen;
  System->GetSettings (FrameWidth, FrameHeight, Depth, FullScreen);

  // Query mouse sensivity
  __dpmi_regs regs;
  regs.x.ax = 0x1B;
  __dpmi_int (0x33, &regs);
  mouse_sensivity_x = regs.x.bx;
  mouse_sensivity_y = regs.x.cx;
  mouse_sensivity_threshold = regs.x.dx;

  // Compute mouse sensivity
  regs.x.cx = 8;
  regs.x.dx = 8;
  regs.x.ax = 0x0F;
  __dpmi_int (0x33, &regs);
  regs.x.bx = (int) ((50 + FrameWidth / 32) * SensivityFactor);
  regs.x.cx = (int) ((50 + FrameHeight / 24) * SensivityFactor);
  regs.x.dx = MAX (regs.x.bx, regs.x.cx); // ? not sure about this
  regs.x.ax = 0x1A;
  __dpmi_int (0x33, &regs);

  // Set mouse range to full-screen
  regs.x.ax = 0x07;
  regs.x.cx = 0;
  regs.x.dx = FrameWidth - 1;
  __dpmi_int (0x33, &regs);
  regs.x.ax = 0x08;
  regs.x.cx = 0;
  regs.x.dx = FrameHeight - 1;
  __dpmi_int (0x33, &regs);

  // Set mouse to (0, 0)
  regs.x.ax = 0x04;
  regs.x.cx = 0;
  regs.x.dx = 0;
  __dpmi_int (0x33, &regs);

  MouseOpened = true;
  return true;
}

void SysMouseDriver::Close ()
{
  if (!MouseOpened)
    return;

  MH.uninstall ();

  // Restore mouse sensivity
  __dpmi_regs regs;
  regs.x.cx = 8;
  regs.x.dx = 16;
  regs.x.ax = 0x0F;
  __dpmi_int (0x33, &regs);
  regs.x.ax = 0x1A;
  regs.x.bx = mouse_sensivity_x;
  regs.x.cx = mouse_sensivity_y;
  regs.x.dx = mouse_sensivity_threshold;
  __dpmi_int (0x33, &regs);

  MouseOpened = false;
}

bool SysMouseDriver::SetMousePosition (int x, int y)
{
  if (!MouseOpened)
    return false;

  __dpmi_regs regs;
  regs.x.cx = x;
  regs.x.dx = y;
  regs.x.ax = 0x04;
  __dpmi_int (0x33, &regs);
  return true;
}
<|endoftext|>


<commit_before>// @(#)root/test:$Id$
// Author: Alejandro García Montoro 08/2017

#include "Fit/BinData.h"
#include "Fit/UnBinData.h"
#include "Fit/Fitter.h"
#include "HFitInterface.h"
#include "TH2.h"
#include "TF2.h"
#include "TRandom.h"

#include "gtest/gtest.h"

#include <iostream>
#include <string>

// Gradient 2D function
template <class T>
class GradFunc2D : public ROOT::Math::IParamMultiGradFunctionTempl<T> {
public:
   void SetParameters(const double *p) {
      std::copy(p, p + NPar(), fParameters);
      // compute integral in interval [0,1][0,1]
      fIntegral = Integral(p);
   }

   const double *Parameters() const { return fParameters; }

   ROOT::Math::IBaseFunctionMultiDimTempl<T> *Clone() const
   {
      GradFunc2D<T> *f = new GradFunc2D<T>();
      f->SetParameters(fParameters);
      return f;
   }

   unsigned int NDim() const { return 2; }

   unsigned int NPar() const { return 5; }

   void ParameterGradient(const T *x, const double * p, T *grad) const
   {
      if (p == nullptr) {
         ParameterGradient(x, fParameters, grad);
         return;
      }
      T xx = (1. - x[0] );
      T yy = (1. - x[1] );
      T fval = FVal(x,p);
      grad[0] =  fval / fIntegral;
      grad[1] =  p[0] * ( xx / fIntegral - fval / (2. * fIntegral * fIntegral ) );
      grad[2] =  p[0] * ( xx * xx / fIntegral -  fval / (3. * fIntegral * fIntegral ) );
      grad[3] =  p[0] * ( yy / fIntegral - fval / (2. * fIntegral * fIntegral ) );
      grad[4] =  p[0] * ( yy * yy / fIntegral -  fval / (3. * fIntegral * fIntegral ) );
   }

   // return integral in interval {0,1}{0,1}
   double Integral(const double * p)
   {
      return 1. +  (p[1] + p[3] )/ 2. + (p[2] + p[4] )/ 3.;
   }

private:

   T FVal(const T * x, const double *p) const
   {
      // use a function based on Bernstein polynomial which have easy normalization
      T xx = (1. - x[0] );
      T yy = (1. - x[1] );
      T fval =  1. + p[1] * xx + p[2] * xx * xx + p[3] * yy + p[4] * yy * yy;
      return fval;
   }

   T DoEvalPar(const T *x, const double *p) const
   {
      if (p == nullptr)
         return DoEvalPar(x, fParameters);
      return p[0] * FVal(x,p) / fIntegral;
   }

   T DoParameterDerivative(const T *x, const double *p, unsigned int ipar) const
   {
      std::vector<T> grad(NPar());
      ParameterGradient(x, p, &grad[0]);
      return grad[ipar];
   }

   double fParameters[5] = {0,0,0,0,0};
   double fIntegral = 1.0;
};

struct LikelihoodFitType {};
struct Chi2FitType {};

template <typename U, typename V, typename F>
struct GradientFittingTestTraits {
   using DataType = U;
   using FittingDataType = V;
   using FitType = F;
};

// Typedefs of GradientTestTraits for scalar (binned and unbinned) data
using ScalarChi2 = GradientFittingTestTraits<Double_t, ROOT::Fit::BinData, Chi2FitType>;
using ScalarBinned = GradientFittingTestTraits<Double_t, ROOT::Fit::BinData, LikelihoodFitType>;
using ScalarUnBinned = GradientFittingTestTraits<Double_t, ROOT::Fit::UnBinData, LikelihoodFitType>;

// Typedefs of GradientTestTraits for vectorial (binned and unbinned) data
#ifdef R__HAS_VECCORE
using VectorialChi2 = GradientFittingTestTraits<ROOT::Double_v, ROOT::Fit::BinData, Chi2FitType>;
using VectorialBinned = GradientFittingTestTraits<ROOT::Double_v, ROOT::Fit::BinData, LikelihoodFitType>;
using VectorialUnBinned = GradientFittingTestTraits<ROOT::Double_v, ROOT::Fit::UnBinData, LikelihoodFitType>;
#endif

template <class T>
class GradientFittingTest : public ::testing::Test {
protected:
   virtual void SetUp()
   {
      // Create TF2 from model function and initialize the fit function
      std::stringstream streamTF2;
      streamTF2 << "f" << this;
      std::string nameTF2 = streamTF2.str();

      GradFunc2D<typename T::DataType> fitFunction;
      fFunction = new TF2(nameTF2.c_str(), fitFunction, 0., 1., 0, 1, 5);
      fFunction->SetNpx(300);
      fFunction->SetNpy(300);
      double p0[5] = {1., 1., 2., 3., 0.5};
      fFunction->SetParameters(p0);
      assert(fFunction->GetNpar() == 5);

      // Assure the to-be-created histogram does not replace an old one
      std::stringstream streamTH1;
      streamTH1 << "h" << this;
      std::string nameTH2 = streamTH1.str();

      auto oldTH2 = gROOT->FindObject(nameTH2.c_str());
      if (oldTH2)
         delete oldTH2;

      fHistogram = new TH2D(nameTH2.c_str(), nameTH2.c_str(), fNumPoints, 0, 1., 99, 0., 1.);

      // Fill the histogram
      gRandom->SetSeed(222);
      for (int i = 0; i < 1000000; ++i) {
         double x, y = 0;
         fFunction->GetRandom2(x, y);
         fHistogram->Fill(x, y);
      }

      // Create the function
      GradFunc2D<typename T::DataType> function;

      double p[5] = {50., 1., 1, 2., 1.};
      function.SetParameters(p);

      // Create the fitter from the function
      fFitter.SetFunction(function);
      //fFitter.SetFunction(function,false);
      fFitter.Config().SetMinimizer("Minuit2");
      //fFitter.Config().MinimizerOptions().SetPrintLevel(3);

      // Fill the binned or unbinned data
      FillData();

      Fit();
   }

   // Fill binned data
   template <class U = typename T::FittingDataType>
   typename std::enable_if<std::is_same<U, typename T::FittingDataType>::value &&
                           std::is_same<U, ROOT::Fit::BinData>::value>::type
   FillData()
   {
      // fill fit data
      fData = new ROOT::Fit::BinData(fNumPoints, 2);
      ROOT::Fit::FillData(*fData, fHistogram, fFunction);
   }

   // Fill unbinned data
   template <class U = typename T::FittingDataType>
   typename std::enable_if<std::is_same<U, typename T::FittingDataType>::value &&
                           std::is_same<U, ROOT::Fit::UnBinData>::value>::type
   FillData()
   {
      unsigned int npoints = 100*fNumPoints + 1;
      //npoints = 101;
      fData = new ROOT::Fit::UnBinData(npoints, 2);

      gRandom->SetSeed(111); // to get the same data
      for (unsigned i = 0; i < npoints; i++) {
         double xdata, ydata = 0;
         fFunction->GetRandom2(xdata, ydata);
         fData->Add(xdata, ydata);
      }

      // for unbin data we need to fix the overall normalization parameter
      fFitter.Config().ParamsSettings()[0].SetValue(1);
      fFitter.Config().ParamsSettings()[0].Fix();
   }

   // Perform the Fit
   template <class F = typename T::FitType>
   typename std::enable_if<std::is_same<F, typename T::FitType>::value &&
                           std::is_same<F, LikelihoodFitType>::value>::type
   Fit()
   {
      std::cout << "Doing a likelihood Fit " << std::endl;
      fFitter.LikelihoodFit(*fData);
   }

   template <class F = typename T::FitType>
   typename std::enable_if<std::is_same<F, typename T::FitType>::value &&
                           std::is_same<F, Chi2FitType>::value>::type
   Fit()
   {
      std::cout << "Doing a chi2 Fit " << std::endl;
      fFitter.Fit(*fData);
   }

   TF2 *fFunction;
   typename T::FittingDataType *fData;
   TH2D *fHistogram;
   ROOT::Fit::Fitter fFitter;

   static const unsigned fNumPoints = 401;
};

// Types used by Google Test to instantiate the tests.
#ifdef R__HAS_VECCORE
typedef ::testing::Types<ScalarChi2, ScalarBinned, ScalarUnBinned, VectorialChi2, VectorialBinned, VectorialUnBinned> TestTypes;

//typedef ::testing::Types<ScalarBinned,VectorialBinned> TestTypes;
#else
typedef ::testing::Types<ScalarChi2, ScalarBinned, ScalarUnBinned> TestTypes;
#endif

// Declare that the GradientFittingTest class should be instantiated with the types defined by TestTypes
TYPED_TEST_CASE(GradientFittingTest, TestTypes);

// Test the fitting using the gradient is successful
TYPED_TEST(GradientFittingTest, GradientFitting)
{
   // TestFixture::fFitter.Config().MinimizerOptions().SetPrintLevel(3);
   EXPECT_TRUE(TestFixture::fFitter.Result().IsValid() && TestFixture::fFitter.Result().Edm() < 0.001);
   TestFixture::fFitter.Result().Print(std::cout);
}

<commit_msg>Improve the gradient test by adding test for multi-threads. Add also possibility to control output via command line by adding verbose options (-v,-vv,-vvv)<commit_after>// @(#)root/test:$Id$
// Author: Alejandro García Montoro 08/2017

#include "Fit/BinData.h"
#include "Fit/UnBinData.h"
#include "Fit/Fitter.h"
#include "HFitInterface.h"
#include "TH2.h"
#include "TF2.h"
#include "TRandom.h"

#include "gtest/gtest.h"

#include <iostream>
#include <string>

// Gradient 2D function
template <class T>
class GradFunc2D : public ROOT::Math::IParamMultiGradFunctionTempl<T> {
public:
   void SetParameters(const double *p) {
      std::copy(p, p + NPar(), fParameters);
      // compute integral in interval [0,1][0,1]
      fIntegral = Integral(p);
   }

   const double *Parameters() const { return fParameters; }

   ROOT::Math::IBaseFunctionMultiDimTempl<T> *Clone() const
   {
      GradFunc2D<T> *f = new GradFunc2D<T>();
      f->SetParameters(fParameters);
      return f;
   }

   unsigned int NDim() const { return 2; }

   unsigned int NPar() const { return 5; }

   void ParameterGradient(const T *x, const double * p, T *grad) const
   {
      if (p == nullptr) {
         ParameterGradient(x, fParameters, grad);
         return;
      }
      T xx = (1. - x[0] );
      T yy = (1. - x[1] );
      T fval = FVal(x,p);
      grad[0] =  fval / fIntegral;
      grad[1] =  p[0] * ( xx / fIntegral - fval / (2. * fIntegral * fIntegral ) );
      grad[2] =  p[0] * ( xx * xx / fIntegral -  fval / (3. * fIntegral * fIntegral ) );
      grad[3] =  p[0] * ( yy / fIntegral - fval / (2. * fIntegral * fIntegral ) );
      grad[4] =  p[0] * ( yy * yy / fIntegral -  fval / (3. * fIntegral * fIntegral ) );
   }

   // return integral in interval {0,1}{0,1}
   double Integral(const double * p)
   {
      return 1. +  (p[1] + p[3] )/ 2. + (p[2] + p[4] )/ 3.;
   }

private:

   T FVal(const T * x, const double *p) const
   {
      // use a function based on Bernstein polynomial which have easy normalization
      T xx = (1. - x[0] );
      T yy = (1. - x[1] );
      T fval =  1. + p[1] * xx + p[2] * xx * xx + p[3] * yy + p[4] * yy * yy;
      return fval;
   }

   T DoEvalPar(const T *x, const double *p) const
   {
      if (p == nullptr)
         return DoEvalPar(x, fParameters);
      return p[0] * FVal(x,p) / fIntegral;
   }

   T DoParameterDerivative(const T *x, const double *p, unsigned int ipar) const
   {
      std::vector<T> grad(NPar());
      ParameterGradient(x, p, &grad[0]);
      return grad[ipar];
   }

   double fParameters[5] = {0,0,0,0,0};
   double fIntegral = 1.0;
};

struct LikelihoodFitType {};
struct Chi2FitType {};

template <typename U, typename V, typename F>
struct GradientFittingTestTraits {
   using DataType = U;
   using FittingDataType = V;
   using FitType = F;
};

// Typedefs of GradientTestTraits for scalar (binned and unbinned) data
using ScalarChi2 = GradientFittingTestTraits<Double_t, ROOT::Fit::BinData, Chi2FitType>;
using ScalarBinned = GradientFittingTestTraits<Double_t, ROOT::Fit::BinData, LikelihoodFitType>;
using ScalarUnBinned = GradientFittingTestTraits<Double_t, ROOT::Fit::UnBinData, LikelihoodFitType>;

// Typedefs of GradientTestTraits for vectorial (binned and unbinned) data
#ifdef R__HAS_VECCORE
using VectorialChi2 = GradientFittingTestTraits<ROOT::Double_v, ROOT::Fit::BinData, Chi2FitType>;
using VectorialBinned = GradientFittingTestTraits<ROOT::Double_v, ROOT::Fit::BinData, LikelihoodFitType>;
using VectorialUnBinned = GradientFittingTestTraits<ROOT::Double_v, ROOT::Fit::UnBinData, LikelihoodFitType>;
#endif

int printLevel = 0;

template <class T>
class GradientFittingTest : public ::testing::Test {
protected:
   virtual void SetUp()
   {
      // Create TF2 from model function and initialize the fit function
      std::stringstream streamTF2;
      streamTF2 << "f" << this;
      std::string nameTF2 = streamTF2.str();

      GradFunc2D<typename T::DataType> fitFunction;
      fFunction = new TF2(nameTF2.c_str(), fitFunction, 0., 1., 0, 1, 5);
      fFunction->SetNpx(300);
      fFunction->SetNpy(300);
      double p0[5] = {1., 1., 2., 3., 0.5};
      fFunction->SetParameters(p0);
      assert(fFunction->GetNpar() == 5);

      // Assure the to-be-created histogram does not replace an old one
      std::stringstream streamTH1;
      streamTH1 << "h" << this;
      std::string nameTH2 = streamTH1.str();

      auto oldTH2 = gROOT->FindObject(nameTH2.c_str());
      if (oldTH2)
         delete oldTH2;

      fHistogram = new TH2D(nameTH2.c_str(), nameTH2.c_str(), fNumPoints, 0, 1., 99, 0., 1.);

      // Fill the histogram
      gRandom->SetSeed(222);
      for (int i = 0; i < 1000000; ++i) {
         double x, y = 0;
         fFunction->GetRandom2(x, y);
         fHistogram->Fill(x, y);
      }

      // Create the function
      GradFunc2D<typename T::DataType> function;

      double p[5] = {50., 1., 1, 2., 1.};
      function.SetParameters(p);

      // Create the fitter from the function
      fFitter.SetFunction(function);
      //fFitter.SetFunction(function,false);
      fFitter.Config().SetMinimizer("Minuit2");

      // Fill the binned or unbinned data
      FillData();

      if (printLevel>1) fFitter.Config().MinimizerOptions().SetPrintLevel(printLevel);

   }

   // Fill binned data
   template <class U = typename T::FittingDataType>
   typename std::enable_if<std::is_same<U, typename T::FittingDataType>::value &&
                           std::is_same<U, ROOT::Fit::BinData>::value>::type
   FillData()
   {
      // fill fit data
      fData = new ROOT::Fit::BinData(fNumPoints, 2);
      ROOT::Fit::FillData(*fData, fHistogram, fFunction);
   }

   // Fill unbinned data
   template <class U = typename T::FittingDataType>
   typename std::enable_if<std::is_same<U, typename T::FittingDataType>::value &&
                           std::is_same<U, ROOT::Fit::UnBinData>::value>::type
   FillData()
   {
      unsigned int npoints = 100*fNumPoints + 1;
      //npoints = 101;
      fData = new ROOT::Fit::UnBinData(npoints, 2);

      gRandom->SetSeed(111); // to get the same data
      for (unsigned i = 0; i < npoints; i++) {
         double xdata, ydata = 0;
         fFunction->GetRandom2(xdata, ydata);
         fData->Add(xdata, ydata);
      }

      // for unbin data we need to fix the overall normalization parameter
      fFitter.Config().ParamsSettings()[0].SetValue(1);
      fFitter.Config().ParamsSettings()[0].Fix();
   }

   // Perform the Fit
   template <class F = typename T::FitType>
   typename std::enable_if<std::is_same<F, typename T::FitType>::value &&
                           std::is_same<F, LikelihoodFitType>::value>::type
   Fit()
   {
      std::cout << "Doing a binned likelihood Fit " << std::endl;
      // the fit is extended in case of bin data types
      bool extended = std::is_same<ROOT::Fit::BinData,typename T::FittingDataType>::value;
      fFitter.LikelihoodFit(*fData, extended,  fExecutionPolicy);
   }

   template <class F = typename T::FitType>
   typename std::enable_if<std::is_same<F, typename T::FitType>::value &&
                           std::is_same<F, Chi2FitType>::value>::type
   Fit()
   {
      std::cout << "Doing a chi2 Fit " << std::endl;
      fFitter.Fit(*fData, fExecutionPolicy );
   }

   // function actually running the test.
   // We define here the condition to say that the test is valid
   bool RunFit(ROOT::Fit::ExecutionPolicy executionPolicy) {
      fExecutionPolicy = executionPolicy;
      if (printLevel>0) {
         std::cout << "**************************************\n";
         if (fExecutionPolicy == ROOT::Fit::ExecutionPolicy::kSerial)
            std::cout << "   RUN SEQUENTIAL \n";
         else if (fExecutionPolicy == ROOT::Fit::ExecutionPolicy::kMultithread)
            std::cout << "   RUN MULTI-THREAD \n";
         else if (fExecutionPolicy == ROOT::Fit::ExecutionPolicy::kMultiprocess)
            std::cout << "   RUN MULTI-PROCESS \n";

         std::cout << "**************************************\n";
      }
      Fit();
      if (printLevel>0) fFitter.Result().Print(std::cout);
      return (fFitter.Result().IsValid() && fFitter.Result().Edm() < 0.001);
   }

   TF2 *fFunction;
   typename T::FittingDataType *fData;
   TH2D *fHistogram;
   ROOT::Fit::Fitter fFitter;
   ROOT::Fit::ExecutionPolicy fExecutionPolicy = ROOT::Fit::ExecutionPolicy::kSerial;
   static const unsigned fNumPoints = 401;
};

// Types used by Google Test to instantiate the tests.
#ifdef R__HAS_VECCORE
typedef ::testing::Types<ScalarChi2, ScalarBinned, ScalarUnBinned, VectorialChi2, VectorialBinned, VectorialUnBinned> TestTypes;

//typedef ::testing::Types<ScalarBinned,VectorialBinned> TestTypes;
#else
typedef ::testing::Types<ScalarChi2, ScalarBinned, ScalarUnBinned> TestTypes;
#endif

// Declare that the GradientFittingTest class should be instantiated with the types defined by TestTypes
TYPED_TEST_CASE_P(GradientFittingTest);

// Test the fitting using the gradient is successful
TYPED_TEST_P(GradientFittingTest, Sequential)
{
   EXPECT_TRUE(TestFixture::RunFit(ROOT::Fit::ExecutionPolicy::kSerial));
}

TYPED_TEST_P(GradientFittingTest, Multithread)
{
   EXPECT_TRUE(TestFixture::RunFit(ROOT::Fit::ExecutionPolicy::kMultithread));
}

REGISTER_TYPED_TEST_CASE_P(GradientFittingTest,Sequential,Multithread);

INSTANTIATE_TYPED_TEST_CASE_P(GradientFitting, GradientFittingTest, TestTypes);

int main(int argc, char** argv) {

// Disables elapsed time by default.
  //::testing::GTEST_FLAG(print_time) = false;

   // Parse command line arguments
   for (Int_t i = 1 ;  i < argc ; i++) {
      std::string arg = argv[i] ;
      if (arg == "-v") {
         std::cout << "---running in verbose mode" << std::endl;
         printLevel = 1;
      } else if (arg == "-vv") {
         std::cout << "---running in very verbose mode" << std::endl;
         printLevel = 2;
      } else if (arg == "-vvv") {
         std::cout << "---running in very very verbose mode" << std::endl;
         printLevel = 3;
      }
   }

  // This allows the user to override the flag on the command line.
  ::testing::InitGoogleTest(&argc, argv);

  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>// Copyright 2010-2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     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.

// This is the skeleton for the official flatzinc interpreter.  Much
// of the funcionalities are fixed (name of parameters, format of the
// input): see http://www.minizinc.org/downloads/doc-1.6/flatzinc-spec.pdf

#if defined(__GNUC__)  // Linux or Mac OS X.
#include <signal.h>
#endif  // __GNUC__

#include <csignal>
#include <string>
#include <vector>

#include "ortools/base/commandlineflags.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/threadpool.h"
#include "ortools/base/timer.h"
#include "ortools/flatzinc/cp_model_fz_solver.h"
#include "ortools/flatzinc/logging.h"
#include "ortools/flatzinc/model.h"
#include "ortools/flatzinc/parser.h"
#include "ortools/flatzinc/presolve.h"

DEFINE_double(time_limit, 0, "time limit in seconds.");
DEFINE_bool(all_solutions, false, "Search for all solutions.");
DEFINE_int32(num_solutions, 0,
             "Maximum number of solution to search for, 0 means unspecified.");
DEFINE_bool(free_search, false,
            "If false, the solver must follow the defined search."
            "If true, other search are allowed.");
DEFINE_int32(threads, 0, "Number of threads the solver will use.");
DEFINE_bool(presolve, true, "Presolve the model to simplify it.");
DEFINE_bool(statistics, false, "Print solver statistics after search.");
DEFINE_bool(read_from_stdin, false,
            "Read the FlatZinc from stdin, not from a file.");
DEFINE_int32(fz_seed, 0, "Random seed");
DEFINE_string(fz_model_name, "stdin",
              "Define problem name when reading from stdin.");
DEFINE_string(params, "", "SatParameters as a text proto.");

DECLARE_bool(log_prefix);

using operations_research::ThreadPool;

namespace operations_research {
namespace fz {

void FixAndParseParameters(int* argc, char*** argv) {
  absl::SetFlag(&FLAGS_log_prefix, false);

  char all_param[] = "--all_solutions";
  char free_param[] = "--free_search";
  char threads_param[] = "--threads";
  char solutions_param[] = "--num_solutions";
  char logging_param[] = "--fz_logging";
  char statistics_param[] = "--statistics";
  char seed_param[] = "--fz_seed";
  char verbose_param[] = "--fz_verbose";
  char debug_param[] = "--fz_debug";
  for (int i = 1; i < *argc; ++i) {
    if (strcmp((*argv)[i], "-a") == 0) {
      (*argv)[i] = all_param;
    }
    if (strcmp((*argv)[i], "-f") == 0) {
      (*argv)[i] = free_param;
    }
    if (strcmp((*argv)[i], "-p") == 0) {
      (*argv)[i] = threads_param;
    }
    if (strcmp((*argv)[i], "-n") == 0) {
      (*argv)[i] = solutions_param;
    }
    if (strcmp((*argv)[i], "-l") == 0) {
      (*argv)[i] = logging_param;
    }
    if (strcmp((*argv)[i], "-s") == 0) {
      (*argv)[i] = statistics_param;
    }
    if (strcmp((*argv)[i], "-r") == 0) {
      (*argv)[i] = seed_param;
    }
    if (strcmp((*argv)[i], "-v") == 0) {
      (*argv)[i] = verbose_param;
    }
    if (strcmp((*argv)[i], "-d") == 0) {
      (*argv)[i] = debug_param;
    }
  }
  const char kUsage[] =
      "Usage: see flags.\nThis program parses and solve a flatzinc problem.";

  gflags::SetUsageMessage(kUsage);
  gflags::ParseCommandLineFlags(argc, argv, true);
  google::InitGoogleLogging((*argv)[0]);
}

Model ParseFlatzincModel(const std::string& input, bool input_is_filename) {
  WallTimer timer;
  timer.Start();
  // Read model.
  std::string problem_name = input_is_filename ? input : FLAGS_fz_model_name;
  if (input_is_filename || absl::EndsWith(problem_name, ".fzn")) {
    CHECK(absl::EndsWith(problem_name, ".fzn"));
    problem_name.resize(problem_name.size() - 4);
    const size_t found = problem_name.find_last_of("/\\");
    if (found != std::string::npos) {
      problem_name = problem_name.substr(found + 1);
    }
  }
  Model model(problem_name);
  if (input_is_filename) {
    CHECK(ParseFlatzincFile(input, &model));
  } else {
    CHECK(ParseFlatzincString(input, &model));
  }

  FZLOG << "File " << (input_is_filename ? input : "stdin") << " parsed in "
        << timer.GetInMs() << " ms" << FZENDL;

  // Presolve the model.
  Presolver presolve;
  presolve.CleanUpModelForTheCpSolver(&model, true);
  if (FLAGS_presolve) {
    FZLOG << "Presolve model" << FZENDL;
    timer.Reset();
    timer.Start();
    presolve.Run(&model);
    FZLOG << "  - done in " << timer.GetInMs() << " ms" << FZENDL;
  }

  // Print statistics.
  ModelStatistics stats(model);
  stats.BuildStatistics();
  stats.PrintStatistics();
  return model;
}

}  // namespace fz
}  // namespace operations_research

int main(int argc, char** argv) {
  // Flatzinc specifications require single dash parameters (-a, -f, -p).
  // We need to fix parameters before parsing them.
  operations_research::fz::FixAndParseParameters(&argc, &argv);
  // We allow piping model through stdin.
  std::string input;
  if (FLAGS_read_from_stdin) {
    std::string currentLine;
    while (std::getline(std::cin, currentLine)) {
      input.append(currentLine);
    }
  } else {
    if (argc <= 1) {
      LOG(ERROR) << "Usage: " << argv[0] << " <file>";
      return EXIT_FAILURE;
    }
    input = argv[1];
  }

  operations_research::fz::Model model =
      operations_research::fz::ParseFlatzincModel(input,
                                                  !FLAGS_read_from_stdin);
  operations_research::fz::FlatzincSatParameters parameters;
  parameters.display_all_solutions = FLAGS_all_solutions;
  parameters.use_free_search = FLAGS_free_search;
  parameters.verbose_logging = FLAGS_fz_logging;
  parameters.max_number_of_solutions =
      FLAGS_num_solutions == 0 ?  // Not fixed.
          (FLAGS_num_solutions = FLAGS_all_solutions ? kint32max : 1)
                               : FLAGS_num_solutions;
  parameters.random_seed = FLAGS_fz_seed;
  parameters.display_statistics = FLAGS_statistics;
  parameters.number_of_threads = FLAGS_threads;
  parameters.max_time_in_seconds = FLAGS_time_limit;

  operations_research::sat::SolveFzWithCpModelProto(model, parameters,
                                                    FLAGS_params);
  return EXIT_SUCCESS;
}
<commit_msg>implement first part of #1367<commit_after>// Copyright 2010-2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     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.

// This is the skeleton for the official flatzinc interpreter.  Much
// of the funcionalities are fixed (name of parameters, format of the
// input): see http://www.minizinc.org/downloads/doc-1.6/flatzinc-spec.pdf

#if defined(__GNUC__)  // Linux or Mac OS X.
#include <signal.h>
#endif  // __GNUC__

#include <csignal>
#include <string>
#include <vector>

#include "ortools/base/commandlineflags.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/threadpool.h"
#include "ortools/base/timer.h"
#include "ortools/flatzinc/cp_model_fz_solver.h"
#include "ortools/flatzinc/logging.h"
#include "ortools/flatzinc/model.h"
#include "ortools/flatzinc/parser.h"
#include "ortools/flatzinc/presolve.h"

DEFINE_double(time_limit, 0, "time limit in seconds.");
DEFINE_bool(all_solutions, false, "Search for all solutions.");
DEFINE_int32(num_solutions, 0,
             "Maximum number of solution to search for, 0 means unspecified.");
DEFINE_bool(free_search, false,
            "If false, the solver must follow the defined search."
            "If true, other search are allowed.");
DEFINE_int32(threads, 0, "Number of threads the solver will use.");
DEFINE_bool(presolve, true, "Presolve the model to simplify it.");
DEFINE_bool(statistics, false, "Print solver statistics after search.");
DEFINE_bool(read_from_stdin, false,
            "Read the FlatZinc from stdin, not from a file.");
DEFINE_int32(fz_seed, 0, "Random seed");
DEFINE_string(fz_model_name, "stdin",
              "Define problem name when reading from stdin.");
DEFINE_string(params, "", "SatParameters as a text proto.");

DECLARE_bool(log_prefix);

using operations_research::ThreadPool;

namespace operations_research {
namespace fz {

void FixAndParseParameters(int* argc, char*** argv) {
  absl::SetFlag(&FLAGS_log_prefix, false);

  char all_param[] = "--all_solutions";
  char free_param[] = "--free_search";
  char threads_param[] = "--threads";
  char solutions_param[] = "--num_solutions";
  char logging_param[] = "--fz_logging";
  char statistics_param[] = "--statistics";
  char seed_param[] = "--fz_seed";
  char verbose_param[] = "--fz_verbose";
  char debug_param[] = "--fz_debug";
  char time_param[] = "--time_limit";
  bool use_time_param = false;
  for (int i = 1; i < *argc; ++i) {
    if (strcmp((*argv)[i], "-a") == 0) {
      (*argv)[i] = all_param;
    }
    if (strcmp((*argv)[i], "-f") == 0) {
      (*argv)[i] = free_param;
    }
    if (strcmp((*argv)[i], "-p") == 0) {
      (*argv)[i] = threads_param;
    }
    if (strcmp((*argv)[i], "-n") == 0) {
      (*argv)[i] = solutions_param;
    }
    if (strcmp((*argv)[i], "-l") == 0) {
      (*argv)[i] = logging_param;
    }
    if (strcmp((*argv)[i], "-s") == 0) {
      (*argv)[i] = statistics_param;
    }
    if (strcmp((*argv)[i], "-r") == 0) {
      (*argv)[i] = seed_param;
    }
    if (strcmp((*argv)[i], "-v") == 0) {
      (*argv)[i] = verbose_param;
    }
    if (strcmp((*argv)[i], "-d") == 0) {
      (*argv)[i] = debug_param;
    }
     if (strcmp((*argv)[i], "-t") == 0) {
      (*argv)[i] = time_param;
      use_time_param = true;
    } }
  const char kUsage[] =
      "Usage: see flags.\nThis program parses and solve a flatzinc problem.";

  gflags::SetUsageMessage(kUsage);
  gflags::ParseCommandLineFlags(argc, argv, true);
  google::InitGoogleLogging((*argv)[0]);

  // Fix time limit if -t was used.
  if (use_time_param) {
    FLAGS_time_limit /= 1000.0;
  }
}

Model ParseFlatzincModel(const std::string& input, bool input_is_filename) {
  WallTimer timer;
  timer.Start();
  // Read model.
  std::string problem_name = input_is_filename ? input : FLAGS_fz_model_name;
  if (input_is_filename || absl::EndsWith(problem_name, ".fzn")) {
    CHECK(absl::EndsWith(problem_name, ".fzn"));
    problem_name.resize(problem_name.size() - 4);
    const size_t found = problem_name.find_last_of("/\\");
    if (found != std::string::npos) {
      problem_name = problem_name.substr(found + 1);
    }
  }
  Model model(problem_name);
  if (input_is_filename) {
    CHECK(ParseFlatzincFile(input, &model));
  } else {
    CHECK(ParseFlatzincString(input, &model));
  }

  FZLOG << "File " << (input_is_filename ? input : "stdin") << " parsed in "
        << timer.GetInMs() << " ms" << FZENDL;

  // Presolve the model.
  Presolver presolve;
  presolve.CleanUpModelForTheCpSolver(&model, true);
  if (FLAGS_presolve) {
    FZLOG << "Presolve model" << FZENDL;
    timer.Reset();
    timer.Start();
    presolve.Run(&model);
    FZLOG << "  - done in " << timer.GetInMs() << " ms" << FZENDL;
  }

  // Print statistics.
  ModelStatistics stats(model);
  stats.BuildStatistics();
  stats.PrintStatistics();
  return model;
}

}  // namespace fz
}  // namespace operations_research

int main(int argc, char** argv) {
  // Flatzinc specifications require single dash parameters (-a, -f, -p).
  // We need to fix parameters before parsing them.
  operations_research::fz::FixAndParseParameters(&argc, &argv);
  // We allow piping model through stdin.
  std::string input;
  if (FLAGS_read_from_stdin) {
    std::string currentLine;
    while (std::getline(std::cin, currentLine)) {
      input.append(currentLine);
    }
  } else {
    if (argc <= 1) {
      LOG(ERROR) << "Usage: " << argv[0] << " <file>";
      return EXIT_FAILURE;
    }
    input = argv[1];
  }

  operations_research::fz::Model model =
      operations_research::fz::ParseFlatzincModel(input,
                                                  !FLAGS_read_from_stdin);
  operations_research::fz::FlatzincSatParameters parameters;
  parameters.display_all_solutions = FLAGS_all_solutions;
  parameters.use_free_search = FLAGS_free_search;
  parameters.verbose_logging = FLAGS_fz_logging;
  parameters.max_number_of_solutions =
      FLAGS_num_solutions == 0 ?  // Not fixed.
          (FLAGS_num_solutions = FLAGS_all_solutions ? kint32max : 1)
                               : FLAGS_num_solutions;
  parameters.random_seed = FLAGS_fz_seed;
  parameters.display_statistics = FLAGS_statistics;
  parameters.number_of_threads = FLAGS_threads;
  parameters.max_time_in_seconds = FLAGS_time_limit;

  operations_research::sat::SolveFzWithCpModelProto(model, parameters,
                                                    FLAGS_params);
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "sessions/SessionManagerComponent.h"

void Susi::Sessions::SessionManagerComponent::handleCheckSessions( Susi::Events::SharedEventPtr event ) {
    checkSessions();
}

void Susi::Sessions::SessionManagerComponent::handleGetAttribute( Susi::Events::EventPtr event ) {
    try {
        std::string sessionID = event->payload["id"];
        std::string key = event->payload["key"];

        event->payload["value"] = getSessionAttribute( sessionID, key );
    }
    catch( const std::exception & e ) {
        std::string msg = "Error in handleSessionGetAttribute(): ";
        msg += e.what();
        throw std::runtime_error( msg );
    }
}
void Susi::Sessions::SessionManagerComponent::handleSetAttribute( Susi::Events::EventPtr event ) {
    try {
        std::string sessionID = event->payload["id"];
        std::string key = event->payload["key"];
        Susi::Util::Any value = event->payload["value"];

        event->payload["success"] = setSessionAttribute( sessionID, key, value );
    }
    catch( const std::exception & e ) {
        event->payload["success"] = false;
        std::string msg = "Error in handleSessionSetAttribute(): ";
        msg += e.what();
        throw std::runtime_error( msg );
    }
}
void Susi::Sessions::SessionManagerComponent::handlePushAttribute( Susi::Events::EventPtr event ) {
    try {
        std::string sessionID = event->payload["id"];
        std::string key = event->payload["key"];
        Susi::Util::Any value = event->payload["value"];

        event->payload["success"] = pushSessionAttribute( sessionID, key, value );
    }
    catch( const std::exception & e ) {
        event->payload["success"] = false;
        std::string msg = "Error in handleSessionPushAttribute(): ";
        msg += e.what();
        throw std::runtime_error( msg );
    }
}
void Susi::Sessions::SessionManagerComponent::handleRemoveAttribute( Susi::Events::EventPtr event ) {
    try {
        std::string sessionID = event->payload["id"];
        std::string key = event->payload["key"];

        event->payload["success"] = removeSessionAttribute( sessionID, key );
    }
    catch( const std::exception & e ) {
        event->payload["success"] = false;
        std::string msg = "Error in handleSessionRemoveAttribute(): ";
        msg += e.what();
        throw std::runtime_error( msg );
    }
}
void Susi::Sessions::SessionManagerComponent::handleUpdate( Susi::Events::EventPtr event ) {
    try {
        std::string sessionID = event->payload["id"];
        std::chrono::seconds secs;

        int seconds = event->payload["seconds"];

        if( seconds > 0 ) {
            secs = std::chrono::seconds( seconds );
            updateSession( sessionID, std::chrono::duration_cast<std::chrono::milliseconds>( secs ) );
        }
        else {
            updateSession( sessionID );
        }

        event->payload["success"] = true;
    }
    catch( const std::exception & e ) {
        event->payload["success"] = false;
        std::string msg = "Error in handleUpdateSession(): ";
        msg += e.what();
        throw std::runtime_error( msg );
    }
}
void Susi::Sessions::SessionManagerComponent::handleCheck( Susi::Events::EventPtr event ) {
    try {
        std::string sessionID = event->payload["id"];
        event->payload["success"] = checkSession( sessionID );
    }
    catch( const std::exception & e ) {
        event->payload["success"] = false;
        std::string msg = "Error in handleCheckSession(): ";
        msg += e.what();
        throw std::runtime_error( msg );
    }
}<commit_msg>[session] allow users to update own session;<commit_after>#include "sessions/SessionManagerComponent.h"

void Susi::Sessions::SessionManagerComponent::handleCheckSessions( Susi::Events::SharedEventPtr event ) {
    checkSessions();
}

void Susi::Sessions::SessionManagerComponent::handleGetAttribute( Susi::Events::EventPtr event ) {
    try {
        std::string sessionID = event->payload["id"];
        std::string key = event->payload["key"];

        event->payload["value"] = getSessionAttribute( sessionID, key );
    }
    catch( const std::exception & e ) {
        std::string msg = "Error in handleSessionGetAttribute(): ";
        msg += e.what();
        throw std::runtime_error( msg );
    }
}
void Susi::Sessions::SessionManagerComponent::handleSetAttribute( Susi::Events::EventPtr event ) {
    try {
        std::string sessionID = event->payload["id"];
        std::string key = event->payload["key"];
        Susi::Util::Any value = event->payload["value"];

        event->payload["success"] = setSessionAttribute( sessionID, key, value );
    }
    catch( const std::exception & e ) {
        event->payload["success"] = false;
        std::string msg = "Error in handleSessionSetAttribute(): ";
        msg += e.what();
        throw std::runtime_error( msg );
    }
}
void Susi::Sessions::SessionManagerComponent::handlePushAttribute( Susi::Events::EventPtr event ) {
    try {
        std::string sessionID = event->payload["id"];
        std::string key = event->payload["key"];
        Susi::Util::Any value = event->payload["value"];

        event->payload["success"] = pushSessionAttribute( sessionID, key, value );
    }
    catch( const std::exception & e ) {
        event->payload["success"] = false;
        std::string msg = "Error in handleSessionPushAttribute(): ";
        msg += e.what();
        throw std::runtime_error( msg );
    }
}
void Susi::Sessions::SessionManagerComponent::handleRemoveAttribute( Susi::Events::EventPtr event ) {
    try {
        std::string sessionID = event->payload["id"];
        std::string key = event->payload["key"];

        event->payload["success"] = removeSessionAttribute( sessionID, key );
    }
    catch( const std::exception & e ) {
        event->payload["success"] = false;
        std::string msg = "Error in handleSessionRemoveAttribute(): ";
        msg += e.what();
        throw std::runtime_error( msg );
    }
}
void Susi::Sessions::SessionManagerComponent::handleUpdate( Susi::Events::EventPtr event ) {
    try {
        std::string sessionID = event->sessionID;
        if(event->payload["id"].isString()){
            std::string sessionID = event->payload["id"];
        }
        std::chrono::seconds secs;

        int seconds = 0;
        if(event->payload["seconds"].isInteger()){
            seconds = event->payload["seconds"];
        }

        if( seconds > 0 ) {
            secs = std::chrono::seconds( seconds );
            updateSession( sessionID, std::chrono::duration_cast<std::chrono::milliseconds>( secs ) );
        }
        else {
            updateSession( sessionID );
        }

        event->payload["success"] = true;
    }
    catch( const std::exception & e ) {
        event->payload["success"] = false;
        std::string msg = "Error in handleUpdateSession(): ";
        msg += e.what();
        throw std::runtime_error( msg );
    }
}
void Susi::Sessions::SessionManagerComponent::handleCheck( Susi::Events::EventPtr event ) {
    try {
        std::string sessionID = event->payload["id"];
        event->payload["success"] = checkSession( sessionID );
    }
    catch( const std::exception & e ) {
        event->payload["success"] = false;
        std::string msg = "Error in handleCheckSession(): ";
        msg += e.what();
        throw std::runtime_error( msg );
    }
}<|endoftext|>