blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
bdc0fd4eb4135d667d701086c0e663cb45eb14e8
633b695a03e789f6aa644c7bec7280367a9252a8
/opencv_cpp/14/14-01.cpp
dd24ac62482365f42b609f587d8acb1680123e3e
[]
no_license
tnakaicode/PlotGallery
3d831d3245a4a51e87f48bd2053b5ef82cf66b87
5c01e5d6e2425dbd17593cb5ecc973982f491732
refs/heads/master
2023-08-16T22:54:38.416509
2023-08-03T04:23:21
2023-08-03T04:23:21
238,610,688
5
2
null
null
null
null
UTF-8
C++
false
false
2,099
cpp
14-01.cpp
#define _CRT_SECURE_NO_WARNINGS #define _USE_MATH_DEFINES #include <iostream> #include <fstream> #include <cmath> #include <ctime> #include <opencv2/opencv.hpp> int main() { //irisデータの読み込み cv::Ptr<cv::ml::TrainData> raw_data = cv::ml::TrainData::loadFromCSV("iris.data", 0); //特徴量データの切り出し cv::Mat data(150, 4, CV_32FC1); data = raw_data->getSamples(); std::cout << data << std::endl; std::cout << data.rows << " x " << data.cols << std::endl; //ラベルデータの切り出し cv::Mat label(150, 1, CV_32SC1); label = raw_data->getResponses(); std::cout << label << std::endl; std::cout << label.rows << " x " << label.cols << std::endl; //k最近傍識別器の構築 cv::Ptr<cv::ml::KNearest> knn = cv::ml::KNearest::create(); //k最近傍識別器のパラメータの設定 knn->setAlgorithmType(cv::ml::KNearest::Types::BRUTE_FORCE); knn->setDefaultK(3); knn->setEmax(0); knn->setIsClassifier(true); //k最近傍識別器の訓練の実行 knn->train(data, cv::ml::SampleTypes::ROW_SAMPLE, label); //検証データの設定 cv::Mat testSample(1, 4, CV_32FC1); testSample.at<float>(0) = 5.0; testSample.at<float>(1) = 3.6; testSample.at<float>(2) = 1.3; testSample.at<float>(3) = 0.25; //訓練されたk最近傍識別器で検証データのラベル値を予測・表示 int response = (int)knn->predict(testSample); std::cout << "knn::response1---> " << response << std::endl; //訓練されたk最近傍識別器のモデルの保存 knn->save("knn.xml"); //訓練されたk最近傍識別器のモデルの読み込み knn = cv::Algorithm::load<cv::ml::KNearest>("knn.xml"); //検証データの設定 testSample.at<float>(0) = 5.8; testSample.at<float>(1) = 2.6; testSample.at<float>(2) = 4.3; testSample.at<float>(3) = 0.9; //訓練されたk最近傍識別器で検証データのラベル値を予測・表示 response = (int)knn->predict(testSample); std::cout << "knn::response2---> " << response << std::endl; system("PAUSE"); return 0; }
aa73fc0b6620b77ba257b9a4e295f41ad0028f2b
d2e0de5f02add44650620b72e177013f7ad4e95c
/system/uapp/guest/linux.cpp
f649712c6439de46cade883f27efa7f4175991aa
[ "BSD-3-Clause", "MIT" ]
permissive
skyformat99/zircon
9af23311038f7ce3165c145e450fbca38377add3
c251582802f9d3291939ea4697d4682a233ab685
refs/heads/master
2021-05-07T03:10:32.844348
2017-11-14T01:44:54
2017-11-14T02:09:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,220
cpp
linux.cpp
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <fcntl.h> #include <inttypes.h> #include <limits.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include <hypervisor/guest.h> #include "linux.h" // clang-format off #define SECTOR_SIZE 512u #define ALIGN(x, alignment) (((x) + (alignment - 1)) & ~(alignment - 1)) #define ZP8(p, off) (*((uint8_t*)((p) + (off)))) #define ZP16(p, off) (*((uint16_t*)((p) + (off)))) #define ZP32(p, off) (*((uint32_t*)((p) + (off)))) #define ZP64(p, off) (*((uint64_t*)((p) + (off)))) // See https://www.kernel.org/doc/Documentation/x86/boot.txt // and https://www.kernel.org/doc/Documentation/x86/zero-page.txt // for an explanation of the zero page, setup header and boot params. // Screen info offsets #define ZP_SI_8_VIDEO_MODE 0x0006 // Original video mode #define ZP_SI_8_VIDEO_COLS 0x0007 // Original video cols #define ZP_SI_8_VIDEO_LINES 0x000e // Original video lines // Setup header offsets #define ZP_SH_8_E820_COUNT 0x01e8 // Number of entries in e820 map #define ZP_SH_8_SETUP_SECTS 0x01f1 // Size of real mode kernel in sectors #define ZP_SH_8_LOADER_TYPE 0x0210 // Type of bootloader #define ZP_SH_8_LOAD_FLAGS 0x0211 // Boot protocol flags #define ZP_SH_8_RELOCATABLE 0x0234 // Is the kernel relocatable? #define ZP_SH_16_BOOTFLAG 0x01fe // Bootflag, should match BOOT_FLAG_MAGIC #define ZP_SH_16_VERSION 0x0206 // Boot protocol version #define ZP_SH_16_XLOADFLAGS 0x0236 // 64-bit and EFI load flags #define ZP_SH_32_SYSSIZE 0x01f4 // Size of protected-mode code + payload in 16-bytes #define ZP_SH_32_HEADER 0x0202 // Header, should match HEADER_MAGIC #define ZP_SH_32_RAMDISK_IMAGE 0x0218 // Ramdisk image address #define ZP_SH_32_RAMDISK_SIZE 0x021c // Ramdisk image size #define ZP_SH_32_COMMAND_LINE 0x0228 // Pointer to command line args string #define ZP_SH_32_KERNEL_ALIGN 0x0230 // Kernel alignment #define ZP_SH_64_PREF_ADDRESS 0x0258 // Preferred address for kernel to be loaded at #define ZP_SH_XX_E820_MAP 0x02d0 // The e820 memory map #define LF_LOAD_HIGH (1u << 0) // The protected mode code defaults to 0x100000 #define XLF_KERNEL_64 (1u << 0) // Kernel has legacy 64-bit entry point at 0x200 #define BOOT_FLAG_MAGIC 0xaa55 // Boot flag value to match for Linux #define HEADER_MAGIC 0x53726448 // Header value to match for Linux #define LEGACY_64_ENTRY_OFFSET 0x200 // Offset for the legacy 64-bit entry point #define LOADER_TYPE_UNSPECIFIED 0xff // We are bootloader that Linux knows nothing about #define MIN_BOOT_PROTOCOL 0x0200 // The minimum boot protocol we support (bzImage) #define MAX_E820_ENTRIES 128 // The space reserved for e820, in entries // clang-format off // Default address to load bzImage at static const uintptr_t kDefaultKernelOffset = 0x100000; static const uintptr_t kInitrdOffset = 0x800000; static bool is_linux(const uintptr_t zero_page) { return ZP16(zero_page, ZP_SH_16_BOOTFLAG) == BOOT_FLAG_MAGIC && ZP32(zero_page, ZP_SH_32_HEADER) == HEADER_MAGIC; } zx_status_t setup_linux(const uintptr_t addr, const size_t size, const uintptr_t first_page, const int fd, const char* initrd_path, const char* cmdline, uintptr_t* guest_ip, uintptr_t* zero_page_addr) { if (!is_linux(first_page)) return ZX_ERR_NOT_SUPPORTED; bool has_legacy_entry = ZP16(first_page, ZP_SH_16_XLOADFLAGS) & XLF_KERNEL_64; if (!has_legacy_entry) { fprintf(stderr, "Kernel lacks the legacy 64-bit entry point\n"); return ZX_ERR_NOT_SUPPORTED; } uint16_t protocol = ZP16(first_page, ZP_SH_16_VERSION); uint8_t loadflags = ZP8(first_page, ZP_SH_8_LOAD_FLAGS); bool is_bzimage = (protocol >= MIN_BOOT_PROTOCOL) && (loadflags & LF_LOAD_HIGH); if (!is_bzimage) { fprintf(stderr, "Kernel is not a bzImage. Use a newer kernel\n"); return ZX_ERR_NOT_SUPPORTED; } // Default to the preferred address, then change if we're relocatable uintptr_t runtime_start = ZP64(first_page, ZP_SH_64_PREF_ADDRESS); if (ZP8(first_page, ZP_SH_8_RELOCATABLE) > 0) { uint64_t kernel_alignment = ZP32(first_page, ZP_SH_32_KERNEL_ALIGN); uint64_t aligned_address = ALIGN(kDefaultKernelOffset, kernel_alignment); runtime_start = aligned_address; } // Move the zero-page. For a 64-bit kernel it can go almost anywhere, // so we'll put it just below the boot kernel. uintptr_t boot_params_off = runtime_start - PAGE_SIZE; uint8_t* zero_page = (uint8_t*)(addr + boot_params_off); memmove(zero_page, (void*)first_page, PAGE_SIZE); // Copy the command line string below the zero page. size_t cmdline_len = strlen(cmdline) + 1; uintptr_t cmdline_off = boot_params_off - cmdline_len; if (cmdline_off > UINT32_MAX) { fprintf(stderr, "Command line offset is outside of 32-bit range\n"); return ZX_ERR_OUT_OF_RANGE; } memcpy((char*)(addr + cmdline_off), cmdline, cmdline_len); ZP32(zero_page, ZP_SH_32_COMMAND_LINE) = static_cast<uint32_t>(cmdline_off); // Set type of bootloader. ZP8(zero_page, ZP_SH_8_LOADER_TYPE) = LOADER_TYPE_UNSPECIFIED; // Zero video, columns and lines to skip early video init - just serial output for now. ZP8(zero_page, ZP_SI_8_VIDEO_MODE) = 0; ZP8(zero_page, ZP_SI_8_VIDEO_COLS) = 0; ZP8(zero_page, ZP_SI_8_VIDEO_LINES) = 0; // Setup e820 memory map. size_t e820_entries = guest_e820_size(size) / sizeof(e820entry_t); if (e820_entries > MAX_E820_ENTRIES) { fprintf(stderr, "Not enough space for e820 memory map\n"); return ZX_ERR_BAD_STATE; } ZP8(zero_page, ZP_SH_8_E820_COUNT) = static_cast<uint8_t>(e820_entries); uintptr_t e820_off = boot_params_off + ZP_SH_XX_E820_MAP; zx_status_t status = guest_create_e820(addr, size, e820_off); if (status != ZX_OK) { fprintf(stderr, "Failed to create the e820 memory map\n"); return status; } int setup_sects = ZP8(zero_page, ZP_SH_8_SETUP_SECTS); if (setup_sects == 0) { // 0 here actually means 4, see boot.txt. setup_sects = 4; } // Read the rest of the bzImage into the protected_mode_kernel location. int protected_mode_off = (setup_sects + 1) * SECTOR_SIZE; off_t ret = lseek(fd, protected_mode_off, SEEK_SET); if (ret < 0) { fprintf(stderr, "Failed seek to protected mode kernel\n"); return ZX_ERR_IO; } size_t remaining = ZP32(zero_page, ZP_SH_32_SYSSIZE) << 4; ret = read(fd, (void*)(addr + runtime_start), remaining); if ((size_t)ret != remaining) { fprintf(stderr, "Failed to read Linux kernel data\n"); return ZX_ERR_IO; } if (initrd_path) { ZP32(zero_page, ZP_SH_32_RAMDISK_IMAGE) = kInitrdOffset; int initrd_fd = open(initrd_path, O_RDONLY); if (initrd_fd < 0) { fprintf(stderr, "Failed to open initial RAM disk\n"); return ZX_ERR_IO; } struct stat initrd_stat; off_t ret = fstat(initrd_fd, &initrd_stat); if (ret < 0) { fprintf(stderr, "Failed to stat initial RAM disk\n"); return ZX_ERR_IO; } if (initrd_stat.st_size > UINT32_MAX || static_cast<size_t>(initrd_stat.st_size) > size - kInitrdOffset) { fprintf(stderr, "Initial RAM disk is too large\n"); return ZX_ERR_OUT_OF_RANGE; } ZP32(zero_page, ZP_SH_32_RAMDISK_SIZE) = static_cast<uint32_t>(initrd_stat.st_size); ret = read(initrd_fd, (void*)(addr + kInitrdOffset), initrd_stat.st_size); if (ret != initrd_stat.st_size) { fprintf(stderr, "Failed to read initial RAM disk\n"); return ZX_ERR_IO; } } *guest_ip = runtime_start + LEGACY_64_ENTRY_OFFSET; *zero_page_addr = boot_params_off; return ZX_OK; }
a092ec8f26a3750a7159900f8982675e4970c7c9
0dd9cf13c4a9e5f28ae5f36e512e86de335c26b4
/LeetCode/leetcode_lfu-cache.cpp
5f078ad91d8e95178f1f73663f83c3c5a7ffda60
[]
no_license
yular/CC--InterviewProblem
908dfd6d538ccd405863c27c65c78379e91b9fd3
c271ea63eda29575a7ed4a0bce3c0ed6f2af1410
refs/heads/master
2021-07-18T11:03:07.525048
2021-07-05T16:17:43
2021-07-05T16:17:43
17,499,294
37
13
null
null
null
null
UTF-8
C++
false
false
2,371
cpp
leetcode_lfu-cache.cpp
/* * * Tag: Data Structure * Time: O(1) * Space: O(n) */ class LFUCache { private: struct Row{ list<pair<int,int>> cols; int freq; Row(int k, int v, int f){ cols.push_back(make_pair(k, v)); freq = f; } }; unordered_map<int, pair<list<Row>::iterator,list<pair<int,int>>::iterator> > dict; list<Row> cache; int cap, curcap; public: LFUCache(int capacity) { dict.clear(); cache.clear(); cap = capacity; curcap = 0; } int get(int key) { if(dict.find(key) == dict.end()) return -1; int value = 0; value = dict[key].second->second; updateCache(key, value); return value; } void set(int key, int value) { if(!cap) return ; if(dict.find(key) == dict.end()){ list<Row>::iterator row, newrow, nxtrow; list<pair<int,int>>::iterator col; if(curcap >= cap){ row = cache.end(); -- row; col = row->cols.end(); -- col; row->cols.pop_back(); if(row->cols.empty()) cache.erase(row); dict.erase(col->first); -- curcap; } if(cache.empty() || cache.back().freq != 1){ newrow = cache.emplace(cache.end(), key, value, 1); }else{ newrow = --cache.end(); newrow->cols.push_front(make_pair(key, value)); } dict[key] = make_pair(newrow, newrow->cols.begin()); ++ curcap; }else{ updateCache(key, value); } } private: void updateCache(int key, int value){ list<Row>::iterator row = dict[key].first, nxtrow, newrow; list<pair<int,int>>::iterator col = dict[key].second; nxtrow = row; -- nxtrow; if(nxtrow == cache.end() || nxtrow->freq != row->freq + 1){ newrow = cache.emplace(row, key, value, row->freq + 1); }else{ newrow = nxtrow; newrow->cols.push_front(make_pair(key, value)); } dict[key] = make_pair(newrow, newrow->cols.begin()); row->cols.erase(col); if(row->cols.empty()) cache.erase(row); } };
00ec64b6600a548b4ee2578e67ba69a9c5e926df
cc49ddde8530bdb646f1c283f4600ab7c0b6681b
/StoryBoard.h
913a96732e9cc8f1d4ad4164781a9c4bc2ef816b
[]
no_license
BharathSD/StoryBoardApp
5b8400d71b4e2db1293159277c2ebd97f03c0f3e
76510cf4deda0adc0cd77e6990ae30a42e0cb100
refs/heads/master
2020-04-29T12:18:51.233029
2019-03-17T17:04:26
2019-03-17T17:04:26
176,132,398
0
0
null
null
null
null
UTF-8
C++
false
false
3,638
h
StoryBoard.h
#pragma once #include <sstream> #include "Notes.h" class CStoryBoard { private: std::list<CNotes*> m_NoteList; std::string m_name; bool checkIfNoteisPresent(std::string title) { bool retVal(false); for (std::list<CNotes*>::iterator itr = m_NoteList.begin(); itr != m_NoteList.end(); ++itr) { if (**itr == title) { // already exists retVal = true; break; } } return retVal; } std::string str() const { std::stringstream ss; ss << "\t\t\t\t" << "Story Board : " << m_name << std::endl; int counter(0); for (std::list<CNotes*>::const_iterator itr = m_NoteList.begin(); itr != m_NoteList.end(); ++itr) { ss << "Note - " << ++counter << std::endl; ss << **itr << std::endl; } return ss.str(); } CNotes* searchNotesByTitle(std::string title) { // title is considered unique, hence the return type of the function isjust a pointer type CNotes* pData = nullptr; for (std::list<CNotes*>::iterator itr = m_NoteList.begin(); itr != m_NoteList.end(); ++itr) { if (**itr == title) { pData = *itr; } } return pData; } std::list<CNotes*> searchNotesByTag(std::list<std::string> tags) { std::list<CNotes*> filteredNotesData; for (std::list<CNotes*>::iterator itr = m_NoteList.begin(); itr != m_NoteList.end(); ++itr) { if (**itr == tags) { filteredNotesData.push_back(*itr); } } return filteredNotesData; } std::list<CNotes*> searchNotesByText(std::string textContent) { std::list<CNotes*> filteredNotesData; for (std::list<CNotes*>::iterator itr = m_NoteList.begin(); itr != m_NoteList.end(); ++itr) { if ((*itr)->compareText(textContent)) { filteredNotesData.push_back(*itr); } } return filteredNotesData; } public: CStoryBoard(std::string name) :m_name(name) { } ~CStoryBoard() { for (auto note : m_NoteList) { if (note) delete note; } m_NoteList.clear(); } template<typename... Args> void addNote(std::string title, std::string textContent, Args... tags) { if(!checkIfNoteisPresent(title)) // check if note already exists m_NoteList.push_back(new CNotes(title, textContent, tags...)); // todo throw exceptions if the Note already exists } void deleteNote(std::string title) { for (std::list<CNotes*>::iterator itr = m_NoteList.begin(); itr != m_NoteList.end(); ++itr) { if (**itr == title) { // found the match delete *itr; m_NoteList.erase(itr); break; // title is unique, hence there would be only one Note with the title name } } } std::string searchByTitle(std::string title) { CNotes* pNote = searchNotesByTitle(title); std::stringstream ss; ss << "Search Result : " << std::endl; ss << *pNote << std::endl; return ss.str(); } std::string searchByTag(std::list<std::string> tags) { auto notesList = searchNotesByTag(tags); std::stringstream ss; ss << "Search Result : " << std::endl; for(auto note : notesList) ss << *note << std::endl; return ss.str(); } std::string searchByText(std::string textContent) { auto notesList = searchNotesByText(textContent); std::stringstream ss; ss << "Search Result : " << std::endl; for (auto note : notesList) ss << *note << std::endl; return ss.str(); } friend std::ostream &operator<<(std::ostream &os, const CStoryBoard &storyBoard); }; std::ostream &operator<<(std::ostream &os, const CStoryBoard &storyBoard) { os << storyBoard.str() << std::endl; return os; }
aafa38bd52e42d6fb109f05a01be24ee71bec8e6
056a35a213f0f146e37394aba99109b93d16834b
/WT_Show/show/core/mat/ink_widget.h
43cf027a8ca4474458bf69db2ec9387f80893244
[]
no_license
wiali/video_record
45e2e7e126448cd2408ac5dbae1703975cabbff6
5d2c9d3b3d6bca9d771b1b9bf434ae5369d3f501
refs/heads/master
2021-07-22T12:59:25.084905
2017-11-01T10:06:16
2017-11-01T10:06:16
103,298,379
0
0
null
null
null
null
UTF-8
C++
false
false
5,601
h
ink_widget.h
/*! \file ink_tool_box.h * \brief Provided a ink canvas used for drawing with mouse, touch or stencil * \details This class is based on Qt official example: http://doc.qt.io/qt-5/qtwidgets-widgets-tablet-tabletcanvas-h.html * \date February, 2017 * \copyright 2017 HP Development Company, L.P. */ #pragma once #ifndef INK_TOOL_BOX_H #define INK_TOOL_BOX_H #include <QWidget> #include <QTimer> #include <QColor> #include <QSharedPointer> #include <QPixmap> #ifdef Q_OS_WIN #include <Windows.h> #endif #include <frame_counting.h> #include "ink_data.h" #include "shared_global.h" #include "model/application_state_model.h" #include "stage_item_3d.h" namespace capture { namespace mat { class SHAREDSHARED_EXPORT InkWidget : public QWidget { Q_OBJECT public: InkWidget(QWidget* leftWidget, QWidget* rightWidget, QWidget *parent = nullptr, bool showFps=false, QSharedPointer<model::ApplicationStateModel> model = QSharedPointer<model::ApplicationStateModel>()); /*! \brief Reset the Ink mode */ void setPenMode(bool penMode); /*! \brief Reset the strokes data. * Important!! The ink data must be set. Otherwise it will lost the ink data. */ void setInkData(QSharedPointer<InkData> strokes); void setStageRenderer(StageRenderer* renderer); /*! \brief Reset the pen color */ void setColor(const QColor &c); /*! \brief Get the pen color */ QColor color() const; /*! \brief Reset the pen point color */ void setPenPointColor(const QColor &penPointColor); /*! \brief Get the pen point color */ QColor penPointColor() const; /*! \brief Enter eraser mode */ void enterEraserMode(); /*! \brief Enable pen */ void enablePen(bool enable); /*! \brief Enter eraser mode */ void enableRemoveStroke(bool enable); /*! \brief Enter drawing mode */ void enterDrawMode(); void setForward(bool forward) { m_forward = forward; } bool forward() { return m_forward; } void updatePixmapBySize(); void onUpdate(); public slots: /*! \brief Handles the resize of our main window */ void mainWindowResize(QSize size); /*! \brief Resizes the draing pixmap and overlay to the parent window */ void resizeToWindow(); /*! \brief Reset the pen size */ void penSizeChanged(int penSize); /*! \brief Reset the pen color */ void colorChanged(const QColor& color); /*! \brief Digitizer pen enters hovering */ void onPenHoverEntered(const POINTER_PEN_INFO& penInfo); /*! \brief Digitizer pen exits hovering */ void onPenHoverExited(const POINTER_PEN_INFO& penInfo); /*! \brief Digitizer pen touch touchmat */ void onPenDown(const POINTER_PEN_INFO& penInfo); /*! \brief Digitizer pen leave touchmat. */ void onPenUp(const POINTER_PEN_INFO& penInfo); /*! \brief Digitizer pen move on touchmat */ void onPenMove(const POINTER_PEN_INFO& penInfo); void updatePixmap(bool updateAll); signals: /*! \brief Ink data has been changed. */ void inkDataChanged(QSharedPointer<InkData> inkData); /*! \brief Ink data has been erased */ void inkDataErasing(const QPoint& point); /*! \brief Ink point have been added. */ void inkPointAdded(const QPoint& point, double width); /*! \brief Ink stroke have been added. */ void inkStrokeAdded(); protected: /*! \brief Paint event */ void paintEvent(QPaintEvent *event) override; /*! \brief Mouse move event */ void mouseMoveEvent(QMouseEvent *event) override; /*! \brief Mouse press event */ void mousePressEvent(QMouseEvent *event) override; /*! \brief Mouse release event */ void mouseReleaseEvent(QMouseEvent *event) override; /*! \brief Hide event */ void hideEvent(QHideEvent *event) override; /*! \brief Show event */ void showEvent(QShowEvent *event) override; private slots: void onEditModeChanged(model::ApplicationStateModel::EditMenuMode mode); private: void changeCursor(int penSize); QString penInfoStr(const POINTER_PEN_INFO& penInfo); // Erase the stroke that near the point void eraseStroke(const QPoint& pos); // Update the pen color void updateColor(const QColor& color); // Add point to current stroke. void addPoint(const QPoint& point, double width); // Add current stroke to the list void addStroke(); QPolygonF corner(); QColor m_color; int m_basePenWidth; /*! \brief Timer used to emulate the end of a resize */ QTimer m_resizeTimer; // Eraser size int m_eraserSize; // Right menu widget QWidget* m_rightMenu; // Left menu widget QWidget* m_leftMenu; // Eraser mode or not bool m_eraserMode; bool m_penEraserMode; // Pen mode or not bool m_penMode; // Pen is drawing. And we will discard the mouse event. bool m_penDrawing; // Enable pen bool m_enablePen; // Mouse is drawing bool m_mouseDrawing; // Disable the remove feature bool m_enableRemoveStroke; bool m_enabled; QColor m_penPointColor; // Ink data QSharedPointer<InkData> m_inkData; // Shadow image to improve the render performance. QPixmap m_pixmap; QSharedPointer<FrameCounting> m_frameCounting; bool m_forward = false; QSharedPointer<model::ApplicationStateModel> m_model; StageRenderer* m_renderer; }; } // namespace mat } // namespace capture #endif // INK_TOOL_BOX_H
73b598b70dfe4ce8a0df3f976bfa7a8ca499b058
7b3d4dff3945584460dc474a8bb8fe8fd9bdb625
/lectures/stack/abstract_stack.hpp
9a7924d4e296c9c24d24524192fc1708a6832af3
[ "MIT" ]
permissive
triffon/oop-2019-20
305535b006cb19e96c9c58d47737a28135fc666e
ec3e5488859d8140de5aa5090811cd0e1318d952
refs/heads/master
2022-05-13T07:04:22.306200
2022-03-19T09:49:17
2022-03-19T09:49:45
241,474,762
21
11
null
null
null
null
UTF-8
C++
false
false
560
hpp
abstract_stack.hpp
#ifndef __ABSTRACT_STACK_HPP #define __ABSTRACT_STACK_HPP template <typename T> class AbstractStack { public: // проверка за празнота virtual bool empty() const = 0; // включване на елемент virtual void push(T const& x) = 0; // изключване на елемент virtual T pop() = 0; // поглеждане на последно включения елемент virtual T peek() const = 0; // виртуален деструктор virtual ~AbstractStack() {} }; #endif
96064a0a472d08456c5575b3caf625eb78c84d3d
7150de89552eb732d3791ea698cfcfa2762ec569
/CRYSTAL/crystproblemfact.hpp
aac87f0aef7e9622449b7053fc33ce624954fb20
[]
no_license
tenkjm/optimisation
1b6434a4872e3ce79994ed84c6e815bd140d2fd4
0398401e02c33d4d4d217bafdb901ead459ea230
refs/heads/master
2021-01-13T11:09:22.633957
2017-02-08T07:54:44
2017-02-08T07:54:44
81,301,633
0
0
null
null
null
null
UTF-8
C++
false
false
1,866
hpp
crystproblemfact.hpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: crystproblemfact.hpp * Author: posypkin * * Created on January 5, 2017, 9:48 PM */ #ifndef CRYSTPROBLEMFACT_HPP #define CRYSTPROBLEMFACT_HPP #include <string> #include <common/sgerrcheck.hpp> #include <latticedata.hpp> #include <atoms.hpp> #include "potentialnames.hpp" #include "ljproblemfactory.hpp" #include "tsofproblemfactory.hpp" /** * Crystal problem factory */ class CrystallProblemFactory { public: /** * Constructor * @param nlayers number of layers * @param double pieceLength the horizontal length of the modeling piece * @param double radius the cutof radius */ CrystallProblemFactory(std::string potname = LENNARD_JONES_POTENTIAL, int nlayers = 3, double pieceLength = 16, double radius = 3, int atom = lattice::CARBON) : mPotName(potname) { setupLatticeData(nlayers, pieceLength, radius, atom); } COMPI::MPProblem<double>* get() { if (mPotName == LENNARD_JONES_POTENTIAL) { LJProblemFactory ljpf(mData); return ljpf.getLJProblem(); } else if (mPotName == TERSOFF_POTENTIAL) { TsofProblemFactory tsofpf(mData); return tsofpf.getTsofProblem(); } else { SG_ERROR_REPORT("wrong potential specified\n"); } } private: void setupLatticeData(int nlayers, double pieceLength, double radius, int atom) { mData.mNumLayers = nlayers; mData.mLength = pieceLength; mData.mRadius = radius; mData.mLayersAtoms.assign(mData.mNumLayers, atom); } lattice::LatticeData mData; std::string mPotName; }; #endif /* CRYSTPROBLEMFACT_HPP */
a93b92fbfca8ea60a4233539d39f051606a0af4b
939e4efb6bd8b747ba361805498da243a715c31c
/Game/menu.h
45ec1cb7e8db38c789da0eae3ccc834f7541759c
[ "MIT" ]
permissive
pmprog/SuperJumpKickTurbo
8dbf8eeaa801f734c24dc1473f8f184b551d71bf
efcf1ac1256297829438bcbd60083e244835b9c6
refs/heads/master
2021-11-18T01:56:50.346563
2021-09-18T19:22:38
2021-09-18T19:22:38
15,175,929
4
3
MIT
2021-09-18T19:22:38
2013-12-13T22:48:58
C++
UTF-8
C++
false
false
775
h
menu.h
#pragma once #include "includes.h" #include "../Framework/Display/spritesheet.h" #include "fighter.h" class Menu : public Stage { private: ALLEGRO_BITMAP* imgSuper; ALLEGRO_BITMAP* imgJumpKick; ALLEGRO_BITMAP* imgBackground; SpriteSheet* imgTurbo; ALLEGRO_FONT* fntTitle; int menuTime; int menuSelection; ALLEGRO_COLOR menuSelectedColour; ALLEGRO_COLOR menuItemColour; Fighter* TitleFighters[3]; int backgroundX; public: static int Player1Joystick; static int Player2Joystick; // Stage control virtual void Begin(); virtual void Pause(); virtual void Resume(); virtual void Finish(); virtual void EventOccurred(Event *e); virtual void Update(); virtual void Render(); virtual bool IsTransition(); };
47bdf161f3b0582436c100fb47b6bdc70617e589
ddc5f6b4e8fbb6cd2d22a3e83b9f46f2d4e2b643
/LineManager.h
eb33caa4fe37e06b2a6d303cd5a322deaead3683
[]
no_license
badalsarkar/AssemblyLineManagement
0b13bd2bb7f192ff5e9020477fe8e924cc3f3d62
dcdba5060635091d6e0e4ab17714dfe8341cd548
refs/heads/master
2020-12-12T22:58:02.383071
2020-02-16T03:18:23
2020-02-16T03:18:23
234,251,854
1
0
null
null
null
null
UTF-8
C++
false
false
1,048
h
LineManager.h
// Name:Badal Sarkar // Seneca Student ID:137226189 // Seneca email:bsarkar2@myseneca.ca // Date of completion:December 1, 2019 // // I confirm that I am the only author of this file // and the content was created entirely by me. #ifndef LINEMANAGER_H #define LINEMANAGER_H #include <vector> #include <deque> #include <string> #include "Task.h" class LineManager{ std::vector<Task*> AssemblyLine; std::deque<CustomerOrder> ToBeFilled; std::deque<CustomerOrder> Completed; unsigned int m_cntCustomerOrder; //the starting size of ToBeFilled std::string firstTaskInAssmLine; void setupNextTask(std::vector<Task*>&, std::string& taskA, std::string& taskB); public: LineManager(const std::string& source, std::vector<Task*>& task_list, std::vector<CustomerOrder>& order_list); bool run(std::ostream&); void displayCompleted(std::ostream&)const; void validateTasks()const; }; //free helper std::string extractToken(std::string& s, char delimiter='\n'); std::string trim(std::string text); #endif
ae88e84ce5971816471601a1837b7e6d5477c501
dfb79d34782a7fba267b55b91f78f0a719f5788a
/HW7/MovieTree.cpp
2e209757b616442d093ae851d9f40a0f001a6eb9
[]
no_license
cwong907/CSCI2270
639e8093dd91b4c0898adc51356a556fb041fce5
392fb79594fc0002a354a90006fb0e87feed497e
refs/heads/master
2022-11-30T17:00:44.189118
2020-07-25T22:12:08
2020-07-25T22:12:08
282,530,300
0
0
null
null
null
null
UTF-8
C++
false
false
8,875
cpp
MovieTree.cpp
#include <iostream> #include <fstream> #include "MovieTree.hpp" using namespace std; /* ------------------------------------------------------ */ MovieTree::MovieTree() { root = NULL; } void deleteN(TreeNode* temp) { if(temp == NULL) { return; } if (temp->leftChild != NULL) { deleteN(temp->leftChild); } if (temp->rightChild != NULL) { deleteN(temp->rightChild); } if (temp->head != NULL) { LLMovieNode* del; while (temp->head != NULL) { del = temp->head; temp->head = temp->head->next; delete del; } temp->head = NULL; } delete temp; } MovieTree::~MovieTree() { deleteN(root); //delete root; root = NULL; } void helpPrint(TreeNode *current, int &counter) { counter++; if(current == NULL) { if(counter == 1) { return; } else { return; } } else { LLMovieNode *move = current->head; helpPrint(current->leftChild, counter); cout << "Movies starting with letter: " << current->titleChar << endl; while(move != NULL) { cout << " >> " << move->title << " " << move->rating << endl; move = move->next; } helpPrint(current->rightChild, counter); } } void MovieTree::printMovieInventory() { int count = 0; helpPrint(root, count); } void LLInsert(TreeNode *check, LLMovieNode *temp, string title) { LLMovieNode *search = check->head; if(check->head == NULL) { search = temp; temp->next = NULL; } else if(check->head->title > title) { temp->next = check->head; check->head = temp; } else { while(search->next != NULL) { if(search->title < title && search->next->title > title && search->next != NULL) { temp->next = search->next; search->next = temp; break; } else if(search->title < title && search->next != NULL) { search = search->next; } } search->next = temp; } } void spinMeRightRound(TreeNode *&current, TreeNode *&root) { if(current->rightChild == NULL) { return; } else if(current == root) { TreeNode *temp = current->rightChild; temp->parent = NULL; current->rightChild = temp->leftChild; current->parent = temp; temp->leftChild = current; root = temp; } else { TreeNode *temp = current->rightChild; TreeNode *P = current->parent; temp->parent = P; if(P->rightChild == current) { P->rightChild = temp; } else { P->leftChild = temp; } current->rightChild = temp->leftChild; current->parent = temp; temp->leftChild = current; } } void MovieTree::leftRotation(TreeNode* curr) { spinMeRightRound(curr, root); } //------ Given Methods--------// void _grader_inorderTraversal(TreeNode *root) { if (root == NULL) { return; } _grader_inorderTraversal(root->leftChild); cout << root->titleChar << " "; _grader_inorderTraversal(root->rightChild); } void MovieTree::inorderTraversal() { _grader_inorderTraversal(root); cout << endl; } TreeNode* searchCharHelper(TreeNode* curr, char key) { if (curr == NULL) return curr; else if(curr->titleChar == key) return curr; else if (curr->titleChar > key) return searchCharHelper(curr->leftChild, key); else return searchCharHelper(curr->rightChild, key); } TreeNode* MovieTree::searchChar(char key) { return searchCharHelper(root, key); } void MovieTree::addMovie(int ranking, string title, int year, float rating) { TreeNode *check = root; if(root == NULL) { //cout << "Test" << endl; TreeNode *x = new TreeNode; root = x; x->titleChar = title.at(0); x->head = new LLMovieNode(ranking, title, year, rating); return; } else { //cout << "Test2" << endl; LLMovieNode *temp = new LLMovieNode(ranking, title, year, rating); while(true) { if(title.at(0) == check->titleChar) { //cout << "Test3" << endl; LLInsert(check, temp, title); return; } else if(title.at(0) > check->titleChar && check->rightChild != NULL) { //cout << "Test4" << endl; check = check->rightChild; } else if(title.at(0) < check->titleChar && check->leftChild != NULL) { //cout << "Test5" << endl; check = check->leftChild; } else if(title.at(0) < check->titleChar && check->leftChild == NULL) { //cout << "ef" << endl; TreeNode *newN = new TreeNode; newN->titleChar = title.at(0); newN->head = temp; check->leftChild = newN; newN->parent = check; //cout << "Test6" << endl; return; } else if(title.at(0) > check->titleChar && check->rightChild == NULL) { //cout << "F" << endl; TreeNode *newN = new TreeNode; newN->titleChar = title.at(0); newN->head = temp; check->rightChild = newN; newN->parent = check; //cout << "Test7" << endl; return; } } } } TreeNode* getMinValueNode(TreeNode* currNode) { if(currNode->leftChild == NULL){ return currNode; } return getMinValueNode(currNode->leftChild); } TreeNode* deleteNode(TreeNode *currNode, char titleC) { if(currNode == NULL) { return NULL; } // else if(currNode->parent == NULL) // { // currNode = currNode->rightChild; // } else if(titleC < currNode->titleChar) { currNode->leftChild = deleteNode(currNode->leftChild, titleC); } else if(titleC > currNode->titleChar) { currNode->rightChild = deleteNode(currNode->rightChild, titleC); } else { if(currNode->leftChild == NULL && currNode->rightChild == NULL) { delete currNode; currNode = NULL; return NULL; } //Only right child else if(currNode->leftChild == NULL && currNode->rightChild != NULL) { TreeNode *temp = currNode->rightChild; currNode->rightChild->parent = currNode->parent; delete currNode; currNode = temp; } //Only left child else if(currNode->rightChild == NULL && currNode->leftChild != NULL) { TreeNode *temp = currNode->leftChild; currNode->leftChild->parent = currNode->parent; delete currNode; currNode = temp; } //Both left and right child else { TreeNode *temp = getMinValueNode(currNode->rightChild); currNode->head = temp->head; currNode->titleChar = temp->titleChar; currNode->rightChild = deleteNode(currNode->rightChild, temp->titleChar); } } return currNode; } void MovieTree::deleteMovie(string title) { TreeNode *check = searchChar(title.at(0)); if(check == NULL) { cout << "Movie: " << title << " not found, cannot delete." << endl; } else { LLMovieNode *look = check->head; LLMovieNode *prev = look; if(check->head->title == title && check->head->next == NULL) { //check->head = NULL; delete check->head; root = deleteNode(root, check->titleChar); } else if(check->head->title == title) { //cout << 4 << endl; check->head = check->head->next; delete look; } else { //cout << 5 << endl; while(look != NULL) { //cout << 6 << endl; if(look->title == title) { //cout << 7 << endl; prev->next = look->next; delete look; break; } else if(look->title == title && look->next == NULL) { prev->next = NULL; delete look; break; } else { prev = look; look = look->next; } } if(look == NULL) { cout << "Movie: " << title << " not found, cannot delete." << endl; } } } }
58f1459fcb287326abf8a65f8a676df2af82416b
11be86a1aaa0f0df94ab5b91a83c54665c5d0ca4
/TargetProject/UnitTestProject/TEST_RandomMinute.cpp
7cc149bf2f98d7ec9e53a5ba6c4f1592b38dc2f0
[]
no_license
falloutkid/TestDrivenDevelopmentForEmbeddedC
98a6db69f9b2dcd1cdcb5abf596498b586b64ce9
78983733eed8f6204eb341538fda906ab67539a4
refs/heads/master
2021-01-23T08:38:54.017403
2015-04-06T18:46:01
2015-04-06T18:46:01
32,821,924
0
0
null
null
null
null
UTF-8
C++
false
false
1,283
cpp
TEST_RandomMinute.cpp
#include "stdafx.h" #include "CppUnitTest.h" #include "string.h" #include <TargetApplication\RandomMinute.h> #include <stdio.h> using namespace Microsoft::VisualStudio::CppUnitTestFramework; static int minute; namespace UnitTestProject { TEST_CLASS(TEST_RandomMinute) { private: static const int BOUND = 30; public: TEST_CLASS_INITIALIZE(setup) { RandomMinute_Create(BOUND); minute = 0; srand(1); } void AssertMinuteIsInRange() { if (minute < -BOUND || minute > BOUND) { printf("bad minute value: %d\n", minute); Assert::Fail(L"Minute out of range"); } } TEST_METHOD(GetIsInRange) { for (int i = 0; i < 100; i++) { minute = RandomMinute_Get(); #if 0 char write_data[256]; sprintf(write_data, "Nomber[%d]::minute[%d]\n", i, minute); Logger::WriteMessage(write_data); #endif AssertMinuteIsInRange(); } } TEST_METHOD(AllValuesPossible) { int hit[2 * BOUND + 1]; memset(hit, 0, sizeof(hit)); int i; for (i = 0; i < 300; i++) { minute = RandomMinute_Get(); AssertMinuteIsInRange(); hit[minute + BOUND]++; } for (i = 0; i < 2 * BOUND + 1; i++) { Assert::IsTrue(hit[i] > 0); } } }; }
8cd7da3d94248ec42ef2d7f93806b7ac853c3eb0
e8c4d4fd1ad02afc908d30358ba4c24f9a0198af
/lab03/mortgage.cpp
52122ec9813508037795bcd275638045ed72e005
[]
no_license
rtabibi98/cmpsc16
40c504547e1822b530cf1000e0696a456484a994
693832add604a4a5f2a5a326cae7d80c7689d363
refs/heads/master
2022-11-30T04:31:55.520418
2020-08-19T23:38:18
2020-08-19T23:38:18
288,842,403
0
0
null
null
null
null
UTF-8
C++
false
false
1,949
cpp
mortgage.cpp
// mortgage.cpp // calculates the annual after-tax cost of a new house for the first year of ownership // 21 October 2018 #include <iostream> using namespace std; // function declarations double annual_mortage_cost(double loan_amt, double loan_interest_rate, double loan_reduction_rate); double annual_tax_savings(double loan_amt, double loan_interest_rate, double tax_rate); int main() { double loan_interest_r(0.06), loan_reduction_r(0.03), tax_r(0.35), loan_amount(0); double down_payment(0), p_home(0), mortage_cost(0), tax_savings(0); cout << "Enter the home price (or zero to quit):\n"; cin >> p_home; while (p_home != 0) { cout << "Enter the down payment:\n"; cin >> down_payment; loan_amount = p_home - down_payment; // the loan is equal to the price of the home minus what the owners pay upfront mortage_cost = annual_mortage_cost(loan_amount, loan_interest_r, loan_reduction_r); tax_savings = annual_tax_savings(loan_amount, loan_interest_r, tax_r); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); // annual after-tax cost is sum of interest rate paid on loan plus the rate they pay off the loan (mortgage) // minus the tax rate multiplied by the interest payment (tax savings) cout << "The after-tax cost is $" << mortage_cost - tax_savings << " annually." << endl; cout << "Enter the home price (or zero to quit):\n"; cin >> p_home; } return 0; } // function definitions double annual_mortage_cost(double loan_amt, double loan_interest_rate, double loan_reduction_rate) { // (loan_amount * loan_reduction_rate) + (loan_amount * loan_interest_rate) = mortgage return (loan_amt * (loan_reduction_rate + loan_interest_rate)); } double annual_tax_savings(double loan_amt, double loan_interest_rate, double tax_rate) { // tax_rate * (loan_amount * loan_interest_rate) = tax savings return (tax_rate * (loan_amt * loan_interest_rate)); }
cd75b919275ff1f703ab8312220946044811a754
d3363534cb895b3b9acbb49e70e205a6f5a524b9
/11727/11727.cpp
9c0c09da904c197877cd0836fd411dc2e4aad624
[]
no_license
Behrouz-Babaki/practice
82a638cbd6a7475930c0fd30fcd86a4333786b7b
27174701c6aeb0dcea2335e27dbcf9ffa3d7f73a
refs/heads/master
2021-08-16T11:38:31.981301
2017-11-19T19:37:19
2017-11-19T19:37:19
12,410,348
0
0
null
null
null
null
UTF-8
C++
false
false
618
cpp
11727.cpp
#include <iostream> using std::cin; using std::endl; using std::cout; int main(void) { size_t num_cases; cin >> num_cases; for (size_t case_counter = 0; case_counter < num_cases; case_counter++) { size_t salary[3]; cin >> salary[0] >> salary[1] >> salary[2]; size_t max = 0, mid = 0; for (int staff_counter = 0; staff_counter < 3; staff_counter++) if (salary[staff_counter] > max) { mid = max; max = salary[staff_counter]; } else if (salary[staff_counter] > mid) mid = salary[staff_counter]; cout << "Case " << case_counter + 1 << ": " << mid << endl; } return 0; }
b5dfe9aabcdc89b48bac20fa309fef4933c668ac
6ec994ad31f6b035f163891a4a8014d15f0e3540
/test/scheduler_test.cpp
e4f52b479ffd8b70c70c690e5f58c6476999c84c
[]
no_license
chonlon/net_base
5bfc4f137ee5f0908b36c794147a34c5b23b03a5
6c6fb145a212a74cc6a84df1de1d1b1831dbac5e
refs/heads/main
2023-07-30T14:32:19.827573
2021-10-02T13:21:13
2021-10-02T13:23:27
346,172,667
0
0
null
null
null
null
UTF-8
C++
false
false
1,982
cpp
scheduler_test.cpp
#include <string> #include <unordered_set> #include <gtest/gtest.h> #include "config/yaml_convert_def.h" #include "coroutine/scheduler.h" #include <algorithm> #include <fmt/ranges.h> TEST(CoroutineTest, sequence) { //在单独线程环境中, 任务执行顺序应该是完全按照添加顺序进行的. std::thread t([](){ int sequence = 0; auto scheduler = lon::coroutine::Scheduler::getThreadLocal(); #define SEQ_XX(seq_expect) \ scheduler->addExecutor(std::make_shared<lon::coroutine::Executor>([&]() \ { \ EXPECT_EQ(sequence++, seq_expect); \ std::cout << "seq:" << sequence << '\n'; \ })); SEQ_XX(0) SEQ_XX(1) SEQ_XX(2) SEQ_XX(3) SEQ_XX(4) SEQ_XX(5) #undef SEQ_XX scheduler->addExecutor(std::make_shared<lon::coroutine::Executor>([scheduler]() { scheduler->stop(); })); scheduler->run(); }); t.join(); } TEST(CoroutineTest, exception) { //在协程函数中抛出的异常会以日志错误形式提醒. EXPECT_NO_THROW([]() { std::thread t([](){ auto scheduler = lon::coroutine::Scheduler::getThreadLocal(); scheduler->addExecutor(std::make_shared<lon::coroutine::Executor>([]() { std::cout << "notion: log error for exception is correct\n"; throw std::invalid_argument("invalid"); })); scheduler->addExecutor(std::make_shared<lon::coroutine::Executor>([scheduler]() { scheduler->stop(); })); scheduler->run(); }); t.join(); }()); } int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
ad31f411ece07532e2557f4be909fd049d1ec792
b3afd40ff8e996749fa96cfa8f54cab6b8966af5
/SteeringBehaviors/Game.cpp
d5ab656fdaff68596539a8b8ff687f0017f9020b
[]
no_license
Knothe/SteeringBehaviorsTests
75babbb11fe6cb35cfa614ebbfaebc92e599fce9
41d3608eab001179a531fdd346efd43f1e0eac1e
refs/heads/master
2021-01-03T02:34:22.886434
2020-02-11T22:32:56
2020-02-11T22:32:56
239,875,816
0
0
null
null
null
null
UTF-8
C++
false
false
2,817
cpp
Game.cpp
#include "Game.h" #include "Pause.h" #include "Endgame.h" /* Initializes variables and adds textures */ Game::Game() { assetManager = AssetManager::getPtr(); platform = Platform::GetPtr(); audioManager = AudioManager::getPtr(); assetManager->AddTexture("Arrow.png", "bow", 7); assetManager->AddTexture("Sword.png", "sword", 6); assetManager->AddTexture("Gem.png", "gem", 4); assetManager->AddTexture("Rupee.png", "rupee", 3); assetManager->AddTexture("Coin.png", "coin", 4); assetManager->AddTexture("Board.png", "board", 1); assetManager->AddTexture("Wand.png", "wand", 5); assetManager->AddTexture("Potions.png", "potion", 6); assetManager->AddTexture("Direction.png", "direction", 8); assetManager->AddTexture("Selected.png", "select", 1); assetManager->AddTexture("ArrowDestroy.png", "bowDes", 7); assetManager->AddTexture("SwordDestroy.png", "swoDes", 7); assetManager->AddTexture("GemDestroy.png", "gemDes", 7); assetManager->AddTexture("RupeeDestroy.png", "rupDes", 7); assetManager->AddTexture("CoinDestroy.png", "coiDes", 7); assetManager->AddTexture("WandDestroy.png", "wanDes", 7); assetManager->AddTexture("PotionsDestroy.png", "potDes", 8); assetManager->AddTexture("DirectionDestroy.png", "dirDes", 8); assetManager->AddTexture("BackGroundGame.png", "game", 1); } /* Checks inputs in game */ void Game::Input() { Vector<int> input; platform->CheckEvent(&input, &mouseData); for (int i = 0; i < input.GetSize(); i++) { if (input.GetAt(i) == SDLK_p) GameManager::getPtr()->SetState(new Pause(this)); if (input.GetAt(i) == SDLK_ESCAPE) state = false; } g->Input(&mouseData); mouseData.ResetClicks(); } /* Updates everything in game */ void Game::Update() { score += g->Update(); maxTime -= (SDL_GetTicks() - lastTime); if (maxTime <= 0) GameManager::getPtr()->SetState(new EndGame(this, score)); scoreT = new Text(Vec2(30, 30), std::to_string(score), "sma", { 255, 255, 255 }); timeT = new Text(Vec2(30, 130), std::to_string(maxTime / 1000), "sma", { 255, 255, 255 }); } /* Draws everything in game */ void Game::Draw() { platform->RenderClear(); PauseDraw(); platform->RenderPresent(); } /* Draws everything but doesnt render */ void Game::PauseDraw() { lastTime = SDL_GetTicks(); platform->RenderImage(&backGround, Vec2(0, 0)); g->Draw(); scoreText->Draw(); timeText->Draw(); scoreT->Draw(); timeT->Draw(); } /* Initializes everything in game */ void Game::Init() { g = new Graph(); audioManager->PlayMusic("game"); backGround.LoadImage("game"); scoreText = new Text(Vec2(0, 0), "Score", "med", { 255,255,255 }); timeText = new Text(Vec2(0, 100), "Time", "med", { 255,255,255 }); score = 0; lastTime = SDL_GetTicks(); maxTime = 30000; } /* Prepares Game for delete */ void Game::Close() { audioManager->PlayMusic("menu"); } Game::~Game() { }
e56fae6ba380ed1da297de058f74f0fe45811644
b8c59b9861f9a6e598ef69db0f7c2cc1d94a0d57
/meshelement.cpp
24b22023893bc5997eaa08b22c13c544e9d3b05b
[]
no_license
papabricole/minisg
129ea42678557862963e34b9ce50c545a500d0c4
0b762f1814b091fd8a64eba11cc5d1d95a31e531
refs/heads/master
2021-10-10T17:12:29.561601
2019-01-11T11:54:00
2019-01-11T12:23:12
33,010,276
0
0
null
null
null
null
UTF-8
C++
false
false
102
cpp
meshelement.cpp
#include "meshelement.h" namespace msg { ELEMENT_SOURCE(MeshElement) MeshElement::MeshElement() {} }
6f1bd67b2b3f206872eaaa39d31db069e4b74a97
34fa911d40b22428122002e9ba1e4af0721e7704
/main.cpp
59dab36a7e1d432b747de0d05bf8b589248779fe
[]
no_license
CPW-CET/GeneticAlgorithm
66a95a1f5990fe0b477525b7344298952c61642c
5bb397f745c3b32957a890e22d26c69f2237994c
refs/heads/master
2020-06-30T05:44:21.192550
2019-08-06T01:15:32
2019-08-06T01:15:32
200,746,470
0
0
null
null
null
null
UTF-8
C++
false
false
295
cpp
main.cpp
#include "RoboGeneration.h" #include "RoboEvaluator.h" #include "GA.h" int main(void) { RoboEvaluator robotTest; RoboGeneration robotContainer = RoboGeneration(Terminator); GA geneticAlgorithm = GA(robotTest, robotContainer); geneticAlgorithm.start(1000); system("pause"); }
92a6ee7dec185f0c74dd2cee918c5c8ce58d425e
d93fc4deef72b4a5c6484834f45be568504aa682
/101/13/solution0021.cpp
2aa0fd7225fd8fa14445912d1e3c3a957fb8abac
[]
no_license
zhangxiaoya/LeetCodeCPP
55701a80c760f07103244eb21d17c3c43539db81
47388a5bcacd4d8e113c591a02828f6983e8b338
refs/heads/master
2021-09-11T08:56:59.725220
2021-08-29T13:24:18
2021-08-29T13:24:18
37,762,197
1
0
null
2021-05-05T08:52:31
2015-06-20T07:43:27
C++
UTF-8
C++
false
false
628
cpp
solution0021.cpp
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* new_list = new ListNode(); ListNode* l1_p = l1; ListNode* l2_p = l2; ListNode* new_p = new_list; while(l1_p != nullptr && l2_p != nullptr) { if(l1_p->val < l2_p->val) { new_p->next = l1_p; l1_p = l1_p->next; } else { new_p->next = l2_p; l2_p = l2_p->next; } new_p = new_p->next; } new_p->next = l1_p != nullptr ? l1_p : l2_p; return new_list->next; } };
385295592f0d0ab1c8825ee08f8b8acfb4a66f1e
08d157ddf330d75f6bab77a94371a52df6dbc363
/_14LongestCommonPrefix/Solution.h
63e3a2fc0be4187b913fe9e7a2f01dfa0f70d292
[]
no_license
AshburnLee/LeetCode
36bf01ad31dffc724d45db211b957bda5d848e17
585e0d332f4f32227bab8a57189fd57fb7ff4878
refs/heads/master
2020-04-26T01:57:38.345607
2020-03-18T08:31:52
2020-03-18T08:31:52
173,218,599
0
0
null
null
null
null
UTF-8
C++
false
false
537
h
Solution.h
#ifndef _14LONGESTCOMMONPREFIX_SOLUTION_H #define _14LONGESTCOMMONPREFIX_SOLUTION_H #include <iostream> #include <vector> using namespace std; ///time: O(N*M) /// space: O(1) class Solution{ public: string longestCommonPrefix(vector<string>& strs){ if (strs.size() == 0) return ""; string res = ""; for (int i=0; i<strs[0].length(); i++){ char tmp = strs[0][i]; for (int j=0; j<strs.size(); j++){ if (tmp != strs[j][i]) return res; } res.push_back(tmp); } return res; } }; #endif
f527b578f7c66843352daa3a781780b6851899b9
38dbb429a776a6a87a7b25d572c0066505c3ac03
/HackerRank/Week of Code 23/2.Ligithouse/Lighthouse.cpp
9c405dcdd6427a4e9390c9bcf0ddd15c175d7faf
[]
no_license
EulerLee/OJ
796e9d42d000cdc45af478fe664d6235d97772df
7f5c2d4a3def7287f93ce4d1888d5d98f3b4276e
refs/heads/master
2022-11-11T09:14:13.899256
2022-11-03T10:59:26
2022-11-03T10:59:26
66,716,354
7
1
null
2016-09-27T08:02:23
2016-08-27T13:41:30
C++
UTF-8
C++
false
false
1,456
cpp
Lighthouse.cpp
#include <iostream> #include <vector> #include <map> #include <algorithm> #include <cmath> using namespace std; const int N = 51; int size[N][N]; bool rsize(int x, int y, int r, bool mp[][N], int n) { if(r == 0){ if(mp[x][y]){ size[x][y] = 0; return true; } else{ return false; } } else{ if(size[x][y] == r - 1){ for(int i = 0; i != r + 1; ++i){ int j = r * r - i * i; j = (int)sqrt(j); bool flag = true; if(x + i < n + 1 && y + j < n + 1 && x - i > 0 && y - j > 0){ for(int l = x - i; l != x + i + 1; ++l){ if(mp[l][y + j] && mp[l][y - j]){ continue; } else{ return false; } } for(int l = y - j; l != y + j + 1; ++l){ if(mp[x - i][l] && mp[x + i][l]){ continue; } else{ return false; } } continue; } else{ return false; } } size[x][y] = r; return true; } else{ return false; } } } int main() { int n; cin >> n; bool mp[N][N]; char tmp; for(int i = 1; i != n + 1; ++i){ for(int j = 1; j != n + 1; ++j){ size[i][j] = -1; cin >> tmp; if(tmp == '.'){ mp[i][j] = true; } else{ mp[i][j] = false; } } } int ans = 0; for(int i = 1; i != n + 1; ++i){ for(int j = 1; j != n + 1; ++j){ if(mp[i][j]){ for(int r = 0; rsize(i, j, r, mp, n); ++r); if(size[i][j] > ans){ ans = size[i][j]; } } } } cout << ans << endl; }
18bb145f9dca3b4cc28c1b0d913b7cfeed06d354
625824c953d0bc1ef2f19d582b26d2b736f8e090
/Lab1/task2d/task2d.ino
0f8c5ffc6f148417030473cc616dfdda4555a0d6
[]
no_license
munisil1/MyProjects
2dce5d47a4e0d5010bd17ebffd3e050a2536685c
f83b649053dd09cb9068ffb3945fbd8f8ddb6b8c
refs/heads/master
2021-01-01T05:07:35.713567
2018-07-03T04:24:35
2018-07-03T04:24:35
56,271,761
0
0
null
null
null
null
UTF-8
C++
false
false
2,077
ino
task2d.ino
const int switch2 = 8; const int switch3 = 9; int ledPin = 11; // LED connected to digital pin 9 int analogPin = A0; int switchState2 = 0; int switchState3 = 0; int LIGHTControlledLED =0; int LEDsB = 0; int LEDsR = 0; int LEDsG = 0; int sensorValue = 0; void setup() { Serial.begin(9600); pinMode(switch2, INPUT); // FOR SWITCH 2 pinMode(switch3, INPUT); // FOR SWITCH 3 pinMode(4, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(ledPin, OUTPUT); pinMode(analogPin, INPUT); } void loop() { switchState2 = digitalRead(switch2); switchState3 = digitalRead(switch3); LIGHTControlledLED = digitalRead(ledPin); LEDsB = digitalRead(4); LEDsR = digitalRead(6); LEDsG = digitalRead(7); sensorValue = digitalRead(analogPin); if (switchState2 == 0 && switchState3 == 1) Serial.println("\rSWITCH:OFF ON" ); if (switchState2 == 1 && switchState3 == 0) Serial.println("\rSWITCH:ON OFF" ); /* if (switchState2 == 1) Serial.println("SWITCH2:ON" ); delay(1); if (switchState3 == 1) Serial.println("SWITCH3:ON"); if (switchState3 == 0) Serial.println("SWITCH3:OFF"); delay(1); */ Serial.println(LIGHTControlledLED); delay(1); Serial.println(LEDsB); delay(1); Serial.println(LEDsR); delay(1); Serial.println(LEDsG); delay(1); int sensorValue = analogRead(A0); // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V): float voltage = sensorValue * (5.0 / 1023.0); // print out the value you read: Serial.println(voltage); int val = analogRead(analogPin); // read the input pin analogWrite(ledPin, val / 4); if (val <= 900) { // fade in from min to max in increments of 5 points: for (int fadeValue = 0 ; fadeValue <= 1000; fadeValue += 60) { // sets the value (range from 0 to 255): analogWrite(ledPin, fadeValue); // wait for 30 milliseconds to see the dimming effect delay(200); } } if (val > 900) { analogWrite(ledPin, 0); // wait for 30 milliseconds to see the dimming effect delay(200); } }
317b3098333efa564a5827960c22dcf75f01e294
5a1114c18637b1d4a0668759ad7db40d05d24dc4
/c/include/config/csv_parser.h
de3a71b774e34d7c3c85f3cd259be7738ccaff55
[]
no_license
hackerlank/Misc
97f1adadd3d96994e9c6eef4e4bf13c77405e3e7
b09520858128d36c71f10d40fa86c5dbca27549d
refs/heads/master
2021-01-12T06:20:02.709846
2015-10-27T11:11:25
2015-10-27T11:11:25
null
0
0
null
null
null
null
GB18030
C++
false
false
9,607
h
csv_parser.h
#ifndef CSV_PARSER_HPP_INCLUDED #define CSV_PARSER_HPP_INCLUDED #define LIBCSV_PARSER_MAJOR_VERSION 1 #define LIBCSV_PARSER_MINOR_VERSION 0 #define LIBCSV_PARSER_PATCH_VERSION 0 #define LIBCSV_PARSER_VERSION_NUMBER 10000 /* C++ header files */ #include <string> #include <vector> #include <map> /* C header files */ #include <cstdio> #include <cstring> #include <cstdlib> long long atoll_noerror(const char *nptr); class field { public: field( ) {} field(const std::string& value) : m_value(value) {} field(const char*p,size_t len) : m_value(p,len) {} const std::string GetString() const { return m_value; } float GetFloat() const { return static_cast<float>(atof(m_value.c_str())); } operator const unsigned int() const { return (unsigned int) (GetFloat()+0.5); } operator const unsigned long() const { return (unsigned long)(GetFloat()+0.5); } operator const int() const { return int(GetFloat()); } operator const long() const { return int(GetFloat()); } operator const unsigned short() const { return (unsigned short)(GetFloat()+0.5); } operator const short() const { return short(GetFloat()+0.5); } operator const unsigned char() const { return (unsigned char)(GetFloat()+0.5); } operator const char() const { return char(GetFloat()+0.5); } operator const bool() const { return atoi(m_value.c_str()) != 0; } operator const float() const { return GetFloat(); } operator const double() const { return atof(m_value.c_str()); } operator const char*() const { return m_value.c_str(); } //#if defined(_ISOC99_SOURCE) || defined(atoll) vc6 没有long long,现在不考虑vc6,直接提出来使用 operator const long long() const { return atoll_noerror(m_value.c_str()); } //不用+0.5吧 operator const unsigned long long() const { return atoll_noerror(m_value.c_str()); } //#endif protected: const std::string m_value; }; typedef std::vector <std::string> vt_csv_row; typedef std::map <std::string, field> map_csv_row; typedef vt_csv_row * vt_csv_row_ptr; class csv_parser { public : csv_parser() : enclosed_char(0x00), field_term_char('\t'), line_term_char(0x0A), record_count(0U), input_fp(NULL), more_rows(false) { } ~csv_parser() { if(input_fp) { fclose(input_fp); input_fp = NULL; } } bool init(FILE * input_file_pointer) { input_fp = input_file_pointer; if (input_fp == NULL) { fprintf(stderr, "Fatal error : unable to open input file from file pointer\n"); return false; } /* Resetting the internal pointer to the beginning of the stream */ rewind(input_fp); more_rows = true; _get_header(); return true; } bool init(const char * input_file) { #ifdef _WIN32 fopen_s(&input_fp, input_file, "rb"); #else input_fp = fopen(input_file, "rb"); #endif if (input_fp == NULL) { fprintf(stderr, "Fatal error : unable to open input file %s\n", input_file); return false; } more_rows = true; _get_header(); return true; } void get_row(vt_csv_row& current_row) { current_row.clear(); /* This will store the length of the buffer */ unsigned int line_length = 0U; /* Character array buffer for the current record */ char * line = NULL; /* Grab one record */ _read_single_line(&line, &line_length); _get_fields_with_optional_enclosure(&current_row, line, &line_length); /* Deallocate the current buffer */ free(line); line = NULL; /* Keeps track of how many times this has method has been called */ record_count++; } void get_map_row(map_csv_row& current_row, const vt_csv_row& row) { current_row.clear(); if(row.size() != header_row.size()) { return; } for(unsigned int i = 0; i < header_row.size(); ++i) { current_row.insert(std::pair<std::string, std::string>(header_row[i], row[i])); } } bool has_more_rows(void) { return more_rows; } unsigned int get_record_count(void) { return record_count; } void reset_record_count(void) { record_count = 0U; } private : void _get_header(void) { if(has_more_rows()) { get_row(header_row); } record_count = 0U; } void _get_fields_with_optional_enclosure(vt_csv_row_ptr row, const char * line, const unsigned int * line_length) { char * field = NULL; /* * How to extract the fields, when the enclosure char is optional. * * This is very similar to parsing the document without enclosure but with the following conditions. * * If the beginning char is an enclosure character, adjust the starting position of the string by + 1. * If the ending char is an enclosure character, adjust the ending position by -1 */ if (*line_length > 0) { field = (char *) malloc(*line_length); memset(field, 0, *line_length); register unsigned int field_start = 0U; register unsigned int field_end = 0U; register unsigned int char_pos = 0U; while(char_pos < *line_length) { char curr_char = line[char_pos]; if (curr_char == field_term_char) { field_end = char_pos; const char * field_starts_at = line + field_start; /* Field width must exclude field delimiter characters */ unsigned int field_width = field_end - field_start; const char line_first_char = field_starts_at[0]; const char line_final_char = field_starts_at[field_width - 1]; /* If the enclosure char is found at either ends of the string */ unsigned int first_adjustment = (line_first_char == enclosed_char) ? 1U : 0U; unsigned int final_adjustment = (line_final_char == enclosed_char) ? 2U : 0U; /* We do not want to have any negative or zero field widths */ field_width = (field_width > 2U) ? (field_width - final_adjustment) : field_width; /* Copy exactly field_width bytes from field_starts_at to field */ memcpy(field, field_starts_at + first_adjustment, field_width); /* This must be a null-terminated character array */ field[field_width] = 0x00; std::string field_string_obj = field; row->push_back(field_string_obj); /* This is the starting point of the next field */ field_start = char_pos + 1; } else if (curr_char == line_term_char) { field_end = char_pos; const char * field_starts_at = line + field_start; /* Field width must exclude line terminating characters */ unsigned int field_width = field_end - field_start; const char line_first_char = field_starts_at[0]; const char line_final_char = field_starts_at[field_width - 1]; /* If the enclosure char is found at either ends of the string */ unsigned int first_adjustment = (line_first_char == enclosed_char) ? 1U : 0U; unsigned int final_adjustment = (line_final_char == enclosed_char) ? 2U : 0U; /* We do not want to have any negative or zero field widths */ field_width = (field_width > 2U) ? (field_width - final_adjustment) : field_width; /* Copy exactly field_width bytes from field_starts_at to field */ memcpy(field, field_starts_at + first_adjustment, field_width); /* This must be a null-terminated character array */ field[--field_width] = 0x00; std::string field_string_obj = field; row->push_back(field_string_obj); } /* Move to the next character in the current line */ char_pos++; } /* Deallocate memory for field buffer */ free(field); field = NULL; } } void _read_single_line(char ** buffer, unsigned int * buffer_len) { long int original_pos = ftell(input_fp); long int current_pos = original_pos; register int current_char = 0; /* Checking one character at a time until the end of a line is found */ while(true) { current_char = fgetc(input_fp); if (current_char == EOF) { /* We have reached the end of the file */ more_rows = false; break; } else if (current_char == line_term_char) { /* We have reached the end of the row */ current_pos++; break; } else { current_pos++; } } /* Let's try to peek one character ahead to see if we are at the end of the file */ if (more_rows) { current_char = fgetc(input_fp); more_rows = (current_char == EOF) ? false : true; } /* Find out how long this row is */ const size_t length_of_row = current_pos - original_pos; if (length_of_row > 0) { *buffer_len = length_of_row * sizeof(char) + 1; *buffer = (char *) realloc(*buffer, *buffer_len); memset(*buffer, 0, *buffer_len); /* Reset the internal pointer to the original position */ fseek(input_fp, original_pos, SEEK_SET); /* Copy the contents of the line into the buffer */ fread(*buffer, 1, length_of_row, input_fp); } } protected : char enclosed_char; char field_term_char; char line_term_char; unsigned int record_count; FILE * input_fp; bool more_rows; vt_csv_row header_row; }; #endif /* CSV_PARSER_HPP_INCLUDED */
78a95a8976e180314902d47b4fec7f5bff413fc3
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_3272_httpd-2.2.11.cpp
9a3c86481ca6b630be0b52caaa8d415dbe5e8125
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
124
cpp
httpd_repos_function_3272_httpd-2.2.11.cpp
static int apr_ldap_rebind_set_callback(LDAP *ld) { ldap_set_rebind_proc(ld, LDAP_rebindproc); return APR_SUCCESS; }
624a321511883273d79f625cbb38d5507e36abda
2aa7bec41df19555583353ba5216c05b6ec1f5fa
/Practice/Task22.cpp
10fdaf679d6c9071569b48c55a52b0e0699c44d4
[]
no_license
Mauz33/progworks
c67dc58b4516f5ef60f64cdd425e197f8566781d
5fdbab5b4a11ac88caf76bf72247c4ed15e4ca88
refs/heads/master
2020-07-27T12:42:45.818552
2020-06-20T02:23:09
2020-06-20T02:23:09
209,092,929
0
2
null
null
null
null
UTF-8
C++
false
false
797
cpp
Task22.cpp
#include <iostream> using namespace std; void swap(int* digit1, int* digit2) { int t = *digit1; *digit1 = *digit2; *digit2 = t; } void info(const int* digit) { cout << "Адрес: " << digit << "; Значение: " << *digit << ";" << endl; } int msort(int* digit1, int* digit2, int* digit3) { if (*digit3 < *digit2) swap(digit3, digit2); if (*digit3 < *digit1) swap(digit3, digit1); if (*digit2 < *digit1) swap(digit2, digit1); return *digit3; } int* add(int* digit1, const int* digit2) { *digit1 = *digit1 + *digit2; return digit1; } int main() { setlocale(LC_ALL, ""); int a = 1, b = 2, c = 3; info(&a); info(&b); info(&c); cout << "Максимум: " << msort(&a, &b, &c) << endl; info(add(&b, add(&a, &c) )); system("pause"); }
b5644b96a7563ce4f243030ccd3118ba4d984908
34c3ad47dc82696e0c66b9b49c2f7d90da9e26b6
/Video_Synopsis_Win.cpp
e14ab2ac1adc1d576bfee5f8c12f04000a18c7c1
[]
no_license
xwyangjshb/video_synopsis
1da77493d2b34a3ec5c34c95e8865ae33d66914d
8a617c8bfc2aac5e85aae5daa2d059f6adb23a1e
refs/heads/master
2021-01-12T01:01:38.876888
2016-05-18T13:15:31
2016-05-18T13:15:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,593
cpp
Video_Synopsis_Win.cpp
// Video_Synopsis_Win.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Video_Synopsis_Win.h" #include "synopsis.h" #include "bspline.h" #include <cv.h> #include <highgui.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <opencv2/opencv.hpp> #include <vector> #include <opencv2/video/background_segm.hpp> #ifdef _DEBUG #define new DEBUG_NEW #endif // The one and only application object CWinApp theApp; using namespace cv; using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; HMODULE hModule = ::GetModuleHandle(NULL); if (hModule != NULL) { // initialize MFC and print and error on failure if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0)) { // TODO: change error code to suit your needs _tprintf(_T("Fatal Error: MFC initialization failed\n")); nRetCode = 1; } else { // TODO: code your application's behavior here. } } else { // TODO: change error code to suit your needs _tprintf(_T("Fatal Error: GetModuleHandle failed\n")); nRetCode = 1; } char file_path[] = "E:\\video_synopsis_data\\001_M_150908080000_20160106144225.avi"; const char file_out_path[] = "E:\\video_synopsis_out\\20150804081124_20150804084125.avi"; int fps, frame_number; tube_database s_database; //s_database = buildTrackDB_KNN(file_path); refineDB_Mat(s_database); reArrangeDB(s_database, file_path); return 0; }
447c63e8c0b2f59decfe8d6734a772ab91b16100
98ba4eca2871f8178c74d327b8c992526859c826
/printer/objects/point_octree_object.h
f84e104955bc7c6072307f00d095cfba2a6eaa88
[ "BSD-3-Clause" ]
permissive
chrisvana/printer
0a34de6cb24e53f9c78494306ca380d35493b127
13435848fc9429541e8607b7bb65220798d5db5e
refs/heads/master
2021-05-02T10:33:08.842890
2018-01-28T05:12:44
2018-01-28T05:12:44
35,244,428
6
5
null
null
null
null
UTF-8
C++
false
false
1,122
h
point_octree_object.h
// Copyright 2015 // Author: Christopher Van Arsdale #ifndef _PRINTER_OBJECTS_POINT_OCTREE_OBJECT_H__ #define _PRINTER_OBJECTS_POINT_OCTREE_OBJECT_H__ #include <memory> #include <string> #include "printer/base/geometry.h" #include "printer/objects/object.h" #include "printer/base/point_octree.h" namespace printer { class PointOctreeObject : public PrintObject { public: typedef PointList::PointMode PointMode; static PointMode FromString(const std::string& name) { return PointList::FromString(name); } explicit PointOctreeObject(double horizontal_resolution, double vertical_resolution, PointMode mode, PointOctree* octree); virtual ~PointOctreeObject(); virtual float ISOValue(const Point& p); virtual bool BoundingBox(Box* b); virtual bool FullyContains(const Box& box) { return false; } virtual bool ThreadSafe() { return true; } private: PointMode mode_; Point expand_; std::unique_ptr<PointOctree> octree_; }; } // namespace printer #endif // _PRINTER_OBJECTS_POINT_OCTREE_OBJECT_H__
56d8184fe4361b06e445ff675f8bf5fe35ba82ff
b4dd54123785b310d03a88835a19fcee77b38b65
/src/SourceString.h
4e84a150ec033bae732a482bc852b64b4724da67
[ "MIT" ]
permissive
tidyverse/readr
5b8a49899586ab0a7a28108b9a0ef634e60940d5
80e4dc1a8e48571323cdec8703d31eb87308eb01
refs/heads/main
2023-08-31T01:10:09.896284
2023-08-01T20:02:52
2023-08-01T20:02:52
11,663,980
631
271
NOASSERTION
2023-09-03T11:49:42
2013-07-25T15:28:22
R
UTF-8
C++
false
false
786
h
SourceString.h
#ifndef FASTREAD_SOURCESTRING_H_ #define FASTREAD_SOURCESTRING_H_ #include "cpp11/strings.hpp" #include "Source.h" class SourceString : public Source { cpp11::sexp string_; const char* begin_; const char* end_; public: SourceString( cpp11::strings x, int skip = 0, bool skipEmptyRows = true, const std::string& comment = "", bool skipQuotes = true) : string_(static_cast<SEXP>(x[0])) { begin_ = CHAR(string_); end_ = begin_ + Rf_xlength(string_); // Skip byte order mark, if needed begin_ = skipBom(begin_, end_); // Skip lines, if needed begin_ = skipLines(begin_, end_, skip, skipEmptyRows, comment, skipQuotes); } const char* begin() { return begin_; } const char* end() { return end_; } }; #endif
69579f07bf99d9ced06650877e3a9ca3a9d0b605
72852e07bb30adbee608275d6048b2121a5b9d82
/algorithms/problem_1198/leetcode2.cpp
2dd52af396b02c509644321e29f28b944c46e1a8
[]
no_license
drlongle/leetcode
e172ae29ea63911ccc3afb815f6dbff041609939
8e61ddf06fb3a4fb4a4e3d8466f3367ee1f27e13
refs/heads/master
2023-01-08T16:26:12.370098
2023-01-03T09:08:24
2023-01-03T09:08:24
81,335,609
0
0
null
null
null
null
UTF-8
C++
false
false
452
cpp
leetcode2.cpp
class Solution { public: int smallestCommonElement(vector<vector<int>>& mat) { int n = mat.size(), m = mat[0].size(); for (int j = 0; j < m; ++j) { bool found = true; for (int i = 1; i < n && found; ++i) { found = binary_search(begin(mat[i]), end(mat[i]), mat[0][j]); } if (found) { return mat[0][j]; } } return -1; } };
702c45989d851b66804556567d84d2a8cba4be7e
5d69a42f8d21bf5fc1042fee7e4e0d0a9503d7ba
/Chkdraft/src/UnitChange.cpp
9683036e0cbf08f78686bd10e47b51566821696b
[ "MIT" ]
permissive
saintofidiocy/Chkdraft
b90da8f3030f9bab88dc147717c8d6b353e3d947
290b232f2b9e09ce60779af6e4e78e9bd3b65a51
refs/heads/master
2021-01-17T05:23:21.331783
2016-04-16T18:57:45
2016-04-16T18:57:45
51,184,424
0
0
null
2016-03-01T06:44:14
2016-02-06T01:26:51
C++
UTF-8
C++
false
false
461
cpp
UnitChange.cpp
#include "UnitChange.h" #include "GuiMap.h" UnitChange::UnitChange(u16 unitIndex, ChkUnitField field, u32 data) : unitIndex(unitIndex), field(field), data(data) { } void UnitChange::Reverse(void *guiMap) { u32 replacedData = ((GuiMap*)guiMap)->GetUnitFieldData(unitIndex, field); ((GuiMap*)guiMap)->SetUnitFieldData(unitIndex, field, data); data = replacedData; } int32_t UnitChange::GetType() { return (int32_t)UndoTypes::UnitChange; }
e51f7ab092ebe3c97cb063711b1eda5cc4065c54
0e3b2c20d82947824392ebfdf1f0a638849c5d08
/DMOJ/acc4p3.cpp
a1587e45578dfab1e6cc120221cbfd81197d897f
[ "Unlicense" ]
permissive
starfy84/Competitive-Programming
d00c730b52bd5fc89f6cd52c5c02a51f9bbbe453
6e024caaf1568723e4eebab208baf366c57830e1
refs/heads/master
2020-05-01T07:14:53.028116
2019-06-22T22:56:03
2019-06-22T22:56:03
177,347,914
0
0
null
null
null
null
UTF-8
C++
false
false
128
cpp
acc4p3.cpp
#include <bits/stdc++.h> using namespace std; bool f(int N){ return sqrt(N) == (int)sqrt(N); } int main() { return 0; }
dd86892b869d225b9ba2d5f10f8a6aba0f10ed1d
e0cd8d28330837235f0d0ddb434b18278cd9dab9
/C++ Scripts/hpjoinsinlges.cpp
2cffc94133e71d04cffcdbde283bd0c7f8e0ca59
[]
no_license
armatita/Scripts-Cplusplus
3e8a0c2bbde9328c0bf88f585e67bd55bd3c8dfe
0a993f15cb48877676300756135ec44ed964d549
refs/heads/master
2021-01-20T05:07:46.238898
2015-07-20T19:45:11
2015-07-20T19:45:11
39,397,887
0
0
null
null
null
null
UTF-8
C++
false
false
2,040
cpp
hpjoinsinlges.cpp
/* * hpjoinsinlges.cpp * * Created on: 2 de Abr de 2011 * Author: pedro.correia */ #include <algorithm> #include "iostream" #include <new> #include "fstream" #include "unistd.h" #include "errno.h" #include "math.h" #include <ctype.h> using namespace std; int main() { cout << "******************************************************\n"; cout << "Starting join single columned files algorithm.\n"; cout << "******************************************************\n"; char conf[256]="singlecolumned.pin"; char filename[1024]; // Caminho e nome do ficheiro de saida. char filename2[1024]; // Abrir ficheiro de entrada e ficheiro de saida. //FILE *inputfile; FILE *inputfile; FILE *outputfile; FILE *fileconf; char c; char cwd[1024]; getcwd(cwd,sizeof(cwd)); cout << cwd << endl; if ((fileconf=fopen(conf,"r"))==NULL){ cout << "Can't find CONF file: " << conf << "\n"; return 1; } int header; int many; int i=0; int j=0; int h; fscanf(fileconf,"%d\n",&header); while (c!='\n'){ c=fgetc(fileconf); if (c!='\n'){ filename2[i]=c; } i++; } outputfile=fopen(filename2,"w"); fscanf(fileconf,"%d\n",&many); fprintf(outputfile,"Joined_%d_files_in_one_singled_columned\n1\nvariable\n",many); while (j<many){ i=0; c='a'; while (c!='\n'){ c=fgetc(fileconf); if (c!='\n'){ filename[i]=c; i++; } } while (i<1024){ filename[i]=NULL; i++; } cout << "Joining file " << filename <<" ("<< j+1 << " from " << many <<")."<< endl; inputfile=fopen(filename,"r"); h=0; while (h<header){ c=fgetc(inputfile); // fgetc receives char by char from file instead of string or stream. if (c=='\n'){h=h+1;} // When the char is equal to '\n' then we've reached a new row. } while (!feof(inputfile)){ // While does not reach end of file symbol (eof or feof)... c=fgetc(inputfile); // Still gathering char by char from file. if (feof(inputfile)){break;} fprintf(outputfile,"%c",c); } fclose(inputfile); j++; } cout << "Finished.\n"; return 0; }
33c4645cb57a8343a1cd2a715d467bb570e77b43
3dcbea79be00ee3a14e45a0d5b7d9d6792803197
/Source Files/Main.cpp
c06cb9ed01714c41f6dc27ff0685f05e86f3db8f
[]
no_license
JoulesCH/practica_1
54f8c31a48c8e946919b3f97c3f38c47379a2a9e
94c32741e03b2245d92f6dd952916d0cfaf04d2e
refs/heads/master
2023-07-28T10:41:12.980537
2021-09-13T05:05:21
2021-09-13T05:05:21
404,914,937
0
0
null
null
null
null
UTF-8
C++
false
false
3,421
cpp
Main.cpp
// BUILT-IN HEADERS #include <stdlib.h> // para malloc #include <string.h> // unicamente para strcat #include <stdio.h> #include <wchar.h> // para usar caracteres especiales #include <locale.h> // LOCAL HEADERS #include "models.h" // definicion de estructuras usadas #include "readfile.h" // leer el archivo #include "clean.h" // limpiar caracteres especiales #include "split.h" // dividir el texto en plabras #include "count.h" // contar las plabras #include "order.h" // ordenar de mayor a menor frecuencia #include "writefile.h" // escribir el archivo #define MAX_SIZE_FILE_NAME 256 int main(int argc, char * argv[]){ // Se pide argv para recibir los nombres de entrada y salida de los archivos // Configurar el uso de acentos setlocale(LC_ALL, ""); // Inicializacion de la estructura que contiene el texto struct texto Text = {NULL, 0,100}; Text.ptr = (char*) malloc(100*sizeof(char)); int lettersCount; // Contendra el numero de letras en el archivo // Inicializacion de los nombres del archivo de entrada y de salida char *inputFile = (char*) malloc(MAX_SIZE_FILE_NAME*sizeof(char)); char *outputFile = (char*) malloc(MAX_SIZE_FILE_NAME*sizeof(char)); strcpy(outputFile, "OUTPUT_"); if(argc == 1){ //Si el usuario no ingresa ningun argumento, se le solicita el nombre de archivo a leer printf("Ingresa el nombre del archivo a leer: "); fgets(inputFile, MAX_SIZE_FILE_NAME, stdin); inputFile[strlen(inputFile)-1]='\0'; // Se crea el nombre de archivo de salida, con el formato OUTPUT_nombreDelArchivoALeer.txt strcat(outputFile, inputFile); } else if(argc == 2){ // Si el usuario ingresa un argumento, se toma como el nombre de archivo a leer inputFile = argv[1]; // Se crea el nombre de archivo de salida, con el formato OUTPUT_nombreDelArchivoALeer.txt strcat(outputFile, inputFile); } else if(argc == 3){ // Si el usuario ingresa dos argumentos, se toma el primero como el nombre de archivo a leer // y el segundo como el nombre de archivo de salida inputFile = argv[1]; outputFile = argv[2]; } // Se lee el archivo y se almacena en la estructura Text Text = Read(Text, inputFile, &lettersCount); // Se revisa que el archivo no este en blanco if(Text.ptr == NULL){ printf("Archivo vacio"); return 0; } // limpiar caracteres especiales Clean(&Text, &lettersCount); // Se inicializa la estructura que contendra las palabras Words words ={NULL, 0, lettersCount*10} ; words.ptr = (Word * ) malloc(lettersCount*10*sizeof(Word)); // se divide el texto en palabras y se libera Text.ptr Split(Text, &words, lettersCount); free(Text.ptr); // Se inicializa la estructura que contendran las palabras con su frecuencia Cuentas cuentas ={NULL, 0, lettersCount*10} ; cuentas.ptr = (Cuenta * ) malloc(lettersCount*10*sizeof(Cuenta)); // se cuentan las palabras y se libera words.ptr Count(words, &cuentas); free(words.ptr); // se ordena de mayor a menor frecuencia Order(&cuentas); // se crea el archivo de salida, escribiendolo y liberando cuentas.ptr Write(cuentas, outputFile); free(cuentas.ptr); return 0; }
24d6afd5e59ae92f364b8bdb402ae99a4ac6dd1a
85e968868872cf79e37ff123e3ce045d75f99027
/src/EQL/src/qt_eql.cpp
12f55280f2151394853d62cc0a133e70f4a59047
[ "MIT" ]
permissive
Vladimir-Lin/QtLISP
b13bddfddefdd6edc11e5a4eab437af478323f63
865043f877d2a20f4418830018a278a384af7bbd
refs/heads/main
2023-06-15T22:26:50.669739
2021-06-16T09:22:56
2021-06-16T09:22:56
377,439,250
1
0
null
null
null
null
UTF-8
C++
false
false
3,636
cpp
qt_eql.cpp
// copyright (c) Polos Ruetz // see Qt_EQL, Qt_EQL_dynamic, QtWebKit: JavaScript / Lisp bridge #include <QtGui> #include <ecl/ecl.h> #include "qt_eql.h" #include "ecl_fun.h" #include "eql.h" #include "gen/_lobjects.h" QT_BEGIN_NAMESPACE #define PUSH_ARG(x, list) list = CONS(to_lisp_arg(qMakePair(QByteArray(x.name()), x.data())), list) static QHash<QByteArray, void*> lisp_functions; static cl_object eql_fun(cl_object l_fun, cl_object l_args) { cl_object l_ret = Cnil; const cl_env_ptr l_env = ecl_process_env(); CL_CATCH_ALL_BEGIN(l_env) { CL_UNWIND_PROTECT_BEGIN(l_env) { l_ret = cl_apply(2, l_fun, l_args); } CL_UNWIND_PROTECT_EXIT {} CL_UNWIND_PROTECT_END; } CL_CATCH_ALL_END; return l_ret; } static QVariant eql_fun2(const QByteArray& pkgFun, int ret_type, const QGenericArgument& a1, const QGenericArgument& a2, const QGenericArgument& a3, const QGenericArgument& a4, const QGenericArgument& a5, const QGenericArgument& a6, const QGenericArgument& a7, const QGenericArgument& a8, const QGenericArgument& a9, const QGenericArgument& a10) { void* symbol = lisp_functions.value(pkgFun); if(!symbol) { int p = pkgFun.indexOf(':'); QByteArray pkg = (p == -1) ? "eql-user" : pkgFun.left(p); QByteArray fun = pkgFun.mid(pkgFun.lastIndexOf(':') + 1); cl_object l_sym = cl_find_symbol(2, make_constant_base_string(fun.toUpper().constData()), cl_find_package(make_constant_base_string(pkg.toUpper().constData()))); if(l_sym != Cnil) { symbol = (void*)l_sym; lisp_functions[pkgFun] = symbol; }} cl_object l_args = Cnil; if(a1.name()) { PUSH_ARG(a1, l_args); if(a2.name()) { PUSH_ARG(a2, l_args); if(a3.name()) { PUSH_ARG(a3, l_args); if(a4.name()) { PUSH_ARG(a4, l_args); if(a5.name()) { PUSH_ARG(a5, l_args); if(a6.name()) { PUSH_ARG(a6, l_args); if(a7.name()) { PUSH_ARG(a7, l_args); if(a8.name()) { PUSH_ARG(a8, l_args); if(a9.name()) { PUSH_ARG(a9, l_args); if(a10.name()) { PUSH_ARG(a10, l_args); }}}}}}}}}} l_args = cl_nreverse(l_args); QVariant ret; if(symbol) { cl_object l_ret = eql_fun((cl_object)symbol, l_args); if(ret_type != -1) { ret = toQVariant(l_ret, 0, ret_type); } return ret; } error_msg(QString("eql_fun(): %1").arg(QString(pkgFun)).toAscii().constData(), l_args); return ret; } void eql_fun(const QByteArray& fun, QGenericArgument a1, QGenericArgument a2, QGenericArgument a3, QGenericArgument a4, QGenericArgument a5, QGenericArgument a6, QGenericArgument a7, QGenericArgument a8, QGenericArgument a9, QGenericArgument a10) { return (void)eql_fun2(fun, -1, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); } QVariant eql_fun(const QByteArray& fun, int ret_type, QGenericArgument a1, QGenericArgument a2, QGenericArgument a3, QGenericArgument a4, QGenericArgument a5, QGenericArgument a6, QGenericArgument a7, QGenericArgument a8, QGenericArgument a9, QGenericArgument a10) { return eql_fun2(fun, ret_type, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); } bool eql_check_type(int id, const QByteArray& name) { return LObjects::checkType(id, name); } QT_END_NAMESPACE
7b30b4c0701d7891c6a4a14997edbb982588fd6d
e9232b22c0a516a9f548ecd845496598c278ea64
/ViewshedTestSuite/Observer.h
77cd3fbfb035fb11724ccfe700632916aa4d4a5a
[]
no_license
Anecoz/ViewshedTestSuite
24ac5f61c75fe8f092aed9576b68086f85132db2
e69deb0f9ee22c0d1157894a8782311f0202b5cc
refs/heads/master
2021-01-24T17:47:58.497964
2016-05-17T05:34:14
2016-05-17T05:34:14
50,833,783
0
0
null
null
null
null
UTF-8
C++
false
false
714
h
Observer.h
#pragma once #include <GL\glew.h> #include <GL\freeglut.h> #include <glm\glm.hpp> #include "Shader.h" #include "Camera.h" #include "KeyboardHandler.h" #include "DrawableModel.h" // Abstraction for observer, includes a model and position and its own shader class Observer { public: Observer(glm::vec3 pos, DrawableModel *simpleModel, Shader &simpleShader); Observer(); ~Observer(); void render(glm::mat4& proj, glm::mat4& camMatrix); void init(); void setPos(glm::vec3); glm::vec3 getPos(); void tick(KeyboardHandler*); void setColor(glm::vec3); private: // MEMBER VARIABLES glm::vec3 pos; Shader shader; glm::vec3 color = glm::vec3(1.0, 0.0, 0.0); // MEMBER OBJECTS DrawableModel *model; };
a2138798f59e9abfe6b92cb22abc3880e7c7df17
4ff6ae333e5776c8321c355d62c78c0bcd2e19b5
/src/herder/TransactionQueue.cpp
b889369b715d1e3e284b5511ffe13b0c5dc9981e
[ "Apache-2.0", "BSD-3-Clause", "MIT", "BSL-1.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
5l1v3r1/stellar-core
3b919dca02a01d4da239cb53fa6816c112e92e7d
0a39daba20797e0f8a73a76b32c6f2ca09ba483c
refs/heads/master
2022-04-09T18:59:13.866885
2020-03-25T17:40:17
2020-03-25T17:40:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,635
cpp
TransactionQueue.cpp
// Copyright 2019 Stellar Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "herder/TransactionQueue.h" #include "crypto/SecretKey.h" #include "ledger/LedgerManager.h" #include "ledger/LedgerTxn.h" #include "main/Application.h" #include "transactions/FeeBumpTransactionFrame.h" #include "transactions/TransactionBridge.h" #include "transactions/TransactionUtils.h" #include "util/HashOfHash.h" #include "util/XDROperators.h" #include <algorithm> #include <lib/util/format.h> #include <medida/meter.h> #include <medida/metrics_registry.h> #include <numeric> namespace stellar { const int64_t TransactionQueue::FEE_MULTIPLIER = 10; TransactionQueue::TransactionQueue(Application& app, int pendingDepth, int banDepth, int poolLedgerMultiplier) : mApp(app) , mPendingDepth(pendingDepth) , mBannedTransactions(banDepth) , mLedgerVersion(app.getLedgerManager() .getLastClosedLedgerHeader() .header.ledgerVersion) , mPoolLedgerMultiplier(poolLedgerMultiplier) { for (auto i = 0; i < pendingDepth; i++) { mSizeByAge.emplace_back(&app.getMetrics().NewCounter( {"herder", "pending-txs", fmt::format("age{}", i)})); } } static bool canReplaceByFee(TransactionFrameBasePtr tx, TransactionFrameBasePtr oldTx) { int64_t newFee = tx->getFeeBid(); uint32_t newNumOps = std::max<uint32_t>(1, tx->getNumOperations()); int64_t oldFee = oldTx->getFeeBid(); uint32_t oldNumOps = std::max<uint32_t>(1, oldTx->getNumOperations()); // newFee / newNumOps >= FEE_MULTIPLIER * oldFee / oldNumOps // is equivalent to // newFee * oldNumOps >= FEE_MULTIPLIER * oldFee * newNumOps // // FEE_MULTIPLIER * v2 does not overflow uint128_t because fees are bounded // by INT64_MAX, while number of operations and FEE_MULTIPLIER are small. auto v1 = bigMultiply(newFee, oldNumOps); auto v2 = bigMultiply(oldFee, newNumOps); return v1 >= TransactionQueue::FEE_MULTIPLIER * v2; } static bool findBySeq(TransactionFrameBasePtr tx, TransactionQueue::Transactions& transactions, TransactionQueue::Transactions::iterator& iter) { int64_t seq = tx->getSeqNum(); int64_t firstSeq = transactions.front()->getSeqNum(); int64_t lastSeq = transactions.back()->getSeqNum(); if (seq < firstSeq || seq > lastSeq + 1) { return false; } assert(seq - firstSeq <= static_cast<int64_t>(transactions.size())); iter = transactions.begin() + (seq - firstSeq); assert(iter == transactions.end() || (*iter)->getSeqNum() == seq); return true; } static bool isDuplicateTx(TransactionFrameBasePtr oldTx, TransactionFrameBasePtr newTx) { auto const& oldEnv = oldTx->getEnvelope(); auto const& newEnv = newTx->getEnvelope(); if (oldEnv.type() == newEnv.type()) { return oldTx->getFullHash() == newTx->getFullHash(); } else if (oldEnv.type() == ENVELOPE_TYPE_TX_FEE_BUMP) { auto oldFeeBump = std::static_pointer_cast<FeeBumpTransactionFrame>(oldTx); return oldFeeBump->getInnerFullHash() == newTx->getFullHash(); } return false; } TransactionQueue::AddResult TransactionQueue::canAdd(TransactionFrameBasePtr tx, AccountStates::iterator& stateIter, Transactions::iterator& oldTxIter) { if (isBanned(tx->getFullHash())) { return TransactionQueue::AddResult::ADD_STATUS_TRY_AGAIN_LATER; } int64_t netFee = tx->getFeeBid(); int64_t netOps = tx->getNumOperations(); int64_t seqNum = 0; stateIter = mAccountStates.find(tx->getSourceID()); if (stateIter != mAccountStates.end()) { auto& transactions = stateIter->second.mTransactions; oldTxIter = transactions.end(); if (!transactions.empty()) { if (tx->getEnvelope().type() != ENVELOPE_TYPE_TX_FEE_BUMP) { Transactions::iterator iter; if (findBySeq(tx, transactions, iter) && iter != transactions.end() && isDuplicateTx(*iter, tx)) { return TransactionQueue::AddResult::ADD_STATUS_DUPLICATE; } seqNum = transactions.back()->getSeqNum(); } else { if (!findBySeq(tx, transactions, oldTxIter)) { tx->getResult().result.code(txBAD_SEQ); return TransactionQueue::AddResult::ADD_STATUS_ERROR; } if (oldTxIter != transactions.end()) { // Replace-by-fee logic if (isDuplicateTx(*oldTxIter, tx)) { return TransactionQueue::AddResult:: ADD_STATUS_DUPLICATE; } if (!canReplaceByFee(tx, *oldTxIter)) { tx->getResult().result.code(txINSUFFICIENT_FEE); return TransactionQueue::AddResult::ADD_STATUS_ERROR; } netOps -= (*oldTxIter)->getNumOperations(); int64_t oldFee = (*oldTxIter)->getFeeBid(); if ((*oldTxIter)->getFeeSourceID() == tx->getFeeSourceID()) { netFee -= oldFee; } } seqNum = tx->getSeqNum() - 1; } } } if (netOps + mQueueSizeOps > maxQueueSizeOps()) { ban({tx}); return TransactionQueue::AddResult::ADD_STATUS_TRY_AGAIN_LATER; } LedgerTxn ltx(mApp.getLedgerTxnRoot()); if (!tx->checkValid(ltx, seqNum)) { return TransactionQueue::AddResult::ADD_STATUS_ERROR; } // Note: stateIter corresponds to getSourceID() which is not necessarily // the same as getFeeSourceID() auto feeSource = stellar::loadAccount(ltx, tx->getFeeSourceID()); auto feeStateIter = mAccountStates.find(tx->getFeeSourceID()); int64_t totalFees = feeStateIter == mAccountStates.end() ? 0 : feeStateIter->second.mTotalFees; if (getAvailableBalance(ltx.loadHeader(), feeSource) - netFee < totalFees) { tx->getResult().result.code(txINSUFFICIENT_BALANCE); return TransactionQueue::AddResult::ADD_STATUS_ERROR; } return TransactionQueue::AddResult::ADD_STATUS_PENDING; } void TransactionQueue::releaseFeeMaybeEraseAccountState(TransactionFrameBasePtr tx) { auto iter = mAccountStates.find(tx->getFeeSourceID()); assert(iter != mAccountStates.end() && iter->second.mTotalFees >= tx->getFeeBid()); iter->second.mTotalFees -= tx->getFeeBid(); if (iter->second.mTransactions.empty()) { if (iter->second.mTotalFees == 0) { mAccountStates.erase(iter); } } } TransactionQueue::AddResult TransactionQueue::tryAdd(TransactionFrameBasePtr tx) { AccountStates::iterator stateIter; Transactions::iterator oldTxIter; auto const res = canAdd(tx, stateIter, oldTxIter); if (res != TransactionQueue::AddResult::ADD_STATUS_PENDING) { return res; } if (stateIter == mAccountStates.end()) { stateIter = mAccountStates.emplace(tx->getSourceID(), AccountState{}).first; oldTxIter = stateIter->second.mTransactions.end(); } if (oldTxIter != stateIter->second.mTransactions.end()) { releaseFeeMaybeEraseAccountState(*oldTxIter); stateIter->second.mQueueSizeOps -= (*oldTxIter)->getNumOperations(); mQueueSizeOps -= (*oldTxIter)->getNumOperations(); *oldTxIter = tx; } else { stateIter->second.mTransactions.emplace_back(tx); mSizeByAge[stateIter->second.mAge]->inc(); } stateIter->second.mQueueSizeOps += tx->getNumOperations(); mQueueSizeOps += tx->getNumOperations(); mAccountStates[tx->getFeeSourceID()].mTotalFees += tx->getFeeBid(); return res; } void TransactionQueue::removeAndReset(TransactionQueue::Transactions const& dropTxs) { for (auto const& tx : dropTxs) { auto extracted = extract(tx, true); if (extracted.first != std::end(mAccountStates)) { extracted.first->second.mAge = 0; } } } void TransactionQueue::ban(TransactionQueue::Transactions const& dropTxs) { auto& bannedFront = mBannedTransactions.front(); for (auto const& tx : dropTxs) { auto extractResult = extract(tx, false); if (extractResult.second.empty()) { // tx was not in the queue bannedFront.insert(tx->getFullHash()); } else { // tx was in the queue, and may have caused other transactions to // get dropped as well for (auto const& extracted : extractResult.second) { bannedFront.insert(extracted->getFullHash()); } } } } TransactionQueue::FindResult TransactionQueue::find(TransactionFrameBasePtr const& tx) { auto const& acc = tx->getSourceID(); auto accIt = mAccountStates.find(acc); if (accIt == std::end(mAccountStates)) { return {std::end(mAccountStates), {}}; } auto& txs = accIt->second.mTransactions; auto txIt = std::find_if(std::begin(txs), std::end(txs), [&](auto const& t) { return tx->getSeqNum() == t->getSeqNum(); }); if (txIt == std::end(txs)) { return {std::end(mAccountStates), {}}; } if ((*txIt)->getFullHash() != tx->getFullHash()) { return {std::end(mAccountStates), {}}; } return {accIt, txIt}; } TransactionQueue::ExtractResult TransactionQueue::extract(TransactionFrameBasePtr const& tx, bool keepBacklog) { std::vector<TransactionFrameBasePtr> removedTxs; // Use a scope here to prevent iterator use after invalidation { auto it = find(tx); if (it.first == mAccountStates.end()) { return {std::end(mAccountStates), {}}; } auto txIt = it.second; auto txRemoveEnd = txIt + 1; if (!keepBacklog) { // remove everything passed tx txRemoveEnd = it.first->second.mTransactions.end(); } std::move(txIt, txRemoveEnd, std::back_inserter(removedTxs)); it.first->second.mTransactions.erase(txIt, txRemoveEnd); mSizeByAge[it.first->second.mAge]->dec(removedTxs.size()); } for (auto const& removedTx : removedTxs) { mAccountStates[removedTx->getSourceID()].mQueueSizeOps -= removedTx->getNumOperations(); mQueueSizeOps -= removedTx->getNumOperations(); releaseFeeMaybeEraseAccountState(removedTx); } // tx->getSourceID() will only be in mAccountStates if it has pending // transactions or if it is the fee source for a transaction for which it is // not the sequence number source auto accIt = mAccountStates.find(tx->getSourceID()); if (accIt != mAccountStates.end() && accIt->second.mTransactions.empty()) { if (accIt->second.mTotalFees == 0) { mAccountStates.erase(accIt); accIt = mAccountStates.end(); } else { accIt->second.mAge = 0; } } return {accIt, std::move(removedTxs)}; } TransactionQueue::AccountTxQueueInfo TransactionQueue::getAccountTransactionQueueInfo( AccountID const& accountID) const { auto i = mAccountStates.find(accountID); if (i == std::end(mAccountStates)) { return {0, 0, 0, 0}; } auto const& txs = i->second.mTransactions; auto seqNum = txs.empty() ? 0 : txs.back()->getSeqNum(); return {seqNum, i->second.mTotalFees, i->second.mQueueSizeOps, i->second.mAge}; } void TransactionQueue::shift() { mBannedTransactions.pop_back(); mBannedTransactions.emplace_front(); auto sizes = std::vector<int64_t>{}; sizes.resize(mPendingDepth); auto& bannedFront = mBannedTransactions.front(); auto end = std::end(mAccountStates); auto it = std::begin(mAccountStates); while (it != end) { // If mTransactions is empty then mAge is always 0. This can occur if an // account is the fee-source for at least one transaction but not the // sequence-number-source for any transaction in the TransactionQueue. if (!it->second.mTransactions.empty()) { ++it->second.mAge; } if (mPendingDepth == it->second.mAge) { for (auto const& toBan : it->second.mTransactions) { // This never invalidates it because // !it->second.mTransactions.empty() // otherwise we couldn't have reached this line. releaseFeeMaybeEraseAccountState(toBan); bannedFront.insert(toBan->getFullHash()); } mQueueSizeOps -= it->second.mQueueSizeOps; it->second.mQueueSizeOps = 0; it->second.mTransactions.clear(); if (it->second.mTotalFees == 0) { it = mAccountStates.erase(it); } else { it->second.mAge = 0; } } else { sizes[it->second.mAge] += static_cast<int64_t>(it->second.mTransactions.size()); ++it; } } for (auto i = 0; i < sizes.size(); i++) { mSizeByAge[i]->set_count(sizes[i]); } } int TransactionQueue::countBanned(int index) const { return static_cast<int>(mBannedTransactions[index].size()); } bool TransactionQueue::isBanned(Hash const& hash) const { return std::any_of( std::begin(mBannedTransactions), std::end(mBannedTransactions), [&](std::unordered_set<Hash> const& transactions) { return transactions.find(hash) != std::end(transactions); }); } std::shared_ptr<TxSetFrame> TransactionQueue::toTxSet(LedgerHeaderHistoryEntry const& lcl) const { auto result = std::make_shared<TxSetFrame>(lcl.hash); uint32_t const nextLedgerSeq = lcl.header.ledgerSeq + 1; int64_t const startingSeq = getStartingSequenceNumber(nextLedgerSeq); for (auto const& m : mAccountStates) { for (auto const& tx : m.second.mTransactions) { result->add(tx); // This condition implements the following constraint: there may be // any number of transactions for a given source account, but all // transactions must satisfy one of the following mutually exclusive // conditions // - sequence number <= startingSeq - 1 // - sequence number >= startingSeq if (tx->getSeqNum() == startingSeq - 1) { break; } } } return result; } std::vector<TransactionQueue::ReplacedTransaction> TransactionQueue::maybeVersionUpgraded() { std::vector<ReplacedTransaction> res; auto const& lcl = mApp.getLedgerManager().getLastClosedLedgerHeader(); if (mLedgerVersion < 13 && lcl.header.ledgerVersion >= 13) { for (auto& banned : mBannedTransactions) { banned.clear(); } for (auto& kv : mAccountStates) { for (auto& txFrame : kv.second.mTransactions) { auto oldTxFrame = txFrame; auto envV1 = txbridge::convertForV13(txFrame->getEnvelope()); txFrame = TransactionFrame::makeTransactionFromWire( mApp.getNetworkID(), envV1); res.emplace_back(ReplacedTransaction{oldTxFrame, txFrame}); } } } mLedgerVersion = lcl.header.ledgerVersion; return res; } bool operator==(TransactionQueue::AccountTxQueueInfo const& x, TransactionQueue::AccountTxQueueInfo const& y) { return x.mMaxSeq == y.mMaxSeq && x.mTotalFees == y.mTotalFees && x.mQueueSizeOps == y.mQueueSizeOps; } size_t TransactionQueue::maxQueueSizeOps() const { size_t maxOpsLedger = mApp.getLedgerManager().getLastMaxTxSetSizeOps(); maxOpsLedger *= mPoolLedgerMultiplier; return maxOpsLedger; } }
fa4db128d48d5386db24a6c8071ef7f5ae710630
48d9255383b7178e09135a3873f33d399b5fa101
/cefclient/SessionSaveListener.cpp
df0d89ce57e7270be7811e988f369f994399901c
[]
no_license
gitstudionorth/cefplatform
a2ec560e260e2858331f0c0912a7ce05740b757a
e92d27a6a2eeeaf2be41a5a1837acaeea1b53553
refs/heads/master
2020-05-04T14:35:16.700898
2012-10-01T21:38:15
2012-10-01T21:38:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,248
cpp
SessionSaveListener.cpp
#include "SessionSaveListener.h" #include <sstream> #include <string> #include "include/cef_dom.h" #include "cefclient/util.h" #include <direct.h> #include "sqlite3.h" #include "string_util.h" #include "repository.h" namespace binding_test { namespace { const char* kTestUrl = "http://sessions"; const char* kMessageName = "binding_test"; // Handle messages in the browser process. class ProcessMessageDelegate : public ClientHandler::ProcessMessageDelegate { public: ProcessMessageDelegate() { } // From ClientHandler::ProcessMessageDelegate. virtual bool OnProcessMessageReceived( CefRefPtr<ClientHandler> handler, CefRefPtr<CefBrowser> browser, CefProcessId source_process, CefRefPtr<CefProcessMessage> message) OVERRIDE { std::string message_name = message->GetName(); if (message_name == "delete") { //args->GetString(0); } else if (message_name == "create") { } if (message_name == kMessageName) { // Handle the message. std::string result; CefRefPtr<CefListValue> args = message->GetArgumentList(); if (args->GetSize() > 0 && args->GetType(0) == VTYPE_STRING) { // Our result is a reverse of the original message. result = args->GetString(0); std::reverse(result.begin(), result.end()); } else { result = "Invalid request"; } storage::insertSession("test 1", "active "); //LoadSessions(browser); //browser->GetMainFrame()->LoadStringW(result, "about:blank"); // Send the result back to the render process. //CefRefPtr<CefProcessMessage> response = // CefProcessMessage::Create(kMessageName); //response->GetArgumentList()->SetString(0, result); // browser->SendProcessMessage(PID_RENDERER, response); return true; } return false; } IMPLEMENT_REFCOUNTING(ProcessMessageDelegate); }; } // namespace void LoadSessions(CefRefPtr<CefBrowser> browser) { char szWorkingDir[MAX_PATH]; // The current working directory // Retrieve the current working directory. if (_getcwd(szWorkingDir, MAX_PATH) == NULL) szWorkingDir[0] = 0; std::string path; path.append(szWorkingDir); path.append("\\sessions.html"); CefRefPtr<CefStreamReader> stream = CefStreamReader::CreateForFile(path.c_str()); ASSERT(stream.get()); // read all of the stream data into a std::string. std::stringstream ss; char buff[100]; size_t read; do { read = stream->Read(buff, sizeof(char), 100-1); if(read > 0) { buff[read] = 0; ss << buff; } } while(read > 0); std::string sessiondata = ss.str(); std::string placeholder = "\"placeholder\""; std::string sessions = storage::getSessions(); size_t found = sessiondata.find(placeholder); if (found != std::string::npos) sessiondata.replace(sessiondata.find(placeholder), placeholder.length(), sessions); browser->GetMainFrame()->LoadStringW(sessiondata, "http://sessions/"); } void CreateProcessMessageDelegates( ClientHandler::ProcessMessageDelegateSet& delegates) { delegates.insert(new ProcessMessageDelegate); } } // namespace binding_test
4e56ad014090251501ad9517c62ab20217ddfe2c
ce35d6c13e4e7aecea28d6facaeed0755f221b59
/Source/include/GraphicsEngine/GraphicEngineMessages.h
3cb2ffe16e2e9433b583cf62da8c708c98f34831
[]
no_license
DanApperloo/Eradicate
43f7964f927a796595ab0d5ad357f3360f95201a
265e333490cbe9941340cce9061db5df089d2c56
refs/heads/master
2021-01-23T06:29:10.119555
2013-11-20T05:34:22
2013-11-20T05:34:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,265
h
GraphicEngineMessages.h
////////////////////////////////////////////////////////////////////////////////////// // // // // // // // // // // ////////////////////////////////////////////////////////////////////////////////////// #ifndef __GraphicEngineMessages_h_ #define __GraphicEngineMessages_h_ // Includes #include "stdafx.h" #include "QueueManagement\Objects\AbstractMessage.h" using namespace Eradicate; // NAME // Explaination typedef enum _GRAPHIC_ENGINE_CONTROL_MESSAGE_TYPE { GRAPHIC_ENGINE_CONTROL_ACTIVATE = 0, GRAPHIC_ENGINE_CONTROL_TRANSITION_TO_SHUTDOWN, GRAPHIC_ENGINE_CONTROL_SHUTDOWN } GRAPHIC_ENGINE_CONTROL_MESSAGE_TYPE; // NAME // Explaination typedef struct _GRAPHIC_ENGINE_CONTROL_MESSAGE_TRANSITION_TO_SHUTDOWN_PARAMS { STATUS exit_status; } GRAPHIC_ENGINE_CONTROL_MESSAGE_TRANSITION_TO_SHUTDOWN_PARAMS; // NAME // Explaination typedef union _GRAPHIC_ENGINE_CONTROL_MESSAGE_PARAMS { GRAPHIC_ENGINE_CONTROL_MESSAGE_TRANSITION_TO_SHUTDOWN_PARAMS transition_params; } GRAPHIC_ENGINE_CONTROL_MESSAGE_PARAMS; // NAME // Explaination typedef struct _GRAPHIC_ENGINE_CONTROL_MESSAGE { GRAPHIC_ENGINE_CONTROL_MESSAGE_TYPE minor_type; GRAPHIC_ENGINE_CONTROL_MESSAGE_PARAMS minor_params; } GRAPHIC_ENGINE_CONTROL_MESSAGE; // NAME // Explaination typedef union _GRAPHIC_ENGINE_MINOR_MESSAGES { GRAPHIC_ENGINE_CONTROL_MESSAGE control_message; } GRAPHIC_ENGINE_MINOR_MESSAGES; // NAME // Explaination typedef enum _GRAPHIC_ENGINE_MAJOR_MESSAGE_TYPE { GRAPHIC_ENGINE_CONTROL = 0, } GRAPHIC_ENGINE_MAJOR_MESSAGE_TYPE; // /// NAME // /// SHORT DESCRIPTION // /// Description: /// LONG DESCRIPTION /// /// Return /// VALUE and DESCRIPTION // class GraphicEngineMessage : public AbstractMessage { public: GRAPHIC_ENGINE_MAJOR_MESSAGE_TYPE major_type; // Message type from enumeration GRAPHIC_ENGINE_MINOR_MESSAGES minor_msg; // Union representing message specific params ULONG getMajorMessageType() { return (ULONG) major_type; } }; #endif // #ifndef __GraphicEngineMessages_h_
ad4f35f5a70dc7779ee04aebf0a2d8ea49c0ca5b
144204c519069fe75ecf084a5aefefea142542b7
/apps/telit-monitor/ATCOPS_AMH.cpp
a60bafb99b0366919246058efe1a67a9582eeaee
[]
no_license
bopopescu/UnitedSafety
fcb6baf9b3382cc1b45c58079da1dcc33b95d434
baea1b16c2fd44e224fb9120d026da2535123bd7
refs/heads/master
2022-10-10T04:04:58.528055
2020-06-11T18:29:19
2020-06-11T18:29:19
282,259,268
1
0
null
2020-07-24T15:48:24
2020-07-24T15:48:24
null
UTF-8
C++
false
false
615
cpp
ATCOPS_AMH.cpp
#include "socket_interface.h" #include "atslogger.h" #include "ATCOPS_AMH.h" void ATCOPS_AMH::on_message(MyData& p_md, const ats::String& p_cmd, const ats::String& p_msg) { if("+COPS" != p_cmd) { return; } const size_t i = p_msg.find('"'); if(i != ats::String::npos) { const ats::String& s = p_msg.substr(i+1); const size_t i = s.find('"'); if(i != ats::String::npos) { const ats::String& cellnetwork = s.substr(0,i); send_trulink_ud_msg("admin-client-cmd", 0, "atcmd cellnetwork %s\r", cellnetwork.c_str()); ats_logf(ATSLOG_DEBUG, "atcmd network: %s", cellnetwork.c_str()); } } }
30d8ebb232e3ed0f6a5893279e83be169545070f
0a9b804a82f4f9710c0acac3831ad882e724804c
/Main/StageControl.cpp
74236e43616e3af6be6dce210ea0fcd27d0cec41
[]
no_license
shuto-fujioka/MAZE
9b1621a64c1e9d43d61aab048a9f4ac5f1af11ea
87446458d1844263807ebdbc8a6b1e5f4436bc43
refs/heads/master
2021-01-25T08:01:44.229842
2017-07-10T02:23:50
2017-07-10T02:23:50
93,703,948
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,141
cpp
StageControl.cpp
#include "Texture_Lib.h" #include "GameScene.h" #include "DirectX_Lib.h" #include "DirectInput_Lib.h" #include "proto.h" #include "Stage.h" #include "Render.h" #include "KeyControl.h" #include <stdio.h> int change[MAP_HEIGHT][MAP_WIDTH]; void MapLoad(const char* mapdata); void LeftStageTurn(float* py, float* px) { int y; int x; //Aキーが押されてる場合...左に回る for (y = 0; y < MAP_HEIGHT; y++) { for (x = 0; x < MAP_WIDTH; x++) { map[y][x] = change[x][14 - y]; } } } void RightStageTurn(float* py, float* px) { int y; int x; //Dキーが押されてる場合...右に回る for (int y = 0; y < MAP_HEIGHT; y++) { for (int x = 0; x < MAP_WIDTH; x++) { map[y][x] = change[14 - x][y]; } } } void StageTurn(float* py, float* px){ int y; int x; //Wキーが押されてる場合...180度回る for (y = 0; y < MAP_HEIGHT; y++) { for (x = 0; x < MAP_WIDTH; x++) { map[y][x] = change[14 - y][14 - x]; } } } void StageControl() { int y; int x; for (y = 0; y < MAP_HEIGHT; y++) { for (x = 0; x < MAP_WIDTH; x++) { change[y][x] = map[y][x]; } } }
5e83578ad1a5006c371b8f1b7ef62e64d1644f5c
fce1c88c239918dda3f46af414d6099d9be0b80a
/lab7_Socket/src/client.cpp
ed213a59605f2fb623cda95e2e46a3e3151ba2cb
[ "MIT" ]
permissive
logos-mhr/Computer-Network
80c025c0279ee82a57332e551e1bb10f5dacc117
132a33968f925a70860e9f67b51de5bad6ea136b
refs/heads/master
2020-12-04T10:56:01.347986
2019-12-31T10:50:48
2019-12-31T10:50:48
231,737,146
3
0
MIT
2020-01-04T09:14:46
2020-01-04T09:14:46
null
UTF-8
C++
false
false
6,330
cpp
client.cpp
#include "client.h" std::mutex mt; int main() { std::ios::sync_with_stdio(false); socketClient client; client.run(); } socketClient::socketClient() { sockfd = -1; key_t msgkey = ftok("/",'a'); msqid = msgget(msgkey, IPC_CREAT | 0666); } socketClient::~socketClient() { close(sockfd); } void socketClient::run() { help(); while (true) { std::cout<<"> "; std::string line; getline(std::cin, line); // split std::regex whitespace("\\s+"); std::vector<std::string> words(std::sregex_token_iterator(line.begin(), line.end(), whitespace, -1), std::sregex_token_iterator()); if (words[0] == "") { continue; } else if (words[0] == "connect") { if (-1 != sockfd) { std::cout<<RED<<"Connected!\n"<<NORMAL; } else { connect(words[1], std::stoi(words[2])); } } else if (words[0] == "close") { if (-1 == sockfd) { std::cout<<RED<<"No connection.\n"<<NORMAL; } else { char buffer = 50; send(sockfd, &buffer, sizeof(buffer), 0); mt.lock(); pthread_cancel(connection_thread); mt.unlock(); close(sockfd); sockfd = -1; std::cout<<GREEN<<"Connection closed.\n"<<NORMAL; } } else if (words[0] == "gettime") { char buffer = 1; messageStruct timemsg; send(sockfd, &buffer, sizeof(buffer), 0); msgrcv(msqid, &timemsg, BUFFER_MAX, 11, 0); time_t time = atol(timemsg.text); std::cout<<YELLOW<<" Server time: "<<ctime(&time)<<NORMAL; } else if (words[0] == "getservername") { char buffer = 2; send(sockfd, &buffer, sizeof(buffer), 0); messageStruct namemsg; msgrcv(msqid, &namemsg, BUFFER_MAX, 12, 0); std::cout<<YELLOW<<"Server host name: "<<namemsg.text<<'\n'<<NORMAL; } else if (words[0] == "getclients") { char buffer = 3; send(sockfd, &buffer, sizeof(buffer), 0); messageStruct peermsg; msgrcv(msqid, &peermsg, BUFFER_MAX, 13, 0); char* ptr = peermsg.text; int count = 0, flag = 1; std::cout<<YELLOW; while (*ptr) { if ('^' == *ptr) { std::cout<<' '; } else if ('$' == *ptr) { std::cout<<'\n'; flag = 1; } else { if (flag) { std::cout<<count++<<' '; flag = 0; } std::cout<<(*ptr); } ptr++; } std::cout<<NORMAL; } else if (words[0] == "send") { char buffer[BUFFER_MAX] = {0}; buffer[0] = 4; sprintf(buffer + strlen(buffer), "%s", words[1].c_str()); sprintf(buffer + strlen(buffer), "^"); sprintf(buffer + strlen(buffer), "%s", words[2].c_str()); sprintf(buffer + strlen(buffer), "$"); for (int i = 3; i < words.size(); ++i) { sprintf(buffer + strlen(buffer), "%s", words[i].c_str()); if (i != words.size()) { sprintf(buffer + strlen(buffer), " "); } else { sprintf(buffer + strlen(buffer), "\n"); } } send(sockfd, buffer, BUFFER_MAX, 0); messageStruct statusmsg; msgrcv(msqid, &statusmsg, BUFFER_MAX, 14, 0); std::cout<<YELLOW<<statusmsg.text<<NORMAL; } else if (words[0] == "receive") { char buffer[BUFFER_MAX] = {0}; buffer[0] = 5; sprintf(buffer + strlen(buffer), "receive"); send(sockfd, buffer, BUFFER_MAX, 0); } else if (words[0] == "exit") { if (-1 != sockfd) { char buffer = 50; send(sockfd, &buffer, sizeof(buffer), 0); close(sockfd); std::cout<<GREEN<<"Socket "<<sockfd<<" closed.\n"<<NORMAL; } std::cout<<YELLOW<<"Bye.\n"<<NORMAL; exit(0); } else if (words[0] == "help") { help(); } else { std::cout<<"Illegal input!\n"; } } } void socketClient::connect(const std::string& ip_addr, const int& port) { sockfd = socket(AF_INET, SOCK_STREAM, 0); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port); serverAddr.sin_addr.s_addr = inet_addr(ip_addr.c_str()); ::connect(sockfd, (sockaddr*)&serverAddr, sizeof(serverAddr)); pthread_create(&connection_thread, nullptr, thread_handle, &sockfd); } void socketClient::help() { std::cout<<"Please input a command:\n" <<"- connect [IP] [port]\n" <<"- close\n" <<"- gettime\n" <<"- getservername\n" <<"- getclients\n" <<"- send [IP] [port] [content]\n" <<"- exit\n" <<"- help\n"; } void connection_handle(int cfd) { char buffer[BUFFER_MAX]; recv(cfd, buffer, BUFFER_MAX, 0); std::cout<<GREEN<<buffer<<NORMAL<<"> "; fflush(stdout); messageStruct msg; key_t key = ftok("/",'a'); int msqid = msgget(key, IPC_CREAT | 0666); while (1) { memset(buffer, 0, BUFFER_MAX); recv(cfd, buffer, BUFFER_MAX, 0); if (20 == buffer[0]) { std::cout<<buffer + 1<<'\n'; continue; } msg.type = buffer[0]; strcpy(msg.text, buffer + 1); msgsnd(msqid, &msg, BUFFER_MAX, 0); } }
64be7faae3236ff1c76518e7d75e59af8a9cf4cb
f0bd42c8ae869dee511f6d41b1bc255cb32887d5
/Codeforces/_Groups/AAST ACM ICPC Training/AAST ACM ICPC 2015 - Individuals Qualification #3/G. Pizza and Cockroaches.cpp
3ef318330f0d8feaf7425deb9d98e00cfead3ab3
[]
no_license
osamahatem/CompetitiveProgramming
3c68218a181d4637c09f31a7097c62f20977ffcd
a5b54ae8cab47b2720a64c68832a9c07668c5ffb
refs/heads/master
2021-06-10T10:21:13.879053
2020-07-07T14:59:44
2020-07-07T14:59:44
113,673,720
3
1
null
null
null
null
UTF-8
C++
false
false
503
cpp
G. Pizza and Cockroaches.cpp
/* * G. Pizza and Cockroaches.cpp * * Created on: Sep 10, 2015 * Author: Osama Hatem */ #include <bits/stdtr1c++.h> #include <ext/numeric> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("in.in", "r", stdin); // freopen("out.out", "w", stdout); #endif freopen("pizza.in", "r", stdin); int T; cin >> T; for (int t = 1; t <= T; t++) { int k; cin >> k; long long ans = (long long) k * (k + 1) / 2 + 1; cout << "Case " << t << ": " << ans << endl; } return 0; }
582319c613b6839d17e4c3ce2c15a28f4c74ac89
3532ffb6f9887ffb9ba93c9e56a983d8e26577b7
/mod/dbapp/dbappfrmmultiupdate.cpp
324d92a6569636a4f0ae4c077bdbd64b3ccde0a8
[]
no_license
santilin/gonglib
a667739cd1131ebec3d86e967be228bd22f15066
4e80d3b9272bf3650575df53f52a08e7280037bf
refs/heads/master
2020-05-18T18:02:26.756943
2016-06-17T16:29:16
2016-06-17T16:29:16
184,568,296
0
0
null
null
null
null
UTF-8
C++
false
false
5,363
cpp
dbappfrmmultiupdate.cpp
#include "config.h" #include <gonggettext.h> #include "dbappdbapplication.h" #include "dbappfrmeditrecmaster.h" #include "dbappfrmmultiupdate.h" namespace gong { FrmMultiUpdate::FrmMultiUpdate(FrmEditRecMaster *theform, QWidget* parent, WidgetFlags fl) : FrmCustom(0, "FrmMultiUpdate", fl), pTheForm( theform ) { setCaption( toGUI(_("Modificación múltiple")) ); const dbTableDefinition *tbldef = theform->getRecord()->getTableDefinition(); XtringList fld_captions; IntList fld_pos; for ( unsigned int i = 0; i < tbldef->getFieldCount(); i++ ) { dbFieldDefinition *fielddef = tbldef->getFieldDefinition ( i ); if( fielddef->getName() == tbldef->getFldIDName() || fielddef->getName().find("_ID") != Xtring::npos ) continue; if( pTheForm->findControl( fielddef->getName() ) ) { Xtring desc = fielddef->getCaption().isEmpty() ? fielddef->getDescription().isEmpty() ? fielddef->getName() : fielddef->getDescription() : fielddef->getCaption(); fld_captions.push_back( desc ); // Permite duplicados, pues es el título fld_pos.push_back( i ); } } pComboField = addComboBoxInt(false, 0, _("Campo a modificar"), fld_captions, fld_pos); pValor = addInput(0, _("Nuevo valor"), "", "STRING"); XtringList rangeoptions; rangeoptions << _("Registro actual") << _("Registros seleccionados") << _("Todo"); int range; if( theform->getDataTable()->getSelectedIDs().size() > 1 ) { range = 1; } else if( !theform->getWholeFilter().isEmpty() && theform->getWholeFilter() != theform->getRecord()->getFilter("") ) { range = 2; } else { range = 0; } pRango = addGroupBox(0, rangeoptions, _("Rango"), range); pSupervisar = addCheckBox(0, _("Supervisar registros uno a uno"), true ); } void FrmMultiUpdate::validate_input( QWidget *sender, bool *isvalid ) { FrmCustom::validate_input( sender, isvalid ); } void FrmMultiUpdate::accept() { List<dbRecordID> ids; Xtring where; switch( pRango->getSelectedPos() ) { case 0: ids << pTheForm->getTableRecordID(); break; case 1: ids << pTheForm->getDataTable()->getSelectedIDs(); break; case 2: for( int nr = 0; nr < pTheForm->getDataTable()->numRows(); ++nr ) ids << pTheForm->getDataTable()->getDataModel()->getRowID( nr ); break; } dbRecord *record = pTheForm->getRecord()->duplicate(); int nupdated = 0; for( List<dbRecordID>::const_iterator it = ids.begin(); it != ids.end(); ++ it ) { dbRecordID recid = *it; bool revisar = pSupervisar->isChecked(); if( record->read( recid ) ) { record->setValue( pComboField->getCurrentItemValue(), pValor->toVariant() ); record->readRelated( true ); if( !record->isValid( ValidResult::fixing, 0 ) ) { DBAPP->showOSD( _("Modificar múltiple"), _("Este registro contiene errores.") ); revisar = true; } if( revisar ) { FrmEditRecMaster *editfrm = static_cast<FrmEditRecMaster *>( DBAPP->createEditForm( 0, record, 0, DataTable::updating, dbApplication::simpleEdition ) ); if ( editfrm ) { editfrm->setFormFilter( pTheForm->getFormFilter() ); // Copy the form filter // editfrm->setJustEditedAllControls( true ); editfrm->showModalFor( this, false, true ); if ( !editfrm->isSaved() ) { delete editfrm; List<dbRecordID>::const_iterator itact = it; if( ++itact == ids.end() ) break; // Don't ask if this is the last one if( !FrmBase::msgYesNo( this, _( "Has anulado la modificación de este registro.\n" "¿Qieres continuar con los siguientes?" ) ) ) { break; } } else { delete editfrm; nupdated ++; } } else { msgOk( this, _( "No se ha podido crear el formulario para modificación múltiple" ) ); break; } } else { DBAPP->waitCursor( true ); try { record->save( false ); // Don't update relations nupdated ++; if( nupdated % 5 == 0 ) DBAPP->showOSD( _("Modificando"), Xtring::printf(_("Modificados %d registros"), nupdated ) ); // TODO descplural } catch( dbError &e ) { _GONG_DEBUG_WARNING( e.what() ); msgError( this, Xtring( _( "Error al guardar el registro:\n" )) + e.what() ); } DBAPP->resetCursor(); } } } delete record; if ( nupdated ) { msgOk( this, Xtring::printf( _( "Se han modificado %d registros" ), nupdated ) ); pTheForm->refresh(); } } } // namespace gong
1ca0fbd665d7a51091fe03f0f453d73b469149e5
214961d5e8fe77d6eb25f2a1f7a5a8babed7f55b
/Source/Effect.h
1aac90ac96fd8733618c813b2999eaa7f18d8c07
[]
no_license
leszqq/GuitarEffectProj
a7f982161ee12153a96f4d11ccbf92332f7e1b5a
2c4581499da8c8227c80b0554d2577093d08f559
refs/heads/master
2021-04-23T08:07:40.975156
2020-03-25T07:56:03
2020-03-25T07:56:03
249,911,858
1
0
null
null
null
null
UTF-8
C++
false
false
719
h
Effect.h
#pragma once #include "../JuceLibraryCode/JuceHeader.h" class FXLoop; class Effect : public Component { public: Effect(FXLoop* fxLoop, std::string name, int index); // nazwa efektu jest istotna. Na jej podstawie tworzone s¹ nowe instancje obiektu ~Effect(); void paint (Graphics&) override = 0; void resized() override = 0; virtual void processSignal(AudioSampleBuffer * processedBuffer) = 0; // metoda realizujaca przetwarzanie próbek sygna³u std::string getName(); void setIndex(int index); // ustawianie miejsca w pêtli efektów FXLoop private: protected: FXLoop* pFXLoop; std::string name; int index; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Effect) };
79415f5797d21c0912f871ef7a7b18dc3bc5c65c
adb9be8abd70701bed4e628532f34c30e405c37c
/gcc/Sources/LampFM/Widget/ScrollList.h
f335439050e842b9dc650c1f60541b84ad755da8
[]
no_license
zvova7890/lg-phone-develop
0ca51f8a313cafddec0f5a58082a7fe0551ab3ca
bade1e9ad9662bff458f065bafba46b420b6f5ea
refs/heads/master
2021-01-18T15:06:09.396770
2015-10-14T19:38:45
2015-10-14T19:38:45
44,271,358
1
0
null
null
null
null
UTF-8
C++
false
false
3,971
h
ScrollList.h
#ifndef HSCROLLAREA_H #define HSCROLLAREA_H #include <Widget/Widget.h> #include <Core/Timer.h> #include <Core/TimerCounter.h> #include <vector> #include <functional> class ScrollList : public Widget, protected Timer { public: class ScrollState { public: ScrollState(int item = 0, int coord_tate = 0) { this->item = item; this->coord_tate = coord_tate; } ScrollState & operator =(const ScrollState &ss) { item = ss.item; coord_tate = ss.coord_tate; return *this; } int item; int coord_tate; }; enum Direction { No = 0, Up = 1, Down }; enum TimerWork { NoWork = 0, ScrollFading = 1, ScrollFixup, ScrollToStartEnd, ScrollToItem }; typedef enum { Vertical = 1, Horizontal }ScrollType; public: ScrollList(const Rect &, ScrollList::ScrollType scroll_type, Widget *parent = 0); virtual ~ScrollList(); virtual void touchItemEvent(int item, int action, int x, int y); virtual int count() const; virtual Widget *widgetItem(int id); void fixupViewPosition(); void breakScrolling(); void resetViewPosition(); void setViewCoord(int c); void setItem(int c); void setLinesCount(int c); void toItem(int c); void toStart(); void toEnd(); bool isAutoScrollActive() const; void addItem(Widget *); void clear(); int listHeightInRect(); /* return a free space after last item */ int leastFreePage(); int lastCanDisplayedItems(int *least_up = 0); void setScrollState(const ScrollState &s) { m_item = s.item; m_coordPos = s.coord_tate; } ScrollState scrollState() const { return ScrollState(item(), m_coordPos); } const std::vector<Widget*> & items() const { return m_items; } inline int item() const { return m_item; } void setMoveDirection(ScrollList::Direction d) { m_moveDirection = d; } int displayingItems() const { return m_displayingItems; } int itemCoord() const { return m_coordPos; } bool isHaveOffscreenItems() const { return m_haveOffscreenItems; } int viewPageHeight() const { return m_pageSize; } void setClipRegionFunc(std::function <void(const Rect&)> f) { m_setClipRegionFunc = f; } void setRestoreClipRegionFunc(std::function <void()> f) { m_setRestoreClipRegionFunc = f; } protected: virtual void paintEvent(); virtual void touchEvent(int action, int x, int y); virtual void resizeEvent(); void init(); bool moveUp(int steps); bool moveDown(int steps); void timerEvent(); void startMove(int speed, int potencial, Direction d); Widget* takeItemByCoord(int x, int y); int checkItemSizes(Widget *) const; inline Widget *lastWidgetItem(); private: std::vector<Widget*> m_items; int m_linesCount; int m_item; int m_coordPos; int m_pageSize; int m_displayingItems; bool m_haveOffscreenItems; Direction m_moveDirection; Point m_touchLastPos, m_lastPos; Widget *m_touched; TimerWork m_timerType; float m_timerSpeed, m_potencialOfHiding; int m_timerValue; Direction m_timerDirectionMove; #ifdef __PC_BUILD__ TimerCounter m_timerCounter; #else unsigned long m_lastTime; #endif int m_timeStampDiff; int m_posDiff; struct { Direction direction; int distance; int speed; int boost; int item; }PosFixup; ScrollType m_scrollType; std::function <int()> dep_type_area_pos; std::function <int(const Widget *)> dep_type_area_size; std::function <void(const Rect &)> m_setClipRegionFunc; std::function <void()> m_setRestoreClipRegionFunc; }; #endif // HSCROLLAREA_H
4a36c374e8e8d760358e56001050119a36ed302b
394a3cb743fa873132d44a5800440e5bf7bcfad8
/src/Ara.h
a48a12072c458ac7c4a955bae7b9310a351ded6f
[]
no_license
lfsmoura/dalgo
19487487271b5410b3facfc0b0647c8736074fa8
47cfb3be3126955e822ca08179f82aa3eba1de6f
refs/heads/master
2020-06-03T11:02:49.541436
2010-06-30T01:35:30
2010-06-30T01:35:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,616
h
Ara.h
#ifndef ARA #define ARA #include <boost/config.hpp> #include <iostream> #include <fstream> #include <limits> #include <queue> #include <list> #include <algorithm> #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> #include <boost/graph/astar_search.hpp> #include <boost/graph/random.hpp> #include <boost/random.hpp> //#include <boost/foreach.hpp> #include "PriorityQueue.h" #include "Timer.h" #define DEBUG //#define DIST_EUCLIDIANA using namespace boost; using namespace std; class Ara{ typedef int Edge_Weight; typedef adjacency_list < listS, vecS, directedS, no_property, property <edge_weight_t, Edge_Weight> > G; typedef graph_traits < G >::vertex_descriptor vertex_descriptor; typedef graph_traits < G >::edge_descriptor edge_descriptor; typedef graph_traits < G >::vertex_iterator vertex_iterator; typedef graph_traits < G >::out_edge_iterator out_edge_iterator; typedef graph_traits < G >::adjacency_iterator adjacency_iterator; typedef std::pair<int, int> Edge; enum Sets { OPEN, CLOSED, INCONS, NONE }; /******************************************************************** * VARIABLES AND CONSTANTS * ********************************************************************/ const double PI; const double DG_TO_RAD; const Edge_Weight INFINITO; int num_nodes, num_edges; Edge* edge_array; Edge_Weight* weights; double* x; double* y; Edge_Weight* f; Edge_Weight* g; Edge_Weight* v; int* backPointer; Sets* set; G* graph; PriorityQueue<Edge_Weight>* open; list<int> incons; #ifdef DEBUG int estadosChecados; int iter; Timer lTimer, gTimer; #endif void load(string co_filename, string dist_filename); void initARA(); void initialize(); void initializeEdges(); double key(int id, const int goal, const double &e); void update_open(const int goal, const double &e); void empty_closed(); void move_incons_open(); void greedyPath(const int &start, const int &goal); void computePath(const double &e, int start, int goal); public: double h(int id, const int goal); Ara(string co_filename, string dist_filename); void publishSolution(int &iter, int et, int start, int goal, int max = 1); void araSpeedUpTest(int repeat = 1); void main(int start, int goal, double e0, double delta); Edge_Weight astar(int start, int goal, bool verbose = false); void dijkstra(int start,int goal); }; #endif
d3b0c5bc9505862fc95b6aa674bf6de17b2c997b
79bd639c75da41ef50549141eb19ad1327026dd5
/helpers/halffloat.hpp
eacb9f91a3defefa5e15c268edf80fcbcab59a8d
[ "MIT" ]
permissive
apitrace/apitrace
0ff067546af346aa623197491e54d4d0f80ca887
00706d1a395ab6570ab88136fffb3028a3ded3bd
refs/heads/master
2023-08-18T14:51:16.977789
2023-08-07T17:51:44
2023-08-11T08:18:20
1,611,530
2,097
452
MIT
2023-08-25T16:49:59
2011-04-13T21:37:46
C++
UTF-8
C++
false
false
3,352
hpp
halffloat.hpp
/************************************************************************** * * Copyright 2010 Luca Barbieri * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #ifndef U_HALF_H #define U_HALF_H #ifdef __cplusplus extern "C" { #endif union fi { float f; int32_t i; uint32_t ui; }; /* * References for float <-> half conversions * * http://fgiesen.wordpress.com/2012/03/28/half-to-float-done-quic/ * https://gist.github.com/2156668 * https://gist.github.com/2144712 */ static inline uint16_t util_float_to_half(float f) { uint32_t sign_mask = 0x80000000; uint32_t round_mask = ~0xfff; uint32_t f32inf = 0xff << 23; uint32_t f16inf = 0x1f << 23; uint32_t sign; union fi magic; union fi f32; uint16_t f16; magic.ui = 0xf << 23; f32.f = f; /* Sign */ sign = f32.ui & sign_mask; f32.ui ^= sign; if (f32.ui == f32inf) { /* Inf */ f16 = 0x7c00; } else if (f32.ui > f32inf) { /* NaN */ f16 = 0x7e00; } else { /* Number */ f32.ui &= round_mask; f32.f *= magic.f; f32.ui -= round_mask; /* * Clamp to max finite value if overflowed. * OpenGL has completely undefined rounding behavior for float to * half-float conversions, and this matches what is mandated for float * to fp11/fp10, which recommend round-to-nearest-finite too. * (d3d10 is deeply unhappy about flushing such values to infinity, and * while it also mandates round-to-zero it doesn't care nearly as much * about that.) */ if (f32.ui > f16inf) f32.ui = f16inf - 1; f16 = f32.ui >> 13; } /* Sign */ f16 |= sign >> 16; return f16; } static inline float util_half_to_float(uint16_t f16) { union fi infnan; union fi magic; union fi f32; infnan.ui = 0x8f << 23; infnan.f = 65536.0f; magic.ui = 0xef << 23; /* Exponent / Mantissa */ f32.ui = (f16 & 0x7fff) << 13; /* Adjust */ f32.f *= magic.f; /* Inf / NaN */ if (f32.f >= infnan.f) f32.ui |= 0xff << 23; /* Sign */ f32.ui |= (f16 & 0x8000) << 16; return f32.f; } #ifdef __cplusplus } #endif #endif /* U_HALF_H */
2ef1e2da2715af618b7f625c867ccafd0c42d446
974d04d2ea27b1bba1c01015a98112d2afb78fe5
/paddle/phi/ops/compat/cudnn_lstm_sig.cc
83e61b396ee5379cbf724bcb6d2659d4766956eb
[ "Apache-2.0" ]
permissive
PaddlePaddle/Paddle
b3d2583119082c8e4b74331dacc4d39ed4d7cff0
22a11a60e0e3d10a3cf610077a3d9942a6f964cb
refs/heads/develop
2023-08-17T21:27:30.568889
2023-08-17T12:38:22
2023-08-17T12:38:22
65,711,522
20,414
5,891
Apache-2.0
2023-09-14T19:20:51
2016-08-15T06:59:08
C++
UTF-8
C++
false
false
1,809
cc
cudnn_lstm_sig.cc
// Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/phi/core/compat/op_utils.h" namespace phi { KernelSignature CudnnLSTMOpArgumentMapping(const ArgumentMappingContext& ctx) { return KernelSignature( "cudnn_lstm", {"Input", "InitH", "InitC", "W", "WeightList", "SequenceLength"}, {"dropout_prob", "is_bidirec", "hidden_size", "num_layers", "is_test", "seed"}, {"Out", "LastH", "LastC", "Reserve", "StateOut"}); } KernelSignature CudnnLSTMGradOpArgumentMapping( const ArgumentMappingContext& ctx) { return KernelSignature( "cudnn_lstm_grad", {"Input", "InitH", "InitC", "WeightList", "SequenceLength", "Out", "Reserve", "StateOut", "Out@GRAD", "LastH@GRAD", "LastC@GRAD"}, {"dropout_prob", "is_bidirec", "hidden_size", "num_layers", "is_test", "seed"}, {"Input@GRAD", "InitH@GRAD", "InitC@GRAD", "WeightList@GRAD"}); } } // namespace phi PD_REGISTER_ARG_MAPPING_FN(cudnn_lstm, phi::CudnnLSTMOpArgumentMapping); PD_REGISTER_ARG_MAPPING_FN(cudnn_lstm_grad, phi::CudnnLSTMGradOpArgumentMapping);
2821773f48c3550925778384fdd084dba93f3754
7af6c31502f6b6f614124ce9bd7c27386ec863dc
/C09/LocalValHideGlobalVal.cpp
ecd78682036af5976fb11a5f8016eeae698f1f97
[]
no_license
bell0136/TIL
7761580b1d7374d46d0ae83d01d2bf4f1576b3d7
d54a6746479423e554f3eaa5c6c62884880af37d
refs/heads/master
2020-09-13T01:20:29.055065
2020-07-31T13:05:08
2020-07-31T13:05:08
222,618,875
0
0
null
null
null
null
UTF-8
C++
false
false
191
cpp
LocalValHideGlobalVal.cpp
#include <stdio.h> int num=1; int add (int); int main (void) { int num=5; add(3); printf("%d\n",add(3)); printf("num+9=%d",num+9); } int add (int i) { int num=9; num+=i; return num; }
10871584864ba219e0de64da5aad815385081886
bef9d6bc4c6ecc9e1668dd80202ce069eb06b320
/Image.h
31bd20679556d1874051f308424332f737c6c388
[]
no_license
home3d2001/ImageProcessing
dc0494df0ebd3eb44f48e32c5d13c424e2e20f94
fc5580149055f48ed770eb4b36fab693c0365dad
refs/heads/master
2020-03-18T13:06:14.798346
2015-04-28T05:27:20
2015-04-28T05:27:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,480
h
Image.h
#ifndef IMAGE_H #define IMAGE_H #include <memory> #include <string> #include <iostream> #include "Matrix.h" using namespace std; namespace MSHIMA001{ class Image{ private: int width, height; unique_ptr<unsigned char[]> data; public: friend ostream& operator<<(ostream& head, const Image& N ); friend istream& operator>>( istream& file, Image& N ); bool operator==(const Image& N); Image(int w, int h, unsigned char* buffer); // default constructor - define in .cpp Image( string fileName); ~Image(); // destructor - define in .cpp file //copy constructor Image(const Image& N); //move constructor Image(Image&& N); //assignment operator Image& operator=(const Image& N ); //move assignment operator. Image& operator=(Image&& N); //method to read input files Image operator!(); bool load(std::string fileName); void save(std::string fileName ); class Iterator{ private: unsigned char *ptr; // grant private access to Image class functions friend class Image; // construct only via Image class (begin/end) Iterator(unsigned char *p); public: //copy construct is public Iterator(const Iterator& N); // define overloaded ops: *, ++, --, = //destructor ~Iterator(); //move constructor Iterator(Iterator&& N); //assignment operator Iterator& operator=(const Iterator& N ); //move assignment operator. Iterator& operator=(Iterator&& N); //++ operator const Iterator& operator ++(); const Iterator& operator --(); unsigned char& operator *(); bool operator !=( const Iterator& N); Iterator& operator+=(int n); //Iterator& operator=(int&& N ); // other methods for Iterator }; Image::Iterator begin(void) const; // etc Image::Iterator end(void) const; Image operator+(const Image& N ); Image operator-(const Image& N ); Image operator/(const Image& N ); Image operator*(int f ); Image operator%(MSHIMA001::Matrix g ); }; } #endif
dfccc98064b2da5f16615446d7a0cba8c0785fcb
26b44414ec79f1fb6a501ec3a1ff7ba23d12983a
/ICDSMSCE/SystemMsg.cpp
c60a6c2558ccab415d69c35ab6cecbc0af03917a
[]
no_license
lwhay/ICDMS
d74d8f894d1b353e8dc00a0e6b98a9545b10077e
3168d48fec96913a26b8a6a837b38dff1f70c8a3
refs/heads/master
2021-01-01T08:21:05.620874
2014-03-23T15:10:02
2014-03-23T15:10:02
17,953,721
1
0
null
null
null
null
UTF-8
C++
false
false
1,265
cpp
SystemMsg.cpp
#include "SystemMsg.h" using namespace Cayuga::SystemMsg; #include <iostream> string Cayuga::SystemMsg::ErrorMsg[] = { "functionality not implemented yet: ", "incompatible data types: ", }; string Cayuga::SystemMsg::WarningMsg[] = { "a function is computed but the result is not named.", "two input streams contain attributes of the same name: ", "$ or $1 is used.", "time unit is used, and has not been supported by CEL compiler.", }; string Cayuga::SystemMsg::Location[] = { "SELECT clause", "BINARY clause", "duration predicate", }; string Cayuga::SystemMsg::Solution[] = { "Will create a new name for this attribute in SELECT clause", "Will create a new name for that attribute in the second input stream", }; void Cayuga::SystemMsg::printError(Cayuga::SystemMsg::ErrorMsgID eid, string param) { cerr<<"Error: "<<ErrorMsg[eid]<<param<<endl; //throw exception(); throw string(); } void Cayuga::SystemMsg::printWarning(Cayuga::SystemMsg::LocationID locID, Cayuga::SystemMsg::WarningMsgID wid, string param) { cerr<<"Warning: "<<"In a "<<Location[locID]<<", "; cerr<<WarningMsg[wid]<<param<<endl; } void Cayuga::SystemMsg::printSolution(Cayuga::SystemMsg::SolutionID sid) { cerr<<Solution[sid]<<endl; }
d2632dd2669a9868d3863e7b37196bb9c70701f2
4eac9e5e93d34429104d273450156e78d65b887c
/practice/algorithm_practise/50ti/5/.svn/text-base/maze1.cpp.svn-base
4e5214958ef86e86da49e133e0ce991c1647bc8c
[]
no_license
yushiyaogg/backup
6e878793d86b89ed874222b6fd48552d7cded123
8eb6bab42027236d0d0934e45b51908abefd8dc8
refs/heads/master
2021-01-10T21:10:51.194152
2014-08-02T01:43:10
2014-08-02T01:43:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,915
maze1.cpp.svn-base
/* * ===================================================================================== * * Filename: maze1.cpp * * Description: * * Version: 1.0 * Created: 04/13/12 10:07:17 * Revision: none * Compiler: gcc * * Author: Heaven (), zhanwenhan@163.com * Company: NDSL * * ===================================================================================== */ #include <iostream> using namespace std; int maze[7][7]={ {2,2,2,2,2,2,2}, {2,0,0,0,0,0,2}, {2,0,2,0,2,0,2}, {2,0,0,2,0,0,2}, {2,2,0,2,0,0,2}, {2,0,0,0,0,0,2}, {2,2,2,2,2,2,2} }; int startI = 1, startJ = 1; int endI = 5, endJ = 5; int success = 0; int visit(int positionI,int positionJ) { maze[positionI][positionJ] = 1; if(positionI == endI&&positionJ == endJ) { success = 1; return success; } else { if( maze[positionI+1][positionJ] == 0) return visit(positionI+1,positionJ); if( maze[positionI][positionJ+1] == 0) return visit(positionI,positionJ+1); if( maze[positionI-1][positionJ] == 0) return visit(positionI-1,positionJ); if( maze[positionI][positionJ-1] == 0) return visit(positionI,positionJ-1); maze[positionI][positionJ] = 0; return success; } } int main() { int i =0, j = 0; for(int i = 0 ; i < 7; i++) { for(int j = 0 ; j < 7 ; j ++) { cout << maze[i][j]<<" "; } cout << endl; } if(visit(startI, startJ) < 0) { cout << "no path"<<endl; } else { for(int i = 0; i< 4;i ++) cout <<endl; for(int i = 0 ; i < 7; i++) { for(int j = 0 ; j < 7 ; j ++) { cout << maze[i][j]<<" "; } cout << endl; } } }
6a76afe6c41cd8f7ca48dc2d4a08c4770ae1a9cf
4fef7e213f4d7807f49704870333d5d2017bd4cb
/Assignment5_NormalMappedModel/BasicWidget.cpp
ac29ff4c44b5cce37fa79a0c4015248fd90b8b48
[]
no_license
andrewalc/ComputerGraphics
6b18588ff0562ba7cd306ea6d4325553936eee25
53f748bee41c37e9d1c90d19abd1829a1102cf4a
refs/heads/master
2020-12-06T11:14:08.479943
2020-04-16T03:24:48
2020-04-16T03:24:48
232,448,461
0
0
null
2020-01-14T18:56:39
2020-01-08T01:08:04
C++
UTF-8
C++
false
false
7,226
cpp
BasicWidget.cpp
#include "BasicWidget.h" #include "ObjParse.h" #include "UnitQuad.h" bool WIREFRAME = false; ////////////////////////////////////////////////////////////////////// // Publics BasicWidget::BasicWidget(QWidget* parent) : QOpenGLWidget(parent), logger_(this) { setFocusPolicy(Qt::StrongFocus); camera_.setPosition(QVector3D(0.5, 0.5, -2.0)); camera_.setLookAt(QVector3D(0.5, 0.5, 0.0)); world_.setToIdentity(); } BasicWidget::~BasicWidget() { for (auto renderable : renderables_) { delete renderable; } renderables_.clear(); } ////////////////////////////////////////////////////////////////////// // Privates /////////////////////////////////////////////////////////////////////// // Protected void BasicWidget::keyReleaseEvent(QKeyEvent* keyEvent) { // Handle key events here. if (keyEvent->key() == Qt::Key_Left) { qDebug() << "Left Arrow Pressed"; update(); // We call update after we handle a key press to trigger a // redraw when we are ready } else if (keyEvent->key() == Qt::Key_Right) { qDebug() << "Right Arrow Pressed"; update(); // We call update after we handle a key press to trigger a // redraw when we are ready } else if (keyEvent->key() == Qt::Key_R) { camera_.setPosition(QVector3D(0.5, 0.5, -2.0)); camera_.setLookAt(QVector3D(0.5, 0.5, 0.0)); update(); } else if (keyEvent->key() == Qt::Key_W) { qDebug() << "W Pressed"; makeCurrent(); WIREFRAME = !WIREFRAME; if (WIREFRAME) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } update(); // We call update after we handle a key press to trigger a // redraw when we are ready } else { qDebug() << "You Pressed an unsupported Key!"; } } void BasicWidget::mousePressEvent(QMouseEvent* mouseEvent) { if (mouseEvent->button() == Qt::LeftButton) { mouseAction_ = Rotate; } else if (mouseEvent->button() == Qt::RightButton) { mouseAction_ = Zoom; } lastMouseLoc_ = mouseEvent->pos(); } void BasicWidget::mouseMoveEvent(QMouseEvent* mouseEvent) { if (mouseAction_ == NoAction) { return; } QPoint delta = mouseEvent->pos() - lastMouseLoc_; lastMouseLoc_ = mouseEvent->pos(); if (mouseAction_ == Rotate) { // TODO: Implement rotating the camera // QVector3D gaze = camera_.gazeVector(); // camera_.translateCamera(gaze + QVector(gaze.x() + 1 , gaze.y() + 1, // gaze.z()) * camera_.ROTATION_SPEED); // camera_.translateLookAt(camera_.upVector() * camera_.ROTATION_SPEED // * (delta.y() > 0 ? -1 : 1)); camera_.translateLookAt( QVector3D(0, 0, 0).crossProduct( camera_.lookAt() - camera_.position(), camera_.upVector()) * camera_.ROTATION_SPEED * delta.x()); } else if (mouseAction_ == Zoom) { // TODO: Implement zoom by moving the camera // Zooming is moving along the gaze direction by some amount. camera_.translateCamera(camera_.gazeVector() * camera_.ZOOM_SPEED * -delta.y()); } update(); } void BasicWidget::mouseReleaseEvent(QMouseEvent* mouseEvent) { mouseAction_ = NoAction; } Renderable* BasicWidget::makeObject(std::string objFile, std::string texFile, QVector3D offset) { // ./App"objects/house/house_obj.obj" "objects/house/house_diffuse.ppm" ObjParse parser = ObjParse(); parser.parse(objFile); QVector<unsigned int> idx = QVector<unsigned int>::fromStdVector(parser.getIdx()); Renderable* ren = new UnitQuad(); ren->init(parser.vertextures, idx, QString::fromStdString(texFile)); QMatrix4x4 backXform; backXform.setToIdentity(); backXform.translate(2.8, .55, 1.0); backXform.rotate(QQuaternion::fromEulerAngles(QVector3D(0,260,0))); ren->setModelMatrix(backXform); renderables_.push_back(ren); std::cout << "object " << objFile << " created " << std::endl; return ren; } void BasicWidget::initializeGL() { makeCurrent(); initializeOpenGLFunctions(); qDebug() << QDir::currentPath(); Renderable* house = makeObject("objects/house/house_obj.obj", "objects/house/house_diffuse.ppm", QVector3D(0, 0, 0)); // TODO: You may have to change these paths. QString brickTex = "../objects/brickWall_highRes/brickWall_diffuse.ppm"; QString grassTex = "./grass.ppm"; UnitQuad* backWall = new UnitQuad(); backWall->init(brickTex); QMatrix4x4 backXform; backXform.setToIdentity(); backXform.scale(1.0, 1.0, -1.0); backWall->setModelMatrix(backXform); renderables_.push_back(backWall); UnitQuad* rightWall = new UnitQuad(); rightWall->init(brickTex); QMatrix4x4 rightXform; rightXform.setToIdentity(); rightXform.rotate(90.0, 0.0, 1.0, 0.0); rightWall->setModelMatrix(rightXform); renderables_.push_back(rightWall); // UnitQuad* leftWall = new UnitQuad(); // leftWall->init(brickTex); // QMatrix4x4 leftXform; // leftXform.setToIdentity(); // leftXform.translate(1.0, 0.0, -1.0); // leftXform.rotate(-90.0, 0.0, 1.0, 0.0); // leftWall->setModelMatrix(leftXform); // renderables_.push_back(leftWall); UnitQuad* floor = new UnitQuad(); floor->init(grassTex); QMatrix4x4 floorXform; floorXform.setToIdentity(); floorXform.translate(-0.5, 0.0, 0.5); floorXform.scale(2.0, 2.0, 2.0); floorXform.rotate(-90.0, 1.0, 0.0, 0.0); floor->setModelMatrix(floorXform); renderables_.push_back(floor); glViewport(0, 0, width(), height()); frameTimer_.start(); } void BasicWidget::resizeGL(int w, int h) { if (!logger_.isLogging()) { logger_.initialize(); // Setup the logger for real-time messaging connect(&logger_, &QOpenGLDebugLogger::messageLogged, [=]() { const QList<QOpenGLDebugMessage> messages = logger_.loggedMessages(); for (auto msg : messages) { qDebug() << msg; } }); logger_.startLogging(); } glViewport(0, 0, w, h); camera_.setPerspective(70.f, (float)w / (float)h, 0.001, 1000.0); glViewport(0, 0, w, h); } void BasicWidget::paintGL() { qint64 msSinceRestart = frameTimer_.restart(); glEnable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glClearColor(0.f, 0.f, 0.f, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); for (auto renderable : renderables_) { renderable->update(msSinceRestart); // TODO: Understand that the camera is now governing the view and // projection matrices renderable->draw(world_, camera_.getViewMatrix(), camera_.getProjectionMatrix()); } update(); }
54775bbd8febc4ad286354da3b521a411cc0494d
7ca4c90eb11c00e1186c50a9e872dbf050766bcd
/HW5/Directory.h
1cd4031d0d06f94a339e8b31fee1a2220c6897a6
[]
no_license
ZorinIvan/hw5
e6154a71bdaeb281bd7f9532910b13688ffa26b0
a08bca07e637e2b88b837e637aee97e3fbc08b3a
refs/heads/master
2020-04-06T04:55:52.651337
2015-06-23T19:16:28
2015-06-23T19:16:28
37,722,296
0
0
null
null
null
null
UTF-8
C++
false
false
4,667
h
Directory.h
#ifndef DIRECTORY_H #define DIRECTORY_H #include "File.h" #include <vector> #include <string> using namespace std; class Directory: public File { public: // c'tor Directory(string name, File* parent = NULL); //cc'tor Directory(const Directory& obj ); // d'tor ~Directory(); //********************************************************************************************* //* Name: AddFile //* Description: Add a new file to the directory, the file will be added at the end of the //* files list //* Parameters: File* file - a pointer of the file to be added //* Return value: bool - true if the file was added successfully //* false if a file with the same name already exists in the directory //********************************************************************************************* bool AddFile(File* pFile); //********************************************************************************************* //* Name: print //* Description: Print the directory to the screen //* Parameters: None //* Return value: None //* Output example: //* Directory: //* Name: /root/dir2 //* Files: file1 file2 //********************************************************************************************* void print() const; //********************************************************************************************* //* Name: RemoveFile //* Description: Remove a file from the directory //* Parameters: string file_name - a of the file to remove //* Return value: bool - true if the file was removed successfully //* false if a file with the same name doesn't exist in the directory //********************************************************************************************* bool RemoveFile(string file_name); //********************************************************************************************* //* Name: GetNumOfFiles //* Description: returns number of files in the directory //* Parameters: none //* Return value: int - num of files. //********************************************************************************************* int GetNumOfFiles() const; //********************************************************************************************* //* Name: GetFile //* Description: returns pointer to file/ //* Parameters: string file_name - name of the file we are searching for //* Return value: File* pointer to file. //********************************************************************************************* File* GetFile(string file_name); //********************************************************************************************* //* Name: operator== //* Description: Implements the equality operator //* Parameters: File file - the file to compare against //* Return value: bool - true if both files are the same, false otherwise //********************************************************************************************* bool operator==(const File& file) const; // Need to define the iterator as friend to give it access to some of our members friend class FilesIterator; //********************************************************************************************* //* Name: begin //* Description: Returns a new iterator to the begining of the subtree starting from the //* current directory, where the current directory is the first element //* Parameters: None //* Return value: FilesIterator - a new iterator that can traverse the file system tree //********************************************************************************************* FilesIterator begin(); //********************************************************************************************* //* Name: end //* Description: Returns a new iterator pointing to an invalid element representing the end //* of the file system tree //* Parameters: None //* Return value: FilesIterator - a new dummy iterator to the end of the file system tree //********************************************************************************************* FilesIterator end(); string getPath() const; File* getFileByPlace(unsigned int place) const; protected: vector<File*> m_files; }; #endif
4e7567ec377dba6b69b595c33dd54d7312159e7c
b0025b70e7eaad87a9a984d83016530fea61a3a9
/boj/BruteForce/23749.cpp
d8f1078a88889b03b8afe0732f995996542d3d83
[]
no_license
yupyub/Algorithm
00fede2885e1646458af1ffe16e7e2f4fc098832
7330e47c7cf70b1d2842004df63a1a347b625f41
refs/heads/master
2022-05-21T05:09:50.497376
2022-03-26T18:19:32
2022-03-26T18:19:32
101,531,563
1
0
null
null
null
null
UTF-8
C++
false
false
1,411
cpp
23749.cpp
#include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <set> #include <map> #include <tuple> #include <string> #include <functional> #include <queue> #include <stack> #include <climits> #include <iostream> using namespace std; #define CINOUT ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #define INF INT_MAX/2-1 typedef long long ll; map<vector<int>, int> dist; int main() { int N; char c; scanf("%d", &N); vector<int> state; for (int i = 0; i < N*2; i++) { scanf(" %c", &c); state.push_back(c); } queue<pair<vector<int>, int> >q; q.push(make_pair(state, 1)); while (!q.empty()) { vector<int> st = q.front().first; int n = q.front().second; q.pop(); if (dist[st] != 0) continue; dist[st] = n; for (int i = 1; i < 2*N; i++) { vector<int> nxt; nxt.push_back(st[i]); for (int j = 0; j < 2*N; j++) { if (i != j) nxt.push_back(st[j]); } q.push(make_pair(nxt, n + 1)); } } int ans = INF; for (auto st = dist.begin(); st != dist.end(); st++) { auto s = st->first; int point1 = 0; int point2 = 0; for (int i = 0; i < s.size();i+=2) { //printf("%c %c ", s[i], s[i + 1]); if (s[i] == s[i + 1]) continue; else if (s[i] == 'O') point1++; else point2++; } if (point1 > point2) ans = min(ans, st->second); } printf("%d", ans-1); return 0; }
e46c520da331fb355346a5522e006ef897701ab3
b0f08154e3eebc7d8465efc57597e52d08d69c18
/src/loaddb/load_db_value_converter.hpp
c658aa07e7826b3344c8f785392bf6a0b7876445
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
CUBRID/cubrid
8f71a0010243b72e43ba887d229210650f4e901e
3b952af33230839a1b561a78ecd4b773374b66f8
refs/heads/develop
2023-08-18T19:16:30.987583
2023-08-18T08:18:05
2023-08-18T08:18:05
52,080,367
287
294
NOASSERTION
2023-09-14T21:29:09
2016-02-19T10:25:32
C
UTF-8
C++
false
false
1,166
hpp
load_db_value_converter.hpp
/* * Copyright 2008 Search Solution Corporation * Copyright 2016 CUBRID Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * load_db_value_converter.hpp - conversion from string to DB_VALUE */ #ifndef _LOAD_DB_VALUE_CONVERTER_HPP_ #define _LOAD_DB_VALUE_CONVERTER_HPP_ #include "dbtype_def.h" #include "load_common.hpp" namespace cubload { // forward declaration class attribute; typedef int (*conv_func) (const char *, const size_t, const attribute *, db_value *); conv_func &get_conv_func (const data_type ldr_type, const DB_TYPE db_type); } // namespace cubload #endif /* _LOAD_DB_VALUE_CONVERTER_HPP_ */
2b4f4b5fbca3d6523b37f94d83c825998ef6bd22
41c3c3473ea1e92714f2c54ebe0e9d2ce1d2415a
/include/Sensory/Brain.h
481d27fe4e059859a2a1f681ab68ddfa34f97b65
[]
no_license
JoaquinDelaRosa/Evolution
355e0e9f1665d4f0490e347c4f006d3a940ca8ee
f3fefc803518b866c58fb77d2128ef7dcf0d8ac9
refs/heads/main
2023-08-07T04:49:19.161297
2021-09-25T08:49:00
2021-09-25T08:49:00
403,215,667
1
0
null
null
null
null
UTF-8
C++
false
false
4,579
h
Brain.h
#ifndef BRAIN_H #define BRAIN_H #include<bits/stdc++.h> #include<VectorMath.h> #include<BodyComp/Body.h> #include<Sensory/EntitySensor.h> #include<Allele.h> #include "Neuralnet/NeuralNetwork.h" #include "Constants.h" class Entity; class Brain { std::map<std::string, Allele<float>*> gene; Entity* entity; NeuralNetwork* nn; public: Brain(Entity* entity , bool mutate = false){ this->gene = *new std::map<std::string, Allele<float>*>(); this->entity = entity; this->nn = new NeuralNetwork(entity); addAllele(new Allele<float>("FoodProbability", 0, 1, Generator::instance().getUniform())); addAllele(new Allele<float>("WasteProbability", 0, 1, Generator::instance().getUniform())); addAllele(new Allele<float>("FoodDigester", -1, 1, Generator::instance().getRandomNumber(-1.0f, 1.0f))); addAllele(new Allele<float>("WasteDigester", -1, 1, Generator::instance().getRandomNumber(-1.0f, 1.0f))); addAllele(new Allele<float>("FoodPerception", 0, 100, Generator::instance().getRandomNumber(10.0f, MAX_PERCEPTION_RADIUS))); addAllele(new Allele<float>("WastePerception", 0, 100, Generator::instance().getRandomNumber(10.0f, MAX_PERCEPTION_RADIUS))); addAllele(new Allele<float>("EntityPerception", 0, 100, Generator::instance().getRandomNumber(10.0f, MAX_PERCEPTION_RADIUS))); addAllele(new Allele<float>("EntitySpeed", 0.0f, 1.0f, Generator::instance().getRandomNumber(0.0f, 1.0f), 0.1f)); } Brain(const Brain& other, Entity* entity){ if(this!= &other && this->entity != entity){ this->gene = *(new std::map<std::string, Allele<float>*>()); for(auto it = other.gene.begin(); it!= other.gene.end(); it++){ this->addAllele(new Allele<float>(it->first, it->second->getMin(), it->second->getMax(), it->second->getValue())); } this->entity = entity; this->nn = new NeuralNetwork(*other.nn, entity); this->mutate(); this->encode(); } } Brain* clone(Entity* entity){ Brain* b = new Brain(entity); b->gene = this->gene; b->nn = new NeuralNetwork(*this->nn, entity); return b; } void addAllele(Allele<float>* a){ this->gene.emplace(a->getName(), a); } void mutate(){ // Mutate the brain's gene. for(auto it = this->gene.begin(); it != this->gene.end(); it++){ it->second->mutate(); } this->nn->mutate(); } void encode(){ // Encode gene characteristics as phenotype Body* body = entity->getBody(); if(body == nullptr) return; if(this->gene["FoodDigester"]->getValue() > 0) body->addComponent(new FoodDigester(entity)); if(this->gene["WasteDigester"]->getValue() > 0) body->addComponent(new WasteDigester(entity)); //this->entity->getEntitySensor()->radius = gene["EntityPerception"]->getValue(); this->entity->getResourceSensor("Food")->radius = gene["FoodPerception"]->getValue(); this->entity->getResourceSensor("Waste")->radius = gene["WastePerception"]->getValue(); this->entity->speed = this->gene["EntitySpeed"]->getValue(); } void think(){ nn->think(); } float getGeneValue(std::string name){ return gene[name]->getValue(); } void display(){ this->nn->display(); } void mutateNN(){ this->nn->mutate(); } bool getCompatibility(Brain* other, float threshold){ if(other == nullptr) return false; float q = C1 * this->distance(other) + C2 * this->nn->distance(other->nn); if(q <= threshold) return true; return false; } float distance(Brain* other){ float tot = 0; auto it = this->gene.begin(); auto ot = other->gene.begin(); while(it != this->gene.end() && ot != this->gene.end()){ float dx = it->second->getWeight() - ot->second->getWeight(); tot += dx * dx; it++; ot++; } return sqrt(tot); } }; #endif // BRAIN_H
6b5773bbcca70e4e73ef8dce02368fa5d11a1401
1f53587b329fe58250bb804a9cffdb34e2b95bef
/3 курс/Программная инженерия/Shedulepro/teacherregistration.cpp
65e3e4bed908f11492ab6f76ccb642facbbfcdb6
[]
no_license
vladborisovjs/Polytech
b43519bdea3482c9d7d680e378292b9d7e9ebc35
60fb31362243558d1c323a52015ad4042668abc1
refs/heads/master
2020-04-02T18:23:35.995868
2018-10-25T16:03:27
2018-10-25T16:03:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,336
cpp
teacherregistration.cpp
#include "teacherregistration.h" #include "ui_teacherregistration.h" #define Path_to_DB "/home/venik_lapochkin/Документы/Qt projects/Shedulepro/DB" #include <QMessageBox> teacherregistration::teacherregistration(QWidget *parent) : QDialog(parent), ui(new Ui::teacherregistration) { ui->setupUi(this); ui->combogender->addItem("male"); ui->combogender->addItem("female"); ui->comboBox->addItems(QStringList()<<"@mail"<<"@yandex"<<"@gmail"); ui->comboBox_2->addItems(QStringList()<<".ru"<<".com"); for (int i=1;i<=12;i++){ if(i<=9){ ui->month->addItem("0"+QString::number(i)); }else ui->month->addItem(QString::number(i)); } for (int i=1;i<=31;i++){ if(i<=9){ ui->day->addItem("0"+QString::number(i)); }else ui->day->addItem(QString::number(i)); } for (int i=2015;i>=1900;i--){ ui->year->addItem(QString::number(i)); } if(slf.connOpen()){ ui->Status->setText("Connected to DB"); } else{ ui->Status->setText("Not connected to DB");} } teacherregistration::~teacherregistration() { delete ui; qDebug() <<"Closing the connection DB"; } void teacherregistration::on_pushButton_2_clicked() { this->close(); } void teacherregistration::on_pushButton_clicked() { QString login,password,spassword,mail,gender,birthday; login = ui->lineEdit->text(); password = ui->lineEdit_2->text(); spassword = ui->lineEdit_3->text(); mail = ui->lineEdit_4->text()+ui->comboBox->currentText()+ui->comboBox_2->currentText(); gender = ui->combogender->currentText(); birthday = ui->day->currentText()+"."+ui->month->currentText()+"."+ui->year->currentText(); if(password.length()<3||login.length()<3||spassword !=password||spassword.length()<3){ if (login == ""){ ui->llabel->setText("Empty login"); } else if (login.length()<3){ ui->llabel->setText("length login less than 3"); } else if (login.contains("а")||login.contains("б")||login.contains("в")||login.contains("г")||login.contains("д")||login.contains("е")||login.contains("ё")||login.contains("ж")||login.contains("з")||login.contains("и")||login.contains("й")||login.contains("к")||login.contains("л")||login.contains("м")||login.contains("н")||login.contains("о")||login.contains("п")||login.contains("р")||login.contains("с")||login.contains("т")||login.contains("у")||login.contains("ф")||login.contains("х")||login.contains("ц")||login.contains("ч")||login.contains("ш")||login.contains("щ")||login.contains("ъ")||login.contains("ы")||login.contains("ь")||login.contains("э")||login.contains("ю")||login.contains("я")) { ui->llabel->setText("only english symbols"); } else {ui->llabel->setText("Correct");} if (password == ""){ ui->plabel->setText("Empty password"); } else if (password.length()<3){ ui->plabel->setText("length password less than 3"); } else if(password.contains("а")||password.contains("б")||password.contains("в")||password.contains("г")||password.contains("д")||password.contains("е")||password.contains("ё")||password.contains("ж")||password.contains("з")||password.contains("и")||password.contains("й")||password.contains("к")||password.contains("л")||password.contains("м")||password.contains("н")||password.contains("о")||password.contains("п")||password.contains("р")||password.contains("с")||password.contains("т")||password.contains("у")||password.contains("ф")||password.contains("х")||password.contains("ц")||password.contains("ч")||password.contains("ш")||password.contains("щ")||password.contains("ъ")||password.contains("ы")||password.contains("ь")||password.contains("э")||password.contains("ю")||password.contains("я")){ ui->plabel->setText("only english symbols"); } else { ui->plabel->setText("Correct");} if (spassword ==""){ ui->splabel->setText("Empty password"); } else if (spassword.length()<3){ ui->splabel->setText("length password less than 3"); } else if(spassword.contains("а")||spassword.contains("б")||spassword.contains("в")||spassword.contains("г")||spassword.contains("д")||spassword.contains("е")||spassword.contains("ё")||spassword.contains("ж")||spassword.contains("з")||spassword.contains("и")||spassword.contains("й")||spassword.contains("к")||spassword.contains("л")||spassword.contains("м")||spassword.contains("н")||spassword.contains("о")||spassword.contains("п")||spassword.contains("р")||spassword.contains("с")||spassword.contains("т")||spassword.contains("у")||spassword.contains("ф")||spassword.contains("х")||spassword.contains("ц")||spassword.contains("ч")||spassword.contains("ш")||spassword.contains("щ")||spassword.contains("ъ")||spassword.contains("ы")||spassword.contains("ь")||spassword.contains("э")||spassword.contains("ю")||spassword.contains("я")){ ui->splabel->setText("only english symbols"); } else if (spassword !=password){ ui->splabel->setText("the passwords do not match"); ui->plabel->setText("the passwords do not match"); } else{ui->plabel->setText("Correct"); ui->splabel->setText("Correct");} if(mail==""){ ui->mlabel->setText("Empty mail"); } else if (mail.length()<3){ ui->mlabel->setText("length mail less than 3"); } else if(mail.contains("а")||mail.contains("б")||mail.contains("в")||mail.contains("г")||mail.contains("д")||mail.contains("е")||mail.contains("ё")||mail.contains("ж")||mail.contains("з")||mail.contains("и")||mail.contains("й")||mail.contains("к")||mail.contains("л")||mail.contains("м")||mail.contains("н")||mail.contains("о")||mail.contains("п")||mail.contains("р")||mail.contains("с")||mail.contains("т")||mail.contains("у")||mail.contains("ф")||mail.contains("х")||mail.contains("ц")||mail.contains("ч")||mail.contains("ш")||mail.contains("щ")||mail.contains("ъ")||mail.contains("ы")||mail.contains("ь")||mail.contains("э")||mail.contains("ю")||mail.contains("я")){ ui->mlabel->setText("only english symbols"); } else{ui->mlabel->setText("Correct");} QString msg = "Please, try again"; QMessageBox::warning(this,"Fail!You weren`t registred ",msg); }else{ if(!slf.connOpen()){ qDebug() <<"No connection to DB"; return; }else{qDebug()<<"Connection exist";} slf.connOpen(); QSqlQuery qry; qry.prepare("insert into teachers (birthday,gender,mail,login,password) values ('"+birthday+"','"+gender+"','"+mail+"','"+login+"','"+password+"')"); if(qry.exec()){ QString msg = "Please, restart your application"; QMessageBox::information(this,"Success!You were registred ",msg); slf.connClose(); }else{ QString msg = "Please, try again"; QMessageBox::warning(this,"Fail!You weren`t registred ",msg); slf.connClose(); } } }
1636b44af86ac4be82ba79840dc0464a6c209c29
b0e1649d7d0dd251babe99d5ee69d65b071831ab
/include/controller.h
b4275169ff9104bc5c315d5dd810b03ffde4d63c
[]
no_license
jwesterinen/jefebot-controller
cbfa4b9f5ddc5f02c5984f8c645fb195f1e0c7a5
a237a5939953bd2bf06722586e04f34b308ff68c
refs/heads/master
2022-05-05T03:48:32.156438
2022-03-15T01:31:28
2022-03-15T01:31:28
91,637,208
0
0
null
null
null
null
UTF-8
C++
false
false
1,620
h
controller.h
/* * controller.h * * Description: This is the base class for any behavior control program for jefebot. * All controllers have the following properties that must be defined: * - Callback: the event handler for the controller * - ui: the physical user interface objecgt used to control jefebot * - locomotive: the locomotive object * - edgeDetector: the edge detector object * - rangeSensor: the range sensor object * - ifVerbose: degree of verbosity flag * - edge: ??? * - distanceToMove: distance variable * - angleToTurn: angle variable */ #ifndef INCLUDE_CONTROLLER_H_ #define INCLUDE_CONTROLLER_H_ #include "peripherals.h" #define PI 3.14 class Controller : public DP::Callback { private: static const unsigned Period = 50; protected: UserInterface& ui; Locomotive& locomotive; EdgeDetector& edgeDetector; SinglePingRangeSensor& rangeSensor; bool isVerbose; enum EdgeDetector::EDGE_SENSORS edge; int distanceToMove; float angleToTurn; public: struct Context { UserInterface& ui; Locomotive& locomotive; EdgeDetector& edgeDetector; SinglePingRangeSensor& rangeSensor; Context( UserInterface& _ui, Locomotive& _locomotive, EdgeDetector& _edgeDetector, SinglePingRangeSensor& _rangeSensor ) : ui(_ui), locomotive(_locomotive), edgeDetector(_edgeDetector), rangeSensor(_rangeSensor) {} }; Controller(Context& ctx, bool _isVerbose); virtual ~Controller() {} }; #endif /* INCLUDE_CONTROLLER_H_ */
bedef5134df1e8b6e791a137e5f96995480a1072
f7f46ea241ce322302757afbc12cae1b59bb9dc3
/examples/main.cpp
0a69a5ff5d728819edaaf12757f50bcd4f7f5635
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
potassco/clasp
7712a7fb70ee59b4bd7d5f5d26234d5eef58f323
4c708a73fdcb78049e9c3bad863a3f6eab437a07
refs/heads/master
2023-08-31T16:34:49.630086
2022-09-10T14:53:14
2022-09-10T14:53:14
58,460,549
105
21
MIT
2023-08-13T17:16:42
2016-05-10T12:44:35
C++
UTF-8
C++
false
false
2,328
cpp
main.cpp
// // Copyright (c) 2009-2017 Benjamin Kaufmann // // This file is part of Clasp. See http://www.cs.uni-potsdam.de/clasp/ // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // #include "example.h" #include <clasp/enumerator.h> #include <clasp/solver.h> void printModel(const Clasp::OutputTable& out, const Clasp::Model& model) { std::cout << "Model " << model.num << ": \n"; // Always print facts. for (Clasp::OutputTable::fact_iterator it = out.fact_begin(), end = out.fact_end(); it != end; ++it) { std::cout << *it << " "; } // Print elements that are true wrt the current model. for (Clasp::OutputTable::pred_iterator it = out.pred_begin(), end = out.pred_end(); it != end; ++it) { if (model.isTrue(it->cond)) { std::cout << it->name << " "; } } // Print additional output variables. for (Clasp::OutputTable::range_iterator it = out.vars_begin(), end = out.vars_end(); it != end; ++it) { std::cout << (model.isTrue(Clasp::posLit(*it)) ? int(*it) : -int(*it)) << " "; } std::cout << std::endl; } #define RUN(x) try { std::cout << "*** Running " << static_cast<const char*>(#x) << " ***" << std::endl; x(); } catch (const std::exception& e) { std::cout << " *** ERROR: " << e.what() << std::endl; } int main() { RUN(example1); RUN(example2); RUN(example3); RUN(example4); }
0203882e89eb2acc17f7b35e2e99d006dc1b3b1f
c7b9056b1e44e9e4ab0796514d7be2561a9aebc4
/RSA/RSA.cpp
8f2bb7ba6e1711af17e800e49d30b010ae229479
[]
no_license
DeathSea/CryptAlgorithmsSimpleImplement
c2c24f53bdf8e4c15c4e5ca73a13bc5f1ade5c2a
42e7ea31b209666ae3b37d741bf52f5730bd1899
refs/heads/master
2021-01-01T05:13:32.197620
2016-06-02T14:49:16
2016-06-02T14:49:16
58,118,880
0
0
null
null
null
null
UTF-8
C++
false
false
5,224
cpp
RSA.cpp
#include "RSA.h" #include "BinPrime4096.h" #include <time.inl> int prime[305] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011 }; int ExGCD(int a, int b, int * x, int *y) { if (b == 0) { *x = 1; *y = 0; return a; } else { int r = ExGCD(b, a%b, x, y); int t = *x; *x = *y; *y = t - (a / b) * *y; return r; } } int mod(int a, int b, int n) { //return pow(a,b) % n int result = 1; int base = a; while (b > 0) { if (b & 1){ result = (result * base) % n; } base = (base * base) % n; b >>= 1; } return result; } int randint(int start, int end) { static bool first = false; if (!first){ srand((unsigned int)time(NULL)); first = true; } int thisint = rand() % (end - start + 1) + start; return thisint; } void outputboolarray(bool *N, int length) { int index = 0; while (index < length) { if (N[index]){ std::cout << "1"; } else{ std::cout << "0"; } index++; if (index % 4 == 0){ std::cout << " "; } } } void outputB(BinNum &A) { if (!A.HighisZero){ outputboolarray(A.High, MAXDIGIT); std::cout << " "; } outputboolarray(A.Low, MAXDIGIT); std::cout << std::endl; } extern BinNum p = BinNum(); extern BinNum q = BinNum(); bool one[1] = { true }; extern BinNum publicKeyN = BinNum(); extern BinNum publicKeyE = BinNum(); extern BinNum privateKeyD = BinNum(); extern BinNum One = BinNum(one, 1); void createprime() { p.Low[MAXDIGIT - 1] = true; p.Low[0] = true; q.Low[MAXDIGIT - 1] = true; q.Low[0] = true; int changebit, times, bit; while (1) { changebit = randint(1, MAXDIGIT - 2); for (times = 0; times < changebit; times++) { bit = randint(1, MAXDIGIT - 2); if (!p.Low[bit]){ p.Low[bit] = true; } else{ times--; } } if (isPrime(p))break; else { memset(p.Low, false, MAXDIGIT); p.Low[MAXDIGIT - 1] = true; p.Low[0] = true; } } while (1) { changebit = randint(1, MAXDIGIT - 2); for (times = 0; times < changebit; times++) { bit = randint(1, MAXDIGIT - 2); if (!q.Low[bit]){ q.Low[bit] = true; } else{ times--; } } if (isPrime(q))break; else { memset(q.Low, false, MAXDIGIT); q.Low[MAXDIGIT - 1] = true; q.Low[0] = true; } } ////p = 0b1011 1001 1110 1111 //bool * Q = new bool[16]{ //true,false,true,true , // true,false,false,true, // true,true,true,false, // true,true,true,true //}; ////q = 0b1111 1111 1110 1111 //bool * P = new bool[16]{ //true,true,true,true, // true,true,true,true, // true,true,true,false, // true,true,true,true //}; //q = BinNum(Q, 16); //p = BinNum(P, 16); std::cout << "the prime num p is: " << std::endl; outputB(p); std::cout << "the prime num q is: " << std::endl; outputB(q); } void calcKey() { publicKeyN = p * q; BinNum omegaN = (p - One)*(q - One); BinNum Tmp = BinNum(); BinNum x = BinNum(); BinNum y = BinNum(); for (int Pindex = 0; Pindex < 564;Pindex++) { Tmp = BinNum(allBinPrime[Pindex],12); BinNum result = ExGCD(Tmp, omegaN, x, y); if (result == One) { publicKeyE = BinNum(Tmp); while (x.sign == true){ x = x + omegaN; } privateKeyD = BinNum(x); break; } } std::cout << "the private key D is: " << std::endl; outputB(privateKeyD); std::cout << "the public key E is: " << std::endl; outputB(publicKeyE); std::cout << "the public key N is: " << std::endl; outputB(publicKeyN); std::cout << "the omega N is: " << std::endl; outputB(omegaN); } BinNum Encrypt(bool * M,int length) { BinNum m = BinNum(M, length); return ModNsquare(m, publicKeyE, publicKeyN); } BinNum Decrypt(BinNum c) { return ModNsquare(c, privateKeyD, publicKeyN); }
abbf0c1efcdb8c27564878f0cedd9996d27bba83
4002bc4433e1493cea98d1a54a3247c7a14cd39d
/estruct amigo.cpp
0a01b5b984a54429e1104f9674a56973b6de641f
[]
no_license
rafaelapure82/C-Parte-3
481e8cea7afdf6df105e15d5c0096d16766374a1
ec33f0afc12c68dcab50541abc0e6a77de610f58
refs/heads/master
2021-09-04T12:38:40.801038
2018-01-18T18:53:53
2018-01-18T18:53:53
118,021,386
0
0
null
null
null
null
UTF-8
C++
false
false
1,543
cpp
estruct amigo.cpp
#include <iostream> #include <windows.h> #define max 100 /*Constante*/ using namespace std; int main(void){ /*Declara las variables para los ciclo for*/ int i = 0; /*Declara estructura persona*/ struct persona{ char nombre[15]; char apellido[15]; int edad; char sexo; char direccion[50]; int telefono; }; /*Declara alumno, arreglo de la estructura persona*/ struct persona amigo[max]; /*Ciclo for que va a recorrer 5 veces*/ for (i = 0; i < 5; i++){ cout<<"\nEscriba el Nombre "<< i+1<<":"; cin>> amigo[i].nombre; cout<<"\nEscriba el Apellido "<< i+1<<":"; cin>> amigo[i].apellido; cout<<"\nEscriba la Edad de "<< i+1<<":"; cin>> amigo[i].edad; cout<<"\nEscriba el sexo "<< i+1<<":"; cin>> amigo[i].sexo; cout<<"\nEscriba la Direccion de "<< i+1<<":"; cin>> amigo[i].direccion; cout<<"\nEscriba el Telefono de "<< i+1<<":"; cin>> amigo[i].telefono; } cout<<"/nEl registro de Alumnos que se introdujeron son: \n\n"; /*Ciclo for que muestra el listado de 5 registro ingresados*/ for (i = 0; i < 5; i++){ /*Se llama al arreglo amigo seguido de la variable*/ cout<<"\t"<<amigo[i].nombre; cout<<"\t"<<amigo[i].apellido; cout<<"\t"<<amigo[i].edad; cout<<"\t"<<amigo[i].sexo; cout<<"\t"<<amigo[i].direccion; cout<<"\t"<<amigo[i].telefono<<"\n\n"; } system("pause"); }
fbe6f5383a24787ee6aa72431c95709ab8a6246a
4f7c4533a0e2db784e47c0c4c2934a5d49723b76
/src/mpi/msmpi/util/local_proc.cpp
e7a678f94362ab676f578711907cdbaa59f7b9a1
[ "MIT", "mpich2", "LicenseRef-scancode-generic-cla" ]
permissive
stepas-toliautas/Microsoft-MPI
588bef1a4ce2cd9fb510ed81f9c79e4bcb0cd606
1dbbaee6373245d0458a8d775b2618b54df2a1eb
refs/heads/master
2020-12-01T18:47:28.783949
2019-11-15T18:16:34
2019-11-15T18:16:34
230,734,136
0
0
NOASSERTION
2019-12-29T10:19:51
2019-12-29T10:19:50
null
UTF-8
C++
false
false
6,218
cpp
local_proc.cpp
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /* * (C) 2001 by Argonne National Laboratory. * See COPYRIGHT in top-level directory. */ #include "precomp.h" #include "mpidimpl.h" /* FIXME this is including a ch3 include file! Implement these functions at the device level. */ #include <limits.h> #include <errno.h> /* MPIU_Find_node_local_and_leaders -- from the list of processes in comm, builds a list of local processes, i.e., processes on this same node, and a list of external processes, i.e., one process from each node. Note that this will not work correctly for spawned or attached processes. external processes: For a communicator, there is one external process per node. You can think of this as the leader process for that node. OUT: local_size_p - number of processes on this node local_ranks_p - (*local_ranks_p)[i] = the rank in comm of the process with local rank i. This is of size (*local_size_p) leaders_size_p - number of external processes leader_ranks_p - (*leader_ranks_p)[i] = the rank in comm of the process with external rank i. This is of size (*leaders_size_p) mappings - mapping in which to fill in the node local and leader for each process in the input communicator. */ int MPIU_Find_node_local_and_leaders( _In_ const MPID_Comm *comm, _Out_ int *local_size_p, _Out_writes_to_(comm->remote_size, *local_size_p) int local_ranks[], _Out_ int *leaders_size_p, _Out_writes_to_(comm->remote_size, *leaders_size_p) int leader_ranks[], _Out_writes_(comm->remote_size) HA_rank_mapping mappings[] ) { int mpi_errno = MPI_SUCCESS; int leaders_size; int local_size; int i; int max_node_id; int node_id; int my_node_id; /* Scan through the list of processes in comm and add one process from each node to the list of "external" processes. We add the first process we find from each node. node_leaders[] is an array where we keep track of whether we have already added that node to the list. */ MPIU_Assert(comm->comm_kind == MPID_INTRACOMM_PARENT); max_node_id = MPID_Get_max_node_id(); StackGuardArray<int> node_leaders = new int[max_node_id + 1]; if( node_leaders == nullptr ) { mpi_errno = MPIU_ERR_NOMEM(); goto fn_fail; } // // node_leaders maps node_id to rank in leader_ranks // RtlFillMemory( node_leaders, sizeof(int) * (max_node_id + 1), -1 ); my_node_id = MPID_Get_node_id(comm, comm->rank); MPIU_Assert(my_node_id >= 0); MPIU_Assert(my_node_id <= max_node_id); // // Build the array of leader processes. We need to do this before building the // mappings array so that we can fill in the leader inforation properly. // bool isLeader = false; leaders_size = 0; for (i = 0; i < comm->remote_size; ++i) { node_id = MPID_Get_node_id(comm, i); /* The upper level can catch this non-fatal error and should be able to recover gracefully. */ if(node_id < 0) { mpi_errno = MPIU_ERR_CREATE(MPI_ERR_OTHER, "**fail"); goto fn_fail; } MPIU_Assert(node_id <= max_node_id); /* build list of external processes since we're traversing ranks from 0, this assignment ensures the comm root to also become the node master of its node */ if (node_leaders[node_id] == -1) { // // This is the first rank on this node. Store the rank of the // node leader for this node. // node_leaders[node_id] = leaders_size; // // Store the mapping from rank in leader_ranks to rank in comm. // leader_ranks[leaders_size] = i; ++leaders_size; // // Flag if we're a leader. // if( i == comm->rank ) { MPIU_Assert( node_id == my_node_id ); isLeader = true; } } } // // Now that we have the leader information, build the mappings array. // local_size = 0; for (i = 0; i < comm->remote_size; ++i) { node_id = MPID_Get_node_id(comm, i ); MPIU_Assert( node_id >= 0 ); if (node_id == my_node_id) { if( isLeader == true && i == comm->rank ) { // // The leader needs to store the leader ranks. // mappings[i].rank = node_leaders[node_id]; mappings[i].isLocal = 0; } else { // // Store the mapping from rank in comm to rank in local_ranks. // mappings[i].rank = local_size; mappings[i].isLocal = 1; } // // Store the mapping from rank in local_ranks to rank in comm. // local_ranks[local_size] = i; ++local_size; } else if (isLeader == true) { // // Leaders store the rank of their peers for remote processes. // mappings[i].rank = node_leaders[node_id]; mappings[i].isLocal = 0; } else { // // Non-leaders always look to rank 0 for data from remote processes. // mappings[i].rank = 0; mappings[i].isLocal = 1; } } *local_size_p = local_size; if( isLeader == true ) { MPIU_Assert( local_ranks[0] == comm->rank ); MPIU_Assert( mappings[comm->rank].rank == static_cast<ULONG>(node_leaders[my_node_id]) ); *leaders_size_p = leaders_size; } else { *leaders_size_p = 0; } fn_exit: return mpi_errno; fn_fail: goto fn_exit; }
8225d71c2feee0c00b324bedd7db8dfc3abb49d1
c6432c5e56f9320aa38b67763074dc4038fdb177
/example/testYMath.cpp
1614672659c0cc28b52fd42acce035dd8c3e5794
[]
no_license
fengChenHPC/util
e285451c911208276565869e2fac0e385d716fc0
a88097644a662b8cecfbf1c69745ee97bcc32ef3
refs/heads/master
2020-04-06T04:34:15.371905
2015-06-13T04:55:39
2015-06-13T04:55:39
32,974,799
0
1
null
null
null
null
UTF-8
C++
false
false
418
cpp
testYMath.cpp
#include "../inc/yyfnutil.h" int main(){ float *rf; size_t len = 10000; rf = (float*) malloc(len*sizeof(float)); CPURandom rand(13); rand.nextGaussianSequence(rf, len); float r = mean(rf, len); printf("%f\n", r); float m = mse(rf, len); printf("%f\n", m); int ir = roundToMultiple(5, 2); printf("%d\n", ir); free(rf); return 0; }
d259c9d2681edd4042c6aa868e5f260f822cc92e
dbe4ce49fc43eb74b403072edc99e2074f324de1
/projects/Direct2dTemplate/Direct2dTemplate/D2dwindow/D2DContextEx.cpp
e224fccfd19fe5086051c6d4fe09c5ab3312b5e5
[ "MIT" ]
permissive
sugarontop/D2DWindow
32de905b7d3bf51f74c9bc7ca1a89eda07266215
57104200b4428f740e715f706d6bb5701094ccad
refs/heads/master
2020-12-24T16:40:30.600752
2016-04-03T00:48:15
2016-04-03T00:48:15
26,255,811
1
1
null
null
null
null
UTF-8
C++
false
false
18,625
cpp
D2DContextEx.cpp
#include "stdafx.h" #include "D2DContextEx.h" #pragma comment(lib,"D2DApi.lib") static LARGE_INTEGER __s_frequency_; namespace V4{ SingletonD2DInstance& SingletonD2DInstance::Init() { static SingletonD2DInstance st; if ( st.factory.p == NULL ) { // Exeにつき1回の実行 D2D1_FACTORY_OPTIONS options; options.debugLevel = D2D1_DEBUG_LEVEL_NONE; THROWIFFAILED( D2D1CreateFactory( D2D1_FACTORY_TYPE_SINGLE_THREADED,__uuidof(ID2D1Factory1),&options,(void**)&st.factory ), L"SingletonD2DInstance::Init()"); THROWIFFAILED( DWriteCreateFactory( DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory1), reinterpret_cast<IUnknown**>(&st.wrfactory)), L"SingletonD2DInstance::Init()"); THROWIFFAILED( st.wrfactory->CreateTextFormat(DEFAULTFONT, 0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, DEFAULTFONT_HEIGHT, L"", &st.text), L"SingletonD2DInstance::Init()"); } return st; } void D2DContext::Init(SingletonD2DInstance& ins ) { insins = &ins; } void D2DContext::CreateHwndRenderTarget( HWND hWnd ) { ID2D1Factory1* factory = insins->factory; CComPtr<ID2D1HwndRenderTarget> temp; THROWIFFAILED(factory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(hWnd, D2D1::SizeU(1, 1), D2D1_PRESENT_OPTIONS_NONE), &temp), L"D2DContext::CreateHwndRenderTarget"); auto hr= temp.p->QueryInterface( &cxt ); xassert(HR(hr)); } void D2DContext::CreateRenderTargetResource( ID2D1RenderTarget* rt ) { // D2DWindow::CreateD2DWindowのタイミングで実行 // D2DWindow::WM_SIZEのタイミングで実行 rt->CreateSolidColorBrush( D2RGB(0,0,0), &black ); rt->CreateSolidColorBrush( D2RGB(255,255,255), &white ); rt->CreateSolidColorBrush( D2RGB(192,192,192), &gray ); rt->CreateSolidColorBrush( D2RGB(255,0,0), &red ); rt->CreateSolidColorBrush( D2RGB(230,230,230), &ltgray); rt->CreateSolidColorBrush( D2RGB(113,113,130), &bluegray); rt->CreateSolidColorBrush( D2RGBA(0, 0, 0, 0), &transparent); rt->CreateSolidColorBrush( D2RGBA(113,113,130,100), &halftone); rt->CreateSolidColorBrush( D2RGBA(250,113,130,150), &halftoneRed); rt->CreateSolidColorBrush( D2RGBA(255,242,0,255), &tooltip); rt->CreateSolidColorBrush(D2RGBA(241, 243, 246, 255), &basegray); rt->CreateSolidColorBrush(D2RGBA(201, 203, 205, 255), &basegray_line); rt->CreateSolidColorBrush(D2RGBA(90,92,98, 255), &basetext); // DestroyRenderTargetResourceを忘れないこと } void D2DContext::CreateResourceOpt() { // RenderTargetとは関係ないリソース作成 ID2D1Factory* factory = insins->factory; float dashes[] = {2.0f}; factory->CreateStrokeStyle( D2D1::StrokeStyleProperties( D2D1_CAP_STYLE_FLAT, D2D1_CAP_STYLE_FLAT, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_MITER, 10.0f, D2D1_DASH_STYLE_CUSTOM, 0.0f), dashes, ARRAYSIZE(dashes), &dot2_ ); float dashes2[] = {4.0f}; factory->CreateStrokeStyle( D2D1::StrokeStyleProperties( D2D1_CAP_STYLE_FLAT, D2D1_CAP_STYLE_FLAT, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_MITER, 10.0f, D2D1_DASH_STYLE_CUSTOM, 0.0f), dashes2, ARRAYSIZE(dashes2), &dot4_ ); text = insins->text.p; wfactory = insins->wrfactory.p; QueryPerformanceFrequency( &__s_frequency_ ); } void D2DContext::DestroyRenderTargetResource() { UINT a = cxt.p->AddRef()-1; cxt.p->Release(); xassert( a == 1 ); cxt.Release(); #ifdef USE_ID2D1DEVICECONTEXT a = dxgiSwapChain.p->AddRef()-1; dxgiSwapChain.p->Release(); xassert( a == 1 ); dxgiSwapChain.Release(); #endif ltgray.Release(); black.Release(); white.Release(); red.Release(); gray.Release(); bluegray.Release(); transparent.Release(); halftone.Release(); halftoneRed.Release(); tooltip.Release(); basegray.Release(); basegray_line.Release(); basetext.Release(); } void D2DContext::DestroyAll() { // OnDestroyのタイミングで実行 DestroyRenderTargetResource(); dot2_.Release(); dot4_.Release(); } void D2DContextText::Init(D2DContext& cxt1, float height, LPCWSTR fontname ) { line_height = 0; xoff = 0; cxt = &cxt1; wrfactory = cxt1.insins->wrfactory; textformat.Release(); if ( HR(cxt1.insins->wrfactory->CreateTextFormat(fontname,0, DWRITE_FONT_WEIGHT_NORMAL,DWRITE_FONT_STYLE_NORMAL,DWRITE_FONT_STRETCH_NORMAL,height,L"",&textformat))) { CComPtr<IDWriteTextLayout> tl; cxt->wfactory->CreateTextLayout( L"T",1, textformat, 1000, 1000, &tl ); DWRITE_HIT_TEST_METRICS mt; float y; tl->HitTestTextPosition( 0, true,&xoff,&y,&mt ); line_height = mt.height; /*DWRITE_TEXT_METRICS tm; GetLineMetric( FSizeF(1000,1000), L"T", 1, tm ); temp_font_height_ = tm.height;*/ } } UINT D2DContextText::GetLineMetrics( const D2D1_SIZE_F& sz, LPCWSTR str, int len, DWRITE_TEXT_METRICS& textMetrics, std::vector<DWRITE_LINE_METRICS>& lineMetrics ) { CComPtr<IDWriteTextLayout> textlayout; cxt->insins->wrfactory->CreateTextLayout(str,len, textformat,(FLOAT)sz.width, (FLOAT)sz.height, &textlayout ); textlayout->GetMetrics(&textMetrics); lineMetrics.resize(textMetrics.lineCount); textlayout->GetLineMetrics(&lineMetrics.front(), textMetrics.lineCount, &textMetrics.lineCount); return textMetrics.lineCount; // 全行数 } UINT D2DContextText::GetLineMetric( const D2D1_SIZE_F& sz, LPCWSTR str, int len, DWRITE_TEXT_METRICS& textMetrics, DWRITE_LINE_METRICS& lineMetric ) { std::vector<DWRITE_LINE_METRICS> ar; UINT r = GetLineMetrics( sz,str,len, textMetrics, ar ); _ASSERT( r ); lineMetric = ar[0]; return r; } UINT D2DContextText::GetLineMetric( const D2D1_SIZE_F& sz, LPCWSTR str, int len, DWRITE_TEXT_METRICS& textMetrics ) { return GetLineMetric( sz, textformat, str,len, textMetrics ); } UINT D2DContextText::GetLineMetric( const D2D1_SIZE_F& sz, IDWriteTextFormat* fmt, LPCWSTR str, int len, DWRITE_TEXT_METRICS& textMetrics ) { CComPtr<IDWriteTextLayout> tl; cxt->insins->wrfactory->CreateTextLayout(str,len, fmt,(FLOAT)sz.width, (FLOAT)sz.height, &tl ); tl->GetMetrics(&textMetrics); return textMetrics.lineCount; } void D2DContext::CreateDeviceContextRenderTarget( HWND hWnd ) { #ifdef USE_ID2D1DEVICECONTEXT RECT rc; GetClientRect(hWnd, &rc); if ( rc.top >= rc.bottom ) rc.bottom = rc.top + 1; _ASSERT( rc.left != rc.right ); _ASSERT( rc.top != rc.bottom ); // UINT width = ::GetSystemMetrics( SM_CXFULLSCREEN ); // UINT height = ::GetSystemMetrics( SM_CYFULLSCREEN ); UINT width = max(100, (UINT)(rc.right*1.5)); UINT height = max(100, (UINT)(rc.bottom*1.5)); // UINT width = max(800, (UINT)(rc.right)); // UINT height = max(800, (UINT)(rc.bottom)); CComPtr<ID2D1DeviceContext> d2d1DeviceContext; CComPtr<IDXGISwapChain1> dxgiSwapChain1; CComPtr<ID2D1Factory1> d2d1Factory = insins->factory; CComPtr<ID2D1Device> d2d1Device; CComPtr<ID2D1Bitmap1> d2d1Bitmap; CComPtr<ID3D11DeviceContext> d3d11DeviceContext; CComPtr<ID3D11Device> d3d11Device; CComPtr<IDXGISurface> dxgiSurface; CComPtr<IDXGIAdapter> dxgiAdapter; CComPtr<IDXGIFactory2> dxgiFactory; CComPtr<IDXGIDevice1> dxgiDevice; UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; D3D_FEATURE_LEVEL returnedFeatureLevel; D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1 }; THROWIFFAILED( D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, 0, creationFlags, featureLevels, ARRAYSIZE(featureLevels), D3D11_SDK_VERSION, &d3d11Device, &returnedFeatureLevel, &d3d11DeviceContext),L"CreateDeviceContextRenderTarget"); THROWIFFAILED(d3d11Device->QueryInterface(&dxgiDevice),L"CreateDeviceContextRenderTarget"); THROWIFFAILED(d2d1Factory->CreateDevice(dxgiDevice.p, &d2d1Device),L"CreateDeviceContextRenderTarget"); THROWIFFAILED(d2d1Device->CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &d2d1DeviceContext),L"CreateDeviceContextRenderTarget"); THROWIFFAILED(dxgiDevice->GetAdapter(&dxgiAdapter),L"CreateDeviceContextRenderTarget"); THROWIFFAILED(dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory)),L"CreateDeviceContextRenderTarget"); DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0}; swapChainDesc.Width = width; swapChainDesc.Height = height; swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; swapChainDesc.Stereo = false; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = 2; swapChainDesc.Scaling = DXGI_SCALING_NONE; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; swapChainDesc.Flags = 0; THROWIFFAILED(dxgiFactory->CreateSwapChainForHwnd(d3d11Device, hWnd, &swapChainDesc, nullptr, nullptr, &dxgiSwapChain1),L"!!CreateSwapChainForHwnd"); // Resource解放忘れがあるとここで落ちる。 xassert( dxgiSwapChain1 ); THROWIFFAILED(dxgiDevice->SetMaximumFrameLatency(1),L"CreateDeviceContextRenderTarget"); THROWIFFAILED(dxgiSwapChain1->GetBuffer(0, IID_PPV_ARGS(&dxgiSurface)),L"CreateDeviceContextRenderTarget"); auto bmp_property = D2D1::BitmapProperties1(D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW, D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_IGNORE)); THROWIFFAILED(d2d1DeviceContext->CreateBitmapFromDxgiSurface(dxgiSurface.p, &bmp_property, &d2d1Bitmap),L"CreateDeviceContextRenderTarget"); d2d1DeviceContext->SetTarget(d2d1Bitmap.p); auto sz = d2d1Bitmap->GetSize(); _ASSERT( sz.width == width ); _ASSERT( sz.height == height ); ////////////////////////////////////////////////////////////////////////////////////////////// RenderSize_.width = width; RenderSize_.height = height; d2d1DeviceContext->QueryInterface(&cxt); dxgiSwapChain = dxgiSwapChain1; #endif } HRESULT D2DContext::CreateFont(LPCWSTR fontnm, float height, IDWriteTextFormat** ret ) { return wfactory->CreateTextFormat( fontnm,0, DWRITE_FONT_WEIGHT_NORMAL,DWRITE_FONT_STYLE_NORMAL,DWRITE_FONT_STRETCH_NORMAL,height,L"", ret ); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DrawCenterText( D2DContextText& cxt, ID2D1Brush* clr, FRectF& rc, LPCWSTR str, int len, int align ) { DWRITE_TEXT_METRICS tm; cxt.GetLineMetric( rc.Size(), str, len, tm ); FRectF rcX(rc); float center = rcX.top + (rcX.bottom-rcX.top)/2.0f; rcX.top = center - tm.height/2; rcX.bottom = rcX.top + tm.height; if ( align == 2 ) rcX.left = rcX.right-tm.width; else if ( align == 1 ) { rcX.left = (rcX.right+rcX.left)/2.0f - tm.width / 2.0f; rcX.right = rcX.left + tm.width; } cxt.cxt->cxt->DrawText( str, len, cxt.textformat, rcX, clr, D2D1_DRAW_TEXT_OPTIONS::D2D1_DRAW_TEXT_OPTIONS_CLIP ); } void TestDrawFillRectEx( D2DContext& cxt,const D2D1_RECT_F& rc, ID2D1Brush* wakuclr,ID2D1Brush* fillclr ) { ID2D1RenderTarget* cxt_ = cxt.cxt; FRectF rcc(rc); rcc.InflateRect(-1,-1); cxt_->DrawRectangle( rcc, wakuclr, 2.0f ); cxt_->FillRectangle( rcc, fillclr ); } void DrawFillRect( D2DContext& cxt, const D2D1_RECT_F& rc, ID2D1Brush* wakuclr,ID2D1Brush* fillclr, float width ) { _ASSERT( width > 0 ); //DrawFillRectEx( cxt.cxt, rc, wakuclr, fillclr, width );// Line is FillRectangle. DRAWFillRect(cxt.cxt, rc, wakuclr, fillclr, width); } void DrawFillRectTypeS( D2DContext& cxt, const D2D1_RECT_F& rc, ID2D1Brush* fillclr ) { FRectF yrc(rc); yrc.InflateRect(-1,-1); cxt.cxt->FillRectangle( yrc, fillclr ); } ///TSF//////////////////////////////////////////////////////////////////////////////////////////// static bool bCaret = false; static LARGE_INTEGER gtm,pregtm; // activeを黒色から即スタート void CaretActive() { bCaret = true; QueryPerformanceCounter(&pregtm); } bool DrawCaret(D2DContext& cxt, const FRectF& rc ) { QueryPerformanceCounter(&gtm); float zfps = (float)(gtm.QuadPart-pregtm.QuadPart) / (float)__s_frequency_.QuadPart; if ( zfps > 0.4f ) { pregtm = gtm; bCaret = !bCaret; } else { cxt.cxt->SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED); cxt.cxt->FillRectangle( rc, ( bCaret ? cxt.black : cxt.white )); cxt.cxt->SetAntialiasMode( D2D1_ANTIALIAS_MODE_PER_PRIMITIVE); } return true; } ////////////////////////////////////////////////////////////////////////////////////////////////// CComPtr<ID2D1SolidColorBrush> MakeBrsuh( D2DContext& cxt, D2D1_COLOR_F clr ) { CComPtr<ID2D1SolidColorBrush> br; cxt.cxt->CreateSolidColorBrush( clr, &br ); return br; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void SingleLineText::CreateLayoutEx(D2DContextText& cxt,IDWriteTextFormat* fmt, const FRectF& rc, LPCWSTR str, int len, int align ) { DWRITE_TEXT_METRICS tm; auto prv = fmt->GetWordWrapping(); fmt->SetWordWrapping( DWRITE_WORD_WRAPPING_NO_WRAP ); //改行なしへ、 cxt.GetLineMetric( rc.Size(), fmt, str, len, tm ); FRectF rcX(rc); float center = rcX.top + (rcX.bottom-rcX.top)/2.0f; rcX.top = center - tm.height/2; rcX.bottom = rcX.top + tm.height; if ( align == 2 ) rcX.left = rcX.right-tm.width; else if ( align == 1 ) { rcX.left = (rcX.right+rcX.left)/2.0f - tm.width / 2.0f; rcX.right = rcX.left + tm.width; } if ( textlayout.p ) textlayout.Release(); ptLineText = rcX.LeftTop(); FSizeF sz = rcX.Size(); cxt.cxt->insins->wrfactory->CreateTextLayout(str,len, fmt ,sz.width, sz.height, &textlayout ); fmt->SetWordWrapping( prv ); } void SingleLineText::CreateLayout(D2DContextText& cxt, const FRectF& rc, LPCWSTR str, int len, int align ) { xassert( rc.top == 0 ); // for vertical line calc. CreateLayoutEx(cxt,cxt.textformat, rc, str, len, align ); } void SingleLineText::DrawText(D2DContext& cxt, ID2D1Brush* foreclr ) { xassert( textlayout.p ); cxt.cxt->DrawTextLayout( ptLineText,textlayout,foreclr ); } //////////////////////////////////////////////////////////////////////////////////////// FRectF FRectFV( _variant_t& x,_variant_t& y,_variant_t& cx,_variant_t& cy ) { float fx; x.ChangeType( VT_R4 ); fx = x.fltVal; float fy; y.ChangeType( VT_R4 ); fy = y.fltVal; float fcx; cx.ChangeType( VT_R4 ); fcx = cx.fltVal+fx; float fcy; cy.ChangeType( VT_R4 ); fcy = cy.fltVal+fy; return FRectF(fx,fy,fcx,fcy ); } FSizeF FSizeFV( _variant_t& cx,_variant_t& cy ) { float fcx; cx.ChangeType( VT_R4 ); fcx = cx.fltVal; float fcy; cy.ChangeType( VT_R4 ); fcy = cy.fltVal; return FSizeF( fcx,fcy ); } FPointF FPointFV( _variant_t& cx,_variant_t& cy ) { float fcx; cx.ChangeType( VT_R4 ); fcx = cx.fltVal; float fcy; cy.ChangeType( VT_R4 ); fcy = cy.fltVal; return FPointF( fcx,fcy ); } FString FStringV( _variant_t& s ) { s.ChangeType( VT_BSTR ); return s.bstrVal; } bool CreateBitmapPartBrush( D2DContext& cxtbase, const FSizeF& size, DrawFunction drawfunc, OUT ID2D1BitmapBrush **ppBitmapBrush ) { // 画面のbitmapを作成、画面のハードコピー, FillRectで表示(0,0から引きつめられる) // cxtのリソースをすべて再作成する必要あり。 D2DContext cxt; ID2D1RenderTarget* pRenderTarget = cxtbase.cxt; CComPtr<ID2D1BitmapRenderTarget> pCompatibleRenderTarget; // create cmpati render target. HRESULT hr = pRenderTarget->CreateCompatibleRenderTarget( size, &pCompatibleRenderTarget ); if (SUCCEEDED(hr)) { if (SUCCEEDED(hr)) { pCompatibleRenderTarget->BeginDraw(); { // change rendertarget. D2D1_MATRIX_3X2_F mat = Matrix3x2F::Identity(); pCompatibleRenderTarget->SetTransform(mat); cxt.cxt = pCompatibleRenderTarget; drawfunc( cxt ); } pCompatibleRenderTarget->EndDraw(); // Create bitmap CComPtr<ID2D1Bitmap> pGridBitmap; hr = pCompatibleRenderTarget->GetBitmap(&pGridBitmap); if (SUCCEEDED(hr)) { // Choose the tiling mode for the bitmap brush. D2D1_BITMAP_BRUSH_PROPERTIES brushProperties = D2D1::BitmapBrushProperties(D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP); // Create the bitmap brush. hr = pRenderTarget->CreateBitmapBrush(pGridBitmap, brushProperties, ppBitmapBrush); } } } return ( hr == S_OK ); } ///////////////////////////////////////////////////////////////////////////////// //std::map<std::wstring, CComPtr<ID2D1SolidColorBrush>> ColorBank::bank_; // //CComPtr<ID2D1SolidColorBrush> ColorBank::SolidColorBrush( D2DContext& cxt, LPCWSTR name, D2D1_COLOR_F defaultColor ) //{ // auto it = bank_.find( name ); // // if ( it == bank_.end()) // { // CComPtr<ID2D1SolidColorBrush> br; // cxt.cxt->CreateSolidColorBrush( defaultColor, &br ); // // bank_[name] = br; // // it = bank_.find( name ); // } // // return it->second; //} ///////////////////////////////////////////////////////////////////////////////////////////////////////// void D2DStringLayout::Draw( D2DContext& cxt, ID2D1Brush* br ) { cxt.cxt->DrawTextLayout( pt_, tl_, br ); } D2DContextBase D2DStringLayout::CreateFont( D2DContext& cxt, LPCWSTR fontname, float height, DWRITE_FONT_WEIGHT bold ) { D2DContextBase ret; ret.cxt = cxt.cxt; auto hr = cxt.insins->wrfactory->CreateTextFormat(fontname,0, bold,DWRITE_FONT_STYLE_NORMAL,DWRITE_FONT_STRETCH_NORMAL,height,L"",&ret.text); xassert( HR(hr)); ret.wfactory = cxt.insins->wrfactory; return ret; } DWRITE_TEXT_METRICS D2DStringLayout::GetMetrics() { xassert( tl_ ); DWRITE_TEXT_METRICS tm; tl_->GetMetrics(&tm); return tm; } bool D2DStringLayout::CreateCenterText( D2DContextBase& cxt, const FRectF& rc, LPCWSTR str, int len, int align ) { if ( !IsFirst()) Clear(); CComPtr<IDWriteTextLayout> tl; FSizeF sz = rc.GetSize(); if (HR(cxt.wfactory->CreateTextLayout(str,len, cxt.text,sz.width, sz.height, &tl ))) { DWRITE_TEXT_METRICS tm; tl->GetMetrics(&tm); FRectF rcX(rc); float center = rcX.top + (rcX.bottom-rcX.top)/2.0f; rcX.top = center - tm.height/2; rcX.bottom = rcX.top + tm.height; if ( align == 2 ) rcX.left = rcX.right-tm.width; else if ( align == 1 ) { rcX.left = (rcX.right+rcX.left)/2.0f - tm.width / 2.0f; rcX.right = rcX.left + tm.width; } tl_ = tl; pt_ = rcX.LeftTop(); } else return false; return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// };
3c173b9fa61a1059d051836a17e70c9b98dd607a
5b83a3eef49ac004b98ff1ff9ce30989fd85c567
/Infoarena/Roy-FloydAE/royfloyd.cpp
fb8f7eb93105a11c829ae5e2aded3ee779424898
[]
no_license
floreaadrian/AlgCodes
cd0dfe331d2b1acae26ead05c4be07d6c3c05f52
b3ba2472ba256a73daea334c22bbca282ff3a24d
refs/heads/master
2020-05-25T14:34:27.475469
2019-05-21T13:49:35
2019-05-21T13:49:35
187,846,889
1
0
null
null
null
null
UTF-8
C++
false
false
614
cpp
royfloyd.cpp
#include<fstream> using namespace std; int a[101][101],n; ifstream fin("royfloyd.in"); ofstream fout("royfloyd.out"); void citire() { int i,j; fin>>n; for(i=1;i<=n;i++) for(j=1;j<=n;j++) fin>>a[i][j]; } void royfloyd() { int i,j,k; for(k=1;k<=n;k++) for(i=1;i<=n;i++) for(j=1;j<=n;j++) if(a[i][k] && a[k][j] && (a[i][j]>a[i][k]+a[k][j] || !a[i][j]) && i!=j) a[i][j]=a[i][k]+a[k][j]; } void afisare() { int i,j; for(i=1;i<=n;i++){ for(j=1;j<=n;j++) fout<<a[i][j]<<" "; fout<<"\n"; } } int main() { citire(); royfloyd(); afisare(); return 0; }
28dd985d8d9be6fc1c8efd7c9dc5551f110ac0a6
f1996b0514b76431c556a2d335d3dd2d9adc3249
/integration/test_workspace/src/test-cmake/hello.cpp
0b45ec12281a3e8a677a5449cf7cd64425d80d74
[ "Apache-2.0", "MIT" ]
permissive
colcon/colcon-bundle
9c968eca8eaa1a9a93372ae539c3dc8b32df550a
23be7df319a141af5a042356e6401d43f55dd845
refs/heads/master
2023-05-11T14:01:03.125195
2023-03-27T23:33:58
2023-03-27T23:33:58
152,110,200
35
30
Apache-2.0
2023-03-27T23:34:00
2018-10-08T16:16:09
Python
UTF-8
C++
false
false
159
cpp
hello.cpp
// A simple program that computes the square root of a number #include <stdio.h> int main (int argc, char *argv[]) { printf("Hello World!\n"); return 0; }
d091d3f8f0d82473e06368ac97a3274b92a82dfe
0f2b08b31fab269c77d4b14240b8746a3ba17d5e
/onnxruntime/core/providers/cpu/nn/pool.h
7796b28b8369b5e0e11fa4ca8e7153fc023153dc
[ "MIT" ]
permissive
microsoft/onnxruntime
f75aa499496f4d0a07ab68ffa589d06f83b7db1d
5e747071be882efd6b54d7a7421042e68dcd6aff
refs/heads/main
2023-09-04T03:14:50.888927
2023-09-02T07:16:28
2023-09-02T07:16:28
156,939,672
9,912
2,451
MIT
2023-09-14T21:22:46
2018-11-10T02:22:53
C++
UTF-8
C++
false
false
2,038
h
pool.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "core/providers/cpu/nn/pool_base.h" namespace onnxruntime { template <typename T, typename PoolType> class Pool : public OpKernel, public PoolBase { public: Pool(const OpKernelInfo& info) : OpKernel(info), PoolBase(info) { const std::string& op_name = info.GetKernelDef().OpName(); if (op_name == "LpPool" || op_name == "GlobalLpPool") { pool_context_.init(info); } } ~Pool() override = default; Status Compute(OpKernelContext* context) const override; private: PoolProcessContext pool_context_; }; // For averagepool v19 and beyond // version 19: Added dilations template <typename T> class AveragePoolV19 : public OpKernel, public PoolBase { public: AveragePoolV19(const OpKernelInfo& info) : OpKernel(info), PoolBase(info) { } Status Compute(OpKernelContext* context) const override; private: int64_t p_; }; // For maxpool v8 and beyond // version 8: Added storage_order And Indices // version 10: Added ceil_mode // version 11: Added dilations // version 12: Added int8/uint8 support class MaxPoolV8 : public OpKernel, public PoolBase { template <typename T> struct ComputeHelper { Status operator()(const MaxPoolV8* inst, OpKernelContext* context) const { return inst->ComputeImpl<T>(context); } }; public: MaxPoolV8(const OpKernelInfo& info) : OpKernel(info), PoolBase(info) {} Status Compute(OpKernelContext* context) const override; private: template <typename T> Status ComputeImpl(OpKernelContext* context) const; }; // For lppool v18 and beyond // version 18: Added ceil_mode and dilations template <typename T> class LpPoolV18 : public OpKernel, public PoolBase { public: LpPoolV18(const OpKernelInfo& info) : OpKernel(info), PoolBase(info) { ORT_ENFORCE(info.GetAttr<int64_t>("p", &p_).IsOK()); } Status Compute(OpKernelContext* context) const override; private: int64_t p_; }; } // namespace onnxruntime
630e6b85a0d051dcc551f31d1889b6995a3b3cc8
d33d14c8b9716ed6130617721bc904c5c69a2953
/lowrisc-chip/riscv-tools/lowrisc-tag-tests/tests/amo_tag_check_test.cc
96293f78981e9ee8f5bb0e7e98fc7633a4780939
[ "LicenseRef-scancode-bsd-3-clause-jtag" ]
permissive
ivanseminara/project
393ba080018f157b29ab6caa979c57668b34a9e7
8e001b9605b88ea3d8d9ce02465ae0d6a779f178
refs/heads/master
2021-01-01T03:54:38.269602
2016-05-05T23:11:31
2016-05-05T23:11:31
58,165,146
1
0
null
null
null
null
UTF-8
C++
false
false
5,280
cc
amo_tag_check_test.cc
/** * * Test tag checks for LR/SC double word and word access, and atomic memory * operations (both double word and word). * * Currently these tests only execute correctly when tags are not automatically * copied from memory into register tags and vice versa. */ #include<stdlib.h> #include<stdio.h> #include<stdint.h> #include"env/tag.h" #define test_body(datatype, load_asm, store_asm, location) ({ \ int i, limit = sizeof(uint64_t) / sizeof(datatype); \ for(i = 0; i < limit; i++) { \ datatype *pointer = (datatype *) location; \ pointer = pointer + i; \ datatype value = 32; \ asm volatile ( #load_asm" a4, 0(%0)\n" \ "not a4, a4\n" \ #store_asm" a3 ,a4, 0(%0)\n" \ : : "r"(pointer) : "a4", "a3"); \ } }) #define amo_test(name, datatype, amo_asm) \ bool amo_##name(void *location, datatype rs2) { \ int i, limit = sizeof(uint64_t) / sizeof(datatype); \ for(i=0; i < limit; i++) { \ datatype *pointer = (datatype *) location; \ pointer = pointer + i; \ datatype value = 32; \ asm volatile ( #amo_asm" %0, %1, (%2)\n" \ : "=r"(value) \ : "r"(rs2), "r"(pointer) ); \ } \ return true; \ } bool lrsc_long(void *location) { test_body(uint64_t, lr.d, sc.d, location); return true; } bool lrsc_int(void *location) { test_body(uint32_t, lr.w, sc.w, location); return true; } amo_test(swap_word, uint32_t, amoswap.w); amo_test(swap_doubleword, uint64_t, amoswap.d); amo_test(add_word, uint32_t, amoadd.w) amo_test(add_doubleword, uint64_t, amoadd.d) amo_test(xor_word, uint32_t, amoxor.w) amo_test(xor_doubleword, uint64_t, amoxor.d) amo_test(and_word, uint32_t, amoand.w) amo_test(and_doubleword, uint64_t, amoand.d) amo_test(or_word, uint32_t, amoor.w) amo_test(or_doubleword, uint64_t, amoxor.d) amo_test(min_word, uint32_t, amomin.w) amo_test(min_doubleword, uint64_t, amomin.d) amo_test(minu_word, uint32_t, amominu.w) amo_test(minu_doubleword, uint64_t, amominu.d) amo_test(max_word, uint32_t, amomax.w) amo_test(max_doubleword, uint64_t, amomax.d) amo_test(maxu_word, uint32_t, amomaxu.w) amo_test(maxu_doubleword, uint64_t, amomaxu.d) bool load_store_checkrun(void *test_memory, bool expect_load_trap, bool expect_store_trap) { uint64_t doubleword_rs2 = 2; uint32_t word_rs2 = 2; //tests: int load_traps = expect_load_trap ? 1 : 0; int store_traps = (expect_store_trap) ? 1 : 0; printf("-- LRSC test 64bit, expect %d load and %d store traps\n", load_traps, store_traps); lrsc_long(test_memory); printf("-- LRSC test 32bit, expect %d load and %d store traps\n", load_traps*2, store_traps*2); lrsc_int(test_memory); store_traps = (!expect_load_trap && expect_store_trap) ? 1 : 0; printf("-- AMO swap test 64bit, expect %d load and %d store traps\n", load_traps, store_traps); amo_swap_doubleword(test_memory, doubleword_rs2); printf("-- AMO swap test 32bit, expect %d load and %d store traps\n", load_traps*2, store_traps*2); amo_swap_word(test_memory, word_rs2); printf("-- remaining AMO tests 64bit, expect %d load and %d store traps\n", load_traps*8, store_traps*8); amo_add_doubleword(test_memory, doubleword_rs2); amo_xor_doubleword(test_memory, doubleword_rs2); amo_and_doubleword(test_memory, doubleword_rs2); amo_or_doubleword(test_memory, doubleword_rs2); amo_min_doubleword(test_memory, doubleword_rs2); amo_minu_doubleword(test_memory, doubleword_rs2); amo_max_doubleword(test_memory, doubleword_rs2); amo_maxu_doubleword(test_memory, doubleword_rs2); printf("-- remaining AMO tests 32bit, expect %d load and %d store traps\n", load_traps*16, store_traps*16); amo_add_word(test_memory, word_rs2); amo_xor_word(test_memory, word_rs2); amo_and_word(test_memory, word_rs2); amo_or_word(test_memory, word_rs2); amo_min_word(test_memory, word_rs2); amo_minu_word(test_memory, word_rs2); amo_max_word(test_memory, word_rs2); amo_maxu_word(test_memory, word_rs2); return true; } bool load_store_check() { // create memory long* test_memory = (long *) malloc(sizeof(long)); if(test_memory == NULL) { fprintf(stderr, "Error - could not allocate enough memory!\n"); return false; } printf("Memory allocated at %p\n", test_memory); char mem_tag = 1; *test_memory = 0xDEADBEEFDEADBEEF; store_tag(test_memory, mem_tag); printf(" ---- Test load and store traps ----\n"); read_write_load_csr(0b10); // trap on value 0x01 read_write_store_csr(0b10); // trap on value 0x01 load_store_checkrun(test_memory, true, true); printf("---- Test no traps ----\n"); read_write_load_csr(0b100); read_write_store_csr(0b100); load_store_checkrun(test_memory, false, false); printf("---- Test only load traps ----\n"); read_write_load_csr(0b10); read_write_store_csr(0b100); load_store_checkrun(test_memory, true, false); printf("---- Test only store traps ----\n"); read_write_load_csr(0b100); read_write_store_csr(0b10); load_store_checkrun(test_memory, false, true); // reset CSRs: read_write_load_csr(0); read_write_store_csr(0); return true; } int main (int argc, char **argv) { bool success = true; success = success && load_store_check(); if (success) printf("All tests passed!\n"); }
5baed73c4b8e6e7c05fd7daba9823bf1695f2a54
528154224bb3038de149d12a1b0b5229d4675159
/contests/control_test_2/contest_test_2.h
7248bd7c52afd337c64d6595198384a1e180a39f
[]
no_license
MeevereMipt/infa_sem2_2021
9084afbb9f4f7eaa2efff746b490ae9a01c0340d
9521970e129228c05ec307846ed83683252a5995
refs/heads/master
2023-04-12T09:09:54.433283
2021-05-14T09:14:33
2021-05-14T09:14:33
337,356,745
0
0
null
null
null
null
UTF-8
C++
false
false
631
h
contest_test_2.h
// // Created by Meevere on 5/14/2021. // #ifndef MIPT2021_2SEM_CONTEST_TEST_2_H #define MIPT2021_2SEM_CONTEST_TEST_2_H namespace control2 { int task1(); // int task2(); // int task3(); // int task4(); // int task5(); int task6(); int task(char index){ switch(index) { case '1': return task1(); // case '2': return task2(); // case '3': return task3(); // case '4': return task4(); // case '5': return task5(); case '6': return task6(); default: return 1; } } } #endif //MIPT2021_2SEM_CONTEST_TEST_2_H
8bbd89f5fc05726b9d6d816feb239145203637d9
13b9df991be7e150333a2cea9d16a58c4cddea61
/dong/cpp/p_16.cpp
20405e1eb69f0bfd849e14c39ec0a34e693519e7
[]
no_license
Mulavar/LeetCode
1aedb8c7a4ef18611418e80e8c41c7f63b2115cc
e50a7129301f9c68e72276c38ce11701897dd929
refs/heads/master
2021-07-20T10:04:47.359105
2021-06-24T16:10:55
2021-06-24T16:12:20
127,959,776
0
1
null
2021-05-07T05:19:35
2018-04-03T19:40:29
Java
UTF-8
C++
false
false
915
cpp
p_16.cpp
#include <cstdio> #include <vector> using namespace std; /* 3Sum Closest */ int threeSumClosest(vector<int> &nums, int target) { sort(nums.begin(), nums.end()); int sz = nums.size(), max_sub = INT_MAX, flag = 0; for (int i = 0; i < sz - 2; i++) { if (i > 0 && nums[i] == nums[i - 1]) continue; int l = i + 1, r = sz - 1; while (l < r) { int tmp = nums[l] + nums[r] + nums[i]; if (tmp == target) return target; else { max_sub = min(max_sub, abs(target - tmp)); flag = max_sub == abs(target - tmp) ? target - tmp : flag; if (target - tmp > 0) l++; else r--; } } } if (flag > 0) return target - max_sub; else return target + max_sub; }
1bc80a499615db4f5d3e358bd4463aa51156c530
55ee5259b9b167f05c53a862d266ccc42d64eb6a
/trunk/SonarGaussian/CloseLoopAnaliseResult.cpp
fba99aaf748c989a00521e8adcf989c1cdcd7e3d
[]
no_license
matheusbg8/SonarGraph
0829a4477271a34ead6c2aaaed5ac810dcada515
88beb18a6650194b352b195fc2a22cf256ec9cc8
refs/heads/master
2021-01-19T11:14:58.651049
2017-02-16T23:18:05
2017-02-16T23:18:05
82,235,034
10
0
null
null
null
null
UTF-8
C++
false
false
11,020
cpp
CloseLoopAnaliseResult.cpp
#include "CloseLoopAnaliseResult.h" #include <cstdio> #include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/contrib/contrib.hpp> using namespace std; using namespace cv; CloseLoopAnaliseResult::CloseLoopAnaliseResult(const char *destPath): destPath(destPath) { } void CloseLoopAnaliseResult::loadResultFrameInformations(const char *fileName) { frResults.clear(); cout << "Loading frame descriptions" << endl; FILE *f =fopen((destPath + fileName).c_str(),"r"); if(f == 0x0) { cout << "File FrameDescriptions.csv not found" << endl; return; } // Ignore first line fscanf(f, "%*[^\n]\n", NULL); unsigned u, nV,nE; while(fscanf(f,"%u,",&u)!= -1) { fscanf(f,"%u,", &nV); fscanf(f,"%u", &nE); frResults.push_back(PUU(nV,nE)); } } void CloseLoopAnaliseResult::loadResultOfMatch(const char *prefix) { resultGraph.clear(); cout << "Loading match results" << endl; unsigned nFrs= frResults.size(); resultGraph.resize(nFrs); char str[300]; unsigned u, v; float score; FILE *f=0x0; for(unsigned i =0 ; i < nFrs ; i++) { sprintf(str, "%s%04u.csv",prefix,i); f = fopen((destPath + str).c_str(),"r"); if(f == 0x0) { cout << "File " << str << " not found" << endl; continue; } // Ignore first line (It's header) fscanf(f, "%*[^\n]\n", NULL); while(fscanf(f,"%u,",&u)!= -1) { fscanf(f,"%u,", &v); fscanf(f,"%g", &score); resultGraph[u].push_back(PUF(v,score)); } fclose(f); } } void CloseLoopAnaliseResult::loadDirectResult(const char *csvFileName, unsigned nFrames) { resultGraph.clear(); cout << "Loading direct match results" << endl; FILE *f = fopen((destPath+ csvFileName).c_str(), "r"); if(f == 0x0) { cout << "CloseLoopAnaliseResult::loadDirectResult file " << csvFileName << " not found!" << endl; return; } resultGraph.resize(nFrames); for(unsigned uFr = 0 ; uFr < nFrames; uFr++) { resultGraph[uFr].reserve(nFrames-uFr); // -1 for(unsigned vFr = uFr+1 ; vFr < nFrames; vFr++) { double value; fscanf(f,"%lf", &value); if(value <0.0) value = 0.0; resultGraph[uFr].push_back(PUF(vFr,value)); } } fclose(f); } /** * @brief * Load gorund truth graph where each vertex * is one image and each edge carry the score * between two images. * (firs - dest and second - score) */ void CloseLoopAnaliseResult::loadGtMatch(const char *gtFileName) { cout << "Loading GT" << endl; gtGraph.clear(); // GTLoopDetection FILE *f = fopen((destPath + gtFileName).c_str(),"r"); if(f == 0x0) { cout << "Error to load GT results, file " << gtFileName << " not found" << endl; return; } unsigned u, v; unsigned biggestId=0; float score; gtGraph.reserve(3700); while(fscanf(f,"%u,",&u)!= -1) { fscanf(f,"%u,", &v); fscanf(f,"%g", &score); if(u >= gtGraph.size()) { gtGraph.resize((u+1)*2); } if(v >= gtGraph.size()) { gtGraph.resize((v+1)*2); } gtGraph[u].reserve(3700); gtGraph[u].push_back(PUF(v,score)); if(u > biggestId) biggestId=u; if(v > biggestId) biggestId=v; } gtGraph.resize(biggestId+1); fclose(f); } void CloseLoopAnaliseResult::normalizeResult() { cout << "Normalize" << endl; for(unsigned uFr = 0 ; uFr < resultGraph.size(); uFr++) { for(unsigned i = 0 ; i < resultGraph[uFr].size(); i++) { PUF &edge = resultGraph[uFr][i]; // < vFr , score > edge.second /= min(frResults[uFr].first,frResults[edge.first].first); } } } void CloseLoopAnaliseResult::normalizeResult2(unsigned maxValue) { cout << "Normalize2 using maxValue = " << maxValue << endl; for(unsigned uFr = 0 ; uFr < resultGraph.size(); uFr++) { for(unsigned i = 0 ; i < resultGraph[uFr].size(); i++) { PUF &edge = resultGraph[uFr][i]; // < vFr , score > if(edge.second > maxValue) edge.second = maxValue; edge.second /= maxValue; } } } float CloseLoopAnaliseResult::findGtScore(unsigned uFr, unsigned vFr) { if(uFr >= gtGraph.size()) return 0.f; // No related data found for(unsigned i = 0 ; i < gtGraph[uFr].size(); i++) { if(gtGraph[uFr][i].first == vFr) return gtGraph[uFr][i].second; } return 0.f; // No related data found } /** * @brief Save achived results into two files * ResultGraph.csv - File with score between two images * ResultFramesInformations.csv - File with image descriptions statitics * */ void CloseLoopAnaliseResult::saveResults(const char *fileName) { FILE *f = fopen((destPath + "ResultGraph.csv").c_str(),"w"); if(f == 0x0) { cout << "Erro when saving results." << endl; return; } for(unsigned u =0 ; u < resultGraph.size();u++) { for(unsigned i = u+1 ; i < resultGraph[u].size(); i++) { PUF &vertex = resultGraph[u][i]; fprintf(f,"%u,%u,%g\n",u,vertex.first,vertex.second); } } fclose(f); f = fopen((destPath + fileName).c_str(),"w"); if(f == 0x0) { cout << "Erro when saving results." << endl; return; } for(unsigned fr =0 ; fr < frResults.size();fr++) { PUU &frInfo = frResults[fr]; fprintf(f,"%u,%u,%u\n",fr, frInfo.first, frInfo.second); } fclose(f); } /** * @brief * * @param uFr */ void CloseLoopAnaliseResult::saveSplitedGTResults(unsigned uFr) { char str[300]; sprintf(str,"GTLoopDetection/GtFrame_%04u.csv", uFr); FILE *f = fopen( (destPath + str).c_str() ,"w"); if(f == 0x0) { cout << "Error when saving file " << str << endl; return; } for(unsigned i = 0 ; i < gtGraph[uFr].size() ; i++) { unsigned vFr = gtGraph[uFr][i].first; float score = gtGraph[uFr][i].second; fprintf(f,"%u,%u,%g\n", uFr, vFr,score); } fclose(f); } void CloseLoopAnaliseResult::saveSplitedGTResults() { for(unsigned i = 0 ;i < gtGraph.size(); i++) { saveSplitedGTResults(i); } } void CloseLoopAnaliseResult::loadAnalisyAndSave() { // ====== Results stuffs ======== // Load Frame Descriptions Statistcs loadResultFrameInformations("Results/ResultFramesInformations.csv"); // Load Frame Matchs loadResultOfMatch("Results/LoopDetections/MatchResults_fr"); // Normalize Results // normalizeResult(); normalizeResult2(23); // ===== Ground Truth Stuffs ==== // Load Ground Truth loadGtMatch("GTMatchs_gps_compass.csv"); // ====== Process and save ==== // Save GT and Result together saveAnalisyResults("Results/CompareResult.csv"); // ==== Direct Result stuffs ===== // cout << "Loading direc results" << endl; // loadDirectResult("deppLResults.csv",gtGraph.size()); // cout << "Finish Loading Direc Results" << endl; generateGTImage(); generateResultImage(); generatePairFeaturesCount(); } /** * @brief Save analisy results * */ void CloseLoopAnaliseResult::saveAnalisyResults(const char *fileName) { unsigned nFr = frResults.size(); FILE *f = fopen( (destPath + fileName).c_str(),"w"); fprintf(f,"srcId,destId,gtScore,ResultScore\n"); for(unsigned uFr = 0 ; uFr < nFr ; uFr++ ) { cout << "Saving frame " << uFr << endl; for(unsigned i= 0; i < resultGraph[uFr].size(); i++ ) { unsigned vFr = resultGraph[uFr][i].first; float rScore = resultGraph[uFr][i].second, gScore = findGtScore(uFr, vFr); fprintf(f, "%u,%u,%f,%f\n",uFr, vFr, rScore, gScore ); } } fclose(f); } void CloseLoopAnaliseResult::splitGTResults() { loadGtMatch(); saveSplitedGTResults(); } void CloseLoopAnaliseResult::generateGTImage() { unsigned nFr = gtGraph.size(); Mat gtImage(nFr,nFr, CV_8UC1); for(unsigned uFr = 0; uFr < nFr ; uFr++) { for(unsigned i = 0; i < gtGraph[uFr].size(); i++) { unsigned vFr = gtGraph[uFr][i].first; float score = gtGraph[uFr][i].second; gtImage.at<uchar>(uFr,vFr) = score*255; gtImage.at<uchar>(vFr,uFr) = score*255; } } Mat colorImg; applyColorMap(gtImage,colorImg,COLORMAP_JET); imwrite("gtImage.png",gtImage); imwrite("gtImageColor.png",colorImg); namedWindow("GT Image",WINDOW_NORMAL); imshow("GT Image", colorImg); waitKey(); } void CloseLoopAnaliseResult::generateResultImage() { unsigned nFr = resultGraph.size(); Mat resultImage(resultGraph.size(),resultGraph.size(), CV_8UC1); for(unsigned uFr = 0; uFr < nFr; uFr++) { for(unsigned i = 0; i < resultGraph[uFr].size(); i++) { unsigned vFr = resultGraph[uFr][i].first; float score = resultGraph[uFr][i].second; resultImage.at<uchar>(uFr,vFr) = score*255; resultImage.at<uchar>(vFr,uFr) = score*255; } } Mat colorImg; applyColorMap(resultImage,colorImg,COLORMAP_JET); imwrite("ResultImage.png",resultImage); imwrite("ResultImageColor.png",colorImg); namedWindow("Result Image",WINDOW_NORMAL ); imshow("Result Image", colorImg); waitKey(); } void CloseLoopAnaliseResult::generatePairFeaturesCount() { unsigned nFr = frResults.size(), minF=9999999,maxF=0; Mat frameInfImage(resultGraph.size(),resultGraph.size(), CV_8UC1); for(unsigned uFr = 0; uFr < nFr; uFr++) { for(unsigned vFr = uFr+1; vFr < nFr; vFr++) { unsigned nVu = frResults[uFr].first, nVv = frResults[vFr].first, nFeatures = min(nVu,nVv); if(nFeatures <minF) minF = nFeatures; if(nFeatures >maxF) maxF = nFeatures; frameInfImage.at<uchar>(uFr,vFr) = nFeatures; frameInfImage.at<uchar>(vFr,uFr) = nFeatures; } } normalize(frameInfImage,frameInfImage,0,255,NORM_MINMAX); Mat colorImg; applyColorMap(frameInfImage,colorImg,COLORMAP_JET); imwrite("frameInfImage.png",frameInfImage); imwrite("frameInfImageColor.png",colorImg); FILE *f = fopen("frameInfImageNormMinMax.csv","w"); fprintf(f,"#minFeturesCount,maxFeaturesCount\n%u,%u",minF,maxF); fclose(f); namedWindow("Frame Inf Image",WINDOW_NORMAL ); imshow("Frame Inf Image", colorImg); waitKey(); }
60c7911c3f3b76a83398c67d81faed4c14d3c382
0d85b61f652acf322bc8e1afe80b9f49c5b0ddcc
/Utils.h
091dc04ce33279f3642382da01bfd5e1b90f6c86
[]
no_license
kutty-kumar/AlgoRhythms
b1bcdd28b46c0c7b39169d565c54aa0ad2b23d5b
8c6ac484596605127b50760ea181980b34a156f3
refs/heads/master
2021-05-02T06:35:20.818921
2018-05-07T04:25:27
2018-05-07T04:25:27
120,860,855
0
0
null
null
null
null
UTF-8
C++
false
false
277
h
Utils.h
/* Created by kumard on 24/4/18. */ #ifndef ALGORHYTHMS_UTILS_H #define ALGORHYTHMS_UTILS_H #include <cstdio> void printArray(int *input, int len){ for(int i=0;i<len;i++){ std::printf("%d ",input[i]); } std::printf("\n"); } #endif //ALGORHYTHMS_UTILS_H
d9c8ac1899d744175bb2ca70b5eb6d8e2a589ded
c5f00505a1af23c65173f56ba786b45068fadeba
/Registro/TP8/Ejercicio3.cpp
1af8b921297139c7a45ce38c631747fcfe1bf1d5
[]
no_license
lucasbravi2019/Cpp
32e72397d16e51eeef8c35928e9e6743eccbd837
c433985fdfb5838f67fef5de2c0ecd68950c39f4
refs/heads/main
2023-08-07T21:50:34.729477
2021-09-29T15:24:21
2021-09-29T15:24:21
399,172,271
0
0
null
null
null
null
UTF-8
C++
false
false
2,679
cpp
Ejercicio3.cpp
#include <iostream> #include <string> using namespace std; struct { struct { string apellido_nombre; int edad; string obra_social; } paciente; string piezas_dentales[20]; struct { int mes; int anio; } ultima_visita; } consultorio[5]; void cargarDatos() { for (int i = 0; i < 5; i++) { consultorio[i].paciente.apellido_nombre = "Nombre " + to_string(i + 1); consultorio[i].paciente.edad = 20 + i; consultorio[i].paciente.obra_social = "Obra social " + to_string(i + 1); consultorio[i].ultima_visita.anio = 2017 + i; consultorio[i].ultima_visita.mes = i * 2; for (int j = 0; j < 20; j++) { int aleatorio = (rand() % 5) + 1; if (aleatorio == 1) { consultorio[i].piezas_dentales[j] = "S"; } if (aleatorio == 2) { consultorio[i].piezas_dentales[j] = "A"; } if (aleatorio == 3) { consultorio[i].piezas_dentales[j] = "I"; } if (aleatorio == 4) { consultorio[i].piezas_dentales[j] = "C"; } if (aleatorio == 5) { consultorio[i].piezas_dentales[j] = "U"; } } } } void mostrarDatos() { for (int i = 0; i < 5; i++) { cout << "Nombre y apellido: " << consultorio[i].paciente.apellido_nombre << "\n"; cout << "Edad: " << consultorio[i].paciente.edad << "\n"; cout << "Obra social: " << consultorio[i].paciente.obra_social << "\n"; cout << "Anio ultima visita: " << consultorio[i].ultima_visita.anio << "\n"; cout << "Mes ultima visita: " << consultorio[i].ultima_visita.mes << "\n"; for (int j = 0; j < 20; j++) { cout << "Pieza dental " << to_string(j + 1) << "\n"; cout << consultorio[i].piezas_dentales[j] << "\n"; } } } void consulta(int anio) { for (int i = 0; i < 5; i++) { if (consultorio[i].ultima_visita.anio == anio) { for (int j = 0; j < 20; j++) { if (consultorio[i].piezas_dentales[j] == "I") { cout << "El paciente " << consultorio[i].paciente.apellido_nombre << " debe realizar una consulta \n"; break; } } } } } int main(int argc, char const *argv[]) { cargarDatos(); mostrarDatos(); int anio; cout << "Introduzca anio \n"; cin >> anio; consulta(anio); return 0; }
6890b9d772e48c91435a49f43b163044b5f68b53
d96935be38daf50d57317c488721ed2c4c8f490b
/jetpack/src/ModulesTable.h
b24d434d7e020984b5e7866a75b5ede3d50ded13
[ "MIT" ]
permissive
Finasia/jetpack.js
e0ce35517cf5da3baadaf8aaaa9fe5ea01392e7c
1961e989ab65158cc7600f32d7b56b4c0238f6e2
refs/heads/master
2023-04-04T05:48:36.404857
2021-04-08T15:36:19
2021-04-08T15:36:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
847
h
ModulesTable.h
// // Created by Duzhong Chen on 2021/3/25. // #pragma once #include <mutex> #include <atomic> #include "Utils.h" #include "ModuleFile.h" namespace jetpack { struct ModulesTable { public: ModulesTable() = default; /** * absolute path -> module */ HashMap<std::string, Sp<ModuleFile>> pathToModule; HashMap<int32_t, Sp<ModuleFile>> idToModule; inline void insert(const Sp<ModuleFile>& mf) { std::lock_guard guard(m); insertWithoutLock(mf); } Sp<ModuleFile> createNewIfNotExists(const std::string& path, bool& isNew); // nullable! Sp<ModuleFile> findModuleById(int32_t id); int32_t ModCount() const; private: std::mutex m; void insertWithoutLock(const Sp<ModuleFile>& mf); }; }
8fe59ce4db5b960cf0e0d5dc23772bf9d2c069ba
24a4d747cb852edd368a133f7672c734d803ef1e
/IA/ItemAssistantHook/CUSTOM/CreatePlayerItemHook.cpp
b910185963ef102c1a1b32c1e37c4a2598df0542
[]
no_license
haapanen/iagd
c291506f3f4c161952d860bb669600bd574f0a9c
c22322f28201e3e193bf3612b6cd2048f7f61f8e
refs/heads/master
2020-05-05T10:25:35.561067
2019-03-30T09:25:41
2019-03-30T09:25:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
138
cpp
CreatePlayerItemHook.cpp
#include "CreatePlayerItemHook.h" CreatePlayerItemHook::CreatePlayerItemHook() { } CreatePlayerItemHook::~CreatePlayerItemHook() { }
7a4fbdeada2dc79776bb8577113390fa23b65635
d7403eda9ca6ee928d4794bfba16a24e1e25941c
/heron/common/src/cpp/network/misc/echoserver.cpp
319c64abcdc728b04ba273844ccc6a776ef41aaa
[ "Apache-2.0" ]
permissive
sbilly/heron
27e66e51d9e165bfe8f2bbc45dc5ba15988f26fd
d8cc6977791dd3d8ed4333562e2ce249646a5226
refs/heads/master
2021-07-19T07:13:35.196110
2016-07-05T17:38:21
2016-07-05T17:38:21
62,685,329
1
0
Apache-2.0
2021-01-26T21:19:15
2016-07-06T02:38:46
Java
UTF-8
C++
false
false
909
cpp
echoserver.cpp
#include "core/network/misc/echoserver.h" #include <iostream> EchoServer::EchoServer(EventLoopImpl* eventLoop, const NetworkOptions& _options) : Server(eventLoop, _options) { InstallRequestHandler(&EchoServer::HandleEchoRequest); } EchoServer::~EchoServer() { } void EchoServer::HandleNewConnection(Connection*) { std::cout << "EchoServer accepting new connection\n"; } void EchoServer::HandleConnectionClose(Connection*, NetworkErrorCode _status) { std::cout << "Connection dropped from echoserver with status " << _status << "\n"; } void EchoServer::HandleEchoRequest(REQID _id, Connection* _connection, EchoServerRequest* _request) { // cout << "Got a echo request " << _request->echo_request() << endl; EchoServerResponse response; response.set_echo_response(_request->echo_request()); SendResponse(_id, _connection, response); delete _request; }
5c72f932c1dcffff855971c95fd5aa57c1ee792d
df314895f8f347db2f4888edba86b5554280e900
/Source/NeuroevolutionAgents/AgentLaunchEnvironmentState.cpp
45902599914b780bfdc4c79e58c823987dca2d08
[]
no_license
FotisSpinos/NeuroevolutionAgents
55d762aeefa5a47063343aa11e6a05fbd62cb5c7
5bb6896a7b308d8c453257887be2cff81206ed5c
refs/heads/master
2022-12-14T02:23:19.042850
2020-09-12T21:54:11
2020-09-12T21:54:11
259,297,657
0
0
null
null
null
null
UTF-8
C++
false
false
791
cpp
AgentLaunchEnvironmentState.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "AgentLaunchEnvironmentState.h" #include "NEAT/network.h" #include "Directories.h" #include "UnrealNNSaverLoader.h" void AAgentLaunchEnvironmentState::InitState() { nn = saverLoader->LoadFromFile(TRAINED_AGENTS + FString("BestAgent.txt")); nn == nullptr ? validNN = false : validNN = true; } void AAgentLaunchEnvironmentState::UpdateState() { //dont allow the state to update if the neural network is invalid if (!validNN) return; // add inputs to the neural network nn->load_sensors(observations[0]); // activate nn nn->activate(); // get nn outputs for (int i = 0; i < nn->outputs.size(); i++) { inputs[0][i] = nn->outputs[i]->activation - 0.5; } // flush nn nn->flush(); }
56a86d80f1493db576e02a0d3ea1c9bdd41fe257
40690f5243c1a30c31336d7b47a0c875cb5a9f67
/HW6/HW6/GTUVector.cpp
a3ac101e158cc42acd2fc66ef0086834bf47c1ba
[]
no_license
sYuksekli/Object-Oriented-Programming
758fe6d046cbd98bc2dfcdf5819719ae76242545
8920c5af78ee88736a99db690e98abed4300d43c
refs/heads/master
2022-12-05T04:02:06.382566
2020-08-30T18:27:34
2020-08-30T18:27:34
239,838,562
0
0
null
null
null
null
UTF-8
C++
false
false
4,170
cpp
GTUVector.cpp
#include "GTUVector.h" namespace GtuSTL { // No parameter constructor template <class T> GTUVector<T>::GTUVector():GTUContainer<T>() { // Empty } // Constructor to initialize acording to capacity value. template <class T> GTUVector<T>::GTUVector(int Capacity):GTUContainer<T>(Capacity) { // Empty } // Checks whether vector is empty template <class T> bool GTUVector<T>::empty() const noexcept(true){ if (this->_size == 0) return true; return false; } // Return size of the vector template <class T> int GTUVector<T>::size() const noexcept(true){ return this->_size; } // Returns the capacity of the vector template <class T> int GTUVector<T>::max_size() const noexcept(true){ return this->capacity; } // Inserts an element according to given parameter. // First parameter indicates the position and second parameter is the value to be inserted. // Returns an iterator that points to inserted element. template <class T> GTUIterator<T> GTUVector<T>::insert(const GTUIterator<T>& iter ,const T& element) noexcept(false){ try{ int sizeCounter = 0; // If vector is full, allocate new space if (this->_size == this->capacity) { shared_ptr<T> tmpPtr(new T[this->capacity]); for (int i = 0; i < this->_size ; ++i) (tmpPtr.get())[i] = (this->container.get())[i]; this->capacity *= 2; shared_ptr<T> tmp(new T[this->capacity], default_delete<T[]>()); this->container = tmp; for (int i = 0; i < this->_size ; ++i) (this->container.get())[i] = (tmpPtr.get())[i]; } // If it is the first element to be inserted if (this->empty()) { (this->container.get())[0] = element; ++this->_size; GTUIterator<T> it = begin(); sizeCounter = 1; return it; } // If not else { int index = 0; GTUIterator<T> it; for (it = this->begin(); it != iter; ++it) ++index; // Find the position using iterator parameter shared_ptr<T> tmpPtr2(new T[this->capacity]); for (int i = 0; i < this->_size ; ++i) (tmpPtr2.get())[i] = this->container.get()[i]; (this->container.get())[index] = element; // Insert new element ++(this->_size); // Increase used space for (int i = index+1; i < this->_size; ++i){ (this->container.get())[i] = (tmpPtr2.get())[i-1]; // Shift every element to right } sizeCounter = 1; return it; } if (sizeCounter == 0){ throw invalid_argument("The position that is sended is invalid"); } } catch(invalid_argument& e){ cerr << "Exception caught:" << e.what() << endl; } } // Erase an element according to the given position. template <class T> GTUIterator<T> GTUVector<T>:: erase(const GTUIterator<T>& iter) noexcept(true){ int index = 0; GTUIterator<T> it; for (it = this->begin(); it != iter ; ++it) ++index; // Find the location of the element to be erased --(this->_size); // Decrease used space for (int i = index; i < this->_size; ++i) (this->container.get())[i] = (this->container.get())[i+1]; // Shift every element to left return it; } // Clears the vector template <class T> void GTUVector<T>::clear() noexcept(true){ shared_ptr<T> tmp(new T[this->capacity], default_delete<T[]>()); // Clear all the element, allocate new space this->container = tmp; this->_size = 0; // used space is zero } // Return an iterator to beginnig of the vector template <class T> GTUIterator<T> GTUVector<T>::begin() noexcept(true){ T* tmpPtr = &this->container.get()[0]; GTUIterator<T> tmpIt(tmpPtr); return tmpIt; } // Return an iterator to the end of the vector template <class T> GTUIterator<T> GTUVector<T>::end() noexcept(true){ T* tmpPtr = &this->container.get()[this->_size]; GTUIterator<T> tmpIt(tmpPtr); return tmpIt; } // Index operator overloading template <class T> T& GTUVector<T>::operator[](int index) noexcept(true){ return (this->container.get())[index]; } // Index operator overloading for const objects template <class T> const T& GTUVector<T>::operator[](int index) const noexcept(true){ return (this->container.get())[index]; } }
b2e4c7d75ac97397b9ce747d11cebfd283d63d23
b11b140ef2fbb3e3e2d0eb53fdbe4c8943ad5ebb
/codeforces/2015theEnd/B/b.cpp
17cd0957f8d1db54a90a98919e69cd63ba0076db
[]
no_license
jer22/OI
ea953208ab43542c51eada3c62ef529a6c14588e
545c2424f277a6626b0f22fb666edd8c37e7328b
refs/heads/master
2021-04-18T22:57:05.678732
2017-11-02T15:40:34
2017-11-02T15:40:34
27,431,322
1
0
null
null
null
null
UTF-8
C++
false
false
569
cpp
b.cpp
#include <bits/stdc++.h> using namespace std; long long l, r; int get(long long x) { if (!x) return 0; if (x == 1) return 0; long long m = x; int idx = 0; bool flag = false; int cu = 0; int cc = 0; while (m) { cu++; if (!(m & 1)) { cc++; idx = cu; } m >>= 1; } int ans = 0; for (int i = cu - 2; i; i--) { // cout << i << endl; ans += i; } ans += cu - idx - 1; if (cc == 1) ans++; return ans; } int main() { // freopen("b.in", "r", stdin); cin >> l >> r; int a = get(l - 1); int b = get(r); cout << b - a << endl; return 0; }
67478c40f6fdc893eea0109d1a36f01f67961f23
fb227e3635b5c06e49bad48928f7b6d3254c4dca
/codeforces/gym/bapc16/e.cpp
2ab2e7e009a5b3bebea5ef527e3a1f98cb464064
[]
no_license
BryanValeriano/marathon
5be2ab354e49187c865f0296f7dfb5ab3c3d6c9b
8dadfad7d1a6822f61ba5ed4a06e998541515634
refs/heads/master
2022-09-11T00:06:14.982588
2022-09-03T17:01:30
2022-09-03T17:01:30
141,581,750
0
0
null
null
null
null
UTF-8
C++
false
false
1,675
cpp
e.cpp
#include <bits/stdc++.h> using namespace std; #define pb push_back #define eb emplace_back #define mk make_pair #define fi first #define se second #define endl '\n' typedef long long ll; typedef pair<int,int> ii; typedef vector<ii> vii; const ll INFLL = 0x3f3f3f3f3f3f3f3f; const double PI = acos(-1.0); struct graph { int size; vector<list<pair<int, ll>>> adj; graph(int n) : size(n), adj(n) {} void addEdge(int a, int b, ll c) { adj[a].emplace_back(b, c); adj[b].emplace_back(a, c); } }; ll dijkstra(graph& g, ll maxe) { vector<ll> dist(g.size, INFLL); vector<bool> visit(g.size, false); priority_queue<pair<ll, int>> q; dist[0] = 0; q.emplace(0, 0); while (!q.empty()) { auto [d, u] = q.top(); q.pop(); if (visit[u]) continue; if (u == g.size - 1) return dist[u]; visit[u] = true; for (auto& [v, w] : g.adj[u]) { if (visit[v] or w > maxe) continue; if (dist[v] > dist[u] + w) { dist[v] = dist[u] + w; q.emplace(-dist[v], v); } } } return -1; } int main() { ios_base::sync_with_stdio(false); int n, m, x; cin >> n >> m >> x; graph g(n); int a, b; ll c; for (int i = 0;i < m;i++) { cin >> a >> b >> c; g.addEdge(a - 1, b - 1, c); } ll bc = dijkstra(g, INFLL); ll l = 1, r = INFLL; ll maxcost = bc + (x * bc) / 100; while (l < r) { ll mid = (l + r) >> 1; ll x = dijkstra(g, mid); if (x == -1 or x > maxcost) l = mid + 1; else r = mid; } cout << l << endl; return 0; }
2cfd341cf43283423e849cf41f15f04f5c69a7fe
202d5dd073c9a8bec9c5d3cfa1e41a4a2dda2aa7
/Server/server.h
bb177cbae612a4dfe4bbfcd29130592afb023901
[]
no_license
Comidon/Multi-User-Spreadsheet
6dd96aab07eadd83a62efb632a5cac867a58e143
5d79512ba504ebb93c29565a5d5617575f803962
refs/heads/master
2020-03-09T22:11:24.408884
2018-04-25T01:13:52
2018-04-25T01:13:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,552
h
server.h
/* Declarations of server class * * server class is used to store connections * and provide methods to process incoming messages * * Team : Bluefly * * Last Modified : April 20th, 2018 */ #ifndef SERVER_H #define SERVER_H #include <string> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/wait.h> #include <signal.h> #include <cstring> #include <vector> #include <algorithm> #include <map> #include <unistd.h> #include <pthread.h> #include <stdlib.h> #include <sstream> #include <fstream> #include <time.h> #include "serverside_sheet.h" class server { public: server(); ~server(); // process general request void process_request(int socket, std::string input, time_t& ping_response_clock); // send disconnect to all connected clients void disconnect_all(); // send a string through a socket void send_string(int socket, std::string s); // process disconnect request void process_disconnect(int socket); // save all opened spreadsheets void save_all_open_sheets(); private: /* * -Data- * */ // lock pthread_mutex_t mtx; // socket container std::vector<int> sockets; // serverside sheet name container std::vector<std::string> ssnamelist; // <socket_id, spreadsheet_name> std::map<int, std::string> socket_user_map; // <socket,spreadsheet_name> std::map<int, std::string> socket_ssn_map; // <spreadsheet_name, spreadsheet_object> std::map<std::string, serverside_sheet*> ssn_sso_map; // <spreadsheet_name, set of socket ids who is editing the sheet> std::map<std::string, std::set<int> > ssn_socketset_map; // <command_name, command_id> std::map<std::string, int> cmd_look_up; /* * -Methods- * */ // process register request void process_register(int socket); // process load request void process_load(int socket, std::string s); // process ping request void process_ping(int socket); // process ping response request void process_ping_response(int socket, time_t& ping_response_clock); // process edit request void process_edit(int socket, std:: string s); // process focus request void process_focus(int socket, std::string s); // process unfocus request void process_unfocus(int socket); // process undo request void process_undo(int socket); // process revert request void process_revert(int socket, std::string s); // parse an int to a string std::string num2string(int Number); }; #endif
6f2caea7b75ccbf53315bd9a46ff37848e870c84
b123ae84991b346dc94477ed8ff0cf4e31149faf
/clients/vmime/include/vmime/emptyContentHandler.hpp
42c7b6adc3c9b79b7f5b8e226ebca79de97b54b1
[]
no_license
darknebuli/darknebuli-EMAIL
c92ee49c36476f710f3b1399298a5a6a3b76ba9f
decb35fd069de9430fba7f0a1d28cf4e954521af
refs/heads/master
2020-05-18T13:25:00.577314
2012-04-30T21:05:12
2012-04-30T21:05:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,600
hpp
emptyContentHandler.hpp
U2FsdGVkX19VaWJjbk95a7zJHIhb5eI5pUJ1qe4XD+MeqNOa7BzL0b1Lrm5vm28K LdVJP2ytFsSBx+gBGpcT7jmWyN655qzSwW005vldE+Lz1rjbraYD+fM/wt2A282L HQHOlwIcG4cN1AJ4UKLiVpSWSCl+LoOP7jG++V6osOREUaoIUf06N60EcBBS7m/H WtQV8a5Czga6PxYCagUKEoPYMo3T9OlDTqDMj8d0cOog27Ph6svCEFj3pWEZM5J6 T50GUT/Flcu9dPiTydT55OmxGU8Dzt0Xc5VuKPR5xzBDOXyPRi3+Ka68ZqgrSBKY LKFRm8lVObQWjDf1G/CtF0rcJErAMrOSL9JFY/Pm9SgbWsCXLW0vUOv6TCkOZMdR 5IisDBd6pgbyy35omCrrLgwHkROa6fLkKFZ7F/Cu5PRTLAX1c6DBGiP3VysYHCpz SDshAxo1qqZzn9Lh0rMSISh1SGcWE8MPISqMmK4kyyR9tQsjBW7SX+9W4lq9OrCj +wnMeJ5q8aZs4CR4h8Ntru6DoHM5bntTtUWfl5XkbbURU3ibtiitilt+WdycvBvq PUwyqd9oP/tZto29NqdCpCqNDV3Tv3Co34pE1kfqfb7xk3HOkVBhF5bXobCjmt6C q8pJbw+Inf9h5aQDk87H9Mvs6HItnhZES2P4XazC53fvsF7zbwPoyjEj5VIiIxCW lLzrIzmL8t0xsqRzIsELv8B+et0D+y2KxBYRRAVS1fBemM9gmTAcTnZGXWl63VI2 Raem7AvQR9tKQO3GQBrgskOsUk4cNHRUfSY3qSODZIf1krPvDKfPCidftNPnlIyz qVxV+yGtZEEUzm3Cv1OtQ7HmEueoczI29sCOI/SjBbRx/pKrb/OfVMIMFKCmlGda b0NOpYnFZct9nWUd9hmqLKcPJiqnR7FpLC5/1AiSVfJKV0Om2bYCD23B5/0ixBbD UP9n8TMoNIWJICbeCGsluUsXrr/HjBQNeR7LdZoxg2+4nP9P8aLXkSz4/Yij8MHN /yjAqZ7w0ha9v6XZRTDRdsJVnuyltQ/qyTWUUkR5RdJf7YdOPHzZA9tOeBpnHEAI BnvBaP5+/IWOGLZDgduj7aMIFQHzv6icEUx5M8FYTScXQF+I6X3QH9bfvMlcobNa KJVgi6kQDQ7xBXCLJzGcqmli9BSaDb5bWcHyzlJ9hx93CEbHTIgByOHncVRgNyRw +BlCkClXGP3N5lDinWUmZeIpKqhzHrTJGjpfOJM5J/byWU/+99ZzMLs+dnttZvHK P56GapfW7eW0DMhL2bMAl9GzNly33bPy6+d5da+r7NV1O4+d+EwG5NZWVu5DLfDN cKSonX7GAvXOrEd015tIo3aEQ7OBuNzK4dvsgi/7rNEiRntQVMqQTKZbZNBfBY6N g/HDaThL+2YfB+yDwYCVp8F38WFtKAtoJdSZDX6s364rQT2wjEjlWvHhxxpo6U9l hUdZ7w4yXKdHHGpEg7j2IFx5xVUopAM9GAeyMCEJ3dOIGTc3zRgBq55jWLIk7zCb s5CMEfe06I2UAMq9sTj6exDXPyzNNw3raW96Fq+cvn0nCzHY+VhApeUkUTi9XrV4 S+lFEXznKXNjplmefEuk3Rvi3/OohzJDV5eS1tXfjP6p56eJkXZKLQTb6snqEiEd MteTS44nEEz7fQwvAOZzId1AhuvKk4jIHeXHQcywbq+UMBxqe8vyTh57ZExpXBZT Yrt9FL+jra703bGaKEVmmOnaytSxkvkENoSzwd49wBSjCYj095H0XNtIh7H0BSVW zE0PtLiw09yPLge5XW3WzA7cpZtRvqwUeA6HgN/qIJgM+lynGnr2XwHK3ZfDruTF t1R4NOBCCM3W29ABwpJS0itmRq7ldIWvyQ9perhHkk5lpc0WJt8zR50jVyoJWByF qW5G+OaGCJ1lTNenFF2t4/FvaMXQ0vWx9UUOLqwCwU/RUWZUJpaJcFLyTeoAPSy/ +Po1wOtL2Piz6Oxc6OWc8YwaP/8guaA0YOT9dyYPbDA2QsNADj65IV6bfwGukx/M GOe73uc4bHMeos7WfKDAdQT+6AAQu+tWB2NZGV1aqonT+JXN9mnqzXVY2scrOQeS YuAzHEgMHMSpUU2fKnth85hGz+3kwsWyJuU0qSLMxbkM+lynGnr2XwHK3ZfDruTF 0jKJHDQxxxjKvPTCJ+smT0g/nAI2h7fPYYYSVl9mrV34pXOGMRc8HtfnzUffBcjK ylAOONUi/Q+pcdCTmDaSEbXE/Kxo/wSXAQH6SmI3a/dhpX5A4tju39WaVqXqKKhQ pGkQVNmC0CAUXMtuDYZlysrxqauVvfMBYGuYTW+Jjte2fU7DlUHKfHCIC3L/FjLM QtFBwxUWhnWLe4PwCI3jdB+P3nVH+P9Rz2AmVLfKv8BRosnaNnf2V+JVOTb8ek+B uSS3PbH3mzcmavL+CXbrltNIkN86OFaCWIEs+TvxGmRJVUmnDjAszwqU4+DVHYCO BnKTrqC2goQR84jvU3vsxXJU1TM/YOFv0jZ1YJrHv0yQb0o2SEJeOWMXMF5/48m9
8214abbcd1e48f87503a5620a94636041ae20a69
042001f325ae2d85e2f15705f12fca964c605ae4
/Hashing.cpp
145455e3f9eb19e895f49d1a47df15e3c6f03bc7
[]
no_license
shaft49/Cookbook
c216e4cd5e6b7361c6f7cd21bcbf8abe463a0a47
2c8b19b4ddcf117d2e6d86c4a8e5117de17aca0e
refs/heads/master
2021-06-20T02:04:13.473545
2020-12-25T08:15:59
2020-12-25T08:15:59
146,844,620
3
0
null
null
null
null
UTF-8
C++
false
false
1,699
cpp
Hashing.cpp
const long long HMOD[] = {2078526727, 2117566807}; const long long BASE[] = {1572872831, 1971536491}; struct stringhash{ int len; vector <long long> P[2], H[2], R[2]; stringhash(){} stringhash(string str){ int i, j; len = str.size(); for (i = 0; i < 2; i++){ P[i].resize(len + 1, 0); H[i].resize(len + 1, 0), R[i].resize(len + 1, 0); for (P[i][0] = 1, j = 1; j <= len; j++) P[i][j] = (P[i][j - 1] * BASE[i]) % HMOD[i]; H[i][0] = 0; for (j = 0; j < len; j++){ H[i][j] = ((H[i][j] * BASE[i]) + str[j] + 1007) % HMOD[i]; H[i][j + 1] = H[i][j]; } R[i][len - 1] = 0; for (j = len - 1; j >= 0; j--){ R[i][j] = ((R[i][j] * BASE[i]) + str[j] + 1007) % HMOD[i]; if (j) R[i][j - 1] = R[i][j]; } } } inline long long hash(int l, int r){ long long ar[2]; ar[0] = H[0][r], ar[1] = H[1][r]; if (l){ for (int i = 0; i < 2; i++){ ar[i] -= ((P[i][r - l + 1] * H[i][l - 1]) % HMOD[i]); if (ar[i] < 0) ar[i] += HMOD[i]; } } return (ar[0] << 32) ^ ar[1]; } inline long long revhash(int l, int r){ long long ar[2]; ar[0] = R[0][l], ar[1] = R[1][l]; if ((r + 1) < len){ for (int i = 0; i < 2; i++){ ar[i] -= ((P[i][r - l + 1] * R[i][r + 1]) % HMOD[i]); if (ar[i] < 0) ar[i] += HMOD[i]; } } return (ar[0] << 32) ^ ar[1]; } };
9525e201b15af45c1fa0c9f4d311d46e97346621
a9ff8c05d086b602516bd91ad44fa8bb98346b83
/OpenGL_OpenCV_Gtk/demo_2/main.cpp
e9af4cc80cbbf6986e3c508f3c222f52e2294fe7
[]
no_license
igopm/GtkOpenGlExamples
f79283e9e810174f447727f83e84bbce8d8aaa66
de363d363ca79ed87b7c1b9af799a1ed8a738e67
refs/heads/master
2021-04-27T15:13:47.432517
2018-02-27T21:19:54
2018-02-27T21:19:54
122,464,354
0
0
null
null
null
null
UTF-8
C++
false
false
803
cpp
main.cpp
// // Created by Igor Maschikevich on 10/25/2017. // //===================================================================================================== #include <gtkmm/application.h> //===================================================================================================== #include "MainWindow.h" //===================================================================================================== int main(int argc, char ** argv) { Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.demo_2"); MainWindow mainWindow; return app->run(mainWindow); } //=====================================================================================================
4e6e22e983627e599325f519bc9d1ac956ae5c0f
0f2b08b31fab269c77d4b14240b8746a3ba17d5e
/onnxruntime/core/optimizer/rule_based_graph_transformer.cc
a4ae82792a03cd699828b94e20bd83e717026c93
[ "MIT" ]
permissive
microsoft/onnxruntime
f75aa499496f4d0a07ab68ffa589d06f83b7db1d
5e747071be882efd6b54d7a7421042e68dcd6aff
refs/heads/main
2023-09-04T03:14:50.888927
2023-09-02T07:16:28
2023-09-02T07:16:28
156,939,672
9,912
2,451
MIT
2023-09-14T21:22:46
2018-11-10T02:22:53
C++
UTF-8
C++
false
false
3,499
cc
rule_based_graph_transformer.cc
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/optimizer/rule_based_graph_transformer.h" #include "core/graph/graph_utils.h" #include "core/optimizer/rewrite_rule.h" using namespace ::onnxruntime::common; namespace onnxruntime { Status RuleBasedGraphTransformer::Register(std::unique_ptr<RewriteRule> rule) { auto op_types = rule->TargetOpTypes(); // XXX: This function does not appear to be exception safe. // If the target op types are empty, this rule will be evaluated for all op types. if (op_types.empty()) { any_op_type_rules_.push_back(*rule); } else { std::for_each(op_types.cbegin(), op_types.cend(), [&](const std::string& op_type) { op_type_to_rules_[op_type].push_back(*rule); }); } // Save unique pointer at the rules_ list. rules_.push_back(std::move(rule)); return Status::OK(); } Status RuleBasedGraphTransformer::ApplyRulesOnNode(Graph& graph, Node& node, gsl::span<const std::reference_wrapper<const RewriteRule>> rules, RuleEffect& rule_effect, const logging::Logger& logger) const { for (const RewriteRule& rule : rules) { ORT_RETURN_IF_ERROR(rule.CheckConditionAndApply(graph, node, rule_effect, logger)); // If the current node was removed as a result of a rule, stop rule application for that node. if (rule_effect == RuleEffect::kRemovedCurrentNode) { break; } } return Status::OK(); } Status RuleBasedGraphTransformer::ApplyImpl(Graph& graph, bool& modified, int graph_level, const logging::Logger& logger) const { GraphViewer graph_viewer(graph); auto& order = graph_viewer.GetNodesInTopologicalOrder(); for (NodeIndex i : order) { auto* node = graph.GetNode(i); // A node might not be found as it might have already been deleted from one of the rules. if (!node) { continue; } // Initialize the effect of rules on this node to denote that the graph has not yet been modified // by the rule application on the current node. auto rule_effect = RuleEffect::kNone; if (!graph_utils::IsSupportedProvider(*node, GetCompatibleExecutionProviders())) { continue; } // First apply rewrite rules that are registered for the op type of the current node; then apply rules that are // registered to be applied regardless of the op type; then recursively apply rules to subgraphs (if any). // Stop further rule application for the current node, if the node gets removed by a rule. const InlinedVector<std::reference_wrapper<const RewriteRule>>* rules = nullptr; rules = GetRewriteRulesForOpType(node->OpType()); if (rules) { ORT_RETURN_IF_ERROR(ApplyRulesOnNode(graph, *node, *rules, rule_effect, logger)); } if (rule_effect != RuleEffect::kRemovedCurrentNode) { rules = GetAnyOpRewriteRules(); if (rules) { ORT_RETURN_IF_ERROR(ApplyRulesOnNode(graph, *node, *rules, rule_effect, logger)); } } // Update the modified field of the rule-based transformer. if (rule_effect != RuleEffect::kNone) { modified = true; } if (rule_effect != RuleEffect::kRemovedCurrentNode) { ORT_RETURN_IF_ERROR(Recurse(*node, modified, graph_level, logger)); } } return Status::OK(); } size_t RuleBasedGraphTransformer::RulesCount() const { return rules_.size(); } } // namespace onnxruntime
de4766886d79501d4d70145c359b378ecf31c0aa
f1eb042365f987eaa759faa8b97811d66423628f
/HapticEvaluation/ExperienceHapticRepAuto.h
ee972e9f536ec488f9de268cf2ddf3a90b019ebb
[]
no_license
cyhd/HaCoE
72e3f89fb3284bf3cca557c370c129371f255ddf
27b05d01a0f2ce3d4e6ab0ffeba774e65dbe8b1c
refs/heads/master
2020-12-29T02:32:34.879438
2017-03-02T12:38:00
2017-03-02T12:38:00
43,976,216
1
0
null
2017-03-02T11:55:45
2015-10-09T19:35:19
C
UTF-8
C++
false
false
366
h
ExperienceHapticRepAuto.h
#pragma once #include<qlabel.h> #include <QWidget> #include <qgridlayout.h> #include <qlineedit.h> #include <QRadioButton> #include "AutoWidget.h" #include "ExperienceWidget.h" class ExperienceHapticRepAuto : public ExperienceWidget { public: ExperienceHapticRepAuto(void); ~ExperienceHapticRepAuto(void); void applySettings(); private: AutoWidget *autoW; };
3aed4ba036d7ad9c097b1ac19d7da5ebb022cd63
0f2b08b31fab269c77d4b14240b8746a3ba17d5e
/onnxruntime/core/platform/windows/logging/etw_sink.h
1e4f49a619302cf86c504a4bc481d5e58fa5bf07
[ "MIT" ]
permissive
microsoft/onnxruntime
f75aa499496f4d0a07ab68ffa589d06f83b7db1d
5e747071be882efd6b54d7a7421042e68dcd6aff
refs/heads/main
2023-09-04T03:14:50.888927
2023-09-02T07:16:28
2023-09-02T07:16:28
156,939,672
9,912
2,451
MIT
2023-09-14T21:22:46
2018-11-10T02:22:53
C++
UTF-8
C++
false
false
1,284
h
etw_sink.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <ntverp.h> // check for Windows 10 SDK or later // https://stackoverflow.com/questions/2665755/how-can-i-determine-the-version-of-the-windows-sdk-installed-on-my-computer #if VER_PRODUCTBUILD > 9600 // ETW trace logging uses Windows 10 SDK's TraceLoggingProvider.h #define ETW_TRACE_LOGGING_SUPPORTED 1 #endif #ifdef ETW_TRACE_LOGGING_SUPPORTED #include <date/date.h> #include <atomic> #include <iostream> #include <string> #include "core/common/logging/capture.h" #include "core/common/logging/isink.h" namespace onnxruntime { namespace logging { class EtwSink : public ISink { public: EtwSink() = default; ~EtwSink() = default; constexpr static const char* kEventName = "ONNXRuntimeLogEvent"; private: ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(EtwSink); void SendImpl(const Timestamp& timestamp, const std::string& logger_id, const Capture& message) override; // limit to one instance of an EtwSink being around, so we can control the lifetime of // EtwTracingManager to ensure we cleanly unregister it static std::atomic_flag have_instance_; }; } // namespace logging } // namespace onnxruntime #endif // ETW_TRACE_LOGGING_SUPPORTED
01e927b0df8b6c42223be7161595135b6a34280b
e65a5f09cb2875e62cf21b0e5eb7b3d3de1f5808
/FacileCppApp/FacileCppApp.cpp
c592f4be6298839d3ab7399f641bb2d17ae34db3
[]
no_license
JezCox/FacileCppApp
e95e41352d8aa0672315d46c1e2b38dbb81f5b35
922b7d85b3703c70033932acb68fbd1403f392c7
refs/heads/master
2021-10-22T08:37:08.125121
2021-10-16T19:13:06
2021-10-16T19:13:06
231,758,632
0
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
FacileCppApp.cpp
#include <iostream> #include "PointlessClass.h" using namespace SomewhatFacile; int main() { std::cout << "Purely for testing that I can commit a VS project to GutHub!\n"; PointlessClass pc; pc.IncAndWriteMember(); pc.DecAndWriteMember(); pc.UseStdMap(); pc.StringAppending(); pc.VectorAlt(); pc.UseGenerateN(); pc.UseQueue(); pc.UseStack(); pc.StringPlay(); pc.ArrayPlay(); pc.MapSort(); //pc.TryoutTemp(); return 1; }
f75426ece7f13ba5b5f3037fc352647c60559836
41279e0ed19e26cc0fcaafa229604d1094aed6a8
/include/bufferednetworking/BufferedSocket.hpp
3e704cd3ad4cf4e7c2697e217d346c4ad4abee78
[]
no_license
ChuxiongMa/TextAdventure
20a180747414ede1a8b0e85869809f955b067b11
4f217106de6908909f17408c16df822ed9543284
refs/heads/master
2016-08-13T02:01:58.490646
2016-02-21T23:26:48
2016-02-21T23:26:48
52,233,748
0
0
null
null
null
null
UTF-8
C++
false
false
2,230
hpp
BufferedSocket.hpp
#ifndef BUFFERED_SOCKET_H #define BUFFERED_SOCKET_H #include <vector> #include <pipeable/IByteBufferAcceptor.hpp> #include <bufferedprotocol/Bufferer.hpp> #include <bufferedprotocol/Sender.hpp> #include <networking/Socket.hpp> using Bufferer = bufferedprotocol::Bufferer; using Sender = bufferedprotocol::Sender; using Socket = networking::Socket; using PeernameResult = networking::PeernameResult; using IByteBufferAcceptor = pipeable::IByteBufferAcceptor; using ISender = pipeable::ISender; namespace bufferednetworking { /** * This is an analogous counterpart to `Socket`. The difference is that any * incoming packet needs to be prepended with some number of bytes to * represent the size of the expected packet. */ class BufferedSocket: public ISender, public IByteBufferAcceptor { public: BufferedSocket(); BufferedSocket(Socket& socket); BufferedSocket(Socket* socket); /** * Dump the specified packet into the bufferer. * * @param packet the packet to dump into the buffer. */ void write(const std::vector<unsigned char>& packet); /** * Dump the specified packet into the bufferer. * * @param packet the packet to dump into the buffer. */ void write(const std::string& packet); /** * Sends the specified string to the remote host. * * @param payload the content to send. */ void send(const std::string& packet); /** * Sends the specified buffer to the remote host. * * @param payload the content to send. */ void send(const std::vector<unsigned char>& packet); /** * Gets the address of the remote host. */ PeernameResult getPeername(); /** * Registers the specified event handler for cases when a payload has been * fully buffered. * * @param callback the event handler to register. */ void onRead( std::function<void(const std::vector<unsigned char>&)> callback ); /** * Registers an event handler for the case when the socket has been closed. */ void onClose(std::function<void (void)> callback); private: Bufferer bufferer; Sender sender; Socket* socket; }; } #endif
dd94d4658ec23845948c331515e37efc63dce0bb
9ce4ccdea825037580d62166437437dbb5673e66
/CCC/CCC 12 S3 - Absolutely Acidic.cpp
89170b4bc0ab0161c6ad2ef98f1a5235432747bb
[]
no_license
makeren/competitive-programming
7e2c0d8daf9441e1ca02b6137618f03ce977b8c9
f5c5e4b96f32c34c0c2bdb0b6a4053b56dff7cef
refs/heads/master
2022-03-15T13:39:56.916956
2019-11-03T03:21:53
2019-11-03T03:21:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,176
cpp
CCC 12 S3 - Absolutely Acidic.cpp
#include <iostream> using namespace std; int N, R, freq [1002], maxa = -1, mindex = -1, second = -1, sindex = -1, top, bottom; int main() { cin >> N; for (int i = 0; i<N; i++) { cin >> R; freq[R]++; if (freq[R]>maxa) { mindex = R; maxa = freq[R]; } else if (freq[R]>second) { sindex = R; second = freq[R]; } } for (int i = 1000; i>0; i--) { if (freq[i]==maxa) { top = i; break; } } for (int i = 1; i<=1000; i++) { if (freq[i]==maxa) { bottom = i; break; } } if (top==bottom) { int t1, t2; for (int i = 1; i<=1000; i++) { if (freq[i]==second) { t1 = i; break; } } for (int i = 1000; i>0; i--) { if (freq[i]==second) { t2 = i; break; } } if (abs(top-t1)>abs(top-t2)) { bottom = t1; } else { bottom = t2; } } cout << abs(top-bottom) << "\n"; return 0; }
16ac1543337566d75190639a766ffab718b69ccf
7f20b623f971e34d9e0d0505c1efde0a5c5e2b5c
/GAT.h
37dba2dcb1e6a020e16dfe72d385794a4a5674a8
[]
no_license
Ed-gong/torch-graph
3602db622f1d0a1a8402bf445896f4ef7cfe6277
87b10d21587d297b4d891d21e60403807516f868
refs/heads/master
2023-02-21T09:47:02.814700
2021-01-14T01:18:46
2021-01-14T01:18:46
285,158,095
0
0
null
null
null
null
UTF-8
C++
false
false
2,604
h
GAT.h
// Created by yidong on 9/24/20. // #pragma once #include <iostream> #include <torch/torch.h> #include <iostream> #include <torch/script.h> #include <iostream> // This header is what defines the custom class registration // behavior specifically. script.h already includes this, but // we include it here so you know it exists in case you want // to look at the API or implementation. //#include <torch/custom_class.h> #include <string> #include <vector> //#include <cstdint> using namespace std; using torch::Tensor; using torch::autograd::Node; using torch::autograd::deleteNode; using torch::autograd::SavedVariable; using torch::autograd::variable_list; using torch::autograd::tensor_list; #include "SnapWrap.h" #include "ManagerWrap.h" torch::Tensor gat_result1(const torch::Tensor & input_feature, snap_t<dst_id_t>* snaph, string gather_operator, int64_t reverse); //torch::Tensor edge_softmax_1(snap_t<dst_id_t>* snaph, const torch::Tensor & efficient_score); torch::Tensor add_by_edge(snap_t<dst_id_t>* snaph, const torch::Tensor & input_left, const torch::Tensor & input_right); torch::Tensor gat_update_by_edge1(const torch::Tensor & input_left, snap_t<dst_id_t>* snaph, const torch::Tensor & input_right, string oper, int64_t reverse); torch::Tensor gat_update_all_vertix1(const torch::Tensor & input_feature, snap_t<dst_id_t>* snaph, const torch::Tensor & edge_score_by_softmax, string gather_operator, int64_t reverse); struct GATlayerImpl : torch::nn::Module { GATlayerImpl(int64_t in_dim, int64_t out_dim); torch::Tensor forward(torch::Tensor input, c10::intrusive_ptr<SnapWrapW> snaph); torch::nn::Linear linear1; torch::Tensor W_left; torch::Tensor W_right; //torch::nn::Linear linear; int64_t in_dim; int64_t out_dim; }; TORCH_MODULE(GATlayer); struct GAT : torch::nn::Module { GAT(int64_t in_dim, int64_t hidden_dim, int64_t out_dim); torch::Tensor forward(torch::Tensor input, c10::intrusive_ptr<SnapWrapW> snaph); //vector<torch::Tensor> parameters(); GATlayer gatlayer1, gatlayer2; }; struct GATmultiheadImpl : torch::nn::Module { GATmultiheadImpl(int64_t in_dim, int64_t out_dim, int64_t num_heads); torch::Tensor forward(torch::Tensor input, c10::intrusive_ptr<SnapWrap> snaph, string merge = "cat"); torch::nn::ModuleList mlist; }; TORCH_MODULE(GATmultihead); struct GAT1 : torch::nn::Module { GAT1(int64_t in_dim, int64_t hidden_dim, int64_t out_dim, int64_t num_heads); torch::Tensor forward(torch::Tensor input, c10::intrusive_ptr<SnapWrap> snaph); GATmultihead gatmultihead1, gatmultihead2; };
8e37023c8954331e3cc148df2dc99da9d9550829
82acbe0823fdbe117a671c9bb321519a40a1f052
/gamelist.cpp
e268a6d90668e4c54bc5d251df1c24123808fc8c
[]
no_license
jncronin/djhero-c
599328545ae31f89199bd0f38f10f211fc2f557c
349ca8b1b8ca31222188eadff5345d6a573fd314
refs/heads/master
2020-03-31T03:10:08.920123
2018-10-25T10:53:44
2018-10-25T10:53:44
151,855,563
1
0
null
null
null
null
UTF-8
C++
false
false
3,051
cpp
gamelist.cpp
#include <lvgl/lvgl.h> #include <iostream> #include "dirlist.h" #include "menuscreen.h" void send_serial(char c); extern bool game_playing; static lv_obj_t *load_scr = NULL; static lv_obj_t *load_text = NULL; struct gamedent : dent { std::string cmdline; }; static lv_obj_t *get_load_scr(std::string pretty) { if(!load_scr) { load_scr = lv_obj_create(NULL, NULL); load_text = lv_label_create(load_scr, NULL); } lv_label_set_text(load_text, ("Loading " + pretty + "...").c_str()); return load_scr; } static bool gamesort(struct dent *a, struct dent *b) { if(a->is_parent) return true; if(b->is_parent) return false; return a->name.compare(b->name) < 0; } static void game_cb(struct dent *dent, struct dent *parent) { (void)parent; send_serial('0'); auto gd = (struct gamedent *)dent; #ifdef DEBUG std::cout << "game_cb: " << gd->cmdline << std::endl; #endif auto old_scr = lv_scr_act(); auto new_scr = get_load_scr(gd->name); lv_scr_load(new_scr); lv_task_handler(); lv_tick_inc(5); game_playing = true; system(gd->cmdline.c_str()); game_playing = false; #ifdef DEBUG std::cout << "game done" << std::endl; #endif lv_scr_load(old_scr); send_serial('9'); } static struct gamedent *mame(std::string pretty, std::string mamename) { auto p = new struct gamedent(); p->name = pretty; p->cmdline = "FRAMEBUFFER=/dev/fb1 /usr/local/bin/advmame --quiet " + mamename; p->cb = game_cb; return p; } static struct gamedent *mame(std::string mamename) { return mame(mamename, mamename); } // Currently we hard-code in the games known to work std::vector<struct dent*> game_list() { std::vector<struct dent*> v; // prev auto prev_dent = new struct dent(); prev_dent->name = SYMBOL_DIRECTORY" .."; prev_dent->cb = root_cb; prev_dent->is_parent = true; v.push_back(prev_dent); v.push_back(mame("1941")); v.push_back(mame("1942")); v.push_back(mame("AfterBurner", "aburner")); v.push_back(mame("Aliens", "aliens")); v.push_back(mame("Contra", "contra")); v.push_back(mame("Donkey Kong", "dkong")); v.push_back(mame("Ice Climber", "iceclimb")); v.push_back(mame("Jackal", "jackal")); v.push_back(mame("Legend of Kage", "lkage")); v.push_back(mame("Mario Brothers", "mario")); v.push_back(mame("Sonic the Hedgehog", "mp_sonic")); v.push_back(mame("Sonic the Hedgehog 2", "mp_soni2")); v.push_back(mame("Paperboy", "paperboy")); v.push_back(mame("Super Mario Brothers", "suprmrio")); v.push_back(mame("Pac-Man", "pacman")); v.push_back(mame("Ms. Pac-Man", "mspacman")); v.push_back(mame("Frogger", "frogger")); v.push_back(mame("Joust", "joust")); v.push_back(mame("Arkanoid", "arkanoid")); v.push_back(mame("Galaga", "galaga")); v.push_back(mame("Galaga '88", "galaga88")); v.push_back(mame("Balloon Fight", "balonfgt")); std::sort(v.begin(), v.end(), gamesort); return v; }
685cbfdde855df490fb5fe6080de0b658db56364
03bd17825dc98a6a2b2ed8e208e800a5ce963622
/lib/analysisresult.cpp
45ab5fa70853ac61693a9ee1c8685bc64f984b2a
[]
no_license
KDE/libstreamanalyzer
f57a9c52e9860782ba290bb12c78cd41b09acf09
d069d1c7816990a1e550c12c3115c13353332d00
refs/heads/master
2021-01-18T22:40:00.725839
2016-05-14T20:20:12
2016-05-14T20:21:45
42,722,498
2
0
null
null
null
null
UTF-8
C++
false
false
14,042
cpp
analysisresult.cpp
/* This file is part of Strigi Desktop Search * * Copyright (C) 2006,2009 Jos van den Oever <jos@vandenoever.info> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "analysisresult.h" #include "indexwriter.h" #include "analyzerconfiguration.h" #include "streamanalyzer.h" #include "strigi_thread.h" #include <strigi/strigiconfig.h> #include <strigi/streambase.h> #include <strigi/textutils.h> #include <time.h> #include <string> #include <cstdlib> #include <iconv.h> #include <cassert> #include <iostream> #include <map> #ifdef ICONV_SECOND_ARGUMENT_IS_CONST #define ICONV_CONST const #else #define ICONV_CONST #endif using namespace Strigi; using namespace std; class Latin1Converter { iconv_t const conv; char* out; size_t outlen; STRIGI_MUTEX_DEFINE(mutex); int32_t _fromLatin1(char*& out, const char* data, size_t len); Latin1Converter() :conv(iconv_open("UTF-8", "ISO-8859-1")), outlen(0) { STRIGI_MUTEX_INIT(&mutex); } ~Latin1Converter() { iconv_close(conv); free(out); STRIGI_MUTEX_DESTROY(&mutex); } static Latin1Converter& converter() { static Latin1Converter l; return l; } public: static int32_t fromLatin1(char*& out, const char* data, int32_t len) { return converter()._fromLatin1(out, data, len); } static void lock() { STRIGI_MUTEX_LOCK(&converter().mutex); } static void unlock() { STRIGI_MUTEX_UNLOCK(&converter().mutex); } }; int32_t Latin1Converter::_fromLatin1(char*& o, const char* data, size_t len) { size_t l = 3*len; if (outlen < l) { out = (char*)realloc(out, l); outlen = l; } else { l = outlen; } o = out; ICONV_CONST char* inp = (char*)data; char* outp = out; iconv(conv, &inp, &len, &outp, &l); return (len == 0) ?(int32_t)(outlen-l) :0; } class AnalysisResult::Private { public: int64_t m_id; mutable void* m_writerData; const time_t m_mtime; std::string m_name; const std::string m_path; const std::string m_parentpath; // only use this value of m_parent == 0 std::string m_encoding; std::string m_mimetype; IndexWriter& m_writer; const int m_depth; StreamAnalyzer& m_indexer; AnalyzerConfiguration& m_analyzerconfig; AnalysisResult* const m_this; AnalysisResult* const m_parent; const StreamEndAnalyzer* m_endanalyzer; std::map<const Strigi::RegisteredField*, int> m_occurrences; AnalysisResult* m_child; Private(const std::string& p, const char* name, time_t mt, AnalysisResult& t, AnalysisResult& parent); Private(const std::string& p, time_t mt, IndexWriter& w, StreamAnalyzer& indexer, const string& parentpath, AnalysisResult& t); void write(); bool checkCardinality(const RegisteredField* field); }; AnalysisResult::Private::Private(const std::string& p, const char* name, time_t mt, AnalysisResult& t, AnalysisResult& parent) :m_writerData(0), m_mtime(mt), m_name(name), m_path(p), m_writer(parent.p->m_writer), m_depth(parent.depth()+1), m_indexer(parent.p->m_indexer), m_analyzerconfig(parent.p->m_analyzerconfig), m_this(&t), m_parent(&parent), m_endanalyzer(0), m_child(0) { // make sure that the path starts with the path of the parent assert(m_path.size() > m_parent->p->m_path.size()+1); assert(m_path.compare(0, m_parent->p->m_path.size(), m_parent->p->m_path) == 0); } AnalysisResult::AnalysisResult(const std::string& path, const char* name, time_t mt, AnalysisResult& parent) :p(new Private(path, name, mt, *this, parent)) { p->m_writer.startAnalysis(this); srand((unsigned int)time(NULL)); } AnalysisResult::Private::Private(const std::string& p, time_t mt, IndexWriter& w, StreamAnalyzer& indexer, const string& parentpath, AnalysisResult& t) :m_writerData(0), m_mtime(mt), m_path(p), m_parentpath(parentpath), m_writer(w), m_depth(0), m_indexer(indexer), m_analyzerconfig(indexer.configuration()), m_this(&t), m_parent(0), m_endanalyzer(0), m_child(0) { size_t pos = m_path.rfind('/'); // TODO: perhaps us '\\' on Windows if (pos == std::string::npos) { m_name = m_path; } else { if (pos == m_path.size()-1) { // assert that there is no trailing '/' unless it is part of a // protocol, which means the parent must be "" and the string must // end in a colon followed by up to three slashes assert(m_parentpath == ""); size_t i = m_path.size(); while (--i > 0 && m_path[i] == '/') {} assert(i > 0 && m_path[i] == ':'); } m_name = m_path.substr(pos+1); } // check that the path start with the path of the parent // if the path of the parent is set (!= ""), m_path should be 2 characters // longer: 1 for the separator and one for the file name. // if m_path == "" and m_parentpath == "" then the unix root dir '/' is // meant assert((m_path.size() == 0 && m_parentpath.size() == 0) || (m_path.size() > (m_parentpath.size()+(m_parentpath.size())?1:0))); assert(m_path.compare(0, m_parentpath.size(), m_parentpath) == 0); } AnalysisResult::AnalysisResult(const std::string& path, time_t mt, IndexWriter& w, StreamAnalyzer& indexer, const string& parentpath) :p(new Private(path, mt, w, indexer, parentpath, *this)) { p->m_writer.startAnalysis(this); } AnalysisResult::~AnalysisResult() { // delete child before writing and deleting the parent delete p->m_child; p->write(); delete p; } void AnalysisResult::Private::write() { const FieldRegister& fr = m_analyzerconfig.fieldRegister(); m_writer.addValue(m_this, fr.pathField, m_path); // get the parent directory and store it without trailing slash m_writer.addValue(m_this, fr.parentLocationField, (m_parent) ?m_parent->path() :m_parentpath); if (m_encoding.length()) { m_writer.addValue(m_this, fr.encodingField, m_encoding); } if (m_mimetype.length()) { m_writer.addValue(m_this, fr.mimetypeField, m_mimetype); } if (m_name.length()) { m_writer.addValue(m_this, fr.filenameField, m_name); } string field = m_this->extension(); if (field.length()) { //m_writer.addValue(m_this, fr.extensionField, field);//FIXME: either get rid of this or replace with NIE equivalent } //This is superfluous. You can use nie:DataObject type to find out whether you've got a file or embedded data //m_writer.addValue(m_this, fr.embeddepthField, (int32_t)m_depth); m_writer.addValue(m_this, fr.mtimeField, (uint32_t)m_mtime); //FIXME a temporary workaround until we have a file(system) analyzer. if(m_depth==0) m_writer.addValue(m_this, fr.typeField, "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#FileDataObject"); m_writer.finishAnalysis(m_this); } const std::string& AnalysisResult::fileName() const { return p->m_name; } const std::string& AnalysisResult::path() const { return p->m_path; } const string& AnalysisResult::parentPath() const { return (p->m_parent) ?p->m_parent->path() :p->m_parentpath; } time_t AnalysisResult::mTime() const { return p->m_mtime; } signed char AnalysisResult::depth() const { return (signed char)p->m_depth; } int64_t AnalysisResult::id() const { return p->m_id; } void AnalysisResult::setId(int64_t i) { p->m_id = i; } void AnalysisResult::setEncoding(const char* enc) { p->m_encoding = enc; } const std::string& AnalysisResult::encoding() const { return p->m_encoding; } void* AnalysisResult::writerData() const { return p->m_writerData; } void AnalysisResult::setWriterData(void* wd) const { p->m_writerData = wd; } void AnalysisResult::setMimeType(const std::string& mt) { p->m_mimetype = mt; } const std::string& AnalysisResult::mimeType() const { return p->m_mimetype; } signed char AnalysisResult::index(InputStream* file) { return p->m_indexer.analyze(*this, file); } signed char AnalysisResult::indexChild(const std::string& name, time_t mt, InputStream* file) { // clean up previous child finishIndexChild(); std::string path(p->m_path); path.append("/"); path.append(name); const char* n = path.c_str() + path.rfind('/') + 1; // check if we should index this file by applying the filename filters // make sure that the depth variable does not overflow if (depth() < 127 && p->m_analyzerconfig.indexFile(path.c_str(), n)) { p->m_child = new AnalysisResult(path, n, mt, *this); return p->m_indexer.analyze(*p->m_child, file); } return 0; } void AnalysisResult::finishIndexChild() { delete p->m_child; p->m_child = 0; } AnalysisResult* AnalysisResult::child() { return p->m_child; } void AnalysisResult::addText(const char* text, int32_t length) { if (checkUtf8(text, length)) { p->m_writer.addText(this, text, length); } else { Latin1Converter::lock(); char* d; int32_t len = Latin1Converter::fromLatin1(d, text, length); if (len && checkUtf8(d, len)) { p->m_writer.addText(this, d, len); } else { fprintf(stderr, "'%.*s' is not a UTF8 or latin1 string\n", length, text); } Latin1Converter::unlock(); } } AnalyzerConfiguration& AnalysisResult::config() const { return p->m_analyzerconfig; } AnalysisResult* AnalysisResult::parent() { return p->m_parent; } const AnalysisResult* AnalysisResult::parent() const { return p->m_parent; } const StreamEndAnalyzer* AnalysisResult::endAnalyzer() const { return p->m_endanalyzer; } void AnalysisResult::setEndAnalyzer(const StreamEndAnalyzer* ea) { p->m_endanalyzer = ea; } string AnalysisResult::extension() const { string::size_type p1 = p->m_name.rfind('.'); string::size_type p2 = p->m_name.rfind('/'); if (p1 != string::npos && (p2 == string::npos || p1 > p2)) { return p->m_name.substr(p1+1); } return ""; } void AnalysisResult::addValue(const RegisteredField* field, const std::string& val) { // make sure the field is not stored more often than allowed if (!p->checkCardinality(field)) { return; } if (checkUtf8(val)) { p->m_writer.addValue(this, field, val); } else { Latin1Converter::lock(); char* d; int32_t len = Latin1Converter::fromLatin1(d, val.c_str(), (int32_t)val.length()); if (len && checkUtf8(d, len)) { p->m_writer.addValue(this, field, (const unsigned char*)d, len); } else { fprintf(stderr, "'%s' is not a UTF8 or latin1 string\n", val.c_str()); } Latin1Converter::unlock(); } } void AnalysisResult::addValue(const RegisteredField* field, const char* data, uint32_t length) { // make sure the field is not stored more often than allowed if (!p->checkCardinality(field)) { return; } if (checkUtf8(data, length)) { p->m_writer.addValue(this, field, (const unsigned char*)data, length); } else { Latin1Converter::lock(); char* d; int32_t len = Latin1Converter::fromLatin1(d, data, length); if (len && checkUtf8(d, len)) { p->m_writer.addValue(this, field, (const unsigned char*)d, len); } else { fprintf(stderr, "'%.*s' is not a UTF8 or latin1 string\n", length, data); } Latin1Converter::unlock(); } } void AnalysisResult::addValue(const RegisteredField* field, int32_t value) { if (!p->checkCardinality(field)) return; p->m_writer.addValue(this, field, value); } void AnalysisResult::addValue(const RegisteredField* field, uint32_t value) { if (!p->checkCardinality(field)) return; p->m_writer.addValue(this, field, value); } void AnalysisResult::addValue(const RegisteredField* field, double value) { if (!p->checkCardinality(field)) return; p->m_writer.addValue(this, field, value); } void AnalysisResult::addTriplet(const std::string& subject, const std::string& predicate, const std::string& object){ p->m_writer.addTriplet(subject, predicate, object); } std::string AnalysisResult::newAnonymousUri(){ std::string result; result.resize(6); result[0]=':'; for(int i=1; i<6; i++) result[i]=(char)((rand() % 26) + 'a'); return result; } bool AnalysisResult::Private::checkCardinality(const RegisteredField* field) { std::map<const Strigi::RegisteredField*, int>::const_iterator i = m_occurrences.find(field); if (i != m_occurrences.end()) { if (i->second >= field->properties().maxCardinality() && field->properties().maxCardinality() >= 0) { fprintf(stderr, "%s hit the maxCardinality limit (%d)\n", field->properties().name().c_str(), field->properties().maxCardinality()); return false; } else { m_occurrences[field]++; } } else { m_occurrences[field] = 1; } return true; }
2dc171119ead9d3c76bfb504b3e6df17038e8add
b0252ba622183d115d160eb28953189930ebf9c0
/Source/CAISystem.h
3ceeb06607b0fef2ecd1f30cd20c0058f38f3c7e
[]
no_license
slewicki/khanquest
6c0ced33bffd3c9ee8a60c1ef936139a594fe2fc
f2d68072a1d207f683c099372454add951da903a
refs/heads/master
2020-04-06T03:40:18.180208
2008-08-28T03:43:26
2008-08-28T03:43:26
34,305,386
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,406
h
CAISystem.h
// File CAISystem.h // // Author: Rodney Kite (RK) // Last Modified: August 20, 2008 // Purpose: Contains class definition for CAISystem Class, which handles // all of the unit AI ////////////////////////////////////////////////////////////////////////// #pragma once #include <windows.h> #include "CTileEngine.h" #include "CTileEngine.h" #include "CTile.h" #include <list> #include "CProfile.h" using std::list; //names of tiles enum { TILEEMPTY, TILEBLOCK, TILESTART, TILEEND, TILEPATH, TILESELECT, }; //const int m_nMapWidth=20; //const int m_nMapHeight=20; class CAISystem { CTileEngine* m_pTE; //dimensions of map int m_nMapWidth; int m_nMapHeight; int **Map; //contains tile data about the map int **MapPath; //contains path finding info about the map marks bool **MapMark; //contains marked tiles for path finding ////dimensions of map //int Map[m_nMapWidth][m_nMapHeight];//contains tile data about the map //int MapPath[m_nMapWidth][m_nMapHeight];//contains pathfinding info about the map ////map marks //bool MapMark[m_nMapWidth][m_nMapHeight];//contains marked tiles for pathfinding list<POINT> m_vPath; private: ////////////////////////////////////////////////////////////////////////// // Function: CEmitter // Last Modified: August 04, 2008 // Purpose : Default constructor ////////////////////////////////////////////////////////////////////////// CAISystem(void); ////////////////////////////////////////////////////////////////////////// // Function: CEmitter // Last Modified: August 04, 2008 // Purpose : Default constructor ////////////////////////////////////////////////////////////////////////// ~CAISystem(void); public: ////////////////////////////////////////////////////////////////////////// // Function: Accessors // Last Modified: August 04, 2008 // Purpose : Returns the specified type. ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Function: Modifiers // Last Modified: August 04, 2008 // Purpose: Modifies the specified type. ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////// // Function: “GetInstance” // Last Modified: August 04, 2008 // Purpose: To return an instance of the class ////////////////////////////////////////////////////// static CAISystem* GetInstance(void) { static CAISystem instance; return &instance; } ////////////////////////////////////////////////////// // Function: “Exit” // Last Modified: August 04, 2008 // Purpose: To unload any needed information ////////////////////////////////////////////////////// void Exit(void); ////////////////////////////////////////////////////// // Function: “UpdateState” // Last Modified: August 04, 2008 // Purpose: To change the units state as needed ////////////////////////////////////////////////////// void UpdateState(void); ////////////////////////////////////////////////////// // Function: “FindPath” // Last Modified: August 06, 2008 // Purpose: To find the path to the dest ////////////////////////////////////////////////////// list<POINT> FindPath(CTile* current, CTile* destination); };
e2129788736c6bc322656a001ce8078416cc786c
193161e8f8fcb692ca873cceb320a3ff33fca190
/problems/ZaprzyjaźnijSięZAlgorytmami/wybrzeze/wybrzeze.cpp
af44d22fe4f711f486ea6b10a04fe250f3112d9e
[]
no_license
questras/algorithms
a96a00917882c08737781d5b918c1d70457e3264
06d79b7b9bfb71e7c151f7cebfcbacfb44a26503
refs/heads/master
2023-03-23T05:07:53.741680
2021-03-22T19:11:29
2021-03-22T19:11:29
343,780,146
0
0
null
null
null
null
UTF-8
C++
false
false
1,290
cpp
wybrzeze.cpp
#include <iostream> #include <vector> using namespace std; int main() { int n, k; cin >> n >> k; int highways[n]; for (int i = 0; i < n; i++) { cin >> highways[i]; } int bestRoadPerHighwayLast[n]; int bestRoadPerHighway[n]; // Without highways, you can only travel from previous city. for (int i = 0; i < n; i++) { bestRoadPerHighway[i] = i; bestRoadPerHighwayLast[i] = i; } vector<int> highwayBeginning[n]; for (int i = 0; i < n; i++) { if (highways[i] != -1) { highwayBeginning[highways[i]].push_back(i); } } for (int i = 1; i < k + 1; i++) { for (int j = 1; j < n; j++) { bestRoadPerHighway[j] = bestRoadPerHighwayLast[j]; for (int l = 0; l < highwayBeginning[j].size(); l++) { bestRoadPerHighway[j] = min(bestRoadPerHighway[j], bestRoadPerHighwayLast[highwayBeginning[j].at(l)] + 1); } } for (int j = 1; j < n; j++) { bestRoadPerHighway[j] = min(bestRoadPerHighway[j], bestRoadPerHighway[j - 1] + 1); bestRoadPerHighwayLast[j] = bestRoadPerHighway[j]; } } cout << bestRoadPerHighway[n - 1] << endl; }
73116b31e6b689acd205137f4d771658af00573d
119eeaa3a8a64c8e5cf945c71f7f720ed16115ae
/gameUr/ChariotGame.h
74fbe7f2393548fc8e7ead4776b2493ab3aaf961
[]
no_license
junsujeong/The-Royal-Game-of-Ur
d521fa5bfcadb997b12020c6d355feef0e47f9ae
6e415a27c5029c9c3b63470049c0a4671419e283
refs/heads/master
2021-07-13T22:23:44.112935
2017-09-25T17:25:39
2017-09-25T17:25:39
104,780,337
0
0
null
null
null
null
UTF-8
C++
false
false
598
h
ChariotGame.h
//--------------------------------------------------------------------------- // Name: David Feldman, Edward VanDerJagt, Alex Bisbach, // Junsu Jeong, Adam Larson // Team: C-- // Project: Play a game of Ur // Purpose: To create chariot game mode //---------------------------------------------------------------------------- #pragma once #ifndef __CHARIOTGAME_H_ #define __CHARIOTGAME_H_ #include "GameMode.h" class ChariotGame : public GameMode { //--------------------------------------- // Constructor //--------------------------------------- ChariotGame() {} }; #endif
fcd7d9a615837a3b4a29321c6bfdd7125a3ddd71
79c0b9a85318cffd1b271d3503eeced36c419305
/source/ui/MarqueeComponent.h
da02f2f51211fd2b9d7b4c9c707c372398afefd8
[]
no_license
hixio-mh/naturalselection
97399d055f668a929d62345470d1c1f161e747fe
9fe69670b33dc6221dbee17e07976ed209dbc6e4
refs/heads/master
2021-06-16T17:13:59.073840
2017-04-12T01:41:58
2017-04-12T01:41:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,289
h
MarqueeComponent.h
//======== (C) Copyright 2002 Charles G. Cleveland All rights reserved. ========= // // The copyright to the contents herein is the property of Charles G. Cleveland. // The contents may be used and/or copied only with the written permission of // Charles G. Cleveland, or in accordance with the terms and conditions stipulated in // the agreement/contract under which the contents have been supplied. // // Purpose: // // $Workfile: MarqueeComponent.h $ // $Date: 2002/08/16 02:28:55 $ // //------------------------------------------------------------------------------- // $Log: MarqueeComponent.h,v $ // Revision 1.3 2002/08/16 02:28:55 Flayra // - Added document headers // //=============================================================================== #ifndef MARQUEECOMPONENT_H #define MARQUEECOMPONENT_H #include "VGUI_Panel.h" #include "ui/GammaAwareComponent.h" class MarqueeComponent : public vgui::Panel, public GammaAwareComponent { public: MarqueeComponent(); virtual void NotifyGammaChange(float inGammaSlope); void SetStartPos(int inX, int inY); void SetEndPos(int inX, int inY); protected: virtual void paint(); virtual void paintBackground(); private: void ResetDimensions(); int mX0, mY0; int mX1, mY1; float mGammaSlope; }; #endif
01deef501b30e6180f6316b5c6ce2eb3b839937e
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
/PWGGA/EMCALTasks/AliEMCalpi0Task.h
f8d06e40ba970eafd89f3973795a82cafb66656e
[]
permissive
alisw/AliPhysics
91bf1bd01ab2af656a25ff10b25e618a63667d3e
5df28b2b415e78e81273b0d9bf5c1b99feda3348
refs/heads/master
2023-08-31T20:41:44.927176
2023-08-31T14:51:12
2023-08-31T14:51:12
61,661,378
129
1,150
BSD-3-Clause
2023-09-14T18:48:45
2016-06-21T19:31:29
C++
UTF-8
C++
false
false
1,805
h
AliEMCalpi0Task.h
#ifndef AliEMCalpi0Task_h #define AliEMCalpi0Task_h /* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ // $Id$ /// \class AliEMCalpi0Task /// \brief Task to analyse AODs for pion/eta in PbPb /// /// \author Astrid Morreale astridmorreale@cern.ch subatech /// \date April 10 2015 #include "AliAnalysisTaskSE.h" #include "Alipi0EventStatStruct.h" class TTree; class TString; class TList; class AliESDEvent; class AliEMCalpi0Task : public AliAnalysisTaskSE { public: AliEMCalpi0Task(const char *name = "AliEMCalpi0Task"); virtual ~AliEMCalpi0Task(); // virtual void GetMom(TLorentzVector& p, const AliVCluster *c1, const AliVCluster *c2, Double_t *vertex); virtual void UserCreateOutputObjects(); virtual void UserExec(Option_t *option); virtual void Terminate(const Option_t*); virtual void FillMixed(const TLorentzVector& p1, const TLorentzVector& p2); virtual Double_t GetMaxCellEnergy(const AliVCluster *cluster, Int_t &id) const; private: /// copy constructor (not implemented ) AliEMCalpi0Task( const AliEMCalpi0Task& ); /// assignment operator (not implemented ) AliEMCalpi0Task& operator = ( const AliEMCalpi0Task& ); enum {kNtype = 10}; /// local event counter Int_t fEvent; //Branch with event stats EventStatStruct* fEventStatStruct; /// list of track records TClonesArray* fClusterStatArray; TClonesArray* fdiClusterStatArray; TClonesArray* fmixedDiClusterStatArray; /// number of entries in TClonesArray Int_t fClusterStatCount; Int_t fdiClusterStatCount; Int_t fmixedDiClusterStatCount; TObjArray *fPool[kNtype]; ClassDef(AliEMCalpi0Task,1) }; #endif
14b473430262324c42bff83a0d85dd88d3f0108d
27466e78d3cd1ed168d96fd4c2fb26add1ec7cc3
/NVIS/Code/UI/Windows/NodeGraphEditor/NEConnectionGEItem.h
4094e615fac68c073a3d6ffaa6a5fc89bc9444d7
[]
no_license
gpudev0517/Fire-Simulator
37e1190d638a30c186ae1532975a56b23ffaac67
46581c19356e47a5c6fc8a9ee6f6478b96d02968
refs/heads/master
2023-04-26T02:54:53.458427
2021-05-14T10:16:10
2021-05-14T15:25:28
277,579,935
3
1
null
null
null
null
UTF-8
C++
false
false
1,104
h
NEConnectionGEItem.h
#pragma once class NENodeGraphEditorItem; class NEConnectionGEItem : public QGraphicsItem { public: enum CurveType { Linear, Quadratic, Cubic }; NEConnectionGEItem(NENodeGraphEditorItem* source, NENodeGraphEditorItem* target, QGraphicsItem *parent = 0); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void adjust(); NENodeGraphEditorItem* sourceNode(); NENodeGraphEditorItem* targetNode(); static CurveType curveType() { return m_CurveType; } static void setCurveType(CurveType type) { m_CurveType = type; } private: NENodeGraphEditorItem* m_pSource; NENodeGraphEditorItem* m_pTarget; QPointF m_SourcePoint; QPointF m_TargetPoint; //NENode::NEConnection* m_pConn; mutable QPainterPath m_Path; double arrowSize; static CurveType m_CurveType; void linearPath(const QPointF& start, const QPointF& end, QPainterPath& path); void cubicPath(const QPointF& start, const QPointF& end, QPainterPath& path); void quadraticPath(const QPointF& start, const QPointF& end, QPainterPath& path); };
0e1cb96fd49c6b914e9e55097b5c667bcdd871bc
0de3be548cb43949d3c15fa04332162e4a2e9452
/HashT2(classroom)/HashT/m.cpp
fb6504cfa8c72b832886e6ae46f33d6f5296a8a7
[]
no_license
AntonK17/newLabs
4dbc1e1db9bfc726a1c5135b824f5159c5f4567a
e31fad9212066b517bd16baaf899e5e0c1d4caba
refs/heads/master
2021-01-25T07:50:22.413455
2017-06-08T21:19:32
2017-06-08T21:19:32
93,676,672
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
707
cpp
m.cpp
#include <string> #include "Hastable.h" #include <conio.h> #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "Russian"); const int n=53; Node<string, int> a; a.SetKey("ura"); a.SetVal(1); cout<<a.GetData()<<", ключ: "<<a.GetKey()<<endl; Table<string,int> t(n,5); t.Add ("Anatoliy",12); cout<<"("<<"12"<<", "<<"Anatoliy"<<"); "; t.Add ("Sergey",11); cout<<"("<<"11"<<", "<<"Sergey"<<"); "; cout<<endl<<"Вывод с использованием [] Формат: (DATA, KEY)"<<endl; cout<<"Поиск по ключу ["<<"Sergey"<<"]"<<endl; cout<<"("<<t["Sergey"].GetData()<<", "<<t["Sergey"].GetKey()<<"); "<<endl; _getch(); return 0; }