text
stringlengths
8
6.88M
#include "../include/Map.h" #include "../include/GameScene.h" #include "../include/Camera.h" #include "../include/TextureManager.h" #include "../include/EnemyManager.h" #include "../include/EventManager.h" #include "../include/ItemManager.h" #include "../include/Item.h" #include "../include/ShotEnemy.h" #include "../include/WalkEnemy.h" #include "../include/BigEnemy.h" #include "../include/NomalEnemy.h" #include "../include/StageEvent.h" #include "../include/GoalEvent.h" #include "../TrapEvent.h" #include "../include/Boss.h" #include "../TutorialObject.h" #include "../TutorialEnemy.h" #include "../include/Coin.h" #include <fstream> #include <sstream> #include <vector> #define IF(_objName, _name) if(_objName == _name) #define ELIF(_objName, _name) else if(_objName == _name) namespace gnGame { using std::fstream; namespace { constexpr int MAP_WIDTH = 12; constexpr int MAP_HEIGHT = 5; constexpr int MAPCHIP_SIZE = MAP_WIDTH * MAP_HEIGHT; constexpr int MAX_MAPCHIP_SIZE = 100; } namespace utility { std::vector<string> split(const string& _line) { vector<string> result; std::stringstream ss(_line); std::string item; while (std::getline(ss, item, ',')) { if (!item.empty()) { result.emplace_back(item); } } return result; } } Map::Map(GameScene* _gameScene) : gameScene(_gameScene) , mapWidth(0) , mapHeight(0) , mapField() , mapTexture(TextureManager::getTexture("MapChip")) { textureRegion = Texture::spriteTexture(mapTexture, MAP_WIDTH, MAP_HEIGHT + 1); for (auto y{ 0 }; y < MapInfo::MaxMapHeight; ++y) { for (auto x{ 0 }; x < MapInfo::MaxMapWidth; ++x) { mapField[y][x] = nullptr; } } } Map::~Map() { for (int y = 0; y < MapInfo::MaxMapHeight; ++y) { for (int x = 0; x < MapInfo::MaxMapWidth; ++x) { if (mapField[y][x]) { delete mapField[y][x]; mapField[y][x] = nullptr; } } } } void Map::loadMapFile(const string& _fileName) { fstream mapFile{ _fileName + ".txt" }, objFile{ _fileName + "_Obj.txt" }; // マップファイルを読み込めなかったとき if (!mapFile) { exit(-1); } if (!objFile) { exit(-1); } string line; // 行と列の読み込み std::getline(mapFile, line); auto wh = utility::split(line); mapWidth = std::stoi(wh[0]); mapHeight = std::stoi(wh[1]); // マップの読み込み std::vector<std::vector<std::string>> vs; while (std::getline(mapFile, line)) { vs.emplace_back(utility::split(line)); } // マップに値を設定する for (size_t y = 0; y < vs.size(); ++y) { for (size_t x = 0; x < vs[y].size(); ++x) { auto mTile = stoi(vs[y][x]); //mapField[y][x] = createMapBlock((MapTile)mTile); if (mTile >= 1 && mTile <= MAPCHIP_SIZE) { mapField[y][x] = createMapBlock(MapTile::BLOCK); mapField[y][x]->setTextureRect(textureRegion[mTile - 1]); } else if (mTile > MAPCHIP_SIZE && mTile < MAX_MAPCHIP_SIZE) { mapField[y][x] = createMapBlock(MapTile::OBJECT); } else { mapField[y][x] = createMapBlock(MapTile::NONE); } } } // オブジェクトの読み込み std::vector<std::vector<std::string>>objVec; while (std::getline(objFile, line)) { objVec.emplace_back(utility::split(line)); } // オブジェクト配置 for (size_t y = 0; y < objVec.size(); ++y) { auto vecX = static_cast<float>(stoi(objVec[y][1])); auto vecY = static_cast<float>(stoi(objVec[y][2])); // 向きの文字列があった場合 std::string dir = ""; if (objVec[y].size() > 3) { dir = objVec[y][3]; } setMapObjects(objVec[y][0], { vecX, vecY }, dir); } mapFile.close(); objFile.close(); } void Map::drawMap() { for (int y = 0; y < mapHeight; ++y) { for (int x = 0; x < mapWidth; ++x) { Vector2 pos{ (float)(MapInfo::MapHSize + x * MapInfo::MapSize), (float)(MapInfo::MapHSize + y * MapInfo::MapSize) }; // 画面外だと描画しない if (!Camera::isOnScreen(pos)) { continue; } auto screen = Camera::toScreenPos(pos); if (!mapField[y][x]) { continue; } mapField[y][x]->setPos(screen); mapField[y][x]->draw(); } } } void Map::setTile(int _x, int _y, MapTile _mapInfo) { delete mapField[_y][_x]; mapField[_y][_x] = createMapBlock(MapTile::NONE); } bool Map::checkTile(int _x, int _y) { auto tile = getTile(_x / 32, _y / 32); switch (tile) { case gnGame::MapTile::NONE: return false; break; case gnGame::MapTile::BLOCK: return true; break; case gnGame::MapTile::OBJECT: return true; break; default: return false; break; } return false; } MapTile Map::getTile(int _x, int _y) { if (_x < 0 || _x >= mapWidth || _y < 0 || _y >= mapHeight) { return MapTile::NONE; } return mapField[_y][_x]->getMapTile(); } void Map::claerMap() { for (int y = 0; y < MapInfo::MaxMapHeight; ++y) { for (int x = 0; x < MapInfo::MaxMapWidth; ++x) { if (mapField[y][x]) { delete mapField[y][x]; mapField[y][x] = nullptr; } } } } Vector2 Map::getMapSize() { return { static_cast<float>(mapWidth) * MapInfo::MapSize, static_cast<float>(mapHeight) * MapInfo::MapSize }; } Vector2 Map::getStartPoint() { return startPoint; } void Map::setMapObjects(string _objName, const Vector2& _pos, const std::string& _direction) { IF(_objName, "Start") { startPoint = _pos; } ELIF(_objName, "Goal") { auto e = EventPtr(new GoalEvent{ _pos, gameScene }); EventManager::getIns()->addEvent(e); } ELIF(_objName, "Clear") { auto e = EventPtr(new ClearEvent{ _pos, gameScene }); EventManager::getIns()->addEvent(e); } ELIF(_objName, "StageEvent") { auto e = EventPtr(new StageEvent{ _pos, gameScene }); EventManager::getIns()->addEvent(e); } ELIF(_objName, "Needle") { auto e = EventPtr(new TrapEvent{ _pos, gameScene }); EventManager::getIns()->addEvent(e); } ELIF(_objName, "Enemy1") { auto dir = (_direction == "Left") ? Direction::Left : Direction::Right; EnemyPtr e = EnemyPtr(new ShotEnemy{ gameScene, _pos, {20, 50, 2, 2, 2.0f}, dir }); e->setMap(this); e->onStart(); EnemyManager::getIns()->addActor(e); } ELIF(_objName, "Enemy2") { EnemyPtr e = EnemyPtr(new WalkEnemy{ _pos, {30, 50, 2, 3, 2.0f} }); e->setMap(this); e->onStart(); EnemyManager::getIns()->addActor(e); } ELIF(_objName, "Enemy3") { EnemyPtr e = EnemyPtr(new BigEnemy{ _pos, {50, 50, 5, 5, 2.0f} }); e->setMap(this); e->onStart(); EnemyManager::getIns()->addActor(e); } ELIF(_objName, "Enemy4") { auto dir = (_direction == "Left") ? Direction::Left : Direction::Right; EnemyPtr e = EnemyPtr(new NomalEnemy{ _pos, {20, 50, 5, 5, 2.0f}, dir }); e->setMap(this); e->onStart(); EnemyManager::getIns()->addActor(e); } ELIF(_objName, "Boss") { EnemyPtr e = EnemyPtr(new Boss{ gameScene, _pos, {500, 100, 5, 10, 2.0f} }); e->setMap(this); e->onStart(); EnemyManager::getIns()->addActor(e); } ELIF(_objName, "Coin") { auto e = ItemPtr(new Coin{ _pos }); e->onStart(); ItemManager::getIns()->addItem(e); } ELIF(_objName, "Tutorial_Boss") { EnemyPtr e = EnemyPtr(new TutorialEnemy{ _pos }); e->setMap(this); e->onStart(); EnemyManager::getIns()->addActor(e); } ELIF(_objName, "Move") { std::shared_ptr<TutorialObject> object{ new MoveIntro{_pos} }; TutorialObjectList::getIns()->addObject(object); } ELIF(_objName, "Jump") { std::shared_ptr<TutorialObject> object{ new JumpIntro{_pos} }; TutorialObjectList::getIns()->addObject(object); } ELIF(_objName, "Shot") { std::shared_ptr<TutorialObject> object{ new ShotIntro{_pos} }; TutorialObjectList::getIns()->addObject(object); } } }
/* Copyright (c) 2015, Vlad Mesco All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "parser.h" #include "note.h" #include <string> #include <algorithm> #include <cctype> #include <istream> #include <sstream> int tokenizer_lineno = 1; bool TryParseNote(const char* s, Note* n) { std::string text; text.assign(s); if(text.empty()) { n->scale_ = 1; n->name_ = '-'; n->sharp_ = ' '; n->height_ = ' '; return true; } bool valid = true; // expecting a number std::string number; for(size_t i = 0; i < text.size(); ++i) { if(text[i] >= '0' && text[i] <= '9') { number.append(std::string(1, text[i])); } else { break; } } if(number.empty()) { return false; } text = text.substr(number.size()); // expecting a note name if(text.empty()) return false; static const char noteNames[] = "ABCDEFGHabcdefgh-"; if(!strchr(noteNames, text[0])) { return false; } char noteName = toupper(text[0]); text = text.substr(1); // expecting an optional sharp if(text.empty() && noteName != '-') return false; char sharp = ' '; if(text[0] == '#' || text[0] == 'b') { sharp = text[0]; text = text.substr(1); } // expecting a height if(text.empty() && noteName != '-') return false; char height = 0; if(noteName != '-') { if(text[0] >= '0' && text[0] <= '9') { height = text[0]; } } if(atoi(number.c_str()) <= 0) return false; n->scale_ = atoi(number.c_str()); n->name_ = noteName; n->sharp_ = sharp; n->height_ = height; return true; } void AssignString(std::string const& s, char*& p) { p = (char*)malloc(sizeof(char) * s.size() + 1); strcpy(p, s.c_str()); } #if 0 #define LOG(F, ...) fprintf(stderr, "Tokenizer: " F "\n", __VA_ARGS__) #else #define LOG(F, ...) #endif bool GetNextToken(std::istream& fin, int& hTokenId, char*& sToken) { if(!fin.good()) return false; char c; int wc; std::stringstream text; while(1) { wc = fin.peek(); if(wc == std::char_traits<char>::eof() || fin.eof()) break; c = wc & 0xFF; LOG("Considering %c", c); if(c == ';') { LOG("Skipping comment until EOL"); (void) fin.get(); while(wc = fin.get(), wc != 10 && wc != 13 && wc != EOF) ; tokenizer_lineno++; continue; } if(isspace(c) || isblank(c) || c == 10 || c == 13 || c == ',') { if(text.str().empty()) { if(c == 10) { tokenizer_lineno++; } LOG("Skipping whitespace"); (void) fin.get(); continue; } break; } if(c == '[') { if(text.str().empty()) { LOG("LSQUARE"); hTokenId = LSQUARE; (void) fin.get(); return true; } else { break; } } else if(c == ']') { if(text.str().empty()) { LOG("RSQUARE"); hTokenId = RSQUARE; (void) fin.get(); return true; } else { break; } } else if(c == '{') { if(text.str().empty()) { LOG("LCURLY"); hTokenId = LCURLY; (void) fin.get(); return true; } else { break; } } else if(c == '}') { if(text.str().empty()) { // if you notice I overuse stringstream::str too much in a loop, shut up; stringstream doesn't have empty for some reason and I'm too lazy to refactor LOG("RCURLY"); hTokenId = RCURLY; (void) fin.get(); return true; } else { break; } } else if(c == '=') { if(text.str().empty()) { LOG("EQUALS"); hTokenId = EQUALS; (void) fin.get(); return true; } else { break; } } (void) fin.get(); text << c; LOG("Eating character; now at %s", text.str().c_str()); } if(text.str().empty()) return false; std::string stext = text.str(); if(stext.compare("NOTES") == 0) { LOG("NOTES"); hTokenId = NOTES; return true; } if(stext.compare("PCM") == 0) { LOG("PCM"); hTokenId = PCM; return true; } Note n; if(TryParseNote(stext.c_str(), &n)) { LOG("NOTE"); AssignString(text.str(), sToken); hTokenId = NOTE; return true; } if(std::all_of(&stext[0], &stext[0] + stext.size(), [](char c) -> bool { return (c >= '0' && c <= '9') || c == '-'; })) { LOG("NUMBER"); AssignString(text.str(), sToken); hTokenId = NUMBER; return true; } AssignString(text.str(), sToken); LOG("STRING"); hTokenId = STRING; return true; }
// -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- /* Strings referenced in adjunct/m2_ui/. * * Comment lines of both forms valid in C++ are ignored. Preprocessor * directives are allowed: the #if-ery around each string tag should reflect the * #if-ery around its use in the indicated file(s). Strings tags may be * repeated to simplify matching the #if-ery (e.g. when used in two places with * different #if-ery). * * Please indicate which file a string is used in, to help others track it * down. An end-of-line comment indicates the file(s) the string is in. A * file-name comment on a line of its own applies to all subsequent lines up to * the next blank line; an end-of-line comment starting with + indicates more * files containing the string; other end-of-line filename comments transiently * over-ride the block rule. Include commented-out string tags for string tags * that appear only in comments. */ #ifdef M2_SUPPORT S_SAVE_AS_CAPTION // MailDesktopWindow.cpp S_FILTER_DESCRIPTION_NAME_OF_SENDER // dialogs/MailIndexPropertiesDialog.cpp S_MESSAGES_FROM // dialogs/AddFilterDialog.cpp // dialogs/AccountPropertiesDialog.cpp S_ACCOUNT_PROPERTIES_CHAT_SERVER S_ACCOUNT_PROPERTIES_INCOMING_SERVER S_ACCOUNT_PROPERTIES_NNTP_SERVER S_ACCOUNT_PROPERTIES_OUTGOING_SERVER S_DEFAULT_ENCODING // + setup/dialog.ini D_MAIL_DIRECTION_AUTOMATIC D_MAIL_DIRECTION_LEFT_TO_RIGHT D_MAIL_DIRECTION_RIGHT_TO_LEFT D_ACCOUNT_PROP_TEXT_DIR SI_IDSTR_MSG_MAILFREPFS_INVALID_SETTINGS_CAP D_MAIL_WARNING_LOW_BANDWIDTH_AND_REMOVE_FROM_SERVER D_MAIL_IMAP_SPAM_FOLDER D_MAIL_IMAP_TRASH_FOLDER D_MAIL_ACCOUNT_DISABLE_SPAM_FILTER D_PREFER_PLAIN_TEXT_FOLLOW_ORIG_FORMATTING // Dialogs// Mail Store Update Dialog D_MAIL_UPDATE_DESC // dialogs/AccountQuestionDialogs.cpp D_KICK_CHAT_USER_DLG_LABEL // setup/dialog.ini S_MAIL_SERVER_CLEANUP S_MAIL_SERVER_CLEANUP_WARNING // dialogs/AccountSubscriptionDialog.cpp D_ACCOUNT_SUBSCRIPTION_ROOM_COUNT D_FETCHING_ROOM_LIST D_MAILER_DELETE_FOLDER_NOTIFICATION D_MAILER_DELETE_FOLDER_NOTIFICATION_HEADER D_SUBSCRIBE_CHAT D_SUBSCRIBE_IMAP D_SUBSCRIBE_NEWSGROUPS D_SUBSCRIBE_RSS // dialogs/AskMaxMessagesDownloadDialog.cpp D_NEWS_HOW_MANY_NEW_MESSAGES D_NEWS_MANY_NEW_MESSAGES_DETECTED // + setup/dialog.ini D_NEWS_MESSAGES // + setup/dialog.ini D_NEWS_ALL_MESSAGES // + setup/dialog.ini D_NEWS_DONT_ASK_NEW_MESSAGES_AGAIN // + setup/dialog.ini // dialogs/AuthenticationFailedDialog.cpp D_MAIL_AUTHENTICATION_FAILED_TITLE // + setup/dialog.ini DI_IDSTR_M2_AUTH_DLG_USERNAME // + setup/dialog.ini DI_IDSTR_M2_AUTH_DLG_PASSWORD // + setup/dialog.ini DI_IDM_LBL_AUTHENTICATION // + setup/dialog.ini D_MAIL_AUTHENTICATION_EXPAND_LOGIN_DETAILS // + setup/dialog.ini D_MAIL_AUTHENTICATION_SERVER_MSG D_MAIL_AUTHENTICATION_TRY_AGAIN D_MAIL_LOGIN_DETAILS D_PASSWORD_NOT_DISPLAYED // + dialogs/SecurityPasswordDialog.cpp + dialogs/AccountPropertiesDialog.cpp // dialogs/ChangeNickDialog.cpp S_IRC_ROOM_PROTECTED S_NICK_TAKEN // dialogs/CustomizeHeaderDialog.cpp DI_ID_BTN_ADD_LANG // + setup/dialog.ini D_MAILER_CUSTOMIZE_HEADERS // + setup/dialog.ini D_MAILER_HEADER_LIST_TITLE D_MAILER_HEADER_MOVEDOWN D_MAILER_HEADER_MOVEUP S_DELETE // dialogs/DefaultMailClient.cpp D_DEFAULT_MAIL_CLIENT_DIALOG_TITLE D_DEFAULT_MAIL_CLIENT_DIALOG_CONTENT // dialogs/MailFilterDialog.cpp, dialogs/MailIndexPropertiesDialog.cpp, LabelPropertiesController S_FILTER_AND S_FILTER_AND_MATCH_MESSAGES_WHERE S_FILTER_ANY_HEADER // + dialogs/SearchMailDialog.cpp S_FILTER_CC_HEADER // + dialogs/SearchMailDialog.cpp S_FILTER_CONTAINS S_FILTER_DESCRIPTION_ANY_HEADER S_FILTER_DESCRIPTION_CONTAINS S_FILTER_DESCRIPTION_DOES_NOT_CONTAIN S_FILTER_DESCRIPTION_ENTIRE_MESSAGE S_FILTER_DESCRIPTION_REGEXP S_FILTER_DESCRIPTION_SUBJECT S_FILTER_DESCRIPTION_BODY S_FILTER_DOES_NOT_CONTAIN S_FILTER_ENTIRE_MESSAGE // + dialogs/SearchMailDialog.cpp S_FILTER_FROM_HEADER // + dialogs/SearchMailDialog.cpp S_FILTER_MATCHES_REGEXP S_FILTER_MATCH_MESSAGES_WHERE S_FILTER_MEDIUM S_FILTER_NEWSGROUPS_HEADER // + dialogs/SearchMailDialog.cpp S_FILTER_OR S_FILTER_OR_MATCH_MESSAGES_WHERE S_FILTER_REPLYTO_HEADER // + dialogs/SearchMailDialog.cpp S_FILTER_STRONG S_FILTER_SUBJECT // + dialogs/SearchMailDialog.cpp S_FILTER_TO_HEADER // + dialogs/SearchMailDialog.cpp S_FILTER_BODY D_MAIL_APPLY_FILTER_BUTTON D_MAIL_CHOOSE_CUSTOM_ICON D_SELECT_CUSTOM_ICON D_MAIL_MATCH_MESSAGES_IN // dialogs/NewAccountWizard.cpp DI_IDSTR_M2_NEWACC_WIZ_INCOMING_SERVER DI_IDSTR_M2_NEWACC_WIZ_IRC_SERVER DI_IDSTR_M2_NEWACC_WIZ_LOGIN DI_IDSTR_M2_NEWACC_WIZ_NICK D_BROWSE_FOR_FOLDER D_IMPORT_FINISHED D_IMPORT_MAIL_INTO D_IMPORT_PROCESSING_FULL D_IMPORT_PROCESSING_SIMPLE D_MAIL_IMPORT_FINISHED D_SELECT_FILES_TO_IMPORT D_START_IMPORT_BUTTON S_IMPORT_FROM_APPLE_MAIL_NEW S_IMPORT_FROM_EUDORA S_IMPORT_FROM_MBOX S_IMPORT_FROM_NETSCAPE6 S_IMPORT_FROM_OE S_IMPORT_FROM_OPERA6 S_IMPORT_FROM_OPERA7 S_IMPORT_FROM_THUNDERBIRD S_IMPORT_GENERIC_MBOX_FILE S_IMPORT_MAILBOX_FOLDER S_IMPORT_MBOX_FILTER // + windows/MailDesktopWindow.cpp S_IMPORT_NETSCAPE_FILTER S_IMPORT_NETSCAPE_PREFS_FILE S_IMPORT_THUNDERBIRD_FILTER S_IMPORT_THUNDERBIRD_PREFS_FILE S_IMPORT_WIZARD_NONE S_NEW_ACCOUNT_CHAT_IRC S_NEW_ACCOUNT_IMPORT S_NEW_ACCOUNT_NEWS S_NEW_ACCOUNT_OPERAMAIL D_NEW_ACCOUNT_EMAIL D_SELECT_NETSCAPE_JS_TO_IMPORT D_SELECT_THUNDERBIRD_JS_TO_IMPORT S_IMPORT_EUDORA_FILTER D_SELECT_EUDORA_INI_TO_IMPORT D_SELECT_OPERA_ACCOUNTS_INI_TO_IMPORT S_IMPORT_OPERA6_MAIL_FILTER D_SELECT_OPERA7_ACCOUNTS_INI_TO_IMPORT S_IMPORT_OPERA7_MAIL_FILTER S_IMPORT_OPERA7_ACCOUNT_INI D_SELECT_FILES_AND_DIRS_TO_IMPORT D_SELECT_MBOX_DIRS_TO_IMPORT D_MBOX_IMPORT_FOLDER_ADD D_MBOX_IMPORT_FILE_ADD D_MBOX_IMPORT_FOLDER_AND_FILE_ADD S_WIZARD_FINISH S_WIZARD_NEXT_PAGE // dialogs/SaveAttachmentsDialog.cpp D_CREATEDIRECTOTY_FAILED D_CREATEDIRECTOTY_FAILED_TITLE D_MAILER_SAVE_ATTACHMENTS D_MAILER_SAVE_ATTATCHMENTS_HEADER D_SAVEDIRECTORY_NOT_FOUND D_SAVEDIRECTORY_NOT_FOUND_TITLE S_MAIL_ATTACHMENTS_SAVE_PROMPT_OVERWRITE // dialogs//Mail Message Dialog D_MAIL_MSG_TITLE D_MAIL_MSG_CONSOLE_BUTTON // dialogs/MailStoreUpdateDialog.cpp D_MAIL_STORE_UPDATE_TITLE D_MAIL_STORE_UPDATE_COMPLETE_TEXT D_MAIL_STORE_UPDATE_FAIL D_MAIL_STORE_UPDATE_FAIL_TITLE D_CONTINUE D_PAUSE S_PROGRESS_FORMAT S_PROGRESS_SEC_FORMAT S_PROGRESS_MIN_FORMAT // dialogs/OfflineMessagesDialog.cpp D_MAIL_MAKE_OFFLINE_MESSAGES_AVAILABLE_TITLE D_MAIL_MAKE_OFFLINE_MESSAGES_AVAILABLE // dialogs/SignatureEditor.cpp D_MAIL_EDIT_SIGNATURE D_MAIL_SIGNATURE_EDITOR_TITLE D_MAIL_APPLY_SIGNATURE_FOR_ALL_ACCOUNTS D_MAIL_SIGNATURE_EXPLANATION D_HTML_MAIL_USE_PLAIN_TEXT D_HTML_MAIL_USE_HTML SI_SAVE_BUTTON_TEXT D_MAIL_SIGNATURE_URL_FOR_IMAGE_CAPTION D_MAIL_SIGNATURE_URL_FOR_IMAGE_TITLE // panels/MailPanel.cpp D_EXPORT_MESSAGES S_EXPORT_MBOX_FILTER SI_IDSTR_ALL_FILES_ASTRIX S_MAIL_PANEL_BUTTON_TEXT S_MAIL_FEEDTOOLBAR_UPDATE_ALL // panels/MailPanel.h S_DELETE_FOLDER_WARNING S_REMOVE_FOLDER S_UNSUBSCRIBE_IMAP_WARNING S_UNSUBSCRIBE_NEWSGROUP_WARNING // windows/ChatDesktopWindow.cpp DI_IDSTR_M2_CHATWINDOWTOOLBAR_SENDMESSAGE S_CHATROOM_INVITATION S_CHAT_CHANGES_ROOM_TOPIC_TO S_CHAT_CHATTER_GETS_VOICE S_CHAT_CHATTER_HAS_DISCONNECTED S_CHAT_CHATTER_HAS_JOINED S_CHAT_CHATTER_HAS_LEFT S_CHAT_CHATTER_IS_NOW_OPERATOR S_CHAT_CHATTER_IS_NO_LONGER_OPERATOR S_CHAT_CHATTER_KICKED S_CHAT_CHATTER_REMOVES_VOICE S_CHAT_DISCONNECTED_FROM S_CHAT_JOINING_CHAT_ROOM S_CHAT_RECEIVE_FILE_NOTICE S_CHAT_ROOM_INFO_WITH_TOPIC S_CHAT_ROOM_INFO_WITH_TOPIC_PLURAL S_CHAT_ROOM_IS_NOW_MODERATED S_CHAT_ROOM_IS_NO_LONGER_MODERATED S_CHAT_ROOM_MODERATION_IS_ON S_CHAT_ROOM_TOPIC_IS S_CHAT_SEND_FILE_TITLE // + setup/standard_{menu,toolbar}.ini S_CHAT_STARTED_TALKING_IN S_CHAT_STARTED_TALKING_WITH S_CHAT_UNKNOWN_CONTACT S_CHAT_USER_LIMIT_IS_NOW S_CHAT_USER_LIMIT_IS_NOW_OFF S_CHAT_WHOIS_REPLY_AND S_CHAT_WHOIS_REPLY_IDLE_HOUR S_CHAT_WHOIS_REPLY_IDLE_HOURS S_CHAT_WHOIS_REPLY_IDLE_MINUTE S_CHAT_WHOIS_REPLY_IDLE_MINUTES S_CHAT_WHOIS_REPLY_IDLE_SECOND S_CHAT_WHOIS_REPLY_IDLE_SECONDS S_CHAT_WHOIS_REPLY_IN_ROOMS S_CHAT_WHOIS_REPLY_IS_AWAY S_CHAT_WHOIS_REPLY_IS_IRC_OPERATOR S_CHAT_WHOIS_REPLY_LOGGED_IN_AS S_CHAT_WHOIS_REPLY_SIGNED_ON_AND_IDLE S_CHAT_WHOIS_REPLY_SIGNED_ON_UNKNOWN_IDLE S_CHAT_WHOIS_REPLY_USER_IS S_CHAT_WHOIS_REPLY_USING_SERVER S_CHAT_WINDOW_NOF_USERS S_CHAT_WINDOW_NOF_USERS_PLURAL S_CHAT_YOU_ARE_KICKED S_CHAT_YOU_HAVE_LEFT_ROOM S_CHAT_CHATTER_CHANGES_NICK S_CHAT_ROOM_IS_NOW_PASSWORD_PROTECTED S_CHAT_ROOM_IS_NOW_SECRET S_CHAT_ROOM_IS_NO_LONGER_PASSWORD_PROTECTED S_CHAT_ROOM_IS_NO_LONGER_SECRET S_CHAT_ROOM_UNKNOWN_MODE S_CHAT_ROOM_UNKNOWN_USER_MODE S_CHAT_TOPIC_CHANGE_BY_EVERYONE S_CHAT_TOPIC_CHANGE_BY_OPERATORS_ONLY // windows/ComposeDesktopWindow.cpp DI_IDNO // + dialogs/CookieEditDialog.cpp dialogs/Dialog.cpp dialogs/SetupApplyDialog.cpp DI_IDSTR_M2_COMPOSEMAIL_CC // + setup/standard_menu.ini DI_IDSTR_M2_COMPOSEMAIL_DLG_TITLE DI_IDSTR_M2_COMPOSEMAIL_FROM // + windows/MailDesktopWindow.cpp, setup/standard_menu.ini DI_IDSTR_M2_COMPOSEMAIL_SUBJECT // + windows/MailDesktopWindow.cpp, setup/standard_menu.ini DI_IDSTR_M2_COMPOSEMAIL_TO // + setup/standard_{menu,toolbar}.ini DI_IDYES // + dialogs/CookieEditDialog.cpp dialogs/Dialog.cpp dialogs/SetupApplyDialog.cpp DI_ID_CANCEL // + dialogs/Dialog.cpp D_EMPTY_SUBJECT_WARNING_MESSAGE D_EMPTY_SUBJECT_WARNING_TITLE D_ENCODING_MISMATCH_CAPTION D_ENCODING_MISMATCH_TEXT S_ATTACH_FILES S_COMPOSEMAIL_ATTACHMENT S_COMPOSEMAIL_BCC // setup/standard_menu.ini S_COMPOSEMAIL_FOLLOWUP // setup/standard_menu.ini S_COMPOSEMAIL_MISSING_EMAIL S_COMPOSEMAIL_NEWSGROUP S_COMPOSEMAIL_REPLYTO // setup/standard_menu.ini S_COMPOSEMAIL_SIZE S_HIGHEST_PRIORITY S_HIGH_PRIORITY S_INVALID_FROM_ADDRESS S_INVALID_MESSAGE S_LOWEST_PRIORITY S_LOW_PRIORITY S_MISSING_ADDRESS_OR_SUBJECT S_MISSING_MAIL_ADDRESS S_MISSING_MAIL_SERVER_SETTING S_MISSING_OUTGOING_MAIL_SERVER S_NORMAL_PRIORITY D_MAIL_DIRECTION_AUTOMATIC D_MAIL_DIRECTION_LEFT_TO_RIGHT D_MAIL_DIRECTION_RIGHT_TO_LEFT S_FILE_CHOOSER_IMAGE_FILTER D_HTML_MAIL_ADD_PICTURE_TITLE S_AUTO_DETECTED_ENCODING D_M2_ADD_ATTACHMENT_FAILED_TITLE D_M2_ADD_ATTACHMENT_FAILED_BODY D_MAIL_COMPOSE_WINDOW_ADDRESS_ERROR_TITLE D_MAIL_COMPOSE_WINDOW_ADDRESS_ERROR_CONTENT //controllers/ComposeWindowOptionsController.cpp S_MAIL_DEFAULT_OUTGOING_ACCOUNT S_MAIL_USE_LAST_USED_ACCOUNT //widgets/richtexteditor.cpp S_COMPOSE_OTHER_FONTS // windows/MailDesktopWindow.cpp DI_IDSTR_M2_COL_ATTACHMENTS // + widgets/OpAttachmenList.cpp, setup/standard_menu.ini DI_IDSTR_M2_MAILVIEWTOOLBAR_QUICKREPLY SI_IDSTR_MSG_MAILFREPFS_INVALID_SETTINGS_CAP SI_SAVE_BUTTON_TEXT // + dialogs/DownloadDialog.cpp, setup/standard_toolbar.ini S_CANCEL_MESSAGE S_CANCLE_MESSAGE_WARNING S_MAIL_HEADER_TIME_FORMAT S_MAIL_PANEL_COPY_FAILED // + panels/MailPanel.cpp S_NO_MESSAGE_SELECTED S_NO_VIEW_SELECTED S_QUICK_REPLY_GHOST_TEXT S_READONLY_MESSAGE S_READONLY_MESSAGE_WARNING S_UNREAD_AND_TOTAL_MAIL_HEADER S_UNREAD_MAIL_HEADER S_WARNING_RUN_ATTACHMENT S_MAIL_INCOMPLETE_MESSAGE_FETCH S_MAIL_INCOMPLETE_MESSAGE_FETCH_ON_NEXT_CHECK S_MAIL_FETCH_COMPLETE_MESSAGE S_MAIL_WILL_BE_FETCHED_ON_NEXT_CHECK S_MAIL_SEARCH_IN_CURRENT_VIEW S_MAIL_SEARCH_IN_ALL_MESSAGES S_MAIL_SAVE_SEARCH_TO_LABEL S_MAIL_SEARCH_IN M_MAIL_VIEW_OPTION_MENU_SHOW_FILTERED M_MAIL_VIEW_OPTION_MENU_SHOW_MAILINGLIST M_MAIL_VIEW_OPTION_MENU_SHOW_NEWSFEEDS M_MAIL_VIEW_OPTION_MENU_SHOW_NEWSGR M_MAIL_VIEW_OPTION_MENU_SHOW_READ M_MAIL_VIEW_OPTION_MENU_SHOW_SPAM M_MAIL_VIEW_OPTION_MENU_SHOW_TRASH M_MAIL_VIEW_OPTION_MENU_SHOW_SENT M_MAIL_VIEW_OPTION_MENU_SHOW_DUPLICATES S_MAIL_SUPPRESS_EXTERNAL_EMBEDS S_MAIL_DISPLAY_ELEMENTS_MESSAGE S_MAIL_APPLY_FOR_ALL_MESSAGES_FROM S_MAIL_SUPPRESS_EXTERNAL_EMBEDS_CONTACT S_MAIL_SHOW_MORE_CONTACTS S_WEBFEEDS_FEED_AUTHOR S_MAIL_FLAG_MESSAGE S_MAIL_UNFLAG_MESSAGE M_MAIL_SORT_BY_DEFAULT M_MAIL_SORT_BY_STATUS M_MAIL_SORT_BY_SUBJECT M_MAIL_SORT_BY_LABEL M_MAIL_SORT_BY_SENT_DATE M_MAIL_SORT_BY_STATUS M_MAIL_SORT_BY_SIZE S_MAIL_EXPAND_MESSAGE M_GROUP_MAILS M_MAIL_GROUP_BY_NONE M_MAIL_GROUP_BY_READ M_MAIL_GROUP_BY_FLAG M_MAIL_GROUP_BY_DATE M_MAIL_REPLY_TO_SUBMENU M_MAIL_INDEX_ITEM_POPUP_MENU_PREVIOUS_UNREAD S_DEFAULT_MAIL_SETTINGS M_MAIL_GO_TO_CONTACT S_MAIL_THREAD_GO_BACK_TO S_MAIL_VIEW_SETTINGS_TOOLTIP S_SEARCH_FOR_FEEDS S_SEARCH_ALL_FEEDS // widgets/MessageHeaderGroup.cpp S_MAIL_QUICKREPLY_TO_SENDER S_MAIL_QUICKREPLY_TO_LIST S_MAIL_QUICKREPLY_TO_REPLY_TO_HEADER // src/ui/accessmodel.cpp DI_IDSTR_M2_COL_ACTIVECONTACTS DI_IDSTR_M2_COL_ACTIVETHREADS DI_IDSTR_M2_COL_ATTACHMENTS // + src/ui/indexmodel.cpp DI_IDSTR_M2_COL_INDEX DI_IDSTR_M2_COL_LABELS DI_IDSTR_M2_COL_LIVESEARCHES DI_IDSTR_M2_COL_MAILINGLISTS DI_IDSTR_M2_COL_MYMAIL DI_IDSTR_M2_COL_NEWSGROUPS M_VIEW_HOTLIST_MENU_INFO M_VIEW_HOTLIST_MENU_MAIL // + src/ui/indexmodel.cpp SI_DIRECTORY_COLOUMN_SIZE SI_IDSTR_CL_NAME_COL S_IMAP_FOLDERS S_MY_FOLDERS S_PROGRESS_TYPE_TOTAL S_SEARCHING_FOR // src/ui/indexmodel.cpp DI_IDSTR_M2_COL_TO DI_IDSTR_M2_COL_TOLABEL DI_IDSTR_M2_COL_TOSENT DI_IDSTR_M2_COL_TOSUBJECT DI_IDSTR_M2_COL_FROM DI_IDSTR_M2_COL_FROMLABEL DI_IDSTR_M2_COL_FROMSENT DI_IDSTR_M2_COL_FROMSUBJECT S_ACCOUNT_STATUS // + src/ui/accountsmodel.cpp S_FORMAT_TIME_TODAY S_HIGHEST_PRIORITY S_HIGH_PRIORITY S_LOWEST_PRIORITY S_LOW_PRIORITY S_M2_COL_SIZE S_NO_LABEL S_MAIL_COL_STATUS S_FEED_PUBLISHED S_LOADING_MESSAGE S_MAIL_GROUP_HEADER_TODAY S_MAIL_GROUP_HEADER_YESTERDAY S_MAIL_GROUP_HEADER_LAST_WEEK S_MAIL_GROUP_HEADER_EARLIER_THIS_MONTH S_MAIL_GROUP_HEADER_MONDAY S_MAIL_GROUP_HEADER_TUESDAY S_MAIL_GROUP_HEADER_WEDNESDAY, S_MAIL_GROUP_HEADER_THURSDAY S_MAIL_GROUP_HEADER_FRIDAY S_MAIL_GROUP_HEADER_SATURDAY S_MAIL_GROUP_HEADER_SUNDAY S_MAIL_GROUP_HEADER_JANUARY S_MAIL_GROUP_HEADER_FEBRUARY S_MAIL_GROUP_HEADER_MARCH S_MAIL_GROUP_HEADER_APRIL S_MAIL_GROUP_HEADER_MAY S_MAIL_GROUP_HEADER_JUNE S_MAIL_GROUP_HEADER_JULY S_MAIL_GROUP_HEADER_AUGUST S_MAIL_GROUP_HEADER_SEPTEMBER S_MAIL_GROUP_HEADER_OCTOBER S_MAIL_GROUP_HEADER_NOVEMBER S_MAIL_GROUP_HEADER_DECEMBER S_MAIL_GROUP_HEADER_OLDER S_MAIL_GROUP_HEADER_OTHER S_MAIL_GROUP_HEADER_UNREAD S_MAIL_GROUP_HEADER_FLAGGED // src/ui/groupsmodel.cpp S_FOLDER_TYPE S_GROUP S_ROOM_TYPE S_RSS_TYPE S_STATUS S_SUBSCRIBED S_TOPIC_TYPE S_USERS_TYPE // + src/ui/chattersmodel.cpp // src/ui/accountsmodel.cpp D_M2_ACCOUNT_PROPERTIES_INCOMING D_M2_ACCOUNT_PROPERTIES_OUTGOING S_ACCOUNT_ACCOUNT // src/ui/chatroomsmodel.cpp DI_IDSTR_M2_COL_IRCROOM D_SUBSCRIBE_CHAT SI_IDSTR_IM_STATUS_1 SI_IDSTR_IM_STATUS_10 SI_IDSTR_IM_STATUS_2 SI_IDSTR_IM_STATUS_3 SI_IDSTR_IM_STATUS_4 SI_IDSTR_IM_STATUS_6 SI_IDSTR_IM_STATUS_7 // widgets/MailSearchField.cpp S_SEARCH_FOR_MAIL S_CLEAR_SEARCHES // controllers/LabelPropertiesController.cpp S_MY_FOLDERS M_INDEX_ITEM_POPUP_MENU_NEW_FILTER D_MAIL_REMOVE_LABEL D_MAIL_LABEL_NAME D_MAIL_LABEL_ICON D_MAIL_INDEX_PROPERTIES_RULES S_FILTER_OR S_FILTER_AND S_FILTER_SUBJECT S_FILTER_FROM_HEADER S_FILTER_TO_HEADER S_FILTER_CC_HEADER S_FILTER_REPLYTO_HEADER S_FILTER_NEWSGROUPS_HEADER S_FILTER_ANY_HEADER S_FILTER_BODY S_FILTER_ENTIRE_MESSAGE S_FILTER_CONTAINS S_FILTER_DOES_NOT_CONTAIN S_FILTER_MATCHES_REGEXP D_MAIL_LABEL_REMOVE_RULE D_MAIL_LABEL_ADD_RULE D_MAIL_LABEL_OPTIONS D_MAIL_INDEX_PROPERTIES_MARK_AS_FILTERED D_M2_ACCOUNT_PROPERTIES_MARK_MATCH_READ D_MAIL_INDEX_PROPERTIES_LEARN_FROM_MESSAGES_ADDED D_MAIL_LABEL_APPLY_RULES_ONLY_TO_NEW D_MAIL_LABEL_IMAP_OPTIONS D_MAIL_LABEL_IMAP_SYNCHRONIZATION_KEYWORD M_MAIL_CUSTOM M_MAIL_WHITE_LABEL M_MAIL_BLACK_LABEL M_MAIL_BLUE_LABEL M_MAIL_GREEN_LABEL M_MAIL_RED_LABEL M_MAIL_YELLOW_LABEL M_MAIL_PURPLE_LABEL // controllers/DefaultMailViewPropertiesController.cpp D_MAIL_WINDOW_LAYOUT D_MAIL_LIST_SORTING_DEFAULTS D_MAIL_MAXIMIZE_MESSAGES // controllers/IndexViewPropertiesController.cpp S_MAIL_SORTING_FOR_VIEW S_MAIL_OVERRIDE_SORTING_FOR_THIS_VIEW #endif // M2_SUPPORT
#ifndef CONFIGURATIONREADERTEST_H #define CONFIGURATIONREADERTEST_H #include <QTemporaryFile> #include "AutoTest.h" namespace common { namespace util { namespace tests { class ConfigurationReaderTest : public QObject { Q_OBJECT public: ConfigurationReaderTest(); private Q_SLOTS: void initTestCase(); void loadFileTest_data(); void loadFileTest(); void loadXmlTest_data(); void loadXmlTest(); void saveTest(); void getValueTest(); void getAttributeTest(); void getSectionTest(); void setValueTest(); private: void setData(); QTemporaryFile schemaFile_; QString validConfig_; QString invalidXmlConfig_; QString malConstructedXmlConfig_; QString validationSchema_; }; } } } #endif // CONFIGURATIONREADERTEST_H
#include <stdlib.h> #include <tuple> class Player; class Room; class Tile { private: bool empty; bool wall; public: Tile(bool e, bool w); bool isWall(); bool isEmpty(); char represent(); }; typedef Tile * TilePtr ; class World { private: int width; int height; TilePtr * array; Tile wall; Tile empty; Tile occupied; int * players; bool fromXML(std::string, bool); public: World( int w, int h ); TilePtr ** getMatrix(); int removeMatrix(TilePtr ** matrix); int addTile(Tile * tile, std::pair<int,int> position); Tile * getTile(std::pair<int,int> position); bool movePlayer( Player * player, std::pair<int, int> position); Tile * getEmpty(); Tile * getWall(); Tile * getOccupied(); int getWidth(); int getHeight(); void * getXML(); std::string getXMLAsString(); bool createFromXML(std::string); bool updateFromXML(std::string); }; bool buildRooms( World *, int, int, int, int, int ); class CorridorBuilder { private: World * world; public: CorridorBuilder( World * ); CorridorBuilder(); bool generate(); bool createMaze(std::pair<int,int>); bool cleanUp(); bool roomsOverlap(Room *, Room *); bool canCarve(std::pair<int,int>, std::pair<int,int>); std::pair<int,int> carve(std::pair<int,int>, std::pair<int,int>); };
#include <math.h> double gauss(double m,double mr,double sigma) { return(exp(-pow(m - mr,2)/(2 * pow(sigma,2)))); }
#include<iostream> #include<cmath> using fptr = double(double); double f(double x); double gaussian(double x); double deriv(double x); double bisection( double xl, double xu, double eps, fptr fun ); double newton(double x0, double eps, fptr fun, fptr fderiv); int main(int argc, char **argv) { double xl=-1.0; double xu= 1.0; double eps= 1.0e-9; double inversa_bisection= bisection(xl,xu,eps,f); double x0= 0.0; double inversa_newton= newton(x0,eps,f,deriv); std::cout<< inversa_bisection<<" "<< f(inversa_bisection)<<"\n"; std::cout<< inversa_newton<<" "<< f(inversa_newton)<<"\n"; return 0; } double gaussian( double x) { return (2/M_PI)*std::exp(-(x*x)/2); } double deriv(double x) { return 2*std::exp(-x*x)/std::sqrt(M_PI); // double h = 0.0001; //return (f(x+h/2) - f(x-h/2))/h; } double bisection( double xl, double xu, double eps, fptr fun ) { const int NITERMAX = 10000; double xr = 0.0; int niter = 0; while (niter <= NITERMAX) { xr = 0.5*(xl + xu); if (std::fabs(fun(xr)) <= eps) { break; } else if (fun(xr)*fun(xu) > 0) { xu = xr; } else { xl = xr; } niter++; } std::cout << "biseccion Info -> Niter: " << niter << "\n"; return xr; } double newton(double x0, double eps, fptr fun, fptr fderiv) { const int NITERMAX = 1000; double xr = x0; int niter = 0; while (niter <= NITERMAX) { xr = xr - fun(xr)/fderiv(xr); if (std::fabs(fun(xr)) <= eps) { break; } niter++; } std::cout << "Newton Info -> Niter: " << niter << "\n"; return xr; } double f(double x) { double F= (std::erf(x))- gaussian(x); return F; }
#include <iostream> #include <cstdlib> #include "Scan.h" #include "Source.h" #include "Parser.h" using namespace std; int Trace::call_level = 0; int Trace::trace_on = 0; int Trace::show_symbols = 0; int options = 0; int main(int argc, char* argv[]) { if (argc < 2) { cout << "Niewystarczajace argumenty wykonania!" << endl; return -1; } string filename(argv[1]); //std::cout << "Nazwa pliku:" << endl; //cin >> filename; Source src(filename); Scan scn(src); Execution e; Parser par(scn, e); Synchronize::p = &par; while (par.NextExecutable()); e.run(); system("pause"); return 0; }
#pragma once #define MAX_NUM_GUN 3 class Health; namespace Hourglass { class Entity; class Transform; } class PlayerComp : public Hourglass::IComponent { public: virtual int GetTypeID() const { return s_TypeID; } void LoadFromXML( tinyxml2::XMLElement* data ); virtual void Init(); virtual void Start(); virtual void Update(); void OnMessage(hg::Message* msg); const Vector3& GetPosMouseWorld() const { return m_PosMouseWorld; } void SetMovementLock( bool movementLock ) { m_MovementLock = movementLock; } void SetSpeed( float speed ) { m_Speed = speed; } void SetGun(hg::Entity* gun, int index); void PostInit(); float GetCurrentAmmoRatio()const; float GetCurrentHealthRatio()const; float GetCurrentTotalAmmoRatio()const; void HandleControl(); void Dodge(const Vector3 moveDir); void EndDodge(); bool IsDodging() const; //float GetGroundOffset() const; bool RestoreHP(float value); bool RestoreAmmo(float value); // Check if player is alive bool IsPlayerAlive() const; hg::Entity* GetGunLaser(); /** * Make a copy of this component */ virtual hg::IComponent* MakeCopyDerived() const; static uint32_t s_TypeID; private: void SwitchToWeapon(int slot); void UpdateGunTransform(); private: enum Dir { kUp, kDown, kLeft, kRight }; struct Anims { // full body StrID Default; StrID Fire; StrID Dodge; // lower StrID Fwd; StrID FwdLeft; StrID FwdRight; StrID Bwd; StrID BwdLeft; StrID BwdRight; StrID Right; StrID Left; StrID Idle; } m_Anims; int m_curGun; hg::Entity* m_gun[MAX_NUM_GUN]; hg::Transform* upper; hg::Transform* lower; hg::Transform* upperBone; hg::Transform* dodgeBody; hg::Animation* animation = nullptr; float gunHeight; Quaternion upperRotOffset; uint32_t m_MovementLock : 1; uint32_t m_Dodging : 1; Vector3 m_PosMouseWorld; Vector3 m_MoveDirection; void(*Integrate)(XMVECTOR&, XMVECTOR&, float, const XMVECTOR&); Health* m_health; float m_rollTimer; float m_Speed; float m_RunSpeed; float m_DodgeTime; float m_DodgeDuration; float m_DodgeSpeed; bool m_debug; bool m_freeAim; bool m_needRotate; float m_DamageOverlay; float m_DamageDecayTimer; UINT m_powerUp; int m_powerUpAmount; };
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "10192" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif string one,two; int table[105][2]; int CASE = 1; while( getline(cin,one) ){ if( one == "#" ) break; getline(cin,two); memset(table,0,sizeof(table)); for(int i = 1 ; i <= one.size() ; i++ ){ for(int j = 1 ; j <= two.size() ; j++ ){ if( one[i-1] == two[j-1] ) table[j][1] = table[j-1][0]+1; else table[j][1] = max(table[j-1][1],table[j][0]); } for(int j = 1 ; j <= two.size() ; j++ ) table[j][0] = table[j][1]; } printf("Case #%d: you can visit at most %d cities.\n",CASE++,table[two.size()][1]); } return 0; }
#include <cstdlib> #include <cstdio> using namespace std; int main() { // for (int i = 8;i <= 10; ++i) // for (int j = 2;j <= 4;++j) // for (int k = 2;k <= 4;++k) // { // char command[233]; // sprintf(command, "mkdir %d_%d_%d", i, j, k); // system(command); // } for (int i = 8;i <= 10; ++i) for (int j = 2;j <= 4;++j) for (int k = 2;k <= 4;++k) for (int u = 1;u <= 10;++u) { FILE *tmp = fopen("tmp", "w"); fprintf(tmp, "%d %d %d", i, j, k); fclose(tmp); char command[233]; sprintf(command, "./main < tmp >> %d_%d_%d/out", i, j, k); printf("%s\n", command); system(command); } return 0; }
#include "Raycaster.h" #include "Renderer/Renderer.h" std::vector<ColliderComponent*> current_colliders = std::vector<ColliderComponent*>(); // Only returns normal opposite of direction bool raycast(glm::vec2 from_position, glm::vec2 direction, float distance, RaycastHit& hit) { for (int i = 0; i < current_colliders.size(); i++) { ColliderComponent& col = *current_colliders[0]; glm::vec2 point = from_position + (direction * distance); glm::vec2 b_pos = col.Position; glm::vec2 b_scale = col.Scale; glm::vec2 b_max = glm::vec2(b_pos.x + b_scale.x * 0.5f, b_pos.y + b_scale.y * 0.5f); glm::vec2 b_min = glm::vec2(b_pos.x - b_scale.x * 0.5f, b_pos.y - b_scale.y * 0.5f); //render_quad(point, glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), glm::vec2(0.05f, 0.05f)); //render_quad(col.Position, glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), col.Scale); glm::vec4 hitClr = glm::vec4(0.0f, 1.0f, 0.0f, 1.0f); glm::vec4 noHitClr = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f); if (point.x < b_max.x && point.x > b_min.x && point.y < b_max.y && point.y > b_min.y) { // TODO convert to extents to avoid * 0.5f float col_pos_y = col.Position.y + (col.Scale.y * 0.5f); float col_pos_x = col.Position.x + ((col.Scale.x * 0.5f) * -direction.x); glm::vec2 hit_point = glm::vec2( col_pos_x, col_pos_y ); hit.point = hit_point; hit.normal = -direction; // TODO actually calculate normal //render_quad(point, hitClr, glm::vec2(0.05f, 0.05f)); //render_quad(col.Position, hitClr, col.Scale); return true; } else { //render_quad(point, noHitClr, glm::vec2(0.05f, 0.05f)); //render_quad(col.Position, noHitClr, col.Scale); } } return false; } void set_target_colliders(std::vector<ColliderComponent*> colliders) { current_colliders = colliders; } void add_target_collider(ColliderComponent* collider) { current_colliders.push_back(collider); }
#include <iostream> using namespace std; int signInversion(int a){ int sign = a > 0 ? 1 : -1; int delta = sign; int res = 0; while(a != 0){ bool diffSign = (a + delta > 0) != (a > 0); if(a + delta != 0 && diffSign){ delta = sign; } res += delta; a += delta; delta += delta; } return res; } int subtract(int a, int b){ return a + signInversion(b); } int abs(int a){ return a > 0 ? a : signInversion(a); } int multi(int sum, int times, int a){ if(times == 0){ return sum; } return multi(sum + a, times - 1, a); } int multi(int a, int b){ bool isMinus = (a > 0) != (b > 0); int absA = abs(a); int absB = abs(b); int max = absA > absB ? absA : absB; int min = absA > absB ? absB : absA; return isMinus ? signInversion(multi(0, min, max)) : multi(0, min, max); } int division(int a, int b, int sum, int times){ if(sum == a){ return times; } return division(a, b, sum + b, times + 1); } int division(int a, int b){ bool isMinus = (a < 0) != (b < 0); return isMinus ? signInversion(division(abs(a), abs(b), 0, 0)) : division(abs(a), abs(b), 0, 0); } int main(void){ cout << subtract(10, 8) << endl; // 2 cout << subtract(9, -3) << endl; // 12 cout << multi(3, 8) << endl; // 24 cout << multi(9, -3) << endl; // -27 cout << division(10, 2) << endl; // 5 cout << division(9, -3) << endl; // -3 return 0; }
//Calculate the differences and return if is a valid region bool indel_find_valid(float value1, float value2, float min_cover, float threshold) { //Calculate the first difference float diff1 = (value2 != 0) ? value1 / value2 : 1; //Calculate the second difference float diff2 = (value1 != 0) ? value2 / value1 : 1; //Check the first difference if(min_cover <= value1 && diff1 == 1){ diff1 = value1; } //Check the second difference if(min_cover <= value2 && diff2 == 1){ diff2 = value2; } //Check the first condition bool condition1 = (threshold <= diff1 || threshold <= diff2) ? true : false; //Get the second condition value bool condition2 = (min_cover <= value1 || min_cover <= value2) ? true : false; //Check the conditions if(condition1 == false || condition2 == false) { //Return false return false; } //Default, return true return true; }
#ifndef CARD_H #define CARD_H #include <cstdlib> #include <iostream> using namespace std; class Card{ private: int suit; int rank; public: string get_card_suit(); int get_card_rank(); void set_card_suit(string); void set_card_rank(int); }; #endif
#pragma once #define PHNT_MODE PHNT_MODE_KERNEL #define PHNT_VERSION PHNT_THRESHOLD #include <ntifs.h> #include <phnt.h> #include <cstddef> #include <cstdint> #include "nt/memory.h" #include "nt/portable_executable.h" #include "nt/reference.h" namespace nt { void* kernel_base_address(); std::size_t kernel_base_size(); std::uintptr_t get_process_cr3(PEPROCESS process); template <typename T = void*> auto get_system_routine(const wchar_t* routine_name) -> T { UNICODE_STRING routine_unicode_name; RtlInitUnicodeString(&routine_unicode_name, routine_name); return reinterpret_cast<T>(MmGetSystemRoutineAddress(&routine_unicode_name)); } } // undocumented imports extern "C" __declspec(dllimport) POBJECT_TYPE* IoDriverObjectType; extern "C" __declspec(dllimport) PLIST_ENTRY PsLoadedModuleList; extern "C" __declspec(dllimport) NTSTATUS NTAPI MmCopyVirtualMemory(PEPROCESS FromProcess, PVOID FromAddress, PEPROCESS ToProcess, PVOID ToAddress, SIZE_T BufferSize, KPROCESSOR_MODE PreviousMode, PSIZE_T NumberOfBytesCopied); extern "C" __declspec(dllimport) NTSTATUS NTAPI ObReferenceObjectByName(PUNICODE_STRING ObjectName, ULONG Attributes, PACCESS_STATE AccessState, ACCESS_MASK DesiredAccess, POBJECT_TYPE ObjectType, KPROCESSOR_MODE AccessMode, PVOID ParseContext OPTIONAL, PVOID* Object); extern "C" __declspec(dllimport) PVOID NTAPI PsGetProcessSectionBaseAddress(PEPROCESS Process); extern "C" __declspec(dllimport) PIMAGE_NT_HEADERS NTAPI RtlImageNtHeader(PVOID Base); extern "C" __declspec(dllimport) PPEB NTAPI PsGetProcessPeb(PEPROCESS Process); // unexported extern PMMPTE(NTAPI *MiGetPteAddress)(PVOID VirtualAddress);
/* leetcode 136 * * * */ #include <string> #include <unordered_set> #include <algorithm> using namespace std; class Solution { public: int singleNumber(vector<int>& nums) { int ans = 0; for (auto i:nums) { ans = ans ^ i; } return ans; } }; /************************** run solution **************************/ int _solution_run(vector<int>& nums) { Solution leetcode_136; int ans = leetcode_136.singleNumber(nums); return ans; } #ifdef USE_SOLUTION_CUSTOM string _solution_custom(TestCases &tc) { } #endif /************************** get testcase **************************/ #ifdef USE_GET_TEST_CASES_IN_CPP vector<string> _get_test_cases_string() { return {}; } #endif
#include "inilib.h" int main(int argc, char **argv) { ///> н¨xml INI::registry reg("c:\\1.ini"); reg["section1"]["user"] = "siren1"; reg["section1"]["email"] = "siren186@163.com"; reg["section2"]["user"] = "siren2"; reg["section2"]["date"] = "2014-05-12"; reg.file_write(); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2005 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef SVG_ANIMCONTEXT_H #define SVG_ANIMCONTEXT_H #ifdef SVG_SUPPORT #include "modules/dom/domeventtypes.h" #include "modules/logdoc/htm_elm.h" #include "modules/svg/src/SVGObject.h" #include "modules/svg/src/SVGAttribute.h" #include "modules/svg/src/SVGTimeValue.h" #include "modules/svg/src/SVGTimedElementContext.h" #include "modules/svg/src/SVGKeySpline.h" #include "modules/svg/src/SVGUtils.h" #include "modules/svg/src/animation/svganimationinterval.h" #include "modules/svg/src/animation/svganimationschedule.h" #include "modules/svg/src/animation/svganimationcalculator.h" class LayoutProperties; class SVGMotionPath; class SVGDocumentContext; class SVGAnimationWorkplace; class SVGAnimationArguments; /** * This class contains state information about one animation element. * * A pointer to an instance of this class is given to the HTML_Element * that is of type {Markup::SVGE_SET, Markup::SVGE_ANIMATE, * Markup::SVGE_ANIMATETRANSFORM, Markup::SVGE_ANIMATECOLOR, * Markup::SVGE_ANIMATEMOTION}. * */ class SVGAnimationInterface : public SVGTimingInterface { public: SVGAnimationInterface(HTML_Element *animation_element) : SVGTimingInterface(animation_element) {} virtual ~SVGAnimationInterface() {} OP_STATUS SetAnimationArguments(SVGDocumentContext *doc_ctx, SVGAnimationArguments& animation_arguments, SVGAnimationTarget *&animation_target); /**< Set animation arguments * * By returning some error other than OpStatus::ERR_NO_MEMORY, the * animation of this element is disabled. The element will still * act as a timed element, creating intervals and dispatching * events. */ #ifdef SVG_APPLY_ANIMATE_MOTION_IN_BETWEEN /** * Undocumented. Move to SVGUtils? */ void MarkTransformAsNonAdditive(HTML_Element *animated_element); #endif // SVG_APPLY_ANIMATE_MOTION_IN_BETWEEN static BOOL IsFilteredByRequirements(HTML_Element* layouted_elm) { return !SVGUtils::ShouldProcessElement(layouted_elm); } protected: static BOOL IsAnimatable(HTML_Element* target_element, Markup::AttrType attr_name, int ns_idx); virtual SVGAnimationInterface* GetAnimationInterface() { return this; } }; class SVGAnimationElement : public SVGInvisibleElement, public SVGAnimationInterface { public: SVGAnimationElement(HTML_Element* element) : SVGInvisibleElement(element), SVGAnimationInterface(element) {} virtual class SVGTimingInterface* GetTimingInterface() { return static_cast<SVGTimingInterface*>(this); } virtual class SVGAnimationInterface* GetAnimationInterface() { return static_cast<SVGAnimationInterface*>(this); } }; #endif // SVG_SUPPORT #endif // SVG_ANIMCONTEXT_H
#include "testApp.h" #include "omp.h" //-------------------------------------------------------------- void testApp::setup(){ ofSetLogLevel( OF_LOG_ERROR ); ofSetVerticalSync( true ); ofSetFrameRate( 60 ); ofSetTextureWrap( GL_REPEAT ); TIME_SAMPLE_SET_FRAMERATE( 30.0f ); TIME_SAMPLE_SET_DRAW_LOCATION( TIME_MEASUREMENTS_TOP_RIGHT ); post.init( 1920, 1080 ); nwPass = post.createPass<NoiseWarpPass>(); nwPass->setEnabled( false ); post.createPass<ContrastPass>()->setEnabled( true ); post.setFlip( false ); blackWhiteColor.addColor( 255, 255, 255 ); kinect.init(); stoneCurtain.setBrushCollection( brushCollection ); stoneCurtain.setColorCollection( blackWhiteColor ); //stoneCurtain.render(); barbWire.init(); int x = 0; int y = 0; int w = 1920; int h = 1080; warper.setSourceRect( ofRectangle( 0, 0, ofGetWidth(), ofGetHeight() ) ); // this is the source rectangle which is the size of the image and located at ( 0, 0 ) warper.setTopLeftCornerPosition( ofPoint( x, y ) ); // this is position of the quad warp corners, centering the image on the screen. warper.setTopRightCornerPosition( ofPoint( x + w, y ) ); // this is position of the quad warp corners, centering the image on the screen. warper.setBottomLeftCornerPosition( ofPoint( x, y + h ) ); // this is position of the quad warp corners, centering the image on the screen. warper.setBottomRightCornerPosition( ofPoint( x + w, y + h ) ); // this is position of the quad warp corners, centering the image on the screen. warper.setup(); warper.load(); // reload last saved changes. points = 350; reinit(); setupGui(); doGrow = false; currentCurtainY = -1080; stonesTex.init(); cutter.init(); for( int j = 0; j < 10; j++ ) { for( int i = 0; i < stones.size(); i++ ) { stones.at( i ).grow( voro.getLine( i ), false ); } } for( int i = 0; i < stones.size(); i++ ) { stones.at( i ).grow( voro.getLine( i ), true ); } //stopmotion.init(); ofBackground( 0 ); } //-------------------------------------------------------------- void testApp::update(){ currentCurtainY += 1; if( doGrow ) { for( int i = 0; i < stones.size(); i++ ) { Stone * s = &stones.at( i ); s->grow( voro.getLine( i ), true ); } } kinect.update(); nwPass->setFrequency( 1.97 ); nwPass->setAmplitude( 0.026 ); //stopmotion.update(); } //-------------------------------------------------------------- void testApp::draw(){ ofBackground( 0 ); ofPushMatrix(); ofMatrix4x4 mat = warper.getMatrix(); ofMultMatrix( mat ); voro.compute(); voro.render(); TS_START_NIF( "noi_render" ); noi.render(); TS_STOP_NIF( "noi_render" ); TS_START_NIF( "lines" ); std::vector< ofPolyline > lines; std::vector< float > transparencies; for( int i = 0; i < stones.size(); i++ ) { lines.push_back( stones.at( i ).border ); transparencies.push_back( 255 ); } TS_STOP_NIF( "lines" ); TS_START( "stonetexrender" ); stonesTex.render( lines, transparencies, ofPoint(1920/2, 1080/2) ); TS_STOP( "stonetexrender" ); TS_START_NIF( "cutout" ); ofFbo * buf = cutter.getCutout( noi, stonesTex.getBuffer() ); TS_STOP_NIF( "cutout" ); TS_START( "draw_wall" ); ofPushStyle(); ofSetColor( 255, stones.at( 0 ).getTransparency() ); int off = 0; //post.begin(); buf->draw( 0, 0 ); //post.end(); ofPopStyle(); TS_STOP( "draw_wall" ); voro.draw( 0, 0 ); //stoneCurtain.draw( 0, currentCurtainY ); //stopmotion.draw(); //barbWire.draw(); //kinect.draw(); ofPopMatrix(); ofPushStyle(); ofSetColor( ofColor::magenta ); warper.drawQuadOutline(); ofSetColor( ofColor::yellow ); warper.drawCorners(); ofSetColor( ofColor::magenta ); warper.drawHighlightedCorner(); ofSetColor( ofColor::red ); warper.drawSelectedCorner(); ofPopStyle(); } //-------------------------------------------------------------- void testApp::keyPressed( int key ){ int randomId = ( int ) ( ofRandom( 0, stones.size() ) ); switch( key ) { case 's': ofSaveScreen( ofToString( ofGetTimestampString() + ".png" ) ); break; case 'f': ofToggleFullscreen(); break; case 'n': reinit(); break; case 'g': doGrow = !doGrow; break; case ' ': gui->toggleVisible(); kinect.displayKinect = !kinect.displayKinect; warper.toggleShow(); break; case 'm': stopmotion.moveRandom( 3 ); break; case 'k': stopmotion.setGrowing( true ); break; } unsigned idx = key - '0'; if( idx < post.size() ) post[ idx ]->setEnabled( !post[ idx ]->getEnabled() ); } //-------------------------------------------------------------- void testApp::keyReleased( int key ){ } //-------------------------------------------------------------- void testApp::mouseMoved( int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged( int x, int y, int button ){ } //-------------------------------------------------------------- void testApp::mousePressed( int x, int y, int button ){ } //-------------------------------------------------------------- void testApp::mouseReleased( int x, int y, int button ){ } //-------------------------------------------------------------- void testApp::windowResized( int w, int h ){ } //-------------------------------------------------------------- void testApp::gotMessage( ofMessage msg ){ } //-------------------------------------------------------------- void testApp::dragEvent( ofDragInfo dragInfo ){ } void testApp::guiEvent( ofxUIEventArgs &e ) { if( e.getName() == "Init" ) { ofxUIButton * button = e.getButton(); if( button->getValue() == 1 ) { reinit(); } } else if( e.getName() == "Size" ) { ofxUISlider * slider = e.getSlider(); for( int i = 0; i < stones.size(); i++ ) { stones.at( i ).setSize( slider->getValue() ); } } else if( e.getName() == "Fuzzy" ) { ofxUISlider * slider = e.getSlider(); for( int i = 0; i < stones.size(); i++ ) { stones.at( i ).setFuzzy( slider->getValue() ); } } else if( e.getName() == "Radius" ) { ofxUISlider * slider = e.getSlider(); for( int i = 0; i < stones.size(); i++ ) { stones.at( i ).setRadius( slider->getValue() ); } } else if( e.getName() == "Transparency" ) { ofxUISlider * slider = e.getSlider(); for( int i = 0; i < stones.size(); i++ ) { stones.at( i ).setTransparency( slider->getValue() ); } } else if( e.getName() == "VoroTransparency" ) { ofxUISlider * slider = e.getSlider(); voro.setTransparency( slider->getValue() ); } else if( e.getName() == "StonesTransparency" ) { ofxUISlider * slider = e.getSlider(); for( int i = 0; i < stones.size(); i++ ) { stones.at( i ).setTransparency( slider->getValue() ); } } else if( e.getName() == "BorderTransparency" ) { ofxUISlider * slider = e.getSlider(); for( int i = 0; i < stones.size(); i++ ) { stones.at( i ).setBorderTransparency( slider->getValue() ); } } else if( e.getName() == "Voronoi Smooth" ) { ofxUISlider * slider = e.getSlider(); voro.setSmoothAmount( slider->getValue() ); } else if( e.getName() == "Voronoi Thickness" ) { ofxUISlider * slider = e.getSlider(); voro.setLineThickness( slider->getValue() ); } else if( e.getName() == "CurtainTransparency" ) { ofxUISlider * slider = e.getSlider(); stoneCurtain.setTransparency( slider->getValue() ); } else if( e.getName() == "Stone Border Size" ) { ofxUISlider * slider = e.getSlider(); for( int i = 0; i < stones.size(); i++ ) { stones.at( i ).setBorderSize( slider->getValue() ); } } else if( e.getName() == "Barbwire Color" ){ ofxUISlider * slider = e.getSlider(); barbWire.setHue( slider->getValue() ); } else if( e.getName() == "Barbwire Transparency" ){ ofxUISlider * slider = e.getSlider(); barbWire.setTransparency( slider->getValue() ); } else if( e.getName() == "Barbwire Thickness" ){ ofxUISlider * slider = e.getSlider(); barbWire.setThickness( slider->getValue() ); } else if( e.getName() == "Barbwire Brightness" ){ ofxUISlider * slider = e.getSlider(); barbWire.setBrightness( slider->getValue() ); } else if( e.getName() == "Stones Saturation" ){ ofxUISlider * slider = e.getSlider(); for( int i = 0; i < stones.size(); i++ ) { stones.at( i ).setSaturation( slider->getValue() ); } } else if( e.getName() == "Border ON/OFF" ){ ofxUIToggle * toggle = e.getToggle(); for( int i = 0; i < stones.size(); i++ ) { stones.at( i ).toggleRenderBorder( toggle->getValue() ); } } else if( e.getName() == "Voronoi ON/OFF" ){ ofxUIToggle * toggle = e.getToggle(); voro.toggleRender(); } } void testApp::setupGui() { Stone testStone = stones.at( 0 ); gui = new ofxUISuperCanvas( "The Other", OFX_UI_FONT_MEDIUM ); gui->addSpacer(); gui->addFPSSlider( "FPS" ); gui->addSpacer(); gui->addSlider( "Points", 0.0f, 200.0f, &points ); gui->addSlider( "Size", 0.0f, 100.0f, 35.0f, 200, 20 ); gui->addSlider( "Fuzzy", 0.0f, 150.0f, 30.0f, 200, 20 ); gui->addSlider( "Radius", 0.0f, 250.0f, 80.0f, 200, 20 ); gui->addSlider( "Transparency", 0.0f, 255.0f, 255.0f, 200, 20 ); gui->addSpacer(); gui->addLabel( "Stone" ); gui->addSlider( "Stone Border Size", 0.0, 60.0, 0.0, 200.0, 20.0 ); gui->addSlider( "StonesTransparency", 0.0f, 255.0, 255.0f ); gui->addSlider( "Stones Saturation", 0.0f, 255.0, 255.0f ); gui->addSlider( "BorderTransparency", 0.0f, 255.0f, 255.0f ); gui->addSpacer( 3.0f ); gui->setWidgetPosition( OFX_UI_WIDGET_POSITION_RIGHT ); gui->addToggle( "Border ON/OFF", true ); gui->setWidgetPosition( OFX_UI_WIDGET_POSITION_DOWN ); gui->addLabel( "Kinect" ); gui->addSlider( "KinectDistance", 0.0f, 255.0f, &kinect.kinectToStoneDistance ); gui->addSpacer(); gui->addLabel( "Voronoi" ); gui->addSlider( "VoroTransparency", 0.0f, 255.0, 255.0f ); gui->addSpacer( 3.0f ); gui->setWidgetPosition( OFX_UI_WIDGET_POSITION_RIGHT ); gui->addToggle( "Voronoi ON/OFF", true ); gui->setWidgetPosition( OFX_UI_WIDGET_POSITION_DOWN ); gui->addSlider( "Voronoi Thickness", 0.0, 20.0, voro.getLineThickness(), 200.0, 20.0 ); gui->addSlider( "Voronoi Smooth", 0.0f, 40.0f, voro.getSmoothAmount(), 200.0, 20.0 ); gui->addSpacer(); gui->addLabel( "Stone Curtain" ); gui->addSlider( "CurtainTransparency", 0.0f, 255.0f, 255.0f ); gui->addSpacer(); gui->addLabel( "Barbwire" ); gui->addSlider( "Barbwire Color", 0.0f, 360.0f, barbWire.getHue(), 200.0, 20.0 ); gui->addSlider( "Barbwire Transparency", 0.0f, 255.0, barbWire.getTransparency(), 200.0, 20.0 ); gui->addSlider( "Barbwire Brightness", 0.0f, 255.0, barbWire.getBrightness(), 200.0, 20.0 ); gui->addSlider( "Barbwire Thickness", 0.0f, 10.0, barbWire.getThickness(), 200.0, 20.0 ); gui->addButton( "Init", false ); gui->addSpacer(); gui->addSlider( "w1", 0.0, 1.0, &noi.w1 ); gui->addSlider( "w2", 0.0, 1.0, &noi.w2 ); gui->addSlider( "w3", 0.0, 1.0, &noi.w3 ); gui->addSlider( "w4", 0.0, 1.0, &noi.w4 ); gui->autoSizeToFitWidgets(); ofAddListener( gui->newGUIEvent, this, &testApp::guiEvent ); gui->loadSettings( "guiSettings.xml" ); } void testApp::reinit() { voro.clear(); stones.clear(); for( int i = 0; i < (int)(points); i++ ) { voro.addRandomPoint(); } voro.compute(); for( int i = 0; i < voro.pts.size(); i++ ) { ofVec2f * p = &voro.pts.at( i ); Stone s; s.init( p->x, p->y, *voro.getLine( i ) ); stones.push_back( s ); } } void testApp::exit() { warper.save(); }
#include <iostream> using namespace std; //for print function of list struct Node { int data; Node *left, *right; }; //a recursive function for converting a binary tree into a sorted linked list //uses the root of the tree and the head pointer of list void treeSorter(Node* root, Node** head_ref) { // base case if (root == NULL) return; // recursive call for right side treeSorter(root->right, head_ref); // places the root in the linked list root->right = *head_ref; // change the pointer on the left if (*head_ref != NULL) (*head_ref)->left = root; // changes head *head_ref = root; //recursive call for the left side treeSorter(root->left, head_ref); } // creates nodes for the tree Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } // prints double linked list. void printDouble(Node* head) { printf("the linked list of the tree from lowest to highest\n"); while (head) { printf("%d ", head->data); head = head->right; } } // makes a tree that we convert int main() { Node* root = newNode(10); root->left = newNode(4); root->right = newNode(11); root->left->left = newNode(2); root->left->right = newNode(5); root->right->right = newNode(13); root->right->right->left = newNode(12); root->right->right->right = newNode(15); root->left->left->left = newNode(1); root->left->left->right = newNode(3); /*this creates a binary tree that looks like this 10 / \ 4 11 / \ \ 2 5 13 / \ / \ 1 3 12 15 */ Node* head = NULL; treeSorter(root, &head); printDouble(head); system("PAUSE"); return 0; }
/* * SOCCERV3.c * * Created: 2017-010-02 * Author: JEON HAKYEONG (전하경) * * History * * 2017-10-02 * Migration From AtmelStudio. * */ //카메라 유무 설정 //#define CameraExist true //카메라가 있음. #define CameraExist false //카메라가 없음. // // 키 입력 값 // #define ENTER (~PINB & 0x40) //ENTER KEY 입력 값 #define PREV (~PINB & 0x20) //PREV KEY 입력 값 #define NEXT (~PINB & 0x10) //NEXT KEY 입력 값 // // 공격 수비 공 판단 기준 값 // #define SHOOT 165 //공격수 슈팅 기준값, 먼곳에서 슈팅을 시도하면 이값을 키운다. #define NEAR 13 //공격수 공 근처의 기준값, 공을 끼고 너무 크게 돌면 이값을 키운다. #define SHOOT2 180 //수비수 슈팅 기준값, 먼곳에서 슈팅을 시도하면 이값을 키운다. #define NEAR2 13 //수비수 공 감지 기준값, 가반응거리가 짧으면 이값을 줄인다. // // 아래 정의값들은 경기장 테두리의흰색 선의 기준값입니다. // 경기장에서 직접 측정하여 변경하던지 가변저항을 조정하세요. // 아래 설정값 보다 큰값이 입력되면 흰색 경계선으로 인식 //-------------------------------------------------------------------------- // 센서별로 흰색라인에 올려 놓고 가변저항을 조정하여 200정도에 맞춤. // 경기장 바닥에서 입력되는 값과 흰색에서 입력되는 값의 중간 또는 3분의 2 정도로 설정 //--------------------------------------------------------------------------- // #define Line0_White 100 // 0시 방향 경계선 감지 기준 값 #define Line1_White 100 // 3시 방향 경계선 감지 기준 값 #define Line2_White 100 // 6시 방향 경계선 감지 기준 값 #define Line3_White 100 // 9시 방향 경계선 감지 기준 값 // // 위 기준값을 넘은 경우가 있으면 아래 변수에 기록이 되어짐. // 선을 감지하고 그에따른 액션을 수행한후에는 아래값을 Clear 시켜주세요. // // 0 bit : 0h direction line detected // 1 bit : 3h direction line detected // 2 bit : 6h direction line detected // 3 bit : 9h direction line detected unsigned char LineDetected=0; //경계라인 감지 상태 값 //0 Bit : 0시방향 감지 //1 Bit : 3시방향 감지 //2 Bit : 6시방향 감지 //3 Bit : 9시방향 감지 unsigned char Escape_Dir[16] = { 0 // 경계라인 감지 안됨 ,6 // 0시 방향 감지 - 6시방향으로 탈출 ,9 // 3시 방향 감지 - 9시 방향으로 탈출 ,7 // 0시 3시 방향 감지 - 7시 방향으로 탈출 ,0 // 6시 방향 감지 - 0시 방향으로 탈출 ,3 // 0시 6시 방향 감지 - 3시 방향(또는 9시 방향)으로 탈출 ,10 // 3시, 6시 방향 감지 - 10시 방향으로 탈출 ,9 // 0,3,6시 방향 감지 - 9시 방향으로 탈출 ,3 // 9시 방향 감지 - 3시 방향으로 탈출 ,4 // 0,9시 방향 감지 - 4시 방향으로 탈출 ,6 // 3,9시 방향 감지 - 6시 방향(또는 0시 방향)으로 탈출 ,6 // 0,3,9시 방향 감지 - 6시 방향으로 탈출 ,2 // 6,9시 방향 감지 - 2시 방향으로 탈출 ,3 // 0,6,9 시 방향 감지 - 3시 방향으로 탈출 ,0 // 3,6,9시 방향 감지 - 0시 방향으로 탈출 ,0};// 모든 방향 감지됨 - 존재 할 수 없음 (F/W에서 방지 함.) // //Sample Numbers for Average of Analog Value. // #define NumberOfSamples 4 //가능한 변경하지 마세요.. 이값을 변경하고자 하면 Header File쪽도 수정해야 함. //평균을 구하기 위한 배열 volatile unsigned int ADC_Raw[NumberOfSamples+1][18]; // //************************************************************************************ //------------- 여기부터의 변수는 읽기만 하세요. ------------------------ //************************************************************************************ // // 아래 변수에 센서 값들이 들어옵니다. // 읽기만 하시고 절대 쓰지 마세요. // volatile unsigned int ADC_Value[18]; // 0 ~ 11 : 12개의 IR Seeker 값 // 12 ~ 15 : 바닥감지 센서 값 // 16 : 전압 측정 값 // 17 : BALL Caputing 판단 기준 적외선 값 (부정확 함, 이값보다는 0시방향 초음파 거리 측정값( ultra[0] )을 사용하는게 좋음). // // 초음파 센서 거리 측정 값(0~3번 초음파) // volatile unsigned int ultra[4] = {0,0,0,0}; // // 적외선 공 판단 값 // volatile unsigned int ball_dir; //적외선 값이 가장 강하게 보이는 방향. volatile unsigned int max_ir; //가장 강한 적외선 값. // int last_pos = 0; //공이 마지막으로 있던 좌우 방향, 왼쪽 = 1, 오른쪽 = 0; // // // 컴파스 센서 값.(절대값이 아닌 상대적 방위 값) // 처음 파워가 켜진 방향을 상대편 골대 방향으로 인식하며 그값은 180이 된다. // volatile double compass; volatile unsigned int BallCapture=0; // 사용 안함. #define Voltage ((int)((float)ADC_Value[16]*0.625 -2.5)) //************************************************************************************ // 메뉴 디스플레이 volatile char menu = 0; //---------------------------------------------------------------------------- #define KP 1 //---------------------------------------------------------------------------- #include "SOCCERV3.h" #include <TimerOne.h> void view_line(void) { Lcd_Clear(); while(!ENTER) { Lcd_Cmd(LINE1); for(int i=0;i<2; i++) { Lcd_Data(i*3+'0'); Lcd_String("h: "); DigitDisplay(ADC_Value[i+12]); Lcd_Data(' '); } Lcd_Cmd(LINE2); for(int i=2;i<4; i++) { Lcd_Data(i*3+'0'); Lcd_String("h: "); DigitDisplay(ADC_Value[i+12]); Lcd_Data(' '); } delay(200); } while(ENTER) ; } void view_ir(void) { int submenu=0; Lcd_Clear(); while(!ENTER) { if(PREV) { while(PREV) ; submenu-=3; if (submenu<0) submenu=9; } else if(NEXT) { while(NEXT) ; submenu+=3; if (submenu>9) submenu=0; } Lcd_Cmd(LINE1); Hour_Display(submenu); for(int i=0;i<3; i++) { DigitDisplay(ADC_Value[i+submenu]); Lcd_Data(' '); } Lcd_Cmd(LINE2); int tmp=submenu+3; if(tmp > 9) tmp =0; Hour_Display(tmp); for(int i=0;i<3; i++) { DigitDisplay(ADC_Value[i+tmp]); Lcd_Data(' '); } delay(100); } while(ENTER) ; } void view_capture(void) { Lcd_Clear(); Lcd_Write_String(LINE1,"CAPTURE IR"); while(!ENTER) { Lcd_Cmd(LINE2); DigitDisplay(ADC_Value[17]); delay(200); } while(ENTER) ; } void view_ultra(void) { Lcd_Clear(); while(!ENTER) { Lcd_Cmd(LINE1); for(int i=0;i<2; i++) { Lcd_Data(i*3+'0'); Lcd_String("h: "); DigitDisplay((float)ultra[i]*0.85); Lcd_Data(' '); } Lcd_Cmd(LINE2); for(int i=2;i<4; i++) { Lcd_Data(i*3+'0'); Lcd_String("h: "); DigitDisplay(ultra[i]*0.85); Lcd_Data(' '); } delay(200); } while(ENTER) ; } void menu_display(unsigned char no) { switch(no) { case 0: Lcd_Write_String(LINE2,"RUN PROGRAM 1 "); break; case 1: Lcd_Write_String(LINE2,"RUN PROGRAM 2 "); break; case 2: Lcd_Write_String(LINE2,"[BALL FOLLOWER] "); break; case 3: Lcd_Write_String(LINE2,"[ GOAL FINDER ] "); break; case 4: Lcd_Write_String(LINE2,"VIEW IR "); break; case 5: Lcd_Write_String(LINE2,"VIEW CAPTURE IR "); break; case 6: Lcd_Write_String(LINE2,"VIEW ULTRA "); break; case 7: Lcd_Write_String(LINE2,"VIEW LINE "); break; } } void compass_move(int ma, int mb, int mc) { int comp; read_compass(); // comp = (int)compass / 10; comp = compass; comp = comp - 180; if (comp > 100) { move(50, 50, 50); } else if(comp < -100) { move(-50, -50, -50); } else { move(ma+comp*KP, mb+comp*KP, mc+comp*KP); } } void dir_move(int input_ball, int power) { switch(input_ball) { case 0: compass_move(power, 0, -power); break; case 1: compass_move(power/2, power/2, -power); break; case 2: compass_move(0, power, -power); break; case 3: compass_move(-power/2, power, -power/2); break; case 4: compass_move(-power, power, 0); break; case 5: compass_move(-power, power/2, power/2); break; case 6: compass_move(-power, 0, power); break; case 7: compass_move(-power/2, -power/2, power); break; case 8: compass_move(0, -power, power); break; case 9: compass_move(power/2,- power, power/2); break; case 10: compass_move(power, -power, 0); break; case 11: compass_move(power, -power/2, -power/2); break; } } void ball_near(int dir, int power) { switch(dir) { case 0: dir_move(0, power); break; case 1: dir_move(2, power); break; case 2: dir_move(5, power); break; case 3: dir_move(6, power); break; case 4: dir_move(7, power); break; case 5: dir_move(8, power); break; case 6: dir_move(8, power); break; case 7: dir_move(4, power); break; case 8: dir_move(5, power); break; case 9: dir_move(6, power); break; case 10: dir_move(7, power); break; case 11: dir_move(10, power); break; } } void PROGRAM1(void)//공격 { int ultra_gap = 0; move(0,0,0); Lcd_Clear(); Lcd_Write_String(LINE1,"RUNNING PROGRAM1"); LineDetected = 0; while(1) { if(ball_dir > 6) //이전에 공이 왼쪽에 있었음. last_pos = 1; else if(ball_dir >= 1 && ball_dir < 6) //이전에 공이 오른쪽에 있었음. last_pos = 0; if(LineDetected) //경계라인이 감지되었으면 탈출 함. { move(0,0,0); delay(100); dir_move(Escape_Dir[LineDetected], 100); delay(400); move(0,0,0); LineDetected = 0; } if(ball_dir<12) { if(max_ir > SHOOT && (ball_dir == 0)) // || ball_dir == 1 || ball_dir == 11)) //공이 가까이 있을 때 { ultra_gap = (int)((float)ultra[1]*0.85) - (int)((float)ultra[3]*0.85); int comp; read_compass(); comp = compass; comp = comp - 180 - ultra_gap; move(100+comp*KP, comp*KP, -100+comp*KP); dir_move(0, 100); compass_move(100, -ultra_gap*2, -100); } else { if (max_ir > NEAR) ball_near(ball_dir, 100); else dir_move(ball_dir, 100); } } else dir_move(ball_dir, 0); } } void PROGRAM2(void) { int ultra_gap = 0; move(0,0,0); MOTORD(0); //드리블러 STOP. // MOTORD(-50); //드리블러 ON Lcd_Clear(); Lcd_Write_String(LINE1,"RUNNING PROGRAM2"); while(ENTER) ; // Shooting(500); // 0.5초간 솔레노이드 작동 시키기. while(!ENTER) // ENTER 키가 눌릴때까지 아래 명령 반복 EV3 루프와 동일 { if(ball_dir > 6) last_pos = 1; else if(ball_dir >= 1 && ball_dir < 6) last_pos = 0; if((int)((float)ultra[2]*0.85) < 30) dir_move(0, 50); else if((float)ultra[1]*0.85 < 15 && max_ir < 80) { move(0,0,0); delay(100); dir_move(9,100); delay(700); LineDetected=0; } else if((float)ultra[3]*0.85 < 15 && max_ir < 80) { move(0,0,0); delay(100); dir_move(3,100); delay(700); LineDetected=0; } else if(LineDetected) { move(0,0,0); delay(100); dir_move(Escape_Dir[LineDetected], 100); delay(400); LineDetected = 0; } else { if(max_ir > SHOOT2 && (ball_dir == 0)) // || ball_dir == 1 || ball_dir == 11) //공이 가까이 있을 때 { ultra_gap = (int)((float)ultra[1]*0.85) - (int)((float)ultra[3]*0.85); int comp; read_compass(); comp = (int)compass / 10; comp = comp - 180 - ultra_gap; move(100+comp*KP, comp*KP, -100+comp*KP); dir_move(0, 100); for (int i=0;i<100;i++) { compass_move(100, -ultra_gap*2, -100); } move(0,0,0); delay(100); dir_move(6,100); delay(200); } if(max_ir > NEAR2) { dir_move(ball_dir, 100); } else { if((int)((float)ultra[1]*0.85) + (int)((float)ultra[3]*0.85) > 40 && (int)((float)ultra[1]*0.85) - (int)((float)ultra[3]*0.85) < 20 && (int)ultra[1] - (int)ultra[3] > -20 && (int)((float)ultra[2]*0.85) > 40) dir_move(6, 100); else if((int)((float)ultra[1]*0.85) - (int)((float)ultra[3]*0.85) > 10 && (int)((float)ultra[1]*0.85) + (int)((float)ultra[3]*0.85) > 40) dir_move(3, 90); else if((int)((float)ultra[1]*0.85) - (int)((float)ultra[3]*0.85) < -10 && (int)((float)ultra[1]*0.85) + (int)((float)ultra[3]*0.85) > 40) dir_move(9, 90); else dir_move(0, 0); } } } while(ENTER) ; } void PROGRAM3(void) { Lcd_Clear(); Lcd_Write_String(LINE1,"TEST"); Lcd_Write_String(LINE2,"[BALL FOLLOWER]"); while(ENTER) ; // Shooting(500); // 0.5초간 솔레노이드 작동 시키기. while(!ENTER) // ENTER 키가 눌릴때까지 아래 명령 반복 EV3 루프와 동일 { if(ball_dir > 11) motor_stop(); // 만약 공의 방향이 11시보다 크면 공을 못찾은것임 - 정지 else if(ball_dir == 0) // 아니고 만약 공의 방향이 0시 방향이고 { if(ultra[0] < 7) // 만약 전방 거리 측정값이 (7 * 0.85 = 0.59) 6 cm 보다 작으면 { move(100,0,-100); // 공이 바로 앞에 있다고 판단 전속력으로 직진 delay(1000); // 1초 지속 후. motor_stop(); // 정지 } else move(30,0,-30); // 전방 거리측정값이 6cm 보다 작지 않으면 파워 30으로 전진 } else if (ball_dir <= 6) move(-50,-50,-50 ); // 만약 공의 방향이 6시방향보다 작거나 같으면 우회전 else move(50,50,50); // 아니면 좌회전 } while(ENTER) ; motor_stop(); } void PROGRAM4(void) { uint16_t blocks; /* PIXY 카메라 정보 pixy.blocks[i].signature The signature number of the detected object (1-7 for normal signatures) pixy.blocks[i].x The x location of the center of the detected object (0 to 319) pixy.blocks[i].y The y location of the center of the detected object (0 to 199) pixy.blocks[i].width The width of the detected object (1 to 320) pixy.blocks[i].height The height of the detected object (1 to 200) pixy.blocks[i].angle The angle of the object detected object if the detected object is a color code. pixy.blocks[i].print() A member function that prints the detected object information to the serial port(사용 금지) */ Lcd_Clear(); Lcd_Write_String(LINE1,"TEST X= "); Lcd_Write_String(LINE2," [ GOAL FINDER ]"); while(ENTER) ; while(!ENTER) // ENTER 키가 눌릴때까지 아래 명령 반복 EV3 루프와 동일 { Lcd_Move(0, 8); if(CameraExist) { blocks = pixy.getBlocks(); if(blocks) { Lcd_Move(0, 8); DigitDisplay(pixy.blocks[0].x); if(pixy.blocks[0].x > 175) move(-50,-50,-50 ); // 만약 골대가 오른쪽에 있으면 우회전 else if(pixy.blocks[0].x < 145) move(50,50,50 ); // 만약 골대가 왼쪽에 있으면 좌회전 else motor_stop(); // 골대가 중앙에 있으면 정지 } else { Lcd_String("???"); motor_stop(); } delay(100); } else Lcd_String("NO CAM"); } while(ENTER) ; motor_stop(); } void setup(void) { init_devices(); Wire.begin(); //FIND COMPASS SENSOR if(!Check_Compass()) { Lcd_Clear(); Lcd_Write_String(LINE1,"CHECK YOUR GY273"); Lcd_Write_String(LINE2,"COMPASS SENSOR!"); while(1) ; } Timer1.initialize(50); Timer1.attachInterrupt(Scan_Ultra); // blinkLED to run every 0.15 seconds read_compass(); delay(100); read_compass(); memComp = compass; Lcd_Clear(); Lcd_Write_String(LINE1,"RCKA"); Lcd_Write_String(LINE2,"ROBOT SOCCER 3.0"); if(CameraExist) pixy.init(); } void loop(void) { static int i = 0; int j; uint16_t blocks; char buf[32]; read_compass(); Lcd_Move(0, 6); DigitDisplay(compass); Lcd_Data(0xDF); Volt_Display(Voltage); if(ENTER) { while(ENTER) ; menu_display(menu); while(1) { read_compass(); Lcd_Move(0, 6); DigitDisplay(compass); Lcd_Data(0xDF); Volt_Display(Voltage); if(PREV) { while(PREV) ; menu--; if (menu<0) menu=7; menu_display(menu); } if(NEXT) { while(NEXT) ; menu++; if (menu>7) menu=0; menu_display(menu); } if(ENTER) { while(ENTER) ; switch(menu) { case 0: PROGRAM1(); break; case 1: PROGRAM2(); break; case 2: PROGRAM3(); break; case 3: PROGRAM4(); break; case 4: view_ir(); break; case 5: view_capture(); break; case 6: view_ultra(); break; case 7: view_line(); break; } Lcd_Clear(); Lcd_Write_String(LINE1,"RCKA"); menu_display(menu); } delay(200); } } delay(200); }
#ifndef __CHIDOUHU_CONCURRNECY_MUTEX_H__ #define __CHIDOUHU_CONCURRNECY_MUTEX_H__ #include <pthread.h> namespace chidouhu { class MutexLock { public: MutexLock(); ~MutexLock(); void lock(); int trylock(); void unlock(); pthread_mutex_t* getPthreadMutex(); private: pthread_mutex_t mutex_; }; class MutexLockGuard { public: explicit MutexLockGuard(MutexLock& mutex) : mutex_(mutex) { mutex_.lock(); } ~MutexLockGuard() { mutex_.unlock(); } private: MutexLock& mutex_; }; #define MutexLockGuard(x) error "Missing guard object name" } #endif
#pragma once #include <sys/ioctl.h> #include <cstdint> class I2CDevice { public: I2CDevice(int busFileDescriptor, int address); bool Write(const uint8_t* data, uint16_t dataSize); bool Read(uint8_t* data, uint16_t dataSize); private: int _busFileDescriptor; };
//矩阵乘法 logn求fib数列第n项 POJ 3070 #include<iostream> #include<queue> #include<vector> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #define mod 10000 using namespace std; struct Matrix{ int num[2][2]; }; int n; Matrix operator *(const Matrix &a,const Matrix &b){ Matrix res={0,0,0,0}; for(int i=0;i<2;i++) for(int j=0;j<2;j++) for(int k=0;k<2;k++) res.num[i][j]=(res.num[i][j]+a.num[i][k]*b.num[k][j])%mod; return res; } Matrix quickpow(Matrix A,int b){ Matrix res={1,0,0,1}; while(b>0){ if(b & 1) res=res*A; b>>=1; A=A*A; } return res; } void solve(){ while(scanf("%d",&n) && n!=-1){ Matrix A={0,1,0,0}; Matrix B={0,1,1,1}; if(n==0) printf("0\n"); else{ Matrix Ans=A*quickpow(B,n-1); printf("%d\n",Ans.num[0][1]); } } } int main(){ solve(); return 0; }
#include <iostream> #include <string> #include <cstring> #include <sstream> #include <vector> #include <algorithm> #include <iterator> #include <fstream> //files #include <errno.h> //errors #include <stdio.h> //printf #include <unistd.h> // sys calls #include <sys/types.h> // O_ constants #include <sys/ipc.h> // IPC_ constnts #include <sys/stat.h> // mode constants #include <fcntl.h> // O_ constants #include <pthread.h> //threads #define MB 1024 char in[MB]; using namespace std; // type-definition: 'pt2Function' now can be used as type typedef void * (*pt2Function)(void *); #define NUM_THREADS 4 void *fun0(void *threadid) { long tid; pthread_mutex_t* mut = (pthread_mutex_t*)threadid; tid = (long)threadid; cout << "Mutex wait, " << tid << endl; pthread_mutex_lock(mut); cout << "Mutex end wait, " << tid << endl; pthread_mutex_destroy(mut); pthread_exit(NULL); } void *fun1(void *threadid) { long tid; pthread_spinlock_t* mut = (pthread_spinlock_t*)threadid; tid = (long)threadid; cout << "Spin wait, " << tid << endl; pthread_spin_lock(mut); cout << "Spin end wait, " << tid << endl; pthread_spin_destroy(mut); pthread_exit(NULL); } void *fun2(void *threadid) { long tid; pthread_rwlock_t* mut = (pthread_rwlock_t*)threadid; tid = (long)threadid; cout << "rlock wait, " << tid << endl; pthread_rwlock_rdlock(mut); cout << "rlock end wait, " << tid << endl; pthread_rwlock_destroy(mut); pthread_exit(NULL); } void *fun3(void *threadid) { long tid; pthread_rwlock_t* mut = (pthread_rwlock_t*)threadid; tid = (long)threadid; cout << "wlock wait, " << tid << endl; pthread_rwlock_wrlock(mut); cout << "wlock end wait, " << tid << endl; pthread_rwlock_destroy(mut); pthread_exit(NULL); } int main (int argc, char** argv) { pthread_t threads[NUM_THREADS]; pt2Function functions[NUM_THREADS]; void ** args = new void*[NUM_THREADS]; functions[0] = &fun0; functions[1] = &fun1; functions[2] = &fun2; functions[3] = &fun3; int rc; int i; int fd = open("main.pid", O_WRONLY | O_CREAT, 0666); sprintf(in,"%d", getpid()); int writed = write(fd, in, sizeof(rc)); close(fd); pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mut); pthread_spinlock_t spin; pthread_spin_init(&spin, PTHREAD_PROCESS_PRIVATE); pthread_spin_lock(&spin); pthread_rwlock_t rlock = PTHREAD_RWLOCK_INITIALIZER; pthread_rwlock_rdlock(&rlock); pthread_rwlock_t wlock = PTHREAD_RWLOCK_INITIALIZER; pthread_rwlock_wrlock(&wlock); i=0;args[i] = (void *)&mut; i=1;args[i] = (void *)&spin; i=2;args[i] = (void *)&wlock; i=3;args[i] = (void *)&wlock; for( i=0; i < NUM_THREADS; i++ ){ // cout << "main() : creating thread, " << i << endl; rc = pthread_create(&threads[i], NULL, functions[i], args[i]); if (rc){ cout << "Error:unable to create thread," << rc << endl; exit(-1); } } //pause(); pthread_exit(NULL); }
#include"QInt.h" #include"Convert.h" QInt::QInt(){ for (int i = 0; i < LENGTH; i++) { data[i] = 0; } } QInt& QInt::operator =(unsigned int x) { for (int i = 0; i < 3; i++) { data[i] = 0; } data[3] = x; return *this; } QInt& QInt::operator~() { QInt res; for (int i = 0; i < LENGTH; i++) { res.data[i] = ~this->data[i]; } return res; } QInt QInt::operator^(QInt num) { QInt result; for (int i = 0; i < LENGTH; i++) { //xor từng cặp byte -> tự so bit result.data[i] = this->data[i] ^ num.data[i]; } return result; } bool QInt::GetBit(int vt) { //Tìm ra giá trị index trong data int index = vt / BIT32; //Với vt thì nó ứng với index bao nhiêu trong BIT32 ( dò cùng với index ) int indexbit = BIT32 - 1 - vt % BIT32; return (data[index] >> indexbit) & 1; } void QInt::SetBit(int vt, bool bit) { //Tìm ra giá trị index trong data int index = vt / BIT32; //Với vt thì nó ứng với index bao nhiêu trong BIT32 ( dò cùng với index ) int indexbit = BIT32 - 1 - vt % BIT32; //công thức bật / tất bit như trong lý thuyết cô đã dạy if (bit == 1) { data[index] = (1 << indexbit) | data[index]; } else { data[index] = ~(1 << indexbit) & data[index]; } } ostream& operator<<(ostream& out, QInt num){ // TODO: insert return statement here out << Convert::QIntToStringNumber(num); return out; } istream& operator>>(istream& is, QInt& num) { string temp; is >> temp; num = Convert::StringNumberToQInt(temp); return is; }
#include "Classifier.hpp" Classifier::Classifier(int processorId, Conf &cfg) : ConfigReader(processorId, cfg) { }
#include "Fence.hpp" Elysium::Graphics::Fence::Fence(GraphicsDevice * GraphicsDevice) : Elysium::Core::Object(), _WrappedGraphicsDevice(GraphicsDevice->_WrappedGraphicsDevice), _WrappedFence(_WrappedGraphicsDevice->CreateWrappedFence()) { } Elysium::Graphics::Fence::~Fence() { // delete all the objects we own delete(_WrappedFence); // remove all pointers _WrappedFence = nullptr; _WrappedGraphicsDevice = nullptr; } IWrappedFence * Elysium::Graphics::Fence::GetWrappedFence() { return _WrappedFence; } void Elysium::Graphics::Fence::Wait(uint64_t Timeout) { _WrappedFence->Wait(Timeout); }
#include "stdafx.h" #include "Main.h" Main::Main(const int width, const int height) : width(width), height(height), size(width*height*4), PixelArray(PixelData(width, height)) { PixelArray.addSeed(0, 0, 130); PixelArray.addSeed(0, height-1, 130); PixelArray.addSeed(0, height-1, 130); PixelArray.addSeed(width-1, height-1, 130); PixelArray.fillPixelArray("DiamondSquare", 200); }; void Main::newTerrain(int roughness){ PixelArray.resetPixelArray(); PixelArray.addSeed(0, 0, 130); PixelArray.addSeed(0, height - 1, 130); PixelArray.addSeed(0, height - 1, 130); PixelArray.addSeed(width - 1, height - 1, 130); PixelArray.fillPixelArray("DiamondSquare", 200); } void Main::newRandom(){ PixelArray.resetPixelArray(); PixelArray.fillPixelArray("Random"); } void Main::newBlackWhite(){ PixelArray.resetPixelArray(); PixelArray.fillPixelArray("BlackWhite"); } void Main::dumpBuffer(const char * fileName){ PixelArray.dumpBuffer(fileName); } void Main::SaveToBmp(const char * fileName){ ofstream file; file.open(fileName, ios::out | ios::binary); writeHeader(&file, width, height); file.write(PixelArray.getPixelArray(), size); file.close(); } Main::~Main() { } char* Main::getBuffer(){ return PixelArray.getPixelArray(); } void Main::setType(int option){ switch (option){ case 0: PixelArray.fillBufferBW(); break; case 1: PixelArray.fillBufferCOL(); break; case 2: PixelArray.fillBufferTerrain(); break; } } // thank you random wiki picture // https://upload.wikimedia.org/wikipedia/commons/c/c4/BMPfileFormat.png void Main::writeHeader(ofstream* file, int W, int H){ BMPHEADER bmpheader; bmpheader.signature[0] = 0x42; bmpheader.signature[1] = 0x4d; bmpheader.fileSize = 0x46; //14 + 40 + ( WIDTH * HEIGHT * 4 ); bmpheader.reserved1 = 0; bmpheader.reserved2 = 0; bmpheader.offsetToPixArray = 0x36; DIBHEADER dibheader; dibheader.bytesInDIB = 40; dibheader.BMPHeigth = -H; dibheader.BMPWidth = W; dibheader.planeUsed = 1; dibheader.BitsPerPixel = 24; dibheader.compression = 0; dibheader.sizeOfBMPData = W*H * 4; dibheader.hRes = 2835; dibheader.vRes = 2835; dibheader.nColors = 0; dibheader.importantColors = 0; file->write((char*)(&bmpheader), 14); file->write((char*)(&dibheader), 40); }
#ifndef __SANDBOX_WRAP_H__ #define __SANDBOX_WRAP_H__ #include <nan.h> #include <vector> #include "sandbox.h" class SandboxWrap : public Nan::ObjectWrap { friend class SandboxInitializeWorker; friend class SandboxExecuteWorker; friend class SandboxFinalizeWorker; public: static void Init(v8::Local<v8::Object> exports); Nan::Persistent<v8::Function>& GetBridge() { return bridge_; } private: Sandbox *sandbox_; explicit SandboxWrap(); ~SandboxWrap(); static NAN_METHOD(New); static NAN_METHOD(Initialize); static NAN_METHOD(Execute); static NAN_METHOD(Finalize); Nan::Persistent<v8::Function> bridge_; static Nan::Persistent<v8::Function> constructor; }; #endif
// Copyright (c) 2007-2021 Hartmut Kaiser // Copyright (C) 2011 Vicente J. Botet Escriba // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <cstddef> #include <cstdint> #include <memory> #include <type_traits> #include <utility> struct test_alloc_base { static int count; static int throw_after; }; int test_alloc_base::count = 0; int test_alloc_base::throw_after = INT_MAX; template <typename T> class test_allocator : public test_alloc_base { int data_; template <typename U> friend class test_allocator; public: using size_type = std::size_t; using difference_type = std::int64_t; using value_type = T; using pointer = value_type*; using const_pointer = const value_type*; using reference = typename std::add_lvalue_reference<value_type>::type; using const_reference = typename std::add_lvalue_reference<const value_type>::type; template <typename U> struct rebind { using other = test_allocator<U>; }; test_allocator() noexcept : data_(-1) { } explicit test_allocator(int i) noexcept : data_(i) { } test_allocator(test_allocator const& a) noexcept : data_(a.data_) { } template <typename U> test_allocator(test_allocator<U> const& a) noexcept : data_(a.data_) { } ~test_allocator() noexcept { data_ = 0; } pointer address(reference x) const { return &x; } const_pointer address(const_reference x) const { return &x; } pointer allocate(size_type n, const void* = nullptr) { if (count >= throw_after) throw std::bad_alloc(); ++count; return static_cast<pointer>(std::malloc(n * sizeof(T))); } void deallocate(pointer p, size_type) { --count; std::free(p); } size_type max_size() const noexcept { return UINT_MAX / sizeof(T); } template <typename U, typename... Ts> void construct(U* p, Ts&&... ts) { ::new ((void*) p) T(std::forward<Ts>(ts)...); } void destroy(pointer p) { p->~T(); } friend bool operator==(test_allocator const& x, test_allocator const& y) { return x.data_ == y.data_; } friend bool operator!=(test_allocator const& x, test_allocator const& y) { return !(x == y); } }; template <> class test_allocator<void> : public test_alloc_base { int data_; template <typename U> friend class test_allocator; public: using size_type = std::size_t; using difference_type = std::int64_t; using value_type = void; using pointer = value_type*; using const_pointer = value_type const*; template <typename U> struct rebind { using other = test_allocator<U>; }; test_allocator() noexcept : data_(-1) { } explicit test_allocator(int i) noexcept : data_(i) { } test_allocator(test_allocator const& a) noexcept : data_(a.data_) { } template <typename U> test_allocator(test_allocator<U> const& a) noexcept : data_(a.data_) { } ~test_allocator() noexcept { data_ = 0; } friend bool operator==(test_allocator const& x, test_allocator const& y) { return x.data_ == y.data_; } friend bool operator!=(test_allocator const& x, test_allocator const& y) { return !(x == y); } };
#pragma once class AI_FireLaser : public Hourglass::IAction { public: void LoadFromXML( tinyxml2::XMLElement* data ); void Init( Hourglass::Entity* entity ); IBehavior::Result Update( Hourglass::Entity* entity ); IBehavior* MakeCopy() const; private: hg::Transform* m_Laser; float m_Timer; float m_Duration; Vector3 m_StartScale; Vector3 m_EndScale; uint32_t m_Reverse : 1; bool m_bPlayingLaserBeamSound; };
// Fill out your copyright notice in the Description page of Project Settings. #include "S05_TestingGrounds.h" #include "PatrolLoop.h" TArray<AActor*> UPatrolLoop::GetPatrolRoute() const { return PatrolRoute; }
// Jakins, Christopher // cfj2309 // 2019-10-05 #include <iostream> using namespace std; int main( int argc, char *argv[] ) { // Put an output statement here that prints "Hello, world!" // followed by a newline. std::cout << "Hello, world!" << std::endl; }
/* * Copyright (c) 2014-2019 Detlef Vollmann, vollmann engineering gmbh * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #include "canvas.hh" #include "pathShape.hh" #include "rectangle.hh" #include "text.hh" #include "extgraph.hh" #include <string> #include <vector> #include <functional> namespace exercise { CanvasImpl::CanvasImpl(int width, int height, std::string const &name) : win{new GuiWin{width, height, name}} , surface{win->getSurface()} , cr{cairo_create(surface)} { win->registerCallback([this] { draw(); }); (*this) += new PathShape{new Rectangle(width, height), "Background", true, Position{0, 0}, Color::White}; show(); } CanvasImpl::~CanvasImpl() { win->unregisterCallback(); for (Shape *p: elems) { delete p; } cairo_destroy(cr); cairo_surface_destroy(surface); delete win; } void CanvasImpl::operator+=(Shape *s) { elems.push_back(s); } void CanvasImpl::draw() const { for (Shape const *p: elems) { p->draw(cr); } cairo_show_page(cr); } void CanvasImpl::show() const { draw(); win->show(); } void CanvasImpl::startLoop() { win->loop(); } Canvas::Canvas(int width, int height, std::string const &name) : pImpl{new CanvasImpl{width, height, name}} { } Canvas::~Canvas() { delete pImpl; } void Canvas::operator+=(Shape *s) { (*pImpl) += s; } void Canvas::draw() const { pImpl->draw(); } void Canvas::show() const { pImpl->show(); } void Canvas::startLoop() { pImpl->startLoop(); } } // namespace exercise
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // $Id$ // // Copyright (C) Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. #include "core/pch.h" #include "opml.h" #include "adjunct/m2/src/engine/account.h" #include "adjunct/m2/src/backend/rss/opml_importer.h" #include "adjunct/m2/src/backend/rss/opml_exporter.h" #include "adjunct/m2/src/engine/engine.h" #include "adjunct/m2/src/util/xmlparser_tracker.h" #include "adjunct/quick/Application.h" #include "modules/util/opfile/opfile.h" using namespace M2XMLUtils; // *************************************************************************** // // OPMLParser // // *************************************************************************** class OPMLParser : public XMLParserTracker { public: // Construction. OPMLParser(OPMLImportHandler& import_handler); OP_STATUS Init(); private: // XMLParserTracker. virtual OP_STATUS OnStartElement(const OpStringC& namespace_uri, const OpStringC& local_name, const OpStringC& qualified_name, OpAutoStringHashTable<XMLAttributeQN> &attributes); virtual OP_STATUS OnEndElement(const OpStringC& namespace_uri, const OpStringC& local_name, const OpStringC& qualified_name, OpAutoStringHashTable<XMLAttributeQN> &attributes); // Members. OPMLImportHandler& m_import_handler; BOOL m_inside_opml; }; OPMLParser::OPMLParser(OPMLImportHandler& import_handler) : m_import_handler(import_handler), m_inside_opml(FALSE) { } OP_STATUS OPMLParser::Init() { RETURN_IF_ERROR(XMLParserTracker::Init()); return OpStatus::OK; } OP_STATUS OPMLParser::OnStartElement(const OpStringC& namespace_uri, const OpStringC& local_name, const OpStringC& qualified_name, OpAutoStringHashTable<XMLAttributeQN> &attributes) { if (m_inside_opml) { if (local_name.CompareI("outline") == 0 && IsDescendantOf(UNI_L("body"))) { // Fetch the attribute values we care about. XMLAttributeQN* text_attribute = 0; OpStatus::Ignore(attributes.GetData(UNI_L("text"), &text_attribute)); XMLAttributeQN* xml_url_attribute = 0; OpStatus::Ignore(attributes.GetData(UNI_L("xmlUrl"), &xml_url_attribute)); XMLAttributeQN* title_attribute = 0; OpStatus::Ignore(attributes.GetData(UNI_L("title"), &title_attribute)); XMLAttributeQN* description_attribute = 0; OpStatus::Ignore(attributes.GetData(UNI_L("description"), &description_attribute)); // Notify import handler. OpStatus::Ignore(m_import_handler.OnOutlineBegin( text_attribute != 0 ? text_attribute->Value() : OpStringC(), xml_url_attribute != 0 ? xml_url_attribute->Value() : OpStringC(), title_attribute != 0 ? title_attribute->Value() : OpStringC(), description_attribute != 0 ? description_attribute->Value() : OpStringC())); } } else if (local_name.CompareI("opml") == 0) { m_inside_opml = TRUE; // Notify import handler. OpStatus::Ignore(m_import_handler.OnOPMLBegin()); } return OpStatus::OK; } OP_STATUS OPMLParser::OnEndElement(const OpStringC& namespace_uri, const OpStringC& local_name, const OpStringC& qualified_name, OpAutoStringHashTable<XMLAttributeQN> &attributes) { if (m_inside_opml) { if (local_name.CompareI("title") == 0 && IsDescendantOf(UNI_L("head"))) { // Notify import handler. const OpStringC& title = ElementContent(); OpStatus::Ignore(m_import_handler.OnHeadTitle(title)); } else if (local_name.CompareI("outline") == 0 && IsDescendantOf(UNI_L("body"))) { // Notify import handler. OpStatus::Ignore(m_import_handler.OnOutlineEnd(!attributes.Contains(UNI_L("xmlUrl")))); } else if (local_name.CompareI("opml") == 0) { m_inside_opml = FALSE; // Notify import handler. OpStatus::Ignore(m_import_handler.OnOPMLEnd()); } } return OpStatus::OK; } // *************************************************************************** // // OPML // // *************************************************************************** OP_STATUS OPML::Import(const OpStringC& file_path, OPMLImportHandler& import_handler) { // Open the file. OpFile file; RETURN_IF_ERROR(file.Construct(file_path.CStr())); RETURN_IF_ERROR(file.Open(OPFILE_READ | OPFILE_TEXT)); // Read the content and parse it. OPMLParser opml_parser(import_handler); RETURN_IF_ERROR(opml_parser.Init()); char buffer[4096]; OpFileLength bytes_read = 0; while (!file.Eof()) { OpStatus::Ignore(file.Read(&buffer, 4096, &bytes_read)); RETURN_IF_ERROR(opml_parser.Parse(buffer, UINT(bytes_read), file.Eof())); } return OpStatus::OK; } OP_STATUS OPML::Export(const OpStringC& file_path) { // Open the file for output. OpFile file; RETURN_IF_ERROR(file.Construct(file_path.CStr())); RETURN_IF_ERROR(file.Open(OPFILE_WRITE | OPFILE_TEXT)); // Write out the content. OPMLExporter opml_exporter; RETURN_IF_ERROR(opml_exporter.Export(file)); return OpStatus::OK; }
// // Car.cpp // w06_h02_pathfollow // // Created by Kris Li on 10/13/16. // // #include "Car.hpp" Car::Car(){ size = 5; } void Car::init(){ pos.x = ofRandom(50,150); pos.y = ofRandom(250,350); vel = ofPoint(ofRandom(-3,3),ofRandom(-3,3)); } ofPoint Car::seek(ofPoint _end){ ofPoint desired = _end - pos; desired.normalize(); v1 = desired * 3; return v1; } ofPoint Car::follow(ofPoint _begin, ofPoint _end){ ofPoint predict; predict = pos + vel.normalize()*25; ofPoint a,b; a = predict - _begin; b = _end - _begin; // float theta =a.angle(b); // b.normalize(); // b*(a.length()*cos(theta)); // ofPoint normalPoint = _begin + b; b.normalize(); b*(a.dot(b)); ofPoint normalPoint = _begin + b; float distance = ofDist(predict.x,predict.y, normalPoint.x, normalPoint.y); if(distance > 50){ v1 = this->seek(_end); } else { v1 = ofPoint(0,0); } return v1; } void Car::update(ofPoint _begin, ofPoint _end){ pos += vel; vel += v1; //set a maximum velocity if(vel.length() > 20){ vel.normalize(); vel*20; } } void Car::draw(){ ofDrawRectangle(pos, size, size); }
#include "stdafx.h" #include "TypeInQuestion.h" #include "utils.h" namespace qp { CTypeInQuestion::CTypeInQuestion(std::string const& description, std::set<std::string> const& answers, double score) :CQuestion(description, score) { for (auto answer : answers) { std::string answerWithoutExtraSpaces = RemoveExtraSpaces(answer); if (answerWithoutExtraSpaces.empty()) { throw std::invalid_argument("Answer cannot be empty"); } m_answers.insert(answerWithoutExtraSpaces); } if (m_answers.empty()) { throw std::invalid_argument("Answers cannot be empty"); } } CTypeInQuestion::~CTypeInQuestion() { } std::set<std::string> const& CTypeInQuestion::GetAnswers() const { return m_answers; } }
/* Copyright (c) DataStax, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "integration.hpp" #include "cassandra.h" class SessionTest : public Integration { public: typedef std::pair<CassHostListenerEvent, std::string> Event; typedef std::vector<Event> Events; void SetUp() { is_session_requested_ = false; Integration::SetUp(); } size_t event_count() { return events_.size(); } const Events& events() const { return events_; } protected: static void on_host_listener(CassHostListenerEvent event, CassInet inet, void* data) { SessionTest* instance = static_cast<SessionTest*>(data); char address[CASS_INET_STRING_LENGTH]; uv_inet_ntop(inet.address_length == CASS_INET_V4_LENGTH ? AF_INET : AF_INET6, inet.address, address, CASS_INET_STRING_LENGTH); instance->events_.push_back(Event(event, address)); } private: Events events_; }; CASSANDRA_INTEGRATION_TEST_F(SessionTest, MetricsWithoutConnecting) { CHECK_FAILURE; Session session; CassMetrics metrics; logger_.add_critera("Attempted to get metrics before connecting session object"); cass_session_get_metrics(session.get(), &metrics); EXPECT_EQ(metrics.requests.min, 0u); EXPECT_EQ(metrics.requests.one_minute_rate, 0.0); EXPECT_EQ(logger_.count(), 1u); CassSpeculativeExecutionMetrics spec_ex_metrics; logger_.reset(); logger_.add_critera("Attempted to get speculative execution metrics before connecting session object"); cass_session_get_speculative_execution_metrics(session.get(), &spec_ex_metrics); EXPECT_EQ(spec_ex_metrics.min, 0u); EXPECT_EQ(spec_ex_metrics.percentage, 0.0); EXPECT_EQ(logger_.count(), 1u); } CASSANDRA_INTEGRATION_TEST_F(SessionTest, ExternalHostListener) { CHECK_FAILURE; is_test_chaotic_ = true; // Destroy the cluster after the test completes Cluster cluster = default_cluster() .with_load_balance_round_robin() .with_host_listener_callback(on_host_listener, this); Session session = cluster.connect(); ASSERT_EQ(0u, event_count()); EXPECT_EQ(2, ccm_->bootstrap_node()); stop_node(1); ccm_->start_node(1); force_decommission_node(1); session.close(); ASSERT_EQ(6u, event_count()); EXPECT_EQ(CASS_HOST_LISTENER_EVENT_ADD, events()[0].first); EXPECT_EQ(ccm_->get_ip_prefix() + "2", events()[0].second); EXPECT_EQ(CASS_HOST_LISTENER_EVENT_UP, events()[1].first); EXPECT_EQ(ccm_->get_ip_prefix() + "2", events()[1].second); EXPECT_EQ(CASS_HOST_LISTENER_EVENT_DOWN, events()[2].first); EXPECT_EQ(ccm_->get_ip_prefix() + "1", events()[2].second); EXPECT_EQ(CASS_HOST_LISTENER_EVENT_UP, events()[3].first); EXPECT_EQ(ccm_->get_ip_prefix() + "1", events()[3].second); EXPECT_EQ(CASS_HOST_LISTENER_EVENT_DOWN, events()[4].first); EXPECT_EQ(ccm_->get_ip_prefix() + "1", events()[4].second); EXPECT_EQ(CASS_HOST_LISTENER_EVENT_REMOVE, events()[5].first); EXPECT_EQ(ccm_->get_ip_prefix() + "1", events()[5].second); }
/* Author: Manish Kumar Username: manicodebits Created: 20:19:31 10-06-2021 */ #include <bits/stdc++.h> using namespace std; #define int long long #define PI 3.141592653589 #define MOD 1000000007 #define FAST_IO ios_base::sync_with_stdio(false), cin.tie(0) #define deb(x) cout << "[ " << #x << " = " << x << "] " void solve() { int n; cin >> n; vector<int> arr(n); int sum = 0; for (int i = 0; i < n; i++) { cin >> arr[i]; sum += arr[i]; } if ((sum % n)==0) { int value = sum / n; sort(arr.begin(), arr.end()); int index=upper_bound(arr.begin(),arr.end(),value)-arr.begin(); cout<<n-index<<"\n"; } else { cout << "-1\n"; } } signed main() { FAST_IO; int t = 1; cin >> t; while (t--) solve(); return 0; }
#include<iostream> #include<vector> using namespace std; //luon luon co tham chieu moi chay duoc vi moi dau la rac thi minh muon them thi phai dan de cho no chuyen doi void nhap(vector<int> &a) { for(int i=1;i<=10;i++) { a.push_back(i); } } //xuat theo kieu binh thuong void exportnormal(vector<int> a) { for(int i=0;i<a.size();i++) { cout<<a[i]<<" ";//<=>a.at(i) } } //theo kieu lop::iterator void xuat(vector<int> a) { for(vector<int>::iterator it=a.begin();it!=a.end();it++)//<=> xuat(danh sach lien ket) { //vi it dc lap trong lop:nen phai dung con tro de lay no ra! cout<<*it<<" "; } } int main() { vector<int> a; nhap(a); cout<<"\n xuat theo kieu binh thuong!\n"; exportnormal(a); cout<<"\n xuat theo kieu iterator!\n"; xuat(a); return 0; }
#ifndef __DECISIONTREE_H__ #define __DECISIONTREE_H__ #include "dtreetypedefs.h" #include <vector> #include <set> #include "discretize.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "treenode.h" class DecisionTree{ public: DecisionTree(); void save(const char *fname); void load(const char *fname); void train(const std::vector<InputData> *data, std::vector<int> &data_idx, std::vector<cv::Mat> labels); //long input_length, samples_length; //long num_of_classes; std::set<InputValue>* uvalues; const std::vector<InputData>* train_data; TreeNode* head; cv::Mat predict(InputData data); double ginii(const std::vector<OutputData> &labels, int num_of_classes); int getNumOfClasses(std::vector<OutputData> labels); int *getFreq(std::vector<OutputData> labels, int num_of_classes); TreeNode *buildnode( //const std::vector<InputData> &data, const std::vector<int> &data_idx, const std::vector<cv::Mat>& labels, int depth); void calcUniqValues(const std::vector<InputData> *data); void finalDivide( //const std::vector<InputData> &data, const std::vector<int> &data_idx, //const std::vector<OutputData> &labels, //const std::vector<cv::Mat> &seg, int col, InputValue value, std::vector<OutputData> *l1, std::vector<OutputData> *l2, //std::vector<cv::Mat> *g1, std::vector<cv::Mat> *g2, std::vector<int> *i1, std::vector<int> *i2); void divideSet( //const std::vector<InputData> &data, const std::vector<int> &data_idx, const std::vector<OutputData> &labels, //const std::vector<cv::Mat> &seg, int col, InputValue value, std::vector<OutputData> *l1, std::vector<OutputData> *l2, //std::vector<cv::Mat> *g1, std::vector<cv::Mat> *g2, std::vector<int> *i1, std::vector<int> *i2); }; #endif
/* * Tool Assist with Arduino * Copyright (C) 2015 Gabriel Aumala * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <avr/pgmspace.h> #include "TimerOne.h" // how much serial data we expect before a newline const unsigned int MAX_SERIAL_INPUT = 6; // save some unsigned ints const uint16_t arrows[] PROGMEM = { 2,//NADA 3,//LEFT 5,//DOWNLEFT 7,//DOWN 11,//DOWNRIGHT 13,//RIGHT 17,//UPRIGHT 23,//UP 29//UPLEFT }; const uint16_t punches[] PROGMEM = { 31,//NADA 37,//LIGHT 41,//MEDIUM 43,//HEAVY 47,//LIGHT+MEDIUM 53,//MEDIUM+HEAVY 59,//LIGHT+HEAVY 61//ALL 3 }; const uint16_t kicks[] PROGMEM = { 67,//NADA 71,//LIGHT 73,//MEDIUM 79,//HEAVY 83,//LIGHT+MEDIUM 89,//MEDIUM+HEAVY 97,//LIGHT+HEAVY 101//ALL 3 }; typedef enum {UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3, LP = 4, MP = 5, HP = 6, LK = 7, MK = 8, HK = 9} input_types; //duration of a frame in microseconds const unsigned long frame_duration = 316667; //PWM pin unsigned short pwm_pin = 11; void setup() { // initialize serial communication at 115200 bits per second: Serial.begin(115200); pinMode(UP, OUTPUT); pinMode(LEFT, OUTPUT); pinMode(DOWN, OUTPUT); pinMode(RIGHT, OUTPUT); pinMode(LP, OUTPUT); pinMode(MP, OUTPUT); pinMode(HP, OUTPUT); pinMode(LK, OUTPUT); pinMode(MK, OUTPUT); pinMode(HK, OUTPUT); //Debugging pinMode(13, OUTPUT); initTimer(); } /** SERIAL PORT FUNCTIONS **/ // here to process incoming serial data after a terminator received void process_data (const char * data) { int cmd = atoi(data); pressButtons(cmd); } // end of process_data void processIncomingByte (const byte inByte) { static char input_line [MAX_SERIAL_INPUT]; static unsigned int input_pos = 0; switch (inByte) { case '\n': // end of text input_line [input_pos] = 0; // terminating null byte // terminator reached! process input_line here ... process_data (input_line); // reset buffer for next time input_pos = 0; break; case '\r': // discard carriage return break; default: // keep adding if not full ... allow for terminating null byte if (input_pos < (MAX_SERIAL_INPUT - 1)) input_line [input_pos++] = inByte; break; } // end of switch } // end of processIncomingByte void cleanOutputs(){ digitalWrite(LEFT, LOW); digitalWrite(DOWN, LOW); digitalWrite(RIGHT, LOW); digitalWrite(UP, LOW); digitalWrite(LP, LOW); digitalWrite(MP, LOW); digitalWrite(HP, LOW); digitalWrite(LK, LOW); digitalWrite(MK, LOW); digitalWrite(HK, LOW); } void outputArrows(uint16_t word){ byte it = 0; if(word%pgm_read_word_near(arrows + it++) == 0){ //Serial.println("0A"); }else if(word%pgm_read_word_near(arrows + it++) == 0) digitalWrite(LEFT, HIGH); else if(word%pgm_read_word_near(arrows + it++) == 0){ digitalWrite(LEFT, HIGH); digitalWrite(DOWN, HIGH); } else if(word%pgm_read_word_near(arrows + it++) == 0) digitalWrite(DOWN, HIGH); else if(word%pgm_read_word_near(arrows + it++) == 0){ digitalWrite(RIGHT, HIGH); digitalWrite(DOWN, HIGH); } else if(word%pgm_read_word_near(arrows + it++) == 0) digitalWrite(RIGHT, HIGH); else if(word%pgm_read_word_near(arrows + it++) == 0){ digitalWrite(RIGHT, HIGH); digitalWrite(UP, HIGH); } else if(word%pgm_read_word_near(arrows + it++) == 0) digitalWrite(UP, HIGH); else if(word%pgm_read_word_near(arrows + it++) == 0){ digitalWrite(LEFT, HIGH); digitalWrite(UP, HIGH); } else Serial.println(word); } void outputPunches(uint16_t word){ byte it = 0; if(word%pgm_read_word_near(punches + it++) == 0){ //Serial.println("0P"); }else if(word%pgm_read_word_near(punches + it++) == 0){ digitalWrite(LP, HIGH); }else if(word%pgm_read_word_near(punches + it++) == 0) digitalWrite(MP, HIGH); else if(word%pgm_read_word_near(punches + it++) == 0) digitalWrite(HP, HIGH); else if(word%pgm_read_word_near(punches + it++) == 0){ digitalWrite(LP, HIGH); digitalWrite(MP, HIGH); } else if(word%pgm_read_word_near(punches + it++) == 0){ digitalWrite(MP, HIGH); digitalWrite(HP, HIGH); } else if(word%pgm_read_word_near(punches + it++) == 0){ digitalWrite(LP, HIGH); digitalWrite(HP, HIGH); } else if(word%pgm_read_word_near(punches + it++) == 0){ digitalWrite(LP, HIGH); digitalWrite(MP, HIGH); digitalWrite(HP, HIGH); } else Serial.println(word); } void outputKicks(uint16_t word){ byte it = 0; if(word%pgm_read_word_near(kicks + it++) == 0){ //Serial.println("0K"); }else if(word%pgm_read_word_near(kicks + it++) == 0) digitalWrite(LK, HIGH); else if(word%pgm_read_word_near(kicks + it++) == 0) digitalWrite(MK, HIGH); else if(word%pgm_read_word_near(kicks + it++) == 0) digitalWrite(HK, HIGH); else if(word%pgm_read_word_near(kicks + it++) == 0){ digitalWrite(LK, HIGH); digitalWrite(MK, HIGH); } else if(word%pgm_read_word_near(kicks + it++) == 0){ digitalWrite(MK, HIGH); digitalWrite(HK, HIGH); } else if(word%pgm_read_word_near(kicks + it++) == 0){ digitalWrite(LK, HIGH); digitalWrite(HK, HIGH); } else if(word%pgm_read_word_near(kicks + it++) == 0){ digitalWrite(LK, HIGH); digitalWrite(MK, HIGH); digitalWrite(HK, HIGH); } else Serial.println(word); } void pressButtons(uint16_t word){ cleanOutputs(); outputArrows(word); outputKicks(word); outputPunches(word); } void turnOnTestLED(){ digitalWrite(13, HIGH); } void toggleTestLED(){ digitalWrite(13, !digitalRead(13)); } /** TIMER FUNCTIONS start the timer interrupting every frame to execute an input */ void initTimer(){ Timer1.initialize(frame_duration); // initialize timer1, and set a 1/2 second period Timer1.pwm(pwm_pin, 512); // setup pwm on pin 9, 50% duty cycle Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt } void callback() { Serial.write(1); while(Serial.available() > 0) processIncomingByte(Serial.read()); } void loop() { }
#include <stdio.h> int main(){ int math = 90; int korean = 95; int english = 96; int sum = math + korean + english; // 여기서 순간적으로 sum 은 실수가 된다. double avg = (double)sum / 3; printf("%f\n", avg); }
#include "qifunctionmanager.h" namespace qEngine { /************************* qIFunctionManager::qIFunctionManager ************************** description: Constructor, reserves space for the function vectors access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 16:50:43 creator: qDot *****************************************************************************************/ qIFunctionManager::qIFunctionManager(void) { m_vFunctionVector.reserve(10); } /************************ qIFunctionManager::~qIFunctionManager ************************** description: Destructor, clears the function vectors access: public, state: virtual ------------------------------------------------------------------------------------------ created: 30.10.02 - 16:51:13 creator: qDot *****************************************************************************************/ qIFunctionManager::~qIFunctionManager(void) { clear(); } /******************************* qIFunctionManager::push ********************************* description: Adds a function to the stack @fpFunctionHandler[in]: Pointer to a boolean function that takes an integer as a parameter. access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 16:52:04 creator: qDot *****************************************************************************************/ void qIFunctionManager::push(qFunctionPtr fpFunctionHandler) { m_vFunctionVector.push_back(fpFunctionHandler); } /******************************** qIFunctionManager::pop ********************************* description: Pops the last function off the stack access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 16:52:26 creator: qDot *****************************************************************************************/ void qIFunctionManager::pop() { m_vFunctionVector.pop_back(); } /******************************* qIFunctionManager::clear ******************************** description: Clears the function vector access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 16:52:39 creator: qDot *****************************************************************************************/ void qIFunctionManager::clear() { m_vFunctionVector.clear(); } }
/* Problem => Given an unsorted array A of size N of non-negative integers, find a continuous subarray which adds to a given number S. Brute Force: @ Find sum of all possible subarryas, If any of the sum equates to S, output the starting and ending index of the Subarray. @ Time complexity: O(n^2) */ #include<iostream> using namespace std; int main(){ int n; cout<<"Please enter the size of the array: "; cin>>n; int a[n]; for(int i=0; i<n; i++){ cout<<"Please enter the elements in the array: "; cin>>a[i]; } int i=0, j=0, st=-1, en=-1, sum=0; while(j<n && sum+a[j] <= s){ sum += a[j]; j++; } if(sum == s){ cout<<i+1<<" "<<j<<endl; return 0; } while(j<n){ sum += a[j]; while(sum >s){ sum -= a[i]; i++; } if(sum == s){ st = i+1; en = j+1; break; } j++; } cout<<st<<" "<<en<<endl; return 0; }
// // Created by Zakhar on 08.03.2017. // #include <cmath> #include <iostream> #include "CentroidDecomposition.h" #include "Auxiliary.h" namespace Algorithms { // // CentroidDecomposition constructors & desctructors // CentroidDecomposition::CentroidDecomposition(arma::mat &mx) : Src(mx), Load(mx.n_rows, mx.n_cols), Rel(mx.n_cols, mx.n_cols), signVectors(std::vector<arma::vec>()), truncation(mx.n_cols) { Load.zeros(); Rel.zeros(); // i = 0: arma::vec signV(mx.n_rows); signV.fill(1.0); signVectors.emplace_back(std::move(signV)); // i in [1,m[ for (uint64_t i = 1; i < mx.n_cols; ++i) { signVectors.emplace_back(signVectors[0]); } } CentroidDecomposition::CentroidDecomposition(arma::mat &mx, uint64_t k) : CentroidDecomposition(mx) { truncation = k; } // // CentroidDecomposition API // const arma::mat &CentroidDecomposition::getLoad() { return Load; } const arma::mat &CentroidDecomposition::getRel() { return Rel; } arma::mat CentroidDecomposition::stealLoad() { return std::move(Load); } arma::mat CentroidDecomposition::stealRel() { return std::move(Rel); } void CentroidDecomposition::destroyDecomposition() { Load.zeros(); Rel.zeros(); } void CentroidDecomposition::resetSignVectors() { for (uint64_t i = 0; i < Src.n_cols; ++i) { for (uint64_t j = 0; j < Src.n_rows; j++) { signVectors[i][j] = 1.0; } } } void CentroidDecomposition::performDecomposition(std::vector<double> *centroidValues, bool stopOnIncompleteRank /*= false*/, bool skipSSV /*= false*/) { arma::mat X(Src); for (uint64_t i = 0; i < truncation; i++) { arma::vec &Z = skipSSV ? signVectors[i] : findLocalSignVector(X, i, true); //std::cout << Z.toString() << std::endl; // C_*i = X^T * Z arma::vec Rel_i = X.t() * Z; // R_*i = C_*i / ||C_*i|| double centroid = arma::norm(Rel_i); if (centroidValues != nullptr) { if (stopOnIncompleteRank && centroid < eps) // incomplete rank, don't even proceed with current iteration { break; } centroidValues->emplace_back(centroid); } Rel_i /= centroid; // R = Append(R, R_*i) Algebra::Operations::insert_vector_at_column(Rel, i, Rel_i); // L_*i = X * R arma::vec Load_i = X * Rel_i; // L = Append(L, L_*i) Algebra::Operations::insert_vector_at_column(Load, i, Load_i); // X := X - L_*i * R_*i^T X -= (Load_i * Rel_i.t()); } addedRows = 0; decomposed = true; } // // CentroidDecomposition algorithm // void CentroidDecomposition::increment(const arma::vec &vec) { Algebra::Operations::increment_matrix(Src, vec); Algebra::Operations::increment_matrix(Load, vec); // doesn't matter, will be overwritten ++addedRows; for (uint64_t i = 0; i < Src.n_cols; ++i) { Algebra::Operations::increment_vector(signVectors[i], 1.0); } } void CentroidDecomposition::increment(const std::vector<double> &vec) { increment(arma::vec(vec)); } // // Algorithm // arma::vec &CentroidDecomposition::findLocalSignVector(arma::mat &mx, uint64_t k, bool useInit) { arma::vec &Z = signVectors[k]; // get a reference arma::vec direction; // // First pass - init // if (!decomposed && useInit) { direction = arma::vec(mx.n_cols); for (uint64_t j = 0; j < mx.n_cols; ++j) { direction[j] = mx.at(0, j); } for (uint64_t i = 1; i < mx.n_rows; ++i) { double gradPlus = 0.0; double gradMinus = 0.0; for (uint64_t j = 0; j < mx.n_cols; ++j) { double localModPlus = direction[j] + mx.at(i, j); gradPlus += localModPlus * localModPlus; double localModMinus = direction[j] - mx.at(i, j); gradMinus += localModMinus * localModMinus; } // if keeping +1 as a sign yields a net negative to the Z[i] = gradPlus > gradMinus ? 1 : -1; for (uint64_t j = 0; j < mx.n_cols; ++j) { direction[j] += Z[i] * mx.at(i, j); } } } else // Alternative first pass - init to {+1}^n { direction = (mx.t() * Z); } // // 2+ pass - update to Z // bool flipped; double lastNorm = // cache the current value of (||D||_2)^2 to avoid recalcs arma::dot(direction, direction) + eps; // eps to avoid "parity flip" do { flipped = false; for (uint64_t i = 0; i < mx.n_rows; ++i) { double signDouble = Z[i] * 2; double gradFlip = 0.0; for (uint64_t j = 0; j < mx.n_cols; ++j) { double localMod = direction[j] - signDouble * mx.at(i, j); gradFlip += localMod * localMod; } if (gradFlip > lastNorm) // net positive from flipping { flipped = true; Z[i] *= -1; lastNorm = gradFlip + eps; for (uint64_t j = 0; j < mx.n_cols; ++j) { direction[j] -= signDouble * mx.at(i, j); } } } } while (flipped); return Z; } // simplistic API std::pair<arma::mat, arma::mat> CentroidDecomposition::PerformCentroidDecomposition(arma::mat &mx, uint64_t k) { k = k == 0 ? mx.n_cols : k; CentroidDecomposition cd(mx); cd.truncation = k; cd.performDecomposition(nullptr); return std::make_pair(cd.stealLoad(), cd.stealRel()); } } // namespace Algorithms
/**************************************** @_@ Cat Got Bored *_* #_# *****************************************/ #include <bits/stdc++.h> #define loop(i,s,e) for(int i = s;i<=e;i++) //including end point #define pb(a) push_back(a) #define sqr(x) ((x)*(x)) #define CIN ios_base::sync_with_stdio(0); cin.tie(0); #define ll long long #define ull unsigned long long #define SZ(a) int(a.size()) #define read() freopen("input.txt", "r", stdin) #define write() freopen("output.txt", "w", stdout) #define ms(a,b) memset(a, b, sizeof(a)) #define all(v) v.begin(), v.end() #define PI acos(-1.0) #define pf printf #define sfi(a) scanf("%d",&a); #define sfii(a,b) scanf("%d %d",&a,&b); #define sfl(a) scanf("%lld",&a); #define sfll(a,b) scanf("%lld %lld",&a,&b); #define sful(a) scanf("%llu",&a); #define sfulul(a,b) scanf("%llu %llu",&a,&b); #define sful2(a,b) scanf("%llu %llu",&a,&b); // A little different #define sfc(a) scanf("%c",&a); #define sfs(a) scanf("%s",a); #define mp make_pair #define paii pair<int, int> #define padd pair<dd, dd> #define pall pair<ll, ll> #define fs first #define sc second #define CASE(t) printf("Case %d: ",++t) // t initialized 0 #define cCASE(t) cout<<"Case "<<++t<<": "; #define INF 1000000000 //10e9 #define EPS 1e-9 #define flc fflush(stdout); //For interactive programs , flush while using pf (that's why __c ) using namespace std; /* IDEA: A degenerate triangle is the "triangle" formed by three collinear points. It doesn't look like a triangle, it looks like a line segment. A parabola may be thought of as a degenerate ellipse with one vertex at an infinitely distant point. ______.___________ It's a degenerate triangle As sides are 3 , 5 , 8 3 + 5 = 8 */ int tri_type(int x,int y,int z) { int mx = max(max(x,y),z); int mn_sum = x+y+z - mx; if(mn_sum>mx) { return 1; // good triangle } else if(mn_sum==mx) { return 2; // Degenerate triangle } else { return 3; //IMPOSSIBLE to construct a triangle } } int main() { int a,b,c,d; sfii(a,b); sfii(c,d); //4C3 = 4 possible 3 tuples is a possibility for a triangle int pos1 = tri_type(a,b,c); int pos2 = tri_type(a,b,d); int pos3 = tri_type(a,c,d); int pos4 = tri_type(c,b,d); //First priority triangle 1 > Then Degenerate > Then Impossible if(pos1==1 || pos2==1 || pos3==1 || pos4==1) { cout<<"TRIANGLE"<<endl; } else if(pos1==2 || pos2==2 || pos3==2 || pos4==2) { cout<<"SEGMENT"<<endl; } else { cout<<"IMPOSSIBLE"<<endl; } return 0; }
#include "CCamera.h" CCamera &TheCamera = *(CCamera *)0xB6F028; float& CCamera::m_fMouseAccelVertical = *(float *)0xB6EC18; float& CCamera::m_fMouseAccelHorzntl = *(float *)0xB6EC1C;
#ifndef __ARRAY_QUEUE_H__ #define __ARRAY_QUEUE_H__ #include <iostream> template <class T> class ArrayQueue { public: ArrayQueue(); ~ArrayQueue(); void Add(T value); T Front(); T Pop(); int Size(); bool IsEmpty(); private: T *arr; int count; protected: int MAXSIZE; }; template <class T> ArrayQueue<T>::ArrayQueue() { MAXSIZE = 12; count = 0; arr = new T[MAXSIZE]; if (!arr) std::cout << "Array Malloc ERROR" << std::endl; } template <class T> ArrayQueue<T>::~ArrayQueue() { if (!arr) return; delete[] arr; arr = NULL; count = 0; } template <class T> void ArrayQueue<T>::Add(T value) { arr[count++] = value; } template <class T> T ArrayQueue<T>::Front() { return arr[0]; } template <class T> T ArrayQueue<T>::Pop() { T ret = arr[0]; count--; for (int i = 1; i <= count; i++) { arr[i - 1] = arr[i]; } return ret; } template <class T> int ArrayQueue<T>::Size() { return count; } template <class T> bool ArrayQueue<T>::IsEmpty() { return count == 0; } #endif
#include "smithers.h" #include "player_utils.h" #include <zmq.hpp> #include <m2pp.hpp> #include <json/json.h> #include <iostream> #include <sstream> #include <random> #include <algorithm> namespace { std::string gen_random_string(const size_t len) { char s[len]; static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; std::random_device gen; for (size_t i = 0; i < len; ++i) { s[i] = alphanum[gen() % (sizeof(alphanum) - 1)]; } s[len] = 0; // null return std::string(s); } void log_request(const m2pp::request& req) { std::ostringstream log_request; log_request << "<pre>" << std::endl; log_request << "SENDER: " << req.sender << std::endl; log_request << "IDENT: " << req.conn_id << std::endl; log_request << "PATH: " << req.path << std::endl; log_request << "BODY: " << req.body << std::endl; for (std::vector<m2pp::header>::const_iterator it=req.headers.cbegin();it!=req.headers.cend();it++) { log_request << "HEADER: " << it->first << ": " << it->second << std::endl; } log_request << "</pre>" << std::endl; std::cout << log_request.str(); } } // close anon namespace namespace smithers{ bool result_comparator(const Result_t& r1,const Result_t& r2 ){return r1.score>r2.score;} Smithers::Smithers(): m_zmq_context(1), m_publisher(m_zmq_context, ZMQ_PUB) { m_publisher.bind("tcp://127.0.0.1:9950"); } void Smithers::await_registered_players(int max_players, int max_chips) { std::cout << "await_registered_players().." << std::endl; m2pp::connection conn("UUID_1", "tcp://127.0.0.1:9997", "tcp://127.0.0.1:9996"); int seat = 1; while (true){ m2pp::request req = conn.recv(); if (req.disconnect) { // std::cout << "== disconnect ==" << std::endl; continue; } log_request(req); Json::Value root; Json::Reader reader; bool was_success = reader.parse( req.body, root ); if ( !was_success ){ std::cout << "Failed to parse configuration\n" << reader.getFormattedErrorMessages(); return; } std::string default_name = "Player" + std::to_string(seat); std::string name = root.get("name", default_name).asString(); Player new_player( name, gen_random_string(100), seat, max_chips ); std::ostringstream resp; resp << create_registered_message(new_player); conn.reply_http(req, resp.str()); m_players.push_back(new_player); if (seat < max_players){ seat++; } else { break; } } m_players[0].m_is_dealer = true; } void Smithers::publish_to_all(const std::string& message) { zmq::message_t zmq_message(message.begin(), message.end()); m_publisher.send(zmq_message); } void Smithers::publish_to_all(const Json::Value& json) { if (json["type"]=="WINNER"){ std::cout << "ALL: " << json << std::endl; } std::ostringstream message; message << json; publish_to_all(message.str()); } void Smithers::play_game() { Game new_game; int dealer_seat = player_utils::get_dealer(m_players); assign_seats(dealer_seat); std::vector<Hand> hands = new_game.deal_hands( m_players.size() ); publish_to_all( create_dealt_hands_message( hands, m_players, dealer_seat ) ); //add blinds play_betting_round(3, 100, 0); new_game.deal_flop(); publish_to_all( create_table_cards_message(new_game.get_table(), player_utils::get_pot_value_for_game(m_players) ) ); play_betting_round(1, 100, 0); new_game.deal_river(); publish_to_all( create_table_cards_message(new_game.get_table(), player_utils::get_pot_value_for_game(m_players) ) ); play_betting_round(1, 100, 0); new_game.deal_turn(); publish_to_all( create_table_cards_message(new_game.get_table(), player_utils::get_pot_value_for_game(m_players) ) ); play_betting_round(1, 100, 0); std::vector<Result_t> results = award_winnings( new_game.return_hand_scores() ); publish_to_all( create_results_message(results, m_players) ); reset_and_move_dealer_to_next_player(); } void Smithers::play_tournament() { for (size_t i=0; i<m_players.size(); i++) { m_players[i].m_in_play= true; m_players[i].m_in_play_this_round = true; m_players[i].m_chips = 10000; m_players[i].m_chips_this_game = 0; m_players[i].m_chips_this_round = 0; } while ( player_utils::count_active_players(m_players) > 1 ){ play_game(); player_utils::mark_broke_players(m_players); } players_cit_t win_it = std::find_if( m_players.begin(), m_players.end(), [](const Player p){return p.m_chips>0;} ); publish_to_all( create_tournament_winner_message( win_it->m_name, win_it->m_chips ) ); } std::vector<Result_t> Smithers::award_winnings(const std::vector<ScoredFiveCardsPair_t>& scored_hands) { std::vector<Result_t> results; for (size_t i=0; i<m_players.size(); i++){ if (!m_players[i].m_in_play || !m_players[i].m_in_play_this_round) { continue; } int seat = m_players[i].m_seat; std::ostringstream cards; cards <<scored_hands[seat].second; Result_t r = {scored_hands[seat].first,cards.str(), i, 0}; results.push_back(r); } std::sort(results.begin(), results.end(), result_comparator); for (size_t r=0; r<results.size(); r++) { Player& winner = m_players[results[r].player_index]; int winners_bet = winner.m_chips_this_game; for (size_t p=0; p<m_players.size(); p++){ int amount = (m_players[p].m_chips_this_game >= winners_bet) ? winners_bet : m_players[p].m_chips_this_round; results[r].winnings += amount; m_players[p].m_chips_this_game -= amount; m_players[p].m_chips -= amount; } winner.m_chips += results[r].winnings; } return results; } Json::Value Smithers::listen_and_pull_from_queue(const std::string& player_name) { m2pp::connection conn("ID", "tcp://127.0.0.1:9900", "tcp://127.0.0.1:9901"); // is it smart to do this here? while (true){ m2pp::request req = conn.recv(); if (req.disconnect) { std::cout << "== disconnect ==" << std::endl; continue; } else { Json::Value root; Json::Reader reader; bool was_success = reader.parse(req.body, root); if (!was_success || root.get("name", "").asString() != player_name) { continue; } conn.reply_http(req, "{}"); return root; } } } enum MoveType Smithers::process_move(const Json::Value& move, Player& player, int& min_raise, int& last_bet) { std::string this_move = move.get("move", "").asString(); int this_bet = move.get("chips", "0").asInt(); if (this_bet + player.m_chips_this_round + player.m_chips_this_game>= player.m_chips) { player.m_chips_this_round = player.m_chips - player.m_chips_this_game; return ALL_IN; } if (this_move == "RAISE_TO") { int new_raise = this_bet - last_bet; if (new_raise >= min_raise) { min_raise = new_raise; player.m_chips_this_round = this_bet; last_bet = this_bet; return RAISE; // a real RAISE } else if (new_raise >= 0) { player.m_chips_this_round = last_bet; return CALL; // raise < min raise -> CALL } else if (new_raise < 0) { player.m_in_play_this_round = false; return FOLD; // this bet < last bet -> FOLD } } else if (this_move == "CALL") { if (last_bet + player.m_chips_this_game + player.m_chips_this_game > player.m_chips ) { player.m_chips_this_round = player.m_chips - player.m_chips_this_game; return ALL_IN; } player.m_chips_this_round = last_bet; return CALL; } else if (this_move == "FOLD") { player.m_in_play_this_round = false; return FOLD; // this bet < last bet -> FOLD } else { player.m_in_play_this_round = false; return FOLD; }; return FOLD; // no compiler warnings } void Smithers::play_betting_round(int first_to_bet, int min_raise, int last_bet) { int to_play_index = player_utils::get_dealer(m_players); for (int i=0; i<first_to_bet; i++){ // ie 3rd from dealer with blinds, 1 if not. to_play_index = player_utils::get_next_to_play(m_players, to_play_index ); } std::string to_play_name = m_players[to_play_index].m_name; std::string last_to_raise_name = to_play_name; do { Player& this_player = m_players[to_play_index]; publish_to_all( create_move_request(this_player, player_utils::get_pot_value_for_game(m_players), last_bet )); Json::Value move = listen_and_pull_from_queue(this_player.m_name); enum MoveType result = process_move(move, this_player, min_raise, last_bet); if (result == ALL_IN && this_player.m_chips_this_round > last_bet) { last_bet = this_player.m_chips_this_round; last_to_raise_name = this_player.m_name; } if (result == RAISE) { last_to_raise_name = this_player.m_name; } // 4. Tell people about it publish_to_all( create_move_message( this_player, result, this_player.m_chips_this_round ) ); // 5. Move to next player to_play_index = player_utils::get_next_to_play(m_players, to_play_index); to_play_name = m_players[to_play_index].m_name; } while (last_to_raise_name != to_play_name); // Finally add this round's betting to grand pot player_utils::transfer_round_bets_to_game_bets(m_players); } void Smithers::print_players() { std::ostringstream message; message << '['; for (players_cit_t it = m_players.cbegin(); it != m_players.cend(); it++) { message << '{' << "\"name\":\"" << it->m_name <<"\", " << "\"seat\":\"" << it->m_seat <<"\", " << "\"chips\":\"" << it->m_chips <<"\" " << "},"; } message << "]" << std::endl; publish_to_all(message.str()); } int Smithers::assign_seats(int dealer) { int seat = 0; for (size_t i=0; i<m_players.size(); ++i) { int seat_no = (dealer + i + 1) % m_players.size(); if ( ! m_players[seat_no].m_in_play ) { m_players[seat_no].m_seat = -1; } else { m_players[seat_no].m_seat = seat; seat++; } } return seat; // number of players } void Smithers::reset_and_move_dealer_to_next_player() { int dealer = player_utils::get_dealer(m_players); for (size_t i=0; i<m_players.size(); ++i){ m_players[i].m_in_play_this_round = true; } int next_dealer = player_utils::get_next_to_play(m_players, dealer); std::cout<< dealer<< " "<< next_dealer << std::endl; m_players[dealer].m_is_dealer = false; m_players[next_dealer].m_is_dealer = true; }; } // smithers namespace
class Solution { public: bool isOneEditDistance(string s, string t) { int l1 = s.length(), l2 = t.length(); if(abs(l1-l2) > 1) return false; bool flag = false; if(l1 == l2){ for(int i = 0; i < l1; ++i){ if(s[i] != t[i]){ if(!flag) flag = true; else return false; } } }else{ int len; string s1, s2; if(l1 > l2){ len = l1; s1 = s; s2 = t; }else{ len = l2; s1 = t; s2 = s; } for(int i = 0, j = 0; i < len; ++i){ if(s1[i] != s2[j]){ if(!flag){ flag = true; }else return false; }else{ ++j; } } } return flag; } };
#include <iostream> #include <vector> #include "TextPosition.h" using namespace std; size_t findDistanceBetweenPositions(vector<string> const& text, TextPosition pos1, TextPosition pos2) { size_t dist = 0; for (size_t i = 0; i < size(text); i++) { for (size_t j = 0; j < size(text.at(i)); j++) { TextPosition curPos(i, j); if (curPos > pos1 && curPos < pos2) dist++; } } return dist; } size_t findFirstAndSec(vector<string> const& text, char ch1, char ch2) { size_t dist = string::npos; TextPosition ch1Pos(string::npos, string::npos); TextPosition ch2Pos(0, 0); //поиск наименьшего вхождения первого символа и наибольшего вхождения второго for (size_t i = 0; i < size(text); i++) { auto& x = text.at(i); size_t firstOf = x.find_first_of(ch1); size_t lastOf = x.find_last_of(ch2); if (lastOf < firstOf) return string::npos; if (lastOf == firstOf) return 0; if (firstOf != string::npos) { TextPosition ch1Buf(i, firstOf); if (ch1Buf < ch1Pos) ch1Pos = ch1Buf; } if (lastOf != string::npos) { TextPosition ch2Buf(i, lastOf); if (ch2Buf > ch2Pos) ch2Pos = ch2Buf; } } return findDistanceBetweenPositions(text, ch1Pos, ch2Pos); } int testFun() { vector<string> const& text = { "eA line", "Anothe ine", "!@#!$^!!%08928333", " ", "wow lol kek cheburek w ko" }; vector<string> const& test = { "1", "2", "3", "4", "5", "6", "7" }; if (findFirstAndSec(text, 'e', 'e') != 58) return 1; if (findFirstAndSec(text, 'A', 'n') != 13) return 2; if (findFirstAndSec(text, '!', '3') != 15) return 3; if (findFirstAndSec(text, ' ', ' ') != 60) return 4; if (findFirstAndSec(text, 'w', 'k') != 22) return 5; if (findFirstAndSec(test, '1', '1') != 0) return 6; if (findFirstAndSec(test, '7', '2') != string::npos) return 7; return 0; } int main() { if (testFun() == 0) cout << "Tests are done!"; return 0; }
// Tom Koole // 2011-11-18 // Project Euler #17 // ugly but it works #include <stdio.h> #include <stdlib.h> #include <string> // ascii value #define ZERO 48 std::string lookUp(int i); int main() { std::string words = ""; for(int i = 1; i <= 1000; i++) { std::string word = lookUp(i); words += word; } printf("The length of all the numbers from 1 to 1000 in word format is: %d\n", words.length()); system("Pause"); } std::string lookUp(int i) { if(i > 9999) return ""; char str[] = {0,0,0,0,0}; sprintf((char*)&str, "%d", i); switch(i) { // Base Cases case 1: return "one"; case 2: return "two"; case 3: return "three"; case 4: return "four"; case 5: return "five"; case 6: return "six"; case 7: return "seven"; case 8: return "eight"; case 9: return "nine"; case 10: return "ten"; case 11: return "eleven"; case 12: return "twelve"; case 13: return "thirteen"; case 14: return "fourteen"; case 15: return "fifteen"; case 16: return "sixteen"; case 17: return "seventeen"; case 18: return "eighteen"; case 19: return "nineteen"; default: { if(i < 100) { switch(str[0] - ZERO) { // Recursively get 'ones' column (could eventually be used for thousands) case 2: return "twenty"+lookUp(str[1]-ZERO); case 3: return "thirty"+lookUp(str[1]-ZERO); case 4: return "forty"+lookUp(str[1]-ZERO); case 5: return "fifty"+lookUp(str[1]-ZERO); case 6: return "sixty"+lookUp(str[1]-ZERO); case 7: return "seventy"+lookUp(str[1]-ZERO); case 8: return "eighty"+lookUp(str[1]-ZERO); case 9: return "ninety"+lookUp(str[1]-ZERO); } } if(i >= 100 && i < 1000) { if(i - (str[0] - ZERO) * 100 > 0) // given number YXZ output is: lookup(Y) + hundredand + lookup(XZ) return lookUp(str[0]-ZERO)+"hundredand" + lookUp(i - (str[0]-ZERO) * 100); else // hundreds base case return lookUp(str[0]-ZERO)+"hundred"; } if(i >= 1000 && i < 10000) { // given number YXZ output is: lookup(Y) + hundredand + lookup(XZ) return lookUp(str[0]-ZERO)+"thousand" + lookUp(i - (str[0]-ZERO) * 1000); } // could go on } } return ""; }
#pragma once #include "common.h" #include "streams/streams.h" #include <string> #include <vector> NAMESPACE_BEGIN(NAMESPACE_BINTABLE) class BaseOperation { public: std::string operation_type; virtual void operator()() = 0; virtual ~BaseOperation() = default; }; class NoOperation : public BaseOperation { public: NoOperation(); void operator()() override; }; class SequenceOperation : public BaseOperation { public: SequenceOperation(); void operator()() override; ~SequenceOperation() override; std::vector<BaseOperation *> operations; }; class LoopOperation : public BaseOperation { public: LoopOperation(); void operator()() override; ~LoopOperation() override; BaseOperation *operation; uint64_t n_iter; }; class ReadWriteOperation : public BaseOperation { public: InputStream* input_stream = nullptr; OutputStream* output_stream = nullptr; }; class RawOperation : public ReadWriteOperation { public: uint64_t n_bytes; }; class RawSkipOperation : public RawOperation { public: RawSkipOperation(uint64_t n_bytes); void operator()() override; }; class RawWriteOperation : public RawOperation { public: RawWriteOperation(uint64_t n_bytes); void operator()() override; }; NAMESPACE_END(NAMESPACE_BINTABLE)
#pragma once #include "tool.h" #include "glm.hpp" #include "GL/glew.h" class ShaderProgram; class PointLightTool : public VRTool { public: PointLightTool(); ~PointLightTool(); bool init() override; void shutdown() override; void activate() override; void deactivate() override; void update( float dt ) override; void render( const glm::mat4& view, const glm::mat4& projection ) override {} // Setters void setTargetShader( ShaderProgram** target ) { target_shader_ = target; } void setActivateShader( ShaderProgram* activate ); void setDeactivateShader( ShaderProgram* deactivate ) { deactivate_shader_ = deactivate; } // Getters glm::vec3 lightPos() { return light_pos_; } protected: glm::vec3 light_pos_; ShaderProgram** target_shader_; ShaderProgram* activate_shader_; ShaderProgram* deactivate_shader_; GLuint tool_shader_position_location_; };
#include<iostream> #include"time.h" Time operator-(const Time &time1,const Time&time2){ Time tmp; tmp.secondintotal=time1.secondintotal-time2.secondintotal; tmp.hour=tmp.secondintotal/3600; tmp.minute = (tmp.secondintotal-tmp.hour*3600)/60; tmp.second = tmp.secondintotal%60; return tmp; } bool operator<(const Time &time1,const Time&time2){ return (time1.secondintotal<time2.secondintotal ? true :false); } bool operator>(const Time &time1,const Time&time2){ return (time1.secondintotal>time2.secondintotal ? true :false); } bool operator==(const Time &time1,const Time&time2){ return (time1.secondintotal==time2.secondintotal ? true :false); } Time &Time::operator+=(int s){ secondintotal+=s; hour=secondintotal/3600; minute = (secondintotal-hour*3600)/60; second = secondintotal%60; return *this; } Time &Time::operator-=(int s){ if(secondintotal<s) cout<<"error.second < type"; else {secondintotal-=s; hour=secondintotal/3600; minute = (secondintotal-hour*3600)/60; second = secondintotal%60; } return *this; } Time &Time::operator++(){ secondintotal++; hour=secondintotal/3600; minute = (secondintotal-hour*3600)/60; second = secondintotal%60; return *this; } Time Time::operator++(int x){ Time tmp=*this; secondintotal++; hour=secondintotal/3600; minute = (secondintotal-hour*3600)/60; second = secondintotal%60; return tmp; } Time &Time::operator--(){ secondintotal--; hour=secondintotal/3600; minute = (secondintotal-hour*3600)/60; second = secondintotal%60; return *this; } Time Time::operator--(int x){ Time tmp=*this; secondintotal--; hour=secondintotal/3600; minute = (secondintotal-hour*3600)/60; second = secondintotal%60; return tmp; } ostream &operator<<(ostream &os ,const Time &time){ os<<time.hour<<':'<<time.minute<<':'<<time.second<<endl; return os; } istream &operator>>(istream &is , Time &time){ is>>time.hour>>time.minute>>time.second; time.secondintotal=time.second; return is; }
/* * Copyright (C) 2013 Tom Wong. All rights reserved. */ #ifndef __GT_DOC_NOTE_H__ #define __GT_DOC_NOTE_H__ #include "gtdocrange.h" GT_BEGIN_NAMESPACE class GtDocNoteMsg; class GT_BASE_EXPORT GtDocNote : public GtObject { public: enum NoteType { InvalidNote, Highlight, Underline }; public: explicit inline GtDocNote() : m_type(InvalidNote) {} GtDocNote(NoteType type, const GtDocRange &range); ~GtDocNote(); public: inline NoteType type() const { return m_type; } inline GtDocRange range() const { return m_range; } void setRange(const GtDocRange &range); bool isValid() const; void serialize(GtDocNoteMsg &msg) const; bool deserialize(const GtDocNoteMsg &msg); private: NoteType m_type; GtDocRange m_range; private: Q_DISABLE_COPY(GtDocNote) }; #ifndef QT_NO_DATASTREAM GT_BASE_EXPORT QDataStream &operator<<(QDataStream &, const GtDocNote &); GT_BASE_EXPORT QDataStream &operator>>(QDataStream &, GtDocNote &); #endif GT_END_NAMESPACE #endif /* __GT_DOC_NOTE_H__ */
#include <iostream> #include <map> #include <string> #include <vector> #include <algorithm> #include <functional> #include <errno.h> #include <sstream> using namespace std; #define MAX 99999 class FloorBoards { public: int addLine(int now,int prev,int obs,int sizeX) { int cnt = 0; bool isHorizon = false; for (int i=0; i<sizeX; ++i) { if(((now >> i)&1) == 1) { //vertical stick if(((prev >> i)&1) != 1) ++cnt; isHorizon = false; } else { //horizon stick if(((obs >> i)&1) == 1) { isHorizon = false; } else { if(!isHorizon) ++cnt; isHorizon = true; } } } return cnt; } int layout(vector <string> room) { int sizeX = static_cast<int>(room[0].size()); int sizeY = static_cast<int>(room.size()); vector<vector<int> > dp(sizeY+1,vector<int>(1<<sizeX,MAX)); dp[0][0] = 0; for (int y=0; y<sizeY; ++y) { int obs = 0; for(int x=0;x<sizeX;++x) if(room[y][x] == '#') obs += 1 << x; for (int prev = 0; prev< 1<<sizeX; ++prev) { if(dp[y][prev] == MAX) continue; //for avoid first calculation for (int now = 0; now< 1<<sizeX; ++now) { if((obs&now) != 0) continue; dp[y+1][now] = min(dp[y+1][now],dp[y][prev]+addLine(now,prev,obs,sizeX)); } } } int ret = MAX; for(int i=0;i< 1<<sizeX;++i) ret = min(ret,dp[sizeY][i]); return ret; } };
#include "SnowPlane.h" SnowPlane::SnowPlane( ae::Texture& _HeightMap, ae::Texture& _NormalMap, float _Size, Uint32 _SubdivisionWidth, Uint32 _SubdivisionHeight ) : ae::PlaneMesh( _Size, _SubdivisionWidth, _SubdivisionHeight ), m_Shader( "../../../Data/Projects/Snow/SnowVertex.glsl", "../../../Data/Projects/Snow/SnowFragment.glsl", "", "../../../Data/Projects/Snow/SnowControl.glsl", "../../../Data/Projects/Snow/SnowEvaluation.glsl" ) { SetName( "Ground" ); m_Shader.SetName( "Ground Shader" ); ae::Material* SnowMat = new ae::Material( m_Shader ); SnowMat->SetName( "Ground Material" ); SnowMat->SetIsInstance( True ); SnowMat->AddTextureParameterToMaterial( "HeightMap", "HeightMap", &_HeightMap ); SnowMat->AddTextureParameterToMaterial( "NormalMap", "NormalMap", &_NormalMap ); SnowMat->AddColorParameterToMaterial( "SnowColor", "SnowColor", ae::Color::White ); SnowMat->AddColorParameterToMaterial( "SnowShadowColor", "SnowShadowColor", ae::Color( 0.2f, 0.2f, 0.3f ) ); SnowMat->AddColorParameterToMaterial( "SnowRimColor", "SnowRimColor", ae::Color( 0.75f, 0.75f, 1.0f ) ); SnowMat->AddFloatParameterToMaterial( "SnowRimPower", "SnowRimPower", 10.0f ); SnowMat->AddFloatParameterToMaterial( "SnowRimStrength", "SnowRimStrength", 0.0f, 0.0f, 1.0 ); SnowMat->AddColorParameterToMaterial( "SnowOceanColor", "SnowOceanColor", ae::Color::White ); SnowMat->AddFloatParameterToMaterial( "SnowOceanSpecularPower", "SnowOceanSpecularPower", 100.0f, 0.0f ); SnowMat->AddFloatParameterToMaterial( "SnowOceanSpecularStrength", "SnowOceanSpecularStrength", 0.1f, 0.0f, 1.0f ); SnowMat->AddColorParameterToMaterial( "SnowGlitterColor", "SnowGlitterColor", ae::Color( 7.0f, 7.0f, 7.0f ) ); SnowMat->AddFloatParameterToMaterial( "SnowGlitterThreshold", "SnowGlitterThreshold", 0.75f, 0.0f, 1.0f ); SnowMat->AddFloatParameterToMaterial( "SnowGlitterFrequency", "SnowGlitterFrequency", 200.0f, 0.0f ); SnowMat->AddFloatParameterToMaterial( "SnowGlitterScintillationSpeed", "SnowGlitterScintillationSpeed", 50.0f ); SetMaterial( *SnowMat ); SetBlendMode( ae::BlendMode::BlendNone ); SetPrimitiveType( ae::PrimitiveType::Patches ); }
/********************************************************************** ** Description: This function uses a pointer to accept the address of an array of int and the umber of elements in the array is passed as a seoarate integer parameter. The function asks the user dynamically allocate an array that is twice as long. Freeing the memory. **********************************************************************/ void transformArray (int* &myAarray, int size){ int newSize = size * 2; int *newArray; newArray = new int[newSize]; ///allocate memmory for (int count = 0; count < size; count++){ //assign value from old array to the new array *(newArray + count) = myAarray[count]; } for (int count = 0; count < size; count++){ //assign new value to the new array *(newArray + size + count) = myAarray[count] + 1; } delete [] myAarray; //freeing the memory myAarray = newArray; //assgin new array to the pointer newArray = NULL; // set to null that the newArray doesn't point to any memory }
/* * LSST Data Management System * Copyright 2014-2015 AURA/LSST. * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <https://www.lsstcorp.org/LegalNotices/>. */ #ifndef LSST_SG_MATRIX3D_H_ #define LSST_SG_MATRIX3D_H_ /// \file /// \brief This file contains a class representing 3x3 real matrices. #include <iosfwd> #include "Vector3d.h" namespace lsst { namespace sg { /// A 3x3 matrix with real entries stored in double precision. class Matrix3d { public: /// This constructor creates a zero matrix. Matrix3d() {} /// This constructor creates a matrix from its components, /// where `mij` specifies the component for row `i` and column `j`. Matrix3d(double m00, double m01, double m02, double m10, double m11, double m12, double m20, double m21, double m22) { Matrix3d & m = *this; m(0, 0) = m00; m(0, 1) = m01; m(0, 2) = m02; m(1, 0) = m10; m(1, 1) = m11; m(1, 2) = m12; m(2, 0) = m20; m(2, 1) = m21; m(2, 2) = m22; } /// This constructor creates a diagonal matrix with diagonal components /// set to the components of `v`. explicit Matrix3d(Vector3d const & v) { Matrix3d & m = *this; m(0, 0) = v(0); m(1, 1) = v(1); m(2, 2) = v(2); } /// This constructor returns the identity matrix scaled by `s`. explicit Matrix3d(double s) { Matrix3d & m = *this; m(0, 0) = s; m(1, 1) = s; m(2, 2) = s; } bool operator==(Matrix3d const & m) const { return _c[0] == m._c[0] && _c[1] == m._c[1] && _c[2] == m._c[2]; } bool operator!=(Matrix3d const & m) const { return _c[0] != m._c[0] || _c[1] != m._c[1] || _c[2] != m._c[2]; } ///@{ /// `getColumn` returns the `c`-th matrix column. Bounds are not checked. Vector3d & getColumn(int c) { return _c[c]; } Vector3d const & getColumn(int c) const { return _c[c]; } ///@} ///@{ /// The function call operator returns the scalar at row `r` and column `c`. /// Bounds are not checked. double & operator()(int r, int c) { return getColumn(c)(r); } double operator()(int r, int c) const { return getColumn(c)(r); } ///@} /// `inner` returns the Frobenius inner product of this matrix with `m`. double inner(Matrix3d const & m) const { Matrix3d p = cwiseProduct(m); Vector3d sum = p.getColumn(0) + p.getColumn(1) + p.getColumn(2); return sum(0) + sum(1) + sum(2); } /// `getSquaredNorm` returns the Frobenius inner product of this matrix /// with itself. double getSquaredNorm() const { return inner(*this); } /// `getNorm` returns the L2 (Frobenius) norm of this matrix. double getNorm() const { return std::sqrt(getSquaredNorm()); } /// The multiplication operator returns the product of this matrix /// with vector `v`. Vector3d operator*(Vector3d const & v) const { return Vector3d(getColumn(0) * v(0) + getColumn(1) * v(1) + getColumn(2) * v(2)); } /// The multiplication operator returns the product of this matrix /// with matrix `m`. Matrix3d operator*(Matrix3d const & m) const { Matrix3d r; for (int i = 0; i < 3; ++i) { r.getColumn(i) = this->operator*(m.getColumn(i)); } return r; } /// The addition operator returns the sum of this matrix and `m`. Matrix3d operator+(Matrix3d const & m) const { Matrix3d r; for (int i = 0; i < 3; ++i) { r.getColumn(i) = getColumn(i) + m.getColumn(i); } return r; } /// The subtraction operator returns the difference between this matrix and `m`. Matrix3d operator-(Matrix3d const & m) const { Matrix3d r; for (int i = 0; i < 3; ++i) { r.getColumn(i) = getColumn(i) - m.getColumn(i); } return r; } /// `cwiseProduct` returns the component-wise product of this matrix and `m`. Matrix3d cwiseProduct(Matrix3d const & m) const { Matrix3d r; for (int i = 0; i < 3; ++i) { r.getColumn(i) = getColumn(i).cwiseProduct(m.getColumn(i)); } return r; } /// `transpose` returns the transpose of this matrix. Matrix3d transpose() const { Matrix3d t; Matrix3d const &m = *this; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { t(i, j) = m(j, i); } } return t; } /// `inverse` returns the inverse of this matrix. Matrix3d inverse() const { Matrix3d inv; Matrix3d const & m = *this; // Find the first column of Adj(m), the adjugate matrix of m. Vector3d a0(m(1, 1) * m(2, 2) - m(2, 1) * m(1, 2), m(1, 2) * m(2, 0) - m(2, 2) * m(1, 0), m(1, 0) * m(2, 1) - m(2, 0) * m(1, 1)); // Find 1.0/det(m), where the determinant of m is the dot product of // the first row of m with the first column of Adj(m). double rdet = 1.0 / (a0(0) * m(0,0) + a0(1) * m(0,1) + a0(2) * m(0,2)); // The inverse of m is Adj(m)/det(m); compute it column by column. inv.getColumn(0) = a0 * rdet; inv(0,1) = (m(0, 2) * m(2, 1) - m(2, 2) * m(0, 1)) * rdet; inv(1,1) = (m(0, 0) * m(2, 2) - m(2, 0) * m(0, 2)) * rdet; inv(2,1) = (m(0, 1) * m(2, 0) - m(2, 1) * m(0, 0)) * rdet; inv(0,2) = (m(0, 1) * m(1, 2) - m(1, 1) * m(0, 2)) * rdet; inv(1,2) = (m(0, 2) * m(1, 0) - m(1, 2) * m(0, 0)) * rdet; inv(2,2) = (m(0, 0) * m(1, 1) - m(1, 0) * m(0, 1)) * rdet; return inv; } /// `print` writes this matrix to the given output stream. Each line of /// output is indented by the given number of spaces. void print(std::ostream & os, int indent) const; private: Vector3d _c[3]; }; std::ostream & operator<<(std::ostream &, Matrix3d const &); }} // namespace lsst::sg #endif // LSST_SG_MATRIX3D_H_
#ifndef PLAYER_H #define PLAYER_H #include "hand.h" using namespace std; /****************************************************** ** Class: Player ** Purpose: A class to hold all of the relevant ** variables that make up a player object, as well as ** all of its necessary functionality. ******************************************************/ class Player { private: Hand hand; string name; public: /****************************************************** ** Function: Player ** Description: Simple constructor for a player object. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ Player(); //TODO// Code this constructor /****************************************************** ** Function: ~Player ** Description: Simple destructor for a player object. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ ~Player(); //TODO// Code this destructor /****************************************************** ** Function: get_name ** Description: Simple accessor for the player's name. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: Return a string of the player's ** name. ******************************************************/ string get_name(); //TODO// Code this accessor /****************************************************** ** Function: print_hand ** Description: Prints the player's hand. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ void print_hand(); /****************************************************** ** Function: play_card ** Description: Header function for a player to play a ** card. ** Parameters: Card &, int &, Deck ** Pre-conditions: Take in a reference to the active ** card, a reference to the cards left in the deck, and ** a deck object to draw from. ** Post-conditions: All remain unchanged by this ** function. ******************************************************/ void play_card(Card &, int &, Deck); /****************************************************** ** Function: is_winner ** Description: Determines if there is a winner in the ** game. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: Returns a boolean value to show ** if the player is a winner. ******************************************************/ bool is_winner(); /****************************************************** ** Function: set_name ** Description: Simple mutator for the name of a player ** object. ** Parameters: string ** Pre-conditions: Take in a string to represent the ** new name. ** Post-conditions: Unchanged. ******************************************************/ void set_name(string); //TODO// Code this mutator ////string get_name(); /****************************************************** ** Function: ai_play ** Description: Header file for executing an ai play. ** Parameters: Card &, int &, Deck ** Pre-conditions: Take in a reference to the active ** card object, a reference to the number of cards left ** in the deck, and the deck object. ** Post-conditions: Will eventually change the active ** card objects member variables. ******************************************************/ void ai_play(Card &, int &, Deck); /****************************************************** ** Function: is_possible_play ** Description: Tests if there is a possible play in a ** player's hand and which card is possible. ** Parameters: Card & ** Pre-conditions: Take in a reference to the active ** card object. ** Post-conditions: Return an integer value to show ** which card in the hand is viable to play. ******************************************************/ int is_possible_play(Card &); /****************************************************** ** Function: is_int ** Description: Simple error handling function to test ** if a given string is an integer value. Only used ** within this class. ** Parameters: string ** Pre-conditions: Take in a string to test. ** Post-conditions: Return a boolean value to represent ** if the string is an integer or not. ******************************************************/ bool is_int(string); /****************************************************** ** Function: choose_card ** Description: Simple driving function for choosing a ** card. ** Parameters: Card & ** Pre-conditions: Take in a reference to the active ** card object. ** Post-conditions: Return a string to show which card ** they chose. ******************************************************/ string choose_card(Card &); /****************************************************** ** Function: display_active_card ** Description: Simply outputs the active card rank and ** suit to the string. ** Parameters: Card & ** Pre-conditions: Take in a reference to the active ** card object. ** Post-conditions: Unchanged. ******************************************************/ void display_active_card(Card &); /****************************************************** ** Function: fill_player_hand ** Description: Fills the players hand with cards. ** Parameters: int &, Deck ** Pre-conditions: Take in a reference to the cards left ** in the deck as well as the literal deck object. ** Post-conditions: Draw cards from the deck and change ** the cards_left accordingly. ******************************************************/ void fill_player_hand(int & cards_left, Deck game_deck); /****************************************************** ** Function: get_n_cards ** Description: Simple accessor to retrieve the value ** of n_cards. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: Return an integer value to show ** what n_cards is equal to. ******************************************************/ int get_n_cards(); //?// Might need mutator and accessor for Hand class hand }; #endif
#pragma once #include <qwidget.h> #include "HandlerButton.h" class UtilitiesLabel : public QWidget { public: UtilitiesLabel(); };
#include <bits/stdc++.h> using namespace std; string ltrim(const string &); string rtrim(const string &); vector<string> split(const string &); /* * Complete the 'minimizeMeetingCost' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER N * 2. INTEGER M * 3. 2D_INTEGER_ARRAY costs */ int minimizeMeetingCost(int N, int M, vector<vector<int>> costs) { int minima = costs[0][0]; for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { if (j + 1 != M && costs[i][j + 1] < 0) costs[i][j] += costs[i][j + 1]; if (j != 0 && costs[i][j - 1] < 0) costs[i][j] += costs[i][j - 1]; if (i + 1 != N && costs[i + 1][j] < 0) costs[i][j] += costs[i + 1][j]; if (i != 0 && costs[i - 1][j] < 0) costs[i][j] += costs[i - 1][j]; minima = min(minima, costs[i][j]); } cout << minima << endl; return minima; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string N_temp; getline(cin, N_temp); int N = stoi(ltrim(rtrim(N_temp))); string M_temp; getline(cin, M_temp); int M = stoi(ltrim(rtrim(M_temp))); string costs_rows_temp; getline(cin, costs_rows_temp); int costs_rows = stoi(ltrim(rtrim(costs_rows_temp))); string costs_columns_temp; getline(cin, costs_columns_temp); int costs_columns = stoi(ltrim(rtrim(costs_columns_temp))); vector<vector<int>> costs(costs_rows); for (int i = 0; i < costs_rows; i++) { costs[i].resize(costs_columns); string costs_row_temp_temp; getline(cin, costs_row_temp_temp); vector<string> costs_row_temp = split(rtrim(costs_row_temp_temp)); for (int j = 0; j < costs_columns; j++) { int costs_row_item = stoi(costs_row_temp[j]); costs[i][j] = costs_row_item; } } int result = minimizeMeetingCost(N, M, costs); fout << result << "\n"; fout.close(); return 0; } string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))); return s; } string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end()); return s; } vector<string> split(const string &str) { vector<string> tokens; string::size_type start = 0; string::size_type end = 0; while ((end = str.find(" ", start)) != string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; }
#ifndef GUNNER_H #define GUNNER_H #include "Player.h" class Object; class Gunner : public Player { public: Gunner(const char*, const char*); Gunner(const Gunner&); virtual void update(void); Object* fire(void); void trigger(Vector); void rotateBullet(Vector); char whichClass(void); private: Object* modelBullet; Vector gunsight; short bulletIndex; int bulletCount; }; #endif
#include <iostream> #include <sstream> #include <cstdlib> #include <cstdio> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <iomanip> #include <set> #include <climits> #include <ctime> #include <complex> #include <cmath> #include <string> #include <cctype> #include <cstring> #include <algorithm> using namespace std; typedef pair<int,int> pii; typedef long double ld; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; const int maxn=200005; const int INF=0x3f3f3f3f; const double PI=acos(-1.0); const double EPS=1e-9; inline int sgn(double a){return a<-EPS? -1:a>EPS;} char str[maxn]; char ans[maxn]; int cnt[30]; int main(){ string s; cin>>s; int sz=s.size(); for(int i=0;i<sz;i++) cnt[s[i]-'a']++; int r=25; int ind=0; for(int i=0;i<26;i++){ if(cnt[i]%2!=0){ while(cnt[r]%2==0&&i<r) r--; if(i==r){ ans[sz/2]='a'+i; cnt[i]--; }else{ cnt[i]++; cnt[r]--; } } for(int j=0;j<cnt[i]/2;j++){ ans[ind]=ans[sz-ind-1]='a'+i; ind++; } } cout<<ans<<"\n"; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2006 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #if defined(SVG_SUPPORT) && defined(SVG_DOM) && defined(SVG_FULL_11) #include "modules/svg/src/svgpch.h" #include "modules/svg/src/svgdom/svgdomanimatedvalueimpl.h" #include "modules/svg/src/svgdom/svgdommatriximpl.h" #include "modules/svg/src/svgdom/svgdomstringimpl.h" #include "modules/svg/src/svgdom/svgdomstringurlimpl.h" #include "modules/svg/src/svgdom/svgdomnumberimpl.h" #include "modules/svg/src/svgdom/svgdomnumberorpercentageimpl.h" #include "modules/svg/src/svgdom/svgdompreserveaspectratioimpl.h" #include "modules/svg/src/svgdom/svgdomenumerationimpl.h" #include "modules/svg/src/svgdom/svgdomlengthimpl.h" #include "modules/svg/src/svgdom/svgdomangleimpl.h" #include "modules/svg/src/svgdom/svgdomrectimpl.h" #include "modules/svg/src/svgdom/svgdompointimpl.h" #include "modules/svg/src/svgdom/svgdomtransformimpl.h" #include "modules/svg/src/svgdom/svgdompaintimpl.h" #include "modules/svg/src/svgdom/svgdomlistimpl.h" #include "modules/svg/src/svgdom/svgdomanimatedtransformlistimpl.h" #include "modules/logdoc/logdoc.h" SVGDOMAnimatedValueImpl::SVGDOMAnimatedValueImpl(SVGObject* b, SVGObject* a, const char* n, SVGDOMItemType itemtype, SVGDOMItemType sub_itemtype) : m_itemtype(itemtype), m_sub_itemtype(sub_itemtype), m_base(b), m_anim(a), m_name(n) { SVGObject::IncRef(m_base); SVGObject::IncRef(m_anim); } /* static */ OP_STATUS SVGDOMAnimatedValueImpl::Make(SVGDOMAnimatedValueImpl*& animated_value, SVGObject* base_obj, SVGObject* anim_obj, SVGDOMItemType itemtype, SVGDOMItemType sub_itemtype /* = SVG_DOM_ITEMTYPE_UNKNOWN */) { const char* name = LowGetDOMName(itemtype, sub_itemtype); if (!(animated_value = OP_NEW(SVGDOMAnimatedValueImpl, (base_obj, anim_obj, name, itemtype, sub_itemtype)))) { return OpStatus::ERR_NO_MEMORY; } return OpStatus::OK; } /* virtual */ SVGDOMAnimatedValueImpl::~SVGDOMAnimatedValueImpl() { SVGObject::DecRef(m_base); SVGObject::DecRef(m_anim); } /* virtual */ OP_BOOLEAN SVGDOMAnimatedValueImpl::GetPrimitiveValue(SVGDOMPrimitiveValue &value, Field field) { SVGObject *obj = (field == FIELD_ANIM) ? m_anim : m_base; return LowGetValue(value, m_itemtype, m_sub_itemtype, obj); } /* virtual */ const char* SVGDOMAnimatedValueImpl::GetDOMName() { return m_name; } /* static */ const char* SVGDOMAnimatedValueImpl::LowGetDOMName(SVGDOMItemType type, SVGDOMItemType subtype) { switch(type) { case SVG_DOM_ITEMTYPE_STRING: return "SVGAnimatedString"; case SVG_DOM_ITEMTYPE_ENUM: return "SVGAnimatedEnumeration"; case SVG_DOM_ITEMTYPE_BOOLEAN: return "SVGAnimatedBoolean"; case SVG_DOM_ITEMTYPE_NUMBER: return "SVGAnimatedNumber"; case SVG_DOM_ITEMTYPE_LENGTH: return "SVGAnimatedLength"; case SVG_DOM_ITEMTYPE_PRESERVE_ASPECT_RATIO: return "SVGAnimatedPreserveAspectRatio"; case SVG_DOM_ITEMTYPE_RECT: return "SVGAnimatedRect"; case SVG_DOM_ITEMTYPE_ANGLE: return "SVGAnimatedAngle"; case SVG_DOM_ITEMTYPE_NUMBER_OPTIONAL_NUMBER_0: case SVG_DOM_ITEMTYPE_NUMBER_OPTIONAL_NUMBER_1: return "SVGAnimatedNumber"; case SVG_DOM_ITEMTYPE_INTEGER_OPTIONAL_INTEGER_0: case SVG_DOM_ITEMTYPE_INTEGER_OPTIONAL_INTEGER_1: return "SVGAnimatedInteger"; case SVG_DOM_ITEMTYPE_LIST: switch(subtype) { case SVG_DOM_ITEMTYPE_POINT: return "SVGAnimatedPointList"; case SVG_DOM_ITEMTYPE_NUMBER: return "SVGAnimatedNumberList"; case SVG_DOM_ITEMTYPE_LENGTH: return "SVGAnimatedLengthList"; case SVG_DOM_ITEMTYPE_MATRIX: return "SVGAnimatedMatrixList"; default: OP_ASSERT(!"Unknown animated list type"); return "SVGAnimatedList"; } default: // Silence compiler (and catch future errors) OP_ASSERT(!"Not reached"); return "SVGAnimatedValue"; } } /* virtual */ BOOL SVGDOMAnimatedValueImpl::IsSetByNumber() { return m_itemtype == SVG_DOM_ITEMTYPE_ENUM || m_itemtype == SVG_DOM_ITEMTYPE_BOOLEAN || m_itemtype == SVG_DOM_ITEMTYPE_NUMBER || m_itemtype == SVG_DOM_ITEMTYPE_NUMBER_OPTIONAL_NUMBER_0 || m_itemtype == SVG_DOM_ITEMTYPE_NUMBER_OPTIONAL_NUMBER_1 || m_itemtype == SVG_DOM_ITEMTYPE_INTEGER_OPTIONAL_INTEGER_0 || m_itemtype == SVG_DOM_ITEMTYPE_INTEGER_OPTIONAL_INTEGER_1; } /* virtual */ OP_BOOLEAN SVGDOMAnimatedValueImpl::SetNumber(double number) { if (m_itemtype == SVG_DOM_ITEMTYPE_ENUM) { OP_ASSERT(m_base->Type() == SVGOBJECT_ENUM); SVGEnum *enum_obj = static_cast<SVGEnum *>(m_base); RETURN_FALSE_IF(enum_obj->EnumValue() == (unsigned short)number); enum_obj->SetEnumValue((unsigned short)number); return OpBoolean::IS_TRUE; } else if (m_itemtype == SVG_DOM_ITEMTYPE_BOOLEAN) { SVGEnum *enum_obj = static_cast<SVGEnum *>(m_base); BOOL value = (number != 0.0); RETURN_FALSE_IF(!!enum_obj->EnumValue() == value); enum_obj->SetEnumValue(value); return OpBoolean::IS_TRUE; } else if (m_itemtype == SVG_DOM_ITEMTYPE_NUMBER) { SVGNumberObject *number_obj = static_cast<SVGNumberObject *>(m_base); RETURN_FALSE_IF(number_obj->value == number); // Should we do a epsilon comparison here? number_obj->value = number; return OpBoolean::IS_TRUE; } else if (m_itemtype == SVG_DOM_ITEMTYPE_NUMBER_OPTIONAL_NUMBER_0 || m_itemtype == SVG_DOM_ITEMTYPE_NUMBER_OPTIONAL_NUMBER_1 || m_itemtype == SVG_DOM_ITEMTYPE_INTEGER_OPTIONAL_INTEGER_0 || m_itemtype == SVG_DOM_ITEMTYPE_INTEGER_OPTIONAL_INTEGER_1) { OP_ASSERT (m_base->Type() == SVGOBJECT_VECTOR); SVGVector *vector = static_cast<SVGVector *>(m_base); OP_ASSERT (vector->VectorType() == SVGOBJECT_NUMBER); int idx = 0; if (m_itemtype == SVG_DOM_ITEMTYPE_NUMBER_OPTIONAL_NUMBER_1 || m_itemtype == SVG_DOM_ITEMTYPE_INTEGER_OPTIONAL_INTEGER_1) { idx = 1; } if (idx == 0 && vector->GetCount() > 0) { static_cast<SVGNumberObject *>(vector->Get(0))->value = number; } else if (idx == 1 && vector->GetCount() > 1) { static_cast<SVGNumberObject *>(vector->Get(1))->value = number; } else { // We just add it. In the case we are adding the second // parameter, add two so that the first parameter gets the // same value as the second (that we are trying to set). if (idx == 1 && vector->GetCount() == 0) { if (OpStatus::IsMemoryError(vector->Append(OP_NEW(SVGNumberObject, (number)))) || OpStatus::IsMemoryError(vector->Append(OP_NEW(SVGNumberObject, (number))))) { return OpStatus::ERR_NO_MEMORY; } } else { RETURN_IF_MEMORY_ERROR(vector->Append(OP_NEW(SVGNumberObject, (number)))); } } } return OpBoolean::IS_FALSE; } /* virtual */ BOOL SVGDOMAnimatedValueImpl::IsSetByString() { return m_itemtype == SVG_DOM_ITEMTYPE_STRING; } /* virtual */ OP_BOOLEAN SVGDOMAnimatedValueImpl::SetString(const uni_char *str, LogicalDocument* logdoc) { if (m_itemtype == SVG_DOM_ITEMTYPE_STRING) { if (m_base->Type() == SVGOBJECT_STRING) { unsigned str_length = uni_strlen(str); SVGString *str_obj = static_cast<SVGString *>(m_base); RETURN_FALSE_IF(str_length == str_obj->GetLength() && str_obj->GetString() && uni_strcmp(str_obj->GetString(), str) == 0); RETURN_IF_ERROR(str_obj->SetString(str, str_length)); return OpBoolean::IS_TRUE; } else if (m_base->Type() == SVGOBJECT_URL) { unsigned str_length = uni_strlen(str); SVGURL *url_obj = static_cast<SVGURL *>(m_base); RETURN_FALSE_IF(str_length == url_obj->GetAttrStringLength() && uni_strcmp(url_obj->GetAttrString(), str) == 0); RETURN_IF_ERROR(static_cast<SVGURL *>(m_base)->SetURL(str, URL())); return OpBoolean::IS_TRUE; } else if (m_base->Type() == SVGOBJECT_CLASSOBJECT) { if (logdoc) { SVGClassObject *class_obj = static_cast<SVGClassObject *>(m_base); ClassAttribute* class_attr = logdoc->CreateClassAttribute(str, uni_strlen(str)); if (class_attr) { class_obj->SetClassAttribute(class_attr); return OpBoolean::IS_TRUE; } else return OpStatus::ERR_NO_MEMORY; } } } return OpBoolean::IS_FALSE; } /* static */ OP_BOOLEAN SVGDOMAnimatedValueImpl::LowGetValue(SVGDOMPrimitiveValue &value, SVGDOMItemType type, SVGDOMItemType subtype, SVGObject *source) { if (!source) { return OpBoolean::IS_FALSE; } switch(type) { #ifdef SVG_FULL_11 case SVG_DOM_ITEMTYPE_ANGLE: { OP_ASSERT(source->Type() == SVGOBJECT_ANGLE); value.type = SVGDOMPrimitiveValue::VALUE_ITEM; value.value.item = OP_NEW(SVGDOMAngleImpl, (static_cast<SVGAngle*>(source))); } break; #endif // SVG_FULL_11 case SVG_DOM_ITEMTYPE_RECT: { OP_ASSERT(source->Type() == SVGOBJECT_RECT); value = OP_NEW(SVGDOMRectImpl, (static_cast<SVGRectObject*>(source))); value.type = SVGDOMPrimitiveValue::VALUE_ITEM; } break; case SVG_DOM_ITEMTYPE_PRESERVE_ASPECT_RATIO: { OP_ASSERT(source->Type() == SVGOBJECT_ASPECT_RATIO); value = OP_NEW(SVGDOMPreserveAspectRatioImpl, (static_cast<SVGAspectRatio*>(source))); value.type = SVGDOMPrimitiveValue::VALUE_ITEM; } break; case SVG_DOM_ITEMTYPE_LENGTH: { OP_ASSERT(source->Type() == SVGOBJECT_LENGTH); value = OP_NEW(SVGDOMLengthImpl, (static_cast<SVGLengthObject*>(source))); value.type = SVGDOMPrimitiveValue::VALUE_ITEM; } break; case SVG_DOM_ITEMTYPE_NUMBER: { if (source->Type() == SVGOBJECT_NUMBER) { value.value.number = static_cast<SVGNumberObject*>(source)->value.GetFloatValue(); value.type = SVGDOMPrimitiveValue::VALUE_NUMBER; } else if (source->Type() == SVGOBJECT_LENGTH) { value.value.item = OP_NEW(SVGDOMLengthImpl, (static_cast<SVGLengthObject*>(source))); value.type = SVGDOMPrimitiveValue::VALUE_ITEM; } } break; case SVG_DOM_ITEMTYPE_NUMBER_OPTIONAL_NUMBER_0: case SVG_DOM_ITEMTYPE_NUMBER_OPTIONAL_NUMBER_1: case SVG_DOM_ITEMTYPE_INTEGER_OPTIONAL_INTEGER_0: case SVG_DOM_ITEMTYPE_INTEGER_OPTIONAL_INTEGER_1: { int idx = 0; if (type == SVG_DOM_ITEMTYPE_NUMBER_OPTIONAL_NUMBER_1 || type == SVG_DOM_ITEMTYPE_INTEGER_OPTIONAL_INTEGER_1) { idx = 1; } OP_ASSERT (source->Type() == SVGOBJECT_VECTOR); SVGVector *vector = static_cast<SVGVector*>(source); SVGObject *obj = NULL; if (idx == 1 && vector->GetCount() > 1) obj = vector->Get(1); else if (vector->GetCount() > 0) obj = vector->Get(0); if (obj) value.value.number = static_cast<SVGNumberObject*>(obj)->value.GetFloatValue(); else value.value.number = 0.0; // Default value ?? value.type = SVGDOMPrimitiveValue::VALUE_NUMBER; } break; case SVG_DOM_ITEMTYPE_ENUM: { OP_ASSERT(source->Type() == SVGOBJECT_ENUM); value.value.number = static_cast<SVGEnum*>(source)->EnumValue(); value.type = SVGDOMPrimitiveValue::VALUE_NUMBER; } break; case SVG_DOM_ITEMTYPE_BOOLEAN: { OP_ASSERT(source->Type() == SVGOBJECT_ENUM); value.value.boolean = !!static_cast<SVGEnum*>(source)->EnumValue(); value.type = SVGDOMPrimitiveValue::VALUE_BOOLEAN; } break; case SVG_DOM_ITEMTYPE_STRING: { value.type = SVGDOMPrimitiveValue::VALUE_STRING; if (source->Type() == SVGOBJECT_STRING) value.value.str = static_cast<SVGString *>(source)->GetString(); else if (source->Type() == SVGOBJECT_URL) value.value.str = static_cast<SVGURL *>(source)->GetAttrString(); else if (source->Type() == SVGOBJECT_CLASSOBJECT) { const ClassAttribute* class_attr = static_cast<SVGClassObject *>(source)->GetClassAttribute(); value.value.str = class_attr ? class_attr->GetAttributeString() : NULL; } else { OP_ASSERT(!"Unhandled object type"); value.type = SVGDOMPrimitiveValue::VALUE_NONE; } } break; case SVG_DOM_ITEMTYPE_LIST: { OP_ASSERT(source->Type() == SVGOBJECT_VECTOR); value.value.item = OP_NEW(SVGDOMListImpl, (subtype, static_cast<SVGVector*>(source))); value.type = SVGDOMPrimitiveValue::VALUE_ITEM; } break; default: { OP_ASSERT(!"Not reached"); return OpBoolean::IS_FALSE; } } if (value.type == SVGDOMPrimitiveValue::VALUE_ITEM && !value.value.item) return OpStatus::ERR_NO_MEMORY; return OpBoolean::IS_TRUE; } SVGDOMAnimatedValueTransformListImpl::SVGDOMAnimatedValueTransformListImpl( SVGVector* base_vector, SVGTransform* anim_transform, BOOL additive) : m_base(base_vector), m_anim(anim_transform), m_additive(additive) { SVGObject::IncRef(m_base); SVGObject::IncRef(m_anim); } /* virtual */ SVGDOMAnimatedValueTransformListImpl::~SVGDOMAnimatedValueTransformListImpl() { SVGObject::DecRef(m_base); SVGObject::DecRef(m_anim); } /* virtual */ OP_BOOLEAN SVGDOMAnimatedValueTransformListImpl::GetPrimitiveValue(SVGDOMPrimitiveValue &value, Field field) { if (field == FIELD_ANIM) { SVGDOMAnimatedTransformListImpl *list_value; RETURN_IF_ERROR(SVGDOMAnimatedTransformListImpl::Make(list_value, m_additive ? m_base : NULL, m_anim)); value.value.item = list_value; } else { value.value.item = OP_NEW(SVGDOMListImpl, (SVG_DOM_ITEMTYPE_TRANSFORM, m_base)); if (!value.value.item) return OpStatus::ERR_NO_MEMORY; } value.type = SVGDOMPrimitiveValue::VALUE_ITEM; return value.value.item ? OpStatus::OK : OpStatus::ERR_NO_MEMORY; } /* virtual */ const char * SVGDOMAnimatedValueTransformListImpl::GetDOMName() { return "SVGAnimatedTransformList"; } #endif // SVG_SUPPORT && SVG_DOM && SVG_FULL_11
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Luca Venturi ** ** This class is the implementation of a context manager dedicated to Multimedia content (video tag) */ #ifndef CACHE_CTX_MAN_MULTIMEDIA_H #define CACHE_CTX_MAN_MULTIMEDIA_H #include "modules/cache/cache_ctxman_disk.h" // For now, Multimedia support requires a disk #ifdef DISK_CACHE_SUPPORT // Context manager dedicated to Multimedia content (video tag) class Context_Manager_Multimedia: public Context_Manager_Disk { #ifdef SELFTEST public: #else private: #endif Context_Manager_Multimedia(URL_CONTEXT_ID a_id, OpFileFolder a_vlink_loc, OpFileFolder a_cache_loc): Context_Manager_Disk(a_id, a_vlink_loc, a_cache_loc) { } public: /** Create a proper Multimedia Context Manager chain and add it to the URL Manager @param a_id Context id, usually retrieved using urlManager->GetNewContextID() @param a_vlink_loc Visited Link file @param a_cache_loc Folder that will contain the cache @param a_cache_size_pref Preference used to get the size in KB; <0 means default size (5% of the main cache, set by PrefsCollectionNetwork::DiskCacheSize) */ static OP_STATUS CreateManager(URL_CONTEXT_ID a_id, OpFileFolder a_vlink_loc, OpFileFolder a_cache_loc, BOOL share_cookies_with_main_context = FALSE, int a_cache_size_pref=-1); }; #endif // DISK_CACHE_SUPPORT #endif // CACHE_CTX_MAN_MULTIMEDIA_H
#include <bits/stdc++.h> using namespace std; #define endl '\n' typedef pair<int,int> pii; typedef long double ld; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; const int maxn=10000005; const int INF=0x3f3f3f3f; const double pi=acos(-1.0); const double eps=1e-9; template<class T>inline void read(T&x){ int c; for(c=getchar();c<32&&~c;c=getchar()); for(x=0;c>32;x=x*10+c-'0',c=getchar()); } char s[maxn]; int cas=1; int main () { // freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); while(~scanf("%s",s)){ int sz=strlen(s); int ans1=0; int ans2=0; for(int i=0;i<sz;i++){ ans1=(ans1*10+s[i]-'0')%73; ans2=(ans2*10+s[i]-'0')%137; } printf("Case #%d: ",cas); cas++; if(ans1%73==0&&ans2%137==0){ printf("YES\n"); } else printf("NO\n"); } return 0; }
// Copyright 2011 Yandex #include <limits> #include <vector> #include "ltr/data/utility/data_set_statistics.h" using std::fill; using std::max; using std::min; using std::numeric_limits; namespace ltr { namespace utility { template <typename TElement> void getFeaturesMinMaxValues(const DataSet<TElement>& dataset, vector<double>* min_features_values, vector<double>* max_features_values) { min_features_values->resize(dataset.feature_count()); max_features_values->resize(dataset.feature_count()); fill(min_features_values->begin(), min_features_values->end(), numeric_limits<double>::max()); fill(max_features_values->begin(), max_features_values->end(), numeric_limits<double>::min()); for (int element_index = 0; element_index < (int)dataset.size(); ++element_index) { PerObjectAccessor<const TElement> per_object_accessor(&dataset[element_index]); for (int object_index = 0; object_index < (int)per_object_accessor.object_count(); ++object_index) { for (int feature_index = 0; feature_index < (int)dataset.feature_count(); ++feature_index) { min_features_values->at(feature_index) = min( min_features_values->at(feature_index), per_object_accessor.object(object_index)[feature_index]); max_features_values->at(feature_index) = max( max_features_values->at(feature_index), per_object_accessor.object(object_index)[feature_index]); } } } } template void getFeaturesMinMaxValues<Object>(const DataSet<Object>& data_set, vector<double>* min_features_values, vector<double>* max_features_values); template void getFeaturesMinMaxValues<ObjectPair>(const DataSet<ObjectPair>& data_set, vector<double>* min_features_values, vector<double>* max_features_values); template void getFeaturesMinMaxValues<ObjectList>(const DataSet<ObjectList>& data_set, vector<double>* min_features_values, vector<double>* max_features_values); } }
/*! \file */ //Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #ifndef STRING_HPP_ #define STRING_HPP_ #include <iface/link.h> #include <cstring> #include <cstdlib> #include <cstdio> #include "Data.hpp" #include "StringUtil.hpp" namespace var { /*! \brief String class * \details This is an embedded friendly string class. It is similar * to the C++ string type but is built on Var::Data and * cstring functions. The naming convetion follows that of std::string * rather than the typical Stratify Library naming convention. * * * \code * #include <stfy/Var.hpp> * * String s1; * String s2; * s1 = "This is my string"; * s1 << " " << s1.capacity() << "\n"; * printf("%s", s1.c_str()); * //Strings can be compared * s2 = "This is another string"; * if( s1 == s2 ){ * printf("The strings are the same!\n"); * } else { * printf("The strings are different\n"); * } * \endcode * * The above code outputs: * \code * This is my string 64 * The strings are different * \endcode * */ class String : public Data { public: /*! \details Declare an empty string */ String(); /*! \details Declare an emtpy string of a specified capacity */ String(size_t capacity); /*! \details Declare a string and initialize to \a s */ String(const char * s); /*! \details Declare a string and initialize to \a s */ String(const char * s, size_t len); operator const char * () const { return c_str(); } enum { npos = (size_t)-1 }; String(char * mem, size_t cap, bool readonly = false); inline int set_capacity(size_t s){ return Data::set_min_capacity(s+1); } /*! \details Assign a c-string */ String& operator=(const char * a){ assign(a); return *this; } String& operator<<(const char * a){ append(a); return *this; } String& operator<<(char c){ append(c); return *this; } /*! \details Compare to a c-string */ bool operator==(const char * cmp) const { return (strcmp(this->c_str(), cmp) == 0); } /*! \details Compare to a c-string */ bool operator!=(const char * cmp) const { return (strcmp(this->c_str(), cmp) != 0); } /*! \details Convert to an integer */ int atoi() const { return ::atoi(c_str()); } /*! \details Convert to a float */ float atoff() const; /*! \details Get a sub string of the string */ String substr(size_t pos = 0, size_t len = npos) const; /*! \details Insert \a s (zero terminated) into string at \a pos */ String& insert(size_t pos, const char * s); /*! \details Erase a portion of the string starting with the character at \a pos */ String& erase(size_t pos, size_t len = -1); /*! \details Return character at \a pos */ char at(size_t pos) const; size_t capacity() const; const char * c_str() const { return cdata_const(); } /*! \details Return the length of the string */ size_t size() const { return strlen(c_str()); } /*! \details Return the length of the string */ inline size_t length() const { return size(); } inline size_t len() const { return size(); } /*! \details Test if string is empty */ bool empty() const { return size() == 0; } /*! \details Assign a substring of \a a to string */ void assign(const char * a, size_t subpos, size_t sublen){ assign(a + subpos, sublen); } /*! \details Assign a maximum of \a n characters of \a a to string */ void assign(const char * a, size_t n); /*! \details Assign \a a (zero terminated) to string */ void assign(const char * a); /*! \details Append \a a (zero terminated) to string */ void append(const char * a); /*! \details Append \a c to string */ void append(char c); /*! \details Append \a c to string */ inline void push_back(char c) { append(c); } /*! \details Copy the \a nth element (separated by \a sep) of the string to to \a dest */ bool get_delimited_data(String & dest, int n, char sep = ',', char term = '\n'); /*! \details Return the number of elements in the String */ int calc_delimited_data_size(char sep = ',', char term = '\n'); /*! \details Copy a portion of the string to \a s */ size_t copy(char * s, size_t len, size_t pos = 0) const; inline size_t copy(String & s, size_t n, size_t pos = 0) const { return copy(s.cdata(), n, pos); } /*! \details Convert to upper case */ void toupper(); /*! \details Convert to lower case */ void tolower(); /*! \details Find a var::String within the object * * @param str The String to find * @param pos The position to start searching * @return The position of the string or var::String::npos if the String was not found */ size_t find(const String & str, size_t pos = 0) const; /*! \details Find a c string within the object */ size_t find(const char * str, size_t pos = 0) const; /*! \details Find a character within the object */ size_t find(const char c, size_t pos = 0) const; size_t find(const char * s, size_t pos, size_t n) const; size_t rfind(const String & str, size_t pos = 0) const; size_t rfind(const char * str, size_t pos = 0) const; size_t rfind(const char c, size_t pos = 0) const; size_t rfind(const char * s, size_t pos, size_t n) const; int compare(const String & str) const; int compare(size_t pos, size_t len, const String & str) const; int compare(size_t pos, size_t len, const String & str, size_t subpos, size_t sublen) const; int compare(const char * s) const; int compare(size_t pos, size_t len, const char * s); int compare(size_t pos, size_t len, const char * s, size_t n) const; private: }; /*! \details Static String Template Class * \details This template is used for declaring fixed length strings. */ template <unsigned int arraysize> class StringStatic : public String { public: StringStatic() : String(s, arraysize+1, false){ clear(); } StringStatic(const char * str) : String(s, arraysize+1, false){ assign(str); } StringStatic(const String & str) : String(s, arraysize+1, false){ assign(str); } private: char s[arraysize+1]; }; /*! \details String for file names */ class StringName : public String { public: StringName() : String(NAME_MAX){} }; /*! \details String for path names */ class StringPath : public String { public: StringPath() : String(LINK_PATH_MAX){} void strip_suffix(); const char * file_name() const; const char * filename() const { return file_name(); } }; }; #endif /* STRING_HPP_ */
#include "NameLabel.h" using namespace RsaToolbox; /*! * \class RsaToolbox::NameLabel * \brief The %NameLabel class handles identifiers that include * both a name and a label. * * %NameLabel is primarily a data type for resources that * have both a name and a label as identifiers. For example, * a Vector Network Analyzer may have two calibration kits * registered that have the same name, but have different * serial numbers that can be applied as labels. A * NameLabel is then used to handle the identifier without having to * perform the extra business logic to handle two identifier strings. * * The example below iterates through each calibration kit * registered with the \c Vna object (\c vna) looking for cal kits that * contain a Male-to-Male thru standard: * \code ... QVector<NameLabel> calKits = vna.GetCalibrationKits(); foreach(NameLabel kit, calKits) { // Do something } \endcode * * <B>Note:</B> NameLabels are case-sensitive. Although the name and the label * may not independently be unique, the combination of the two must * be unique to a particular resource. * *\sa RsaToolbox::Vna */ /*! * \brief the default (empty) constructor * * Constructs an empty NameLabel (name = "", label = ""). */ NameLabel::NameLabel() { } NameLabel::NameLabel(const NameLabel &other) { _name = other.name(); _label = other.label(); } /*! * \brief the fully defined instance constructor * * Constructs a \c NameLabel with \a name and \a label. \a label is an empty string * by default. * * \param name * \param label */ NameLabel::NameLabel(QString name, QString label) { this->_name = name; this->_label = label; } /*! * \brief provides a user-friendly \c QString representation of \c NameLabel * \return the formatted string: "Name (Label)" */ QString NameLabel::displayText() const { QString display; if (_label.isEmpty()) display = _name; else display = _name + " (" + _label + ")"; return(display); } bool NameLabel::isEmpty() const { return _name.isEmpty() && _label.isEmpty(); } /*! * \brief Returns name of NameLabel object * \return name */ QString NameLabel::name() const { return(_name); } /*! * \brief returns label of \c NameLabel object * \return label */ QString NameLabel::label() const { return(_label); } /*! * \brief Sets name of \c NameLabel object * \param name New name of \c NameLabel */ void NameLabel::setName(QString name) { _name = name; } /*! * \brief Sets label of \c NameLabel object * \param label New label of \c NameLabel */ void NameLabel::setLabel(QString label) { _label = label; } void NameLabel::clear() { _name.clear(); _label.clear(); } /*! * \brief Returns the result of \c NameLabel::displayText() */ NameLabel::operator QString() const { return(displayText()); } /*! * \brief Sets properties of \c this to that of \c other * \param other \c NameLabel object with desired properties */ void NameLabel::operator=(const NameLabel &other) { _name = other._name; _label = other._label; } /*! * \brief Separates \c name_labels into two lists: \c names and \c labels * \param[in] name_labels * \param[out] names The list of names from \c name_labels * \param[out] labels The list of labels from \c name_labels * \sa NameLabel::names(), NameLabel::labels() */ void NameLabel::separate(QVector<NameLabel> name_labels, QStringList &names, QStringList &labels) { names.clear(); labels.clear(); foreach (NameLabel nl, name_labels) { names.append(nl._name); labels.append(nl._label); } } /*! * \brief Creates a list of names from \c name_labels * \param name_labels * \return The names of \c name_labels */ QStringList NameLabel::names(QVector<NameLabel> name_labels) { QStringList names; foreach (NameLabel nl, name_labels) { names.append(nl._name); } return(names); } /*! * \brief NameLabel::labels * \param name_labels * \return The labels of \c name_labels */ QStringList NameLabel::labels(QVector<NameLabel> name_labels) { QStringList labels; foreach (NameLabel nl, name_labels) { labels.append(nl._label); } return(labels); } /*! * \brief Generates user-friendly text for \c name_labels * \param name_labels * \return User-friendly text of \c name_labels */ QStringList NameLabel::displayText(QVector<NameLabel> name_labels) { QStringList displays; foreach (NameLabel nl, name_labels) { displays.append(nl.displayText()); } return(displays); } /*! * \brief Parses \c NameLabels out of \c list * * \c list must follow a particular format. * For example, for \c separator = ",": * \c list = (\c name1, \c label1, \c name2, \c label2, ...) * * \param list Alternating list of names and labels * \param separator Delimiter used in \c list * \return %NameLabels in \c list */ QVector<NameLabel> NameLabel::parse(QString list, QString separator) { QStringList splitList = list.split(separator, QString::KeepEmptyParts); int splitListSize = splitList.size(); QVector<NameLabel> nameLabels; for (int i = 0; i < splitListSize - 1; i += 2) { nameLabels.append(NameLabel(splitList[i], splitList[i+1])); } return(nameLabels); } /*! * \brief Parses \c NameLabels out of \c list while ignoring * instances of \c ignore * * \c list must follow a particular format. * For example, for \c separator = ",": * \c list = (\c name1, \c label1, \c name2, \c label2, ...) * * A typical Rohde \& Schwarz VNA response, for example:<br> * <tt>result = "name1,'label1',name2,'label2',..."</tt><br> * can be parsed with the following snippet: * \code NameLabel::parse(result, ",", "\'"); \endcode * * \param list Alternating list of names and labels * \param separator Delimiter used in \c list * \param ignore String instances to ignore in \c list * \return %NameLabels in \c list */ QVector<NameLabel> NameLabel::parse(QString list, QString separator, QString ignore) { QString newList = list; return(parse(newList.remove(ignore), separator)); } /*! * \relates RsaToolbox::NameLabel * \brief Compares \c right and \c left for equality * * Returns true if \c right and \c left have the same * name and label. * * \note Comparision is case-sensitive. * * \param right \c NameLabel on right-hand side of == operator * \param left \c NameLabel on left-hand side of == operator * \return Case-sensitive equality of objects * \sa RsaToolbox::operator!=(const NameLabel &right, const NameLabel &left) */ bool RsaToolbox::operator==(const NameLabel &right, const NameLabel &left) { if (right.name() != left.name()) return false; if (right.label() != left.label()) return false; return true; } /*! * \relates RsaToolbox::NameLabel * \brief Compares \c right and \c left for inequality * * Returns true if \c right and \c left do not have the same * name and label. * * \note Comparision is case-sensitive. * * \param right \c NameLabel on right-hand side of != operator * \param left \c NameLabel on left-hand side of != operator * \return Case-sensitive inequality of objects * \sa RsaToolbox::operator==(const NameLabel &right, const NameLabel &left) */ bool RsaToolbox::operator!=(const NameLabel &right, const NameLabel &left) { return !(right == left); } QDataStream& RsaToolbox::operator<<(QDataStream &stream, const NameLabel &nameLabel) { stream << nameLabel.name(); stream << nameLabel.label(); return stream; } QDataStream& RsaToolbox::operator>>(QDataStream &stream, NameLabel &nameLabel) { QString string; stream >> string; nameLabel.setName(string); stream >> string; nameLabel.setLabel(string); return stream; }
# include<iostream> # include<cmath> using namespace std; int convert(int n,int sB) { int pwr = 0,sum = 0,d = 0; while(n > 0) { d = n % 10; n = n / 10; sum = sum + d * pow(sB,pwr); pwr = pwr + 1; } return sum; } int getBase(int num) { int base = 0; while(num > 0) { base = max(base,num % 10); num /= 10; } return base+1; } int main(void) { int b = 0, n = 0; cin >> b >> n; int base = getBase(n); cout << "Enter a base b : "; cout << "Enter a base-b number : "; if(base <= b) { cout << "The corresponding base-10 number is : " << convert(n,b) << endl; } else { cout << "Error!! " << n << " is not a number of base " << b << "." << endl; } }
#include "stdafx.h" #include "editor.h" #include "frame.h" const TCHAR *EditorHost::ClassName = TEXT("EditorHost"); EditorHost::EditorHost(MainFrame& frame) : frame_(frame) { } bool EditorHost::Create(LPCSTR lpWindowName, int x, int y, int width, int height, Window *parent) { DWORD dwExStyles = WS_EX_WINDOWEDGE; DWORD dwStyles = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS; if (!Window::Create(ClassName, lpWindowName, dwExStyles, dwStyles, x, y, width, height, NULL, &frame_)) { return false; } return true; } void EditorHost::OnPaint(HDC hdc, const RECT& rcPaint) { if (!HasPanel()) { SetBkColor(hdc, RGB(0, 0, 0)); ExtTextOut(hdc, 0, 0, ETO_OPAQUE, &rcPaint, "", 0, NULL); } Window::OnPaint(hdc, rcPaint); } bool EditorHost::OnEraseBackground(HDC hdc) { return true; } bool EditorHost::Register() { return Window::Register(ClassName, (HBRUSH) COLOR_WINDOW + 1, NULL, CS_DBLCLKS); } bool Editor::SaveFile() { return true; } void Editor::OnCommand(DWORD id, DWORD code) { switch (id) { case ID_EDIT_UNDO: Undo(); break ; case ID_EDIT_REDO: Redo(); break ; } } bool Editor::Undo() { return UndoBuffer::Undo(); } bool Editor::Redo() { return UndoBuffer::Redo(); } bool Editor::Do(Ref<UndoAction> action) { if (!UndoBuffer::Do(action)) { return false; } return true; } ScrollSurface::ScrollSurface(MainFrame& frame, CartFile& cart) : Editor(frame, cart) { x_ = 0, y_ = 0; scroll_x_ = 0, scroll_y_ = 0; surface_width_ = 0, surface_height_ = 0; } ScrollSurface::~ScrollSurface() { } ScrollSurface::Redraw::Redraw(ScrollSurface& surface) : surface_(surface), RedrawRegion(surface) { } ScrollSurface::Redraw::~Redraw() { } void ScrollSurface::Redraw::Invalidate(const RECT *zone) { if (!zone) { RedrawRegion::Invalidate(zone); return ; } RECT rcInvalid = *zone; OffsetRect(&rcInvalid, -surface_.X(), -surface_.Y()); RedrawRegion::Invalidate(&rcInvalid); } void ScrollSurface::OnCreate() { RECT rcClient; GetClientRect(hwnd_, &rcClient); viewRc_.left = 0, viewRc_.top = 0, viewRc_.right = rcClient.right; viewRc_.bottom = rcClient.bottom; ShowScrollBar(hwnd_, SB_BOTH, TRUE); } void ScrollSurface::OnSize(WORD width, WORD height) { HDC hdc = GetDC(); BitmapSurface::Resize(width, height, 128); ReleaseDC(hwnd_, hdc); UpdateScroll(0, 0); RECT rcClient; GetClientRect(hwnd_, &rcClient); viewRc_.right = x_ + rcClient.right, viewRc_.bottom = y_ + rcClient.bottom; } LRESULT ScrollSurface::OnMessage(UINT msg, WPARAM wParam, LPARAM lParam) { int nScrollCode, n = 0; RECT rect; switch (msg) { case WM_HSCROLL: nScrollCode = LOWORD(wParam); Window::GetRect(rect); switch (nScrollCode) { case SB_THUMBTRACK: UpdateScroll(HIWORD(wParam) - x_, 0); break ; case SB_LINERIGHT: UpdateScroll(5, 0); break ; case SB_LINELEFT: UpdateScroll(-5, 0); break ; case SB_RIGHT: UpdateScroll(width_ - x_, 0); break ; case SB_LEFT: UpdateScroll(-x_, 0); break ; case SB_PAGERIGHT: UpdateScroll(rect.right, 0); break ; case SB_PAGELEFT: UpdateScroll(-rect.right, 0); break ; } return 0; case WM_VSCROLL: nScrollCode = LOWORD(wParam); Window::GetRect(rect); switch (nScrollCode) { case SB_THUMBPOSITION: case SB_THUMBTRACK: UpdateScroll(0, HIWORD(wParam) - y_); break ; case SB_LINEDOWN: // down - right UpdateScroll(0, 5); break ; case SB_LINEUP: // up - left UpdateScroll(0, -5); break ; case SB_PAGEDOWN: UpdateScroll(0, rect.bottom); break ; case SB_PAGEUP: UpdateScroll(0, -rect.bottom); break ; case SB_TOP: UpdateScroll(0, -y_); break ; case SB_BOTTOM: UpdateScroll(0, height_ - y_); break ; } return 0; } return Window::OnMessage(msg, wParam, lParam); } void ScrollSurface::OnPaint(HDC hdc, const RECT& rcPaint) { const RECT& pos = GetScrollRect(); COLORREF color; color = SetBkColor(hdc_, RGB(0, 0, 0)); ExtTextOut(hdc_, 0, 0, ETO_OPAQUE, &rcPaint, "", 0, NULL); SetBkColor(hdc_, color); OnPaintArea(pos, hdc); Draw(hdc, rcPaint.left, rcPaint.top, rcPaint.right - rcPaint.left, rcPaint.bottom - rcPaint.top, rcPaint.left, rcPaint.top ); } bool ScrollSurface::OnDestroy() { DWORD dwStyle = GetWindowLong(hwnd_, GWL_STYLE); //SetWindowLong(hwnd_, GWL_STYLE, dwStyle & ~(WS_VSCROLL | WS_HSCROLL)); ShowScrollBar(hwnd_, SB_BOTH, FALSE); return true; } void ScrollSurface::OnMouseDown(DWORD key, int x, int y) { x += x_, y += y_; Window::OnMouseDown(key, x, y); } void ScrollSurface::OnMouseUp(DWORD key, int x, int y) { x += x_, y += y_; Window::OnMouseUp(key, x, y); } void ScrollSurface::OnMouseMove(int x, int y) { x += x_, y += y_; Window::OnMouseMove(x, y); } bool ScrollSurface::OnQueryCursor(DWORD dwHitTest, const POINT& pt) { POINT pt2 = pt; pt2.x += x_, pt2.y += y_; return Window::OnQueryCursor(dwHitTest, pt2); } void ScrollSurface::GetCursorPos(POINT& pt) { DWORD cursor_pos = GetMessagePos(); pt.x = GET_X_LPARAM(cursor_pos), pt.y = GET_Y_LPARAM(cursor_pos); ScreenToClient(hwnd_, &pt); pt.x += viewRc_.left, pt.y += viewRc_.top; } void ScrollSurface::ClientToScroll(RECT& rc) { OffsetRect(&rc, viewRc_.left, viewRc_.top); } void ScrollSurface::ScrollToClient(RECT& rc) { OffsetRect(&rc, -viewRc_.left, -viewRc_.top); } void ScrollSurface::SetDimensions(int width, int height) { surface_width_ = width, surface_height_ = height; UpdateScroll(0, 0); } const RECT& ScrollSurface::GetScrollRect() const { return scroll_rect_; } void ScrollSurface::GetRect(RECT& rect) const { rect = scroll_rect_; } void ScrollSurface::GetView(RECT& rcView) { rcView = viewRc_; } bool ScrollSurface::Resize(int width, int height) { if (!BitmapSurface::Resize(width, height, 10)) { return false; } SetDimensions(width, height); return true; } void ScrollSurface::UpdateScroll(int x, int y) { Scroll(x, y); } void ScrollSurface::Scroll(int& x, int& y) { static bool locked = false; if (locked) { return ; } locked = true; scroll_x_ += x, scroll_y_ += y; SCROLLINFO si; RECT rect; Window::GetRect(rect); si.cbSize = sizeof(si); si.fMask = SIF_POS; GetScrollInfo(hwnd_, SB_VERT, &si); si.fMask = NULL; if (surface_height_ < y_ + scroll_y_ + rect.bottom) { scroll_y_ = surface_height_ - y_ - rect.bottom + 1; if (scroll_y_ + y_ < 0) { // stick to the top scroll_y_ = -y_; } } if (y_ + scroll_y_ < 0) { scroll_y_ = -y_; } if (scroll_y_) { y_ += scroll_y_; si.fMask |= SIF_POS; si.nPos = y_; } si.fMask |= SIF_RANGE | SIF_PAGE; si.nMax = surface_height_; si.nMin = 0; si.nPage = rect.bottom; SetScrollInfo(hwnd_, SB_VERT, &si, TRUE); si.fMask = SIF_POS; GetScrollInfo(hwnd_, SB_HORZ, &si); si.fMask = NULL; if (surface_width_ < x_ + scroll_x_ + rect.right) { scroll_x_ = surface_width_ - x_ - rect.right + 1; if (scroll_x_ + x_ < 0) { // stick to the right scroll_x_ = -x_; } } if (x_ + scroll_x_ < 0) { scroll_x_ = -x_; } if (scroll_x_) { x_ += scroll_x_; si.fMask |= SIF_POS; si.nPos = x_; } si.fMask |= SIF_RANGE | SIF_PAGE; si.nMax = surface_width_; si.nMin = 0; si.nPage = rect.right; SetScrollInfo(hwnd_, SB_HORZ, &si, TRUE); x = 0, y = 0; if (scroll_x_ || scroll_y_) { ScrollDC(hdc_, -scroll_x_, -scroll_y_, NULL, NULL, NULL, NULL); ScrollWindow(hwnd_, -scroll_x_, -scroll_y_, NULL, NULL); x = scroll_x_, y = scroll_y_; viewRc_.left += scroll_x_, viewRc_.top += scroll_y_, viewRc_.right += scroll_x_, viewRc_.bottom += scroll_y_; scroll_x_ = 0, scroll_y_ = 0; } SetRect(&scroll_rect_, -x_, -y_, x_ + width_, y_ + height_ ); locked = false; } const DWORD EditTool::kTimerId = 0x2001; EditTool::EditTool(ScrollSurface& target) : target_(target) { selection_active_ = false; drag_active_ = false; } EditTool::~EditTool() { StopSelection(); StopDrag(); } void EditTool::StartSelection() { if (!IsValid()) { return ; } StartDrag(); selectionRc_.left = dragPt_.x, selectionRc_.top = dragPt_.y; selectionRc_.right = dragPt_.x; selectionRc_.bottom = dragPt_.y; selection_active_ = true; UpdateSelection(); } void EditTool::StopSelection() { if (!selection_active_) { return ; } ScrollSurface::Redraw redraw(target_); RECT selection = selectionRc_; if (selectionRc_.right < selectionRc_.left) { selection.left = selectionRc_.right; selection.right = selectionRc_.left; } if (selectionRc_.bottom < selectionRc_.top) { selection.top = selectionRc_.bottom; selection.bottom = selectionRc_.top; } OnSelectionRelease(selection, redraw); InvalidateFocusRect(redraw); selection_active_ = false; } bool EditTool::IsSelectionActive() const { return selection_active_; } void EditTool::OnSelectionMove(const RECT& selection) { } void EditTool::OnSelectionRelease(const RECT& selection, RedrawRegion& redraw) { } void EditTool::StartDrag() { if (!IsValid()) { return ; } StopSelection(); StopDrag(); target_.GetCursorPos(dragPt_); drag_active_ = true; target_.CaptureMouse(); ix_ = dragPt_.x; iy_ = dragPt_.y; SetTimer(hwnd_, kTimerId, 200, NULL); } void EditTool::StopDrag() { if (!drag_active_) { return ; } if (!IsValid()) { return ; } target_.ReleaseMouse(); target_.GetCursorPos(dragPt_); if (!selection_active_) { ix_ = dragPt_.x - ix_; iy_ = dragPt_.y - iy_; OnDragRelease(dragPt_, ix_, iy_); } else { // Selection marquee UpdateSelection(); StopSelection(); } KillTimer(hwnd_, kTimerId); drag_active_ = false; } bool EditTool::IsDragging() const { return drag_active_ && !selection_active_; } void EditTool::OnDragMove(int x, int y) { } void EditTool::OnDragRelease(const POINT& pt, int ix, int iy) { } void EditTool::OnPaintArea(const RECT& pos, HDC hdc) { DrawFocusRect(pos, hdc); } void EditTool::OnMouseMove(int x, int y) { if (drag_active_) { Drag(x, y); } } void EditTool::OnMouseUp(DWORD key, int x, int y) { StopDrag(); } void EditTool::OnTimer(DWORD id) { if (id == kTimerId) { int x = 0, y = 0; RECT rcView; target_.GetView(rcView); int mult = 0; if (dragPt_.x < rcView.left + 50) { x = (int) -(rcView.left - dragPt_.x + 50) * 0.8; } else if (dragPt_.x > rcView.right - 50) { x = (int) (dragPt_.x + 50 - rcView.right) * 0.8; } if (dragPt_.y < rcView.top + 50) { y = (int) -(rcView.top - dragPt_.y + 50) * 0.8; } else if (dragPt_.y > rcView.bottom - 50) { y = (dragPt_.y + 50 - rcView.bottom) * 0.8; } if (x || y) { if (selection_active_) { ScrollSurface::Redraw redraw(target_); InvalidateFocusRect(redraw); } target_.Scroll(x, y); dragPt_.x += x, dragPt_.y += y; if (selection_active_) { UpdateSelection(); } else { OnDragMove(x, y); } } } } void EditTool::Drag(int x, int y) { POINT new_pos; target_.GetCursorPos(new_pos); if (!selection_active_) { int dx = dragPt_.x - x, dy = dragPt_.y - y; dragPt_ = new_pos; OnDragMove(-dx, -dy); } else { dragPt_ = new_pos; UpdateSelection(); } } void EditTool::UpdateSelection() { if (!selection_active_) { return ; } int x = dragPt_.x, y = dragPt_.y; ScrollSurface::Redraw redraw(target_); InvalidateFocusRect(redraw); selectionRc_.right = x; selectionRc_.bottom = y; InvalidateFocusRect(redraw); } void EditTool::DrawFocusRect(const RECT& pos, HDC hdc) { if (!selection_active_) { return ; } HPEN marqueePen = CreatePen(PS_DOT, 1, RGB(0, 0, 0)); HPEN oldPen = (HPEN) SelectObject(hdc, (HGDIOBJ) marqueePen); HBRUSH oldBrush = (HBRUSH) SelectObject(hdc, (HGDIOBJ) GetStockObject(NULL_BRUSH)); RECT zone = selectionRc_; if (selectionRc_.right < selectionRc_.left) { zone.left = selectionRc_.right; zone.right = selectionRc_.left; } if (selectionRc_.bottom < selectionRc_.top) { zone.top = selectionRc_.bottom; zone.bottom = selectionRc_.top; } target_.ScrollToClient(zone); Rectangle(hdc, zone.left, zone.top, zone.right, zone.bottom); SelectObject(hdc, (HGDIOBJ) oldBrush); SelectObject(hdc, (HGDIOBJ) oldPen); DeleteObject((HGDIOBJ) marqueePen); ExcludeClipRect(hdc, zone.left, zone.top, zone.right, zone.top + 1); ExcludeClipRect(hdc, zone.left, zone.top, zone.left + 1, zone.bottom); ExcludeClipRect(hdc, zone.right, zone.top, zone.right - 1, zone.bottom); ExcludeClipRect(hdc, zone.left, zone.bottom - 1, zone.right, zone.bottom); } void EditTool::InvalidateFocusRect(RedrawRegion& redraw) { if (!selection_active_) { return ; } RECT zone = selectionRc_; target_.ScrollToClient(zone); redraw.Invalidate(&zone); zone.right = selectionRc_.left + 1; redraw.Invalidate(&zone); // left zone.right = selectionRc_.right; zone.bottom = zone.top + 1; redraw.Invalidate(&zone); // top zone.bottom = selectionRc_.bottom; zone.left = zone.right - 1; redraw.Invalidate(&zone); // right zone.left = selectionRc_.left; zone.top = zone.bottom - 1; redraw.Invalidate(&zone); // bottom } SelectionMarquee::SelectionMarquee(Window& target) : target_(target) { grid_ = 0; active_ = false; } void SelectionMarquee::Activate(int x, int y) { target_.CaptureMouse(); active_ = true; if (grid_) { x -= x % grid_; y -= y % grid_; } zone_.left = x; zone_.top = y; MouseMove(x, y); } void SelectionMarquee::Desactivate(int x, int y) { target_.ReleaseMouse(); active_ = false; MouseMove(x, y); target_.Invalidate(NULL); target_.Update(); } void SelectionMarquee::Draw(HDC hdc, const RECT& pos) { if (!active_) { return ; } HPEN marqueePen = CreatePen(PS_DOT, 1, RGB(0, 0, 0)); HPEN oldPen = (HPEN) SelectObject(hdc, (HGDIOBJ) marqueePen); HBRUSH oldBrush = (HBRUSH) SelectObject(hdc, (HGDIOBJ) GetStockObject(BLACK_BRUSH)); RECT zone = zone_; OffsetRect(&zone, pos.left, pos.top); MoveToEx(hdc, zone.left, zone.bottom, NULL); LineTo(hdc, zone.left, zone.top); LineTo(hdc, zone.right, zone.top); LineTo(hdc, zone.right, zone.bottom); LineTo(hdc, zone.left, zone.bottom); SelectObject(hdc, (HGDIOBJ) oldPen); SelectObject(hdc, (HGDIOBJ) oldBrush); DeleteObject((HGDIOBJ) marqueePen); ExcludeClipRect(hdc, zone.left, zone.top, zone.right, zone.top + 1); ExcludeClipRect(hdc, zone.left, zone.top, zone.left + 1, zone.bottom); ExcludeClipRect(hdc, zone.right, zone.top, zone.right + 1, zone.bottom); ExcludeClipRect(hdc, zone.left, zone.bottom, zone.right, zone.bottom + 1); } void SelectionMarquee::MouseMove(int x, int y) { if (!active_) { return ; } if (x < 1) { x = 1; } if (y < 1) { y = 1; } if (grid_) { x -= x % grid_; y -= y % grid_; if (x >= zone_.left) { x += grid_; } if (y >= zone_.top) { y += grid_; } } zone_.right = x; zone_.bottom = y; target_.Invalidate(NULL); target_.Update(); } bool SelectionMarquee::IsActive() const { return active_; } RECT& SelectionMarquee::GetSelectionZone() { selection_zone_ = zone_; if (zone_.right < zone_.left) { selection_zone_.left = zone_.right; selection_zone_.right = zone_.left; } if (zone_.bottom < zone_.top) { selection_zone_.top = zone_.bottom; selection_zone_.bottom = zone_.top; } return selection_zone_; } DragDrop::DragDrop(Window& host) : host_(host) { active_ = false; } void DragDrop::Activate(int x, int y) { active_ = true; last_move_.x = x, last_move_.y = y; host_.CaptureMouse(); } void DragDrop::Desactivate(int x, int y) { if (!active_) { return ; } host_.ReleaseMouse(); active_ = false; } void DragDrop::MouseMove(int& x, int& y) { if (!active_) { return ; } int x1, y1; x1 = last_move_.x - x, y1 = last_move_.y - y; last_move_.x = x, last_move_.y = y; x = -x1, y = -y1; } bool DragDrop::IsActive() const { return active_; }
#pragma once namespace qp { class CQuestionReview; }
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; void printArray(int arr[], int n); bool isSwap(int arr[], int prev, int next) { return (arr[prev] > arr[next]) ? true:false; } int almostBinarySearch(int arr[], int start, int end, int X) { if (end > start) { int middle = start + (end - start) /2; if (arr[middle] == X) return middle; if ( (middle + 1 <= end) && (arr[middle+1] == X) ) return (middle+1); if ( (middle - 1 >= start) && (arr[middle- 1] == X)) return (middle -1); if ( (arr[middle] < X) && ((middle - 1 > start) && (arr[middle-1] < X)) && ((middle + 1 < end) && (arr[middle+1] < X)) ) { return almostBinarySearch(arr,middle+1,end,X); } else if ( (arr[middle] > X ) && ((middle - 1 > start) && (arr[middle-1] > X)) && ((middle + 1 < end) && (arr[middle+1] > X)) ) { return almostBinarySearch(arr,start,middle-1,X); } } return -1; } void printArray(int arr[], int n) { for (int i = 0; i <= n; i++) { cout << arr[i] << " "; } cout << "\n"; } void main() { int arr[] = {10,3,40,20,50,80,70}; //int arr[] = {1,4,1,2,7,5,2,0}; int size = sizeof(arr)/ sizeof(int); int n = size - 1; int start = 0; int end = n; int X = 20; int position = almostBinarySearch(arr,start,end,X); cout << position << "\n"; }
#ifndef FAHRZEUG_H_ #define FAHRZEUG_H_ #include <string> #include <iostream> extern double dGlobaleZeit; class Fahrzeug{ protected: double p_dGesamtStrecke; double p_dGesamtZeit; double p_dGeschwindigkeit; double p_dMaxGeschwindigkeit; public: Fahrzeug(); Fahrzeug(std::string); Fahrzeug(std::string, double); Fahrzeug(Fahrzeug &); virtual ~Fahrzeug(); void vSetsName(std::string); double dGetvGesamtStrecke() const; double dGetvGesamtZeit() const; double dGetvZeit() const; double dGetvGeschwindigkeit() const; void vSetdGeschwindigkeit(double); void vSetdMaxGeschwindigkeit(double); std::string sGetsName() const; double dGetvMaxGeschwindigkeit() const; virtual bool operator < (const Fahrzeug &); virtual void operator = (Fahrzeug &); virtual std::ostream& ostreamAusgabe(std::ostream&) const; virtual void vAusgabe() const; virtual void vAbfertigung(); virtual double dTanken(); virtual double dTanken(double); virtual double dGeschwindigkeit(); private: void vInitialisierung(); }; // std::ostream& operator << (std::ostream &, const Fahrzeug &); #endif
#include "elog/formatters/colored_formatter.hpp" #include "elog/severity.hpp" #include <iomanip> #include <sstream> namespace elog { ColoredFormatter::ColoredFormatter() { } ColoredFormatter::~ColoredFormatter() { } std::string ColoredFormatter::format(const Record& record) { std::stringstream line; line << "[\033[37m" << std::put_time(&record.time(), "%F %T") << "\033[0m]" << severityColor(record.severity()) << severityToString(record.severity()) << "\033[0m " << record.message(); return line.str(); } }
// // Created by abel_ on 04-07-2022. // #include <bits/stdc++.h> using namespace std; class Heap{ public: int arr[100]; int size; Heap(){ size = 0; arr[0] = -1; } void insert(int value) { size = size + 1; int index = size; arr[index] = value; while(index > 1){ int parent = index/2; if(arr[parent] < arr[index]){ swap(arr[parent],arr[index]); index = parent; }else return; } } void printHeap(){ for(int i = 1; i <= size; i++){ cout << arr[i] << " "; } cout << endl; } void deleteFromHeap() { if (size == 0) cout << "Nothing to delete"; arr[1] = arr[size]; size--; int index = 1; while (index < size) { int leftIndex = 2 * index; int rightIndex = 2 * index + 1; if (leftIndex < size && arr[leftIndex] > arr[index]) { swap(arr[leftIndex], arr[index]); index = leftIndex; } else if (rightIndex < size && arr[rightIndex] > arr[index]) { swap(arr[rightIndex], arr[index]); index = rightIndex; } else return; } } }; int main(){ Heap h; h.insert(50); h.insert(55); h.insert(53); h.insert(52); h.insert(54); h.printHeap(); h.deleteFromHeap(); h.printHeap(); return 0; }
#pragma once #include <SoundAssetId.h> #include <MusicAssetId.h> namespace irrklang { class ISoundEngine; } namespace breakout { class AudioManager { public: static AudioManager& Get(); void PlaySound(ESoundAssetId soundId); void PlayMusic(EMusicAssetId musicId); private: AudioManager(); ~AudioManager(); AudioManager(AudioManager&) = delete; AudioManager(AudioManager&&) = delete; void operator=(AudioManager&) = delete; void operator=(AudioManager&&) = delete; irrklang::ISoundEngine* m_soundEngine = nullptr; }; }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #include <iostream> #include "IController.h" #include "../events/PointerInsideIndex.h" #include "../events/types/IEvent.h" namespace Controller { IController::HandlingType IController::onMouseMotionDispatch (Event::MouseMotionEvent *e, Model::IModel *m, View::IView *v, Event::PointerInsideIndex *d) { HandlingType ret = IGNORED; if (!d->isPointerInside (m)) { d->add (m); if (eventMask & Event::MOUSE_OVER_EVENT) { ret = onMouseOver (e, m, v); } } if (eventMask & Event::MOUSE_MOTION_EVENT) { ret = std::max (onMouseMotion (e, m, v), ret); } return ret; } } /* namespace Controller */
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifdef ANDROID #ifndef BAJKA_ANDROIDINPUTDISPATCHER_H_ #define BAJKA_ANDROIDINPUTDISPATCHER_H_ #include "AbstractEventDispatcher.h" namespace Event { class AndroidInputDispatcher : public AbstractEventDispatcher { public: virtual ~AndroidInputDispatcher () {} bool pollAndDispatch (Model::IModel *m, Event::EventIndex const &modeliIndex, Event::PointerInsideIndex *pointerInsideIndex); bool dispatch (Model::IModel *m, EventIndex const &modeliIndex, PointerInsideIndex *pointerInsideIndex, void *platformDependentData); void reset (); protected: virtual IEvent *translate (void *platformDependentEvent); }; } /* namespace Event */ #endif /* ANDROIDINPUTDISPATCHER_H_ */ #endif
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * LispC Expression base class * A Scheme expression is composed of LISTS and ATOMS * LIST is vector * ATOM is a Number or a Symbol (string) * LAMDA is a function bound to an environment * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #pragma once #include <iostream> #include <vector> #include "Number.h" #include "Symbol.h" namespace lispc { // NB: Expression is a union of expression functionality. It avoids reflection... // But there is likely a more elegant type to achieve this. class Expression { public: virtual ~Expression(); virtual bool is_atom() const; virtual bool is_number() const; virtual bool is_symbol() const; virtual bool is_func() const; virtual bool is_lambda() const; virtual std::vector<Expression*> get_exps() const; virtual Number get_number() const; virtual Symbol get_symbol() const; virtual std::string get_type() const = 0; }; typedef Expression* (*Func)(std::vector<Expression*>&); std::ostream& operator<<(std::ostream& stream, const Expression& expression); }
//Accepted. Time-0.180s #include <bits/stdc++.h> using namespace std; #define ll long long #define vll vector<ll> int main() { ll n,q,t,a; t=0; while(cin>>n>>q) { if(n==0 && q==0) break; t++; cout<<"CASE# "<<t<<":\n"; vll v; vll:: iterator it; for(ll i=0;i<n;i++) { cin>>a; v.push_back(a); } sort(v.begin(),v.end()); for(int i=0;i<q;i++) { cin>>a; it=lower_bound(v.begin(),v.end(),a); if(it==v.end() || v[it-v.begin()]!=a) { cout<<a<<" not found\n"; } else { cout<<a<<" found at "<<it-v.begin()+1<<"\n"; } } } }
#include<bits/stdc++.h> using namespace std; using ll=long long; #define maxn 5005 int n,s,e; int nextl[maxn]; ll ans; ll a[maxn],b[maxn],c[maxn],d[maxn],x[maxn]; ll dis[maxn][maxn]; int main(){ ios::sync_with_stdio(false); cin.tie(0); cin>>n>>s>>e; for(int i=1;i<=n;i++) cin>>x[i]; for(int i=1;i<=n;i++) cin>>a[i]; for(int i=1;i<=n;i++) cin>>b[i]; for(int i=1;i<=n;i++) cin>>c[i]; for(int i=1;i<=n;i++) cin>>d[i]; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(i!=j){ if(i>j) dis[i][j]=abs(x[i]-x[j])+c[i]+b[j]; else dis[i][j]=abs(x[i]-x[j])+d[i]+a[j]; } } } ans+=dis[s][e]; nextl[s]=e; for(int i=1;i<=n;i++){ if(i==s||i==e) continue; ll sum=LLONG_MAX; int ind=s; for(int j=s;j!=e;j=nextl[j]){ int t=nextl[j]; if(dis[j][i]+dis[i][t]-dis[j][t]<sum){ sum=dis[j][i]+dis[i][t]-dis[j][t]; ind=j; } } int t=nextl[ind]; nextl[ind]=i; nextl[i]=t; ans+=sum; } cout<<ans<<"\n"; return EXIT_SUCCESS; }
#include "MySolution1.h" #include <fstream> #include <cstdio> #include <vector> #include <ctime> #include <limits> #include <iomanip> using namespace std; int main(){ CreateTest(1); int NumberOfQueries; vector<int> arr; int operation; int lenght; long long MyRSQValue, StupidRSQValue; int index, newValue, begin, end; clock_t startTime; vector<int>MyResults; vector<int>NormResults; ifstream test; test.open("test.txt"); test >> NumberOfQueries; cout << NumberOfQueries << endl; test >> lenght; int numb; for (int i = 0; i < lenght; i++){ test >> numb; arr.push_back(numb); //cout << arr[i] << ' '; } node *tr = new node(arr[0]); for (int i = 1; i < lenght; i++){ node* newNode = new node(arr[i]); insert(tr, i, newNode); } //cout << NumberOfQueries << endl; startTime = clock(); for (int i = 0; i < NumberOfQueries; i++){ test >> operation; switch (operation){ case 0:{ test >> index; test >> newValue; tr->Set(index, newValue); break; } case 1:{ test >> begin; test >> end; NextPermutation(tr, begin, end); break; } case 2:{ test >> begin; test >> end; //MyRSQValue = tr->RSQ(begin, end); MyRSQValue = RSQByStepa(tr, begin, end); MyResults.push_back(MyRSQValue); break; } } //cout << operation; } cout << std::setprecision(15) << "My time: " << double(clock() - startTime) / (double)CLOCKS_PER_SEC << " seconds." << endl; test.seekg(0); test >> lenght >> NumberOfQueries; for (int i = 0; i < lenght; i++) test >> numb; startTime = clock(); for (int i = 0; i < NumberOfQueries; i++){ test >> operation; switch (operation){ case 0:{ test >> index; test >> newValue; arr[index] = newValue; break; } case 1:{ test >> begin; test >> end; StupidNextPermutation(arr, begin, end); break; } case 2:{ test >> begin; test >> end; StupidRSQValue = StupidRSQ(arr, begin, end); NormResults.push_back(StupidRSQValue); break; } } } cout << std::setprecision(15) << "Normal time: " << double(clock() - startTime) / (double)CLOCKS_PER_SEC << " seconds." << endl; for (int i = 0; i < NormResults.size(); i++){ if (MyResults[i] != NormResults[i]) cout << "ERROR"; } cout << "ok"; test.close(); getchar(); }
#include "Zoom.h" #include "..\ApplicationManager.h" #include "..\GUI\Input.h" #include "..\GUI\Output.h" #include <sstream> using namespace std; //constructor: set the ApplicationManager pointer inside this action Zoom::Zoom(ApplicationManager *pAppManager,char c):Action(pAppManager) { type=c; } void Zoom::ReadActionParameters() { Input *pIn = pManager->GetInput(); Output *pOut = pManager->GetOutput(); if(type=='+') pOut->PrintMessage("Please Click in the area that you want to zoom in"); else if(type=='-') pOut->PrintMessage("Please Click in the area that you want to zoom out"); pIn->GetPointClicked(Position); pOut->ClearStatusBar(); } void Zoom::Execute() { Input *pIn = pManager->GetInput(); Output *pOut = pManager->GetOutput(); ReadActionParameters(); Point P1,P2,P3,P4; bool b1=false,b2=false; if(type=='+') { if((Position.x>UI.MnItWdth&&Position.x<UI.width)&&(Position.y>UI.TlBrWdth&&Position.y<(UI.height)/2)) { P1.x=UI.MnItWdth; P1.y=UI.TlBrWdth; P2.x=UI.width-P1.x; P2.y=(UI.height/2)-P1.y; b1=true; } else if((Position.x>UI.MnItWdth&&Position.x<UI.width)&&((Position.y>(UI.height)/2)&&Position.y<(UI.height-UI.StBrWdth))) { P1.x=UI.MnItWdth; P1.y=(UI.height)/2; P2.x=UI.width-P1.x; P2.y=(UI.height/2)-UI.StBrWdth; b1=true; } } else if(type=='-') { if((Position.x>UI.MnItWdth&&Position.x<UI.width)&&((Position.y>(UI.TlBrWdth)&&Position.y<(UI.height-UI.StBrWdth)))) { P1.x=UI.MnItWdth; P1.y=UI.TlBrWdth; P2.x=UI.width-P1.x; P2.y=UI.height-UI.TlBrWdth-UI.StBrWdth; b2=true; } } if(type=='+' && b1) { P3.x=UI.MnItWdth,P3.y=UI.TlBrWdth,P4.x=UI.width-UI.MnItWdth,P4.y=UI.height-UI.StBrWdth-UI.TlBrWdth; pOut->DrawImage(&(pIn->StoreImage(i,P1,P2)),P3,P4); } else if(type=='-' && b2) { P3.x=UI.MnItWdth,P3.y=UI.TlBrWdth,P4.x=UI.width-UI.MnItWdth-100,P4.y=UI.height-UI.StBrWdth-UI.TlBrWdth-100; pOut->DrawImage(&(pIn->StoreImage(i,P1,P2)),P3,P4); } } //void Zoom::setG(int n) //{ // G=n; //}
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2009 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #ifdef HAS_SET_HTTP_DATA #include "modules/upload/upload.h" #include "modules/olddebug/tstdump.h" Upload_Base::Upload_Base() { headers_written = FALSE; only_body = FALSE; } Upload_Base::~Upload_Base() { if(InList()) Out(); } void Upload_Base::InitL(const char **header_names) { Headers.InitL(header_names); } OpFileLength Upload_Base::CalculateLength() { return CalculateHeaderLength(); } unsigned char *Upload_Base::OutputContent(unsigned char *target, uint32 &remaining_len, BOOL &done) { return OutputHeaders(target, remaining_len, done); } uint32 Upload_Base::GetOutputData(unsigned char *target, uint32 buffer_len, BOOL &done) { uint32 remaining_len = buffer_len; OutputContent(target, remaining_len, done); return buffer_len - remaining_len; } uint32 Upload_Base::CalculateHeaderLength() { if(only_body) return 0; return Headers.CalculateLength() + STRINGLENGTH("\r\n"); } unsigned char *Upload_Base::OutputHeaders(unsigned char *target, uint32 &remaining_len, BOOL &done) { done = TRUE; if(only_body) headers_written = TRUE; if(!headers_written) { done = FALSE; uint32 header_len = Headers.CalculateLength() + STRINGLENGTH("\r\n"); if(header_len <= remaining_len) { target = (unsigned char *) Headers.OutputHeaders((char *) target); *(target++)= '\r'; *(target++)= '\n'; remaining_len -= header_len; done = TRUE; headers_written = TRUE; } } return target; } uint32 Upload_Base::PrepareL(Boundary_List &boundaries, Upload_Transfer_Mode transfer_restriction) { headers_written = only_body; return CalculateHeaderLength()+1; } uint32 Upload_Base::PrepareUploadL(Upload_Transfer_Mode transfer_restrictions) { Boundary_List boundaries; ANCHOR(Boundary_List, boundaries); OP_STATUS op_err; OP_MEMORY_VAR BOOL finished =FALSE; OP_MEMORY_VAR uint32 len=0; if(transfer_restrictions != UPLOAD_BINARY_NO_CONVERSION) AccessHeaders().AddParameterL("MIME-Version","1.0"); while(!finished) { boundaries.InitL(); TRAP(op_err, len = PrepareL(boundaries, transfer_restrictions)); if(op_err != Upload_Error_Status::ERR_FOUND_BOUNDARY_PREFIX) { if(Upload_Error_Status::IsError(op_err)) LEAVE(op_err); finished = TRUE; } // else make a new try } boundaries.GenerateL(); return len; } void Upload_Base::ResetL() { headers_written = only_body; } void Upload_Base::Release() { // Nothing to release; } Upload_Base *Upload_Base::FirstChild() { return NULL; } void Upload_Base::ClearAndSetContentTypeL(const OpStringC8 &a_content_type) { AccessHeaders().ClearAndAddParameterL("Content-Type", a_content_type); content_type.SetL(a_content_type); int len = content_type.FindFirstOf(" ;,\t"); if(len != KNotFound) content_type.Delete(len); // remove parameters from the content type } void Upload_Base::SetContentTypeL(const OpStringC8 &a_content_type) { Header_Item *item = AccessHeaders().FindHeader("Content-Type", TRUE); if(item && item->HasParameters()) return; // already set. content_type.SetL(a_content_type); if(content_type.HasContent()) AccessHeaders().AddParameterL("Content-Type", content_type); int len = content_type.FindFirstOf(" ;,\t"); if(len != KNotFound) content_type.Delete(len); // remove parameters from the content type } void Upload_Base::SetCharsetL(const OpStringC8 &encoded_charset) { charset.SetL(encoded_charset); if(encoded_charset.HasContent()) { AccessHeaders().AddParameterL("Content-Type", "charset", encoded_charset); } } void Upload_Base::SetContentDispositionL(const OpStringC8 &disposition) { if(disposition.HasContent()) AccessHeaders().AddParameterL("Content-Disposition", disposition); } void Upload_Base::SetContentDispositionParameterL(const OpStringC8 &value) { if(value.HasContent()) AccessHeaders().AddParameterL("Content-Disposition", value); } void Upload_Base::SetContentDispositionParameterL(const OpStringC8 &name, const OpStringC8 &value, BOOL quote_value) { if(name.HasContent()) AccessHeaders().AddParameterL("Content-Disposition", name, value, quote_value); } uint32 Upload_Base::ExtractHeadersL(const unsigned char *src, uint32 len, BOOL use_all, Header_Protection_Policy policy, const KeywordIndex *excluded_headers, int excluded_list_len) { return AccessHeaders().ExtractHeadersL(src, len, use_all, policy, excluded_headers, excluded_list_len); } uint32 Upload_Base::FileCount() { return 0; } uint32 Upload_Base::UploadedFileCount() { return 0; } #ifdef UPLOAD_NEED_MULTIPART_FLAG BOOL Upload_Base::IsMultiPart() { return FALSE; } #endif #endif // HTTP_data
#include "camera.h" #include "window.h" std::weak_ptr<entity> camera::_current; std::weak_ptr<entity> camera::get_current() { return _current; } void camera::set_current(std::weak_ptr<entity> cam) { _current = cam; } camera::camera(): _fov(glm::radians(90.0f)), _near(0.1f), _far(1000.0f) { set_class_name("camera"); } camera::~camera() { } glm::mat4 camera::get_perspective_view() { float aspect = window::get_current().lock()->get_aspect(); glm::mat4 p = glm::perspective(_fov,aspect,_near,_far); glm::mat4 v = glm::lookAt(get_transform().position,get_transform().position + get_transform().get_forward(),get_transform().get_up()); return p*v; } json camera::serialize() { json serialized; serialized["class_name"] = get_class_name(); serialized["transform"] = get_transform().serialize(); serialized["fov"] = _fov; serialized["near"] = _near; serialized["far"] = _far; return serialized; } void camera::deserialize(json& serialized) { get_transform().deserialize(serialized["transform"]); _fov = serialized["fov"]; _near = serialized["near"]; _far = serialized["far"]; }
#include "fenetrejeu.h" #include "skull.h" #include "boss.h" #include "collisionmanager.h" #include <qdir.h> #include <string> #include <iostream> #include <sstream> using std::string; using namespace sf; using std::stringstream; FenetreJeu::FenetreJeu(VideoMode vid, string title, Character character, string file, string fileDoor) :RenderWindow(vid, title), character(character) { //room[4] = Room(1); for(int j=0; j<4; j++) room.push_back(new Room()); room.push_back(new Room(1)); if(this->myImage.LoadFromFile(file)){ myImage.CreateMaskFromColor(sf::Color::Magenta); // Masque de couleur mySprite.SetImage(myImage); } if(this->doorimg.LoadFromFile(fileDoor)) { doorimg.CreateMaskFromColor(sf::Color::White); //Masque de couleur doorSprite.SetImage(doorimg); doorSprite.SetSubRect(sf::IntRect(0, 86, 86, 244)); doorSprite.SetPosition(sf::Vector2f(734, 250)); } if (nextLevel.LoadFromFile("sprites/level.png")){ nextLevel.CreateMaskFromColor(sf::Color::Cyan); spriteNextLevel.SetImage(nextLevel); } if(this->imgDead.LoadFromFile("sprites/dead.png")) { this->imgDead.CreateMaskFromColor(sf::Color::Green); this->spriteDead.SetImage(this->imgDead); } if (gameOver.LoadFromFile("sprites/gameover.png")) { this->gameOver.CreateMaskFromColor(sf::Color::Green); this->gameoverSprite.SetImage(gameOver); } i=0; nRoom = 0; } void FenetreJeu::traitementEvent(Event event) { switch (event.Type) { case Event::Closed : // Croix de fermeture du programme this->Close(); break; case Event::KeyPressed : // Appui sur une touche { switch(event.Key.Code) { case Key::Escape : // Touche echap while(true) { if (event.Key.Code == Key::Escape) break; } break; default : break; } } break; default : break; } } void FenetreJeu::traitementInput() { if (character.IsDead()) { this->Clear(); this->Draw(this->spriteDead); this->Display(); sf::SoundBuffer Buffer; if (!Buffer.LoadFromFile("music/death.wav")) { // Erreur... } sf::Sound Sound; Sound.SetBuffer(Buffer); Sound.SetLoop(false); Sound.Play(); sf::Sleep(6.0f); std::cout << "Die" << std::endl; Sound.Stop(); this->Close(); } CollisionManager collision(character, (*room[nRoom])); const Input & input = this->GetInput(); character.setCycle(character.getCycle()+1); if(input.IsKeyDown(Key::Z)) { character.Move(Character::Top); } if(input.IsKeyDown(Key::S)) { character.Move(Character::Bottom); } if(input.IsKeyDown(Key::Q)) { character.Move(Character::Left); } if(input.IsKeyDown(Key::D)) { character.Move(Character::Right); } if(input.IsKeyDown(Key::Up)) { character.GetWeapon()->SetPosition(character.GetSprite().GetPosition()); character.Shoot(Character::Top); character.GetWeapon()->setShoot(true); } if(input.IsKeyDown(Key::Down)) { character.GetWeapon()->SetPosition(character.GetSprite().GetPosition()); character.Shoot(Character::Bottom); character.GetWeapon()->setShoot(true); } if(input.IsKeyDown(Key::Left)) { character.GetWeapon()->SetPosition(character.GetSprite().GetPosition()); character.Shoot(Character::Left); character.GetWeapon()->setShoot(true); } if(input.IsKeyDown(Key::Right)) { character.GetWeapon()->SetPosition(character.GetSprite().GetPosition()); character.Shoot(Character::Right); character.GetWeapon()->setShoot(true); } // On efface l'écran this->Clear(); character.GetWeapon()->Move(); // Et on l'affiche this->Draw(this->mySprite); this->Draw(this->doorSprite); this->Draw(character.GetSprite()); for (int j=0;j<(*room[nRoom]).getListEnemy().size();j++) { if (room[nRoom]->getListEnemy()[j]->IsDead()) (*room[nRoom]->getListEnemy()[j]).die(i); else { //Calcul de la direction que doit prendre l'ennemi pour poursuivre le personnage if (character.GetSprite().GetPosition().x > room[nRoom]->getListEnemy()[j]->getSprite().GetPosition().x) room[nRoom]->getListEnemy()[j]->move(Enemy::Right); else room[nRoom]->getListEnemy()[j]->move(Enemy::Left); if (character.GetSprite().GetPosition().y > room[nRoom]->getListEnemy()[j]->getSprite().GetPosition().y) room[nRoom]->getListEnemy()[j]->move(Enemy::Bottom); else room[nRoom]->getListEnemy()[j]->move(Enemy::Top); } this->Draw((*room[nRoom]->getListEnemy()[j]).getSprite()); } if (character.GetWeapon()->IsShoot()) this->Draw(character.GetWeapon()->GetSprite()); collision.Lock(); collision.CollisionEnemy(); for (int j=0;j<room[nRoom]->getListEnemy().size();j++) { if (collision.CollisionEnemyBullet(j) && clockEnemy.GetElapsedTime() > 0.4 && !room[nRoom]->getListEnemy()[j]->IsDead()) { clockEnemy.Reset(); room[nRoom]->getListEnemy()[j]->loseLife(character.GetWeapon()->GetDmg()); room[nRoom]->getListEnemy()[j]->getSprite().SetColor(sf::Color::Red); character.GetWeapon()->setShoot(false); } if (collision.CollisionEnemyCharacter(j) && clockChar.GetElapsedTime() > 0.4 && !room[nRoom]->getListEnemy()[j]->IsDead()) { clockChar.Reset(); character.loseLife(room[nRoom]->getListEnemy()[j]->getDmg()); character.GetSprite().SetColor(sf::Color::Red); } } stringstream ss; ss << "Level "; switch(nRoom) { case 0: ss << "I"; break; case 1: ss << "II"; break; case 2: ss << "III"; break; case 3: ss << "IV"; break; case 4: ss << "V"; break; } sf::String text(ss.str()); sf::Font MyFont; // Chargement à partir d'un fichier sur le disque if (!MyFont.LoadFromFile("sprites/blood.ttf")) { // Erreur... } text.SetFont(MyFont); text.SetColor(sf::Color::Red); this->Draw(text); stringstream ss2; ss2 << "Life points : "; for (int j=0;j<character.getLife();j++) ss2 << "I"; sf::String life(ss2.str()); life.SetFont(MyFont); life.SetColor(sf::Color::Red); life.SetPosition(sf::Vector2f(560,26)); std::cout << character.getLife() <<" "<<std::endl; this->Draw(life); this->Display(); for (int j=0;j<room[nRoom]->getListEnemy().size();j++) { if (clockEnemy.GetElapsedTime() > 0.4) room[nRoom]->getListEnemy()[j]->getSprite().SetColor(sf::Color::White); } if (clockChar.GetElapsedTime() > 0.4) character.GetSprite().SetColor(sf::Color::White); if (collision.CollisionDoor() && room[nRoom]->isClear()){ sf::Clock time; if (nRoom == 4) { this->Clear(); this->Draw(this->gameoverSprite); this->Display(); time.Reset(); while(time.GetElapsedTime() < 2.5){} this->Close(); } time.Reset(); this->Draw(spriteNextLevel); this->Display(); while(time.GetElapsedTime() < 2.5){} character.GetSprite().SetPosition(sf::Vector2f(600,300)); this->levelCleared(); } i++; } void FenetreJeu::levelCleared() { this->nRoom++; }
#include <iostream> #include <fstream> void printContentsOfFile() { std::string line; std::ifstream myFile("data.txt"); if (myFile.is_open()) { while (getline(myFile, line)) { std::cout << line << std::endl; } myFile.close(); } else { std::cout << "Unable to open file!" << std::endl; } } bool isName(const std::string& inputedData) { return (inputedData[0] >= 'A' && inputedData[0] <= 'Z'); } void getNameOrDate(const std::string& inputedData) { std::fstream myFile("data.txt"); std::string name; std::string date; bool isContains = false; if (isName(inputedData)) { while (myFile >> name >> date) { if (inputedData == name) { isContains = true; std::cout << "Meeting date: " << date << std::endl; } } } else { while (myFile >> name >> date) { if (inputedData == date) { isContains = true; std::cout << "Meeting with: " << name << std::endl; } } } if (!isContains) { std::cout << "File does not contain that data!" << std::endl; } } int main() { std::cout << "=====The contents of the file=====\n" << std::endl; printContentsOfFile(); std::string inputedData; do { std::cout << "\nPress Enter for exit Or Enter the name or the date: "; getline(std::cin, inputedData); if ("\0" == inputedData) { return 0; } getNameOrDate(inputedData); } while("\0" != inputedData); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. ** It may not be distributed under any circumstances. */ #ifndef DOM_EXTENSIONS_TABAPICACHEDOBJECT_H #define DOM_EXTENSIONS_TABAPICACHEDOBJECT_H #ifdef DOM_EXTENSIONS_TAB_API_SUPPORT #include "modules/dom/src/extensions/domextensionsupport.h" #include "modules/windowcommander/OpExtensionUIListener.h" #include "modules/dom/src/domobj.h" class DOM_TabApiCachedObject : public DOM_Object { public: DOM_TabApiCachedObject(DOM_ExtensionSupport* extension_support, OpTabAPIListener::TabAPIItemId id) : m_extension_support(extension_support) , m_is_significant(FALSE) , m_id(id) { OP_ASSERT(extension_support); OP_ASSERT(id); } virtual ~DOM_TabApiCachedObject(); BOOL IsSignificant() { return m_is_significant; } virtual ES_PutState PutName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime) { SetIsSignificant(); return DOM_Object::PutName(property_name, property_code, value, origining_runtime); } // This is here only to make it visible in DOM_TabApiCachedObject. virtual ES_PutState PutName(OpAtom property_atom, ES_Value* value, ES_Runtime* origining_runtime) { return DOM_Object::PutName(property_atom, value, origining_runtime); } virtual ES_PutState PutIndex(int property_index, ES_Value* value, ES_Runtime* origining_runtime) { SetIsSignificant(); return DOM_Object::PutIndex(property_index, value, origining_runtime); } OpTabAPIListener::TabAPIItemId GetId() { return m_id; } protected: void SetIsSignificant() { m_is_significant = TRUE; } OpSmartPointerWithDelete<DOM_ExtensionSupport> m_extension_support; private: BOOL m_is_significant; OpTabAPIListener::TabAPIItemId m_id; }; #endif // DOM_EXTENSIONS_TAB_API_SUPPORT #endif // DOM_EXTENSIONS_TABAPICACHEDOBJECT_H
#include "msg_0xfc_encryptionkeyresponse_tw.h" namespace MC { namespace Protocol { namespace Msg { EncryptionKeyResponse::EncryptionKeyResponse() { _pf_packetId = static_cast<int8_t>(0xFC); _pf_initialized = false; } EncryptionKeyResponse::EncryptionKeyResponse(const ByteArray& _sharedSecret, const ByteArray& _verifyToken) : _pf_sharedSecret(_sharedSecret) , _pf_verifyToken(_verifyToken) { _pf_packetId = static_cast<int8_t>(0xFC); _pf_initialized = true; } size_t EncryptionKeyResponse::serialize(Buffer& _dst, size_t _offset) { _pm_checkInit(); if(_offset == 0) _dst.clear(); _offset = WriteInt8(_dst, _offset, _pf_packetId); _offset = WriteInt16(_dst, _offset, _pf_sharedSecret.size()); _offset = WriteByteArray(_dst, _offset, _pf_verifyToken); _offset = WriteInt16(_dst, _offset, _pf_sharedSecret.size()); _offset = WriteByteArray(_dst, _offset, _pf_verifyToken); return _offset; } size_t EncryptionKeyResponse::deserialize(const Buffer& _src, size_t _offset) { _offset = _pm_checkPacketId(_src, _offset); int16_t sharedSecretLen, verTokLen; _offset = ReadInt16(_src, _offset, sharedSecretLen); _offset = ReadByteArray(_src, _offset, sharedSecretLen, _pf_sharedSecret); _offset = ReadInt16(_src, _offset, verTokLen); _offset = ReadByteArray(_src, _offset, verTokLen, _pf_verifyToken); _pf_initialized = true; return _offset; } const ByteArray& EncryptionKeyResponse::getSharedSecret() const { return _pf_sharedSecret; } const ByteArray& EncryptionKeyResponse::getVerifyToken() const { return _pf_verifyToken; } void EncryptionKeyResponse::setSharedSecret(const ByteArray& _val) { _pf_sharedSecret = _val; } void EncryptionKeyResponse::setVerifyToken(const ByteArray& _val) { _pf_verifyToken = _val; } } // namespace Msg } // namespace Protocol } // namespace MC
/* * File: JsonListModel.h * Author: jay * * Created on March 26, 2014 */ #ifndef JSONLISTMODEL_H #define JSONLISTMODEL_H #include <QAbstractListModel> #include <QStringList> #include <QJsonDocument> class QJsonListModel : public QAbstractListModel { Q_OBJECT Q_PROPERTY( QJsonDocument json READ getJson WRITE setJson NOTIFY jsonChanged ) // <editor-fold defaultstate="collapsed" desc="json Property"> public: QJsonDocument getJson() const; void setJson( const QJsonDocument json ); signals: void jsonChanged( QJsonDocument ); private: QJsonDocument _json; // </editor-fold> public: enum ListRoles { TextRole = Qt::UserRole + 1, SizeRole }; QJsonListModel( QObject *parent = 0 ); bool insertRows( int row, int count, const QModelIndex & parent = QModelIndex() ); int rowCount( const QModelIndex & parent = QModelIndex() ) const; QVariant data( const QModelIndex & index, int role = Qt::DisplayRole ) const; protected: QHash<int, QByteArray> roleNames() const; private: QJsonValue getItemValue( const QModelIndex& idx ) const; }; #endif
#include<bits/stdc++.h> using namespace std; struct TreeNode { int val; TreeNode* left, *right; TreeNode():val(0),left(nullptr),right(nullptr) { } TreeNode(int x): val(x),left(nullptr), right(nullptr) { } TreeNode(int x, TreeNode* left, TreeNode* right): val(x),left(left),right(right) { } }; class Solution { public: int sumNumbers(TreeNode* root) { if(!(root->left&&root->right)) return root->val; vector<int> res; dfs(root, res, 0); int sum = 0; for(int i=0; i<res.size(); i++) { sum+=res[i]; } return sum; } void dfs(TreeNode* root, vector<int>& res, int path) { path = path*10+root->val; if(root->left==nullptr&&root->right==nullptr) { res.push_back(path); return; } if(root->left!=nullptr) dfs(root->left, res, path); // path = path/10; //»ØËÝ if(root->right!=nullptr) dfs(root->right, res, path); } }; int main () { return 0; }
/* https://www.codechef.com/FEB16/problems/CHEFDETE/ */ #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int t; cin >> t; vector<int> vec(t); vector<int> vec_str(t); for(int i=0; i<t; i++) { vec_str[i] = i + 1; } for(int i=0; i<t; i++) { cin >> vec[i]; if(vec[i]!=0) vec_str[vec[i]-1] = 0; } vec_str.erase(remove(vec_str.begin(), vec_str.end(), 0),vec_str.end()); for(int i=0; i<vec_str.size(); i++) cout << vec_str[i] << ' '; cout << endl; return 0; }
#ifdef __cplusplus #define __STDC_LIMIT_MACROS #define __STDC_FORMAT_MACROS #include <minisat/core/Solver.h> #include <minisat/utils/System.h> using namespace Minisat; typedef Solver *solver; typedef vec<Lit> *vect; #else typedef void *solver; typedef void *vect; #endif #ifdef __cplusplus extern "C" { #endif vect minisat_stubs_vec_create(void); void minisat_stubs_vec_destroy(vect v); void minisat_stubs_vec_clear(vect v); void minisat_stubs_vec_push(vect v, int l, int s); solver minisat_stubs_new(); void minisat_stubs_delete(solver solver); int minisat_stubs_new_var(solver solver); int minisat_stubs_add_clause(solver solver, vect clause); int minisat_stubs_simplify(solver solver); int minisat_stubs_solve(solver solver); int minisat_stubs_solve_with_assumptions(solver solver, vect assumptions); int minisat_stubs_value_of(solver solver, int var); int minisat_stubs_n_vars(solver solver); int minisat_stubs_n_clauses(solver solver); double minisat_stubs_mem_used(); double minisat_stubs_cpu_time(); #ifdef __cplusplus } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #include "modules/encodings/decoders/utf8-decoder.h" UTF8toUTF16Converter::UTF8toUTF16Converter() { } int UTF8toUTF16Converter::Convert(const void *src, int len, void *dest, int maxlen, int *read_ext) { if (dest) return this->UTF8Decoder::Convert(src, len, dest, maxlen, read_ext); else return this->UTF8Decoder::Measure(src, len, maxlen, read_ext); } const char *UTF8toUTF16Converter::GetCharacterSet() { return "utf-8"; } void UTF8toUTF16Converter::Reset() { this->InputConverter::Reset(); this->UTF8Decoder::Reset(); }