hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
f4f13b044f9221528c862b19ad1af4e8935cc5f8
77
hh
C++
build/X86/mem/protocol/VIPERCoalescer.hh
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
5
2019-12-12T16:26:09.000Z
2022-03-17T03:23:33.000Z
build/X86/mem/protocol/VIPERCoalescer.hh
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
null
null
null
build/X86/mem/protocol/VIPERCoalescer.hh
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
null
null
null
#include "/home/zhoushuxin/gem5/build/X86/mem/ruby/system/VIPERCoalescer.hh"
38.5
76
0.805195
f4f1ddcc73b72ad1189d7145666bdabb400f88e4
239
cpp
C++
src/question_1/question1.cpp
juliaholland/acc-cosc-1337-midterm-juliaholland
a6d09518393fd8ee9e88c1a4ae3d468e2bd291c3
[ "MIT" ]
null
null
null
src/question_1/question1.cpp
juliaholland/acc-cosc-1337-midterm-juliaholland
a6d09518393fd8ee9e88c1a4ae3d468e2bd291c3
[ "MIT" ]
null
null
null
src/question_1/question1.cpp
juliaholland/acc-cosc-1337-midterm-juliaholland
a6d09518393fd8ee9e88c1a4ae3d468e2bd291c3
[ "MIT" ]
null
null
null
#include "question1.h" bool test_config() { return true; } double get_kinetic_energy(double mass, double velocity) { double kineticEnergy; kineticEnergy = 0.5 * mass * velocity * velocity; return kineticEnergy; }
14.058824
55
0.682008
f4f2a7201d0e73ca372a5a429bfe6ca7b51eb2fd
40,892
cpp
C++
src/vedit.cpp
linails/vnote
97810731db97292f474951c3450aac150acef0bc
[ "MIT" ]
1
2019-07-27T10:46:41.000Z
2019-07-27T10:46:41.000Z
src/vedit.cpp
linails/vnote
97810731db97292f474951c3450aac150acef0bc
[ "MIT" ]
1
2022-01-22T13:10:44.000Z
2022-01-22T13:10:44.000Z
src/vedit.cpp
linails/vnote
97810731db97292f474951c3450aac150acef0bc
[ "MIT" ]
1
2021-06-17T02:43:27.000Z
2021-06-17T02:43:27.000Z
#include <QtWidgets> #include <QVector> #include <QDebug> #include "vedit.h" #include "vnote.h" #include "vconfigmanager.h" #include "vtableofcontent.h" #include "utils/vutils.h" #include "utils/veditutils.h" #include "utils/vmetawordmanager.h" #include "veditoperations.h" #include "vedittab.h" #include "dialog/vinsertlinkdialog.h" #include "utils/viconutils.h" extern VConfigManager *g_config; extern VNote *g_vnote; extern VMetaWordManager *g_mwMgr; VEdit::VEdit(VFile *p_file, QWidget *p_parent) : QTextEdit(p_parent), m_file(p_file), m_editOps(NULL), m_enableInputMethod(true) { const int labelTimerInterval = 500; const int extraSelectionHighlightTimer = 500; const int labelSize = 64; m_selectedWordColor = QColor(g_config->getEditorSelectedWordBg()); m_searchedWordColor = QColor(g_config->getEditorSearchedWordBg()); m_searchedWordCursorColor = QColor(g_config->getEditorSearchedWordCursorBg()); m_incrementalSearchedWordColor = QColor(g_config->getEditorIncrementalSearchedWordBg()); m_trailingSpaceColor = QColor(g_config->getEditorTrailingSpaceBg()); QPixmap wrapPixmap(":/resources/icons/search_wrap.svg"); m_wrapLabel = new QLabel(this); m_wrapLabel->setPixmap(wrapPixmap.scaled(labelSize, labelSize)); m_wrapLabel->hide(); m_labelTimer = new QTimer(this); m_labelTimer->setSingleShot(true); m_labelTimer->setInterval(labelTimerInterval); connect(m_labelTimer, &QTimer::timeout, this, &VEdit::labelTimerTimeout); m_highlightTimer = new QTimer(this); m_highlightTimer->setSingleShot(true); m_highlightTimer->setInterval(extraSelectionHighlightTimer); connect(m_highlightTimer, &QTimer::timeout, this, &VEdit::doHighlightExtraSelections); m_extraSelections.resize((int)SelectionId::MaxSelection); updateFontAndPalette(); m_config.init(QFontMetrics(font()), false); updateConfig(); connect(this, &VEdit::cursorPositionChanged, this, &VEdit::handleCursorPositionChanged); connect(this, &VEdit::selectionChanged, this, &VEdit::highlightSelectedWord); m_lineNumberArea = new LineNumberArea(this); connect(document(), &QTextDocument::blockCountChanged, this, &VEdit::updateLineNumberAreaMargin); connect(this, &QTextEdit::textChanged, this, &VEdit::updateLineNumberArea); connect(verticalScrollBar(), &QScrollBar::valueChanged, this, &VEdit::updateLineNumberArea); updateLineNumberAreaMargin(); connect(document(), &QTextDocument::contentsChange, this, &VEdit::updateBlockLineDistanceHeight); } VEdit::~VEdit() { } void VEdit::updateConfig() { m_config.update(QFontMetrics(font())); if (m_config.m_tabStopWidth > 0) { setTabStopWidth(m_config.m_tabStopWidth); } emit configUpdated(); } void VEdit::beginEdit() { updateFontAndPalette(); updateConfig(); setReadOnlyAndHighlight(false); setModified(false); } void VEdit::endEdit() { setReadOnlyAndHighlight(true); } void VEdit::saveFile() { Q_ASSERT(m_file->isModifiable()); if (!document()->isModified()) { return; } m_file->setContent(toHtml()); setModified(false); } void VEdit::reloadFile() { setHtml(m_file->getContent()); setModified(false); } bool VEdit::scrollToBlock(int p_blockNumber) { QTextBlock block = document()->findBlockByNumber(p_blockNumber); if (block.isValid()) { VEditUtils::scrollBlockInPage(this, block.blockNumber(), 0); moveCursor(QTextCursor::EndOfBlock); return true; } return false; } bool VEdit::isModified() const { return document()->isModified(); } void VEdit::setModified(bool p_modified) { document()->setModified(p_modified); } void VEdit::insertImage() { if (m_editOps) { m_editOps->insertImage(); } } void VEdit::insertLink() { if (!m_editOps) { return; } QString text; QString linkText, linkUrl; QTextCursor cursor = textCursor(); if (cursor.hasSelection()) { text = VEditUtils::selectedText(cursor).trimmed(); // Only pure space is accepted. QRegExp reg("[\\S ]*"); if (reg.exactMatch(text)) { QUrl url = QUrl::fromUserInput(text, m_file->fetchBasePath()); QRegExp urlReg("[\\.\\\\/]"); if (url.isValid() && text.contains(urlReg)) { // Url. linkUrl = text; } else { // Text. linkText = text; } } } VInsertLinkDialog dialog(tr("Insert Link"), "", "", linkText, linkUrl, false, this); if (dialog.exec() == QDialog::Accepted) { linkText = dialog.getLinkText(); linkUrl = dialog.getLinkUrl(); Q_ASSERT(!linkText.isEmpty() && !linkUrl.isEmpty()); m_editOps->insertLink(linkText, linkUrl); } } bool VEdit::peekText(const QString &p_text, uint p_options, bool p_forward) { if (p_text.isEmpty()) { makeBlockVisible(document()->findBlock(textCursor().selectionStart())); highlightIncrementalSearchedWord(QTextCursor()); return false; } bool wrapped = false; QTextCursor retCursor; bool found = findTextHelper(p_text, p_options, p_forward, p_forward ? textCursor().position() + 1 : textCursor().position(), wrapped, retCursor); if (found) { makeBlockVisible(document()->findBlock(retCursor.selectionStart())); highlightIncrementalSearchedWord(retCursor); } return found; } // Use QTextEdit::find() instead of QTextDocument::find() because the later has // bugs in searching backward. bool VEdit::findTextHelper(const QString &p_text, uint p_options, bool p_forward, int p_start, bool &p_wrapped, QTextCursor &p_cursor) { p_wrapped = false; bool found = false; // Options QTextDocument::FindFlags findFlags; bool caseSensitive = false; if (p_options & FindOption::CaseSensitive) { findFlags |= QTextDocument::FindCaseSensitively; caseSensitive = true; } if (p_options & FindOption::WholeWordOnly) { findFlags |= QTextDocument::FindWholeWords; } if (!p_forward) { findFlags |= QTextDocument::FindBackward; } // Use regular expression bool useRegExp = false; QRegExp exp; if (p_options & FindOption::RegularExpression) { useRegExp = true; exp = QRegExp(p_text, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive); } // Store current state of the cursor. QTextCursor cursor = textCursor(); if (cursor.position() != p_start) { if (p_start < 0) { p_start = 0; } else if (p_start > document()->characterCount()) { p_start = document()->characterCount(); } QTextCursor startCursor = cursor; startCursor.setPosition(p_start); setTextCursor(startCursor); } while (!found) { if (useRegExp) { found = find(exp, findFlags); } else { found = find(p_text, findFlags); } if (p_wrapped) { break; } if (!found) { // Wrap to the other end of the document to search again. p_wrapped = true; QTextCursor wrapCursor = textCursor(); if (p_forward) { wrapCursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor); } else { wrapCursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); } setTextCursor(wrapCursor); } } if (found) { p_cursor = textCursor(); } // Restore the original cursor. setTextCursor(cursor); return found; } QList<QTextCursor> VEdit::findTextAll(const QString &p_text, uint p_options) { QList<QTextCursor> results; if (p_text.isEmpty()) { return results; } // Options QTextDocument::FindFlags findFlags; bool caseSensitive = false; if (p_options & FindOption::CaseSensitive) { findFlags |= QTextDocument::FindCaseSensitively; caseSensitive = true; } if (p_options & FindOption::WholeWordOnly) { findFlags |= QTextDocument::FindWholeWords; } // Use regular expression bool useRegExp = false; QRegExp exp; if (p_options & FindOption::RegularExpression) { useRegExp = true; exp = QRegExp(p_text, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive); } int startPos = 0; QTextCursor cursor; QTextDocument *doc = document(); while (true) { if (useRegExp) { cursor = doc->find(exp, startPos, findFlags); } else { cursor = doc->find(p_text, startPos, findFlags); } if (cursor.isNull()) { break; } else { results.append(cursor); startPos = cursor.selectionEnd(); } } return results; } bool VEdit::findText(const QString &p_text, uint p_options, bool p_forward, QTextCursor *p_cursor, QTextCursor::MoveMode p_moveMode) { clearIncrementalSearchedWordHighlight(); if (p_text.isEmpty()) { clearSearchedWordHighlight(); return false; } QTextCursor cursor = textCursor(); bool wrapped = false; QTextCursor retCursor; int matches = 0; int start = p_forward ? cursor.position() + 1 : cursor.position(); if (p_cursor) { start = p_forward ? p_cursor->position() + 1 : p_cursor->position(); } bool found = findTextHelper(p_text, p_options, p_forward, start, wrapped, retCursor); if (found) { Q_ASSERT(!retCursor.isNull()); if (wrapped) { showWrapLabel(); } if (p_cursor) { p_cursor->setPosition(retCursor.selectionStart(), p_moveMode); } else { cursor.setPosition(retCursor.selectionStart(), p_moveMode); setTextCursor(cursor); } highlightSearchedWord(p_text, p_options); highlightSearchedWordUnderCursor(retCursor); matches = m_extraSelections[(int)SelectionId::SearchedKeyword].size(); } else { clearSearchedWordHighlight(); } if (matches == 0) { statusMessage(tr("Found no match")); } else { statusMessage(tr("Found %1 %2").arg(matches) .arg(matches > 1 ? tr("matches") : tr("match"))); } return found; } void VEdit::replaceText(const QString &p_text, uint p_options, const QString &p_replaceText, bool p_findNext) { QTextCursor cursor = textCursor(); bool wrapped = false; QTextCursor retCursor; bool found = findTextHelper(p_text, p_options, true, cursor.position(), wrapped, retCursor); if (found) { if (retCursor.selectionStart() == cursor.position()) { // Matched. retCursor.beginEditBlock(); retCursor.insertText(p_replaceText); retCursor.endEditBlock(); setTextCursor(retCursor); } if (p_findNext) { findText(p_text, p_options, true); } } } void VEdit::replaceTextAll(const QString &p_text, uint p_options, const QString &p_replaceText) { // Replace from the start to the end and restore the cursor. QTextCursor cursor = textCursor(); int nrReplaces = 0; QTextCursor tmpCursor = cursor; tmpCursor.setPosition(0); setTextCursor(tmpCursor); int start = tmpCursor.position(); while (true) { bool wrapped = false; QTextCursor retCursor; bool found = findTextHelper(p_text, p_options, true, start, wrapped, retCursor); if (!found) { break; } else { if (wrapped) { // Wrap back. break; } nrReplaces++; retCursor.beginEditBlock(); retCursor.insertText(p_replaceText); retCursor.endEditBlock(); setTextCursor(retCursor); start = retCursor.position(); } } // Restore cursor position. cursor.clearSelection(); setTextCursor(cursor); qDebug() << "replace all" << nrReplaces << "occurences"; emit statusMessage(tr("Replace %1 %2").arg(nrReplaces) .arg(nrReplaces > 1 ? tr("occurences") : tr("occurence"))); } void VEdit::showWrapLabel() { int labelW = m_wrapLabel->width(); int labelH = m_wrapLabel->height(); int x = (width() - labelW) / 2; int y = (height() - labelH) / 2; if (x < 0) { x = 0; } if (y < 0) { y = 0; } m_wrapLabel->move(x, y); m_wrapLabel->show(); m_labelTimer->stop(); m_labelTimer->start(); } void VEdit::labelTimerTimeout() { m_wrapLabel->hide(); } void VEdit::updateFontAndPalette() { setFont(g_config->getBaseEditFont()); setPalette(g_config->getBaseEditPalette()); } void VEdit::highlightExtraSelections(bool p_now) { m_highlightTimer->stop(); if (p_now) { doHighlightExtraSelections(); } else { m_highlightTimer->start(); } } void VEdit::doHighlightExtraSelections() { int nrExtra = m_extraSelections.size(); Q_ASSERT(nrExtra == (int)SelectionId::MaxSelection); QList<QTextEdit::ExtraSelection> extraSelects; for (int i = 0; i < nrExtra; ++i) { extraSelects.append(m_extraSelections[i]); } setExtraSelections(extraSelects); } void VEdit::highlightCurrentLine() { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::CurrentLine]; if (g_config->getHighlightCursorLine() && !isReadOnly()) { // Need to highlight current line. selects.clear(); // A long block maybe splited into multiple visual lines. QTextEdit::ExtraSelection select; select.format.setBackground(m_config.m_cursorLineBg); select.format.setProperty(QTextFormat::FullWidthSelection, true); QTextCursor cursor = textCursor(); if (m_config.m_highlightWholeBlock) { cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor, 1); QTextBlock block = cursor.block(); int blockEnd = block.position() + block.length(); int pos = -1; while (cursor.position() < blockEnd && pos != cursor.position()) { QTextEdit::ExtraSelection newSelect = select; newSelect.cursor = cursor; selects.append(newSelect); pos = cursor.position(); cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, 1); } } else { cursor.clearSelection(); select.cursor = cursor; selects.append(select); } } else { // Need to clear current line highlight. if (selects.isEmpty()) { return; } selects.clear(); } highlightExtraSelections(true); } void VEdit::highlightSelectedWord() { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SelectedWord]; if (!g_config->getHighlightSelectedWord()) { if (!selects.isEmpty()) { selects.clear(); highlightExtraSelections(true); } return; } QString text = textCursor().selectedText().trimmed(); if (text.isEmpty() || wordInSearchedSelection(text)) { selects.clear(); highlightExtraSelections(true); return; } QTextCharFormat format; format.setBackground(m_selectedWordColor); highlightTextAll(text, FindOption::CaseSensitive, SelectionId::SelectedWord, format); } // Do not highlight trailing spaces with current cursor right behind. static void trailingSpaceFilter(VEdit *p_editor, QList<QTextEdit::ExtraSelection> &p_result) { QTextCursor cursor = p_editor->textCursor(); if (!cursor.atBlockEnd()) { return; } int cursorPos = cursor.position(); for (auto it = p_result.begin(); it != p_result.end(); ++it) { if (it->cursor.selectionEnd() == cursorPos) { p_result.erase(it); // There will be only one. return; } } } void VEdit::highlightTrailingSpace() { if (!g_config->getEnableTrailingSpaceHighlight()) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::TrailingSpace]; if (!selects.isEmpty()) { selects.clear(); highlightExtraSelections(true); } return; } QTextCharFormat format; format.setBackground(m_trailingSpaceColor); QString text("\\s+$"); highlightTextAll(text, FindOption::RegularExpression, SelectionId::TrailingSpace, format, trailingSpaceFilter); } bool VEdit::wordInSearchedSelection(const QString &p_text) { QString text = p_text.trimmed(); QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeyword]; for (int i = 0; i < selects.size(); ++i) { QString searchedWord = selects[i].cursor.selectedText(); if (text == searchedWord.trimmed()) { return true; } } return false; } void VEdit::highlightTextAll(const QString &p_text, uint p_options, SelectionId p_id, QTextCharFormat p_format, void (*p_filter)(VEdit *, QList<QTextEdit::ExtraSelection> &)) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)p_id]; if (!p_text.isEmpty()) { selects.clear(); QList<QTextCursor> occurs = findTextAll(p_text, p_options); for (int i = 0; i < occurs.size(); ++i) { QTextEdit::ExtraSelection select; select.format = p_format; select.cursor = occurs[i]; selects.append(select); } } else { if (selects.isEmpty()) { return; } selects.clear(); } if (p_filter) { p_filter(this, selects); } highlightExtraSelections(); } void VEdit::highlightSearchedWord(const QString &p_text, uint p_options) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeyword]; if (!g_config->getHighlightSearchedWord() || p_text.isEmpty()) { if (!selects.isEmpty()) { selects.clear(); highlightExtraSelections(true); } return; } QTextCharFormat format; format.setBackground(m_searchedWordColor); highlightTextAll(p_text, p_options, SelectionId::SearchedKeyword, format); } void VEdit::highlightSearchedWordUnderCursor(const QTextCursor &p_cursor) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeywordUnderCursor]; if (!p_cursor.hasSelection()) { if (!selects.isEmpty()) { selects.clear(); highlightExtraSelections(true); } return; } selects.clear(); QTextEdit::ExtraSelection select; select.format.setBackground(m_searchedWordCursorColor); select.cursor = p_cursor; selects.append(select); highlightExtraSelections(true); } void VEdit::highlightIncrementalSearchedWord(const QTextCursor &p_cursor) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::IncrementalSearchedKeyword]; if (!g_config->getHighlightSearchedWord() || !p_cursor.hasSelection()) { if (!selects.isEmpty()) { selects.clear(); highlightExtraSelections(true); } return; } selects.clear(); QTextEdit::ExtraSelection select; select.format.setBackground(m_incrementalSearchedWordColor); select.cursor = p_cursor; selects.append(select); highlightExtraSelections(true); } void VEdit::clearSearchedWordHighlight() { clearIncrementalSearchedWordHighlight(false); clearSearchedWordUnderCursorHighlight(false); QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeyword]; if (selects.isEmpty()) { return; } selects.clear(); highlightExtraSelections(true); } void VEdit::clearSearchedWordUnderCursorHighlight(bool p_now) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeywordUnderCursor]; if (selects.isEmpty()) { return; } selects.clear(); highlightExtraSelections(p_now); } void VEdit::clearIncrementalSearchedWordHighlight(bool p_now) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::IncrementalSearchedKeyword]; if (selects.isEmpty()) { return; } selects.clear(); highlightExtraSelections(p_now); } void VEdit::contextMenuEvent(QContextMenuEvent *p_event) { QMenu *menu = createStandardContextMenu(); menu->setToolTipsVisible(true); const QList<QAction *> actions = menu->actions(); if (!textCursor().hasSelection()) { VEditTab *editTab = dynamic_cast<VEditTab *>(parent()); V_ASSERT(editTab); if (editTab->isEditMode()) { QAction *saveExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/save_exit.svg"), tr("&Save Changes And Read"), this); saveExitAct->setToolTip(tr("Save changes and exit edit mode")); connect(saveExitAct, &QAction::triggered, this, &VEdit::handleSaveExitAct); QAction *discardExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/discard_exit.svg"), tr("&Discard Changes And Read"), this); discardExitAct->setToolTip(tr("Discard changes and exit edit mode")); connect(discardExitAct, &QAction::triggered, this, &VEdit::handleDiscardExitAct); menu->insertAction(actions.isEmpty() ? NULL : actions[0], discardExitAct); menu->insertAction(discardExitAct, saveExitAct); if (!actions.isEmpty()) { menu->insertSeparator(actions[0]); } } else if (m_file->isModifiable()) { // HTML. QAction *editAct= new QAction(VIconUtils::menuIcon(":/resources/icons/edit_note.svg"), tr("&Edit"), this); editAct->setToolTip(tr("Edit current note")); connect(editAct, &QAction::triggered, this, &VEdit::handleEditAct); menu->insertAction(actions.isEmpty() ? NULL : actions[0], editAct); // actions does not contain editAction. if (!actions.isEmpty()) { menu->insertSeparator(actions[0]); } } } alterContextMenu(menu, actions); menu->exec(p_event->globalPos()); delete menu; } void VEdit::handleSaveExitAct() { emit saveAndRead(); } void VEdit::handleDiscardExitAct() { emit discardAndRead(); } void VEdit::handleEditAct() { emit editNote(); } VFile *VEdit::getFile() const { return m_file; } void VEdit::handleCursorPositionChanged() { static QTextCursor lastCursor; QTextCursor cursor = textCursor(); if (lastCursor.isNull() || cursor.blockNumber() != lastCursor.blockNumber()) { highlightCurrentLine(); highlightTrailingSpace(); } else { // Judge whether we have trailing space at current line. QString text = cursor.block().text(); if (text.rbegin()->isSpace()) { highlightTrailingSpace(); } // Handle word-wrap in one block. // Highlight current line if in different visual line. if ((lastCursor.positionInBlock() - lastCursor.columnNumber()) != (cursor.positionInBlock() - cursor.columnNumber())) { highlightCurrentLine(); } } lastCursor = cursor; } VEditConfig &VEdit::getConfig() { return m_config; } void VEdit::mousePressEvent(QMouseEvent *p_event) { if (p_event->button() == Qt::LeftButton && p_event->modifiers() == Qt::ControlModifier && !textCursor().hasSelection()) { m_oriMouseX = p_event->x(); m_oriMouseY = p_event->y(); m_readyToScroll = true; m_mouseMoveScrolled = false; p_event->accept(); return; } m_readyToScroll = false; m_mouseMoveScrolled = false; QTextEdit::mousePressEvent(p_event); emit selectionChangedByMouse(textCursor().hasSelection()); } void VEdit::mouseReleaseEvent(QMouseEvent *p_event) { if (m_mouseMoveScrolled || m_readyToScroll) { viewport()->setCursor(Qt::IBeamCursor); m_readyToScroll = false; m_mouseMoveScrolled = false; p_event->accept(); return; } m_readyToScroll = false; m_mouseMoveScrolled = false; QTextEdit::mouseReleaseEvent(p_event); } void VEdit::mouseMoveEvent(QMouseEvent *p_event) { const int threshold = 5; if (m_readyToScroll) { int deltaX = p_event->x() - m_oriMouseX; int deltaY = p_event->y() - m_oriMouseY; if (qAbs(deltaX) >= threshold || qAbs(deltaY) >= threshold) { m_oriMouseX = p_event->x(); m_oriMouseY = p_event->y(); if (!m_mouseMoveScrolled) { m_mouseMoveScrolled = true; viewport()->setCursor(Qt::SizeAllCursor); } QScrollBar *verBar = verticalScrollBar(); QScrollBar *horBar = horizontalScrollBar(); if (verBar->isVisible()) { verBar->setValue(verBar->value() - deltaY); } if (horBar->isVisible()) { horBar->setValue(horBar->value() - deltaX); } } p_event->accept(); return; } QTextEdit::mouseMoveEvent(p_event); emit selectionChangedByMouse(textCursor().hasSelection()); } void VEdit::requestUpdateVimStatus() { if (m_editOps) { m_editOps->requestUpdateVimStatus(); } else { emit vimStatusUpdated(NULL); } } bool VEdit::jumpTitle(bool p_forward, int p_relativeLevel, int p_repeat) { Q_UNUSED(p_forward); Q_UNUSED(p_relativeLevel); Q_UNUSED(p_repeat); return false; } QVariant VEdit::inputMethodQuery(Qt::InputMethodQuery p_query) const { if (p_query == Qt::ImEnabled) { return m_enableInputMethod; } return QTextEdit::inputMethodQuery(p_query); } void VEdit::setInputMethodEnabled(bool p_enabled) { if (m_enableInputMethod != p_enabled) { m_enableInputMethod = p_enabled; QInputMethod *im = QGuiApplication::inputMethod(); im->reset(); // Ask input method to query current state, which will call inputMethodQuery(). im->update(Qt::ImEnabled); } } void VEdit::decorateText(TextDecoration p_decoration) { if (m_editOps) { m_editOps->decorateText(p_decoration); } } void VEdit::updateLineNumberAreaMargin() { int width = 0; if (g_config->getEditorLineNumber()) { width = m_lineNumberArea->calculateWidth(); } setViewportMargins(width, 0, 0, 0); } void VEdit::updateLineNumberArea() { if (g_config->getEditorLineNumber()) { if (!m_lineNumberArea->isVisible()) { updateLineNumberAreaMargin(); m_lineNumberArea->show(); } m_lineNumberArea->update(); } else if (m_lineNumberArea->isVisible()) { updateLineNumberAreaMargin(); m_lineNumberArea->hide(); } } void VEdit::resizeEvent(QResizeEvent *p_event) { QTextEdit::resizeEvent(p_event); if (g_config->getEditorLineNumber()) { QRect rect = contentsRect(); m_lineNumberArea->setGeometry(QRect(rect.left(), rect.top(), m_lineNumberArea->calculateWidth(), rect.height())); } } void VEdit::lineNumberAreaPaintEvent(QPaintEvent *p_event) { int lineNumberType = g_config->getEditorLineNumber(); if (!lineNumberType) { updateLineNumberAreaMargin(); m_lineNumberArea->hide(); return; } QPainter painter(m_lineNumberArea); painter.fillRect(p_event->rect(), g_config->getEditorLineNumberBg()); QAbstractTextDocumentLayout *layout = document()->documentLayout(); QTextBlock block = firstVisibleBlock(); if (!block.isValid()) { return; } int blockNumber = block.blockNumber(); int offsetY = contentOffsetY(); QRectF rect = layout->blockBoundingRect(block); int top = offsetY + (int)rect.y(); int bottom = top + (int)rect.height(); int eventTop = p_event->rect().top(); int eventBtm = p_event->rect().bottom(); const int digitHeight = m_lineNumberArea->getDigitHeight(); const int curBlockNumber = textCursor().block().blockNumber(); const QString &fg = g_config->getEditorLineNumberFg(); const int lineDistanceHeight = m_config.m_lineDistanceHeight; painter.setPen(fg); // Display line number only in code block. if (lineNumberType == 3) { if (m_file->getDocType() != DocType::Markdown) { return; } int number = 0; while (block.isValid() && top <= eventBtm) { int blockState = block.userState(); switch (blockState) { case HighlightBlockState::CodeBlockStart: Q_ASSERT(number == 0); number = 1; break; case HighlightBlockState::CodeBlockEnd: number = 0; break; case HighlightBlockState::CodeBlock: if (number == 0) { // Need to find current line number in code block. QTextBlock startBlock = block.previous(); while (startBlock.isValid()) { if (startBlock.userState() == HighlightBlockState::CodeBlockStart) { number = block.blockNumber() - startBlock.blockNumber(); break; } startBlock = startBlock.previous(); } } break; default: break; } if (blockState == HighlightBlockState::CodeBlock) { if (block.isVisible() && bottom >= eventTop) { QString numberStr = QString::number(number); painter.drawText(0, top + 2, m_lineNumberArea->width(), digitHeight, Qt::AlignRight, numberStr); } ++number; } block = block.next(); top = bottom; bottom = top + (int)layout->blockBoundingRect(block).height() + lineDistanceHeight; } return; } // Handle lineNumberType 1 and 2. Q_ASSERT(lineNumberType == 1 || lineNumberType == 2); while (block.isValid() && top <= eventBtm) { if (block.isVisible() && bottom >= eventTop) { bool currentLine = false; int number = blockNumber + 1; if (lineNumberType == 2) { number = blockNumber - curBlockNumber; if (number == 0) { currentLine = true; number = blockNumber + 1; } else if (number < 0) { number = -number; } } else if (blockNumber == curBlockNumber) { currentLine = true; } QString numberStr = QString::number(number); if (currentLine) { QFont font = painter.font(); font.setBold(true); painter.setFont(font); } painter.drawText(0, top + 2, m_lineNumberArea->width(), digitHeight, Qt::AlignRight, numberStr); if (currentLine) { QFont font = painter.font(); font.setBold(false); painter.setFont(font); } } block = block.next(); top = bottom; bottom = top + (int)layout->blockBoundingRect(block).height() + lineDistanceHeight; ++blockNumber; } } int VEdit::contentOffsetY() { int offsety = 0; QScrollBar *sb = verticalScrollBar(); offsety = sb->value(); return -offsety; } QTextBlock VEdit::firstVisibleBlock() { QTextDocument *doc = document(); QAbstractTextDocumentLayout *layout = doc->documentLayout(); int offsetY = contentOffsetY(); // Binary search. int idx = -1; int start = 0, end = doc->blockCount() - 1; while (start <= end) { int mid = start + (end - start) / 2; QTextBlock block = doc->findBlockByNumber(mid); if (!block.isValid()) { break; } int y = offsetY + (int)layout->blockBoundingRect(block).y(); if (y == 0) { return block; } else if (y < 0) { start = mid + 1; } else { if (idx == -1 || mid < idx) { idx = mid; } end = mid - 1; } } if (idx != -1) { return doc->findBlockByNumber(idx); } // Linear search. qDebug() << "fall back to linear search for first visible block"; QTextBlock block = doc->begin(); while (block.isValid()) { int y = offsetY + (int)layout->blockBoundingRect(block).y(); if (y >= 0) { return block; } block = block.next(); } return QTextBlock(); } int LineNumberArea::calculateWidth() const { int bc = m_document->blockCount(); if (m_blockCount == bc) { return m_width; } const_cast<LineNumberArea *>(this)->m_blockCount = bc; int digits = 1; int max = qMax(1, m_blockCount); while (max >= 10) { max /= 10; ++digits; } int width = m_digitWidth * digits; const_cast<LineNumberArea *>(this)->m_width = width; return m_width; } void VEdit::makeBlockVisible(const QTextBlock &p_block) { if (!p_block.isValid() || !p_block.isVisible()) { return; } QScrollBar *vbar = verticalScrollBar(); if (!vbar || !vbar->isVisible()) { // No vertical scrollbar. No need to scroll. return; } QAbstractTextDocumentLayout *layout = document()->documentLayout(); int height = rect().height(); QScrollBar *hbar = horizontalScrollBar(); if (hbar && hbar->isVisible()) { height -= hbar->height(); } bool moved = false; QRectF rect = layout->blockBoundingRect(p_block); int y = contentOffsetY() + (int)rect.y(); int rectHeight = (int)rect.height(); // Handle the case rectHeight >= height. if (rectHeight >= height) { if (y <= 0) { if (y + rectHeight < height) { // Need to scroll up. while (y + rectHeight < height && vbar->value() > vbar->minimum()) { moved = true; vbar->setValue(vbar->value() - vbar->singleStep()); rect = layout->blockBoundingRect(p_block); rectHeight = (int)rect.height(); y = contentOffsetY() + (int)rect.y(); } } } else { // Need to scroll down. while (y > 0 && vbar->value() < vbar->maximum()) { moved = true; vbar->setValue(vbar->value() + vbar->singleStep()); rect = layout->blockBoundingRect(p_block); rectHeight = (int)rect.height(); y = contentOffsetY() + (int)rect.y(); } } if (moved) { qDebug() << "scroll to make huge block visible"; } return; } while (y < 0 && vbar->value() > vbar->minimum()) { moved = true; vbar->setValue(vbar->value() - vbar->singleStep()); rect = layout->blockBoundingRect(p_block); rectHeight = (int)rect.height(); y = contentOffsetY() + (int)rect.y(); } if (moved) { qDebug() << "scroll page down to make block visible"; return; } while (y + rectHeight > height && vbar->value() < vbar->maximum()) { moved = true; vbar->setValue(vbar->value() + vbar->singleStep()); rect = layout->blockBoundingRect(p_block); rectHeight = (int)rect.height(); y = contentOffsetY() + (int)rect.y(); } if (moved) { qDebug() << "scroll page up to make block visible"; } } bool VEdit::isBlockVisible(const QTextBlock &p_block) { if (!p_block.isValid() || !p_block.isVisible()) { return false; } QScrollBar *vbar = verticalScrollBar(); if (!vbar || !vbar->isVisible()) { // No vertical scrollbar. return true; } QAbstractTextDocumentLayout *layout = document()->documentLayout(); int height = rect().height(); QScrollBar *hbar = horizontalScrollBar(); if (hbar && hbar->isVisible()) { height -= hbar->height(); } QRectF rect = layout->blockBoundingRect(p_block); int y = contentOffsetY() + (int)rect.y(); int rectHeight = (int)rect.height(); return (y >= 0 && y < height) || (y < 0 && y + rectHeight > 0); } void VEdit::alterContextMenu(QMenu *p_menu, const QList<QAction *> &p_actions) { Q_UNUSED(p_menu); Q_UNUSED(p_actions); } void VEdit::updateBlockLineDistanceHeight(int p_pos, int p_charsRemoved, int p_charsAdded) { if ((p_charsRemoved == 0 && p_charsAdded == 0) || m_config.m_lineDistanceHeight <= 0) { return; } QTextDocument *doc = document(); QTextBlock block = doc->findBlock(p_pos); QTextBlock lastBlock = doc->findBlock(p_pos + p_charsRemoved + p_charsAdded); QTextCursor cursor(block); bool changed = false; while (block.isValid()) { cursor.setPosition(block.position()); QTextBlockFormat fmt = cursor.blockFormat(); if (fmt.lineHeightType() != QTextBlockFormat::LineDistanceHeight || fmt.lineHeight() != m_config.m_lineDistanceHeight) { fmt.setLineHeight(m_config.m_lineDistanceHeight, QTextBlockFormat::LineDistanceHeight); if (!changed) { changed = true; cursor.joinPreviousEditBlock(); } cursor.mergeBlockFormat(fmt); qDebug() << "merge block format line distance" << block.blockNumber(); } if (block == lastBlock) { break; } block = block.next(); } if (changed) { cursor.endEditBlock(); } } void VEdit::evaluateMagicWords() { QString text; QTextCursor cursor = textCursor(); if (!cursor.hasSelection()) { // Get the WORD in current cursor. int start, end; VEditUtils::findCurrentWORD(cursor, start, end); if (start == end) { return; } else { cursor.setPosition(start); cursor.setPosition(end, QTextCursor::KeepAnchor); } } text = VEditUtils::selectedText(cursor); Q_ASSERT(!text.isEmpty()); QString evaText = g_mwMgr->evaluate(text); if (text != evaText) { qDebug() << "evaluateMagicWords" << text << evaText; cursor.insertText(evaText); if (m_editOps) { m_editOps->setVimMode(VimMode::Insert); } setTextCursor(cursor); } } void VEdit::setReadOnlyAndHighlight(bool p_readonly) { setReadOnly(p_readonly); highlightCurrentLine(); }
28.615815
112
0.58092
f4f2b945b1685e17693494aed5602c18ef01f341
5,812
cxx
C++
Modules/Filtering/FFT/test/itkForwardInverseFFTImageFilterTest.cxx
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2020-10-09T18:12:53.000Z
2020-10-09T18:12:53.000Z
Modules/Filtering/FFT/test/itkForwardInverseFFTImageFilterTest.cxx
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2018-10-18T18:49:19.000Z
2018-10-18T18:49:19.000Z
Modules/Filtering/FFT/test/itkForwardInverseFFTImageFilterTest.cxx
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2020-10-13T07:24:57.000Z
2020-10-13T07:24:57.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkVnlForwardFFTImageFilter.h" #include "itkVnlInverseFFTImageFilter.h" #include "itkVnlRealToHalfHermitianForwardFFTImageFilter.h" #include "itkVnlHalfHermitianToRealInverseFFTImageFilter.h" #if defined(ITK_USE_FFTWF) || defined(ITK_USE_FFTWD) #include "itkFFTWForwardFFTImageFilter.h" #include "itkFFTWInverseFFTImageFilter.h" #include "itkFFTWRealToHalfHermitianForwardFFTImageFilter.h" #include "itkFFTWHalfHermitianToRealInverseFFTImageFilter.h" #endif #include "itkForwardInverseFFTTest.h" int itkForwardInverseFFTImageFilterTest(int argc, char* argv[]) { if ( argc < 2 ) { std::cout << "Usage: " << argv[0] << " <input file> " << std::endl; return EXIT_FAILURE; } constexpr unsigned int Dimension = 2; using FloatType = float; using DoubleType = double; using FloatImageType = itk::Image< FloatType, Dimension >; using DoubleImageType = itk::Image< DoubleType, Dimension >; bool success = true; using FloatVnlFullFFTType = itk::VnlForwardFFTImageFilter<FloatImageType>; using FloatVnlFullIFFTType = itk::VnlInverseFFTImageFilter<FloatVnlFullFFTType::OutputImageType>; if ( !ForwardInverseFullFFTTest< FloatVnlFullFFTType, FloatVnlFullIFFTType >( argv[1] ) ) { success = false; std::cerr << "Test failed for FloatVnlFullFFTType" << std::endl; } else { std::cout << "Test passed for FloatVnlFullFFTType" << std::endl; } using DoubleVnlFullFFTType = itk::VnlForwardFFTImageFilter<DoubleImageType>; using DoubleVnlFullIFFTType = itk::VnlInverseFFTImageFilter<DoubleVnlFullFFTType::OutputImageType>; if ( !ForwardInverseFullFFTTest< DoubleVnlFullFFTType, DoubleVnlFullIFFTType >( argv[1] ) ) { success = false; std::cerr << "Test failed for DoubleVnlFullFFTType" << std::endl; } else { std::cout << "Test passed for DoubleVnlFullFFTType" << std::endl; } #if defined(ITK_USE_FFTWF) using FloatFFTWFullFFTType = itk::FFTWForwardFFTImageFilter<FloatImageType>; using FloatFFTWFullIFFTType = itk::FFTWInverseFFTImageFilter<FloatFFTWFullFFTType::OutputImageType>; if ( !ForwardInverseFullFFTTest< FloatFFTWFullFFTType, FloatFFTWFullIFFTType >( argv[1] ) ) { success = false; std::cerr << "Test failed for FloatFFTWFullFFTType" << std::endl; } else { std::cout << "Test passed for FloatFFTWFullFFTType" << std::endl; } #endif #if defined(ITK_USE_FFTWD) using DoubleFFTWFullFFTType = itk::FFTWForwardFFTImageFilter<DoubleImageType>; using DoubleFFTWFullIFFTType = itk::FFTWInverseFFTImageFilter<DoubleFFTWFullFFTType::OutputImageType>; if ( !ForwardInverseFullFFTTest< DoubleFFTWFullFFTType, DoubleFFTWFullIFFTType >( argv[1] ) ) { success = false; std::cerr << "Test failed for DoubleFFTWFullFFTType" << std::endl; } else { std::cout << "Test passed for DoubleFFTWFullFFTType" << std::endl; } #endif using FloatVnlHalfFFTType = itk::VnlRealToHalfHermitianForwardFFTImageFilter<FloatImageType>; using FloatVnlHalfIFFTType = itk::VnlHalfHermitianToRealInverseFFTImageFilter<FloatVnlHalfFFTType::OutputImageType>; if ( !ForwardInverseHalfFFTTest< FloatVnlHalfFFTType, FloatVnlHalfIFFTType >( argv[1] ) ) { success = false; std::cerr << "Test failed for FloatVnlHalfFFTType" << std::endl; } else { std::cout << "Test passed for FloatVnlHalfFFTType" << std::endl; } using DoubleVnlHalfFFTType = itk::VnlRealToHalfHermitianForwardFFTImageFilter<DoubleImageType>; using DoubleVnlHalfIFFTType = itk::VnlHalfHermitianToRealInverseFFTImageFilter<DoubleVnlHalfFFTType::OutputImageType>; if ( !ForwardInverseHalfFFTTest< DoubleVnlHalfFFTType, DoubleVnlHalfIFFTType >( argv[1] ) ) { success = false; std::cerr << "Test failed for DoubleVnlHalfFFTType" << std::endl; } else { std::cout << "Test passed for DoubleVnlHalfFFTType" << std::endl; } #if defined(ITK_USE_FFTWF) using FloatFFTWHalfFFTType = itk::FFTWRealToHalfHermitianForwardFFTImageFilter<FloatImageType>; using FloatFFTWHalfIFFTType = itk::FFTWHalfHermitianToRealInverseFFTImageFilter<FloatFFTWHalfFFTType::OutputImageType>; if ( !ForwardInverseHalfFFTTest< FloatFFTWHalfFFTType, FloatFFTWHalfIFFTType >( argv[1] ) ) { success = false; std::cerr << "Test failed for FloatFFTWHalfFFTType" << std::endl; } else { std::cout << "Test passed for FloatFFTWHalfFFTType" << std::endl; } #endif #if defined(ITK_USE_FFTWD) using DoubleFFTWHalfFFTType = itk::FFTWRealToHalfHermitianForwardFFTImageFilter<DoubleImageType>; using DoubleFFTWHalfIFFTType = itk::FFTWHalfHermitianToRealInverseFFTImageFilter<DoubleFFTWHalfFFTType::OutputImageType>; if ( !ForwardInverseHalfFFTTest< DoubleFFTWHalfFFTType, DoubleFFTWHalfIFFTType >( argv[1] ) ) { success = false; std::cerr << "Test failed for DoubleFFTWHalfFFTType" << std::endl; } else { std::cout << "Test passed for DoubleFFTWHalfFFTType" << std::endl; } #endif return success ? EXIT_SUCCESS : EXIT_FAILURE; }
37.25641
123
0.720062
f4f8b3ded57685503b36f0e9542b3f5210036b25
34,267
cpp
C++
multimedia/dshow/filters/inftee/inftee.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/dshow/filters/inftee/inftee.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/dshow/filters/inftee/inftee.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//==========================================================================; // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. // // Copyright (c) 1992 - 1998 Microsoft Corporation. All Rights Reserved. // //--------------------------------------------------------------------------; #include <streams.h> #include <initguid.h> #include <inftee.h> #include <tchar.h> #include <stdio.h> // // // What this sample illustrates // // A pass through filter splits a data stream into many output channels // // Summary // // This is a sample ActiveMovie pass through filter. We have a single input // pin and can have many output pins. We start with one output pin and each // time we connect an output pin we spawn another, although we could keep // doing this ad infinitum we have a top level maximum of INFTEE_MAX_PINS. // Any data samples our input pin receives will be sent down each output // pin in turn. Each output pin has a separate thread if necessary (see // the output queue class in the SDK) to avoid delivery blocking our thread // // Demonstration instructions // // Start GRAPHEDT available in the ActiveMovie SDK tools. Drag and drop any // MPEG, AVI or MOV file into the tool and it will be rendered. Then go to // the filters in the graph and find the filter (box) titled "Video Renderer" // Then click on the box and hit DELETE. After that go to the Graph menu and // select "Insert Filters", from the dialog box find and select the "Infinite // Tee Filter" and then dismiss the dialog. Back in the graph layout find the // output pin of the filter that was connected to the input of the video // renderer you just deleted, right click and select "Render". You should // see it being connected to the input pin of the filter you just inserted // // The infinite tee filter will have one output pin connected and will have // spawned another, right click on this and select Render. A new renderer // will pop up fo the stream. Do this once or twice more and then click on // the Pause and Run on the GRAPHEDT frame and you will see the video... // .. many times over in different windows // // Files // // inftee.cpp Main implementation of the infinite tee // inftee.def What APIs the DLL will import and export // inftee.h Class definition of the infinite tee // inftee.rc Not much, just our version information // inftee.reg What goes in the registry to make us work // makefile How to build it... // // // Base classes used // // CBaseInputPin Basic IMemInputPin based input pin // CBaseOutputPin Used for basic connection stuff // CBaseFilter Well we need a filter don't we // CCritSec Controls access to output pin list // COutputQueue Delivers data on a separate thread // // #define INFTEE_MAX_PINS 1000 // Using this pointer in constructor #pragma warning(disable:4355) // Setup data const AMOVIESETUP_MEDIATYPE sudPinTypes = { &MEDIATYPE_NULL, // Major CLSID &MEDIASUBTYPE_NULL // Minor type }; const AMOVIESETUP_PIN psudPins[] = { { L"Input", // Pin's string name FALSE, // Is it rendered FALSE, // Is it an output FALSE, // Allowed none FALSE, // Allowed many &CLSID_NULL, // Connects to filter L"Output", // Connects to pin 1, // Number of types &sudPinTypes }, // Pin information { L"Output", // Pin's string name FALSE, // Is it rendered TRUE, // Is it an output FALSE, // Allowed none FALSE, // Allowed many &CLSID_NULL, // Connects to filter L"Input", // Connects to pin 1, // Number of types &sudPinTypes } // Pin information }; const AMOVIESETUP_FILTER sudInfTee = { &CLSID_InfTee, // CLSID of filter L"Infinite Pin Tee Filter", // Filter's name MERIT_DO_NOT_USE, // Filter merit 2, // Number of pins psudPins // Pin information }; #ifdef FILTER_DLL CFactoryTemplate g_Templates [1] = { { L"Infinite Pin Tee" , &CLSID_InfTee , CTee::CreateInstance , NULL , &sudInfTee } }; int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]); // // DllRegisterServer // STDAPI DllRegisterServer() { return AMovieDllRegisterServer2( TRUE ); } // // DllUnregisterServer // STDAPI DllUnregisterServer() { return AMovieDllRegisterServer2( FALSE ); } #endif // // CreateInstance // // Creator function for the class ID // CUnknown * WINAPI CTee::CreateInstance(LPUNKNOWN pUnk, HRESULT *phr) { return new CTee(NAME("Infinite Tee Filter"), pUnk, phr); } // // Constructor // CTee::CTee(TCHAR *pName, LPUNKNOWN pUnk, HRESULT *phr) : m_OutputPinsList(NAME("Tee Output Pins list")), m_lCanSeek(TRUE), m_pAllocator(NULL), m_NumOutputPins(0), m_NextOutputPinNumber(0), m_Input(NAME("Input Pin"), this, phr, L"Input"), CBaseFilter(NAME("Tee filter"), pUnk, this, CLSID_InfTee) { ASSERT(phr); // Create a single output pin at this time InitOutputPinsList(); CTeeOutputPin *pOutputPin = CreateNextOutputPin(this); if (pOutputPin != NULL ) { m_NumOutputPins++; m_OutputPinsList.AddTail(pOutputPin); } } // // Destructor // CTee::~CTee() { InitOutputPinsList(); } // // GetPinCount // int CTee::GetPinCount() { return (1 + m_NumOutputPins); } // // GetPin // CBasePin *CTee::GetPin(int n) { if (n < 0) return NULL ; // Pin zero is the one and only input pin if (n == 0) return &m_Input; // return the output pin at position(n - 1) (zero based) return GetPinNFromList(n - 1); } // // InitOutputPinsList // void CTee::InitOutputPinsList() { POSITION pos = m_OutputPinsList.GetHeadPosition(); while(pos) { CTeeOutputPin *pOutputPin = m_OutputPinsList.GetNext(pos); ASSERT(pOutputPin->m_pOutputQueue == NULL); pOutputPin->Release(); } m_NumOutputPins = 0; m_OutputPinsList.RemoveAll(); } // InitOutputPinsList // // CreateNextOutputPin // CTeeOutputPin *CTee::CreateNextOutputPin(CTee *pTee) { WCHAR szbuf[20]; // Temporary scratch buffer m_NextOutputPinNumber++; // Next number to use for pin HRESULT hr = NOERROR; wsprintfW(szbuf, L"Output%d", m_NextOutputPinNumber); CTeeOutputPin *pPin = new CTeeOutputPin(NAME("Tee Output"), pTee, &hr, szbuf, m_NextOutputPinNumber); if (FAILED(hr) || pPin == NULL) { delete pPin; return NULL; } pPin->AddRef(); return pPin; } // CreateNextOutputPin // // DeleteOutputPin // void CTee::DeleteOutputPin(CTeeOutputPin *pPin) { POSITION pos = m_OutputPinsList.GetHeadPosition(); while(pos) { POSITION posold = pos; // Remember this position CTeeOutputPin *pOutputPin = m_OutputPinsList.GetNext(pos); if (pOutputPin == pPin) { // If this pin holds the seek interface release it if (pPin->m_bHoldsSeek) { InterlockedExchange(&m_lCanSeek, FALSE); pPin->m_bHoldsSeek = FALSE; pPin->m_pPosition->Release(); } m_OutputPinsList.Remove(posold); ASSERT(pOutputPin->m_pOutputQueue == NULL); delete pPin; m_NumOutputPins--; IncrementPinVersion(); break; } } } // DeleteOutputPin // // GetNumFreePins // int CTee::GetNumFreePins() { int n = 0; POSITION pos = m_OutputPinsList.GetHeadPosition(); while(pos) { CTeeOutputPin *pOutputPin = m_OutputPinsList.GetNext(pos); if (pOutputPin->m_Connected == NULL) n++; } return n; } // GetNumFreePins // // GetPinNFromList // CTeeOutputPin *CTee::GetPinNFromList(int n) { // Validate the position being asked for if (n >= m_NumOutputPins) return NULL; // Get the head of the list POSITION pos = m_OutputPinsList.GetHeadPosition(); n++; // Make the number 1 based CTeeOutputPin *pOutputPin; while(n) { pOutputPin = m_OutputPinsList.GetNext(pos); n--; } return pOutputPin; } // GetPinNFromList // // Stop // // Overriden to handle no input connections // STDMETHODIMP CTee::Stop() { CBaseFilter::Stop(); m_State = State_Stopped; return NOERROR; } // // Pause // // Overriden to handle no input connections // STDMETHODIMP CTee::Pause() { CAutoLock cObjectLock(m_pLock); HRESULT hr = CBaseFilter::Pause(); if (m_Input.IsConnected() == FALSE) { m_Input.EndOfStream(); } return hr; } // // Run // // Overriden to handle no input connections // STDMETHODIMP CTee::Run(REFERENCE_TIME tStart) { CAutoLock cObjectLock(m_pLock); HRESULT hr = CBaseFilter::Run(tStart); if (m_Input.IsConnected() == FALSE) { m_Input.EndOfStream(); } return hr; } // // CTeeInputPin constructor // CTeeInputPin::CTeeInputPin(TCHAR *pName, CTee *pTee, HRESULT *phr, LPCWSTR pPinName) : CBaseInputPin(pName, pTee, pTee, phr, pPinName), m_pTee(pTee), m_bInsideCheckMediaType(FALSE) { ASSERT(pTee); } #ifdef DEBUG // // CTeeInputPin destructor // CTeeInputPin::~CTeeInputPin() { DbgLog((LOG_TRACE,2,TEXT("CTeeInputPin destructor"))); ASSERT(m_pTee->m_pAllocator == NULL); } #endif #ifdef DEBUG // // DisplayMediaType -- (DEBUG ONLY) // void DisplayMediaType(TCHAR *pDescription,const CMediaType *pmt) { // Dump the GUID types and a short description DbgLog((LOG_TRACE,2,TEXT(""))); DbgLog((LOG_TRACE,2,TEXT("%s"),pDescription)); DbgLog((LOG_TRACE,2,TEXT(""))); DbgLog((LOG_TRACE,2,TEXT("Media Type Description"))); DbgLog((LOG_TRACE,2,TEXT("Major type %s"),GuidNames[*pmt->Type()])); DbgLog((LOG_TRACE,2,TEXT("Subtype %s"),GuidNames[*pmt->Subtype()])); DbgLog((LOG_TRACE,2,TEXT("Subtype description %s"),GetSubtypeName(pmt->Subtype()))); DbgLog((LOG_TRACE,2,TEXT("Format size %d"),pmt->cbFormat)); // Dump the generic media types */ DbgLog((LOG_TRACE,2,TEXT("Fixed size sample %d"),pmt->IsFixedSize())); DbgLog((LOG_TRACE,2,TEXT("Temporal compression %d"),pmt->IsTemporalCompressed())); DbgLog((LOG_TRACE,2,TEXT("Sample size %d"),pmt->GetSampleSize())); } // DisplayMediaType #endif // // CheckMediaType // HRESULT CTeeInputPin::CheckMediaType(const CMediaType *pmt) { CAutoLock lock_it(m_pLock); // If we are already inside checkmedia type for this pin, return NOERROR // It is possble to hookup two of the tee filters and some other filter // like the video effects sample to get into this situation. If we don't // detect this situation, we will carry on looping till we blow the stack if (m_bInsideCheckMediaType == TRUE) return NOERROR; m_bInsideCheckMediaType = TRUE; HRESULT hr = NOERROR; #ifdef DEBUG // Display the type of the media for debugging perposes DisplayMediaType(TEXT("Input Pin Checking"), pmt); #endif // The media types that we can support are entirely dependent on the // downstream connections. If we have downstream connections, we should // check with them - walk through the list calling each output pin int n = m_pTee->m_NumOutputPins; POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition(); while(n) { CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos); if (pOutputPin != NULL) { if (pOutputPin->m_Connected != NULL) { // The pin is connected, check its peer hr = pOutputPin->m_Connected->QueryAccept(pmt); if (hr != NOERROR) { m_bInsideCheckMediaType = FALSE; return VFW_E_TYPE_NOT_ACCEPTED; } } } else { // We should have as many pins as the count says we have ASSERT(FALSE); } n--; } // Either all the downstream pins have accepted or there are none. m_bInsideCheckMediaType = FALSE; return NOERROR; } // CheckMediaType // // SetMediaType // HRESULT CTeeInputPin::SetMediaType(const CMediaType *pmt) { CAutoLock lock_it(m_pLock); HRESULT hr = NOERROR; // Make sure that the base class likes it hr = CBaseInputPin::SetMediaType(pmt); if (FAILED(hr)) return hr; ASSERT(m_Connected != NULL); return NOERROR; } // SetMediaType // // BreakConnect // HRESULT CTeeInputPin::BreakConnect() { // Release any allocator that we are holding if (m_pTee->m_pAllocator) { m_pTee->m_pAllocator->Release(); m_pTee->m_pAllocator = NULL; } return NOERROR; } // BreakConnect // // NotifyAllocator // STDMETHODIMP CTeeInputPin::NotifyAllocator(IMemAllocator *pAllocator, BOOL bReadOnly) { CAutoLock lock_it(m_pLock); if (pAllocator == NULL) return E_FAIL; // Free the old allocator if any if (m_pTee->m_pAllocator) m_pTee->m_pAllocator->Release(); // Store away the new allocator pAllocator->AddRef(); m_pTee->m_pAllocator = pAllocator; // Notify the base class about the allocator return CBaseInputPin::NotifyAllocator(pAllocator,bReadOnly); } // NotifyAllocator // // EndOfStream // HRESULT CTeeInputPin::EndOfStream() { CAutoLock lock_it(m_pLock); ASSERT(m_pTee->m_NumOutputPins); HRESULT hr = NOERROR; // Walk through the output pins list, sending the message downstream int n = m_pTee->m_NumOutputPins; POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition(); while(n) { CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos); if (pOutputPin != NULL) { hr = pOutputPin->DeliverEndOfStream(); if (FAILED(hr)) return hr; } else { // We should have as many pins as the count says we have ASSERT(FALSE); } n--; } return(NOERROR); } // EndOfStream // // BeginFlush // HRESULT CTeeInputPin::BeginFlush() { CAutoLock lock_it(m_pLock); ASSERT(m_pTee->m_NumOutputPins); HRESULT hr = NOERROR; // Walk through the output pins list, sending the message downstream int n = m_pTee->m_NumOutputPins; POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition(); while(n) { CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos); if (pOutputPin != NULL) { hr = pOutputPin->DeliverBeginFlush(); if (FAILED(hr)) return hr; } else { // We should have as many pins as the count says we have ASSERT(FALSE); } n--; } return CBaseInputPin::BeginFlush(); } // BeginFlush // // EndFlush // HRESULT CTeeInputPin::EndFlush() { CAutoLock lock_it(m_pLock); ASSERT(m_pTee->m_NumOutputPins); HRESULT hr = NOERROR; // Walk through the output pins list, sending the message downstream int n = m_pTee->m_NumOutputPins; POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition(); while(n) { CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos); if (pOutputPin != NULL) { hr = pOutputPin->DeliverEndFlush(); if (FAILED(hr)) return hr; } else { // We should have as many pins as the count says we have ASSERT(FALSE); } n--; } return CBaseInputPin::EndFlush(); } // EndFlush // // NewSegment // HRESULT CTeeInputPin::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) { CAutoLock lock_it(m_pLock); ASSERT(m_pTee->m_NumOutputPins); HRESULT hr = NOERROR; // Walk through the output pins list, sending the message downstream int n = m_pTee->m_NumOutputPins; POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition(); while(n) { CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos); if (pOutputPin != NULL) { hr = pOutputPin->DeliverNewSegment(tStart, tStop, dRate); if (FAILED(hr)) return hr; } else { // We should have as many pins as the count says we have ASSERT(FALSE); } n--; } return CBaseInputPin::NewSegment(tStart, tStop, dRate); } // NewSegment // // Receive // HRESULT CTeeInputPin::Receive(IMediaSample *pSample) { CAutoLock lock_it(m_pLock); // Check that all is well with the base class HRESULT hr = NOERROR; hr = CBaseInputPin::Receive(pSample); if (hr != NOERROR) return hr; // Walk through the output pins list, delivering to each in turn int n = m_pTee->m_NumOutputPins; POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition(); while(n) { CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos); if (pOutputPin != NULL) { hr = pOutputPin->Deliver(pSample); if (hr != NOERROR) return hr; } else { // We should have as many pins as the count says we have ASSERT(FALSE); } n--; } return NOERROR; } // Receive // // Completed a connection to a pin // HRESULT CTeeInputPin::CompleteConnect(IPin *pReceivePin) { HRESULT hr = CBaseInputPin::CompleteConnect(pReceivePin); if (FAILED(hr)) { return hr; } // Force any output pins to use our type int n = m_pTee->m_NumOutputPins; POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition(); while(n) { CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos); if (pOutputPin != NULL) { // Check with downstream pin if (pOutputPin->m_Connected != NULL) { if (m_mt != pOutputPin->m_mt) m_pTee->ReconnectPin(pOutputPin, &m_mt); } } else { // We should have as many pins as the count says we have ASSERT(FALSE); } n--; } return S_OK; } // // CTeeOutputPin constructor // CTeeOutputPin::CTeeOutputPin(TCHAR *pName, CTee *pTee, HRESULT *phr, LPCWSTR pPinName, int PinNumber) : CBaseOutputPin(pName, pTee, pTee, phr, pPinName) , m_pOutputQueue(NULL), m_bHoldsSeek(FALSE), m_pPosition(NULL), m_pTee(pTee), m_cOurRef(0), m_bInsideCheckMediaType(FALSE) { ASSERT(pTee); } #ifdef DEBUG // // CTeeOutputPin destructor // CTeeOutputPin::~CTeeOutputPin() { ASSERT(m_pOutputQueue == NULL); } #endif // // NonDelegatingQueryInterface // // This function is overwritten to expose IMediaPosition and IMediaSelection // Note that only one output stream can be allowed to expose this to avoid // conflicts, the other pins will just return E_NOINTERFACE and therefore // appear as non seekable streams. We have a LONG value that if exchanged to // produce a TRUE means that we have the honor. If it exchanges to FALSE then // someone is already in. If we do get it and error occurs then we reset it // to TRUE so someone else can get it. // STDMETHODIMP CTeeOutputPin::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv,E_POINTER); ASSERT(ppv); *ppv = NULL; HRESULT hr = NOERROR; // See what interface the caller is interested in. if (riid == IID_IMediaPosition || riid == IID_IMediaSeeking) { if (m_pPosition) { if (m_bHoldsSeek == FALSE) return E_NOINTERFACE; return m_pPosition->QueryInterface(riid, ppv); } } else return CBaseOutputPin::NonDelegatingQueryInterface(riid, ppv); CAutoLock lock_it(m_pLock); ASSERT(m_pPosition == NULL); IUnknown *pMediaPosition = NULL; // Try to create a seeking implementation if (InterlockedExchange(&m_pTee->m_lCanSeek, FALSE) == FALSE) return E_NOINTERFACE; // Create implementation of this dynamically as sometimes we may never // try and seek. The helper object implements IMediaPosition and also // the IMediaSelection control interface and simply takes the calls // normally from the downstream filter and passes them upstream hr = CreatePosPassThru( GetOwner(), FALSE, (IPin *)&m_pTee->m_Input, &pMediaPosition); if (pMediaPosition == NULL) { InterlockedExchange(&m_pTee->m_lCanSeek, TRUE); return E_OUTOFMEMORY; } if (FAILED(hr)) { InterlockedExchange(&m_pTee->m_lCanSeek, TRUE); pMediaPosition->Release (); return hr; } m_pPosition = pMediaPosition; m_bHoldsSeek = TRUE; return NonDelegatingQueryInterface(riid, ppv); } // NonDelegatingQueryInterface // // NonDelegatingAddRef // // We need override this method so that we can do proper reference counting // on our output pin. The base class CBasePin does not do any reference // counting on the pin in RETAIL. // // Please refer to the comments for the NonDelegatingRelease method for more // info on why we need to do this. // STDMETHODIMP_(ULONG) CTeeOutputPin::NonDelegatingAddRef() { CAutoLock lock_it(m_pLock); #ifdef DEBUG // Update the debug only variable maintained by the base class m_cRef++; ASSERT(m_cRef > 0); #endif // Now update our reference count m_cOurRef++; ASSERT(m_cOurRef > 0); return m_cOurRef; } // NonDelegatingAddRef // // NonDelegatingRelease // // CTeeOutputPin overrides this class so that we can take the pin out of our // output pins list and delete it when its reference count drops to 1 and there // is atleast two free pins. // // Note that CreateNextOutputPin holds a reference count on the pin so that // when the count drops to 1, we know that no one else has the pin. // // Moreover, the pin that we are about to delete must be a free pin(or else // the reference would not have dropped to 1, and we must have atleast one // other free pin(as the filter always wants to have one more free pin) // // Also, since CBasePin::NonDelegatingAddRef passes the call to the owning // filter, we will have to call Release on the owning filter as well. // // Also, note that we maintain our own reference count m_cOurRef as the m_cRef // variable maintained by CBasePin is debug only. // STDMETHODIMP_(ULONG) CTeeOutputPin::NonDelegatingRelease() { CAutoLock lock_it(m_pLock); #ifdef DEBUG // Update the debug only variable in CBasePin m_cRef--; ASSERT(m_cRef >= 0); #endif // Now update our reference count m_cOurRef--; ASSERT(m_cOurRef >= 0); // if the reference count on the object has gone to one, remove // the pin from our output pins list and physically delete it // provided there are atealst two free pins in the list(including // this one) // Also, when the ref count drops to 0, it really means that our // filter that is holding one ref count has released it so we // should delete the pin as well. if (m_cOurRef <= 1) { int n = 2; // default forces pin deletion if (m_cOurRef == 1) { // Walk the list of pins, looking for count of free pins n = m_pTee->GetNumFreePins(); } // If there are two free pins, delete this one. // NOTE: normall if (n >= 2 ) { m_cOurRef = 0; #ifdef DEBUG m_cRef = 0; #endif m_pTee->DeleteOutputPin(this); return(ULONG) 0; } } return(ULONG) m_cOurRef; } // NonDelegatingRelease // // DecideBufferSize // // This has to be present to override the PURE virtual class base function // HRESULT CTeeOutputPin::DecideBufferSize(IMemAllocator *pMemAllocator, ALLOCATOR_PROPERTIES * ppropInputRequest) { return NOERROR; } // DecideBufferSize // // DecideAllocator // HRESULT CTeeOutputPin::DecideAllocator(IMemInputPin *pPin, IMemAllocator **ppAlloc) { ASSERT(m_pTee->m_pAllocator != NULL); *ppAlloc = NULL; // Tell the pin about our allocator, set by the input pin. HRESULT hr = NOERROR; hr = pPin->NotifyAllocator(m_pTee->m_pAllocator,TRUE); if (FAILED(hr)) return hr; // Return the allocator *ppAlloc = m_pTee->m_pAllocator; m_pTee->m_pAllocator->AddRef(); return NOERROR; } // DecideAllocator // // CheckMediaType // HRESULT CTeeOutputPin::CheckMediaType(const CMediaType *pmt) { CAutoLock lock_it(m_pLock); // If we are already inside checkmedia type for this pin, return NOERROR // It is possble to hookup two of the tee filters and some other filter // like the video effects sample to get into this situation. If we // do not detect this, we will loop till we blow the stack if (m_bInsideCheckMediaType == TRUE) return NOERROR; m_bInsideCheckMediaType = TRUE; HRESULT hr = NOERROR; #ifdef DEBUG // Display the type of the media for debugging purposes DisplayMediaType(TEXT("Output Pin Checking"), pmt); #endif // The input needs to have been conneced first if (m_pTee->m_Input.m_Connected == NULL) { m_bInsideCheckMediaType = FALSE; return VFW_E_NOT_CONNECTED; } // Make sure that our input pin peer is happy with this hr = m_pTee->m_Input.m_Connected->QueryAccept(pmt); if (hr != NOERROR) { m_bInsideCheckMediaType = FALSE; return VFW_E_TYPE_NOT_ACCEPTED; } // Check the format with the other outpin pins int n = m_pTee->m_NumOutputPins; POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition(); while(n) { CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos); if (pOutputPin != NULL && pOutputPin != this) { if (pOutputPin->m_Connected != NULL) { // The pin is connected, check its peer hr = pOutputPin->m_Connected->QueryAccept(pmt); if (hr != NOERROR) { m_bInsideCheckMediaType = FALSE; return VFW_E_TYPE_NOT_ACCEPTED; } } } n--; } m_bInsideCheckMediaType = FALSE; return NOERROR; } // CheckMediaType // // EnumMediaTypes // STDMETHODIMP CTeeOutputPin::EnumMediaTypes(IEnumMediaTypes **ppEnum) { CAutoLock lock_it(m_pLock); ASSERT(ppEnum); // Make sure that we are connected if (m_pTee->m_Input.m_Connected == NULL) return VFW_E_NOT_CONNECTED; // We will simply return the enumerator of our input pin's peer return m_pTee->m_Input.m_Connected->EnumMediaTypes(ppEnum); } // EnumMediaTypes // // SetMediaType // HRESULT CTeeOutputPin::SetMediaType(const CMediaType *pmt) { CAutoLock lock_it(m_pLock); #ifdef DEBUG // Display the format of the media for debugging purposes DisplayMediaType(TEXT("Output pin type agreed"), pmt); #endif // Make sure that we have an input connected if (m_pTee->m_Input.m_Connected == NULL) return VFW_E_NOT_CONNECTED; // Make sure that the base class likes it HRESULT hr = NOERROR; hr = CBaseOutputPin::SetMediaType(pmt); if (FAILED(hr)) return hr; return NOERROR; } // SetMediaType // // CompleteConnect // HRESULT CTeeOutputPin::CompleteConnect(IPin *pReceivePin) { CAutoLock lock_it(m_pLock); ASSERT(m_Connected == pReceivePin); HRESULT hr = NOERROR; hr = CBaseOutputPin::CompleteConnect(pReceivePin); if (FAILED(hr)) return hr; // If the type is not the same as that stored for the input // pin then force the input pins peer to be reconnected if (m_mt != m_pTee->m_Input.m_mt) { hr = m_pTee->ReconnectPin(m_pTee->m_Input.m_Connected, &m_mt); if(FAILED(hr)) { return hr; } } // Since this pin has been connected up, create another output pin. We // will do this only if there are no unconnected pins on us. However // CompleteConnect will get called for the same pin during reconnection int n = m_pTee->GetNumFreePins(); ASSERT(n <= 1); if (n == 1 || m_pTee->m_NumOutputPins == INFTEE_MAX_PINS) return NOERROR; // No unconnected pins left so spawn a new one CTeeOutputPin *pOutputPin = m_pTee->CreateNextOutputPin(m_pTee); if (pOutputPin != NULL ) { m_pTee->m_NumOutputPins++; m_pTee->m_OutputPinsList.AddTail(pOutputPin); m_pTee->IncrementPinVersion(); } // At this point we should be able to send some // notification that we have sprung a new pin return NOERROR; } // CompleteConnect // // Active // // This is called when we start running or go paused. We create the // output queue object to send data to our associated peer pin // HRESULT CTeeOutputPin::Active() { CAutoLock lock_it(m_pLock); HRESULT hr = NOERROR; // Make sure that the pin is connected if (m_Connected == NULL) return NOERROR; // Create the output queue if we have to if (m_pOutputQueue == NULL) { m_pOutputQueue = new COutputQueue(m_Connected, &hr, TRUE, FALSE); if (m_pOutputQueue == NULL) return E_OUTOFMEMORY; // Make sure that the constructor did not return any error if (FAILED(hr)) { delete m_pOutputQueue; m_pOutputQueue = NULL; return hr; } } // Pass the call on to the base class CBaseOutputPin::Active(); return NOERROR; } // Active // // Inactive // // This is called when we stop streaming // We delete the output queue at this time // HRESULT CTeeOutputPin::Inactive() { CAutoLock lock_it(m_pLock); // Delete the output queus associated with the pin. if (m_pOutputQueue) { delete m_pOutputQueue; m_pOutputQueue = NULL; } CBaseOutputPin::Inactive(); return NOERROR; } // Inactive // // Deliver // HRESULT CTeeOutputPin::Deliver(IMediaSample *pMediaSample) { // Make sure that we have an output queue if (m_pOutputQueue == NULL) return NOERROR; pMediaSample->AddRef(); return m_pOutputQueue->Receive(pMediaSample); } // Deliver // // DeliverEndOfStream // HRESULT CTeeOutputPin::DeliverEndOfStream() { // Make sure that we have an output queue if (m_pOutputQueue == NULL) return NOERROR; m_pOutputQueue->EOS(); return NOERROR; } // DeliverEndOfStream // // DeliverBeginFlush // HRESULT CTeeOutputPin::DeliverBeginFlush() { // Make sure that we have an output queue if (m_pOutputQueue == NULL) return NOERROR; m_pOutputQueue->BeginFlush(); return NOERROR; } // DeliverBeginFlush // // DeliverEndFlush // HRESULT CTeeOutputPin::DeliverEndFlush() { // Make sure that we have an output queue if (m_pOutputQueue == NULL) return NOERROR; m_pOutputQueue->EndFlush(); return NOERROR; } // DeliverEndFlish // // DeliverNewSegment // HRESULT CTeeOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) { // Make sure that we have an output queue if (m_pOutputQueue == NULL) return NOERROR; m_pOutputQueue->NewSegment(tStart, tStop, dRate); return NOERROR; } // DeliverNewSegment // // Notify // STDMETHODIMP CTeeOutputPin::Notify(IBaseFilter *pSender, Quality q) { // We pass the message on, which means that we find the quality sink // for our input pin and send it there POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition(); CTeeOutputPin *pFirstOutput = m_pTee->m_OutputPinsList.GetNext(pos); if (this == pFirstOutput) { if (m_pTee->m_Input.m_pQSink!=NULL) { return m_pTee->m_Input.m_pQSink->Notify(m_pTee, q); } else { // No sink set, so pass it upstream HRESULT hr; IQualityControl * pIQC; hr = VFW_E_NOT_FOUND; if (m_pTee->m_Input.m_Connected) { m_pTee->m_Input.m_Connected->QueryInterface(IID_IQualityControl,(void**)&pIQC); if (pIQC!=NULL) { hr = pIQC->Notify(m_pTee, q); pIQC->Release(); } } return hr; } } // Quality management is too hard to do return NOERROR; } // Notify
26.379523
89
0.609274
f4fcd19ec91eed6f776df2b612bb035119130639
1,015
cpp
C++
Si7006.cpp
m4nue1X/Arduino-TemperatureHumidityPressureSensors
20031b172ff4de0b6d4cc0b52151c3af6593b8ee
[ "MIT" ]
null
null
null
Si7006.cpp
m4nue1X/Arduino-TemperatureHumidityPressureSensors
20031b172ff4de0b6d4cc0b52151c3af6593b8ee
[ "MIT" ]
null
null
null
Si7006.cpp
m4nue1X/Arduino-TemperatureHumidityPressureSensors
20031b172ff4de0b6d4cc0b52151c3af6593b8ee
[ "MIT" ]
null
null
null
#include "Si7006.h" #include <WireUtil.h> int Si7006::configure(Resolution res, bool enable_heater, HeaterPower heater_power) { if(WireUtil::writeRegister(kSi7006Addr, kSi7006RegWriteUserRegister1, kSi7006UserRegister1Default | uint8_t(res) | uint8_t(enable_heater ? HeaterEnable::kEnable : HeaterEnable::kDisable)) != 0 || WireUtil::writeRegister(kSi7006Addr, kSi7006RegWriteHeaterCtrlRegister, kSi7006HeaterCtrlRegisterDefault | uint8_t(heater_power)) != 0) { return -1; } return 0; } int Si7006::measureTemperatureAndHumidity(float& temperature, float& humidity) { // NOTE: The humidy meaurement takes usually 18-19ms to finish. We allow 20ms. uint32_t humidity_raw, temperature_raw; if (WireUtil::readRegister(0x40, 0xF5, 2, humidity_raw, false, 20e3) == 0 && WireUtil::readRegister(0x40, 0xE0, 2, temperature_raw, false, 0) == 0) { humidity = 125 * humidity_raw / 65536.0 - 6; temperature = 175.72 * temperature_raw / 65536.0 - 46.85; return 0; } return -1; }
40.6
197
0.731034
f4fdcf9263914ccf76be06a87351d5576a534c0f
52,096
cpp
C++
core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/sock-new.cpp
qiuhere/Bench
80f15facb81120b754547586cf3a7e5f46ca1551
[ "Apache-2.0" ]
null
null
null
core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/sock-new.cpp
qiuhere/Bench
80f15facb81120b754547586cf3a7e5f46ca1551
[ "Apache-2.0" ]
null
null
null
core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/sock-new.cpp
qiuhere/Bench
80f15facb81120b754547586cf3a7e5f46ca1551
[ "Apache-2.0" ]
null
null
null
#include "sock.h" #ifdef GLib_UNIX class TSocketTimer : public TTTimer { private: int SockId; public: TSocketTimer(const int TimeOut, /*PSock &_Socket*/ const int _SockId) : TTTimer(TimeOut), SockId(_SockId) {} ~TSocketTimer() {} void OnTimeOut(); }; #endif ///////////////////////////////////////////////// // Socket-System class TSockSys{ public: // socket-system initialized static bool Active; #ifdef GLib_WIN32 // window handles static HWND SockWndHnd; static HWND DnsWndHnd; static HWND ReportWndHnd; static HWND TimerWndHnd; // message-handles static UINT SockMsgHnd; static UINT SockErrMsgHnd; static UINT DnsMsgHnd; static UINT ReportMsgHnd; #endif #ifdef GLib_UNIX static int TimerSignal; static int ResolverSignal; static int ET_epoll_fd, LT_epoll_fd; #endif // sockets static uint64 SockBytesRead; static uint64 SockBytesWritten; static THash<TInt, TUInt64> SockIdToHndH; static THash<TUInt64, TInt> SockHndToIdH; static THash<TUInt64, TInt> SockHndToEventIdH; #ifdef GLib_WIN32 static TIntH SockTimerIdH; #elif defined(GLib_UNIX) static THash<TInt, TInt> SockToTimerIdH; static THash<TInt, TInt> SockHndToStateH; #endif static TUInt64H ActiveSockHndH; // socket-host static THash<TUInt64, PSockHost> HndToSockHostH; // socket-event static THash<TInt, PSockEvent> IdToSockEventH; static TIntH ActiveSockEventIdH; // report-event static THash<TInt, PReportEvent> IdToReportEventH; // timer static THash<TInt, ATimer> IdToTimerH; public: // windows-sockets messages static TStr GetErrStr(const int ErrCd); #ifdef GLib_WIN32 // main message handler static LRESULT CALLBACK MainWndProc( HWND WndHnd, UINT Msg, WPARAM wParam, LPARAM lParam); #endif public: TSockSys(); ~TSockSys(); TSockSys& operator=(const TSockSys&){Fail; return *this;} #ifdef GLib_WIN32 // window handles static HWND GetSockWndHnd(){IAssert(Active); return SockWndHnd;} static HWND GetDnsWndHnd(){IAssert(Active); return DnsWndHnd;} static HWND GetReportWndHnd(){IAssert(Active); return ReportWndHnd;} static HWND GetTimerWndHnd(){IAssert(Active); return TimerWndHnd;} // message handles static UINT GetSockMsgHnd(){IAssert(Active); return SockMsgHnd;} static UINT GetSockErrMsgHnd(){IAssert(Active); return SockErrMsgHnd;} static UINT GetDnsMsgHnd(){IAssert(Active); return DnsMsgHnd;} static UINT GetReportMsgHnd(){IAssert(Active); return ReportMsgHnd;} // event set static int GetAllSockEventCdSet(){ return (FD_READ|FD_WRITE|FD_OOB|FD_ACCEPT|FD_CONNECT|FD_CLOSE);} #endif #ifdef GLib_UNIX static int GetFreeRTSig(int Start); static void SetupFAsync(int fd); static void DoIOEvent(struct epoll_event *e); static void DoIO(); static void DoTimer(siginfo_t *si); static void DoResolver(siginfo_t *si); static void AsyncLoop(); #endif // sockets (SockIdToHndH, SockHndToIdH, SockHndToEventH) static uint64 GetSockBytesRead(){return SockBytesRead;} static uint64 GetSockBytesWritten(){return SockBytesWritten;} static void AddSock( const int& SockId, const TSockHnd& SockHnd, const int& SockEventId); static void DelSock(const int& SockId); static bool IsSockId(const int& SockId){ IAssert(Active); return SockIdToHndH.IsKey(SockId);} static bool IsSockHnd(const TSockHnd& SockHnd){ IAssert(Active); return SockHndToIdH.IsKey(SockHnd);} static TSockHnd GetSockHnd(const int& SockId){ IAssert(Active); return TSockHnd(SockIdToHndH.GetDat(SockId));} static TSockHnd GetSockId(const TSockHnd& SockHnd){ IAssert(Active); return SockHndToIdH.GetDat(SockHnd);} static int GetSockEventId(const TSockHnd& SockHnd){ IAssert(Active); return SockHndToEventIdH.GetDat(SockHnd);} #ifdef GLib_WIN32 static void AddSockTimer(const int& SockId, const int& MSecs){ UINT ErrCd=(UINT)SetTimer(TSockSys::GetSockWndHnd(), SockId, uint(MSecs), NULL); ESAssert(ErrCd!=0); TSockSys::SockTimerIdH.AddKey(SockId);} static void DelIfSockTimer(const int& SockId){ KillTimer(TSockSys::GetSockWndHnd(), SockId); TSockSys::SockTimerIdH.DelIfKey(SockId);} #elif defined(GLib_UNIX) static void AddSockTimer(const int& SockId, const int& MSecs); static void DelIfSockTimer(const int& SockId); #endif static bool IsSockActive(const TSockHnd& SockHnd){ return ActiveSockHndH.IsKey(SockHnd);} static void SetSockActive(const TSockHnd& SockHnd, const bool& Active){ IAssert( (Active&&!IsSockActive(SockHnd))|| (!Active&&IsSockActive(SockHnd))); if (Active){ActiveSockHndH.AddKey(SockHnd);} else {ActiveSockHndH.DelKey(SockHnd);}} static const int MxSockBfL; // socket host (HndToSockHostH) static void AddSockHost(const TUInt64& SockHostHnd, const PSockHost& SockHost){ HndToSockHostH.AddDat(SockHostHnd, SockHost);} static void DelSockHost(const TUInt64& SockHostHnd){ HndToSockHostH.DelKey(SockHostHnd);} static bool IsSockHost(const TUInt64& SockHostHnd){ return HndToSockHostH.IsKey(SockHostHnd);} static PSockHost GetSockHost(const TUInt64& SockHostHnd){ return HndToSockHostH.GetDat(SockHostHnd);} // socket event (IdToSockEventH, ActiveSockEventIdH) static void AddSockEvent(const PSockEvent& SockEvent){ IAssert(!IsSockEvent(SockEvent)); IdToSockEventH.AddDat(SockEvent->GetSockEventId(), SockEvent);} static void DelSockEvent(const PSockEvent& SockEvent){ IdToSockEventH.DelKey(SockEvent->GetSockEventId());} static bool IsSockEvent(const int& SockEventId){ return IdToSockEventH.IsKey(TInt(SockEventId));} static bool IsSockEvent(const PSockEvent& SockEvent){ return IdToSockEventH.IsKey(TInt(SockEvent->GetSockEventId()));} static PSockEvent GetSockEvent(const int& SockEventId){ return IdToSockEventH.GetDat(SockEventId);} static bool IsSockEventActive(const int& SockEventId){ return ActiveSockEventIdH.IsKey(SockEventId);} static void SetSockEventActive(const int& SockEventId, const bool& Active){ IAssert( (Active&&!IsSockEventActive(SockEventId))|| (!Active&&IsSockEventActive(SockEventId))); if (Active){ActiveSockEventIdH.AddKey(SockEventId);} else {ActiveSockEventIdH.DelKey(SockEventId);}} // report event (IdToReportEventH) static void AddReportEvent(const PReportEvent& ReportEvent){ IAssert(!IsReportEvent(ReportEvent)); IdToReportEventH.AddDat(TInt(ReportEvent->GetReportEventId()), ReportEvent);} static void DelReportEvent(const PReportEvent& ReportEvent){ IdToReportEventH.DelKey(TInt(ReportEvent->GetReportEventId()));} static bool IsReportEvent(const PReportEvent& ReportEvent){ return IdToReportEventH.IsKey(TInt(ReportEvent->GetReportEventId()));} static PReportEvent GetReportEvent(const int& ReportEventId){ return IdToReportEventH.GetDat(ReportEventId);} // timer (IdToTimerH) static void AddTimer(const ATimer& Timer){ IAssert(!IsTimer(Timer->GetTimerId())); IdToTimerH.AddDat(TInt(Timer->GetTimerId()), Timer);} static void DelTimer(const int& TimerId){ IdToTimerH.DelKey(TimerId);} static bool IsTimer(const int& TimerId){ return IdToTimerH.IsKey(TimerId);} static ATimer GetTimer(const int& TimerId){ return IdToTimerH.GetDat(TimerId);} // socket & host events static void OnRead(const TSockHnd& SockHnd, const PSockEvent& SockEvent); static void OnWrite(const TSockHnd& SockHnd, const PSockEvent& SockEvent); static void OnOob(const TSockHnd& SockHnd, const PSockEvent& SockEvent); static void OnAccept(const TSockHnd& SockHnd, const PSockEvent& SockEvent); static void OnConnect(const TSockHnd& SockHnd, const PSockEvent& SockEvent); static void OnClose(const TSockHnd& SockHnd, const PSockEvent& SockEvent); static void OnTimeOut(const TSockHnd& SockHnd, const PSockEvent& SockEvent); static void OnError( const TSockHnd& SockHnd, const PSockEvent& SockEvent, const int& ErrCd); static void OnGetHost(const PSockHost& SockHost); // status static TStr GetStatusStr(); }; // socket system initialized bool TSockSys::Active=false; #ifdef GLib_WIN32 // window handles HWND TSockSys::SockWndHnd=0; HWND TSockSys::DnsWndHnd=0; HWND TSockSys::ReportWndHnd=0; HWND TSockSys::TimerWndHnd=0; // message handles UINT TSockSys::SockMsgHnd=0; UINT TSockSys::SockErrMsgHnd=0; UINT TSockSys::DnsMsgHnd=0; UINT TSockSys::ReportMsgHnd=0; #endif #ifdef GLib_UNIX int TSockSys::TimerSignal = -1; int TSockSys::ResolverSignal = -1; int TSockSys::ET_epoll_fd = -1; int TSockSys::LT_epoll_fd = -1; #endif // sockets uint64 TSockSys::SockBytesRead=0; uint64 TSockSys::SockBytesWritten=0; THash<TInt, TUInt64> TSockSys::SockIdToHndH; THash<TUInt64, TInt> TSockSys::SockHndToIdH; THash<TUInt64, TInt> TSockSys::SockHndToEventIdH; #ifdef GLib_WIN32 TIntH TSockSys::SockTimerIdH; #elif defined(GLib_UNIX) THash<TInt, TInt> TSockSys::SockToTimerIdH; THash<TInt, TInt> TSockSys::SockHndToStateH; #endif TUInt64H TSockSys::ActiveSockHndH; const int TSockSys::MxSockBfL=100*1024; // socket host THash<TUInt64, PSockHost> TSockSys::HndToSockHostH; // socket event THash<TInt, PSockEvent> TSockSys::IdToSockEventH; TIntH TSockSys::ActiveSockEventIdH; // report event THash<TInt, PReportEvent> TSockSys::IdToReportEventH; // timer THash<TInt, ATimer> TSockSys::IdToTimerH; TSockSys SockSys; // the only instance of TSockSys #ifdef GLib_WIN32 TStr TSockSys::GetErrStr(const int ErrCd){ switch (ErrCd){ // WSAStartup errors case WSASYSNOTREADY: return "Underlying network subsystem is not ready for network communication."; case WSAVERNOTSUPPORTED: return "The version of Windows Sockets support requested is not provided by this particular Windows Sockets implementation."; case WSAEPROCLIM: return "Limit on the number of tasks supported by the Windows Sockets implementation has been reached."; // WSACleanup error case WSANOTINITIALISED: return "Windows Sockets not initialized."; case WSAENETDOWN: return "The network subsystem has failed."; // general errors case WSAEWOULDBLOCK: return "Resource temporarily unavailable (op. would block)."; case WSAEINPROGRESS: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function."; case WSAEADDRINUSE: return "The specified address is already in use."; case WSAEADDRNOTAVAIL: return "The specified address is not available from the local machine."; case WSAEAFNOSUPPORT: return "Addresses in the specified family cannot be used with this socket."; case WSAECONNREFUSED: return "The attempt to connect was forcefully rejected."; case WSAENETUNREACH: return "The network cannot be reached from this host at this time."; case WSAEFAULT: return "Bad parameter."; case WSAEINVAL: return "The socket is already bound to an address."; case WSAEISCONN: return "The socket is already connected."; case WSAEMFILE: return "No more file descriptors are available."; case WSAENOBUFS: return "No buffer space is available. The socket cannot be connected."; case WSAENOTCONN: return "The socket is not connected."; case WSAETIMEDOUT: return "Attempt to connect timed out without establishing a connection."; case WSAECONNRESET: return "The connection was reset by the remote side."; case WSAECONNABORTED: return "The connection was terminated due to a time-out or other failure."; default: return TStr("Unknown socket error (code ")+TInt::GetStr(ErrCd)+TStr(")."); } } LRESULT CALLBACK TSockSys::MainWndProc( HWND WndHnd, UINT MsgHnd, WPARAM wParam, LPARAM lParam){ if (MsgHnd==TSockSys::SockMsgHnd){ IAssert(WndHnd==GetSockWndHnd()); TSockHnd SockHnd=wParam; if (IsSockHnd(SockHnd)){ int SockEventId=GetSockEventId(SockHnd); PSockEvent SockEvent=GetSockEvent(SockEventId); //SetSockActive(SockHnd, true); SetSockEventActive(SockEventId, true); try { int ErrCd=WSAGETSELECTERROR(lParam); if (ErrCd==0){ int EventCd=WSAGETSELECTEVENT(lParam); switch (EventCd){ case FD_READ: OnRead(SockHnd, SockEvent); break; case FD_WRITE: OnWrite(SockHnd, SockEvent); break; case FD_OOB: OnOob(SockHnd, SockEvent); break; case FD_ACCEPT: OnAccept(SockHnd, SockEvent); break; case FD_CONNECT: OnConnect(SockHnd, SockEvent); break; case FD_CLOSE: OnClose(SockHnd, SockEvent); break; default: Fail; } } else { OnError(SockHnd, SockEvent, ErrCd); } } catch (...){ SaveToErrLog("Exception from 'switch (EventCd)'"); } SetSockEventActive(SockEventId, false); //SetSockActive(SockHnd, false); } } else if (MsgHnd==TSockSys::SockErrMsgHnd){ IAssert(WndHnd==GetSockWndHnd()); TSockHnd SockHnd=wParam; if (IsSockHnd(SockHnd)){ int SockEventId=GetSockEventId(SockHnd); PSockEvent SockEvent=GetSockEvent(SockEventId); //SetSockActive(SockHnd, true); SetSockEventActive(SockEventId, true); try { int ErrCd=int(lParam); OnError(SockHnd, SockEvent, ErrCd); } catch (...){ SaveToErrLog("Exception from 'OnError(SockHnd, SockEvent, ErrCd)'"); } SetSockEventActive(SockEventId, false); //SetSockActive(SockHnd, false); } } else if (MsgHnd==WM_TIMER){ if (WndHnd==GetSockWndHnd()){ int SockId=int(wParam); DelIfSockTimer(SockId); if (IsSockId(SockId)){ TSockHnd SockHnd=GetSockHnd(SockId); int SockEventId=GetSockEventId(SockHnd); PSockEvent SockEvent=GetSockEvent(SockEventId); //SetSockActive(SockHnd, true); SetSockEventActive(SockEventId, true); try { OnTimeOut(SockHnd, SockEvent); } catch (...){ SaveToErrLog("Exception from OnTimeOut(SockHnd, SockEvent);"); } SetSockEventActive(SockEventId, false); //SetSockActive(SockHnd, false); } } else if (WndHnd==GetTimerWndHnd()){ int TimerId=int(wParam); if (TSockSys::IsTimer(TimerId)){ PTimer Timer=TSockSys::GetTimer(TimerId)(); Timer->IncTicks(); try { Timer->OnTimeOut(); } catch (...){ SaveToErrLog("Exception from Timer->OnTimeOut();"); } } } else { Fail; } } else if (MsgHnd==TSockSys::DnsMsgHnd){ IAssert(WndHnd==GetDnsWndHnd()); uint SockHostHnd=int(wParam); if (TSockSys::IsSockHost(SockHostHnd)){ TSockHostStatus Status=TSockHost::GetStatus(WSAGETASYNCERROR(lParam)); PSockHost SockHost=TSockSys::GetSockHost(SockHostHnd); SockHost->GetFromHostEnt(Status, (hostent*)SockHost->HostEntBf); DelSockHost(SockHostHnd); // !!! !bn: kaj se zgodi ce unics TSockHost prezgodi? sej se ne deregistrira? try { OnGetHost(SockHost); } catch (...){ SaveToErrLog("Exception from OnGetHost(SockHost);"); } } } else if (MsgHnd==TSockSys::ReportMsgHnd){ IAssert(WndHnd==GetReportWndHnd()); int ReportEventId=int(lParam); PReportEvent ReportEvent=TSockSys::GetReportEvent(ReportEventId); try { ReportEvent->OnReport(); } catch (...){ SaveToErrLog("Exception from ReportEvent->OnReport()"); } TSockSys::DelReportEvent(ReportEvent); } else { return DefWindowProc(WndHnd, MsgHnd, wParam, lParam); } return 0; } TSockSys::TSockSys(){ IAssert(Active==false); WNDCLASS WndClass; WndClass.style=0; WndClass.lpfnWndProc=MainWndProc; WndClass.cbClsExtra=0; WndClass.cbWndExtra=0; FSAssert((WndClass.hInstance=GetModuleHandle(NULL))!=NULL); WndClass.hIcon=NULL; WndClass.hCursor=NULL; WndClass.hbrBackground=NULL; WndClass.lpszMenuName=NULL; WndClass.lpszClassName="SockWndClass"; FSAssert(RegisterClass(&WndClass)!=0); TSockSys::SockWndHnd=CreateWindow( "SockWndClass", "Socket Window", WS_OVERLAPPEDWINDOW, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, GetModuleHandle(NULL), NULL); FSAssert(TSockSys::SockWndHnd!=NULL); TSockSys::DnsWndHnd=CreateWindow( "SockWndClass", "Dns Window", WS_OVERLAPPEDWINDOW, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, GetModuleHandle(NULL), NULL); FSAssert(TSockSys::DnsWndHnd!=NULL); TSockSys::ReportWndHnd=CreateWindow( "SockWndClass", "RepMsg Window", WS_OVERLAPPEDWINDOW, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, GetModuleHandle(NULL), NULL); FSAssert(TSockSys::ReportWndHnd!=NULL); TSockSys::TimerWndHnd=CreateWindow( "SockWndClass", "Net Timer", WS_OVERLAPPEDWINDOW, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, GetModuleHandle(NULL), NULL); FSAssert(TSockSys::TimerWndHnd!=NULL); SockMsgHnd=RegisterWindowMessage("SockSys.SockMsg"); FSAssert(SockMsgHnd!=0); SockErrMsgHnd=RegisterWindowMessage("SockSys.SockErrorMsg"); FSAssert(SockErrMsgHnd!=0); DnsMsgHnd=RegisterWindowMessage("SockSys.DnsMsg"); FSAssert(DnsMsgHnd!=0); ReportMsgHnd=RegisterWindowMessage("SockSys.RepMsg"); FSAssert(ReportMsgHnd!=0); //WORD Version=MAKEWORD((2),(0)); WORD Version=((WORD) (((BYTE) (2)) | (((WORD) ((BYTE) (0))) << 8))); WSADATA WsaData; int WsaErrCd=WSAStartup(Version, &WsaData); FAssert(WsaErrCd==0, TSockSys::GetErrStr(WsaErrCd)); FAssert( WsaData.wVersion==Version, "Can not find appropriate version of WinSock DLL."); Active=true; } TSockSys::~TSockSys(){ if (Active){ IAssert(ActiveSockHndH.Len()==0); IAssert(ActiveSockEventIdH.Len()==0); int WsaErrCd=WSACleanup(); FAssert(WsaErrCd==0, TSockSys::GetErrStr(WsaErrCd)); Active=false; } } #elif defined(GLib_UNIX) TStr TSockSys::GetErrStr(const int ErrCd) { char b[1024]; /* -- somewhat annoying - strerror_r as defined by SUSv3 doesn't want to work here. int ret = strerror_r(ErrCd, b, 1023); if (ret == -1) { if (errno == EINVAL) strcpy(b, "Invalid error number."); else if (errno == ERANGE) strcpy(b, "Insufficient storage space for error string."); else strcpy(b, "Error."); } return TStr(b); */ return TStr(strerror_r(ErrCd, b, 1023)); } void TSockSys::AddSockTimer(const int& SockId, const int& MSecs) { ATimer Tmr = new TSocketTimer(MSecs, SockId); AddTimer(Tmr); SockToTimerIdH.AddDat(SockId, Tmr->GetTimerId()); } void TSockSys::DelIfSockTimer(const int& SockId) { // can be called from within TSocketTimer::OnTimeout() ! // !!! !bn: error handling. ATimer Tmr = GetTimer(SockToTimerIdH[SockId]); DelTimer(SockToTimerIdH[SockId]); // first take from timer list, then destroy object! delete Tmr(); } int TSockSys::GetFreeRTSig(int Start) { sigset_t ss, cs; sigemptyset(&ss); sigprocmask(SIG_BLOCK, &ss, &cs); for (int i=Start;i<=SIGRTMAX;i++) { if (sigismember(&cs, i)) { // it's not blocked. if it does not have a signal handler, it's ours. struct sigaction sa; if (sigaction(i, NULL, &sa) != 0) { // !!! !bn: error handling. EINTR possible? } if ((sa.sa_flags & SA_SIGINFO) && (sa.sa_sigaction != NULL)) continue; if (!(sa.sa_flags & SA_SIGINFO) && (sa.sa_handler != NULL)) continue; return i; } } return -1; } TSockSys::TSockSys() { IAssert(Active==false); TimerSignal = GetFreeRTSig(SIGRTMIN); ResolverSignal = GetFreeRTSig(TimerSignal+1); sigset_t css; sigemptyset(&css); sigaddset(&css, SIGIO); sigaddset(&css, TimerSignal); sigaddset(&css, ResolverSignal); sigaddset(&css, SIGPIPE); // these two could kill the process on socket errors / OOB. sigaddset(&css, SIGURG); // we'll handle errors synchronously sigprocmask(SIG_BLOCK, &css, NULL); ET_epoll_fd = epoll_create(20); LT_epoll_fd = epoll_create(20); Active = true; } TSockSys::~TSockSys() { if (Active){ IAssert(ActiveSockHndH.Len()==0); IAssert(ActiveSockEventIdH.Len()==0); close(ET_epoll_fd); close(LT_epoll_fd); sigset_t css; sigemptyset(&css); sigaddset(&css, SIGIO); sigaddset(&css, TimerSignal); sigaddset(&css, ResolverSignal); sigprocmask(SIG_UNBLOCK, &css, NULL); TimerSignal = ResolverSignal = -1; Active = false; } } void TSockSys::SetupFAsync(int fd) { IAssert(Active==true); fcntl(fd, F_SETOWN, (int)getpid()); int flags = fcntl(fd, F_GETFL); flags |= O_NONBLOCK|O_ASYNC; fcntl(fd, F_SETFL, flags); struct epoll_event epe; epe.events = EPOLLIN; epe.data.fd = fd; if (epoll_ctl(LT_epoll_fd, EPOLL_CTL_ADD, fd, &epe) == -1) perror("epoll_ctl"); // !!!! TODO: kaksn assert nej bi dau tle? epe.events = EPOLLOUT | EPOLLET; if (epoll_ctl(ET_epoll_fd, EPOLL_CTL_ADD, fd, &epe) == -1) perror("epoll_ctl"); } void TSockSys::DoIOEvent(struct epoll_event *e) { printf(" event = %d on fd = %d\n", e->events, e->data.fd); TSockHnd SockHnd=e->data.fd; int Events = e->events; if (IsSockHnd(SockHnd)){ int SockEventId=GetSockEventId(SockHnd); PSockEvent SockEvent=GetSockEvent(SockEventId); //SetSockActive(SockHnd, true); SetSockEventActive(SockEventId, true); // what was the event? // note: close is handled in OnRead() // connect generates IN and OUT events, but only one is delivered [lt/et descriptors are separate, event aggregation not done] // -> if socket not connected // * OUT event ignored // * IN event triggers OnConnect [if the first-delivered event triggered connect, // then OnRead() could be called on freshly connected socket and nothing to read.] // -> if it's a listening socket, do OnAccept() // err, oob, read|close, write try { int ErrCd=TSock::GetSockErr(SockHnd); if (ErrCd==0) { if (Events & EPOLLIN) { if (SockHndToStateH[SockHnd] == scsConnected) { OnRead(SockHnd, SockEvent); } else if (SockHndToStateH[SockHnd] == scsListening) { OnAccept(SockHnd, SockEvent); } else { SockHndToStateH[SockHnd] = scsConnected; OnConnect(SockHnd, SockEvent); } } if ((Events & EPOLLOUT)&&(SockHndToStateH[SockHnd] == scsConnected)) { OnWrite(SockHnd, SockEvent); } if (Events & EPOLLPRI) { OnOob(SockHnd, SockEvent); } if (Events & EPOLLERR) { OnError(SockHnd, SockEvent, TSock::GetSockErr(SockHnd)); } // !bn: !!! to je blo not ze pred win32 SockErrReportHnd in processing kodo. a je prov? if (Events & EPOLLHUP) { // !!! a nas to sploh zanima? not really - dokler podatki so jih beremo, ko jih zmanjka jih je konc. al kako. } } else { OnError(SockHnd, SockEvent, ErrCd); } } catch (...){ SaveToErrLog("Exception from 'switch (EventCd)'"); } SetSockEventActive(SockEventId, false); //SetSockActive(SockHnd, false); } } void TSockSys::DoIO() { printf(":: do_io\n"); while (true) { // process ALL I/O events, 64+64 at a time, interleaved. that's why DelayedIO. struct epoll_event evt[2][64]; int ret = epoll_wait(LT_epoll_fd, evt[0], 64, 0); printf("lt epoll_wait.ret = %d\n", ret); int eret = epoll_wait(ET_epoll_fd, evt[1], 64, 0); printf("et epoll_wait.ret = %d\n", eret); if (ret == 0 && eret == 0) break; for (int i=0;i<ret;i++) DoIOEvent(&evt[0][i]); for (int i=0;i<eret;i++) DoIOEvent(&evt[1][i]); } } void TSockSys::DoTimer(siginfo_t *si) { int TimerId = si->si_int; if (TSockSys::IsTimer(TimerId)){ PTimer Timer=TSockSys::GetTimer(TimerId)(); Timer->IncTicks(); try { Timer->OnTimeOut(); } catch (...){ SaveToErrLog("Exception from Timer->OnTimeOut();"); } } } void TSockSys::DoResolver(siginfo_t *si) { int SockHostHnd = si->si_int; if (TSockSys::IsSockHost(SockHostHnd)) { PSockHost SockHost=TSockSys::GetSockHost(SockHostHnd); TSockHostStatus Status=TSockHost::GetStatus(&(SockHost->GAI)); SockHost->GetFromHostEnt(Status, &(SockHost->GAI)); DelSockHost(SockHostHnd); try { OnGetHost(SockHost); } catch (...){ SaveToErrLog("Exception from OnGetHost(SockHost);"); } } } void TSockSys::AsyncLoop() { bool DelayedIO = false; while (true) { int ret; sigset_t ss; siginfo_t si; sigemptyset(&ss); sigaddset(&ss, SIGIO); sigaddset(&ss, TimerSignal); sigaddset(&ss, ResolverSignal); if (DelayedIO) { struct timespec tsp; tsp.tv_sec = tsp.tv_nsec = 0; ret = sigtimedwait(&ss, &si, &tsp); } else { ret = sigwaitinfo(&ss, &si); } if (ret == -1) { if (errno == EINTR) continue; if (errno == EAGAIN) { DelayedIO = false; DoIO(); } } else { if (si.si_signo == SIGIO) { DelayedIO = true; } else if (si.si_signo == TimerSignal) { DoTimer(&si); } else if (si.si_signo == ResolverSignal) { DoResolver(&si); } } } } #endif void TSockSys::AddSock( const int& SockId, const TSockHnd& SockHnd, const int& SockEventId){ IAssert(Active); SockIdToHndH.AddDat(SockId, SockHnd); SockHndToIdH.AddDat(SockHnd, SockId); SockHndToEventIdH.AddDat(SockHnd, SockEventId); #ifdef GLib_UNIX SockHndToStateH.AddDat(SockHnd, scsCreated); SetupFAsync(SockHnd); #endif } void TSockSys::DelSock(const int& SockId){ IAssert(Active); TSockHnd SockHnd=TSockHnd(SockIdToHndH.GetDat(SockId)); IAssert(!IsSockActive(SockHnd)); // delete socket entries SockIdToHndH.DelKey(SockId); SockHndToIdH.DelKey(SockHnd); SockHndToEventIdH.DelKey(SockHnd); #ifdef GLib_UNIX SockHndToStateH.DelKey(SockHnd); #endif // kill associated timer if exists DelIfSockTimer(SockId); } #ifdef GLib_UNIX // !!! TODO: prever za vse kar si splitnu zarad SOCKET_ERROR - a je v vseh primerih -1 to ? kaj je to na windowsih? // v tem primeru bi blo upraviceno tole generalno nardit pa dat mir. #define SOCKET_ERROR -1 // !bn: GLib_UNIX -> OnReadOrClose() :) // "all subsequent reads will return -1" -> prvic ko recv() vrne 0, mormo klicat onclose() // - kje sm ze to brau? // eniwejz. al tko, al pa dobimo ENOTCONN. druzga ze ne more bit. #endif void TSockSys::OnRead(const TSockHnd& SockHnd, const PSockEvent& SockEvent){ TMem Mem(MxSockBfL); char* Bf=new char[MxSockBfL]; int BfL; do { BfL=recv(SockHnd, Bf, MxSockBfL, 0); if (BfL!=SOCKET_ERROR){ Mem.AddBf(Bf, BfL); SockBytesRead+=BfL;} } while ((BfL>0)&&(BfL!=SOCKET_ERROR)); #ifdef GLib_UNIX bool Closed = (BfL == 0); #endif delete[] Bf; if (Closed && !SockEvent.Empty()){ PSIn SIn=Mem.GetSIn(); SockEvent->OnRead(int(GetSockId(SockHnd)), SIn); } } void TSockSys::OnWrite(const TSockHnd& SockHnd, const PSockEvent& SockEvent){ if (!SockEvent.Empty()){ SockEvent->OnWrite(int(GetSockId(SockHnd)));} } void TSockSys::OnOob(const TSockHnd& SockHnd, const PSockEvent& SockEvent){ if (!SockEvent.Empty()){ SockEvent->OnOob(int(GetSockId(SockHnd)));} } void TSockSys::OnAccept(const TSockHnd& SockHnd, const PSockEvent& SockEvent){ PSock AccSock=TSock::Accept(SockHnd, SockEvent); if (AccSock() == NULL) return; // !bn: discard async networks errors; don't die on them. if (!SockEvent.Empty()){ SockEvent->OnAccept(AccSock->GetSockId(), AccSock);} } void TSockSys::OnConnect(const TSockHnd& SockHnd, const PSockEvent& SockEvent){ if (!SockEvent.Empty()){ SockEvent->OnConnect(int(GetSockId(SockHnd)));} } void TSockSys::OnClose(const TSockHnd& SockHnd, const PSockEvent& SockEvent){ if (!SockEvent.Empty()){ SockEvent->OnClose(int(GetSockId(SockHnd)));} } void TSockSys::OnTimeOut(const TSockHnd& SockHnd, const PSockEvent& SockEvent){ if (!SockEvent.Empty()){ SockEvent->OnTimeOut(int(GetSockId(SockHnd)));} } void TSockSys::OnError( const TSockHnd& SockHnd, const PSockEvent& SockEvent, const int& ErrCd){ if (!SockEvent.Empty()){ SockEvent->OnError(int(GetSockId(SockHnd)), ErrCd, GetErrStr(ErrCd));} } void TSockSys::OnGetHost(const PSockHost& SockHost){ if (IsSockEvent(SockHost->GetSockEventId())){ PSockEvent SockEvent=SockHost->GetSockEvent(); if (!SockEvent.Empty()){ SockEvent->OnGetHost(SockHost);} } } TStr TSockSys::GetStatusStr(){ TChA ChA; ChA+="Sockets: "; ChA+=TInt::GetStr(SockIdToHndH.Len()); ChA+="\r\n"; ChA+="Host-Resolutions: "; ChA+=TInt::GetStr(HndToSockHostH.Len()); ChA+="\r\n"; ChA+="Socket-Events: "; ChA+=TInt::GetStr(IdToSockEventH.Len()); ChA+="\r\n"; ChA+="Report-Events: "; ChA+=TInt::GetStr(IdToReportEventH.Len()); ChA+="\r\n"; ChA+="Timers: "; ChA+=TInt::GetStr(IdToTimerH.Len()); ChA+="\r\n"; return ChA; } ///////////////////////////////////////////////// // Socket-Event int TSockEvent::LastSockEventId=0; TSockEvent::~TSockEvent(){ IAssert(!TSockSys::IsSockEventActive(SockEventId)); } bool TSockEvent::IsReg(const PSockEvent& SockEvent){ return TSockSys::IsSockEvent(SockEvent); } void TSockEvent::Reg(const PSockEvent& SockEvent){ IAssert(!TSockSys::IsSockEvent(SockEvent)); TSockSys::AddSockEvent(SockEvent); } void TSockEvent::UnReg(const PSockEvent& SockEvent){ IAssert(TSockSys::IsSockEvent(SockEvent)); TSockSys::DelSockEvent(SockEvent); } ///////////////////////////////////////////////// // Socket-Host int TSockHost::LastSockHostId = 0; #ifdef GLib_WIN32 void TSockHost::GetFromHostEnt( const TSockHostStatus& _Status, const hostent* HostEnt){ if ((Status=_Status)==shsOk){ IAssert(HostEnt!=NULL); IAssert(HostEnt->h_addrtype==AF_INET); IAssert(HostEnt->h_length==4); HostNmV.Add(TStr(HostEnt->h_name).GetLc()); int HostNmN=0; while (HostEnt->h_aliases[HostNmN]!=NULL){ HostNmV.Add(TStr(HostEnt->h_aliases[HostNmN]).GetLc()); HostNmN++;} int IpNumN=0; while (HostEnt->h_addr_list[IpNumN]!=NULL){ TStr IpNum= TInt::GetStr(uchar(HostEnt->h_addr_list[IpNumN][0]))+"."+ TInt::GetStr(uchar(HostEnt->h_addr_list[IpNumN][1]))+"."+ TInt::GetStr(uchar(HostEnt->h_addr_list[IpNumN][2]))+"."+ TInt::GetStr(uchar(HostEnt->h_addr_list[IpNumN][3])); IpNumV.Add(IpNum); IpNumN++; } } } #elif defined(GLib_UNIX) // !!! tole nalozi TSockHost iz addrinfo strukture (hostent na starih unixih in win32) // !!! zato je TSockSys nas frend - da lahko zahteva da se nalozimo iz async odgovora. // addrinfa ni treba posiljat, zato ker ga async dobimo direkt v nas gaicb void TSockHost::GetFromHostEnt( const TSockHostStatus& _Status, gaicb *gcb) { if ((Status=_Status)==shsOk){ // !!! TODO !bn: implement load from addrinfo. if ((Status=_Status)==shsOk) { IAssert(gcb!=NULL); addrinfo *ai = gcb->ar_result; // !!! kaj pa ce host nima imena? v vsakem primeru v name vtaknemo query. drgac bi biu lahko cist prazn. HostNmV.Add(gcb->ar_name); //HostNmV.Add(HNm); free((char *)gcb->ar_name); while (ai) { if (ai->ai_canonname) HostNmV.Add(ai->ai_canonname); if (ai->ai_family == PF_INET) { uchar *ia = (uchar*)&(((struct sockaddr_in*)ai->ai_addr)->sin_addr.s_addr); // !!! tole je pa narobe. sej je v network-order zapisan ip? TStr IpNum= TInt::GetStr(ia[0])+"." + TInt::GetStr(ia[1])+"."+ TInt::GetStr(ia[2])+"." + TInt::GetStr(ia[3]); IpNumV.Add(IpNum); } addrinfo *oai = ai; ai = ai->ai_next; freeaddrinfo(oai); } } } } #endif PSockEvent TSockHost::GetSockEvent() const { return TSockSys::GetSockEvent(SockEventId); } bool TSockHost::IsIpNum(const TStr& HostNm){ int HostNmLen=HostNm.Len(); for (int ChN=0; ChN<HostNmLen; ChN++){ if (TCh::IsAlpha(HostNm[ChN])){return false;}} return true; } TStr TSockHost::GetIpNum(const uint& IpNum){ TChA IpNumChA; IpNumChA+=TUInt::GetStr(IpNum/0x1000000); IpNumChA+='.'; IpNumChA+=TUInt::GetStr((IpNum/0x10000)%0x100); IpNumChA+='.'; IpNumChA+=TUInt::GetStr((IpNum/0x100)%0x100); IpNumChA+='.'; IpNumChA+=TUInt::GetStr(IpNum%0x100); return IpNumChA; } #ifdef GLib_WIN32 PSockHost TSockHost::GetSyncSockHost(const TStr& HostNm){ hostent* HostEnt; TSockHostStatus Status(shsUndef); if ((HostNm.Len()>0)&&(!IsIpNum(HostNm))){ HostEnt=gethostbyname(HostNm.CStr()); if (HostEnt==NULL){Status=GetStatus(WSAGetLastError());} else {Status=shsOk;} } else { uint HostIpNum=inet_addr(HostNm.CStr()); if (HostIpNum==INADDR_NONE){ Status=shsError; HostEnt=NULL; } else { HostEnt=gethostbyaddr((char*)&HostIpNum, 4, AF_INET); if (HostEnt==NULL){Status=GetStatus(WSAGetLastError());} else {Status=shsOk;} } } PSockHost SockHost=PSockHost(new TSockHost()); SockHost->GetFromHostEnt(Status, HostEnt); return SockHost; } void TSockHost::GetAsyncSockHost( const TStr& HostNm, const PSockEvent& SockEvent){ PSockHost SockHost=PSockHost(new TSockHost(SockEvent)); HANDLE SockHostHnd=0; // if ((HostNm.Len()>0)&&(!IsIpNum(HostNm))){ if ((HostNm.Len()>0)){ SockHostHnd=WSAAsyncGetHostByName(TSockSys::GetDnsWndHnd(), TSockSys::GetDnsMsgHnd(), HostNm.CStr(), SockHost->HostEntBf, MAXGETHOSTSTRUCT); } else { uint HostIpNum=inet_addr(HostNm.CStr()); if (HostIpNum==INADDR_NONE){ SockHostHnd=0; } else { SockHostHnd=WSAAsyncGetHostByAddr(TSockSys::GetDnsWndHnd(), TSockSys::GetDnsMsgHnd(), (char*)&HostIpNum, 4, AF_INET, SockHost->HostEntBf, MAXGETHOSTSTRUCT); } } EAssertR(SockHostHnd!=0, TSockSys::GetErrStr(WSAGetLastError())); if (SockHostHnd!=0){ TSockSys::AddSockHost(TUInt64(SockHostHnd), SockHost); } } TSockHostStatus TSockHost::GetStatus(const int& ErrCd){ switch (ErrCd){ case 0: return shsOk; case WSAHOST_NOT_FOUND: return shsHostNotFound; case WSATRY_AGAIN: return shsTryAgain; default: return shsError; } } TSockHost::~TSockHost(){} #elif defined(GLib_UNIX) TSockHostStatus TSockHost::GetStatus(gaicb *gcb){ switch (gai_error(gcb)){ case 0: return shsOk; case EAI_NONAME: return shsHostNotFound; case EAI_AGAIN: return shsTryAgain; case EAI_INPROGRESS: return shsInProgress; default: return shsError; } } TStr TSockHost::GetGaiErrStr(const int ErrCd) { /* switch (ErrCd) { case EAI_AGAIN: return "The name could not be resolved at this time."; case EAI_BADFLAGS: return "The flags had an invalid value."; case EAI_FAIL: return "A non-recoverable error occured."; case EAI_FAMILY: return "The address family was not recognized or the address length was invalid."; case EAI_MEMORY: return "Memory allocation failure."; case EAI_NONAME: return "The name does not resolve for the supplied parameters."; case EAI_SERVICE: return "The service passed was not recognized for the specified socket type."; case EAI_INPROGRESS: return "The asynchronous lookup has not yet finished."; case EAI_INTR: return "The operation was interrupted by a signal."; case EAI_CANCELED: return "The asynchronous request was canceled."; case EAI_NOTCANCELED: return "The asynchronous request was not canceled."; case EAI_ALLDONE: return "Nothing had to be done."; case EAI_SYSTEM: return TSockSys::GetErrStr(errno); default: return "Unknown error."; } */ return gai_strerror(ErrCd); } TSockHostStatus TSockHost::SubmitQuery(const TStr &HostStr, gaicb *gcb, addrinfo *request, bool sync, uint32 EventId) { sigevent ev; if (!sync) { ev.sigev_notify = SIGEV_SIGNAL; ev.sigev_signo = TSockSys::ResolverSignal; ev.sigev_value.sival_int = EventId; ev.sigev_notify_attributes = NULL; } memset(gcb, 0, sizeof(*gcb)); memset(request, 0, sizeof(*request)); gcb->ar_name = strdup(HostStr.CStr()); // !!! TODO: pocistt za tem. oz pocistt sploh za vsemskup. like v GetFromHostEnt je treba tole sprostit in sprostit gcb result. // HNm = HostStr; // !!! TODO !!! MEMORY LEAK !!! // ne res. ar_name je const. submitquery je pa static. torej ne more spreminjat objektov. // !!!!!!!!!!!!!!!!!!!!! nekak freeji result. :) //gcb->ar_name = HostStr.CStr(); if (gcb->ar_name == NULL) return shsError; // v destruktorju pazi .. ce si naredu submit, si mogu tud pobrat rezultate. ce je pa outstanding, mors pa vsaj skenslat in gcb->ar_service = NULL; // deregistrirat, drugac bos v velki p***. vbistvu mors PREJ unregister nardit predn cekiras ce si spucu za sabo, gcb->ar_request = request; // drugac med pucanjem lahk pride rezultat not, pa mas leak. gcb->ar_result = NULL; /*if (IsIpNm(HostStr))*/ request->ai_flags = AI_CANONNAME; request->ai_family = PF_INET; // gcb->ar_request->ai_flags = AI_CANONNAME; // !!! ce se odlocas o completionu na podlagi Status polja, preglej ce pravilno povsod vpises to polje. // gcb->ar_request->ai_family = PF_INET; gcb->ar_request = request; gaicb *gca[1] = { gcb }; int ret = getaddrinfo_a(sync?GAI_WAIT:GAI_NOWAIT, gca, 1, sync?NULL:&ev); if (ret == 0) { return shsOk; } else { return GetStatus(gcb); } } PSockHost TSockHost::GetSyncSockHost(const TStr& HostStr){ gaicb gcb; addrinfo ai; TSockHostStatus Status(shsUndef); Status = SubmitQuery(HostStr, &gcb, &ai); PSockHost SockHost=PSockHost(new TSockHost()); SockHost->GetFromHostEnt(Status, &gcb); return SockHost; } void TSockHost::GetAsyncSockHost( const TStr& HostStr, const PSockEvent& SockEvent){ PSockHost SockHost=PSockHost(new TSockHost(SockEvent)); SockHost->Status = shsInProgress; TSockHostStatus Status = SubmitQuery(HostStr, &(SockHost->GAI), &(SockHost->request), false, SockHost->SockHostId); EAssertR(Status == shsOk, TSockHost::GetGaiErrStr(gai_error(&(SockHost->GAI)))); if (Status == shsOk){ TSockSys::AddSockHost(SockHost->SockHostId, SockHost); } else { SockHost->Status = Status; // need this for the destructor. } } TSockHost::~TSockHost() { if (Status == shsInProgress) { TSockSys::DelSockHost(SockHostId); // we don't want an async result to happen if we don't exist anymore. do we? int ret; do { ret = gai_cancel(&GAI); // !!! problem. tole lahko vrne 'glih dugaja'. ce izmaknemo objekt, bo stala. } while (ret == EAI_NOTCANCELED); // !!! ni lepo da se vrtimo v zanki, ampak objekta NE SMEMO BRISAT. addrinfo *ai = GAI.ar_result; while (ai) { addrinfo *oai = ai; ai = ai->ai_next; freeaddrinfo(oai); } free((char*)GAI.ar_name); // it was allocated once and never cleaned up by AI->SH } // !!! povozil smo const kvalifikator. upam da se svet ne bo podru. :) } #endif PSockHost TSockHost::GetLocalSockHost(){ PSockHost SockHost=TSockHost::GetSyncSockHost(LocalHostNm); if (SockHost->IsOk()){ SockHost=TSockHost::GetSyncSockHost(SockHost->GetHostNm());} return SockHost; } const TStr TSockHost::LocalHostNm("localhost"); ///////////////////////////////////////////////// // Socket int TSock::LastSockId=0; TSock::TSock(const PSockEvent& SockEvent): SockId(++LastSockId), SockHnd(0), SockEventId(SockEvent->GetSockEventId()){ SockHnd=socket(PF_INET, SOCK_STREAM, 0); // !bn: changed. was: AF_INET. it is the same, for now. documentation says PF_INET. #ifdef GLib_WIN32 EAssertR(SockHnd!=INVALID_SOCKET, TSockSys::GetErrStr(WSAGetLastError())); #elif defined(GLib_UNIX) EAssertR(SockHnd!=-1, TSockSys::GetErrStr(TSock::GetSockErr(SockHnd))); #endif TSockSys::AddSock(SockId, SockHnd, SockEventId); IAssert(TSockEvent::IsReg(SockEvent)); } TSock::TSock(const TSockHnd& _SockHnd, const PSockEvent& SockEvent): SockId(++LastSockId), SockHnd(_SockHnd), SockEventId(SockEvent->GetSockEventId()){ TSockSys::AddSock(SockId, SockHnd, SockEventId); IAssert(TSockEvent::IsReg(SockEvent)); } TSock::~TSock(){ IAssert(!TSockSys::IsSockActive(SockHnd)); TSockSys::DelSock(SockId); #ifdef GLib_WIN32 closesocket(SockHnd); #elif defined(GLib_UNIX) close(SockHnd); #endif //EAssertR(closesocket(SockHnd)==0, TSockSys::GetErrStr(WSAGetLastError())); } PSockEvent TSock::GetSockEvent() const { return TSockSys::GetSockEvent(SockEventId); } int TSock::GetSockErr(const TSockHnd s) { int err; socklen_t sz = sizeof(err); getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &sz); return err; } void TSock::Listen(const int& PortN){ sockaddr_in SockAddr; memset(&SockAddr, 0, sizeof(SockAddr)); SockAddr.sin_family=AF_INET; #ifdef GLib_WIN32 SockAddr.sin_addr.s_addr=INADDR_ANY; #elif defined(GLib_UNIX) SockAddr.sin_addr.s_addr=htonl(INADDR_ANY); // !bn: i think this is the 'correct' formulation. INADDR_ANY is 0 anyway, but perhaps might not remain so forever #endif SockAddr.sin_port=htons(u_short(PortN)); #ifdef GLib_WIN32 EAssertR( bind(SockHnd, (sockaddr*)&SockAddr, sizeof(SockAddr))==0, TSockSys::GetErrStr(WSAGetLastError())); EAssertR( WSAAsyncSelect(SockHnd, TSockSys::GetSockWndHnd(), TSockSys::GetSockMsgHnd(), TSockSys::GetAllSockEventCdSet())==0, TSockSys::GetErrStr(WSAGetLastError())); EAssertR( listen(SockHnd, SOMAXCONN)==0, TSockSys::GetErrStr(WSAGetLastError())); #elif defined(GLib_UNIX) // !!! copypaste :/ [almost] // replace WSAGetLastError() with getsockopt() - returns per-socket error // instead per-process/thread error which might be already invalid. EAssertR( bind(SockHnd, (sockaddr*)&SockAddr, sizeof(SockAddr))==0, TSockSys::GetErrStr(GetSockErr(SockHnd))); // !!! why was there a select here? EAssertR( listen(SockHnd, SOMAXCONN)==0, TSockSys::GetErrStr(GetSockErr(SockHnd))); TSockSys::SockHndToStateH[SockHnd] = scsListening; #endif } int TSock::GetPortAndListen(const int& MnPortN){ int PortN=MnPortN-1; int ErrCd=0; forever { PortN++; sockaddr_in SockAddr; memset(&SockAddr, 0, sizeof(SockAddr)); SockAddr.sin_family=AF_INET; #ifdef GLib_WIN32 SockAddr.sin_addr.s_addr=INADDR_ANY; #elif defined(GLib_UNIX) SockAddr.sin_addr.s_addr=htonl(INADDR_ANY); #endif SockAddr.sin_port=htons(u_short(PortN)); int OkCd=bind(SockHnd, (sockaddr*)&SockAddr, sizeof(SockAddr)); #ifdef GLib_WIN32 if (OkCd==SOCKET_ERROR){ ErrCd=WSAGetLastError(); if (ErrCd!=WSAEADDRINUSE){break;} } else { ErrCd=0; break; } #elif defined(GLib_UNIX) if (OkCd==-1){ ErrCd=GetSockErr(SockHnd); if (ErrCd!=EACCES){break;} // !!! !bn: a res bind vrne EACCESS ce ne more bindat? } else { ErrCd=0; break; } #endif } EAssertR(ErrCd==0, TSockSys::GetErrStr(ErrCd)); #ifdef GLib_WIN32 EAssertR( WSAAsyncSelect(SockHnd, TSockSys::GetSockWndHnd(), TSockSys::GetSockMsgHnd(), TSockSys::GetAllSockEventCdSet())==0, TSockSys::GetErrStr(WSAGetLastError())); EAssertR( listen(SockHnd, SOMAXCONN)==0, TSockSys::GetErrStr(WSAGetLastError())); #elif defined(GLib_UNIX) // !!! copypaste because of wsagetlasterror. EAssertR( listen(SockHnd, SOMAXCONN)==0, TSockSys::GetErrStr(GetSockErr(SockHnd))); #endif return PortN; } void TSock::Connect(const PSockHost& SockHost, const int& PortN){ IAssert(SockHost->IsOk()); #ifdef GLib_WIN32 uint HostIpNum=inet_addr(SockHost->GetIpNum().CStr()); IAssert(HostIpNum!=INADDR_NONE); #elif defined(GLib_UNIX) uint HostIpNum; IAssert(inet_aton(SockHost->GetIpNum().CStr(), (in_addr*)&HostIpNum) == 0); // !!! prov typecast? #endif sockaddr_in SockAddr; memset(&SockAddr, 0, sizeof(SockAddr)); memcpy(&(SockAddr.sin_addr), &HostIpNum, sizeof(HostIpNum)); SockAddr.sin_family=AF_INET; SockAddr.sin_port=htons(u_short(PortN)); #ifdef GLib_WIN32 EAssertR( WSAAsyncSelect(SockHnd, TSockSys::GetSockWndHnd(), TSockSys::GetSockMsgHnd(), TSockSys::GetAllSockEventCdSet())==0, TSockSys::GetErrStr(WSAGetLastError())); #endif int ErrCd=connect(SockHnd, (sockaddr*)&SockAddr, sizeof(SockAddr)); EAssertR( #ifdef GLib_WIN32 (ErrCd==SOCKET_ERROR)&&(WSAGetLastError()==WSAEWOULDBLOCK), #elif defined(GLib_UNIX) // !!! !bn: tole je pa resno: na errno se ne gre zanasat ker ni mt-safe, ampak v errno-ju se najde EINPROGRESS. socket je pa lahko ze sconnectan do takrat. // a je tale pogoj - EINPROGRESS || 0 uredu? ((ErrCd==-1)&&(GetSockErr(SockHnd)==EINPROGRESS))||(GetSockErr(SockHnd) == 0), #endif "Unsuccessful socket-connect."); } void TSock::Send(const PSIn& SIn, bool& Ok, int& ErrCd){ if (!SIn.Empty()){UnsentBf+=SIn;} Ok=true; ErrCd=0; int SentChs=0; while (SentChs<UnsentBf.Len()){ int SendBfL=UnsentBf.Len()-SentChs; if (SendBfL>TSockSys::MxSockBfL){SendBfL=TSockSys::MxSockBfL;} int LSentChs=send(SockHnd, &UnsentBf[SentChs], SendBfL, 0); #ifdef GLib_WIN32 if (LSentChs==SOCKET_ERROR){ ErrCd=WSAGetLastError(); Ok=(ErrCd==WSAEWOULDBLOCK); #elif defined(GLib_UNIX) if (LSentChs==-1){ ErrCd=GetSockErr(SockHnd); Ok=(ErrCd==EWOULDBLOCK); #endif break; } else { SentChs+=LSentChs; TSockSys::SockBytesWritten+=LSentChs; } } UnsentBf.Del(0, SentChs-1); } void TSock::Send(const PSIn& SIn){ bool Ok; int ErrCd; Send(SIn, Ok, ErrCd); #ifdef GLib_WIN32 if (!Ok){ ESAssert(PostMessage( TSockSys::GetSockWndHnd(), TSockSys::SockErrMsgHnd, SockHnd, ErrCd)); } #elif defined(GLib_UNIX) if (!Ok){ // !!! !bn: why does win32 code post the error message instead of calling errorhandler? // i don't want to do it by writing (sockhnd, errcd) in a pipe, because of a possible race condition (sockhnd is not unique) GetSockEvent()->OnError(SockId, ErrCd, TSockSys::GetErrStr(ErrCd)); } #endif } void TSock::SendSafe(const PSIn& SIn){ bool Ok; int ErrCd; Send(SIn, Ok, ErrCd); } TStr TSock::GetPeerIpNum() const { sockaddr_in SockAddr; memset(&SockAddr, 0, sizeof(SockAddr)); #ifdef GLib_WIN32 int NmLen=sizeof(sockaddr_in); #elif defined(GLib_UNIX) socklen_t NmLen=sizeof(sockaddr_in); #endif EAssertR( getpeername(SockHnd, (sockaddr*)&SockAddr, &NmLen)==0, #ifdef GLib_WIN32 TSockSys::GetErrStr(WSAGetLastError())); TStr IpNum= TInt::GetStr(SockAddr.sin_addr.s_net)+"."+ TInt::GetStr(SockAddr.sin_addr.s_host)+"."+ TInt::GetStr(SockAddr.sin_addr.s_lh)+"."+ TInt::GetStr(SockAddr.sin_addr.s_impno); #elif defined(GLib_UNIX) TSockSys::GetErrStr(GetSockErr(SockHnd))); uchar *s_addr = (uchar*)&SockAddr.sin_addr.s_addr; TStr IpNum= TInt::GetStr(s_addr[4])+"."+ // !!! like .. check. a ma kakrsnkol smisu tole. TInt::GetStr(s_addr[3])+"."+ TInt::GetStr(s_addr[2])+"."+ TInt::GetStr(s_addr[1]); #endif return IpNum; } TStr TSock::GetLocalIpNum() const { sockaddr_in SockAddr; memset(&SockAddr, 0, sizeof(SockAddr)); #ifdef GLib_WIN32 int NmLen=sizeof(sockaddr_in); #elif defined(GLib_UNIX) socklen_t NmLen=sizeof(sockaddr_in); #endif EAssertR( getsockname(SockHnd, (sockaddr*)&SockAddr, &NmLen)==0, #ifdef GLib_WIN32 TSockSys::GetErrStr(WSAGetLastError())); TStr IpNum= TInt::GetStr(SockAddr.sin_addr.s_net)+"."+ TInt::GetStr(SockAddr.sin_addr.s_host)+"."+ TInt::GetStr(SockAddr.sin_addr.s_lh)+"."+ TInt::GetStr(SockAddr.sin_addr.s_impno); #elif defined(GLib_UNIX) TSockSys::GetErrStr(GetSockErr(SockHnd))); uchar *s_addr = (uchar*)&SockAddr.sin_addr.s_addr; TStr IpNum= TInt::GetStr(s_addr[4])+"."+ // !!! like .. check. a ma kakrsnkol smisu tole. TInt::GetStr(s_addr[3])+"."+ TInt::GetStr(s_addr[2])+"."+ TInt::GetStr(s_addr[1]); #endif return IpNum; } void TSock::PutTimeOut(const int& MSecs){ TSockSys::AddSockTimer(SockId, MSecs); } void TSock::DelTimeOut(){ TSockSys::DelIfSockTimer(SockId); } PSock TSock::Accept(const TSockHnd& SockHnd, const PSockEvent& SockEvent){ sockaddr_in SockAddr; #ifdef GLib_WIN32 int SockAddrLen=sizeof(SockAddr); #elif defined(GLib_UNIX) socklen_t SockAddrLen=sizeof(SockAddr); #endif memset(&SockAddr, 0, sizeof(SockAddr)); TSockHnd AccSockHnd=accept(SockHnd, (sockaddr*)&SockAddr, &SockAddrLen); #ifdef GLib_WIN32 EAssertR( AccSockHnd!=INVALID_SOCKET, TSockSys::GetErrStr(WSAGetLastError())); PSock AccSock=PSock(new TSock(AccSockHnd, SockEvent)); EAssertR( WSAAsyncSelect(AccSock->GetSockHnd(), TSockSys::GetSockWndHnd(), TSockSys::GetSockMsgHnd(), TSockSys::GetAllSockEventCdSet())==0, TSockSys::GetErrStr(WSAGetLastError())); return AccSock; #elif defined(GLib_UNIX) if (AccSockHnd == -1) { // !!! !bn: a bi rajs GetSockErr()? if ((errno == EWOULDBLOCK) || (errno == ECONNABORTED) || (errno == EINTR)) return NULL; // !!! ECONNABORTED -> just return NULL. EAssertR( // !!! !bn: overkill. ret==-1 se lahko velikrat zgodi, mogl bi sam preprost ignorirat take evente pa vrnt null. AccSockHnd!=-1, TSockSys::GetErrStr(GetSockErr(SockHnd))); return NULL; } else { PSock AccSock=PSock(new TSock(AccSockHnd, SockEvent)); TSockSys::SockHndToStateH[AccSock->SockHnd] = scsConnected; return AccSock; } #endif } TStr TSock::GetSockSysStatusStr(){ return TSockSys::GetStatusStr(); } uint64 TSock::GetSockSysBytesRead(){ return TSockSys::SockBytesRead; } uint64 TSock::GetSockSysBytesWritten(){ return TSockSys::SockBytesWritten; } bool TSock::IsSockId(const int& SockId){ return TSockSys::IsSockId(SockId); } ///////////////////////////////////////////////// // Report-Event int TReportEvent::LastReportEventId=0; void TReportEvent::SendReport(){ #ifdef GLib_WIN32 TSockSys::AddReportEvent(this); ESAssert(PostMessage( TSockSys::GetReportWndHnd(), TSockSys::GetReportMsgHnd(), 0, ReportEventId)); #elif defined(GLib_UNIX) Fail; // !!! not implemented. [obsolete?] #endif } ///////////////////////////////////////////////// // Timer int TTTimer::LastTimerId=0; TTTimer::TTTimer(const int& _TimeOut): TimerId(++LastTimerId), #ifdef GLib_WIN32 TimerHnd(0), #endif TimeOut(_TimeOut), Ticks(0), StartTm(TSecTm::GetCurTm()) { #ifdef GLib_UNIX sigevent evp; evp.sigev_notify = SIGEV_SIGNAL; evp.sigev_signo = TSockSys::TimerSignal; evp.sigev_value.sival_int = TimerId; evp.sigev_notify_attributes = NULL; IAssert(timer_create(CLOCK_MONOTONIC, &evp, &TimerHnd) == 0); #endif IAssert(TimeOut>=0); StartTimer(TimeOut); } TTTimer::~TTTimer(){ StopTimer(); #ifdef GLib_UNIX timer_delete(TimerHnd); #endif } void TTTimer::StartTimer(const int& _TimeOut){ IAssert((_TimeOut==-1)||(_TimeOut>=0)); // if _TimeOut==-1 use previous TimeOut if (_TimeOut!=-1){ TimeOut=_TimeOut;} // stop current-timer StopTimer(); if (TimeOut>0){ #ifdef GLib_WIN32 TimerHnd=uint(SetTimer( TSockSys::GetTimerWndHnd(), UINT(TimerId), UINT(TimeOut), NULL)); ESAssert(TimerHnd!=0); #elif defined(GLib_UNIX) itimerspec its; its.it_value.tv_sec = its.it_interval.tv_sec = TimeOut / 1000; its.it_value.tv_nsec = its.it_interval.tv_nsec = (TimeOut % 1000) * 1000000; EAssertR(timer_settime(TimerHnd, 0, &its, NULL) == 0, TSockSys::GetErrStr(errno)); // !!! TODO: check: ce je sigpending, pa ze pobrisemo timer pripadajoc. a prevermo ce smemo brskat? #endif TSockSys::AddTimer(this); } } void TTTimer::StopTimer(){ if (TimerHnd!=0){ #ifdef GLib_WIN32 ESAssert(KillTimer(TSockSys::GetTimerWndHnd(), TimerId)); #elif defined(GLib_UNIX) itimerspec its; its.it_value.tv_sec = its.it_interval.tv_sec = 0; its.it_value.tv_nsec = its.it_interval.tv_nsec = 0; EAssertR(timer_settime(TimerHnd, 0, &its, NULL) == 0, TSockSys::GetErrStr(errno)); #endif TSockSys::DelTimer(TimerId); TimerHnd=0; } } #ifdef GLib_UNIX void TSocketTimer::OnTimeOut() { TSockHnd SockHnd=TSockSys::GetSockHnd(SockId); int SockEventId=TSockSys::GetSockEventId(SockHnd); PSockEvent SockEvent=TSockSys::GetSockEvent(SockEventId); TSockSys::SetSockEventActive(SockEventId, true); try { if (!SockEvent.Empty()) SockEvent->OnTimeOut(int(SockId)); } catch (...){ SaveToErrLog("Exception from OnTimeOut(SockHnd, SockEvent);"); } TSockSys::SetSockEventActive(SockEventId, false); TSockSys::DelIfSockTimer(SockId); } #endif
33.784695
188
0.690034
f4ffcc19fc0c4406900eb88970acc8eef163ae68
511
cpp
C++
drape/oglcontextfactory.cpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
1
2019-01-11T05:02:05.000Z
2019-01-11T05:02:05.000Z
drape/oglcontextfactory.cpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
null
null
null
drape/oglcontextfactory.cpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
1
2019-08-09T21:21:09.000Z
2019-08-09T21:21:09.000Z
#include "drape/oglcontextfactory.hpp" namespace dp { ThreadSafeFactory::ThreadSafeFactory(OGLContextFactory * factory) : m_factory(factory) { } ThreadSafeFactory::~ThreadSafeFactory() { delete m_factory; } OGLContext *ThreadSafeFactory::getDrawContext() { threads::MutexGuard lock(m_mutex); return m_factory->getDrawContext(); } OGLContext *ThreadSafeFactory::getResourcesUploadContext() { threads::MutexGuard lock(m_mutex); return m_factory->getResourcesUploadContext(); } } // namespace dp
17.62069
65
0.772994
f4ffdbc72af1209c3c20227409afe3684aac4f62
576
cpp
C++
libvermilion/core/src/stb_image.cpp
Jojojoppe/vermilion
2bfe545c5f2c02e11d96940c191bac6f6c491843
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
libvermilion/core/src/stb_image.cpp
Jojojoppe/vermilion
2bfe545c5f2c02e11d96940c191bac6f6c491843
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
libvermilion/core/src/stb_image.cpp
Jojojoppe/vermilion
2bfe545c5f2c02e11d96940c191bac6f6c491843
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
#define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include "Texture.hpp" #include <string> unsigned char * Vermilion::Core::loadTextureData(const std::string& path, size_t * width, size_t * height, size_t * channels){ *width = 0; *height = 0; *channels = 4; Vermilion::Core::flipLoading(); return stbi_load(path.c_str(), (int*)width, (int*)height, nullptr, STBI_rgb_alpha); } void Vermilion::Core::freeTextureData(unsigned char * data){ stbi_image_free(data); } void Vermilion::Core::flipLoading(){ stbi_set_flip_vertically_on_load(true); }
28.8
126
0.713542
760079c76903f55110459bca977957ed078cc68c
4,093
cpp
C++
vendor/tree/tree.cpp
MufidJamaluddin/gedungh
6229fda7bf35d8b33af9308e2a404378a7411399
[ "BSD-3-Clause" ]
1
2019-03-13T15:30:28.000Z
2019-03-13T15:30:28.000Z
vendor/tree/tree.cpp
MufidJamaluddin/gedungh
6229fda7bf35d8b33af9308e2a404378a7411399
[ "BSD-3-Clause" ]
null
null
null
vendor/tree/tree.cpp
MufidJamaluddin/gedungh
6229fda7bf35d8b33af9308e2a404378a7411399
[ "BSD-3-Clause" ]
null
null
null
/* ADT AVL Tree www.geeksforgeeks.org */ #include<stdio.h> #include<stdlib.h> // An AVL tree node struct Node { int key; struct Node *left; struct Node *right; int height; int texture; }; // A utility function to get maximum of two integers int max(int a, int b); // A utility function to get the height of the tree int height(struct Node *N) { if (N == NULL) return 0; return N->height; } // A utility function to get maximum of two integers int max(int a, int b) { return (a > b)? a : b; } /* Helper function that allocates a new node with the given key and NULL left and right pointers. */ struct Node* newNode(int key, int texture) { struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially added at leaf node->texture = texture; return(node); } // A utility function to right rotate subtree rooted with y // See the diagram given above. struct Node *rightRotate(struct Node *y) { struct Node *x = y->left; struct Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right))+1; x->height = max(height(x->left), height(x->right))+1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. struct Node *leftRotate(struct Node *x) { struct Node *y = x->right; struct Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right))+1; y->height = max(height(y->left), height(y->right))+1; // Return new root return y; } // Get Balance factor of node N int getBalance(struct Node *N) { if (N == NULL) return 0; return height(N->left) - height(N->right); } // Recursive function to insert a key in the subtree rooted // with node and returns the new root of the subtree. struct Node* insert(struct Node* node, int key, int texture) { /* 1. Perform the normal BST insertion */ if (node == NULL) return(newNode(key, texture)); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); else return node; /* 2. Update height of this ancestor node */ node->height = 1 + max(height(node->left), height(node->right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /** * Mencari TextureID * Jika key Node lebih kecil dari key, check kiri * Jika key Node lebih besar dari key, check kanan * * @author Mufid Jamaluddin **/ int getTexture(Node * root, int key) { if(root != NULL) { if(root->key == key) return root->texture; else if (key < node->key) getTexture(root->left); else if (key > node->key) getTexture(root->right); } return 0; } /** * Menghapus Tree dari Memori * * @author Mufid Jamaluddin **/ void freeNode(Node * root) { if(root == NULL) return; freeNode(root->left); freeNode(root->right); free(root); }
23.796512
73
0.592964
76028276bf7c9e6e899d16d6e47452956936c4f6
11,255
cpp
C++
src/Engine/Audio/CPianoKeyboard.cpp
slajerek/MTEngineSDL
19b5295d875c197ec03bc20ddacd48c228920365
[ "MIT" ]
4
2021-12-16T11:22:30.000Z
2022-01-05T11:20:32.000Z
src/Engine/Audio/CPianoKeyboard.cpp
slajerek/MTEngineSDL
19b5295d875c197ec03bc20ddacd48c228920365
[ "MIT" ]
1
2022-01-07T10:41:38.000Z
2022-01-09T12:04:03.000Z
src/Engine/Audio/CPianoKeyboard.cpp
slajerek/MTEngineSDL
19b5295d875c197ec03bc20ddacd48c228920365
[ "MIT" ]
null
null
null
/* * CPianoKeyboard (CPianoKeyboard.cpp) * MobiTracker * * Created by Marcin Skoczylas on 09-11-26. * Copyright 2009 Marcin Skoczylas. All rights reserved. * */ #include "CPianoKeyboard.h" #include "VID_Main.h" #include "CGuiMain.h" #include "CLayoutParameter.h" #define OCT_NAME_FONT_SIZE_X 8.0 #define OCT_NAME_FONT_SIZE_Y 8.0 #define OCT_NAME_GAP_X 2.0 #define OCT_NAME_GAP_Y 1.0 const char *pianoKeyboardKeyNames = "CDEFGAB"; void CPianoKeyboardCallback::PianoKeyboardNotePressed(CPianoKeyboard *pianoKeyboard, u8 note) { } void CPianoKeyboardCallback::PianoKeyboardNoteReleased(CPianoKeyboard *pianoKeyboard, u8 note) { } CPianoKeyboard::CPianoKeyboard(const char *name, float posX, float posY, float posZ, float sizeX, float sizeY, CPianoKeyboardCallback *callback) :CGuiView(name, posX, posY, posZ, sizeX, sizeY) { keyWhiteWidth = 1.0/7.0; keyBlackOffset = keyWhiteWidth * (3.0f/4.0f); keyBlackWidth = keyWhiteWidth * (2.0f/4.0f); keyBlackHeight = (3.0f/5.0f); this->numOctaves = 8; this->octaveNames = new const char *[this->numOctaves]; octaveNames[0] = "0"; octaveNames[1] = "I"; octaveNames[2] = "II"; octaveNames[3] = "III"; octaveNames[4] = "IV"; octaveNames[5] = "V"; octaveNames[6] = "VI"; octaveNames[7] = "VII"; // octaveNames[8] = "VIII"; // octaveNames[9] = "IX"; SetKeysFadeOut(true); SetKeysFadeOutSpeed(0.40f); currentOctave = 4; AddDefaultKeyCodes(); this->callback = callback; this->InitKeys(); AddLayoutParameter(new CLayoutParameterBool("Keys fade out", &doKeysFadeOut)); AddLayoutParameter(new CLayoutParameterFloat("Keys fade out speed", &keysFadeOutSpeedParameter)); } void CPianoKeyboard::SetKeysFadeOut(bool doKeysFadeOut) { this->doKeysFadeOut = doKeysFadeOut; } void CPianoKeyboard::SetKeysFadeOutSpeed(float speed) { this->keysFadeOutSpeed = speed; this->keysFadeOutSpeedOneMinus = 1.0f - this->keysFadeOutSpeed; this->keysFadeOutSpeedParameter = speed * 10.0f; } void CPianoKeyboard::LayoutParameterChanged(CLayoutParameter *layoutParameter) { this->keysFadeOutSpeed = keysFadeOutSpeedParameter / 10.0f; this->keysFadeOutSpeedOneMinus = 1.0f - this->keysFadeOutSpeed; } CPianoKey::CPianoKey(u8 keyNote, u8 keyOctave, const char *keyName, double x, double y, double sizeX, double sizeY, bool isBlackKey) { this->keyNote = keyNote; this->keyOctave = keyOctave, this->x = x; this->y = y; this->sizeX = sizeX; this->sizeY = sizeY; this->isBlackKey = isBlackKey; strcpy(this->keyName, keyName); if (!isBlackKey) { r = g = b = a = 1.0f; cr = cg = cb = ca = 1.0f; } else { r = g = b = 0; a = 1.0f; cr = cg = cb = 0; ca = 1.0f; } // LOGD("CPianoKey: %d %s: %6.3f %6.3f %6.3f %6.3f", keyNote, keyName, x, y, sizeX, sizeY); } void CPianoKeyboard::InitKeys() { char *keyName = SYS_GetCharBuf(); double fOctaveStep = 1 / (double)numOctaves; keyWhiteWidth = fOctaveStep * 1.0/7.0; keyBlackOffset = keyWhiteWidth * (3.0f/4.0f); keyBlackWidth = keyWhiteWidth * (2.0f/4.0f); keyBlackHeight = (3.0f/5.0f); CPianoKey *key = NULL; int keyNum = 0; for (int octaveNum = 0; octaveNum < numOctaves; octaveNum++) { double octaveOffset = fOctaveStep * (double)octaveNum; for (int keyNumInOctave = 0; keyNumInOctave < 7; keyNumInOctave++) { sprintf(keyName, "%c-%d", pianoKeyboardKeyNames[keyNumInOctave], octaveNum); key = new CPianoKey(keyNum, octaveNum, keyName, keyWhiteWidth * (double)keyNumInOctave + octaveOffset, 0.0f, keyWhiteWidth, 1.0f, false); keyNum++; pianoKeys.push_back(key); pianoWhiteKeys.push_back(key); if (keyNumInOctave == 0 || keyNumInOctave == 1 || keyNumInOctave == 3 || keyNumInOctave == 4 || keyNumInOctave == 5) { sprintf(keyName, "%c#%d", pianoKeyboardKeyNames[keyNumInOctave], octaveNum); key = new CPianoKey(keyNum, octaveNum, keyName, keyBlackOffset + keyWhiteWidth * (double)keyNumInOctave + octaveOffset, 0.0f, keyBlackWidth, keyBlackHeight, true); keyNum++; pianoKeys.push_back(key); pianoBlackKeys.push_back(key); } } } SYS_ReleaseCharBuf(keyName); LOGD("InitKeys done"); } void CPianoKeyboard::Render() { // LOGD("CPianoKeyboard::Render"); for (std::vector<CPianoKey *>::iterator it = pianoWhiteKeys.begin(); it != pianoWhiteKeys.end(); it++) { CPianoKey *key = *it; BlitFilledRectangle(this->posX + key->x * this->sizeX, this->posY + key->y * this->sizeY, -1, key->sizeX * this->sizeX, key->sizeY * this->sizeY, key->cr, key->cg, key->cb, key->ca); // border BlitRectangle(this->posX + key->x * this->sizeX, this->posY + key->y * this->sizeY, -1, key->sizeX * this->sizeX, key->sizeY * this->sizeY, 0, 0, 0, 1); } for (std::vector<CPianoKey *>::iterator it = pianoBlackKeys.begin(); it != pianoBlackKeys.end(); it++) { CPianoKey *key = *it; BlitFilledRectangle(this->posX + key->x * this->sizeX, this->posY + key->y * this->sizeY, -1, key->sizeX * this->sizeX, key->sizeY * this->sizeY, key->cr, key->cg, key->cb, key->ca); BlitRectangle(this->posX + key->x * this->sizeX, this->posY + key->y * this->sizeY, -1, key->sizeX * this->sizeX, key->sizeY * this->sizeY, 0, 0, 0, 1); } } void CPianoKeyboard::DoLogic() { // LOGD("CPianoKeyboard::DoLogic"); if (doKeysFadeOut) { for (std::vector<CPianoKey *>::iterator it = pianoKeys.begin(); it != pianoKeys.end(); it++) { CPianoKey *key = *it; key->cr = key->cr * keysFadeOutSpeedOneMinus + key->r * keysFadeOutSpeed; key->cg = key->cg * keysFadeOutSpeedOneMinus + key->g * keysFadeOutSpeed; key->cb = key->cb * keysFadeOutSpeedOneMinus + key->b * keysFadeOutSpeed; key->ca = key->ca * keysFadeOutSpeedOneMinus + key->a * keysFadeOutSpeed; } } } bool CPianoKeyboard::DoTap(float x, float y) { LOGG("CPianoKeyboard::DoTap: x=%f y=%f posX=%f posY=%f sizeX=%f sizeY=%f", x, y, posX, posY, sizeX, sizeY); // this->pressedNote = GetPressedNote(x, y); // // if (pressedNote != NOTE_NONE) // { // if (callback != NULL) // callback->PianoKeyboardNotePressed(pressedNote + editNoteOctave*12); //this->selectedInstrument, // } // LOGG("pressed note=%d", pressedNote); // if (pressedNote != NOTE_NONE) // return true; return false; } u8 CPianoKeyboard::GetPressedNote(float x, float y) { return -1; } bool CPianoKeyboard::DoDoubleTap(float x, float y) { return this->DoTap(x, y); } bool CPianoKeyboard::DoFinishTap(float x, float y) { if (IsInsideNonVisible(x, y)) return true; return false; } bool CPianoKeyboard::DoFinishDoubleTap(float x, float y) { return this->DoFinishTap(x, y); } bool CPianoKeyboard::DoMove(float x, float y, float distX, float distY, float diffX, float diffY) { LOGG("CPianoKeyboard::DoMove"); // if (x < SCREEN_WIDTH-menuButtonSizeX) // { // u8 bPressedNote = this->GetPressedNote(x, y); // LOGG("bPressedNote=%d", bPressedNote); // // if (bPressedNote != this->pressedNote) // { // this->pressedNote = bPressedNote; // // if (bPressedNote != NOTE_NONE) // { // if (callback != NULL) // callback->PianoKeyboardNotePressed(bPressedNote + editNoteOctave*12); //this->selectedInstrument, // } // LOGG("pressed note=%d", pressedNote); // } // // if (pressedNote != NOTE_NONE) // { // return true; // } // } return false; //this->DoTap(x, y); } bool CPianoKeyboard::FinishMove(float x, float y, float distX, float distY, float accelerationX, float accelerationY) { // if (x < SCREEN_WIDTH-menuButtonSizeX) // return this->DoFinishTap(x, y); return false; } bool CPianoKeyboard::KeyDown(u32 keyCode, bool isShift, bool isAlt, bool isControl, bool isSuper) { LOGD("CPianoKeyboard::KeyDown: keyCode=%x", keyCode); // TODO: make via callback if (keyCode == '[') { if (currentOctave > 0) currentOctave--; return true; } else if (keyCode == ']') { if (currentOctave < numOctaves-2) currentOctave++; return true; } else if (this->callback != NULL) { // scan for note key code for (std::list<CPianoNoteKeyCode *>::iterator it = notesKeyCodes.begin(); it != notesKeyCodes.end(); it++) { CPianoNoteKeyCode *noteKeyCode = *it; if (keyCode == noteKeyCode->keyCode) { this->callback->PianoKeyboardNotePressed(this, noteKeyCode->keyNote + currentOctave*12); return true; } } } return false; } bool CPianoKeyboard::KeyUp(u32 keyCode, bool isShift, bool isAlt, bool isControl, bool isSuper) { LOGD("CPianoKeyboard::KeyUp: keyCode=%x", keyCode); if (this->callback != NULL) { // scan for note key code for (std::list<CPianoNoteKeyCode *>::iterator it = notesKeyCodes.begin(); it != notesKeyCodes.end(); it++) { CPianoNoteKeyCode *noteKeyCode = *it; if (keyCode == noteKeyCode->keyCode) { this->callback->PianoKeyboardNoteReleased(this, noteKeyCode->keyNote + currentOctave*12); return true; } } } return false; } void CPianoKeyboard::AddDefaultKeyCodes() { // 0 = C-0 notesKeyCodes.push_back(new CPianoNoteKeyCode('z', 0)); // C-0 notesKeyCodes.push_back(new CPianoNoteKeyCode('s', 1)); notesKeyCodes.push_back(new CPianoNoteKeyCode('x', 2)); notesKeyCodes.push_back(new CPianoNoteKeyCode('d', 3)); notesKeyCodes.push_back(new CPianoNoteKeyCode('c', 4)); notesKeyCodes.push_back(new CPianoNoteKeyCode('v', 5)); notesKeyCodes.push_back(new CPianoNoteKeyCode('g', 6)); notesKeyCodes.push_back(new CPianoNoteKeyCode('b', 7)); notesKeyCodes.push_back(new CPianoNoteKeyCode('h', 8)); notesKeyCodes.push_back(new CPianoNoteKeyCode('n', 9)); notesKeyCodes.push_back(new CPianoNoteKeyCode('j', 10)); notesKeyCodes.push_back(new CPianoNoteKeyCode('m', 11)); notesKeyCodes.push_back(new CPianoNoteKeyCode(',', 12)); // C-1 notesKeyCodes.push_back(new CPianoNoteKeyCode('l', 13)); notesKeyCodes.push_back(new CPianoNoteKeyCode('.', 14)); notesKeyCodes.push_back(new CPianoNoteKeyCode(';', 15)); notesKeyCodes.push_back(new CPianoNoteKeyCode('/', 16)); notesKeyCodes.push_back(new CPianoNoteKeyCode('q', 12)); // C-1 notesKeyCodes.push_back(new CPianoNoteKeyCode('2', 13)); notesKeyCodes.push_back(new CPianoNoteKeyCode('w', 14)); notesKeyCodes.push_back(new CPianoNoteKeyCode('3', 15)); notesKeyCodes.push_back(new CPianoNoteKeyCode('e', 16)); notesKeyCodes.push_back(new CPianoNoteKeyCode('r', 17)); notesKeyCodes.push_back(new CPianoNoteKeyCode('5', 18)); notesKeyCodes.push_back(new CPianoNoteKeyCode('t', 19)); notesKeyCodes.push_back(new CPianoNoteKeyCode('6', 20)); notesKeyCodes.push_back(new CPianoNoteKeyCode('y', 21)); notesKeyCodes.push_back(new CPianoNoteKeyCode('7', 22)); notesKeyCodes.push_back(new CPianoNoteKeyCode('u', 23)); notesKeyCodes.push_back(new CPianoNoteKeyCode('i', 24)); notesKeyCodes.push_back(new CPianoNoteKeyCode('9', 25)); notesKeyCodes.push_back(new CPianoNoteKeyCode('o', 26)); notesKeyCodes.push_back(new CPianoNoteKeyCode('0', 27)); notesKeyCodes.push_back(new CPianoNoteKeyCode('p', 28)); } CPianoKeyboard::~CPianoKeyboard() { while(!pianoKeys.empty()) { CPianoKey *key = pianoKeys.back(); pianoKeys.pop_back(); delete key; } while(!notesKeyCodes.empty()) { CPianoNoteKeyCode *keyCode = notesKeyCodes.back(); notesKeyCodes.pop_back(); delete keyCode; } }
28.278894
153
0.687517
760412626f88fb941d8e6b4255045abda9a3697f
1,340
hpp
C++
src/entity/sprite/Sprite.hpp
JulienTD/pacman
71e92b367b4c57bba065c18faa67570842bdd67f
[ "MIT" ]
null
null
null
src/entity/sprite/Sprite.hpp
JulienTD/pacman
71e92b367b4c57bba065c18faa67570842bdd67f
[ "MIT" ]
null
null
null
src/entity/sprite/Sprite.hpp
JulienTD/pacman
71e92b367b4c57bba065c18faa67570842bdd67f
[ "MIT" ]
null
null
null
#ifndef SPRITE_HPP_ #define SPRITE_HPP_ #include <string> #include <SDL2/SDL.h> #include <SDL2/SDL_pixels.h> #include <SDL2/SDL_image.h> #include "window/Window.hpp" #include "entity/Entity.hpp" class Sprite : public Entity { public: Sprite(std::string id, std::string spritePath, Window *window, int x, int y, int width, int height); ~Sprite(); void setMaxStateNbr(int stateNbr); void setXStateGap(int xGap); void setYStateGap(int yGap); void setSpriteX(int spriteX); void setSpriteY(int spriteY); void setSpriteHeight(int spriteHeight); void setSpriteWidth(int spriteWidth); void setXAnimation(bool xAnimation); void setYAnimation(bool yAnimation); void setTickRate(int tickRate); void setTickStep(int tickStep); void render(Window *window); protected: private: SDL_Surface *_image; SDL_Texture *_texture; int _width; int _height; int _stateNbr; int _maxStateNbr; int _xStateGap; int _yStateGap; int _spriteX; int _spriteY; int _spriteWidth; int _spriteHeight; bool _xAnimation; bool _yAnimation; int _currentTick; int _tickRate; int _tickStep; }; #endif /* !SPRITE_HPP_ */
26.8
108
0.629851
76053454382ed3308b268d1d7609151207f9f737
7,804
cpp
C++
arangod/IResearch/IResearchRocksDBRecoveryHelper.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
arangod/IResearch/IResearchRocksDBRecoveryHelper.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
arangod/IResearch/IResearchRocksDBRecoveryHelper.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Daniel Larkin-York //////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include <rocksdb/db.h> #include <velocypack/Builder.h> #include <velocypack/Slice.h> #include "IResearch/IResearchRocksDBRecoveryHelper.h" #include "ApplicationFeatures/ApplicationServer.h" #include "Basics/Exceptions.h" #include "Basics/Result.h" #include "Basics/StaticStrings.h" #include "Basics/debugging.h" #include "Basics/error.h" #include "Basics/voc-errors.h" #include "IResearch/IResearchCommon.h" #include "IResearch/IResearchLink.h" #include "IResearch/IResearchLinkHelper.h" #include "IResearch/IResearchRocksDBLink.h" #include "Indexes/Index.h" #include "Logger/LogMacros.h" #include "Logger/Logger.h" #include "Logger/LoggerStream.h" #include "RestServer/DatabaseFeature.h" #include "RocksDBEngine/RocksDBColumnFamilyManager.h" #include "RocksDBEngine/RocksDBEngine.h" #include "RocksDBEngine/RocksDBKey.h" #include "RocksDBEngine/RocksDBLogValue.h" #include "RocksDBEngine/RocksDBTypes.h" #include "RocksDBEngine/RocksDBValue.h" #include "StorageEngine/EngineSelectorFeature.h" #include "Transaction/StandaloneContext.h" #include "Utils/SingleCollectionTransaction.h" #include "VocBase/AccessMode.h" #include "VocBase/LogicalCollection.h" #include "VocBase/vocbase.h" #include "Basics/DownCast.h" namespace arangodb::transaction { class Context; } namespace { std::shared_ptr<arangodb::LogicalCollection> lookupCollection( arangodb::DatabaseFeature& db, arangodb::RocksDBEngine& engine, uint64_t objectId) { auto pair = engine.mapObjectToCollection(objectId); auto vocbase = db.useDatabase(pair.first); return vocbase ? vocbase->lookupCollection(pair.second) : nullptr; } std::vector<std::shared_ptr<arangodb::Index>> lookupLinks( arangodb::LogicalCollection& coll) { auto indexes = coll.getIndexes(); // filter out non iresearch links const auto it = std::remove_if( indexes.begin(), indexes.end(), [](std::shared_ptr<arangodb::Index> const& idx) { return idx->type() != arangodb::Index::IndexType::TRI_IDX_TYPE_IRESEARCH_LINK; }); indexes.erase(it, indexes.end()); return indexes; } } // namespace namespace arangodb { namespace iresearch { IResearchRocksDBRecoveryHelper::IResearchRocksDBRecoveryHelper( ArangodServer& server) : _server(server) {} void IResearchRocksDBRecoveryHelper::prepare() { _dbFeature = &_server.getFeature<DatabaseFeature>(); _engine = &_server.getFeature<EngineSelectorFeature>().engine<RocksDBEngine>(); _documentCF = RocksDBColumnFamilyManager::get( RocksDBColumnFamilyManager::Family::Documents) ->GetID(); } void IResearchRocksDBRecoveryHelper::PutCF(uint32_t column_family_id, const rocksdb::Slice& key, const rocksdb::Slice& value, rocksdb::SequenceNumber /*tick*/) { if (column_family_id != _documentCF) { return; } auto coll = lookupCollection(*_dbFeature, *_engine, RocksDBKey::objectId(key)); if (coll == nullptr) { return; } auto const links = lookupLinks(*coll); if (links.empty()) { return; } auto docId = RocksDBKey::documentId(key); auto doc = RocksDBValue::data(value); transaction::StandaloneContext ctx(coll->vocbase()); SingleCollectionTransaction trx(std::shared_ptr<transaction::Context>( std::shared_ptr<transaction::Context>(), &ctx), // aliasing ctor *coll, arangodb::AccessMode::Type::WRITE); Result res = trx.begin(); if (res.fail()) { THROW_ARANGO_EXCEPTION(res); } for (std::shared_ptr<arangodb::Index> const& link : links) { IndexId indexId(coll->vocbase().id(), coll->id(), link->id()); // optimization: avoid insertion of recovered documents twice, // first insertion done during index creation if (!link || _recoveredIndexes.find(indexId) != _recoveredIndexes.end()) { continue; // index was already populated when it was created } basics::downCast<IResearchRocksDBLink>(*link).insert(trx, nullptr, docId, doc, {}, false); } res = trx.commit(); if (res.fail()) { THROW_ARANGO_EXCEPTION(res); } } // common implementation for DeleteCF / SingleDeleteCF void IResearchRocksDBRecoveryHelper::handleDeleteCF( uint32_t column_family_id, const rocksdb::Slice& key, rocksdb::SequenceNumber /*tick*/) { if (column_family_id != _documentCF) { return; } auto coll = lookupCollection(*_dbFeature, *_engine, RocksDBKey::objectId(key)); if (coll == nullptr) { return; } auto const links = lookupLinks(*coll); if (links.empty()) { return; } auto docId = RocksDBKey::documentId(key); transaction::StandaloneContext ctx(coll->vocbase()); SingleCollectionTransaction trx(std::shared_ptr<transaction::Context>( std::shared_ptr<transaction::Context>(), &ctx), // aliasing ctor *coll, arangodb::AccessMode::Type::WRITE); Result res = trx.begin(); if (res.fail()) { THROW_ARANGO_EXCEPTION(res); } for (std::shared_ptr<arangodb::Index> const& link : links) { IResearchLink& impl = basics::downCast<IResearchRocksDBLink>(*link); impl.remove(trx, docId); } res = trx.commit(); if (res.fail()) { THROW_ARANGO_EXCEPTION(res); } } void IResearchRocksDBRecoveryHelper::LogData(const rocksdb::Slice& blob, rocksdb::SequenceNumber tick) { RocksDBLogType const type = RocksDBLogValue::type(blob); switch (type) { case RocksDBLogType::IndexCreate: { // Intentional NOOP. Index is committed upon creation. // So if this marker was written - index was persisted already. } break; case RocksDBLogType::CollectionTruncate: { TRI_ASSERT(_dbFeature); TRI_ASSERT(_engine); uint64_t objectId = RocksDBLogValue::objectId(blob); auto coll = lookupCollection(*_dbFeature, *_engine, objectId); if (coll != nullptr) { auto const links = lookupLinks(*coll); for (auto const& link : links) { link->afterTruncate(tick, nullptr); } } break; } default: break; // shut up the compiler } } } // namespace iresearch } // namespace arangodb // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // -----------------------------------------------------------------------------
30.724409
80
0.631599
7606ed3bc233b9ed7f32bc613a8838b4e6ef0824
9,151
cc
C++
pigasus/software/tools/u2boat/u2boat.cc
zhipengzhaocmu/fpga2022_artifact
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
pigasus/software/tools/u2boat/u2boat.cc
zhipengzhaocmu/fpga2022_artifact
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
pigasus/software/tools/u2boat/u2boat.cc
zhipengzhaocmu/fpga2022_artifact
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
//-------------------------------------------------------------------------- // Copyright (C) 2014-2018 Cisco and/or its affiliates. All rights reserved. // Copyright (C) 2002-2013 Sourcefire, Inc. // // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License Version 2 as published // by the Free Software Foundation. You may not use, modify or distribute // this program under any other version of the GNU General Public License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. //-------------------------------------------------------------------------- // u2boat.cc author Ryan Jordan <ryan.jordan@sourcefire.com> #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <pcap.h> #include <unistd.h> #include <cctype> #include <cerrno> #include <cstdlib> #include <cstring> #include "../u2spewfoo/u2_common.h" #define FAILURE (-1) #define SUCCESS 0 #define PCAP_MAGIC_NUMBER 0xa1b2c3d4 #define PCAP_TIMEZONE 0 #define PCAP_SIGFIGS 0 #define PCAP_SNAPLEN 65535 #define ETHERNET 1 #define PCAP_LINKTYPE ETHERNET #define MAX_U2RECORD_DATA_LENGTH 65536 static int GetRecord(FILE* input, u2record* rec); static int PcapInitOutput(FILE* output); static int PcapConversion(u2record* rec, FILE* output); static int ConvertLog(FILE* input, FILE* output, const char* format) { u2record tmp_record; /* Determine conversion function */ int (* ConvertRecord)(u2record*, FILE*) = nullptr; /* This will become an if/else series once more formats are supported. * Callbacks are used so that this comparison only needs to happen once. */ if (strncasecmp(format, "pcap", 4) == 0) { ConvertRecord = PcapConversion; } if (ConvertRecord == nullptr) { fprintf(stderr, "Error setting conversion routine, aborting...\n"); return FAILURE; } /* Initialize the record's data pointer */ tmp_record.data = (uint8_t*)malloc(MAX_U2RECORD_DATA_LENGTH * sizeof(uint8_t)); if (tmp_record.data == nullptr) { fprintf(stderr, "Error allocating memory, aborting...\n"); return FAILURE; } /* Run through input file and convert records */ while ( !(feof(input) || ferror(input) || ferror(output)) ) { if (GetRecord(input, &tmp_record) == FAILURE) { break; } if (ConvertRecord(&tmp_record, output) == FAILURE) { break; } } if (tmp_record.data != nullptr) { free(tmp_record.data); tmp_record.data = nullptr; } if (ferror(input)) { fprintf(stderr, "Error reading input file, aborting...\n"); return FAILURE; } if (ferror(output)) { fprintf(stderr, "Error reading output file, aborting...\n"); return FAILURE; } return SUCCESS; } /* Create and write the pcap file's global header */ static int PcapInitOutput(FILE* output) { size_t ret; struct pcap_file_header hdr; hdr.magic = PCAP_MAGIC_NUMBER; hdr.version_major = PCAP_VERSION_MAJOR; hdr.version_minor = PCAP_VERSION_MINOR; hdr.thiszone = PCAP_TIMEZONE; hdr.sigfigs = PCAP_SIGFIGS; hdr.snaplen = PCAP_SNAPLEN; hdr.linktype = PCAP_LINKTYPE; ret = fwrite( (void*)&hdr, sizeof(struct pcap_file_header), 1, output); if (ret < 1) { fprintf(stderr, "Error: Unable to write pcap file header\n"); return FAILURE; } return SUCCESS; } /* Convert a unified2 packet record to pcap format, then dump */ static int PcapConversion(u2record* rec, FILE* output) { Serial_Unified2Packet packet; struct pcap_pkthdr pcap_hdr; uint32_t* field; uint8_t* pcap_data; static int packet_found = 0; /* Ignore IDS Events. We are only interested in Packets. */ if (rec->type != UNIFIED2_PACKET) { return SUCCESS; } /* Initialize the pcap file if this is the first packet */ if (!packet_found) { if (PcapInitOutput(output) == FAILURE) { return FAILURE; } packet_found = 1; } /* Fill out the Serial_Unified2Packet */ memcpy(&packet, rec->data, sizeof(Serial_Unified2Packet)); /* Unified 2 records are always stored in network order. * Convert all fields except packet data to host order */ field = (uint32_t*)&packet; while (field < (uint32_t*)packet.packet_data) { *field = ntohl(*field); field++; } /* Create a pcap packet header */ pcap_hdr.ts.tv_sec = packet.packet_second; pcap_hdr.ts.tv_usec = packet.packet_microsecond; pcap_hdr.caplen = packet.packet_length; pcap_hdr.len = packet.packet_length; /* Write to the pcap file */ pcap_data = rec->data + sizeof(Serial_Unified2Packet) - 4; pcap_dump( (uint8_t*)output, &pcap_hdr, (uint8_t*)pcap_data); return SUCCESS; } /* Retrieve a single unified2 record from input file */ static int GetRecord(FILE* input, u2record* rec) { uint32_t items_read; static uint32_t buffer_size = MAX_U2RECORD_DATA_LENGTH; uint8_t* tmp; if (!input || !rec) return FAILURE; items_read = fread(rec, sizeof(uint32_t), 2, input); if (items_read != 2) { if ( !feof(input) ) /* Not really an error if at EOF */ { fprintf(stderr, "Error: incomplete record.\n"); } return FAILURE; } /* Type and Length are stored in network order */ rec->type = ntohl(rec->type); rec->length = ntohl(rec->length); /* Read in the data portion of the record */ if (rec->length > buffer_size) { tmp = (uint8_t*)malloc(rec->length * sizeof(uint8_t)); if (tmp == nullptr) { fprintf(stderr, "Error: memory allocation failed.\n"); return FAILURE; } else { if (rec->data != nullptr) { free(rec->data); } rec->data = tmp; buffer_size = rec->length; } } items_read = fread(rec->data, sizeof(uint8_t), rec->length, input); if (items_read != rec->length) { fprintf(stderr, "Error: incomplete record. %u of %u bytes read.\n", items_read, rec->length); return FAILURE; } return SUCCESS; } int main(int argc, char* argv[]) { char* input_filename = nullptr; char* output_filename = nullptr; const char* output_type = nullptr; FILE* input_file = nullptr; FILE* output_file = nullptr; int c, errnum; opterr = 0; /* Use Getopt to parse options */ while ((c = getopt (argc, argv, "t:")) != -1) { switch (c) { case 't': output_type = optarg; break; case '?': if (optopt == 't') fprintf(stderr, "Option -%c requires an argument.\n", optopt); else if (isprint (optopt)) fprintf(stderr, "Unknown option -%c.\n", optopt); return FAILURE; default: abort(); } } /* At this point, there should be two filenames remaining. */ if (optind != (argc - 2)) { fprintf(stderr, "Usage: u2boat [-t type] <infile> <outfile>\n"); return FAILURE; } input_filename = argv[optind]; output_filename = argv[optind+1]; /* Check inputs */ if (input_filename == nullptr) { fprintf(stderr, "Error: Input filename must be specified.\n"); return FAILURE; } if (output_type == nullptr) { fprintf(stdout, "Defaulting to pcap output.\n"); output_type = "pcap"; } if (strcasecmp(output_type, "pcap")) { fprintf(stderr, "Invalid output type. Valid types are: pcap\n"); return FAILURE; } if (output_filename == nullptr) { fprintf(stderr, "Error: Output filename must be specified.\n"); return FAILURE; } /* Open the files */ if ((input_file = fopen(input_filename, "r")) == nullptr) { fprintf(stderr, "Unable to open file: %s\n", input_filename); return FAILURE; } if ((output_file = fopen(output_filename, "w")) == nullptr) { fclose(input_file); fprintf(stderr, "Unable to open/create file: %s\n", output_filename); return FAILURE; } ConvertLog(input_file, output_file, output_type); if (fclose(input_file) != 0) { errnum = errno; fprintf(stderr, "Error closing input: %s\n", strerror(errnum)); } if (fclose(output_file) != 0) { errnum = errno; fprintf(stderr, "Error closing output: %s\n", strerror(errnum)); } return 0; }
27.89939
83
0.602666
7608a5f1d9ac50567702b78a115c3600c1abc70f
4,916
cpp
C++
test-suite/generated-src/jni/NativeInterfaceEncapsulator.cpp
iRobotCorporation/djinni
50ab071b855beab4e65af1772823dc2080b450b8
[ "Apache-2.0" ]
1
2016-03-04T20:23:31.000Z
2016-03-04T20:23:31.000Z
test-suite/generated-src/jni/NativeInterfaceEncapsulator.cpp
iRobotCorporation/djinni
50ab071b855beab4e65af1772823dc2080b450b8
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/jni/NativeInterfaceEncapsulator.cpp
iRobotCorporation/djinni
50ab071b855beab4e65af1772823dc2080b450b8
[ "Apache-2.0" ]
null
null
null
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from interface_inheritance.djinni #include "NativeInterfaceEncapsulator.hpp" // my header #include "NativeBaseCppInterfaceInheritance.hpp" #include "NativeBaseObjcJavaInterfaceInheritance.hpp" #include "NativeSubObjcJavaInterfaceInheritance.hpp" namespace djinni_generated { NativeInterfaceEncapsulator::NativeInterfaceEncapsulator() : ::djinni::JniInterface<::testsuite::InterfaceEncapsulator, NativeInterfaceEncapsulator>("com/dropbox/djinni/test/InterfaceEncapsulator$CppProxy") {} NativeInterfaceEncapsulator::~NativeInterfaceEncapsulator() = default; CJNIEXPORT void JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_nativeDestroy(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef) { try { DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef); delete reinterpret_cast<::djinni::CppProxyHandle<::testsuite::InterfaceEncapsulator>*>(nativeRef); } JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, ) } CJNIEXPORT void JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1setCppObject(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef, jobject j_object) { try { DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef); const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef); ref->set_cpp_object(::djinni_generated::NativeBaseCppInterfaceInheritance::toCpp(jniEnv, j_object)); } JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, ) } CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1getCppObject(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef) { try { DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef); const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef); auto r = ref->get_cpp_object(); return ::djinni::release(::djinni_generated::NativeBaseCppInterfaceInheritance::fromCpp(jniEnv, r)); } JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */) } CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1subCppAsBaseCpp(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef) { try { DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef); const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef); auto r = ref->sub_cpp_as_base_cpp(); return ::djinni::release(::djinni_generated::NativeBaseCppInterfaceInheritance::fromCpp(jniEnv, r)); } JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */) } CJNIEXPORT void JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1setObjcJavaObject(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef, jobject j_object) { try { DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef); const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef); ref->set_objc_java_object(::djinni_generated::NativeBaseObjcJavaInterfaceInheritance::toCpp(jniEnv, j_object)); } JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, ) } CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1getObjcJavaObject(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef) { try { DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef); const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef); auto r = ref->get_objc_java_object(); return ::djinni::release(::djinni_generated::NativeBaseObjcJavaInterfaceInheritance::fromCpp(jniEnv, r)); } JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */) } CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1castBaseArgToSub(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef, jobject j_subAsBase) { try { DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef); const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef); auto r = ref->cast_base_arg_to_sub(::djinni_generated::NativeBaseObjcJavaInterfaceInheritance::toCpp(jniEnv, j_subAsBase)); return ::djinni::release(::djinni_generated::NativeSubObjcJavaInterfaceInheritance::fromCpp(jniEnv, r)); } JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */) } CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_create(JNIEnv* jniEnv, jobject /*this*/) { try { DJINNI_FUNCTION_PROLOGUE0(jniEnv); auto r = ::testsuite::InterfaceEncapsulator::create(); return ::djinni::release(::djinni_generated::NativeInterfaceEncapsulator::fromCpp(jniEnv, r)); } JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */) } } // namespace djinni_generated
53.434783
209
0.778885
760a33560dd67baa90060d7973adde8257a61375
837
hpp
C++
PolyEngine/Editor/Src/Controls/IControlBase.hpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
65
2017-04-04T20:33:44.000Z
2019-12-02T23:06:58.000Z
PolyEngine/Editor/Src/Controls/IControlBase.hpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
46
2017-04-21T12:26:38.000Z
2019-12-15T05:31:47.000Z
PolyEngine/Editor/Src/Controls/IControlBase.hpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
51
2017-04-12T10:53:32.000Z
2019-11-20T13:05:54.000Z
#pragma once #include <QtWidgets/qwidget.h> #include <QtCore/qtimer.h> #include <RTTI/RTTI.hpp> #include <Utils/Logger.hpp> using namespace Poly; // This is base class for all controls for core types such as int, string or vector. // @see Poly::RTTI::eCorePropertyType class IControlBase { public: // Assigns given object to control and updates this control. virtual void SetObject(void* ptr) = 0; // Name of assigned property. virtual void SetName(String name) = 0; // Tool tip for this control. virtual void SetToolTip(String type) = 0; // If set to true then control will not permit changing its content. virtual void SetDisableEdit(bool disable) = 0; // Resets this control to initial state; virtual void Reset() = 0; // Call this to update control state from assigned object. virtual void UpdateControl() = 0; };
26.15625
84
0.734767
760be1fbba299668e2b3974b11ff6c5d131f3464
21,384
cpp
C++
src/CQPropertyViewTree.cpp
SammyEnigma/CQPropertyView
4dd64a266929b754a68839243daf0aeb80331185
[ "MIT" ]
8
2018-05-07T13:06:53.000Z
2022-03-08T05:25:06.000Z
src/CQPropertyViewTree.cpp
SammyEnigma/CQPropertyView
4dd64a266929b754a68839243daf0aeb80331185
[ "MIT" ]
2
2021-06-18T06:08:37.000Z
2022-03-12T11:45:17.000Z
src/CQPropertyViewTree.cpp
SammyEnigma/CQPropertyView
4dd64a266929b754a68839243daf0aeb80331185
[ "MIT" ]
4
2019-04-01T13:13:59.000Z
2022-01-20T12:14:44.000Z
#include <CQPropertyViewTree.h> #include <CQPropertyViewFilter.h> #include <CQPropertyViewModel.h> #include <CQPropertyViewDelegate.h> #include <CQPropertyViewItem.h> #include <CQHeaderView.h> #include <QApplication> #include <QHeaderView> #include <QMouseEvent> #include <QClipboard> #include <QMenu> #include <set> #include <iostream> CQPropertyViewTree:: CQPropertyViewTree(QWidget *parent) : QTreeView(parent), model_(new CQPropertyViewModel) { init(); modelAllocated_ = true; } CQPropertyViewTree:: CQPropertyViewTree(QWidget *parent, CQPropertyViewModel *model) : QTreeView(parent), model_(model) { init(); } CQPropertyViewTree:: ~CQPropertyViewTree() { if (modelAllocated_) delete model_; delete filter_; } void CQPropertyViewTree:: init() { setObjectName("propertyView"); //-- filter_ = new CQPropertyViewFilter(this); if (model_) { connect(model_, SIGNAL(valueChanged(QObject *, const QString &)), this, SIGNAL(valueChanged(QObject *, const QString &))); connect(model_, SIGNAL(valueChanged(QObject *, const QString &)), this, SLOT(redraw())); model_->setTree(this); filter_->setSourceModel(model_); setModel(filter_); } //-- setHeader(new CQHeaderView(this)); header()->setStretchLastSection(true); //header()->setSectionResizeMode(QHeaderView::Interactive); //header()->setSectionResizeMode(QHeaderView::ResizeToContents); //-- setSelectionMode(ExtendedSelection); setUniformRowHeights(true); setAlternatingRowColors(true); setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed); //-- // Set Item Delegate delegate_ = new CQPropertyViewDelegate(this); setItemDelegate(delegate_); connect(delegate_, SIGNAL(closeEditor(QWidget*, QAbstractItemDelegate::EndEditHint)), this, SLOT(closeEditorSlot(QWidget*, QAbstractItemDelegate::EndEditHint))); //-- // handle click (for bool check box) connect(this, SIGNAL(clicked(const QModelIndex &)), this, SLOT(itemClickedSlot(const QModelIndex &))); //--- // handle selection auto *sm = this->selectionModel(); if (sm) connect(sm, SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, SLOT(itemSelectionSlot())); //--- // add menu setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(customContextMenuSlot(const QPoint&))); } void CQPropertyViewTree:: setPropertyModel(CQPropertyViewModel *model) { // disconnect current model if (model_) { disconnect(model_, SIGNAL(valueChanged(QObject *, const QString &)), this, SIGNAL(valueChanged(QObject *, const QString &))); disconnect(model_, SIGNAL(valueChanged(QObject *, const QString &)), this, SLOT(redraw())); model_->setTree(nullptr); } //--- model_ = model; //--- // connect new model if (model_) { connect(model_, SIGNAL(valueChanged(QObject *, const QString &)), this, SIGNAL(valueChanged(QObject *, const QString &))); connect(model_, SIGNAL(valueChanged(QObject *, const QString &)), this, SLOT(redraw())); model_->setTree(this); filter_->setSourceModel(model_); setModel(filter_); } } void CQPropertyViewTree:: setMouseHighlight(bool b) { mouseHighlight_ = b; setMouseTracking(mouseHighlight_); } void CQPropertyViewTree:: setFilter(const QString &filter) { filter_->setFilter(filter); } void CQPropertyViewTree:: modelResetSlot() { //std::cerr << "model reset" << std::endl; } void CQPropertyViewTree:: redraw() { viewport()->update(); } void CQPropertyViewTree:: clear() { model_->clear(); } void CQPropertyViewTree:: addProperty(const QString &path, QObject *obj, const QString &name, const QString &alias) { model_->addProperty(path, obj, name, alias); } bool CQPropertyViewTree:: setProperty(QObject *object, const QString &path, const QVariant &value) { bool rc = model_->setProperty(object, path, value); redraw(); return rc; } bool CQPropertyViewTree:: getProperty(const QObject *object, const QString &path, QVariant &value) const { return model_->getProperty(object, path, value); } void CQPropertyViewTree:: selectObject(const QObject *obj) { auto *root = model_->root(); for (int i = 0; i < model_->numItemChildren(root); ++i) { auto *item = model_->itemChild(root, i); if (selectObject(item, obj)) return; } } bool CQPropertyViewTree:: selectObject(CQPropertyViewItem *item, const QObject *obj) { auto *obj1 = item->object(); if (obj1 == obj) { if (item->parent()) { selectItem(item->parent(), true); return true; } } for (int i = 0; i < model_->numItemChildren(item); ++i) { auto *item1 = model_->itemChild(item, i); if (selectObject(item1, obj)) return true; } return false; } void CQPropertyViewTree:: deselectAllObjects() { auto *sm = this->selectionModel(); sm->clear(); } bool CQPropertyViewTree:: setCurrentProperty(QObject *object, const QString &path) { auto *item = model_->propertyItem(object, path); if (! item) return false; auto ind = indexFromItem(item, 0, /*map*/true); if (! ind.isValid()) return false; setCurrentIndex(ind); return true; } void CQPropertyViewTree:: resizeColumns() { resizeColumnToContents(0); resizeColumnToContents(1); header()->setStretchLastSection(false); header()->setStretchLastSection(true); } void CQPropertyViewTree:: expandAll() { auto *root = model_->root(); expandAll(root); } void CQPropertyViewTree:: expandAll(CQPropertyViewItem *item) { expandItemTree(item); for (int i = 0; i < model_->numItemChildren(item); ++i) { auto *item1 = model_->itemChild(item, i); expandAll(item1); } } void CQPropertyViewTree:: collapseAll() { auto *root = model_->root(); collapseAll(root); } void CQPropertyViewTree:: collapseAll(CQPropertyViewItem *item) { collapseItemTree(item); for (int i = 0; i < model_->numItemChildren(item); ++i) { auto *item1 = model_->itemChild(item, i); collapseAll(item1); } } void CQPropertyViewTree:: expandSelected() { auto indices = this->selectedIndexes(); for (int i = 0; i < indices.length(); ++i) { auto *item = getModelItem(indices[i]); expandItemTree(item); } resizeColumns(); for (int i = 0; i < indices.length(); ++i) { auto *item = getModelItem(indices[i]); scrollToItem(item); } } void CQPropertyViewTree:: getSelectedObjects(Objs &objs) { auto indices = this->selectedIndexes(); for (int i = 0; i < indices.length(); ++i) { auto *item = getModelItem(indices[i]); QObject *obj; QString path; getItemData(item, obj, path); objs.push_back(obj); } } //--- bool CQPropertyViewTree:: isShowHidden() const { return model_->isShowHidden(); } void CQPropertyViewTree:: setShowHidden(bool b) { if (model_ && b != model_->isShowHidden()) { saveState(); model_->setShowHidden(b); model_->reset(); restoreState(); } } //--- void CQPropertyViewTree:: saveState() { assert(model_); stateData_.expandPaths.clear(); auto ind = indexAt(QPoint(0, 0)); stateData_.topItem.clear(); itemPath(ind, stateData_.topItem); //std::cerr << "Top : "; printPath(stateData_.topItem); stateData_.topIndex = QModelIndex(); saveState1(QModelIndex(), stateData_, 0); } void CQPropertyViewTree:: saveState1(const QModelIndex &parent, StateData &stateData, int depth) { auto *filterModel = this->filterModel(); int nr = filterModel->rowCount(parent); for (int r = 0; r < nr; ++r) { auto ind = filterModel->index(r, 0, parent); if (! filterModel->hasChildren(ind)) continue; if (isExpanded(ind)) { ItemPath path; itemPath(ind, path); stateData.expandPaths[depth].push_back(path); //std::cerr << "Save : "; printPath(path); } saveState1(ind, stateData, depth + 1); } } void CQPropertyViewTree:: restoreState() { assert(model_); restoreState1(QModelIndex(), stateData_, 0); redraw(); if (stateData_.topIndex.isValid()) { #if 0 ItemPath topItem; auto ind1 = indexAt(QPoint(0, 0)); itemPath(ind1, topItem); std::cerr << "Top : "; printPath(topItem); auto rect = visualRect(stateData_.topIndex); int dy = rect.top(); std::cerr << "DY : " << dy << "\n"; #endif scrollTo(stateData_.topIndex, QAbstractItemView::EnsureVisible); #if 0 rect = visualRect(stateData_.topIndex); dy = rect.top(); std::cerr << "DY : " << dy << "\n"; topItem.clear(); ind1 = indexAt(QPoint(0, 0)); itemPath(ind1, topItem); std::cerr << "Top : "; printPath(topItem); #endif scrollTo(stateData_.topIndex, QAbstractItemView::PositionAtTop); #if 0 rect = visualRect(stateData_.topIndex); dy = rect.top(); std::cerr << "DY : " << dy << "\n"; topItem.clear(); ind1 = indexAt(QPoint(0, 0)); itemPath(ind1, topItem); std::cerr << "Top : "; printPath(topItem); #endif } } void CQPropertyViewTree:: restoreState1(const QModelIndex &parent, StateData &stateData, int depth) { auto pd = stateData.expandPaths.find(depth); //--- auto itemMatch = [&](const ItemPath &path1, const ItemPath &path2) { int np = path1.length(); if (path2.length() != np) return false; for (int i = 0; i < np; ++i) { if (path1[i] != path2[i]) return false; } return true; }; auto hasPath = [&](const ItemPath &path) { auto &itemPaths = (*pd).second; for (const auto &path1 : itemPaths) { if (itemMatch(path, path1)) return true; } return false; }; //--- auto *filterModel = this->filterModel(); int nr = filterModel->rowCount(parent); for (int r = 0; r < nr; ++r) { auto ind = filterModel->index(r, 0, parent); ItemPath path; itemPath(ind, path); if (itemMatch(stateData_.topItem, path)) stateData.topIndex = ind; if (! filterModel->hasChildren(ind)) continue; if (pd != stateData.expandPaths.end()) { if (hasPath(path)) { setExpanded(ind, true); //std::cerr << "Restore : "; printPath(path); } } restoreState1(ind, stateData, depth + 1); } } void CQPropertyViewTree:: itemPath(const QModelIndex &ind, ItemPath &path) const { auto *filterModel = this->filterModel(); if (ind.parent().isValid()) itemPath(ind.parent(), path); auto str = filterModel->data(ind, Qt::DisplayRole).toString(); path.push_back(str); } #if 0 void CQPropertyViewTree:: printPath(const ItemPath &path) const { std::cerr << path.join("|").toStdString() << "\n"; } #endif //--- void CQPropertyViewTree:: autoUpdateSlot(bool b) { if (! model_) return; if (b) updateDirtySlot(); model_->setAutoUpdate(b); } void CQPropertyViewTree:: updateDirtySlot() { if (! model_) return; emit startUpdate(); model_->updateDirty(); emit endUpdate(); } //--- void CQPropertyViewTree:: search(const QString &text) { auto searchStr = text; if (searchStr.length() && searchStr[searchStr.length() - 1] != '*') searchStr += "*"; if (searchStr.length() && searchStr[0] != '*') searchStr = "*" + searchStr; QRegExp regexp(searchStr, Qt::CaseSensitive, QRegExp::Wildcard); auto *root = model_->root(); // get matching items Items items; for (int i = 0; i < model_->numItemChildren(root); ++i) { auto *item = model_->itemChild(root, i); searchItemTree(item, regexp, items); } // select matching items auto *sm = this->selectionModel(); sm->clear(); for (uint i = 0; i < items.size(); ++i) { auto *item = items[i]; selectItem(item, true); } //--- // ensure selection expanded for (uint i = 0; i < items.size(); ++i) { auto *item = items[i]; expandItemTree(item); } //--- // make item visible resizeColumns(); for (uint i = 0; i < items.size(); ++i) { auto *item = items[i]; scrollToItem(item); } } void CQPropertyViewTree:: searchItemTree(CQPropertyViewItem *item, const QRegExp &regexp, Items &items) { auto itemText = item->aliasName(); if (regexp.exactMatch(itemText)) items.push_back(item); int n = model_->numItemChildren(item); for (int i = 0; i < n; ++i) { auto *item1 = model_->itemChild(item, i); searchItemTree(item1, regexp, items); } } void CQPropertyViewTree:: expandItemTree(CQPropertyViewItem *item) { while (item) { expandItem(item); item = item->parent(); } } void CQPropertyViewTree:: collapseItemTree(CQPropertyViewItem *item) { while (item) { collapseItem(item); item = item->parent(); } } void CQPropertyViewTree:: itemClickedSlot(const QModelIndex &index) { auto *item = getModelItem(index); if (item && index.column() == 1) { if (item->click()) { update(index); } } //--- QObject *obj; QString path; getItemData(item, obj, path); emit itemClicked(obj, path); } void CQPropertyViewTree:: itemSelectionSlot() { // filter model indices auto indices = this->selectedIndexes(); if (indices.empty()) return; auto ind = indices[0]; assert(ind.model() == filter_); auto *item = getModelItem(ind); QObject *obj; QString path; getItemData(item, obj, path); emit itemSelected(obj, path); } CQPropertyViewItem * CQPropertyViewTree:: getModelItem(const QModelIndex &ind, bool map) const { if (map) { bool ok; auto *item = model_->item(ind, ok); if (! item) return nullptr; assert(! ok); auto ind1 = filter_->mapToSource(ind); auto *item1 = model_->item(ind1); return item1; } else { auto *item = model_->item(ind); return item; } } void CQPropertyViewTree:: getItemData(CQPropertyViewItem *item, QObject* &obj, QString &path) { path = item->path("/"); //--- // use object from first branch child auto *item1 = item; int n = model_->numItemChildren(item1); while (n > 0) { item1 = model_->itemChild(item1, 0); n = model_->numItemChildren(item1); } obj = item1->object(); } void CQPropertyViewTree:: customContextMenuSlot(const QPoint &pos) { // Map point to global from the viewport to account for the header. menuPos_ = viewport()->mapToGlobal(pos); menuItem_ = getModelItem(indexAt(pos)); if (isItemMenu()) { if (menuItem_) { QObject *obj; QString path; getItemData(menuItem_, obj, path); if (obj) { showContextMenu(obj, menuPos_); return; } } } //--- auto *menu = new QMenu; //--- addMenuItems(menu); //--- menu->exec(menuPos_); delete menu; } void CQPropertyViewTree:: addMenuItems(QMenu *menu) { addStandardMenuItems(menu); } void CQPropertyViewTree:: addStandardMenuItems(QMenu *menu) { auto addAction = [&](const QString &text, const char *slotName) { auto *action = new QAction(text, menu); connect(action, SIGNAL(triggered()), this, slotName); menu->addAction(action); return action; }; auto addCheckAction = [&](const QString &text, bool checked, const char *slotName) { auto *action = new QAction(text, menu); action->setCheckable(true); action->setChecked(checked); connect(action, SIGNAL(triggered(bool)), this, slotName); menu->addAction(action); return action; }; //--- (void) addAction("Expand All" , SLOT(expandAll())); (void) addAction("Collapse All", SLOT(collapseAll())); //--- menu->addSeparator(); (void) addCheckAction("Show Hidden", isShowHidden(), SLOT(setShowHidden(bool))); //--- auto *copyAction = addAction("Copy", SLOT(copySlot())); copyAction->setShortcut(QKeySequence::Copy); //--- if (model()) { menu->addSeparator(); (void) addCheckAction("Auto Update", model_->isAutoUpdate(), SLOT(autoUpdateSlot(bool))); if (! model_->isAutoUpdate()) (void) addAction("Update Dirty", SLOT(updateDirtySlot())); } //--- menu->addSeparator(); (void) addAction("Print" , SLOT(printSlot())); (void) addAction("Print Changed", SLOT(printChangedSlot())); } void CQPropertyViewTree:: showContextMenu(QObject *obj, const QPoint &globalPos) { emit menuExec(obj, globalPos); } void CQPropertyViewTree:: mouseMoveEvent(QMouseEvent *me) { if (! isMouseHighlight()) return; auto ind = indexAt(me->pos()); if (ind.isValid()) { auto *item = getModelItem(ind); if (item) { if (! isMouseInd(ind)) { setMouseInd(ind); redraw(); } return; } } if (! isMouseInd(QModelIndex())) { unsetMouseInd(); redraw(); } } void CQPropertyViewTree:: leaveEvent(QEvent *) { if (! isMouseHighlight()) return; unsetMouseInd(); redraw(); } void CQPropertyViewTree:: keyPressEvent(QKeyEvent *ke) { if (ke->matches(QKeySequence::Copy)) { auto p = QCursor::pos(); copyAt(p, /*html*/false); } else if (ke->key() == Qt::Key_Escape) { closeCurrentEditor(); } else QTreeView::keyPressEvent(ke); } void CQPropertyViewTree:: showEvent(QShowEvent *) { if (! shown_) { if (isResizeOnShow()) resizeColumns(); shown_ = true; } } void CQPropertyViewTree:: resizeEvent(QResizeEvent *e) { QTreeView::resizeEvent(e); } void CQPropertyViewTree:: scrollToItem(CQPropertyViewItem *item) { auto ind = indexFromItem(item, 0, /*map*/true); if (ind.isValid()) scrollTo(ind); } void CQPropertyViewTree:: selectItem(CQPropertyViewItem *item, bool selected) { auto *sm = this->selectionModel(); auto ind = indexFromItem(item, 0, /*map*/true); if (ind.isValid()) { if (selected) { sm->select(ind, QItemSelectionModel::Select); } else { //sm->select(ind, QItemSelectionModel::Deselect); } } } void CQPropertyViewTree:: expandItem(CQPropertyViewItem *item) { auto ind = indexFromItem(item, 0, /*map*/true); if (ind.isValid()) setExpanded(ind, true); } void CQPropertyViewTree:: collapseItem(CQPropertyViewItem *item) { auto ind = indexFromItem(item, 0, /*map*/true); if (ind.isValid()) setExpanded(ind, false); } void CQPropertyViewTree:: editItem(CQPropertyViewItem *item) { auto ind = indexFromItem(item, 1, /*map*/true); if (ind.isValid()) edit(ind); } void CQPropertyViewTree:: copySlot() const { copyAt(menuPos_, /*html*/false); } void CQPropertyViewTree:: copyAt(const QPoint &p, bool html) const { auto ind = indexAt(viewport()->mapFromGlobal(p)); if (ind.isValid()) { auto *item = getModelItem(ind); if (! item) return; QString value; if (ind.column() == 0) value = item->nameTip(html); else if (ind.column() == 1) value = item->valueTip(html); else return; auto *clipboard = QApplication::clipboard(); clipboard->setText(value, QClipboard::Clipboard); clipboard->setText(value, QClipboard::Selection); } } void CQPropertyViewTree:: printSlot() const { auto indices = this->selectionModel()->selectedRows(); for (int i = 0; i < indices.length(); ++i) { auto *item = getModelItem(indices[i]); auto path = item->path(".", /*alias*/true); std::cerr << path.toStdString() << "=" << item->dataStr().toStdString() << "\n"; } } void CQPropertyViewTree:: printChangedSlot() const { CQPropertyViewModel::NameValues nameValues; model_->getChangedNameValues(nameValues, /*tcl*/false); for (const auto &nv : nameValues) std::cerr << nv.first.toStdString() << "=" << nv.second.toString().toStdString() << "\n"; } void CQPropertyViewTree:: closeEditorSlot() { closeCurrentEditor(); } void CQPropertyViewTree:: closeCurrentEditor() { auto *editor = delegate_->getEditor(); if (! editor) return; if (! delegate_->isEditing()) return; delegate_->setModelData(editor, model(), delegate_->getEditorIndex()); // turn off edit triggers so we don't start a new editor auto triggers = editTriggers(); setEditTriggers(QAbstractItemView::NoEditTriggers); // close editor QAbstractItemView::closeEditor(editor, QAbstractItemDelegate::NoHint); // restore edit triggers setEditTriggers(triggers); //setSelectedIndex(delegate_->getEditorIndex().row()); delegate_->setEditing(false); } void CQPropertyViewTree:: closeEditorSlot(QWidget *, QAbstractItemDelegate::EndEditHint) { delegate_->setEditing(false); } QModelIndex CQPropertyViewTree:: indexFromItem(CQPropertyViewItem *item, int column, bool map) const { auto ind = model_->indexFromItem(item, column); if (! ind.isValid()) return QModelIndex(); if (map) { auto *filterModel = this->filterModel(); return filterModel->mapFromSource(ind); } return ind; } void CQPropertyViewTree:: setMouseInd(const QModelIndex &i) { assert(i.isValid()); hasMouseInd_ = true; mouseInd_ = i; } void CQPropertyViewTree:: unsetMouseInd() { hasMouseInd_ = false; mouseInd_ = QModelIndex(); } bool CQPropertyViewTree:: isMouseInd(const QModelIndex &i) { if (! isMouseHighlight()) return false; if (i.isValid()) { if (! hasMouseInd_) return false; assert(i.model() == mouseInd_.model()); if (mouseInd_.parent() != i.parent()) return false; return (mouseInd_.row() == i.row()); } else { return ! hasMouseInd_; } }
17.6
93
0.648803
76169e6048a4751df05e23b45ca86658151d7cd1
755
cpp
C++
Competitions/Codeforces/Codeforces Round #352 (Div. 2)/Summer Camp.cpp
cnm06/Competitive-Programming
94242ae458570d503b8218f37624b88cc5020d23
[ "MIT" ]
994
2017-02-28T06:13:47.000Z
2022-03-31T10:49:00.000Z
Competitions/Codeforces/Codeforces Round #352 (Div. 2)/Summer Camp.cpp
Quadrified/Competitive-Programming
bccb69952cc5260fb3647b3301ddac1023dacac8
[ "MIT" ]
16
2018-01-01T02:59:55.000Z
2021-11-22T12:49:16.000Z
Competitions/Codeforces/Codeforces Round #352 (Div. 2)/Summer Camp.cpp
Quadrified/Competitive-Programming
bccb69952cc5260fb3647b3301ddac1023dacac8
[ "MIT" ]
325
2017-06-15T03:32:43.000Z
2022-03-28T22:43:42.000Z
#include <iostream> #include <bits/stdc++.h> using namespace std; long long int n, temp; int main() { cin>>n; if(n<10 && n>0) { cout<<n<<endl; } else if(n>9 && n<190) { n=n-9; temp=n%2; n=9+n/2; if(temp==0) { cout<<n%10<<endl; } else { n++; cout<<n/10<<endl; } } else { n=n-189; temp=n%3; n=99+n/3; if(temp==0) { cout<<n%10<<endl; } else if(temp==1) { n++; cout<<n/100<<endl; } else { n++; n=n/10; cout<<n%10<<endl; } } return 0; }
14.803922
30
0.316556
76173854685ca6fc47d1690112e0dde625311ca5
606
cpp
C++
src/format.cpp
sharonshmuel/CppND-System-Monitor
2fb14d0f2b45d8c99759c91a0c80af0d7dbb5c98
[ "MIT" ]
null
null
null
src/format.cpp
sharonshmuel/CppND-System-Monitor
2fb14d0f2b45d8c99759c91a0c80af0d7dbb5c98
[ "MIT" ]
null
null
null
src/format.cpp
sharonshmuel/CppND-System-Monitor
2fb14d0f2b45d8c99759c91a0c80af0d7dbb5c98
[ "MIT" ]
null
null
null
#include <string> #include "format.h" using std::string; // INPUT: Long int measuring seconds // OUTPUT: HH:MM:SS string Format::ElapsedTime(long seconds) { string format; long minutes = seconds / 60; long hours = minutes / 60; long h = hours;// (hours % 24) ; string hs = (h < 10) ? "0" + std::to_string(h): std::to_string(h); long m = (minutes % 60); string ms = (m < 10) ? "0" + std::to_string(m): std::to_string(m); long s = (seconds % 60); string ss = (s < 10) ? "0" + std::to_string(s): std::to_string(s); format = hs+":"+ms+":"+ss; return format; }
30.3
71
0.574257
761761409dd0e995e32457cf0293e50204fb6b1a
443
hpp
C++
src/Qt5Network/QLocalServer.hpp
dafrito/luacxx
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
[ "MIT" ]
128
2015-01-07T19:47:09.000Z
2022-01-22T19:42:14.000Z
src/Qt5Network/QLocalServer.hpp
dafrito/luacxx
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
[ "MIT" ]
null
null
null
src/Qt5Network/QLocalServer.hpp
dafrito/luacxx
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
[ "MIT" ]
24
2015-01-07T19:47:10.000Z
2022-01-25T17:42:37.000Z
#ifndef luacxx_QLocalServer_INCLUDED #define luacxx_QLocalServer_INCLUDED #include "../stack.hpp" #include "../enum.hpp" #include <QLocalServer> #include "../Qt5Core/QObject.hpp" // http://qt-project.org/doc/qt-5/qlocalserver.html#details LUA_METATABLE_INHERIT(QLocalServer, QObject) LUA_METATABLE_ENUM(QLocalServer::SocketOption) extern "C" int luaopen_Qt5Network_QLocalServer(lua_State* const); #endif // luacxx_QLocalServer_INCLUDED
23.315789
65
0.801354
7621daf177cc86bd608edb512ae2a03fd7b72d28
6,164
cpp
C++
Mesh_3/archive/applications/identify_identical_points_in_OFF_files.cpp
antoniospg/cgal
2891c22fc7f64f680ac7e144407afe49f6425cb9
[ "CC0-1.0" ]
2
2020-12-12T09:30:07.000Z
2021-01-04T05:00:23.000Z
Mesh_3/archive/applications/identify_identical_points_in_OFF_files.cpp
antoniospg/cgal
2891c22fc7f64f680ac7e144407afe49f6425cb9
[ "CC0-1.0" ]
17
2018-01-10T13:32:24.000Z
2021-07-30T12:23:20.000Z
Mesh_3/archive/applications/identify_identical_points_in_OFF_files.cpp
antoniospg/cgal
2891c22fc7f64f680ac7e144407afe49f6425cb9
[ "CC0-1.0" ]
1
2019-02-21T15:26:25.000Z
2019-02-21T15:26:25.000Z
// Copyright (c) 2007 INRIA Sophia-Antipolis (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // // $URL$ // $Id$ // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial // // Author(s) : Laurent Rineau #include <iostream> #include <string> #include <vector> #include <map> #include <stack> #include <boost/tuple/tuple.hpp> #include <boost/tuple/tuple_comparison.hpp> #include <boost/format.hpp> using std::cout; using std::cin; using std::endl; int main() { std::string header; cin >> header; if(header != "OFF") { std::cerr << "header is \"" << header << "\"\nshould be \"OFF\".\n"; return 1; } cout << header << endl; unsigned int n_vertices; unsigned int n_facets; std::string dummy; cin >> n_vertices; cin >> n_facets; getline(cin, dummy); // Vector that maps from old vertex index to new vertex index, // as some (old) vertices may have identical point coordinates. std::vector<int> new_index(n_vertices); typedef boost::tuple<double, double, double> Point; // Vector that stores the points coordinates (in a Point). std::vector<Point> points(n_vertices); // Map that retains the mapping from the point coordinates (in a Point) // to the nex index. typedef std::map<Point, int> Renumber; Renumber renumber; unsigned int index = 0; for(unsigned int i = 0; i < n_vertices; ++i) { cin >> boost::get<0>(points[index]) >> boost::get<1>(points[index]) >> boost::get<2>(points[index]); Renumber::const_iterator it = renumber.find(points[index]); if( it == renumber.end() ) { renumber[points[index]] = index; new_index[i] = index; ++index; } else { new_index[i] = it->second; } } cout << index << " " << n_facets << dummy << endl; for(unsigned int i = 0; i < index; ++i) { cout << boost::get<0>(points[i]) << " " << boost::get<1>(points[i]) << " " << boost::get<2>(points[i]) << "\n"; } // Vector that stores each facet. typedef std::vector<boost::tuple<int, int, int> > Facets; Facets facets; // For each (oriented) edge, that map stores a vector of adjacent facets, // with a boolean that tells if the edge is in the opposite orientation, // in the facet. // Edges are stores in the direction from the smallest index to the // greatest. typedef std::pair<int, int> Edge; typedef std::map<Edge, std::vector<std::pair<int, bool> > > Edges_map; Edges_map edges; // "nested function" opposite, that returns the edge, in the opposite // direction. struct { Edge operator()(Edge e) const { return std::make_pair(e.second, e.first); }; } opposite; for(unsigned int i_facet = 0; i_facet < n_facets; ++i_facet) { // Read a facet, then reindex its vertices. int i, j, k; cin >> dummy >> i >> j >> k; if( dummy != "3" ) { std::cerr << "In facet #" << i_facet << ", expected \"3\", found \"" << dummy << "\"!\n"; return 1; } i = new_index[i]; j = new_index[j]; k = new_index[k]; facets.push_back(boost::make_tuple(i, j, k)); // Create the three edges of the facet. Edge e[3]; e[0] = std::make_pair(i, j); e[1] = std::make_pair(j, k); e[2] = std::make_pair(k, i); for(int i_edge = 0; i_edge < 3; ++i_edge) { if( e[i_edge].first < e[i_edge].second ) edges[e[i_edge]].push_back(std::make_pair(i_facet, false)); else edges[opposite(e[i_edge])].push_back(std::make_pair(i_facet, true)); } } // Map that stores all already passed facet, and retains the orientation // of the facet. "true" means that the facet needs to be reoriented. std::map<int, bool> oriented_set; // Stack of facets indices to be handled. std::stack<int> stack; int seed_facet_candidate = 0; while (oriented_set.size() != n_facets) { // find a facet index that is not yet in 'oriented_set'. while( oriented_set.find(seed_facet_candidate) != oriented_set.end() ) ++seed_facet_candidate; std::cerr << "Need seed facet: " << seed_facet_candidate << "\n"; // push it in oriented set oriented_set[seed_facet_candidate] = false; stack.push(seed_facet_candidate); while(! stack.empty() ) { const int f = stack.top(); stack.pop(); const int i = boost::get<0>(facets[f]); const int j = boost::get<1>(facets[f]); const int k = boost::get<2>(facets[f]); Edge e[3]; e[0] = std::make_pair(i, j); e[1] = std::make_pair(j, k); e[2] = std::make_pair(k, i); for(int ih = 0 ; ih < 3 ; ++ih) { bool f_orient = false; if(e[ih].first > e[ih].second) { f_orient = true; e[ih] = opposite(e[ih]); } Edges_map::iterator edge_it = edges.find(e[ih]); if(edge_it->second.size() == 2) { // regular edge int fn = edge_it->second[0].first; bool fn_orient = edge_it->second[0].second; if(fn == f) { fn = edge_it->second[1].first; fn_orient = edge_it->second[1].second; } if (oriented_set.find(fn) == oriented_set.end()) { if(f_orient == fn_orient) oriented_set[fn] = ! oriented_set[f]; else oriented_set[fn] = oriented_set[f]; stack.push(fn); } } // end "if the edge is regular" else { std::cerr << boost::format("Irregular edge: (%1%,%2%)" ", %3% facets.\n") % e[ih].first % e[ih].second % edge_it->second.size(); } } // end "for each neighbor of f" } // end "stack non empty" } // end "oriented_set not full" for(unsigned int i_facet = 0; i_facet < n_facets; ++i_facet) { const int i = boost::get<0>(facets[i_facet]); const int j = boost::get<1>(facets[i_facet]); const int k = boost::get<2>(facets[i_facet]); if(oriented_set[i_facet]) cout << "3 " << j << " " << i << " " << k << "\n"; else cout << "3 " << i << " " << j << " " << k << "\n"; } }
29.352381
76
0.571058
76231a822c50524b2f87ef378d5e7334ef090703
2,378
hpp
C++
blast/include/objtools/format/ftable_formatter.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
blast/include/objtools/format/ftable_formatter.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
blast/include/objtools/format/ftable_formatter.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
#ifndef OBJTOOLS_FORMAT___FTABLE_FORMATTER__HPP #define OBJTOOLS_FORMAT___FTABLE_FORMATTER__HPP /* $Id: ftable_formatter.hpp 103491 2007-05-04 17:18:18Z kazimird $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Aaron Ucko, NCBI * Mati Shomrat * * File Description: * 5-Column feature table formatting */ #include <corelib/ncbistd.hpp> #include <objtools/format/item_formatter.hpp> #include <objtools/format/items/feature_item.hpp> BEGIN_NCBI_SCOPE BEGIN_SCOPE(objects) class CSeq_loc; class NCBI_FORMAT_EXPORT CFtableFormatter : public CFlatItemFormatter { public: CFtableFormatter(void); void FormatReference(const CReferenceItem& keys, IFlatTextOStream& text_os); void FormatFeatHeader(const CFeatHeaderItem& fh, IFlatTextOStream& text_os); void FormatFeature(const CFeatureItemBase& feat, IFlatTextOStream& text_os); private: void x_FormatLocation(const CSeq_loc& loc, const string& key, CBioseqContext& ctx, list<string>& l); void x_FormatQuals(const CFlatFeature::TQuals& quals, CBioseqContext& ctx, list<string>& l); }; END_SCOPE(objects) END_NCBI_SCOPE #endif /* OBJTOOLS_FORMAT___FTABLE_FORMATTER__HPP */
34.463768
80
0.707317
7626c7483fb2ea7749e070c7818a48b71e7fa0c9
46
cpp
C++
tests/src/experimental/tests_Optional.cpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
1
2021-07-16T14:19:50.000Z
2021-07-16T14:19:50.000Z
tests/src/experimental/tests_Optional.cpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
1
2018-06-05T11:03:30.000Z
2018-06-05T11:03:30.000Z
tests/src/experimental/tests_Optional.cpp
tum-ei-rcs/mart-common
6f8f18ac23401eb294d96db490fbdf78bf9b316c
[ "MIT" ]
null
null
null
#include <mart-common/experimental/Optional.h>
46
46
0.826087
762827d26f7dec396fe5a7a69c3bf9b17ce3596b
11,362
cpp
C++
renderer.cpp
zH4x/SoT-DLL
6f7cf448c937a63d9f068bdf10a679dfb15bf357
[ "MIT" ]
51
2019-05-02T07:07:19.000Z
2022-02-17T03:28:17.000Z
renderer.cpp
booggzen/SoT-DLL
3131cb07305e30a154c2d3568a7dd060831bef07
[ "MIT" ]
1
2020-07-10T18:41:32.000Z
2020-07-10T18:41:32.000Z
renderer.cpp
booggzen/SoT-DLL
3131cb07305e30a154c2d3568a7dd060831bef07
[ "MIT" ]
19
2019-09-24T02:09:00.000Z
2022-02-17T03:28:18.000Z
#include "renderer.h" Renderer::Renderer(ID3D11Device *direct3DDevice, const std::wstring &defaultFontFamily) : direct3DDevice(direct3DDevice), immediateContext(nullptr), inputLayout(nullptr), vertexShader(nullptr), pixelShader(nullptr), fontFactory(nullptr), fontWrapper(nullptr), defaultFontFamily(defaultFontFamily), maxVertices(16384 * 8 * 4 * 3) { D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16 , D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; ID3DBlob *vsBlob = nullptr; ID3DBlob *psBlob = nullptr; direct3DDevice->GetImmediateContext(&immediateContext); throwIfFailed(FW1CreateFactory(FW1_VERSION, &fontFactory)); renderList = std::make_unique<RenderList>(fontFactory, maxVertices); throwIfFailed(fontFactory->CreateFontWrapper(direct3DDevice, defaultFontFamily.c_str(), &fontWrapper)); throwIfFailed(D3DCompile(shader, std::size(shader), nullptr, nullptr, nullptr, "VS", "vs_4_0", 0, 0, &vsBlob, nullptr)); throwIfFailed(D3DCompile(shader, std::size(shader), nullptr, nullptr, nullptr, "PS", "ps_4_0", 0, 0, &psBlob, nullptr)); throwIfFailed(direct3DDevice->CreateVertexShader(vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), nullptr, &vertexShader)); throwIfFailed(direct3DDevice->CreatePixelShader(psBlob->GetBufferPointer(), psBlob->GetBufferSize(), nullptr, &pixelShader)); throwIfFailed(direct3DDevice->CreateInputLayout(layout, static_cast<UINT>(std::size(layout)), vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), &inputLayout)); safeRelease(vsBlob); safeRelease(psBlob); D3D11_BLEND_DESC blendDesc{}; blendDesc.RenderTarget->BlendEnable = TRUE; blendDesc.RenderTarget->SrcBlend = D3D11_BLEND_SRC_ALPHA; blendDesc.RenderTarget->DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendDesc.RenderTarget->SrcBlendAlpha = D3D11_BLEND_ONE; blendDesc.RenderTarget->DestBlendAlpha = D3D11_BLEND_ZERO; blendDesc.RenderTarget->BlendOp = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget->BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget->RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; throwIfFailed(direct3DDevice->CreateBlendState(&blendDesc, &blendState)); D3D11_BUFFER_DESC bufferDesc{}; bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.ByteWidth = sizeof(Vertex) * static_cast<UINT>(maxVertices); bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; bufferDesc.MiscFlags = 0; throwIfFailed(direct3DDevice->CreateBuffer(&bufferDesc, nullptr, &vertexBuffer)); bufferDesc = {}; bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.ByteWidth = sizeof(XMMATRIX); bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; bufferDesc.MiscFlags = 0; throwIfFailed(direct3DDevice->CreateBuffer(&bufferDesc, nullptr, &screenProjectionBuffer)); D3D11_VIEWPORT viewport{}; UINT numViewports = 1; immediateContext->RSGetViewports(&numViewports, &viewport); projection = XMMatrixOrthographicOffCenterLH(0.0f, viewport.Width, viewport.Height, 0.0f, -100.0f, 100.0f); D3D11_MAPPED_SUBRESOURCE mappedResource; throwIfFailed(immediateContext->Map(screenProjectionBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)); { std::memcpy(mappedResource.pData, &projection, sizeof(XMMATRIX)); } immediateContext->Unmap(screenProjectionBuffer, 0); } Renderer::~Renderer() { safeRelease(vertexShader); safeRelease(pixelShader); safeRelease(vertexBuffer); safeRelease(screenProjectionBuffer); safeRelease(inputLayout); safeRelease(blendState); safeRelease(fontWrapper); safeRelease(fontFactory); } void Renderer::begin() { immediateContext->VSSetShader(vertexShader, nullptr, 0); immediateContext->PSSetShader(pixelShader, nullptr, 0); immediateContext->OMSetBlendState(blendState, nullptr, 0xffffffff); immediateContext->VSSetConstantBuffers(0, 1, &screenProjectionBuffer); immediateContext->IASetInputLayout(inputLayout); UINT stride = sizeof(Vertex); UINT offset = 0; immediateContext->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset); fontWrapper->DrawString(immediateContext, L"", 0.0f, 0.0f, 0.0f, 0xff000000, FW1_RESTORESTATE | FW1_NOFLUSH); } void Renderer::end() { renderList->clear(); } void Renderer::draw(const RenderList::Ptr &renderList) { if (std::size(renderList->vertices) > 0) { D3D11_MAPPED_SUBRESOURCE mappedResource; throwIfFailed(immediateContext->Map(vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)); { std::memcpy(mappedResource.pData, renderList->vertices.data(), sizeof(Vertex) * std::size(renderList->vertices)); } immediateContext->Unmap(vertexBuffer, 0); } std::size_t pos = 0; for (const auto &batch : renderList->batches) { immediateContext->IASetPrimitiveTopology(batch.topology); immediateContext->Draw(static_cast<UINT>(batch.count), static_cast<UINT>(pos)); pos += batch.count; } fontWrapper->Flush(immediateContext); fontWrapper->DrawGeometry(immediateContext, renderList->textGeometry, nullptr, nullptr, FW1_RESTORESTATE); } void Renderer::draw() { draw(renderList); } void Renderer::addVertex(const RenderList::Ptr &renderList, Vertex &vertex, D3D11_PRIMITIVE_TOPOLOGY topology) { assert(topology != D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP && "addVertex >Use addVertices to draw line/triangle strips!"); assert(topology != D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ && "addVertex >Use addVertices to draw line/triangle strips!"); assert(topology != D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP && "addVertex >Use addVertices to draw line/triangle strips!"); assert(topology != D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ && "addVertex >Use addVertices to draw line/triangle strips!"); if (std::size(renderList->vertices) >= maxVertices) (this->renderList == renderList) ? draw(renderList) : throw std::exception( "Renderer::addVertex - Vertex buffer exhausted! Increase the size of the vertex buffer or add a custom implementation."); if (std::empty(renderList->batches) || renderList->batches.back().topology != topology) renderList->batches.emplace_back(0, topology); renderList->batches.back().count += 1; renderList->vertices.push_back(vertex); } void Renderer::addVertex(Vertex &vertex, D3D11_PRIMITIVE_TOPOLOGY topology) { addVertex(renderList, vertex, topology); } void Renderer::drawText(const RenderList::Ptr &renderList, const Vec2 &pos, const std::wstring &text, const Color &color, std::uint32_t flags, float fontSize, const std::wstring &fontFamily) { std::uint32_t shadowColor = XMCOLOR(0.1f, 0.1f, 0.1f, 0.85f); FW1_RECTF shadowRect = { pos.x + 0.5f, pos.y + 0.5f, pos.x + 0.5f, pos.y + 0.5f }; fontWrapper->AnalyzeString(nullptr, text.c_str(), (fontFamily == std::wstring{}) ? defaultFontFamily.c_str() : fontFamily.c_str(), fontSize, &shadowRect, shadowColor, flags | FW1_NOFLUSH | FW1_NOWORDWRAP, renderList->textGeometry); std::uint32_t transformedColor = XMCOLOR(color.f[2], color.f[1], color.f[0], color.f[3]); FW1_RECTF rect = { pos.x, pos.y, pos.x, pos.y }; fontWrapper->AnalyzeString(nullptr, text.c_str(), (fontFamily == std::wstring{}) ? defaultFontFamily.c_str() : fontFamily.c_str(), fontSize, &rect, transformedColor, flags | FW1_NOFLUSH | FW1_NOWORDWRAP, renderList->textGeometry); } void Renderer::drawText(const Vec2 &pos, const std::wstring &text, const Color &color, std::uint32_t flags, float fontSize, const std::wstring &fontFamily) { drawText(renderList, pos, text, color, flags, fontSize, fontFamily); } Vec2 Renderer::getTextExtent(const std::wstring &text, float fontSize, const std::wstring &fontFamily) const { FW1_RECTF nullRect = { 0.f, 0.f, 0.f, 0.f }; FW1_RECTF rect = fontWrapper->MeasureString(text.c_str(), (fontFamily == std::wstring{}) ? defaultFontFamily.c_str() : fontFamily.c_str(), fontSize, &nullRect, FW1_NOWORDWRAP); return{ rect.Right, rect.Bottom }; } void Renderer::drawPixel(const RenderList::Ptr &renderList, const Vec2 &pos, const Color &color) { drawFilledRect(renderList, XMFLOAT4{ pos.x, pos.y, 1.f, 1.f }, color); } void Renderer::drawPixel(const Vec2 &pos, const Color &color) { drawFilledRect(renderList, XMFLOAT4{ pos.x, pos.y, 1.f, 1.f }, color); } void Renderer::drawLine(const RenderList::Ptr &renderList, const Vec2 &from, const Vec2 &to, const Color &color) { Vertex v[] { { from.x, from.y, 0.0f, color }, { to.x, to.y, 0.0f, color } }; addVertices(renderList, v, D3D11_PRIMITIVE_TOPOLOGY_LINELIST); } void Renderer::drawLine(const Vec2 &from, const Vec2 &to, const Color &color) { drawLine(renderList, from, to, color); } void Renderer::drawFilledRect(const RenderList::Ptr &renderList, const Vec4 &rect, const Color &color) { Vertex v[] { { rect.x, rect.y, 0.f, color }, { rect.x + rect.z, rect.y, 0.f, color }, { rect.x, rect.y + rect.w, 0.f, color }, { rect.x + rect.z, rect.y, 0.f, color }, { rect.x + rect.z, rect.y + rect.w, 0.f, color }, { rect.x, rect.y + rect.w, 0.f, color } }; addVertices(renderList, v, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); } void Renderer::drawFilledRect(const Vec4 &rect, const Color &color) { drawFilledRect(renderList, rect, color); } void Renderer::drawRect(const RenderList::Ptr &renderList, const Vec4 &rect, float strokeWidth, const Color &color) { XMFLOAT4 tmp = rect; tmp.z = strokeWidth; drawFilledRect(renderList, tmp, color); tmp.x = rect.x + rect.z - strokeWidth; drawFilledRect(renderList, tmp, color); tmp.z = rect.z; tmp.x = rect.x; tmp.w = strokeWidth; drawFilledRect(renderList, tmp, color); tmp.y = rect.y + rect.w; drawFilledRect(renderList, tmp, color); } void Renderer::drawRect(const Vec4 &rect, float strokeWidth, const Color &color) { drawRect(renderList, rect, strokeWidth, color); } void Renderer::drawOutlinedRect(const RenderList::Ptr &renderList, const Vec4 &rect, float strokeWidth, const Color &strokeColor, const Color &fillColor) { drawFilledRect(renderList, rect, fillColor); drawRect(renderList, rect, strokeWidth, strokeColor); } void Renderer::drawOutlinedRect(const Vec4 &rect, float strokeWidth, const Color &strokeColor, const Color &fillColor) { drawOutlinedRect(renderList, rect, strokeWidth, strokeColor, fillColor); } void Renderer::drawCircle(const RenderList::Ptr &renderList, const Vec2 &pos, float radius, const Color &color) { const int segments = 24; Vertex v[segments + 1]; for (int i = 0; i <= segments; i++) { float theta = 2.f * XM_PI * static_cast<float>(i) / static_cast<float>(segments); v[i] = Vertex{ pos.x + radius * std::cos(theta), pos.y + radius * std::sin(theta), 0.f, color }; } addVertices(renderList, v, D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP); } void Renderer::drawCircle(const Vec2 &pos, float radius, const Color &color) { drawCircle(renderList, pos, radius, color); } std::shared_ptr<Renderer> Renderer::ptr() { return shared_from_this(); } IFW1Factory *Renderer::getFontFactory() const { return fontFactory; }
34.852761
164
0.728833
762a0dc66e72d07d2707b64b32450fe35bb7e0c6
2,276
cpp
C++
tc 160+/OptimalList.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/OptimalList.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/OptimalList.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; const int di[] = { -1, 0, 1, 0 }; const int dj[] = { 0, 1, 0, -1 }; string dir = "NESW"; int getDir(char c) { return dir.find(c); } class OptimalList { public: string optimize(string inst) { int i = 0; int j = 0; for (int k=0; k<(int)inst.size(); ++k) { int d = getDir(inst[k]); i += di[d]; j += dj[d]; } int d1; if (i >= 0) d1 = 2; else d1 = 0; int d2; if (j >= 0) d2 = 1; else d2 = 3; if (dir[d1] > dir[d2]) return string(abs(j), dir[d2]) + string(abs(i), dir[d1]); else return string(abs(i), dir[d1]) + string(abs(j), dir[d2]); } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "NENENNWWWWWS"; string Arg1 = "NNNWWW"; verify_case(0, Arg1, optimize(Arg0)); } void test_case_1() { string Arg0 = "NNEESSWW"; string Arg1 = ""; verify_case(1, Arg1, optimize(Arg0)); } void test_case_2() { string Arg0 = "NEWSNWESWESSEWSENSEWSEWESEWWEWEEWESSSWWWWWW"; string Arg1 = "SSSSSSSSWWW"; verify_case(2, Arg1, optimize(Arg0)); } void test_case_3() { string Arg0 = "NENENE"; string Arg1 = "EEENNN"; verify_case(3, Arg1, optimize(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { OptimalList ___test; ___test.run_test(-1); } // END CUT HERE
29.558442
315
0.566784
762abd73654bedd41bbb03db5ede2cb40c955af2
475
cpp
C++
PassingCars/C++/PassingCars.cpp
ArturMarekNowak/Random-Algorithms-Repository
bda0e18bed68d3ab1b61b445e693a5c3c03a1179
[ "MIT" ]
1
2022-02-12T14:57:48.000Z
2022-02-12T14:57:48.000Z
PassingCars/C++/PassingCars.cpp
ArturMarekNowak/Random-Algorithms-Repository
bda0e18bed68d3ab1b61b445e693a5c3c03a1179
[ "MIT" ]
null
null
null
PassingCars/C++/PassingCars.cpp
ArturMarekNowak/Random-Algorithms-Repository
bda0e18bed68d3ab1b61b445e693a5c3c03a1179
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> int passingCars(std::vector<int> & someVec) { if(someVec.size() == 1) return 0; int counter = 0, result = 0; for(int i = someVec.size() - 1; i >= 0; i--) if(someVec[i] == 1) counter++; else if(someVec[i] == 0) { result += counter; if(result > 1000000000) return -1; } return result; } int main() { std::vector<int> vecOne = {0, 1, 0, 1, 1}; std::cout << passingCars(vecOne) << std::endl; return 0; }
15.322581
47
0.574737
762ae0e3ad471639a76e787ed602828358d9d040
5,668
cpp
C++
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/Audio/Chorus/chorusmodel.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/Audio/Chorus/chorusmodel.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/Audio/Chorus/chorusmodel.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
// // chorusmodel.cpp // MDStudio // // Created by Daniel Cliche on 2017-05-08. // Copyright © 2017-2020 Daniel Cliche. All rights reserved. // #include "chorusmodel.h" #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> #include <string.h> #define GRAPH_SAMPLE_RATE 44100 #define ROUND(n) ((int)((float)(n) + 0.5)) #define BSZ 8192 // must be about 1/5 of a second at given sample rate #define MODF(n, i, f) ((i) = (int)(n), (f) = (n) - (float)(i)) using namespace MDStudio; #define NUM_MIX_MODES 7 // --------------------------------------------------------------------------------------------------------------------- ChorusModel::ChorusModel() { _paramWidth = 0.8f; _paramDelay = 0.2f; _paramMixMode = 0; _sweepSamples = 0; _delaySamples = 22; _lfoPhase = 0.0f; setRate(0.2f); setWidth(0.5f); _fp = 0; _sweep = 0.0; setMixMode(kMixStereoWetOnly); _wet = 0.0f; // allocate the buffer _buf = new GraphSampleType[BSZ]; memset(_buf, 0, sizeof(GraphSampleType) * BSZ); } // --------------------------------------------------------------------------------------------------------------------- ChorusModel::~ChorusModel() { if (_buf) delete[] _buf; } // --------------------------------------------------------------------------------------------------------------------- void ChorusModel::setRate(float rate) { _paramSweepRate = rate; _lfoDeltaPhase = 2 * M_PI * rate / GRAPH_SAMPLE_RATE; // map into param onto desired sweep range with log curve _sweepRate = pow(10.0, (double)_paramSweepRate); _sweepRate -= 1.0; _sweepRate *= 1.1f; _sweepRate += 0.1f; // finish setup setSweep(); } // --------------------------------------------------------------------------------------------------------------------- // Maps 0.0-1.0 input to calculated width in samples from 0ms to 50ms void ChorusModel::setWidth(float v) { _paramWidth = v; // map so that we can spec between 0ms and 50ms _sweepSamples = ROUND(v * 0.05 * GRAPH_SAMPLE_RATE); // finish setup setSweep(); } // --------------------------------------------------------------------------------------------------------------------- // Expects input from 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 void ChorusModel::setDelay(float v) { _paramDelay = v; // make onto desired values applying log curve double delay = pow(10.0, (double)v * 2.0) / 1000.0; // map logarithmically and convert to seconds _delaySamples = ROUND(delay * GRAPH_SAMPLE_RATE); // finish setup setSweep(); } // --------------------------------------------------------------------------------------------------------------------- // Sets up sweep based on rate, depth, and delay as they're all interrelated // Assumes _sweepRate, _sweepSamples, and _delaySamples have all been set by // setRate, setWidth, and setDelay void ChorusModel::setSweep() { // calc min and max sweep now _minSweepSamples = _delaySamples; _maxSweepSamples = _delaySamples + _sweepSamples; // set intial sweep pointer to midrange _sweep = (_minSweepSamples + _maxSweepSamples) / 2; } // --------------------------------------------------------------------------------------------------------------------- void ChorusModel::setMixMode(int mixMode) { _paramMixMode = mixMode; switch (mixMode) { case kMixMono: default: _mixLeftWet = _mixRightWet = 1.0; _mixLeftDry = _mixRightDry = 1.0f; break; case kMixWetOnly: _mixLeftWet = _mixRightWet = 1.0f; _mixLeftDry = _mixRightDry = 0.0; break; case kMixWetLeft: _mixLeftWet = 1.0f; _mixLeftDry = 0.0f; _mixRightWet = 0.0f; _mixRightDry = 1.0f; break; case kMixWetRight: _mixLeftWet = 0.0f; _mixLeftDry = 1.0f; _mixRightWet = 1.0f; _mixRightDry = 0.0f; break; case kMixStereoWetOnly: _mixLeftWet = 1.0f; _mixLeftDry = 0.0f; _mixRightWet = -1.0f; _mixRightDry = 0.0f; break; } } // --------------------------------------------------------------------------------------------------------------------- void ChorusModel::setWet(float v) { _wet = v; } // --------------------------------------------------------------------------------------------------------------------- int ChorusModel::renderInput(UInt32 inNumberFrames, GraphSampleType* ioData[2], UInt32 stride) { float* io1 = ioData[0]; float* io2 = ioData[1]; for (int i = 0; i < inNumberFrames; ++i) { // assemble mono input value and store it in circle queue float inval = (*io1 + *io2) / 2.0f; _buf[_fp] = inval; _fp = (_fp + 1) & (BSZ - 1); // build the two emptying pointers and do linear interpolation int ep1, ep2; float w1, w2; float ep = _fp - _sweep; MODF(ep, ep1, w2); ep1 &= (BSZ - 1); ep2 = ep1 + 1; ep2 &= (BSZ - 1); w1 = 1.0 - w2; GraphSampleType outval = _buf[ep1] * w1 + _buf[ep2] * w2; // develop output mix *io1 = (float)(_mixLeftDry * *io1 + _mixLeftWet * _wet * outval); *io2 = (float)(_mixRightDry * *io2 + _mixRightWet * _wet * outval); _sweep = _minSweepSamples + _sweepSamples * (sinf(_lfoPhase) + 1.0f) / 2.0f; _lfoPhase += _lfoDeltaPhase; _lfoPhase = fmod(_lfoPhase, 2 * M_PI); io1 += stride; io2 += stride; } return 0; }
31.314917
120
0.481475
762b2d51877e601a10f55acb64f4fd2c81f7dd2d
14,190
cc
C++
src/HR2Scheduler.cc
harsha-simhadri/sbsched
8d12a010727ea415d5e4a23d389740d57c68278c
[ "MIT" ]
1
2020-09-30T14:47:02.000Z
2020-09-30T14:47:02.000Z
src/HR2Scheduler.cc
harsha-simhadri/sbsched
8d12a010727ea415d5e4a23d389740d57c68278c
[ "MIT" ]
null
null
null
src/HR2Scheduler.cc
harsha-simhadri/sbsched
8d12a010727ea415d5e4a23d389740d57c68278c
[ "MIT" ]
null
null
null
// This code is part of the project "Experimental Analysis of Space-Bounded // Schedulers", presented at Symposium on Parallelism in Algorithms and // Architectures, 2014. // Copyright (c) 2014 Harsha Vardhan Simhadri, Guy Blelloch, Phillip Gibbons, // Jeremy Fineman, Aapo Kyrola. // // 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 "HR2Scheduler.hh" #include <assert.h> HR2Scheduler::Cluster::Cluster (const lluint size, const int block_size, int num_children, int sibling_id, Cluster * parent, Cluster ** children) : _size (size), _block_size (block_size), _occupied(0), _num_children(num_children), _sibling_id(sibling_id), _parent(parent), _locked_thread_id (-1) { _children = new Cluster* [_num_children]; if (children!=NULL) for (int i=0; i<_num_children; ++i) _children[i]=children[i]; } HR2Scheduler::Cluster* HR2Scheduler::Cluster::create_tree( Cluster * root, Cluster ** leaf_array, int num_levels, uint * fan_outs, lluint * sizes, uint * block_sizes, int bucket_version) { static int leaf_counter=0; Cluster * ret; if (root == NULL) { // Create the root (RAM) node ret = new Cluster (1<<((sizeof(lluint)*4)-1) -1, block_sizes[0], fan_outs[0], 0); if (bucket_version==0) ret->_buckets = new Buckets<HR2Job*> (num_levels,0,*block_sizes,sizes,*fan_outs,SIGMA); else if (bucket_version==1) ret->_buckets = new TopDistrBuckets<HR2Job*> (num_levels,0,*block_sizes,sizes,*fan_outs,SIGMA); else exit(-1); leaf_counter = 0; for (int i=0; i<fan_outs[0]; ++i) { ret->_children[i] = create_tree (ret, leaf_array, num_levels-1, fan_outs+1, sizes+1, block_sizes+1,bucket_version); ret->_children[i]->_sibling_id = i; } } else if (num_levels>0) { ret = new Cluster (sizes[0], block_sizes[0], fan_outs[0], -1, root); if (bucket_version==0) ret->_buckets = new Buckets<HR2Job*> (num_levels,*sizes,*block_sizes,sizes,*fan_outs,SIGMA); else if (bucket_version==1) ret->_buckets = new TopDistrBuckets<HR2Job*> (num_levels,*sizes,*block_sizes,sizes,*fan_outs,SIGMA); else exit(-1); for (int i=0; i<fan_outs[0]; ++i) { ret->_children[i] = create_tree (ret, leaf_array, num_levels-1, fan_outs+1, sizes+1, block_sizes+1,bucket_version); ret->_children[i]->_sibling_id = i; } } else { ret = new Cluster (0, 1, 1, -1, root); // L0 cache/register leaf_array[leaf_counter++] = ret; } return ret; } void HR2Scheduler::print_tree( Cluster * root, int num_levels, int total_levels) { if (total_levels == -1) total_levels=num_levels; if (num_levels > 0) { for (int i=0; i<total_levels-num_levels; ++i) std::cout<<"\t\t"; std::cout<<"Occ:"<<root->_occupied<<" | "; if (root->is_locked()) std::cout<<"L | "; else std::cout<<"U | "; for (int i=0; i<root->_buckets->_num_levels; ++i) std::cout<<root->_buckets->_queues[i]->size()<<","; std::cout<<std::endl; for (int i=0; i<root->_num_children; ++i) print_tree (root->_children[i], num_levels-1, total_levels); } } void HR2Scheduler::print_job (HR2Job* sized_job) { std::cout<<" Job: "<<sized_job->get_id() <<", Str: "<<sized_job->strand_id() <<", Pin: "<<sized_job->get_pin_cluster() <<", Pin_Cl_Sz: "<<((HR2Scheduler::Cluster*)sized_job->get_pin_cluster())->_size <<", Pin_Cl_Occ: "<<((HR2Scheduler::Cluster*)sized_job->get_pin_cluster())->_occupied <<std::endl <<", Task_Size: "<<sized_job->size(1) <<", Strand_Size: "<<sized_job->strand_size(1) <<", cont_job? "<<sized_job->is_cont_job() <<", maximal_job: "<<sized_job->is_maximal() <<std::endl; } HR2Scheduler::HR2Scheduler (int num_threads, int num_levels, int * fan_outs, lluint * sizes, int * block_sizes, int bucket_version) : Scheduler (num_threads) { _type = 0; std::cout<<_type<<std::endl; _tree = new TreeOfCaches; _tree->_num_levels=num_levels; _tree->_fan_outs=new uint[_tree->_num_levels]; _tree->_sizes=new lluint[_tree->_num_levels]; _tree->_block_sizes=new uint[_tree->_num_levels]; _tree->_num_leaves=1; for (int i=0; i<_tree->_num_levels; ++i) { _tree->_fan_outs[i] = fan_outs[i]; _tree->_sizes[i] = sizes[i]; _tree->_block_sizes[i] = block_sizes[i]; _tree->_num_leaves*=fan_outs[i]; } _tree->_leaf_array = new Cluster* [_tree->_num_leaves]; _tree->_root = _tree->_root->create_tree (NULL, _tree->_leaf_array, _tree->_num_levels, _tree->_fan_outs, _tree->_sizes, _tree->_block_sizes,bucket_version); _tree->_num_locks_held = new int [_tree->_num_leaves]; _tree->_locked_clusters = new Cluster** [_tree->_num_leaves]; for (int i=0; i<_tree->_num_leaves; ++i) { _tree->_num_locks_held[i] = 0; _tree->_locked_clusters[i] = new Cluster*[_tree->_num_levels+1+8]; // +8 is to pad each list for (int j=0; j<_tree->_num_levels+1; ++j) _tree->_locked_clusters[i][j] = NULL; } } HR2Scheduler::~HR2Scheduler() { for (int i=0; i<_tree->_num_leaves; ++i) delete _tree->_locked_clusters[i]; delete _tree->_fan_outs; delete _tree->_sizes; delete _tree->_block_sizes; delete _tree->_num_locks_held; delete _tree->_locked_clusters; // Delete the cluster tree too } // Basic sanity check on locks held by a thread void HR2Scheduler::check_lock_consistency (int thread_id) { for (int i=0; i<_tree->_num_levels+1; ++i) { if (i<_tree->_num_locks_held[thread_id]) assert (_tree->_locked_clusters[thread_id][i] != NULL); else assert (_tree->_locked_clusters[thread_id][i] == NULL); if (i != _tree->_num_levels+1) if (_tree->_locked_clusters[thread_id][i] != NULL) assert (_tree->_locked_clusters[thread_id][i] != _tree->_locked_clusters[thread_id][i+1]); } } // Lock up 'node', and add that lock to the locked up node list void HR2Scheduler::lock (Cluster* node, int thread_id) { // std::cout<<"Lock, thr: "<<thread_id<<" "<<node<<std::endl; if (node->_num_children > 1) { node->lock(); assert(node->_locked_thread_id == -1); node->_locked_thread_id = thread_id; _tree->_locked_clusters[thread_id][_tree->_num_locks_held[thread_id]] = node; ++_tree->_num_locks_held[thread_id]; } } bool HR2Scheduler::has_lock (Cluster* node, int thread_id) { // std::cerr<<__func__<<": Not currently operational"<<std::endl; return (node->_num_children==1 || node->_locked_thread_id == thread_id); } void HR2Scheduler::print_locks (int thread_id) { std::cout<<"Thread "<<thread_id<<" has "<<_tree->_num_locks_held[thread_id] <<" locks: "; for (int i=0; i<_tree->_num_locks_held[thread_id]; ++i) { std::cout<<" '"<<_tree->_locked_clusters[thread_id][i]; } std::cout<<std::endl; } // Check if the node is the last in the list of locked nodes, void HR2Scheduler::unlock (Cluster* node, int thread_id) { //std::cout<<"Unlock, thr: "<<thread_id<<" "<<node<<std::endl; if (node->_num_children > 1) { --_tree->_num_locks_held[thread_id]; _tree->_locked_clusters[thread_id][_tree->_num_locks_held[thread_id]] = NULL; assert(node->_locked_thread_id == thread_id); node->_locked_thread_id = -1; node->unlock(); } } // Release all locks held by thread in the inverse order they were obtained void HR2Scheduler::release_locks (int thread_id) { while (_tree->_num_locks_held[thread_id] > 0) unlock (_tree->_locked_clusters[thread_id][_tree->_num_locks_held[thread_id]-1], thread_id); } /* Should be called only by a thread holding a lock on the current cluster */ void HR2Scheduler::pin (HR2Job *job, Cluster *cluster) { assert (cluster->_occupied <= cluster->_size); job->pin_to_cluster (cluster, job->size(cluster->_block_size)); } void HR2Scheduler::add (Job* uncast_job, int thread_id) { HR2Job* job = (HR2Job*)uncast_job; Cluster *root = _tree->_root; /* Job added by an agent other than the threads */ if (thread_id == _num_threads) { root->lock (); pin (job, root); root->_occupied+=job->size(root->_block_size); root->_buckets->add_job_to_bucket (job, 0); root->unlock (); return; } /* If root has no active job, set it here */ if (job->get_pin_cluster() == NULL) { for (Cluster *cur = _tree->_leaf_array[thread_id];cur->_parent!=NULL;cur = cur->_parent) lock (cur, thread_id); pin (job, root); root->_occupied+=job->size(root->_block_size); release_locks (thread_id); } /* Add job to the approporiate queue */ int child_id=0; for (Cluster * cur = _tree->_leaf_array[thread_id];;cur = cur->_parent ) { if (job->get_pin_cluster() == cur) { cur->_buckets->add_job_to_bucket (job, child_id); return; } child_id = cur->_sibling_id; } assert (false);exit(-1); } void HR2Scheduler::add_multiple (int num_jobs, Job** uncast_jobs, int thread_id) { HR2Job* job = (HR2Job*)uncast_jobs[0]; Cluster *root = _tree->_root; /* Job added by an agent other than the threads */ if (thread_id == _num_threads) { root->lock (); for (int i=0; i<num_jobs; ++i) { job = (HR2Job*)uncast_jobs[i]; pin (job, root); root->_occupied+=job->size(root->_block_size); root->_buckets->add_job_to_bucket (job, 0); } root->unlock (); return; } /* If root has no active job, set it here */ if (job->get_pin_cluster() == NULL) { for (Cluster *cur = _tree->_leaf_array[thread_id];cur->_parent!=NULL;cur = cur->_parent) lock (cur, thread_id); for (int i=0; i<num_jobs; ++i) { job = (HR2Job*)uncast_jobs[i]; pin (job, root); root->_occupied+=job->size(root->_block_size); } release_locks (thread_id); } /* Add job to the approporiate queue */ int child_id=0; for (Cluster * cur = _tree->_leaf_array[thread_id];;cur = cur->_parent ) { if (job->get_pin_cluster() == cur) { for (int i=0; i<num_jobs; ++i) { job = (HR2Job*)uncast_jobs[i]; cur->_buckets->add_job_to_bucket (job, child_id); } return; } child_id = cur->_sibling_id; } assert (false);exit(-1); } void HR2Scheduler::done (Job *uncast_job, int thread_id, bool deactivate) { HR2Job * job = (HR2Job*)uncast_job; Cluster * cur = _tree->_leaf_array[thread_id]; Cluster * pin = (Cluster*) job->get_pin_cluster(); /* Update occupied size */ for ( ; cur!=pin; cur=cur->_parent) { lluint strand_size = job->strand_size(cur->_block_size); lock (cur,thread_id); cur->_occupied -= (strand_size>(int)(MU*(cur->_size)) ? (int)(MU*(cur->_size)) : strand_size); } /* If the done task started a pin, clean up the allocation */ if (deactivate) { // Strand joins and end its task if (job->is_maximal()) { lock (cur, thread_id); cur->_occupied -= job->size(cur->_block_size); } } release_locks (thread_id); /* Last job done in the system */ if (job->parent_fork()==NULL && deactivate) { //print_tree (_tree->_root, _tree->_num_levels, _tree->_num_levels); //std::cout<<"Finished root task at thread: "<<thread_id<<std::endl; } } bool HR2Scheduler::fit_job (HR2Job *job, int thread_id, int height, int bucket_level) { Cluster *leaf=_tree->_leaf_array[thread_id]; Cluster *cur=leaf; for (int i=0; i<height-bucket_level; ++i) { lock (cur, thread_id); if (cur->_occupied > (1-MU)*(double)cur->_size) { release_locks (thread_id); return false; } cur=cur->_parent; } lluint task_size = job->size (cur->_block_size); assert (task_size <= SIGMA*(cur->_size) || cur->_parent == NULL); if (bucket_level > 0) { assert (!job->is_cont_job()); lock (cur, thread_id); if (task_size > cur->_size-cur->_occupied) { release_locks (thread_id); return false; } else { pin (job, cur); assert (job->is_maximal()); cur->_occupied += task_size; } } else { assert (job->get_pin_cluster() == cur); } for (Cluster *iter=leaf; iter!=cur ; iter=iter->_parent) { lluint strand_size = ((HR2Job*)job)->strand_size (iter->_block_size); assert (has_lock (iter, thread_id)); assert (iter->_occupied <= (1-MU)*iter->_size); iter->_occupied += (strand_size<(int)(MU*iter->_size) ? strand_size : (int)(MU*iter->_size)); } release_locks(thread_id); return true; } Job* HR2Scheduler::get (int thread_id) { HR2Job * job = NULL; int height=1; int child_id=_tree->_leaf_array[thread_id]->_sibling_id; for ( Cluster *cur=_tree->_leaf_array[thread_id]->_parent; cur!=NULL; cur=cur->_parent,++height) { int level = cur->_buckets->get_job_from_bucket(&job, 0, child_id); while (level !=-1) { if (fit_job (job, thread_id, height, level)==true) { release_locks(thread_id); return job; } else { cur->_buckets->return_to_queue (job, level, child_id); } level = cur->_buckets->get_job_from_bucket(&job, 1+level, child_id); } if ( cur->_occupied > (int)((1-MU)* cur->_size) ) return NULL; child_id = cur->_sibling_id; } return NULL; } bool HR2Scheduler::more (int thread_id) { std::cerr<<__func__<<" has been deprecated"<<std::endl; exit (-1); }
31.744966
106
0.657717
762d09dad5ba121135195bebd503ada89e9d4a39
144
hpp
C++
star.rg/include/tileDB.hpp
masscry/badbaby
f0b2e793081491ed7598d3170725fe4b48ae1fff
[ "MIT" ]
null
null
null
star.rg/include/tileDB.hpp
masscry/badbaby
f0b2e793081491ed7598d3170725fe4b48ae1fff
[ "MIT" ]
null
null
null
star.rg/include/tileDB.hpp
masscry/badbaby
f0b2e793081491ed7598d3170725fe4b48ae1fff
[ "MIT" ]
null
null
null
#pragma once #ifndef TILE_DATABASE_HEADER #define TILE_DATABASE_HEADER extern const tileInfo_t tileID[]; #endif // TILE_DATABASE_HEADER
10.285714
33
0.791667
7631c1aa955429bb64b7372f54adb09b33ab2d4e
3,619
cpp
C++
core123/ut/ut_simd_threefry.cpp
fennm/fs123
559b97659352620ce16030824f9acd26f590f4e1
[ "BSD-3-Clause" ]
22
2019-04-10T18:05:35.000Z
2021-12-30T12:26:39.000Z
core123/ut/ut_simd_threefry.cpp
fennm/fs123
559b97659352620ce16030824f9acd26f590f4e1
[ "BSD-3-Clause" ]
13
2019-04-09T00:19:29.000Z
2021-11-04T15:57:13.000Z
core123/ut/ut_simd_threefry.cpp
fennm/fs123
559b97659352620ce16030824f9acd26f590f4e1
[ "BSD-3-Clause" ]
4
2019-04-07T16:33:44.000Z
2020-07-02T02:58:51.000Z
#if defined(__ICC) #include <stdio.h> int main(int, char **){ printf(__FILE__ " Icc (through version 18) doesn't fully support gcc's 'vector' extensions."); return 0; } #else #pragma GCC diagnostic ignored "-Wunknown-warning-option" #pragma GCC diagnostic ignored "-Wpsabi" // see comments in simd_threefry.hpp #include <core123/simd_threefry.hpp> #include <core123/streamutils.hpp> #include <core123/timeit.hpp> #include <numeric> #include <iostream> #include <chrono> using core123::threefry; using core123::insbe; using core123::timeit; using namespace std::chrono; static constexpr unsigned ROUNDS = 12; int main(int, char **){ using vcbrng = threefry<4, uint64_tx8, ROUNDS>; vcbrng::domain_type ctr; using eltype = vcbrng::domain_type::value_type; ctr[0] = eltype{00,01,02,03,04,05,06,07}; ctr[1] = eltype{10,11,12,13,14,15,16,17}; if(ctr.size()>2){ ctr[2] = eltype{20,21,22,23,24,25,26,27}; ctr[3] = eltype{30,31,32,33,34,35,36,37}; } { vcbrng tf; auto r = tf(ctr); std::cout << "Vector threefry: sizeof(range_type): " << sizeof(vcbrng::range_type) << "\n"; std::cout << std::hex; switch(r.size()){ case 4: std::cout << r[0][0] << " " << r[1][0] << " " << r[2][0] << " " << r[3][0] << "\n"; std::cout << r[0][1] << " " << r[1][1] << " " << r[2][1] << " " << r[3][1] << "\n"; std::cout << r[0][2] << " " << r[1][2] << " " << r[2][2] << " " << r[3][2] << "\n"; std::cout << r[0][3] << " " << r[1][3] << " " << r[2][3] << " " << r[3][3] << "\n"; break; case 2: throw "Nope. Not done yet"; std::cout << r[0][0] << " " << r[1][0] << "\n"; std::cout << r[0][1] << " " << r[1][1] << "\n"; std::cout << r[0][2] << " " << r[1][2] << "\n"; std::cout << r[0][3] << " " << r[1][3] << "\n"; break; } tf.setkey(r); // Don't allow the optimizer to exploit zero-valued keys. ctr = r; // set the key and counter to "random" values static const int LOOP = 2; static const int millis = 2000; eltype sum = {}; auto result = timeit(milliseconds(millis), [&ctr, &sum, tf](){ eltype incr = {1, 1, 1, 1, 1, 1, 1, 1}; for(int i=0; i<LOOP; ++i){ ctr[0] += incr; auto rv = tf(ctr); sum = std::accumulate(rv.begin(), rv.end(), sum); // i.e., sum += r[0] + r[1] + .. + r[N-1]; } }); // Print the sum, so the optimizer can't elide the whole thing! std::cout << "sum = " << sum[0] << " " << sum[1] << " " << sum[2] << " " << sum[3] << " " << sum[4] << " " << sum[5] << " " << sum[6] << " " << sum[7] << "\n"; float ns_per_byte = 1.e9*result.sec_per_iter()/LOOP/sizeof(vcbrng::range_type); printf("8-way simd threefry: %lld calls in about %d ms. %.2f ns per call. %.3f ns per byte.\n", LOOP*result.count, millis, 1.e9*result.sec_per_iter()/LOOP, ns_per_byte); static const float GHz = 3.7; printf("at %.1fGHz that's %.2f cpb or %.1f bytes per cycle\n", GHz, ns_per_byte * GHz, 1./(ns_per_byte * GHz)); } std::cout << "Scalar threefry:\n"; { using cbrng = threefry<4, uint64_t, ROUNDS>; cbrng::range_type r; cbrng tf; r = tf({00, 10, 20, 30}); std::cout << insbe(r) << "\n"; r = tf({01, 11, 21, 31}); std::cout << insbe(r) << "\n"; r = tf({02, 12, 22, 32}); std::cout << insbe(r) << "\n"; r = tf({03, 13, 23, 33}); std::cout << insbe(r) << "\n"; } return 0; } #endif // not __ICC
36.555556
163
0.498757
7632d97bf2358fb269500f0dc8461a4d5a7f9069
244
cpp
C++
Index.cpp
Robert-xiaoqiang/MiniSQL-TeamLanTianLiuShe
9dcad804615412e85de31797c0a0afb84135918f
[ "MIT" ]
2
2018-07-29T03:08:45.000Z
2019-06-08T15:41:24.000Z
Index.cpp
Robert-xiaoqiang/MiniSQL-TeamLanTianLiuShe
9dcad804615412e85de31797c0a0afb84135918f
[ "MIT" ]
null
null
null
Index.cpp
Robert-xiaoqiang/MiniSQL-TeamLanTianLiuShe
9dcad804615412e85de31797c0a0afb84135918f
[ "MIT" ]
1
2019-05-24T05:08:06.000Z
2019-05-24T05:08:06.000Z
#include "Index.h" Index::Index(std::string new_name, std::string new_table_name, std::string new_attr_name, attr_type new_type): name(new_name), table_name(new_table_name), attr_name(new_attr_name), type(new_type) { } Index::~Index() { }
18.769231
110
0.745902
76391c5d2e93b899fb7a50edf3fecfa8d866424c
1,462
cxx
C++
doctype/solarmail.cxx
re-Isearch/re-Isearch
f2a2012c1814b0940a6004b6186a5e6896c1135a
[ "BSD-4-Clause-UC", "Apache-2.0" ]
2
2022-02-05T17:48:29.000Z
2022-02-06T15:25:04.000Z
doctype/solarmail.cxx
re-Isearch/re-Isearch
f2a2012c1814b0940a6004b6186a5e6896c1135a
[ "BSD-4-Clause-UC", "Apache-2.0" ]
null
null
null
doctype/solarmail.cxx
re-Isearch/re-Isearch
f2a2012c1814b0940a6004b6186a5e6896c1135a
[ "BSD-4-Clause-UC", "Apache-2.0" ]
1
2022-03-30T20:14:00.000Z
2022-03-30T20:14:00.000Z
static const char RCS_Id[]="$Id: solarmail.cxx,v 1.1 2007/05/15 15:47:29 edz Exp $"; /* ######################################################################## Usenet News Folder Doctype Basis Systeme netzwerk Brecherspitzstr. 8 D-81541 Munich, Germany File: sunfolder.cxx Description: Class SOLARMAIL - Sun Solaris 2.x Mailfolder Document Type Version: $Revision: 1.1 $ Created: Sun Dec 24 23:11:21 MET 1995 Author: Edward C. Zimmermann <edz@nonmonotonic.net> Modified: Sun Dec 24 23:11:22 MET 1995 Last maintained by: Edward C. Zimmermann <edz@nonmonotonic.net> (c) Copyright 1995 Basis Systeme netzwerk, Munich ######################################################################## Note: This is really just an alias for mailfolder.... ####################################################################### */ #include "solarmail.hxx" SOLARMAIL::SOLARMAIL (PIDBOBJ DbParent): MAILFOLDER::MAILFOLDER (DbParent) { } void SOLARMAIL::ParseRecords (const RECORD& FileRecord) { #if BSN_EXTENSIONS RECORD Record (FileRecord); // Easy way #else /* CNIDR must do it the hard way! (see above ) */ RECORD Record; STRING s; FileRecord.GetPath(&s); Record.SetPath( s ); FileRecord.GetFileName(&s); Record.SetFileName( s ); FileRecord.GetDocumentType(&s); #endif Record.SetDocumentType ("MAILFOLDER"); MAILFOLDER::ParseRecords (Record); } SOLARMAIL::~SOLARMAIL () { }
26.107143
84
0.589603
763e5b8db9c5b5d782ba03570f8a664a402f751e
4,163
hpp
C++
openscenario/openscenario_interpreter/include/openscenario_interpreter/utility/execution_timer.hpp
TakahiroNISHIOKA/scenario_simulator_v2
949a46a64a26d17413c2586577e1f3a5ba41161e
[ "Apache-2.0" ]
null
null
null
openscenario/openscenario_interpreter/include/openscenario_interpreter/utility/execution_timer.hpp
TakahiroNISHIOKA/scenario_simulator_v2
949a46a64a26d17413c2586577e1f3a5ba41161e
[ "Apache-2.0" ]
null
null
null
openscenario/openscenario_interpreter/include/openscenario_interpreter/utility/execution_timer.hpp
TakahiroNISHIOKA/scenario_simulator_v2
949a46a64a26d17413c2586577e1f3a5ba41161e
[ "Apache-2.0" ]
null
null
null
// Copyright 2015-2020 Tier IV, Inc. 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. #ifndef OPENSCENARIO_INTERPRETER__UTILITY__EXECUTION_TIMER_HPP_ #define OPENSCENARIO_INTERPRETER__UTILITY__EXECUTION_TIMER_HPP_ #include <chrono> #include <cmath> #include <functional> #include <unordered_map> namespace openscenario_interpreter { inline namespace utility { template <typename Clock = std::chrono::system_clock> class ExecutionTimer { class Statistics { std::int64_t ns_max = 0; std::int64_t ns_min = std::numeric_limits<std::int64_t>::max(); std::int64_t ns_sum = 0; std::int64_t ns_square_sum = 0; int count = 0; public: template <typename Duration> auto add(Duration diff) -> void { std::int64_t diff_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(diff).count(); count++; ns_max = std::max(ns_max, diff_ns); ns_min = std::min(ns_max, diff_ns); ns_sum += diff_ns; ns_square_sum += std::pow(diff_ns, 2); } template <typename T> auto max() const { return std::chrono::duration_cast<T>(std::chrono::nanoseconds(ns_max)); } template <typename T> auto min() const { return std::chrono::duration_cast<T>(std::chrono::nanoseconds(ns_min)); } template <typename T> auto mean() const { return std::chrono::duration_cast<T>(std::chrono::nanoseconds(ns_sum / count)); } template <typename T> auto standardDeviation() const { std::int64_t mean_of_square = ns_square_sum / count; std::int64_t square_of_mean = std::pow(ns_sum / count, 2); std::int64_t var = mean_of_square - square_of_mean; double standard_deviation = std::sqrt(var); return std::chrono::duration_cast<T>( std::chrono::nanoseconds(static_cast<std::int64_t>(standard_deviation))); } friend auto operator<<(std::ostream & os, const Statistics & statistics) -> std::ostream & { using namespace std::chrono; return os << "mean = " << statistics.template mean<milliseconds>().count() << " ms, " << "max = " << statistics.template max<milliseconds>().count() << " ms, " << "standard deviation = " << statistics.template standardDeviation<milliseconds>().count() / 1000.0 << " ms"; } }; std::unordered_map<std::string, Statistics> statistics_map; public: template <typename Thunk, typename... Ts> auto invoke(const std::string & tag, Thunk && thunk) -> typename std::enable_if< std::is_same<typename std::result_of<Thunk()>::type, void>::value, typename Clock::duration>::type { const auto begin = Clock::now(); thunk(); const auto end = Clock::now(); statistics_map[tag].add(end - begin); return end - begin; } template <typename Thunk, typename... Ts> auto invoke(const std::string & tag, Thunk && thunk) -> typename std::enable_if< std::is_same<typename std::result_of<Thunk()>::type, bool>::value, typename Clock::duration>::type { const auto begin = Clock::now(); const auto result = thunk(); const auto end = Clock::now(); if (result) { statistics_map[tag].add(end - begin); } return end - begin; } auto clear() { statistics_map.clear(); } auto getStatistics(const std::string & tag) -> const auto & { return statistics_map[tag]; } auto begin() const { return statistics_map.begin(); } auto end() const { return statistics_map.end(); } }; } // namespace utility } // namespace openscenario_interpreter #endif // OPENSCENARIO_INTERPRETER__UTILITY__EXECUTION_TIMER_HPP_
29.111888
99
0.664425
76427c417c94cb5460cf6ef17f43fbcd44277d62
293
hpp
C++
src/resources/resource.hpp
ifamakes/sidhe-cpp
ce660872fa0c9eba7d41357ab330410a397f59eb
[ "CC0-1.0" ]
null
null
null
src/resources/resource.hpp
ifamakes/sidhe-cpp
ce660872fa0c9eba7d41357ab330410a397f59eb
[ "CC0-1.0" ]
null
null
null
src/resources/resource.hpp
ifamakes/sidhe-cpp
ce660872fa0c9eba7d41357ab330410a397f59eb
[ "CC0-1.0" ]
null
null
null
#pragma once #include <iostream> #include <string> struct Resource { virtual ~Resource() = default; virtual void print() const = 0; }; struct File : Resource { std::string_view filename; virtual void print() const override { std::cout << __PRETTY_FUNCTION__ << std::endl; }; };
19.533333
50
0.675768
76442cf857d809354d445c7ecfb216a91d327ab3
15,115
cpp
C++
src/server.cpp
Subsentient/nexus
719cca618afe8729522607ed35e9415d76582347
[ "Unlicense" ]
2
2016-03-17T21:25:51.000Z
2021-09-02T13:20:23.000Z
src/server.cpp
Subsentient/nexus
719cca618afe8729522607ed35e9415d76582347
[ "Unlicense" ]
1
2018-03-04T18:55:48.000Z
2018-03-07T00:19:37.000Z
src/server.cpp
Subsentient/nexus
719cca618afe8729522607ed35e9415d76582347
[ "Unlicense" ]
2
2016-03-19T00:31:27.000Z
2017-01-09T23:41:32.000Z
/*NEXUS IRC session BNC, by Subsentient. This software is public domain.*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <ctype.h> #ifdef WIN #include <winsock2.h> #else #include <fcntl.h> #endif #include <list> #include <string> #include "server.h" #include "netcore.h" #include "config.h" #include "nexus.h" #include "state.h" #include "scrollback.h" #include "irc.h" #include "substrings/substrings.h" /**This file has our IRC pseudo-server that we run ourselves and its interaction with clients.**/ //Globals std::list<struct ClientListStruct> ClientListCore; struct ClientListStruct *CurrentClient, *PreviousClient; //Prototypes namespace Server { static void SendChannelNamesList(const class ChannelList *const Channel, struct ClientListStruct *Client); static void SendChannelRejoin(const class ChannelList *const Channel, const int ClientDescriptor); static void SendIRCWelcome(const int ClientDescriptor); } //Functions struct ClientListStruct *Server::ClientList::Lookup(const int Descriptor) { std::list<struct ClientListStruct>::iterator Iter = ClientListCore.begin(); for (; Iter != ClientListCore.end(); ++Iter) { if (Iter->Descriptor == Descriptor) { return &*Iter; //Not used to doing this kind of weird shit. That'd seem really stupid and redundant in C, where Iter would be a pointer. } } return NULL; } struct ClientListStruct *Server::ClientList::Add(const struct ClientListStruct *const InStruct) { ClientListCore.push_front(*InStruct); return &*ClientListCore.begin(); } void Server::ClientList::Shutdown(void) { ClientListCore.clear(); PreviousClient = NULL; CurrentClient = NULL; } bool Server::ClientList::Del(const int Descriptor) { std::list<struct ClientListStruct>::iterator Iter = ClientListCore.begin(); for (; Iter != ClientListCore.end(); ++Iter) { if (Iter->Descriptor == Descriptor) { if (&*Iter == CurrentClient) CurrentClient = reinterpret_cast<struct ClientListStruct*>(-1); if (&*Iter == PreviousClient) PreviousClient = reinterpret_cast<struct ClientListStruct*>(-1); ClientListCore.erase(Iter); return true; } } return false; } bool Server::ForwardToAll(const char *const InStream) { //This function sends the provided text stream to all clients. Very simple. std::list<struct ClientListStruct>::iterator Iter = ClientListCore.begin(); for (; Iter != ClientListCore.end(); ++Iter) { Iter->SendLine(InStream); } return true; } bool Server::NukeClient(const int Descriptor) { //Close the descriptor, remove from select() tracking, and purge him from our minds. struct ClientListStruct *Client = Server::ClientList::Lookup(Descriptor); if (!Client) return false; Net::Close(Client->Descriptor); NEXUS::DescriptorSet_Del(Client->Descriptor); Server::ClientList::Del(Client->Descriptor); return true; } void Server::SendQuit(const int Descriptor, const char *const Reason) { //Tells all clients or just one client to quit std::list<struct ClientListStruct>::iterator Iter = ClientListCore.begin(); char OutBuf[2048]; for (; Iter != ClientListCore.end(); ++Iter) { //If not on "everyone" mode we check if the descriptor matches. if (Descriptor != -1 && Descriptor != Iter->Descriptor) continue; if (Reason) { snprintf(OutBuf, sizeof OutBuf, ":%s!%s@%s QUIT :%s\r\n", IRCConfig.Nick, Iter->Ident, Iter->IP, Reason); } else { snprintf(OutBuf, sizeof OutBuf, ":%s!%s@%s QUIT :Disconnected from NEXUS.\r\n", IRCConfig.Nick, Iter->Ident, Iter->IP); } try { Net::Write(Iter->Descriptor, OutBuf, strlen(OutBuf)); } catch (...) {} } } static void Server::SendIRCWelcome(const int ClientDescriptor) { char OutBuf[2048]; struct ClientListStruct *Client = Server::ClientList::Lookup(ClientDescriptor); std::map<std::string, ChannelList>::iterator Iter = ChannelListCore.begin(); const int ClientCount = ClientListCore.size(); if (!Client) return; //First thing we send is our greeting, telling them they're connected OK. snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 001 %s :NEXUS is forwarding you to server %s:%hu\r\n", IRCConfig.Nick, IRCConfig.Server, IRCConfig.PortNum); //Putting IRCConfig.Nick here is the same as sending a NICK command. Client->SendLine(OutBuf); //Tell them to join all channels we are already in. for (; Iter != ChannelListCore.end(); ++Iter) { Server::SendChannelRejoin(&Iter->second, Client->Descriptor); } //Count clients for our next cool little trick. /**Send a MOTD.**/ //Send the beginning. snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 375 %s :Welcome to NEXUS " NEXUS_VERSION ". You are being forwarded to \"%s:%hu\".\r\n", IRCConfig.Nick, IRCConfig.Server, IRCConfig.PortNum); Client->SendLine(OutBuf); //For dumb bots that connect, make it abundantly clear what their nick should be. snprintf(OutBuf, sizeof OutBuf, ":%s!%s@%s NICK :%s\r\n", Client->OriginalNick, Client->Ident, Client->IP, IRCConfig.Nick); Client->SendLine(OutBuf); //Send the middle. snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 372 %s :There are currently %d other instances connected to this NEXUS server.\r\n", IRCConfig.Nick, ClientCount - 1); Client->SendLine(OutBuf); //Send the end. snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 376 %s :End of MOTD.\r\n", IRCConfig.Nick); Client->SendLine(OutBuf); //Send all scrollback. Scrollback::SendAllToClient(Client); } static void Server::SendChannelNamesList(const class ChannelList *const Channel, struct ClientListStruct *Client) { char OutBuf[2048]; unsigned Ticker = 1; std::map<std::string, struct UserStruct> &UserListRef = Channel->GetUserList(); std::map<std::string, struct UserStruct>::iterator Iter = UserListRef.begin(); SendBegin: std::string OutString = std::string(":" NEXUS_FAKEHOST " 353 ") + IRCConfig.Nick + " = " + Channel->GetChannelName() + " :"; for (Ticker = 1; Iter != UserListRef.end(); ++Iter, ++Ticker) { const struct UserStruct *Worker = &Iter->second; //Reconstitute the mode flag for this user. const char Sym = State::UserModes_Get_Mode2Symbol(Worker->Modes); if (Sym) { OutString += Sym; } OutString += Worker->Nick; std::map<std::string, struct UserStruct>::iterator TempIter = Iter; ++TempIter; if (Ticker == 20 || TempIter == UserListRef.end()) { OutString += "\r\n"; Client->SendLine(OutString.c_str()); if (TempIter != UserListRef.end()) { goto SendBegin; } } else { OutString += " "; } } snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 366 %s %s :End of /NAMES list.\r\n", IRCConfig.Nick, Channel->GetChannelName()); Client->SendLine(OutBuf); } static void Server::SendChannelRejoin(const class ChannelList *const Channel, const int ClientDescriptor) { //Sends the list of channels we are in to the client specified. char OutBuf[2048]; struct ClientListStruct *Client = Server::ClientList::Lookup(ClientDescriptor); if (!Client) return; //Send the join command. snprintf(OutBuf, sizeof OutBuf, ":%s!%s@%s JOIN %s\r\n", IRCConfig.Nick, Client->Ident, Client->IP, Channel->GetChannelName()); Client->SendLine(OutBuf); //Send the topic and the setter of the topic. if (*Channel->GetTopic() && *Channel->GetWhoSetTopic() && Channel->GetWhenSetTopic() != 0) { snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 332 %s %s :%s\r\n", IRCConfig.Nick, Channel->GetChannelName(), Channel->GetTopic()); Client->SendLine(OutBuf); snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 333 %s %s %s %u\r\n", IRCConfig.Nick, Channel->GetChannelName(), Channel->GetWhoSetTopic(), Channel->GetWhenSetTopic()); Client->SendLine(OutBuf); } //Send list of users. Server::SendChannelNamesList(Channel, Client); } struct ClientListStruct *Server::AcceptLoop(void) { struct ClientListStruct TempClient; char InBuf[2048]; struct ClientListStruct *Client = NULL; bool UserProvided = false, NickProvided = false; bool PasswordProvided = false; if (!Net::AcceptClient(&TempClient.Descriptor, TempClient.IP, sizeof TempClient.IP)) { //No client. return NULL; } ///Apparently there is a client. Client = Server::ClientList::Add(&TempClient); //Store their information. /**Continuously try to read their replies until we get them.**/ while (!UserProvided || !NickProvided) { //Wait for their greeting. const bool NetReadReturn = Net::Read(Client->Descriptor, InBuf, sizeof InBuf, true); if (!NetReadReturn) { Server::NukeClient(Client->Descriptor); return NULL; } //Does it start with USER? if (!strncmp(InBuf, "USER", sizeof "USER" - 1) || !strncmp(InBuf, "user", sizeof "user" - 1)) { //This information is needed to fool the IRC clients. const char *TWorker = InBuf + sizeof "USER"; unsigned Inc = 0; //If we want a password, WE WANT A PASSWORD. You're supposed to send PASS first, dunce! if (*NEXUSConfig.ServerPassword && !PasswordProvided) { Server::NukeClient(Client->Descriptor); return NULL; } while (*TWorker == ' ' || *TWorker == ':') ++TWorker; for (; TWorker[Inc] != ' ' && TWorker[Inc] != '\0' && Inc < sizeof Client->Ident - 1; ++Inc) { //Copy in the ident they sent us. Client->Ident[Inc] = TWorker[Inc]; } Client->Ident[Inc] = '\0'; UserProvided = true; } else if (!strncmp(InBuf, "NICK", sizeof "NICK" - 1) || !strncmp(InBuf, "nick", sizeof "nick" - 1)) { const char *TWorker = InBuf + sizeof "nick"; //If we want a password, WE WANT A PASSWORD. if (*NEXUSConfig.ServerPassword && !PasswordProvided) { Net::Close(Client->Descriptor); return NULL; } while (*TWorker == ' ' || *TWorker == ':') ++TWorker; strncpy(Client->OriginalNick, TWorker, sizeof Client->OriginalNick - 1); //Copy in their chosen nick. Client->OriginalNick[sizeof Client->OriginalNick - 1] = '\0'; NickProvided = true; } else if (!strncmp(InBuf, "PASS", sizeof "PASS" - 1)) { const char *TW = InBuf + sizeof "PASS"; if (!*NEXUSConfig.ServerPassword) { //We don't NEED a password. Just ignore this. continue; } while (*TW == ' ') ++TW; if (!strcmp(TW, NEXUSConfig.ServerPassword)) PasswordProvided = true; else { //Wrong password. Net::Close(Client->Descriptor); return NULL; } } continue; } //Time to welcome them. Server::SendIRCWelcome(Client->Descriptor); //Return the client we found. return Client; } enum ServerMessageType Server::GetMessageType(const char *InStream_) { //Another function torn out of aqu4bot. const char *InStream = InStream_; char Command[32]; unsigned Inc = 0; for (; InStream[Inc] != ' ' && InStream[Inc] != '\0' && Inc < sizeof Command - 1; ++Inc) { /*Copy in the command.*/ Command[Inc] = toupper(InStream[Inc]); } Command[Inc] = '\0'; /*Time for the comparison.*/ if (!strcmp(Command, "PRIVMSG")) return SERVERMSG_PRIVMSG; else if (!strcmp(Command, "NOTICE")) return SERVERMSG_NOTICE; else if (!strcmp(Command, "MODE")) return SERVERMSG_MODE; else if (!strcmp(Command, "JOIN")) return SERVERMSG_JOIN; else if (!strcmp(Command, "PART")) return SERVERMSG_PART; else if (!strcmp(Command, "PING")) return SERVERMSG_PING; else if (!strcmp(Command, "PONG")) return SERVERMSG_PONG; else if (!strcmp(Command, "NICK")) return SERVERMSG_NICK; else if (!strcmp(Command, "QUIT")) return SERVERMSG_QUIT; else if (!strcmp(Command, "KICK")) return SERVERMSG_KICK; else if (!strcmp(Command, "KILL")) return SERVERMSG_KILL; else if (!strcmp(Command, "INVITE")) return SERVERMSG_INVITE; else if (!strcmp(Command, "TOPIC")) return SERVERMSG_TOPIC; else if (!strcmp(Command, "NAMES")) return SERVERMSG_NAMES; else if (!strcmp(Command, "WHO")) return SERVERMSG_WHO; else return SERVERMSG_UNKNOWN; } bool ClientListStruct::Ping() { std::string Out = "PING :" NEXUS_FAKEHOST "\r\n"; bool RetVal = false; #ifdef WIN u_long Value = 1; ioctlsocket(this->Descriptor, FIONBIO, &Value); #else fcntl(this->Descriptor, F_SETFL, O_NONBLOCK); //Set nonblocking. Necessary for our single-threaded model. #endif //WIN try { Net::Write(this->Descriptor, Out.c_str(), Out.length()); } catch (Net::Errors::Any) { goto End; } RetVal = true; this->PingSentTime = time(NULL); this->WaitingForPing = true; End: #ifdef WIN Value = 0; ioctlsocket(this->Descriptor, FIONBIO, &Value); #else fcntl(this->Descriptor, F_SETFL, 0); #endif //WIN return RetVal; } bool ClientListStruct::CompletePing(void) { if (!this->WaitingForPing) return false; this->WaitingForPing = false; this->PingRecvTime = time(NULL); return true; } ClientListStruct::ClientListStruct(const int InDescriptor, const char *IP, const char *OriginalNick, const char *Ident) : WaitingForPing(false), PingSentTime(0), PingRecvTime(time(NULL)), Descriptor(InDescriptor) { //PingRecvTime is initialized with a real time so that the server doesn't send pings instantly. SubStrings.Copy(this->IP, IP, sizeof this->IP); SubStrings.Copy(this->OriginalNick, OriginalNick, sizeof this->OriginalNick); SubStrings.Copy(this->Ident, Ident, sizeof this->Ident); } ClientListStruct::ClientListStruct(void) : WaitingForPing(false), PingSentTime(0), PingRecvTime(time(NULL)), Descriptor(0) { } void ClientListStruct::SendNxCtlPrivmsg(const char *const String) { std::string Out = std::string(":" CONTROL_NICKNAME "!NEXUS@NEXUS PRIVMSG ") + IRCConfig.Nick + " :" + String; if (!SubStrings.EndsWith("\r\n", Out.c_str())) { //SendLine() does the same thing, but we're aiming for consistency and safety. Out += "\r\n"; } this->SendLine(Out.c_str()); } void ClientListStruct::SendLine(const char *const String) { std::string Out = String; if (!SubStrings.EndsWith("\r\n", Out.c_str())) { Out += "\r\n"; } this->WriteQueue.push(Out); } bool ClientListStruct::FlushSendBuffer(void) { if (this->WriteQueue.empty()) return false; while (!this->WriteQueue.empty()) { if (!this->WriteQueue_Pop()) return false; } return true; } bool ClientListStruct::WriteQueue_Pop(void) { if (this->WriteQueue.empty()) return false; bool RetVal = false; std::string Out = this->WriteQueue.front(); #ifdef WIN u_long Value = 1; ioctlsocket(this->Descriptor, FIONBIO, &Value); #else fcntl(this->Descriptor, F_SETFL, O_NONBLOCK); //Set nonblocking. Necessary for our single-threaded model. #endif //WIN try { Net::Write(this->Descriptor, Out.c_str(), Out.length()); } catch (Net::Errors::BlockingError Err) { if (Err.BytesSentBeforeBlocking > 0) { std::string &Str = this->WriteQueue.front(); std::string New = Str; Str = New.c_str() + Err.BytesSentBeforeBlocking; } goto End; } catch (Net::Errors::Any) { //We will probably get Net::Errors::BlockingError. goto End; } RetVal = true; this->WriteQueue.pop(); End: #ifdef WIN Value = 0; ioctlsocket(this->Descriptor, FIONBIO, &Value); #else fcntl(this->Descriptor, F_SETFL, 0); #endif //WIN return RetVal; }
27.836096
139
0.691631
764d3fec3b50869b29975839adf3de55ea856e79
3,491
cpp
C++
dp0.cpp
lordblendi/cpp-deklarativ-programozas-hf
85d875d9eb35f1dcc0275439f8284993b556143f
[ "MIT" ]
null
null
null
dp0.cpp
lordblendi/cpp-deklarativ-programozas-hf
85d875d9eb35f1dcc0275439f8284993b556143f
[ "MIT" ]
null
null
null
dp0.cpp
lordblendi/cpp-deklarativ-programozas-hf
85d875d9eb35f1dcc0275439f8284993b556143f
[ "MIT" ]
null
null
null
//segédfgv length_help(L,N) = N+L hossza, N-ben tárolom az addigi elemek számát int length_help(list l, int n){ if(nil == l) return n; return length_help(tl(l), n+1); } //length(L) = L lista hossza int list_length(list l){ return length_help(l, 0); } //insert_nth(L,N,E) L lista olyan másolata, amelyben az L lista n-edik és N+1-edik eleme közé be van szúrva az E elem (a lista számozása 0-tól kezdõdik) list insert_nth(list l, int n, int e){ if(n==0) return cons(e, l); return cons(hd(l), insert_nth(tl(l), n-1, e)); } //number_to_base(n, b, l) az n számot visszaadja az l listában b számrendszerben list number_to_base(int n, int b, list l){ if(n<b) return cons(n, l); return number_to_base((n-n%b)/b, b, cons(n%b, l)); } //number_to_base_ten(l,alap,szorzo,szam, i) az l listát visszadja számként 10-es számrendszerben. b a számrender, amiben a szám van, i hanyadik elemnél tartok, szorzo az aktuális szorzó (=hatványai az alapnak), szam pedig hogy mennyi az aktuális összeg int number_to_base_ten(list l, int alap, int szorzo, int szam, int i){ if(i < 0) return szam; return szam + number_to_base_ten(l, alap, szorzo*alap, nth(l, i)* szorzo, i-1); } //nth(l,n) visszadja az l lista n-edik elemét. a számozás 0-tól kezdõdik int nth(list l, int n){ if(n==0) return hd(l); return nth(tl(l), n-1); } //split(l,r,n) r-ben visszaad minden második számot az l listából. n értékétõl függõen ez lehetnek páros vagy páratlan sorszámú elem list split(list l, list r, int n){ if(n > 1) return split(l, cons(nth(l,n),r),n-2); return cons(nth(l,n), r); } //paratlan(l) visszaadja az L lista páratlan helyiértéken álló elemeit -> megfelelõ n értékkel meghívja a splitet list paratlan(list l){ if((list_length(l) % 2) == 0) return split(l, nil, list_length(l)-2); return split(l, nil, list_length(l)-1); } //paros(l) visszaadja az L lista páros helyiértéken álló elemeit -> megfelelõ n értékkel meghívja a splitet list paros(list l){ if((list_length(l) % 2) == 0) return split(l, nil, list_length(l)-1); return split(l, nil, list_length(l)-2); } //páratlan listába a páros lista elemeit megfordítva beleszúrjuk list beszur(list paratlan, list paros){ return beszur_help(paratlan, paros, list_length(paros)-1, 1); } //beszur_help(paratlan, paros, n, i) segédfgv a beszúrhoz, beszúrja a paratlan lista minden 2. elemének a paros listát visszafelé. n és i tartják számon, hogy melyik listában hanyadik elemnél tartok list beszur_help(list paratlan, list paros, int n, int i){ if(n < 0) return paratlan; return beszur_help(insert_nth(paratlan, i, nth(paros,n)), paros, n-1, i+2); } /* osszekevert(S, A) == SK, ha SK az S szám A alapú összekevert változata (S>0, A>1 egész számok). Egy S szám A alapú összekevertjét úgy kapjuk meg, hogy az S számot felírjuk az A alapú számrendszerben, a számjegyeit egy listával ábrázoljuk, a listát a fentiek szerint átrendezzük, majd a kapott lista elemeit egy A alapú szám jegyeinek tekintve elõállítjuk a keresett értéket. ha a lista hossza <4, akkor felesleges cserélgetnünk, mert csak 1 párosodik szám van, és felesleges cserélgetni */ int osszekevert(const int S, const int A) { if(list_length(number_to_base(S,A,nil))<4) return S; return number_to_base_ten(beszur(paratlan(number_to_base(S,A,nil)), paros(number_to_base(S,A,nil))) , A,1,0,list_length(beszur(paratlan(number_to_base(S,A,nil)), paros(number_to_base(S,A,nil))))-1); }
43.6375
254
0.708393
764f988d3b8a1339b595365a3abbb9929fee84b1
1,955
inl
C++
RTCLI.AOT/Internal/Managed.inl
Team-RTCLI/RTCLI.Runtime
3e888dca4401d7eb9b78aaf02d23b1281d8f0c2a
[ "MIT" ]
19
2020-10-21T02:54:39.000Z
2022-03-31T02:55:48.000Z
RTCLI.AOT/Internal/Managed.inl
Team-RTCLI/RTCLI.Runtime
3e888dca4401d7eb9b78aaf02d23b1281d8f0c2a
[ "MIT" ]
null
null
null
RTCLI.AOT/Internal/Managed.inl
Team-RTCLI/RTCLI.Runtime
3e888dca4401d7eb9b78aaf02d23b1281d8f0c2a
[ "MIT" ]
null
null
null
namespace RTCLI { namespace System { // ******************* Managed<T> *************************// template<typename T> RTCLI_FORCEINLINE Managed<T>::operator const T&() const RTCLI_NOEXCEPT { if(!object) { return null; } return *static_cast<const T*>(object); } template<typename T> RTCLI_FORCEINLINE Managed<T>::operator T&() RTCLI_NOEXCEPT { if(!object) { return null; } return *static_cast<T*>(object); } template<typename T> RTCLI_FORCEINLINE Managed<T>::Managed() RTCLI_NOEXCEPT :object(const_cast<System::Object*>(&RTCLI::nullObject)) { } template<typename T> RTCLI_FORCEINLINE Managed<T>::Managed(nullref_t null) RTCLI_NOEXCEPT :object(const_cast<System::Object*>(&RTCLI::nullObject)) { } template<typename T> RTCLI_FORCEINLINE Managed<T>::Managed(const System::Object& object_) RTCLI_NOEXCEPT { if (object_.isNull()) { object = const_cast<System::Object*>(&RTCLI::nullObject); } else { object = const_cast<System::Object*>(&object_); } } template<typename T> RTCLI_FORCEINLINE T& Managed<T>::Get() RTCLI_NOEXCEPT { return *static_cast<T*>(object); } template<typename T> RTCLI_FORCEINLINE const T& Managed<T>::Get() const RTCLI_NOEXCEPT { return *static_cast<const T*>(object); } template<typename T> RTCLI_FORCEINLINE Managed<T>& Managed<T>::operator=(const System::Object& object_) RTCLI_NOEXCEPT { if(this->object == &object_) { return *this; } if (object_.isNull()) { object = const_cast<System::Object*>(&RTCLI::nullObject); } else { object = const_cast<System::Object*>(&object_); } return *this; } } }
24.4375
101
0.557545
7653a2d7c669c259f2df23c413a6d5a80fe46dde
862
cpp
C++
src/core/resumable.cpp
Anomander/xi
0340675310c41d659762fc3eea48c84ff13b95db
[ "MIT" ]
null
null
null
src/core/resumable.cpp
Anomander/xi
0340675310c41d659762fc3eea48c84ff13b95db
[ "MIT" ]
null
null
null
src/core/resumable.cpp
Anomander/xi
0340675310c41d659762fc3eea48c84ff13b95db
[ "MIT" ]
null
null
null
#include "xi/core/resumable.h" #include "xi/core/abstract_worker.h" namespace xi { namespace core { namespace v2 { thread_local resumable_stat RESUMABLE_STAT; } void resumable::attach_executor(abstract_worker* e) { _worker = e; } void resumable::detach_executor(abstract_worker* e) { assert(_worker == e); _worker = nullptr; } void resumable::unblock() { sleep_hook.unlink(); ready_hook.unlink(); _worker->schedule(this); } void resumable::block() { yield(blocked); } steady_clock::time_point resumable::wakeup_time() { return _wakeup_time; } void resumable::wakeup_time(steady_clock::time_point when) { _wakeup_time = when; } void resumable::sleep_for(nanoseconds ns) { assert(_worker != nullptr); ready_hook.unlink(); _worker->sleep_for(this, ns); block(); } } }
18.73913
62
0.668213
76578b47ce79e8d46b82ba4c2a9ca7a80b451c9b
555
cpp
C++
Solutions-to-OJs/POJ/2000-2999/2719_Faulty_Odometer.cpp
Horizon-Blue/playground
4bd42bfcec60b8e89e127f4784c99f6ba669d359
[ "MIT" ]
2
2016-08-31T19:13:24.000Z
2017-02-18T18:48:31.000Z
Solutions-to-OJs/POJ/2000-2999/2719_Faulty_Odometer.cpp
Horizon-Blue/playground
4bd42bfcec60b8e89e127f4784c99f6ba669d359
[ "MIT" ]
1
2018-12-10T16:32:26.000Z
2018-12-27T19:50:48.000Z
Solutions-to-OJs/POJ/2000-2999/2719_Faulty_Odometer.cpp
Horizon-Blue/playground
4bd42bfcec60b8e89e127f4784c99f6ba669d359
[ "MIT" ]
null
null
null
// Xiaoyan Wang 9/8/2016 #include <iostream> // #include <vector> using namespace std; // arry stores 0, 9^1, 9^2 ... 9^8 int arry[] = {1, 9, 81, 729, 6561, 59049, 531441, 4782969, 43046721/*, 387420489*/}; // input range: 1 to 10^10 int main() { ios::sync_with_stdio(false); int n; while(cin >> n && n) { int result = 0; int digit; for(int i = 0, div = 1; i < 10; ++i, div *= 10) { if((digit = (n % (div * 10)) / div) > 4) --digit; result += digit * arry[i]; } cout << n << ": " << result << "\n"; } cout << flush; return 0; }
22.2
84
0.536937
765928c98b462e252e72220293d6e1eb924600d4
54
hpp
C++
src/boost_geometry_formulas_thomas_inverse.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_geometry_formulas_thomas_inverse.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_geometry_formulas_thomas_inverse.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/geometry/formulas/thomas_inverse.hpp>
27
53
0.833333
7659c3421dbb45aa88d737e948f1bad88733d706
4,001
cpp
C++
ycsbWorkloadCBench.cpp
pfent/exchangeableTransports
a17ddcf99eba16b401df8f0865c1264e11c15c85
[ "MIT" ]
32
2018-12-14T16:54:11.000Z
2022-02-28T13:07:17.000Z
ycsbWorkloadCBench.cpp
pfent/exchangeableTransports
a17ddcf99eba16b401df8f0865c1264e11c15c85
[ "MIT" ]
null
null
null
ycsbWorkloadCBench.cpp
pfent/exchangeableTransports
a17ddcf99eba16b401df8f0865c1264e11c15c85
[ "MIT" ]
5
2020-05-25T07:05:29.000Z
2022-03-05T02:59:38.000Z
#include <include/DomainSocketsTransport.h> #include <include/TcpTransport.h> #include <include/SharedMemoryTransport.h> #include "include/RdmaTransport.h" #include <array> #include <vector> #include <thread> #include "util/bench.h" #include "util/ycsb.h" #include "util/Random32.h" #include "util/doNotOptimize.h" using namespace l5::transport; static constexpr uint16_t port = 1234; static std::string_view ip = "127.0.0.1"; void doRunNoCommunication() { const auto database = YcsbDatabase(); auto rand = Random32(); const auto lookupKeys = generateZipfLookupKeys(ycsb_tx_count * 10); std::array<char, ycsb_field_length> data{}; std::cout << "none, "; bench(ycsb_tx_count * 10, [&] { for (auto lookupKey : lookupKeys) { const auto field = rand.next() % ycsb_field_count; database.lookup(lookupKey, field, data.begin()); DoNotOptimize(data); } }); } template<class Server, class Client> void doRun(bool isClient, std::string connection) { struct ReadMessage { YcsbKey lookupKey; size_t field; }; struct ReadResponse { std::array<char, ycsb_field_length> data; }; if (isClient) { auto client = Client(); for (int i = 0;; ++i) { try { client.connect(connection); break; } catch (...) { std::this_thread::sleep_for(std::chrono::milliseconds(20)); if (i > 1000) throw; } } auto rand = Random32(); const auto lookupKeys = generateZipfLookupKeys(ycsb_tx_count); auto response = ReadResponse{}; for (const auto lookupKey: lookupKeys) { const auto field = rand.next() % ycsb_field_count; const auto message = ReadMessage{lookupKey, field}; client.write(message); client.read(response); DoNotOptimize(response); } } else { // server auto server = Server(connection); const auto database = YcsbDatabase(); server.accept(); bench(ycsb_tx_count, [&] { for (size_t i = 0; i < ycsb_tx_count; ++i) { auto message = ReadMessage{}; server.read(message); auto&[lookupKey, field] = message; auto response = ReadResponse{}; database.lookup(lookupKey, field, reinterpret_cast<char*>(&response)); server.write(response); } }); } } int main(int argc, char **argv) { if (argc < 3) { std::cout << "Usage: " << argv[0] << " <client / server> <[DS|SHM|TCP|RDMA]> <(IP, optional) 127.0.0.1>" << std::endl; return -1; } const auto isClient = std::string_view(argv[1]) == "client"; const auto transportProtocol = std::string_view(argv[2]); if (argc >= 3) ip = argv[2]; std::string connectionString; if (isClient) { connectionString = std::string(ip) + ":" + std::to_string(port); } else { connectionString = std::to_string(port); } if (!isClient) std::cout << "connection, transactions, time, msgps, user, system, total\n"; if (!isClient) doRunNoCommunication(); if (transportProtocol == "DS") { if (!isClient) std::cout << "domainSocket, "; doRun<DomainSocketsTransportServer, DomainSocketsTransportClient>(isClient, "/tmp/testSocket"); } else if (transportProtocol == "SHM") { if (!isClient) std::cout << "shared memory, "; doRun<SharedMemoryTransportServer<>, SharedMemoryTransportClient<>>(isClient, "/tmp/testSocket"); } else if (transportProtocol == "TCP") { if (!isClient) std::cout << "tcp, "; doRun<TcpTransportServer, TcpTransportClient>(isClient, connectionString); } else if (transportProtocol == "RDMA") { if (!isClient) std::cout << "rdma, "; doRun<RdmaTransportServer<>, RdmaTransportClient<>>(isClient, connectionString); } }
34.196581
126
0.593852
766150558a10806e22a6e4d1dc3931ce9f259468
7,410
cpp
C++
examples/06-multithreaded-ROUTERserver-doneRight/server.cpp
cibercitizen1/zmqHelper
8fbfe33ddb2642657ed565ffbb157e174035a52d
[ "MIT" ]
5
2015-01-02T15:54:39.000Z
2021-01-12T18:00:29.000Z
examples/06-multithreaded-ROUTERserver-doneRight/server.cpp
cibercitizen1/zmqHelper
8fbfe33ddb2642657ed565ffbb157e174035a52d
[ "MIT" ]
null
null
null
examples/06-multithreaded-ROUTERserver-doneRight/server.cpp
cibercitizen1/zmqHelper
8fbfe33ddb2642657ed565ffbb157e174035a52d
[ "MIT" ]
2
2017-09-01T19:54:50.000Z
2017-11-09T14:34:11.000Z
// --------------------------------------------------------------- // server.cpp // // multi-threaded router server done right ! // // // -> ROUTER socket -> main-thread -> in-proc socket -> delegate to worker // /* * ON MULTITHREADING WITH ZeroMQ * * Remember: * * Do not use or close sockets except in the thread that created them. * * Don't share ZeroMQ sockets between threads. * ZeroMQ sockets are not threadsafe. * * Isolate data privately within its thread and never share data * in multiple threads. The only exception to this are ZeroMQ contexts, * which are threadsafe. * * Stay away from the classic concurrency mechanisms like as mutexes, * critical sections, semaphores, etc. These are an anti-pattern * in ZeroMQ applications. * * Create one ZeroMQ context at the start of your process, * and pass that to all threads that you want to connect via inproc sockets. * * * * If you need to start more than one proxy in an application, * for example, you will want to run each in their own thread. * It is easy to make the error of creating the proxy frontend * and backend sockets in one thread, and then passing the sockets * to the proxy in another thread. This may appear to work at first * but will fail randomly in real use. * * Some widely used models, despite being the basis for entire * industries, are fundamentally broken, and shared state concurrency * is one of them. Code that wants to scale without limit does it * like the Internet does, by sending messages and sharing nothing * */ /* * * ON CONTEXTS * * ZeroMQ applications always start by creating a context, * and then using that for creating sockets. * In C, it's the zmq_ctx_new() call. * You should create and use exactly one context in your process. * Technically, the context is the container for all sockets * in a single process, and acts as the transport for inproc sockets, * which are the fastest way to connect threads in one process. * If at runtime a process has two contexts, * these are like separate ZeroMQ instances. * If that's explicitly what you want, OK, but otherwise remember: * * Do one zmq_ctx_new() at the start of your main line code, * and one zmq_ctx_destroy() at the end. */ // --------------------------------------------------------------- #include <iostream> #include <future> #include <thread> #include <string> #include <vector> #include <stdlib.h> #include "../../zmqHelper.hpp" // --------------------------------------------------------------- // --------------------------------------------------------------- const std::string PORT_NUMBER = "5580"; // --------------------------------------------------------------- // --------------------------------------------------------------- template <typename ITERABLE> void showLines (const std::string & msg, ITERABLE & it) { std::cout << msg << ": message: |"; for (auto item : it) { std::cout << item << "|"; } std::cout << "\n"; } // --------------------------------------------------------------- // --------------------------------------------------------------- // --------------------------------------------------------------- // --------------------------------------------------------------- class Worker { private: // // // zmq::context_t & sharedContext; // // previous version: the thread in constructor creates // the socket but it is used by the thread in main // // zmqHelper::SocketAdaptor< ZMQ_REP > internalRepSocket; // // // std::thread * theThread = nullptr; // ------------------------------------------------------------- // ------------------------------------------------------------- void main (){ // // a new thread executes this // // // the socket is created and use here // // remember RAII (resourse adquisition is initialization) // zmqHelper::SocketAdaptor< ZMQ_REP > internalRepSocket {sharedContext}; // // // internalRepSocket.connect ("inproc://innerChannel"); // // // std::cout << " ***** worker main " << this << " starts **** \n"; // // // std::vector<std::string> lines; while ( internalRepSocket.receiveText (lines) ) { std::cout << " ** worker: " << this; showLines (" got ", lines); // // do some work ! // sleep (1); // // reply // internalRepSocket.sendText ({"echo of: " + lines[0] + " " + lines[1]}); } // while } // () public: // ------------------------------------------------------------- // ------------------------------------------------------------- Worker ( zmq::context_t & sharedContext_) : sharedContext {sharedContext_} { // // // theThread = new std::thread (&Worker::main, this); } // ------------------------------------------------------------- // ------------------------------------------------------------- ~Worker ( ) { std::cerr << " worker destructor \n"; if (theThread == nullptr) { return; } theThread->join (); delete (theThread); theThread = nullptr; } }; // --------------------------------------------------------------- // --------------------------------------------------------------- int main () { std::cout << " main stars \n"; // // create internal socket to talk to workers // zmqHelper::SocketAdaptor< ZMQ_DEALER > innerDealerSocket; innerDealerSocket.bind ("inproc://innerChannel"); // // 4 workers, you can experience with the // number of workers, timing run.client // Worker wk1 {innerDealerSocket.getContext()}; Worker wk2 {innerDealerSocket.getContext()}; Worker wk3 {innerDealerSocket.getContext()}; Worker wk4 {innerDealerSocket.getContext()}; std::cerr << "main(): workers created\n"; // // create external socket to talk with clients // zmqHelper::SocketAdaptor< ZMQ_ROUTER > outerRouterSocket; outerRouterSocket.bind ("tcp://*:" + PORT_NUMBER); // // for ever ... // while (true) { std::cout << "\n\n while(true): waiting for clients/worker ... \n"; std::vector<std::string> lines; // // wait (blocking poll) for data in either of the sockets // std::vector< zmqHelper::ZmqSocketType * > list = { outerRouterSocket.getZmqSocket(), innerDealerSocket.getZmqSocket() }; zmqHelper::ZmqSocketType * who = zmqHelper::waitForDataInSockets ( list ); // // there is data // if ( who == outerRouterSocket.getZmqSocket() ) { // // from client // if ( outerRouterSocket.receiveText (lines) ) { std::cout << " server: client -> data -> worker \n"; // // delegate to worker // innerDealerSocket.sendText( lines ); } else { std::cout << " outer socket: awoken for nothing ?????????????????\n"; } } else if ( who == innerDealerSocket.getZmqSocket() ) { // // reply from worker // if ( innerDealerSocket.receiveText (lines) ) { std::cout << " server: client <- data <- worker \n"; // // answer the client // outerRouterSocket.sendText( lines ); } else { std::cout << " inner socket: awoken for nothing ?????????????????\n"; } } else { std::cout << " ****** server: error in polling? \n"; } } // while } // main ()
26.183746
82
0.518758
766ef3a32b2fe7e6c2ca3a1dda0abc133df01a2a
3,639
hpp
C++
Includes/Core/CUDA/CUDAStdArray-Impl.hpp
ADMTec/CubbyFlow
c71457fd04ccfaf3ef22772bab9bcec4a0a3b611
[ "MIT" ]
216
2017-01-25T04:34:30.000Z
2021-07-15T12:36:06.000Z
Includes/Core/CUDA/CUDAStdArray-Impl.hpp
ADMTec/CubbyFlow
c71457fd04ccfaf3ef22772bab9bcec4a0a3b611
[ "MIT" ]
323
2017-01-26T13:53:13.000Z
2021-07-14T16:03:38.000Z
Includes/Core/CUDA/CUDAStdArray-Impl.hpp
ADMTec/CubbyFlow
c71457fd04ccfaf3ef22772bab9bcec4a0a3b611
[ "MIT" ]
33
2017-01-25T05:05:49.000Z
2021-06-17T17:30:56.000Z
// This code is based on Jet framework. // Copyright (c) 2018 Doyub Kim // CubbyFlow is voxel-based fluid simulation engine for computer games. // Copyright (c) 2020 CubbyFlow Team // Core Part: Chris Ohk, Junwoo Hwang, Jihong Sin, Seungwoo Yoo // AI Part: Dongheon Cho, Minseo Kim // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #ifndef CUBBYFLOW_CUDA_STD_ARRAY_IMPL_HPP #define CUBBYFLOW_CUDA_STD_ARRAY_IMPL_HPP #ifdef CUBBYFLOW_USE_CUDA namespace CubbyFlow { template <typename T, size_t N> CUDAStdArray<T, N>::CUDAStdArray() { Fill(T{}); } template <typename T, size_t N> template <typename... Args> CUDAStdArray<T, N>::CUDAStdArray(ConstReference first, Args... rest) { static_assert( sizeof...(Args) == N - 1, "Number of arguments should be equal to the size of the vector."); SetAt(0, first, rest...); } template <typename T, size_t N> CUDAStdArray<T, N>::CUDAStdArray(const std::array<T, N>& other) { for (size_t i = 0; i < N; ++i) { m_elements[i] = other[i]; } } template <typename T, size_t N> CUDAStdArray<T, N>::CUDAStdArray(const Vector<T, N>& other) { for (size_t i = 0; i < N; ++i) { m_elements[i] = other[i]; } } template <typename T, size_t N> CUDAStdArray<T, N>::CUDAStdArray(const CUDAStdArray& other) { for (size_t i = 0; i < N; ++i) { m_elements[i] = other[i]; } } template <typename T, size_t N> CUDAStdArray<T, N>::CUDAStdArray(CUDAStdArray&& other) noexcept { for (size_t i = 0; i < N; ++i) { m_elements[i] = std::move(other[i]); } } template <typename T, size_t N> CUDAStdArray<T, N>& CUDAStdArray<T, N>::operator=(const CUDAStdArray& other) { for (size_t i = 0; i < N; ++i) { m_elements[i] = other[i]; } return *this; } template <typename T, size_t N> CUDAStdArray<T, N>& CUDAStdArray<T, N>::operator=(CUDAStdArray&& other) noexcept { for (size_t i = 0; i < N; ++i) { m_elements[i] = std::move(other[i]); } return *this; } template <typename T, size_t N> void CUDAStdArray<T, N>::Fill(ConstReference val) { for (size_t i = 0; i < N; ++i) { m_elements[i] = val; } } template <typename T, size_t N> CUBBYFLOW_CUDA_HOST Vector<T, N> CUDAStdArray<T, N>::ToVector() const { Vector<T, N> vec; for (size_t i = 0; i < N; ++i) { vec[i] = m_elements[i]; } return vec; } template <typename T, size_t N> typename CUDAStdArray<T, N>::Reference CUDAStdArray<T, N>::operator[](size_t i) { return m_elements[i]; } template <typename T, size_t N> typename CUDAStdArray<T, N>::ConstReference CUDAStdArray<T, N>::operator[]( size_t i) const { return m_elements[i]; } template <typename T, size_t N> bool CUDAStdArray<T, N>::operator==(const CUDAStdArray& other) const { for (size_t i = 0; i < N; ++i) { if (m_elements[i] != other.m_elements[i]) { return false; } } return true; } template <typename T, size_t N> bool CUDAStdArray<T, N>::operator!=(const CUDAStdArray& other) const { return !(*this == other); } template <typename T, size_t N> template <typename... Args> void CUDAStdArray<T, N>::SetAt(size_t i, ConstReference first, Args... rest) { m_elements[i] = first; SetAt(i + 1, rest...); } template <typename T, size_t N> template <typename... Args> void CUDAStdArray<T, N>::SetAt(size_t i, ConstReference first) { m_elements[i] = first; } } // namespace CubbyFlow #endif #endif
22.054545
80
0.636439
767284f4e7d34ff0b4e33313398b849527528b74
1,504
cpp
C++
LoveBabbar/12_graph/17_given_sorted_alien_dictionary_find_the_order_of_character.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
LoveBabbar/12_graph/17_given_sorted_alien_dictionary_find_the_order_of_character.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
LoveBabbar/12_graph/17_given_sorted_alien_dictionary_find_the_order_of_character.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
/* link: https://practice.geeksforgeeks.org/problems/alien-dictionary/1 sol: https://www.geeksforgeeks.org/given-sorted-dictionary-find-precedence-characters/ video: https://youtu.be/wMMwRK-w0r4 steps: 1. form graph from given words by comparing (as given they are sorted) 2. so form graph such that word from smaller to larger forms edge 3. find topological sort that's it */ // ----------------------------------------------------------------------------------------------------------------------- // /* TC: O(N + K) + O(N + K), first for forming graph and second for dfs Note that there would be K vertices and at-most (N-1) edges in the graph. */ void dfs(int curr, string& ans, vector<int>& vis, vector<vector<int>>& g) { vis[curr] = 1; for (auto i : g[curr]) { if (!vis[i]) { dfs(i, ans, vis, g); } } ans += (curr + 'a'); } string findOrder(string dict[], int N, int K) { vector<vector<int>> g(K); for (int i = 0;i < N - 1;i++) { string a = dict[i]; string b = dict[i + 1]; for (int j = 0;j < min(a.size(), b.size());j++) { if (a[j] != b[j]) { g[a[j] - 'a'].push_back(b[j] - 'a'); break; } } } vector<int> vis(K, 0); string ans = ""; for (int i = 0;i < K;i++) { if (!vis[i]) { dfs(i, ans, vis, g); } } reverse(ans.begin(), ans.end()); return ans; }
25.066667
125
0.470745
7673c1cf27f096c1ee32b3c97b316fb1166fc777
109
hpp
C++
PlanetaMatchMakerServer/source/server/server_constants.hpp
InstytutXR/PlanetaMatchMaker
4bf7503c031aea467c191c3a0d14c6dd58354f99
[ "MIT" ]
6
2019-08-15T09:48:55.000Z
2021-07-25T14:40:59.000Z
PlanetaMatchMakerServer/source/server/server_constants.hpp
InstytutXR/PlanetaMatchMaker
4bf7503c031aea467c191c3a0d14c6dd58354f99
[ "MIT" ]
43
2019-12-25T14:54:52.000Z
2022-02-24T17:22:48.000Z
PlanetaMatchMakerServer/source/server/server_constants.hpp
InstytutXR/PlanetaMatchMaker
4bf7503c031aea467c191c3a0d14c6dd58354f99
[ "MIT" ]
2
2020-05-06T20:14:44.000Z
2020-06-02T21:21:10.000Z
#pragma once #include "data/data_constants.hpp" namespace pgl { constexpr version_type api_version = 0; }
13.625
40
0.761468
7675a01a3ca635adcf7702c2fc5d040ba1edee18
14,146
cc
C++
src/AutoPolyLine.cc
uli2k/auto-polyline
2f2b52dbd86e505d89894f9a98753b7e14cae783
[ "MIT" ]
2
2017-08-28T06:13:16.000Z
2017-09-04T02:28:27.000Z
src/AutoPolyLine.cc
uli2k/auto-polyline
2f2b52dbd86e505d89894f9a98753b7e14cae783
[ "MIT" ]
null
null
null
src/AutoPolyLine.cc
uli2k/auto-polyline
2f2b52dbd86e505d89894f9a98753b7e14cae783
[ "MIT" ]
null
null
null
/*---------------------------------------------------------------------------------------- * Copyright (c) Jinan Tony Robotics Co., Ltd. All rights reserved. * Author: Sun Liang * 带权的二维地图路径搜索方法 *--------------------------------------------------------------------------------------*/ #include "AutoPolyLine.h" namespace autopolyline { using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; using v8::Number; using v8::Object; using v8::Persistent; using v8::String; using v8::Value; Persistent<Function> AutoPolyLine::constructor; AutoPolyLine::AutoPolyLine(int width, int height) { if (width <= 0 || height <= 0 || width > 45000 || height > 45000) return; int size = width * height; this->width = width; this->height = height; this->BorderWidth = 0; this->BorderResistance = 1; this->map = new char[size]; this->travel = new char[size]; this->BoundaryBuf = new int[(width + height) * 2][2]; this->BoundaryStep = new char[(width + height) * 2][2]; } AutoPolyLine::~AutoPolyLine() { if (this->BoundaryStep) delete[] this->BoundaryStep; if (this->BoundaryBuf) delete[] this->BoundaryBuf; if (this->travel) delete[] this->travel; if (this->map) delete[] this->map; } void AutoPolyLine::InitSize(int width, int height) { if (width <= 0 || height <= 0 || width > 45000 || height > 45000) return; int size = width * height; this->width = width; this->height = height; delete[] this->BoundaryStep; delete[] this->BoundaryBuf; delete[] this->travel; delete[] this->map; this->map = new char[size]; this->travel = new char[size]; this->BoundaryBuf = new int[(width + height) * 2][2]; this->BoundaryStep = new char[(width + height) * 2][2]; } void AutoPolyLine::InitMap() { for (int i = 0; i < this->width * this->height; i++) // 全部设置为可通过 this->map[i] = 1; } void AutoPolyLine::SetBorder(int width, char resistance) { if (width < 0) width = 0; this->BorderWidth = width; if (resistance < 1) resistance = 1; this->BorderResistance = resistance; } bool AutoPolyLine::FixRect(int *x, int *y, int *width, int *height) { if (*x >= this->width || *x + *width <= 0 || *y >= this->height || *y + *height <= 0) return false; // 位置在地图外 if (*width <= 0 || *height <= 0) return false; // 非法尺寸 if (*x < 0) // 超出部分裁剪 { *width += *x; *x = 0; } if (*width > this->width - *x) *width = this->width - *x; if (*y < 0) { *height += *y; *y = 0; } if (*height > this->height - *y) *height = this->height - *y; return true; } void AutoPolyLine::FillRect(int x, int y, int width, int height, char val) { char *p = this->map + x + y * this->width; while (height > 0) { x = width; while (x > 0) { if (*p) *p = val; p++; x--; } p += this->width - width; height--; } } void AutoPolyLine::AddObstacleRect(int x, int y, int width, int height, char resistance) { if (!this->FixRect(&x, &y, &width, &height)) return; this->FillRect(x, y, width, height, resistance); int bx, by, bw, bh; // 左侧边框 bx = x - this->BorderWidth; by = y; bw = this->BorderWidth; bh = height; if (this->FixRect(&bx, &by, &bw, &bh)) this->FillRect(bx, by, bw, bh, this->BorderResistance); // 右侧边框 bx = x + width; by = y; bw = this->BorderWidth; bh = height; if (this->FixRect(&bx, &by, &bw, &bh)) this->FillRect(bx, by, bw, bh, this->BorderResistance); // 上方边框 bx = x - this->BorderWidth; by = y - this->BorderWidth; bw = width + this->BorderWidth * 2; bh = this->BorderWidth; if (this->FixRect(&bx, &by, &bw, &bh)) this->FillRect(bx, by, bw, bh, this->BorderResistance); // 下方边框 bx = x - this->BorderWidth; by = y + height; bw = width + this->BorderWidth * 2; bh = this->BorderWidth; if (this->FixRect(&bx, &by, &bw, &bh)) this->FillRect(bx, by, bw, bh, this->BorderResistance); } void AutoPolyLine::AddPolyLineBorder(const int point[], int count) { for (int i = 2; i < count * 2; i += 2) { int bx, by, bw, bh; // 计算线的方向 if (point[i] == point[i - 2]) // 竖线 { if (point[i + 1] < point[i - 1]) { by = point[i + 1] - this->BorderWidth; bh = point[i - 1] - by + 1 + this->BorderWidth; } else { by = point[i - 1] - this->BorderWidth; bh = point[i + 1] - by + 1 + this->BorderWidth; } bx = point[i] - this->BorderWidth; bw = 1 + this->BorderWidth * 2; } else // 横线 { if (point[i] < point[i - 2]) { bx = point[i] - this->BorderWidth; bw = point[i - 2] - bx + 1 + this->BorderWidth; } else { bx = point[i - 2] - this->BorderWidth; bw = point[i] - bx + 1 + this->BorderWidth; } by = point[i + 1] - this->BorderWidth; bh = 1 + this->BorderWidth * 2; } if (this->FixRect(&bx, &by, &bw, &bh)) this->FillRect(bx, by, bw, bh, this->BorderResistance); } } int AutoPolyLine::CreatePolyLine(const int dirx[], const int diry[], int x1, int y1, int x2, int y2) { if (x1 < 0 || x1 >= this->width || y1 < 0 || y1 >= this->height) // 起始结束点不在区域内 return 0; if (x2 < 0 || x2 >= this->width || y2 < 0 || y2 >= this->height) return 0; if (x1 == x2 && y1 == y2) // 起始结束点重合 return 0; if (this->map[x1 + y1 * this->width] == 0 || this->map[x2 + y2 * this->width] == 0) // 起始点或结束点不可通过 return 0; for (int i = 0; i < this->width * this->height; i++) // 全部设置为未搜索 this->travel[i] = -1; this->travel[x1 + y1 * this->width] = 4; // 设置起始点,4可区分任何方向,表示端点 this->BoundaryBuf[0][0] = x1 + y1 * this->width; this->BoundaryStep[0][0] = this->map[x1 + y1 * this->width]; int BbCount[2] = {1}; // 边界点计数器 int step = 0; // 计步器 for (;;) { for (int i = 0; i < BbCount[step % 2]; i++) // 遍历已搜索到的边界点 if (this->BoundaryStep[i][step % 2] == 0) // 步数清空,可向四周继续搜索 for (int dir = 0; dir < 4; dir++) // 4个方向 { int x = this->BoundaryBuf[i][step % 2] % this->width + dirx[dir]; int y = this->BoundaryBuf[i][step % 2] / this->width + diry[dir]; if (x >= 0 && x < width && y >= 0 && y < height) { int idx = x + y * this->width; if (this->map[idx] > 0 && this->travel[idx] < 0) // 可以通过且尚未搜索过 { this->travel[idx] = dir; // 标记来时方向 this->BoundaryBuf[BbCount[(step + 1) % 2]][(step + 1) % 2] = idx; // 放入另一个边界点缓冲区中 this->BoundaryStep[BbCount[(step + 1) % 2]][(step + 1) % 2] = this->map[idx] - 1; // 设置步数 BbCount[(step + 1) % 2]++; if (x == x2 && y == y2) // 到达结束点,进行后续处理,回溯路径,标记线边框 { this->BoundaryBuf[0][0] = x; // BoundaryBuf改用于暂存路径 this->BoundaryBuf[0][1] = y; // 加入结束点 BbCount[0] = 1; for (;;) { x -= dirx[dir]; y -= diry[dir]; int tmpdir = this->travel[x + y * this->width]; if (tmpdir != dir) // 方向不一致,出现拐点 { // 加入路径拐点 this->BoundaryBuf[BbCount[0]][0] = x; // BoundaryBuf改用于暂存路径 this->BoundaryBuf[BbCount[0]][1] = y; BbCount[0]++; dir = tmpdir; } if (dir == 4) // 到达端点,返回折线点个数 return BbCount[0]; } } } } } else // 步数不足 { this->BoundaryBuf[BbCount[(step + 1) % 2]][(step + 1) % 2] = this->BoundaryBuf[i][step % 2]; // 放入另一个边界点缓冲区中 this->BoundaryStep[BbCount[(step + 1) % 2]][(step + 1) % 2] = this->BoundaryStep[i][step % 2] - 1; // 步数减1 BbCount[(step + 1) % 2]++; } if (BbCount[step % 2] == 0) // 没有边界点,没有可到达的路径 return 0; BbCount[step % 2] = 0; // 清空边界点缓冲 step++; } } void AutoPolyLine::Init(Local<Object> exports) { Isolate *isolate = exports->GetIsolate(); // 准备构造函数模版 Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New); tpl->SetClassName(String::NewFromUtf8(isolate, "AutoPolyLine")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // 原型 NODE_SET_PROTOTYPE_METHOD(tpl, "InitSize", InitSize); NODE_SET_PROTOTYPE_METHOD(tpl, "InitMap", InitMap); NODE_SET_PROTOTYPE_METHOD(tpl, "SetBorder", SetBorder); NODE_SET_PROTOTYPE_METHOD(tpl, "AddObstacleRect", AddObstacleRect); NODE_SET_PROTOTYPE_METHOD(tpl, "CreatePolyLine", CreatePolyLine); constructor.Reset(isolate, tpl->GetFunction()); exports->Set(String::NewFromUtf8(isolate, "AutoPolyLine"), tpl->GetFunction()); } void AutoPolyLine::New(const FunctionCallbackInfo<Value>& args) { Isolate *isolate = args.GetIsolate(); // 检查传入的参数的个数 if (args.Length() < 2) { // 抛出一个错误并传回到 JavaScript isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments"))); return; } // 检查参数的类型 if (!args[0]->IsNumber() || !args[1]->IsNumber()) { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments"))); return; } if (args.IsConstructCall()) { // 像构造函数一样调用:`new AutoPolyLine(...)` int width = args[0]->IsUndefined() ? 0 : args[0]->Int32Value(); int height = args[1]->IsUndefined() ? 0 : args[1]->Int32Value(); AutoPolyLine *obj = new AutoPolyLine(width, height); obj->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } else { // 像普通方法 `AutoPolyLine(...)` 一样调用,转为构造调用。 const int argc = 2; Local<Value> argv[argc] = { args[0], args[1] }; Local<Context> context = isolate->GetCurrentContext(); Local<Function> cons = Local<Function>::New(isolate, constructor); Local<Object> result = cons->NewInstance(context, argc, argv).ToLocalChecked(); args.GetReturnValue().Set(result); } } void AutoPolyLine::InitSize(const FunctionCallbackInfo<Value>& args) { Isolate *isolate = args.GetIsolate(); // 检查传入的参数的个数 if (args.Length() < 2) { // 抛出一个错误并传回到 JavaScript isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments"))); return; } // 检查参数的类型 if (!args[0]->IsNumber() || !args[1]->IsNumber()) { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments"))); return; } AutoPolyLine *obj = ObjectWrap::Unwrap<AutoPolyLine>(args.Holder()); int width = args[0]->IsUndefined() ? 0 : args[0]->Int32Value(); int height = args[1]->IsUndefined() ? 0 : args[1]->Int32Value(); obj->InitSize(width, height); } void AutoPolyLine::InitMap(const FunctionCallbackInfo<Value>& args) { AutoPolyLine *obj = ObjectWrap::Unwrap<AutoPolyLine>(args.Holder()); obj->InitMap(); } void AutoPolyLine::SetBorder(const FunctionCallbackInfo<Value>& args) { Isolate *isolate = args.GetIsolate(); // 检查传入的参数的个数 if (args.Length() < 2) { // 抛出一个错误并传回到 JavaScript isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments"))); return; } // 检查参数的类型 if (!args[0]->IsNumber() || !args[1]->IsNumber()) { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments"))); return; } AutoPolyLine *obj = ObjectWrap::Unwrap<AutoPolyLine>(args.Holder()); int width = args[0]->IsUndefined() ? 0 : args[0]->Int32Value(); char resistance = args[1]->IsUndefined() ? 0 : args[1]->Int32Value(); obj->SetBorder(width, resistance); } void AutoPolyLine::AddObstacleRect(const FunctionCallbackInfo<Value>& args) { Isolate *isolate = args.GetIsolate(); // 检查传入的参数的个数 if (args.Length() < 5) { // 抛出一个错误并传回到 JavaScript isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments"))); return; } // 检查参数的类型 if (!args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsNumber() || !args[3]->IsNumber() || !args[4]->IsNumber()) { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments"))); return; } AutoPolyLine *obj = ObjectWrap::Unwrap<AutoPolyLine>(args.Holder()); int x = args[0]->IsUndefined() ? 0 : args[0]->Int32Value(); int y = args[1]->IsUndefined() ? 0 : args[1]->Int32Value(); int width = args[2]->IsUndefined() ? 0 : args[2]->Int32Value(); int height = args[3]->IsUndefined() ? 0 : args[3]->Int32Value(); char resistance = args[4]->IsUndefined() ? 0 : args[4]->Int32Value(); obj->AddObstacleRect(x, y, width, height, resistance); } void AutoPolyLine::CreatePolyLine(const FunctionCallbackInfo<Value>& args) { Isolate *isolate = args.GetIsolate(); // 检查传入的参数的个数 if (args.Length() < 4) { // 抛出一个错误并传回到 JavaScript isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments"))); return; } // 检查参数的类型 if (!args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsNumber() || !args[3]->IsNumber()) { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments"))); return; } AutoPolyLine *obj = ObjectWrap::Unwrap<AutoPolyLine>(args.Holder()); int x1 = args[0]->IsUndefined() ? 0 : args[0]->Int32Value(); int y1 = args[1]->IsUndefined() ? 0 : args[1]->Int32Value(); int x2 = args[2]->IsUndefined() ? 0 : args[2]->Int32Value(); int y2 = args[3]->IsUndefined() ? 0 : args[3]->Int32Value(); Local<Array> arr; static const int dir1x[4] = {-1, 1, 0, 0}; // 左 右 上 下 4个方向 static const int dir1y[4] = {0, 0, -1, 1}; static const int dir2x[4] = {0, 0, -1, 1}; // 上 下 左 右 4个方向 static const int dir2y[4] = {-1, 1, 0, 0}; int pnum = obj->CreatePolyLine(dir1x, dir1y, x1, y1, x2, y2); // 生成第一次点 if (pnum == 0) // 找不到折线 { arr = Array::New(isolate, 4); // 直连起始点 arr->Set(0, Number::New(isolate, x1)); arr->Set(1, Number::New(isolate, y1)); arr->Set(2, Number::New(isolate, x2)); arr->Set(3, Number::New(isolate, y2)); } else { int tmpPoint[64]; // 暂存第一次点 for (int i = 0; i < pnum; i++) { tmpPoint[i * 2 + 0] = obj->BoundaryBuf[i][0]; tmpPoint[i * 2 + 1] = obj->BoundaryBuf[i][1]; } int pnum2 = obj->CreatePolyLine(dir2x, dir2y, x1, y1, x2, y2); // 生成第二次点 if (pnum2 < pnum) // 第二次生成的点比第一次少 { pnum = pnum2; for (int i = 0; i < pnum; i++) { tmpPoint[i * 2 + 0] = obj->BoundaryBuf[i][0]; tmpPoint[i * 2 + 1] = obj->BoundaryBuf[i][1]; } } obj->AddPolyLineBorder(tmpPoint, pnum); // 设置折线阻隔框 arr = Array::New(isolate, pnum * 2); // 连接折线点 for (int i = 0; i < pnum * 2; i++) arr->Set(i, Number::New(isolate, tmpPoint[i])); } args.GetReturnValue().Set(arr); } void InitAll(Local<Object> exports) { AutoPolyLine::Init(exports); } NODE_MODULE(autopolyline, InitAll) }
28.12326
122
0.607522
767841bcaf8190d65c1cdf5653bd80edfbd31f3a
11,933
hpp
C++
sol/function_types.hpp
SuperV1234/sol2
76b73bdfab4475933c42e715fd98737a4699794a
[ "MIT" ]
null
null
null
sol/function_types.hpp
SuperV1234/sol2
76b73bdfab4475933c42e715fd98737a4699794a
[ "MIT" ]
null
null
null
sol/function_types.hpp
SuperV1234/sol2
76b73bdfab4475933c42e715fd98737a4699794a
[ "MIT" ]
1
2021-05-02T15:57:13.000Z
2021-05-02T15:57:13.000Z
// The MIT License (MIT) // Copyright (c) 2013-2016 Rapptz, ThePhD and contributors // 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. #ifndef SOL_FUNCTION_TYPES_HPP #define SOL_FUNCTION_TYPES_HPP #include "function_types_core.hpp" #include "function_types_templated.hpp" #include "function_types_basic.hpp" #include "function_types_member.hpp" #include "function_types_overloaded.hpp" #include "resolve.hpp" #include "call.hpp" namespace sol { template <typename Sig, typename... Ps> struct function_arguments { std::tuple<Ps...> params; template <typename... Args> function_arguments(Args&&... args) : params(std::forward<Args>(args)...) {} }; template <typename Sig = function_sig<>, typename... Args> function_arguments<Sig, Args...> function_args(Args&&... args) { return function_arguments<Sig, Args...>(std::forward<Args>(args)...); } namespace stack { template<typename... Sigs> struct pusher<function_sig<Sigs...>> { template <typename... Sig, typename Fx, typename... Args> static void select_convertible(std::false_type, types<Sig...>, lua_State* L, Fx&& fx, Args&&... args) { typedef std::remove_pointer_t<std::decay_t<Fx>> clean_fx; std::unique_ptr<function_detail::base_function> sptr = std::make_unique<function_detail::functor_function<clean_fx>>(std::forward<Fx>(fx), std::forward<Args>(args)...); set_fx(L, std::move(sptr)); } template <typename R, typename... A, typename Fx, typename... Args> static void select_convertible(std::true_type, types<R(A...)>, lua_State* L, Fx&& fx, Args&&... args) { using fx_ptr_t = R(*)(A...); fx_ptr_t fxptr = detail::unwrap(std::forward<Fx>(fx)); select_function(std::true_type(), L, fxptr, std::forward<Args>(args)...); } template <typename R, typename... A, typename Fx, typename... Args> static void select_convertible(types<R(A...)> t, lua_State* L, Fx&& fx, Args&&... args) { typedef std::decay_t<meta::unwrapped_t<meta::unqualified_t<Fx>>> raw_fx_t; typedef R(*fx_ptr_t)(A...); typedef std::is_convertible<raw_fx_t, fx_ptr_t> is_convertible; select_convertible(is_convertible(), t, L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename Fx, typename... Args> static void select_convertible(types<>, lua_State* L, Fx&& fx, Args&&... args) { typedef meta::function_signature_t<meta::unwrapped_t<meta::unqualified_t<Fx>>> Sig; select_convertible(types<Sig>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename Fx, typename T, typename... Args> static void select_reference_member_variable(std::false_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) { typedef std::remove_pointer_t<std::decay_t<Fx>> clean_fx; std::unique_ptr<function_detail::base_function> sptr = std::make_unique<function_detail::member_variable<meta::unqualified_t<T>, clean_fx>>(std::forward<Fx>(fx), std::forward<T>(obj), std::forward<Args>(args)...); set_fx(L, std::move(sptr)); } template <typename Fx, typename T, typename... Args> static void select_reference_member_variable(std::true_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) { typedef std::decay_t<Fx> dFx; dFx memfxptr(std::forward<Fx>(fx)); auto userptr = detail::ptr(std::forward<T>(obj), std::forward<Args>(args)...); lua_CFunction freefunc = &function_detail::upvalue_member_variable<std::decay_t<decltype(*userptr)>, meta::unqualified_t<Fx>>::call; int upvalues = stack::stack_detail::push_as_upvalues(L, memfxptr); upvalues += stack::push(L, lightuserdata_value(static_cast<void*>(userptr))); stack::push(L, c_closure(freefunc, upvalues)); } template <typename Fx, typename... Args> static void select_member_variable(std::false_type, lua_State* L, Fx&& fx, Args&&... args) { select_convertible(types<Sigs...>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename Fx, typename T, typename... Args> static void select_member_variable(std::true_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) { typedef meta::boolean<meta::is_specialization_of<std::reference_wrapper, meta::unqualified_t<T>>::value || std::is_pointer<T>::value> is_reference; select_reference_member_variable(is_reference(), L, std::forward<Fx>(fx), std::forward<T>(obj), std::forward<Args>(args)...); } template <typename Fx> static void select_member_variable(std::true_type, lua_State* L, Fx&& fx) { typedef typename meta::bind_traits<meta::unqualified_t<Fx>>::object_type C; lua_CFunction freefunc = &function_detail::upvalue_this_member_variable<C, Fx>::call; int upvalues = stack::stack_detail::push_as_upvalues(L, fx); stack::push(L, c_closure(freefunc, upvalues)); } template <typename Fx, typename T, typename... Args> static void select_reference_member_function(std::false_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) { typedef std::remove_pointer_t<std::decay_t<Fx>> clean_fx; std::unique_ptr<function_detail::base_function> sptr = std::make_unique<function_detail::member_function<meta::unwrapped_t<meta::unqualified_t<T>>, clean_fx>>(std::forward<Fx>(fx), std::forward<T>(obj), std::forward<Args>(args)...); set_fx(L, std::move(sptr)); } template <typename Fx, typename T, typename... Args> static void select_reference_member_function(std::true_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) { typedef std::decay_t<Fx> dFx; dFx memfxptr(std::forward<Fx>(fx)); auto userptr = detail::ptr(std::forward<T>(obj), std::forward<Args>(args)...); lua_CFunction freefunc = &function_detail::upvalue_member_function<std::decay_t<decltype(*userptr)>, meta::unqualified_t<Fx>>::call; int upvalues = stack::stack_detail::push_as_upvalues(L, memfxptr); upvalues += stack::push(L, lightuserdata_value(static_cast<void*>(userptr))); stack::push(L, c_closure(freefunc, upvalues)); } template <typename Fx, typename... Args> static void select_member_function(std::false_type, lua_State* L, Fx&& fx, Args&&... args) { select_member_variable(std::is_member_object_pointer<meta::unqualified_t<Fx>>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename Fx, typename T, typename... Args> static void select_member_function(std::true_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) { typedef meta::boolean<meta::is_specialization_of<std::reference_wrapper, meta::unqualified_t<T>>::value || std::is_pointer<T>::value> is_reference; select_reference_member_function(is_reference(), L, std::forward<Fx>(fx), std::forward<T>(obj), std::forward<Args>(args)...); } template <typename Fx> static void select_member_function(std::true_type, lua_State* L, Fx&& fx) { typedef typename meta::bind_traits<meta::unqualified_t<Fx>>::object_type C; lua_CFunction freefunc = &function_detail::upvalue_this_member_function<C, Fx>::call; int upvalues = stack::stack_detail::push_as_upvalues(L, fx); stack::push(L, c_closure(freefunc, upvalues)); } template <typename Fx, typename... Args> static void select_function(std::false_type, lua_State* L, Fx&& fx, Args&&... args) { select_member_function(std::is_member_function_pointer<meta::unqualified_t<Fx>>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename Fx, typename... Args> static void select_function(std::true_type, lua_State* L, Fx&& fx, Args&&... args) { std::decay_t<Fx> target(std::forward<Fx>(fx), std::forward<Args>(args)...); lua_CFunction freefunc = &function_detail::upvalue_free_function<Fx>::call; int upvalues = stack::stack_detail::push_as_upvalues(L, target); stack::push(L, c_closure(freefunc, upvalues)); } static void select_function(std::true_type, lua_State* L, lua_CFunction f) { stack::push(L, f); } template <typename Fx, typename... Args> static void select(lua_State* L, Fx&& fx, Args&&... args) { select_function(std::is_function<meta::unqualified_t<Fx>>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...); } static void set_fx(lua_State* L, std::unique_ptr<function_detail::base_function> luafunc) { function_detail::base_function* target = luafunc.release(); void* targetdata = static_cast<void*>(target); lua_CFunction freefunc = function_detail::call; stack::push(L, userdata_value(targetdata)); function_detail::free_function_cleanup(L); lua_setmetatable(L, -2); stack::push(L, c_closure(freefunc, 1)); } template<typename... Args> static int push(lua_State* L, Args&&... args) { // Set will always place one thing (function) on the stack select(L, std::forward<Args>(args)...); return 1; } }; template<typename T, typename... Args> struct pusher<function_arguments<T, Args...>> { template <std::size_t... I, typename FP> static int push_func(std::index_sequence<I...>, lua_State* L, FP&& fp) { return stack::push<T>(L, detail::forward_get<I>(fp.params)...); } template <typename FP> static int push(lua_State* L, FP&& fp) { return push_func(std::make_index_sequence<sizeof...(Args)>(), L, std::forward<FP>(fp)); } }; template<typename Signature> struct pusher<std::function<Signature>> { static int push(lua_State* L, std::function<Signature> fx) { return pusher<function_sig<Signature>>{}.push(L, std::move(fx)); } }; template<typename Signature> struct pusher<Signature, std::enable_if_t<std::is_member_pointer<Signature>::value>> { template <typename F> static int push(lua_State* L, F&& f) { return pusher<function_sig<>>{}.push(L, std::forward<F>(f)); } }; template<typename Signature> struct pusher<Signature, std::enable_if_t<meta::all<std::is_function<Signature>, meta::neg<std::is_same<Signature, lua_CFunction>>, meta::neg<std::is_same<Signature, std::remove_pointer_t<lua_CFunction>>>>::value>> { template <typename F> static int push(lua_State* L, F&& f) { return pusher<function_sig<>>{}.push(L, std::forward<F>(f)); } }; template<typename... Functions> struct pusher<overload_set<Functions...>> { static int push(lua_State* L, overload_set<Functions...>&& set) { pusher<function_sig<>>{}.set_fx(L, std::make_unique<function_detail::overloaded_function<Functions...>>(std::move(set.set))); return 1; } static int push(lua_State* L, const overload_set<Functions...>& set) { pusher<function_sig<>>{}.set_fx(L, std::make_unique<function_detail::overloaded_function<Functions...>>(set.set)); return 1; } }; } // stack } // sol #endif // SOL_FUNCTION_TYPES_HPP
48.116935
237
0.684405
76809ff92dee2935f5ee84fbd564304130ac376c
5,453
cc
C++
test/nosync/ppoll-based-event-loop-test.cc
nokia/libNoSync
af0f0e5b738feac8c42c357c9dbdf3dc7e541a76
[ "BSD-3-Clause" ]
2
2018-04-28T18:29:08.000Z
2018-07-03T08:16:34.000Z
test/nosync/ppoll-based-event-loop-test.cc
nokia/libNoSync
af0f0e5b738feac8c42c357c9dbdf3dc7e541a76
[ "BSD-3-Clause" ]
null
null
null
test/nosync/ppoll-based-event-loop-test.cc
nokia/libNoSync
af0f0e5b738feac8c42c357c9dbdf3dc7e541a76
[ "BSD-3-Clause" ]
1
2018-04-27T07:53:16.000Z
2018-04-27T07:53:16.000Z
// This file is part of libnosync library. See LICENSE file for license details. #include <algorithm> #include <chrono> #include <fcntl.h> #include <functional> #include <gtest/gtest.h> #include <memory> #include <nosync/ppoll-based-event-loop.h> #include <nosync/type-utils.h> #include <system_error> #include <vector> namespace ch = std::chrono; using namespace std::chrono_literals; using namespace std::string_literals; using nosync::activity_handle; using nosync::eclock; using nosync::fd_watch_mode; using nosync::make_copy; using nosync::make_ppoll_based_event_loop; using std::errc; using std::function; using std::make_error_code; using std::unique_ptr; using std::vector; namespace { constexpr auto small_time_increment = 1ns; } TEST(NosyncPpollBasedEventLoop, TestSimpleTask) { auto evloop = make_ppoll_based_event_loop(); auto counter = 0U; evloop->invoke_at( evloop->get_etime() + small_time_increment, [&]() { ++counter; }); ASSERT_EQ(counter, 0U); ASSERT_FALSE(evloop->run_iterations()); ASSERT_EQ(counter, 1U); } TEST(NosyncPpollBasedEventLoop, TestTasksWithTimeIncrements) { constexpr auto task_repetitions = 5U; auto evloop = make_ppoll_based_event_loop(); const auto start_time = evloop->get_etime(); vector<ch::time_point<eclock>> task_times; function<void()> task; task = [&]() { task_times.push_back(evloop->get_etime()); if (task_times.size() < task_repetitions) { evloop->invoke_at(evloop->get_etime() + small_time_increment, make_copy(task)); } }; evloop->invoke_at(evloop->get_etime() + small_time_increment, make_copy(task)); ASSERT_FALSE(evloop->run_iterations()); ASSERT_EQ(task_times.size(), task_repetitions); auto prev_task_time = start_time; for (auto task_time : task_times) { ASSERT_GT(task_time, prev_task_time); prev_task_time = task_time; } } TEST(NosyncPpollBasedEventLoop, TestTasksNoTimeIncrements) { constexpr auto task_repetitions = 5U; auto evloop = make_ppoll_based_event_loop(); vector<ch::time_point<eclock>> task_times; for (auto i = 0U; i < task_repetitions; ++i) { evloop->invoke_at( evloop->get_etime() + small_time_increment, [&]() { task_times.push_back(evloop->get_etime()); }); } ASSERT_FALSE(evloop->run_iterations()); ASSERT_EQ(task_times.size(), task_repetitions); for (const auto task_time : task_times) { ASSERT_EQ(task_time, task_times.front()); } } TEST(NosyncPpollBasedEventLoop, TestFdWatch) { auto evloop = make_ppoll_based_event_loop(); int pipe_fds_a[2]; ASSERT_EQ(::pipe2(pipe_fds_a, O_CLOEXEC), 0); unique_ptr<activity_handle> activity_handle_a; int pipe_fds_b[2]; ASSERT_EQ(::pipe2(pipe_fds_b, O_CLOEXEC), 0); unique_ptr<activity_handle> activity_handle_b; auto exec_trace = ""s; evloop->invoke_at( evloop->get_etime() + small_time_increment, [&]() { exec_trace.push_back('S'); activity_handle_a = evloop->add_watch( pipe_fds_a[0], fd_watch_mode::input, [&]() { exec_trace.push_back('R'); activity_handle_a->disable(); }); activity_handle_b = evloop->add_watch( pipe_fds_b[0], fd_watch_mode::input, [&]() { exec_trace.push_back('r'); activity_handle_b->disable(); }); evloop->invoke_at( evloop->get_etime() + small_time_increment, [&]() { exec_trace.push_back('W'); ::write(pipe_fds_a[1], "", 1); }); }); evloop->invoke_at( evloop->get_etime(), [&]() { exec_trace.push_back('w'); ::write(pipe_fds_b[1], "", 1); }); ASSERT_EQ(exec_trace, ""s); ASSERT_FALSE(evloop->run_iterations()); ASSERT_EQ(exec_trace, "wSrWR"s); } TEST(NosyncPpollBasedEventLoop, TestQuitBetweenTasks) { auto evloop = make_ppoll_based_event_loop(); auto exec_trace = ""s; unique_ptr<activity_handle> activity_handle; evloop->invoke_at( evloop->get_etime() + small_time_increment, [&]() { exec_trace.push_back('1'); evloop->quit(); }); evloop->invoke_at( evloop->get_etime() + small_time_increment * 2, [&]() { exec_trace.push_back('2'); }); ASSERT_EQ(exec_trace, ""s); ASSERT_EQ(evloop->run_iterations(), make_error_code(errc::interrupted)); ASSERT_EQ(exec_trace, "1"s); } TEST(NosyncPpollBasedEventLoop, TestQuitBetweenWatches) { auto evloop = make_ppoll_based_event_loop(); int pipe_fds[2]; ASSERT_EQ(::pipe2(pipe_fds, O_CLOEXEC), 0); auto exec_trace = ""s; evloop->add_watch( pipe_fds[0], fd_watch_mode::input, [&]() { exec_trace.push_back('1'); evloop->quit(); }); evloop->add_watch( pipe_fds[0], fd_watch_mode::input, [&]() { exec_trace.push_back('2'); }); ::write(pipe_fds[1], "", 1); ASSERT_EQ(exec_trace, ""s); ASSERT_EQ(evloop->run_iterations(), make_error_code(errc::interrupted)); ASSERT_EQ(exec_trace, "1"s); }
25.600939
91
0.615074
76821c60e0b5e0d0b79e905cf309fa43dd9dda05
2,072
cpp
C++
src/core/CL/CLHelpers.cpp
longbowlee/ARMComputeLibrary
c772c0b2ecfe76cac5867915fdc296d14bb829a2
[ "MIT" ]
3
2017-04-02T08:41:24.000Z
2017-10-20T07:56:01.000Z
src/core/CL/CLHelpers.cpp
loliod/ComputeLibrary
871448ee8eff790c4ccc3250008dd71170cc78b2
[ "MIT" ]
null
null
null
src/core/CL/CLHelpers.cpp
loliod/ComputeLibrary
871448ee8eff790c4ccc3250008dd71170cc78b2
[ "MIT" ]
1
2017-12-21T04:13:45.000Z
2017-12-21T04:13:45.000Z
/* * Copyright (c) 2016, 2017 ARM Limited. * * SPDX-License-Identifier: MIT * * 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 "arm_compute/core/CL/CLHelpers.h" #include "arm_compute/core/Error.h" #include "arm_compute/core/Types.h" namespace arm_compute { std::string get_cl_type_from_data_type(const DataType &dt) { switch(dt) { case DataType::U8: return "uchar"; case DataType::S8: return "char"; case DataType::U16: return "ushort"; case DataType::S16: return "short"; case DataType::U32: return "uint"; case DataType::S32: return "int"; case DataType::U64: return "ulong"; case DataType::S64: return "long"; case DataType::F16: return "half"; case DataType::F32: return "float"; default: ARM_COMPUTE_ERROR("Unsupported input data type."); return ""; } } } // namespace arm_compute
33.967213
81
0.662645
76860c006f96ab42e021eb975a9e686c1500b924
719
cpp
C++
src/pass/analyze-usage/conditional.cpp
arrow-lang/arrow-legacy
5857697b88201c9a6abdd63c1b132741f3451b01
[ "MIT" ]
1
2017-05-02T14:13:51.000Z
2017-05-02T14:13:51.000Z
src/pass/analyze-usage/conditional.cpp
arrow-lang/arrow-legacy
5857697b88201c9a6abdd63c1b132741f3451b01
[ "MIT" ]
null
null
null
src/pass/analyze-usage/conditional.cpp
arrow-lang/arrow-legacy
5857697b88201c9a6abdd63c1b132741f3451b01
[ "MIT" ]
null
null
null
// Copyright (c) 2014-2015 Ryan Leckey, All Rights Reserved. // Distributed under the MIT License // See accompanying file LICENSE #include <algorithm> #include "arrow/pass/analyze-usage.hpp" #include "arrow/match.hpp" namespace arrow { namespace pass { void AnalyzeUsage::visit_conditional(ast::Conditional& x) { // Accept the conditiona (always entered) x.condition->accept(*this); // Accept the lhs-hand-side (but apply its result as not-definite) _enter_block(*x.lhs); x.lhs->accept(*this); _exit_block(false); // Accept the rhs-hand-side (but apply its result as not-definite) _enter_block(*x.rhs); x.rhs->accept(*this); _exit_block(false); } } // namespace pass } // namespace arrow
23.193548
68
0.713491
768629ebd1783b922f786e0b5e0b29393a08a2a2
639
cpp
C++
src/E12.cpp
microentropie/IEC60063
6b3900d9ed4554209cbb88c044d3d81e17ba47a6
[ "MIT" ]
null
null
null
src/E12.cpp
microentropie/IEC60063
6b3900d9ed4554209cbb88c044d3d81e17ba47a6
[ "MIT" ]
null
null
null
src/E12.cpp
microentropie/IEC60063
6b3900d9ed4554209cbb88c044d3d81e17ba47a6
[ "MIT" ]
null
null
null
/* Author: Stefano Di Paolo License: MIT, https://en.wikipedia.org/wiki/MIT_License Date: 2017-12-31 Library: IEC60063 series resistors. Sources repository: https://github.com/microentropie/ */ #include "E-series.h" const char E12Tolerance[] = "10%"; #define E12size 12 static const unsigned short E12[E12size + 1] = { 100, 120, 150, 180, 220, 270, 330, 390, 470, 560, 680, 820, 1000 }; float E12Value(float r) { return EserieValue(E12, E12size, r); } char *E12FormattedValue(char *buf, int len, float r, char unitTypeChar) { return EserieFormattedValue(buf, len, E12, E12size, r, unitTypeChar); }
22.821429
117
0.682316
768c4c836c3bebef4ea2a3a02cacaf5127d75b51
1,503
cpp
C++
HotDays.cpp
Drew138/competitive
6efdbfed97934ba5a894e2b71d76340d4c769e45
[ "MIT" ]
null
null
null
HotDays.cpp
Drew138/competitive
6efdbfed97934ba5a894e2b71d76340d4c769e45
[ "MIT" ]
null
null
null
HotDays.cpp
Drew138/competitive
6efdbfed97934ba5a894e2b71d76340d4c769e45
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define D(x) cout << #x << " = " << x << endl; #define ios ios_base::sync_with_stdio(0), cin.tie(0); #define forn(i, n) for (int i = 0; i < (int)n; ++i) #define all(v) v.begin(), v.end() #define formap(map) for (const auto &[key, value] : map) #define ms(ar, val) memset(ar, val, sizeof ar) typedef long long ll; typedef long double ld; using namespace std; int main() { ll numRegions, numChildren, regTemp, maxTemp, penalty, costBus, numBuses, minCase, maxCase, total = 0; cin >> numRegions >> numChildren; while (numRegions--) { cin >> regTemp >> maxTemp >> penalty >> costBus; if (maxTemp >= (regTemp + numChildren)) { total += costBus; } else { if (regTemp >= maxTemp) { total += costBus + (numChildren * penalty); } else { minCase = costBus + (numChildren * penalty); if (numChildren % (maxTemp - regTemp)) { maxCase = min(costBus * ((numChildren / (maxTemp - regTemp)) + 1), costBus * (numChildren / (maxTemp - regTemp)) + penalty * ((numChildren % (maxTemp - regTemp)) + (maxTemp - regTemp))); } else { maxCase = costBus * ((numChildren / (maxTemp - regTemp))); } total += min(maxCase, minCase); } } } cout << total; }
30.673469
206
0.496341
768cf7a415fa7f7e2d366091974abdea7db9f3dd
1,700
cpp
C++
windows/pw6e.official/CPlusPlus/Chapter10/WheresMyElement/WheresMyElement/MainPage.xaml.cpp
nnaabbcc/exercise
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
[ "MIT" ]
1
2016-11-23T08:18:08.000Z
2016-11-23T08:18:08.000Z
windows/pw6e.official/CPlusPlus/Chapter10/WheresMyElement/WheresMyElement/MainPage.xaml.cpp
nnaabbcc/exercise
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
[ "MIT" ]
null
null
null
windows/pw6e.official/CPlusPlus/Chapter10/WheresMyElement/WheresMyElement/MainPage.xaml.cpp
nnaabbcc/exercise
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
[ "MIT" ]
1
2016-11-23T08:17:34.000Z
2016-11-23T08:17:34.000Z
// // MainPage.xaml.cpp // Implementation of the MainPage class. // #include "pch.h" #include "MainPage.xaml.h" using namespace WheresMyElement; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; MainPage::MainPage() { InitializeComponent(); } void MainPage::OnTapped(TappedRoutedEventArgs^ args) { if (storyboardPaused) { storyboard->Resume(); storyboardPaused = false; return; } GeneralTransform^ xform = txtblk->TransformToVisual(contentGrid); // Draw blue polygon around element polygon->Points->Clear(); polygon->Points->Append(xform->TransformPoint(Point(0, 0))); polygon->Points->Append(xform->TransformPoint(Point((float)txtblk->ActualWidth, 0))); polygon->Points->Append(xform->TransformPoint(Point((float)txtblk->ActualWidth, (float)txtblk->ActualHeight))); polygon->Points->Append(xform->TransformPoint(Point(0, (float)txtblk->ActualHeight))); // Draw red bounding box RectangleGeometry^ rectangleGeometry = ref new RectangleGeometry(); rectangleGeometry->Rect = xform->TransformBounds(Rect(Point(0, 0), txtblk->DesiredSize)); path->Data = rectangleGeometry; storyboard->Pause(); storyboardPaused = true; }
31.481481
94
0.678235
768d6f873a3541c480be1ebe205126a99cba81d2
2,035
cpp
C++
peaks/find_peakCpp.cpp
rguliev/auto-baseline
96ad0121991c1e95736a59974c7de8d3b83a98dd
[ "MIT" ]
2
2019-11-06T02:52:31.000Z
2021-03-29T14:15:07.000Z
peaks/find_peakCpp.cpp
rguliev/auto-baseline
96ad0121991c1e95736a59974c7de8d3b83a98dd
[ "MIT" ]
null
null
null
peaks/find_peakCpp.cpp
rguliev/auto-baseline
96ad0121991c1e95736a59974c7de8d3b83a98dd
[ "MIT" ]
1
2021-04-11T09:59:40.000Z
2021-04-11T09:59:40.000Z
#include <Rcpp.h> using namespace Rcpp; //This function returns the sign of a given real valued double. // [[Rcpp::export]] double signDblCPP (double x){ double ret = 0; if(x > 0){ret = 1;} if(x < 0){ret = -1;} return(ret); } //Tested to be 6x faster(37 us vs 207 us). This operation is done from 200x per layer //Original R function by Stas_G // [[Rcpp::export]] NumericVector findPeaksCPP( NumericVector vY, int m = 3) { int sze = vY.size(); int i = 0;//generic iterator int q = 0;//second generic iterator int lb = 0;//left bound int rb = 0;//right bound bool isGreatest = true;//flag to state whether current index is greatest known value NumericVector ret(1); int pksFound = 0; for(i = 0; i < (sze-2); ++i){ //Find all regions with negative laplacian between neighbors //following expression is identical to diff(sign(diff(xV, na.pad = FALSE))) if(signDblCPP( vY(i + 2) - vY( i + 1 ) ) - signDblCPP( vY( i + 1 ) - vY( i ) ) < 0){ //Now assess all regions with negative laplacian between neighbors... lb = i - m - 1;// define left bound of vector if(lb < 0){lb = 0;}//ensure our neighbor comparison is bounded by vector length rb = i + m + 1;// define right bound of vector if(rb >= (sze-2)){rb = (sze-3);}//ensure our neighbor comparison is bounded by vector length //Scan through loop and ensure that the neighbors are smaller in magnitude for(q = lb; q < rb; ++q){ if(vY(q) > vY(i+1)){ isGreatest = false; } } //We have found a peak by our criterion if(isGreatest){ if(pksFound > 0){//Check vector size. ret.insert( 0, double(i + 2) ); }else{ ret(0) = double(i + 2); } pksFound = pksFound + 1; }else{ // we did not find a peak, reset location is peak max flag. isGreatest = true; }//End if found peak }//End if laplace condition }//End loop return(ret); }//End Fn
35.701754
99
0.589681
768e2018aa71800fb684786b766ce0df824b538e
604
cpp
C++
allMatuCommit/实现Point类(C++)_qwe123qwe_20210920104346.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
allMatuCommit/实现Point类(C++)_qwe123qwe_20210920104346.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
allMatuCommit/实现Point类(C++)_qwe123qwe_20210920104346.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include<algorithm> #include<cstring> #include<string.h> #include<math.h> #include<cmath> using namespace std; typedef long long int ll; class Point{ private : double x,y; public: Point(double a,double b) { x=a;y=b; } double Distance( Point const & b ) { double ans=0; ans = sqrt( pow(x- b.x,2)+ pow(y- b.y,2 ) ); return ans; } }; int main() { double a,b,c,d; cin>>a>>b>>c>>d; Point A(a,b),B(c,d); cout<<A.Distance(B)<<endl; return 0; double x=2.5; //cout<<pow(x,3)<<endl; return 0; }
15.1
48
0.56457
7692b4bc129f3cee9fead0e4559e38bac59cce54
6,004
cpp
C++
src/LinearColorCalibrator.cpp
alarrosa14/Sendero
fb81c43b3f0ef3b8ef8fbbce6fdd2d413b4c9542
[ "MIT" ]
1
2016-07-06T23:22:16.000Z
2016-07-06T23:22:16.000Z
src/LinearColorCalibrator.cpp
alarrosa14/Sendero
fb81c43b3f0ef3b8ef8fbbce6fdd2d413b4c9542
[ "MIT" ]
null
null
null
src/LinearColorCalibrator.cpp
alarrosa14/Sendero
fb81c43b3f0ef3b8ef8fbbce6fdd2d413b4c9542
[ "MIT" ]
null
null
null
// // LinearColorCalibrator.cpp // LEDColorCalibrator // // Created by Tomas Laurenzo on 4/20/13. // // #include "LinearColorCalibrator.h" LinearColorCalibrator::LinearColorCalibrator(){ gammaCorrecting = false; isCalculated = true; } void LinearColorCalibrator::useGamma() { gammaCorrecting = true; } void LinearColorCalibrator::dontUseGamma() { gammaCorrecting = false; } void LinearColorCalibrator::setGamma (float gamma) { this->gamma = gamma; } bool LinearColorCalibrator::calculateCalibration() { if (pairs.size() < 3) { isCalculated = false; return false; } ofColor v0 = pairs[pairs.size() - 1].first; ofColor v1 = pairs[pairs.size() - 2].first; ofColor v2 = pairs[pairs.size() - 3].first; ofColor w0 = pairs[pairs.size() - 1].second; ofColor w1 = pairs[pairs.size() - 2].second; ofColor w2 = pairs[pairs.size() - 3].second; double *A; A = new double[81]; // matrix in COLUMN MAJOR ORDER // columns 1..3 int i = 0; A[i++] = v0.r; A[i++] = v1.r; A[i++] = v2.r; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.g; A[i++] = v1.g; A[i++] = v2.g; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.b; A[i++] = v1.b; A[i++] = v2.b; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; //columns 4..6 A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.r; A[i++] = v1.r; A[i++] = v2.r; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.g; A[i++] = v1.g; A[i++] = v2.g; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.b; A[i++] = v1.b; A[i++] = v2.b; A[i++] = 0; A[i++] = 0; A[i++] = 0; //columns 7..9 A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.r; A[i++] = v1.r; A[i++] = v2.r; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.g; A[i++] = v1.g; A[i++] = v2.g; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.b; A[i++] = v1.b; A[i++] = v2.b; double *b; b = new double[9]; // w1, w2, w3 i = 0; b[i++] = w0[0]; b[i++] = w0[1]; b[i++] = w0[2]; b[i++] = w1[0]; b[i++] = w1[1]; b[i++] = w1[2]; b[i++] = w2[0]; b[i++] = w2[1]; b[i++] = w2[2]; // solving the linear system AX = b int N = 9; // number of columns of A int NRHS = 1; // number of columns of b int LDA = 9; // number of rows of A int IPIV[9]; // pivot indices int LDB = 9; // number of rows of b int INFO = 0; //INFO = clapack_dgesv((CBLAS_ORDER) 101, N, NRHS, A, LDA, IPIV, b, LDB); dgesv_(&N, &NRHS, A, &LDA, IPIV, b, &LDB, &INFO); if (INFO == 0) cout << endl << "dgesv_: OK"; if (INFO < 0) cout << "dgesv_: the element " << INFO << " is invalid"; if (INFO > 0) cout << "dgesv_: the LU decomposition returned 0 "; cout << endl << endl; /* __CLPK_integer is long * __CLPK_doublereal is double * dgesv_(__CLPK_integer *n, __CLPK_integer *nrhs, __CLPK_doublereal *a, __CLPK_integer *lda, __CLPK_integer *ipiv, __CLPK_doublereal *b, __CLPK_integer *ldb, __CLPK_integer *info) void dgesv_(const int *N, const int *nrhs, double *A, const int *lda, int *ipiv, double *b, const int *ldb, int *info); Notice that all parameters are passed by reference. That's the good old Fortran way. The meanings of the parameters are: N number of columns of A nrhs number of columns of b, usually 1 lda number of rows (Leading Dimension of A) of A ipiv pivot indices ldb number of rows of b */ i = 0; T[0][0] = b[i++]; T[1][0] = b[i++]; T[2][0] = b[i++]; T[0][1] = b[i++]; T[1][1] = b[i++]; T[2][1] = b[i++]; T[0][2] = b[i++]; T[1][2] = b[i++]; T[2][2] = b[i++]; cout << "Transformation matrix: " << endl; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j ++) { cout << "\t" << T[i][j]; } cout << endl; } cout << endl; isCalculated = true; delete[]A; delete[]b; } ofColor LinearColorCalibrator::getCalibratedColor(ofColor color) { if (!isCalculated) calculateCalibration(); if (!isCalculated) return color; // calibrated color = T * color ofColor res; res = res.black; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { res[i] += color[i] * T[j][i]; } } if (gammaCorrecting) { for (int i = 0; i < 3; i++) { float f = (int)res[i] / 255.0f; float r = pow(f, gamma); int g = r * 255.0f; int o = f * 255.0f; res[i] = g; } } return res; } float LinearColorCalibrator::getGamma() { return gamma; } void LinearColorCalibrator::addEquivalentPair(ofColor first, ofColor second) { // we assume lineal, because we are in a hurry and non linear is complicated // todo: change it to non linear transformation using little CMS // the idea is, we create a profile for the LEDs and a profile for the monitor and use little CMS to make the // transformation between them // pair <first, second> p; pairs.push_back(pair<ofColor, ofColor>(first, second)); isCalculated = false; } void LinearColorCalibrator::reset() { pairs.clear(); isCalculated = false; }
21.519713
124
0.463025
7693b2d81fb6d9bef245f2341f00fb948e664470
5,756
cpp
C++
Source/PraticeActor/CBattlePC.cpp
CitrusNyamNyam/Unreal-Portfolio
f5a63fbe796e0531604470767207831b5c523b54
[ "MIT" ]
1
2018-11-25T10:40:10.000Z
2018-11-25T10:40:10.000Z
Source/PraticeActor/CBattlePC.cpp
CitrusNyamNyam/Unreal-Portfolio
f5a63fbe796e0531604470767207831b5c523b54
[ "MIT" ]
null
null
null
Source/PraticeActor/CBattlePC.cpp
CitrusNyamNyam/Unreal-Portfolio
f5a63fbe796e0531604470767207831b5c523b54
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "CBattlePC.h" #include "CBattleGM.h" #include "CPlayer.h" #include "CAirplane_C130.h" #include "CFlyingViewer.h" #include "CResult_Widget.h" #include "CClientMain_Widget.h" #include "CWorldMap_Widget.h" #include "Animation/WidgetAnimation.h" #include "UserWidget.h" #include "UnrealNetwork.h" #include "Engine.h" ACBattlePC::ACBattlePC() :bDived(false), bWorldMap(false) , MapSize(816000.0f,816000.0f,0.0f) { static ConstructorHelpers::FObjectFinder<UClass> clientWidget(TEXT("/Game/GameMode/Battle/UMG/WidgetBP_ClientMain.WidgetBP_ClientMain_C")); if (clientWidget.Object) TSubClientMainWidget = clientWidget.Object; static ConstructorHelpers::FObjectFinder<UClass> resultWidget(TEXT("/Game/GameMode/Battle/UMG/WidgetBP_Result.WidgetBP_Result_C")); if (resultWidget.Object) TSubResultWidget = resultWidget.Object; static ConstructorHelpers::FObjectFinder<UClass> worldMapWidget(TEXT("/Game/WorldMap/WidgetBP_WorldMap.WidgetBP_WorldMap_C")); if (worldMapWidget.Object) TSubWorldMapWidget = worldMapWidget.Object; } void ACBattlePC::BeginPlay() { Super::BeginPlay(); TArray<AActor*> outActors; UGameplayStatics::GetAllActorsWithTag(GetWorld(), FName("C130"), outActors); if (outActors.Num() > 0) { Airplane_C130 = Cast<ACAirplane_C130>(outActors[0]); } SetInputMode(FInputModeGameOnly()); bShowMouseCursor = false; if (!HasAuthority()) { ClientMainWidget = CreateWidget<UCClientMain_Widget>(GetWorld(), TSubClientMainWidget); ResultWidget = CreateWidget<UCResult_Widget>(GetWorld(), TSubResultWidget); if (ClientMainWidget) { ClientMainWidget->AddToViewport(); } } } void ACBattlePC::SetupInputComponent() { Super::SetupInputComponent(); InputComponent->BindAction("WorldMap", EInputEvent::IE_Pressed, this, &ACBattlePC::OnOpenWorldMap); } bool ACBattlePC::GetAirplane() { ACFlyingViewer* viewer = Cast<ACFlyingViewer>(GetPawn()); if (viewer) { return true; } else return false; } FVector ACBattlePC::GetPawnDirection() { ACFlyingViewer* viewer = Cast<ACFlyingViewer>(GetPawn()); if (viewer) { return Airplane_C130->GetActorForwardVector(); } else { return GetPawn()->GetActorForwardVector(); } return FVector::ZeroVector; } void ACBattlePC::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(ACBattlePC, NotificationFromServer); } void ACBattlePC::OnCharacterDeath() { ACBattleGM* gameMode = Cast<ACBattleGM>(UGameplayStatics::GetGameMode(GetWorld())); if (gameMode) { gameMode->OnCharacterDeath(this); } } void ACBattlePC::OnOpenWorldMap() { if (WorldMapWidget == NULL) { WorldMapWidget = CreateWidget<UCWorldMap_Widget>(GetWorld(), TSubWorldMapWidget); } if (WorldMapWidget != NULL) { if (!bWorldMap) { bWorldMap = true; WorldMapWidget->AddToViewport(); } else { bWorldMap = false; WorldMapWidget->RemoveFromParent(); } } } FVector ACBattlePC::GetPawnPosition() { if (GetPawn()) { return GetPawn()->GetActorLocation(); } return FVector(9999999999,9999999999,0); } bool ACBattlePC::ServerRPC_RideInAirplaneC130_Validate(ACAirplane_C130 * airplane) { return true; } void ACBattlePC::ServerRPC_RideInAirplaneC130_Implementation(ACAirplane_C130 * airplane) { if (airplane) { GetPawn()->Destroy(); FActorSpawnParameters parameters; parameters.Owner = this; parameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; FVector location = airplane->GetActorLocation(); ACFlyingViewer* viewer = GetWorld()->SpawnActor<ACFlyingViewer>(ACFlyingViewer::StaticClass(), location, FRotator::ZeroRotator, parameters); Possess(viewer); FAttachmentTransformRules rules(EAttachmentRule::SnapToTarget, EAttachmentRule::SnapToTarget, EAttachmentRule::SnapToTarget, true); viewer->AttachToActor(airplane, rules); } } bool ACBattlePC::ServerRPC_WantToDive_Validate() { return true; } void ACBattlePC::ServerRPC_WantToDive_Implementation() { if (bDived) return; bDived = true; FVector location = GetPawn()->GetActorLocation(); location.Z -= 1000.0f; FActorSpawnParameters parameters; parameters.Owner = this; parameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; ACPlayer* player = GetWorld()->SpawnActor<ACPlayer>(ACPlayer::StaticClass(), location, FRotator::ZeroRotator, parameters); GetPawn()->Destroy(); if (player) { player->SetDive(true); Possess(player); } } void ACBattlePC::ClientRPC_BackToLobby_Implementation() { UGameplayStatics::OpenLevel(GetWorld(), FName("Lobby")); } void ACBattlePC::ClientRPC_ShowDeathResult_Implementation(int rank) { if (ResultWidget) { ResultWidget->ResultString = FString(TEXT("that's fine, that can happen..")); ResultWidget->RankString = FString("#") + FString::FromInt(rank); ResultWidget->AddToViewport(); FInputModeUIOnly Mode; Mode.SetWidgetToFocus(ResultWidget->GetCachedWidget()); SetInputMode(Mode); bShowMouseCursor = true; } } void ACBattlePC::ClientRPC_ShowWinnerResult_Implementation() { if (ResultWidget) { ResultWidget->ResultString = FString(TEXT("WINNER WINNER CHICKEN DINNER")); ResultWidget->RankString = FString("#") + FString::FromInt(1); ResultWidget->AddToViewport(); FInputModeUIOnly Mode; Mode.SetWidgetToFocus(ResultWidget->GetCachedWidget()); SetInputMode(Mode); bShowMouseCursor = true; } } void ACBattlePC::ClientRPC_ShowBloodScreenEffect_Implementation() { if (ClientMainWidget) { if (ClientMainWidget->BloodEffectAnimation) { ClientMainWidget->PlayAnimation(ClientMainWidget->BloodEffectAnimation); } } }
23.590164
142
0.761119
7696137c106984a49fa532b5274a6d9255224b6d
112
hpp
C++
libraries/chain/include/DA-DAPPS/chain/protocol.hpp
mycloudmyworld2019/DA-DAPPS
534ace858fb5d852d69a578151929e64e2932f8b
[ "MIT" ]
null
null
null
libraries/chain/include/DA-DAPPS/chain/protocol.hpp
mycloudmyworld2019/DA-DAPPS
534ace858fb5d852d69a578151929e64e2932f8b
[ "MIT" ]
null
null
null
libraries/chain/include/DA-DAPPS/chain/protocol.hpp
mycloudmyworld2019/DA-DAPPS
534ace858fb5d852d69a578151929e64e2932f8b
[ "MIT" ]
null
null
null
/** * @file * @copyright defined in DA-DAPPS/LICENSE */ #pragma once #include <DA-DAPPSio/chain/block.hpp>
16
42
0.669643
76989c61c94af3b6113a9aa7631b96bfc0944f0c
5,677
cpp
C++
computer-vision-2/assignments/assignment_3/src/Frame3D/Frame3D.cpp
askliar/computer-vision
988f3b6aae1a45515cf7b133f2b89af4118f0c3a
[ "MIT" ]
null
null
null
computer-vision-2/assignments/assignment_3/src/Frame3D/Frame3D.cpp
askliar/computer-vision
988f3b6aae1a45515cf7b133f2b89af4118f0c3a
[ "MIT" ]
null
null
null
computer-vision-2/assignments/assignment_3/src/Frame3D/Frame3D.cpp
askliar/computer-vision
988f3b6aae1a45515cf7b133f2b89af4118f0c3a
[ "MIT" ]
4
2019-02-07T15:59:54.000Z
2021-05-01T18:58:07.000Z
/* * Frame3D.cpp * * Created on: 15 Nov 2015 * Author: Morris Franken @ 3DUniversum */ #include <fstream> #include <sstream> #include <string> #include <vector> #include <iostream> #include <stdexcept> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgcodecs/imgcodecs_c.h> #include "Frame3D.h" #include "FileUtils.h" #if USE_EIGEN #include <Eigen/Core> #include <opencv2/core/eigen.hpp> #endif using namespace std; using namespace cv; string Frame3D::extension = ".3df"; vector<int> Frame3D::paramsJPG = {CV_IMWRITE_JPEG_QUALITY, 90}; vector<int> Frame3D::paramsWEBP = {CV_IMWRITE_WEBP_QUALITY, 90}; vector<int> Frame3D::paramsPNG = {CV_IMWRITE_PNG_COMPRESSION, 3}; Frame3D::~Frame3D() {} Frame3D::Frame3D() : version_(-1), focal_length_(0) {} Frame3D::Frame3D(string path) : version_(-1), focal_length_(0) { load(path); } Frame3D::Frame3D(Mat rgb_image, Mat depth_image, Mat rotation_translation, float focal_length, std::string device_name/*=""*/) : version_(-1), rgb_image_(rgb_image), depth_image_(depth_image), transformation_(rotation_translation), focal_length_(focal_length), device_name_(device_name) { assert(rgb_image.type() == CV_8UC3); assert(depth_image.type() == CV_16U); assert(transformation_.size() == Size(4,4)); syncTrans(); } Frame3D::Frame3D(Mat rgb_image, Mat depth_image, Mat rotation, Mat translation, float focal_length, std::string device_name/*=""*/) : version_(-1), rgb_image_(rgb_image), depth_image_(depth_image), focal_length_(focal_length), device_name_(device_name) { assert(rgb_image.type() == CV_8UC3); assert(depth_image.type() == CV_16U); assert(rotation.size() == Size(3,3)); assert(translation.size() == Size(1,3)); syncTrans(rotation, translation); } void Frame3D::syncTrans(cv::Mat &rotation, cv::Mat &translation) { transformation_ = Mat::zeros(4,4,CV_32F); rotation.copyTo(transformation_(Rect(0,0,3,3))); translation.copyTo(transformation_(Rect(3,0,1,3))); syncTrans(); } void Frame3D::syncTrans() { rotation_ = transformation_(Rect(0,0,3,3)); translation_ = transformation_(Rect(3,0,1,3)); } void Frame3D::setTranslation(cv::Mat &translation) { assert(translation.size() == Size(1,3)); translation.copyTo(transformation_(Rect(3,0,1,3))); translation_ = transformation_(Rect(3,0,1,3)); } void Frame3D::setRotation(cv::Mat &rotation) { assert(rotation.size() == Size(3,3)); rotation.copyTo(transformation_(Rect(0,0,3,3))); rotation_ = transformation_(Rect(0,0,3,3)); } void Frame3D::setTranformation(cv::Mat &transformation) { assert(transformation_.size() == Size(4,4)); transformation_ = transformation; syncTrans(); } /* Get Eigen Matrix format, convienient single matrix transformation in Eigen format. Enable it if you have Eigen installed */ #if USE_EIGEN Eigen::Matrix4f Frame3D::getEigenTransform() const { Eigen::Matrix4f eigen_matrix; cv2eigen(transformation_, eigen_matrix); eigen_matrix(3, 3) = 1.; return eigen_matrix; } #endif /* Save 3D frame to file. 2 options are available: * - version 0.5 : Frame is saved without any compression, a simple memory dump * - version 1 : Frame is saved using JPG compression (90%) on the rgb_image, and PNG compression(type 3) on the depth_image. * This compression comes at a cost, since it is about 5 times slower to load than simple memory dump * - version 1.2 : In addition to version 1, in version 1.2 the rotation and translation matrices are stored in 1 4x4 matrix * - version 1.3 : Device name is added */ void Frame3D::save(string path, double version/*=1.3*/) { if (version != 0.5 && version != 1 && version != 1.2 && version != 1.3) throw(runtime_error("Frame3D::save : invalid version number!, currently only version 0.5, 1, 1.2 and 1.3 are supported")); FileWriter writer(path); writer.appendDouble(version); if (version >= 1) { writer.appendImage(rgb_image_, ".jpg", paramsJPG); writer.appendImage(depth_image_, ".png", paramsPNG); } else { writer.appendMat(rgb_image_); writer.appendMat(depth_image_); } if (version >= 1.2) { writer.appendMat(transformation_); } else { Mat temp1 = rotation_.clone(); Mat temp2 = translation_.clone(); writer.appendMat(temp1); writer.appendMat(temp2); } writer.appendDouble(focal_length_); if (version >= 1.3) writer.appendString(device_name_); } /* Load .3df file, the variables have to be loaded in the same order as they have been saved * TODO(morris) : make something like a header to check whether or not this is actually a legit .3DF file */ void Frame3D::load(string path) { int index = path.find_last_of('.'); if (index > 0 && path.substr(index) == Frame3D::extension) { FileReader reader(path); version_ = reader.readDouble(); if (version_ >= 1) { rgb_image_ = reader.readImage(); depth_image_ = reader.readImage(); } else { rgb_image_ = reader.readMat(); depth_image_ = reader.readMat(); } if (version_ >= 1.2) { transformation_ = reader.readMat(); syncTrans(); } else { rotation_ = reader.readMat(); translation_ = reader.readMat(); syncTrans(rotation_, translation_); } focal_length_ = reader.readDouble(); if (version_ >= 1.3) device_name_ = reader.readString(); } else { throw(runtime_error("this is not a valid " + Frame3D::extension + " file: " + path)); } } vector<Frame3D> Frame3D::loadFrames(string frame_dir_path) { vector<Frame3D> frames; vector<string> file_paths = ListFilesRecursive(frame_dir_path, extension); frames.reserve(file_paths.size()); for (const string &path : file_paths) { frames.emplace_back(Frame3D(path)); } return frames; }
31.021858
133
0.70953
769951a4c9b60f20bdb25e2bf0f6607c12640307
877
cpp
C++
v142/main.cpp
glensand/visual-studio-compatibility
7a7c7953bd4f7b8cf16485e66a90c966c8b1f829
[ "MIT" ]
3
2020-07-11T07:12:45.000Z
2020-07-13T03:00:40.000Z
v142/main.cpp
glensand/visual-studio-compatibility
7a7c7953bd4f7b8cf16485e66a90c966c8b1f829
[ "MIT" ]
null
null
null
v142/main.cpp
glensand/visual-studio-compatibility
7a7c7953bd4f7b8cf16485e66a90c966c8b1f829
[ "MIT" ]
1
2020-07-11T07:10:33.000Z
2020-07-11T07:10:33.000Z
#include "v110/export_class_110.h" #include "v141/export_class_141.h" #include "v142/derived_class_142.h" #include "v110_static/class_110.h" int main() { // stack object construction - destruction works well export_class_110 ec; // we cannot deallocate memory were allocated in another module // it seems like wrong dll loading //const auto vector = ec.getStringList(); //std::vector<std::string> testNotTrivialVector; //ExportClass::Fill(testNotTrivialVector); // also memory allocation and deallocation if it were done in single module works auto* export_110 = export_class_110::create(); export_class_110::destroy(export_110); auto* export_141 = export_class_141::create(); delete export_141; ref_counted* d_c = new derived_class_142; delete d_c; class_110 static_class; static_class.do_something(); static_class.add_string("asfsadgdg"); return 0; }
28.290323
82
0.769669
769a742c357a56feffbcb12987512783b6dc1fd0
14,624
cpp
C++
src/mods/vr/D3D11Component.cpp
fengjixuchui/REFramework
131b25ef58064b1c36cdd15072c30f5fbd9a7ad8
[ "MIT" ]
null
null
null
src/mods/vr/D3D11Component.cpp
fengjixuchui/REFramework
131b25ef58064b1c36cdd15072c30f5fbd9a7ad8
[ "MIT" ]
null
null
null
src/mods/vr/D3D11Component.cpp
fengjixuchui/REFramework
131b25ef58064b1c36cdd15072c30f5fbd9a7ad8
[ "MIT" ]
null
null
null
#include <imgui.h> #include <imgui_internal.h> #include <openvr.h> #include "../VR.hpp" #include "D3D11Component.hpp" #ifdef VERBOSE_D3D11 #define LOG_VERBOSE(...) spdlog::info(__VA_ARGS__) #else #define LOG_VERBOSE #endif namespace vrmod { vr::EVRCompositorError D3D11Component::on_frame(VR* vr) { if (m_left_eye_tex == nullptr) { setup(); } auto& hook = g_framework->get_d3d11_hook(); // get device auto device = hook->get_device(); // Get the context. ComPtr<ID3D11DeviceContext> context{}; device->GetImmediateContext(&context); // get swapchain auto swapchain = hook->get_swap_chain(); // get back buffer ComPtr<ID3D11Texture2D> backbuffer{}; swapchain->GetBuffer(0, IID_PPV_ARGS(&backbuffer)); if (backbuffer == nullptr) { spdlog::error("[VR] Failed to get back buffer."); return vr::VRCompositorError_None; } auto runtime = vr->get_runtime(); // If m_frame_count is even, we're rendering the left eye. if (vr->m_render_frame_count % 2 == vr->m_left_eye_interval) { if (runtime->is_openxr() && runtime->ready()) { LOG_VERBOSE("Copying left eye"); m_openxr.copy(0, backbuffer.Get()); } if (runtime->is_openvr()) { // Copy the back buffer to the left eye texture (m_left_eye_tex0 holds the intermediate frame). context->CopyResource(m_left_eye_tex.Get(), backbuffer.Get()); vr::Texture_t left_eye{(void*)m_left_eye_tex.Get(), vr::TextureType_DirectX, vr::ColorSpace_Auto}; auto e = vr::VRCompositor()->Submit(vr::Eye_Left, &left_eye, &vr->m_left_bounds); bool submitted = true; if (e != vr::VRCompositorError_None) { spdlog::error("[VR] VRCompositor failed to submit left eye: {}", (int)e); vr->m_submitted = false; return e; } } } else { if (runtime->ready()) { if (runtime->is_openxr()) { LOG_VERBOSE("Copying right eye"); m_openxr.copy(1, backbuffer.Get()); } if (runtime->get_synchronize_stage() == VRRuntime::SynchronizeStage::VERY_LATE || !runtime->got_first_sync) { runtime->synchronize_frame(); if (!runtime->got_first_poses) { runtime->update_poses(); } } } if (runtime->is_openxr() && vr->m_openxr->ready()) { if (runtime->get_synchronize_stage() == VRRuntime::SynchronizeStage::VERY_LATE || !vr->m_openxr->frame_began) { LOG_VERBOSE("Beginning frame."); vr->m_openxr->begin_frame(); } LOG_VERBOSE("Ending frame"); auto result = vr->m_openxr->end_frame(); vr->m_openxr->needs_pose_update = true; vr->m_submitted = result == XR_SUCCESS; } if (runtime->is_openvr()) { // Copy the back buffer to the right eye texture. context->CopyResource(m_right_eye_tex.Get(), backbuffer.Get()); vr::Texture_t right_eye{(void*)m_right_eye_tex.Get(), vr::TextureType_DirectX, vr::ColorSpace_Auto}; auto e = vr::VRCompositor()->Submit(vr::Eye_Right, &right_eye, &vr->m_right_bounds); bool submitted = true; if (e != vr::VRCompositorError_None) { spdlog::error("[VR] VRCompositor failed to submit right eye: {}", (int)e); vr->m_submitted = false; return e; } vr->m_submitted = true; } if (runtime->ready()) { hook->ignore_next_present(); } } return vr::VRCompositorError_None; } void D3D11Component::on_reset(VR* vr) { m_left_eye_tex.Reset(); m_right_eye_tex.Reset(); m_left_eye_depthstencil.Reset(); m_right_eye_depthstencil.Reset(); if (vr->get_runtime()->is_openxr() && vr->get_runtime()->loaded) { if (m_openxr.last_resolution[0] != vr->get_hmd_width() || m_openxr.last_resolution[1] != vr->get_hmd_height()) { m_openxr.create_swapchains(); } } } void D3D11Component::setup() { // Get device and swapchain. auto& hook = g_framework->get_d3d11_hook(); auto device = hook->get_device(); auto swapchain = hook->get_swap_chain(); // Get back buffer. ComPtr<ID3D11Texture2D> backbuffer{}; swapchain->GetBuffer(0, IID_PPV_ARGS(&backbuffer)); // Get backbuffer description. D3D11_TEXTURE2D_DESC backbuffer_desc{}; backbuffer->GetDesc(&backbuffer_desc); backbuffer_desc.BindFlags |= D3D11_BIND_RENDER_TARGET; // Create eye textures. device->CreateTexture2D(&backbuffer_desc, nullptr, &m_left_eye_tex); device->CreateTexture2D(&backbuffer_desc, nullptr, &m_right_eye_tex); // copy backbuffer into right eye // Get the context. ComPtr<ID3D11DeviceContext> context{}; device->GetImmediateContext(&context); context->CopyResource(m_right_eye_tex.Get(), backbuffer.Get()); // Make depth stencils for both eyes. auto depthstencil = hook->get_last_depthstencil_used(); if (depthstencil != nullptr) { D3D11_TEXTURE2D_DESC depthstencil_desc{}; depthstencil->GetDesc(&depthstencil_desc); // Create eye depthstencils. device->CreateTexture2D(&depthstencil_desc, nullptr, &m_left_eye_depthstencil); device->CreateTexture2D(&depthstencil_desc, nullptr, &m_right_eye_depthstencil); // Copy the current depthstencil into the right eye. context->CopyResource(m_right_eye_depthstencil.Get(), depthstencil.Get()); } spdlog::info("[VR] d3d11 textures have been setup"); } void D3D11Component::OpenXR::initialize(XrSessionCreateInfo& session_info) { std::scoped_lock _{this->mtx}; auto& hook = g_framework->get_d3d11_hook(); auto device = hook->get_device(); this->binding.device = device; PFN_xrGetD3D11GraphicsRequirementsKHR fn = nullptr; xrGetInstanceProcAddr(VR::get()->m_openxr->instance, "xrGetD3D11GraphicsRequirementsKHR", (PFN_xrVoidFunction*)(&fn)); if (fn == nullptr) { spdlog::error("[VR] xrGetD3D11GraphicsRequirementsKHR not found"); return; } // get existing adapter from device ComPtr<IDXGIDevice> dxgi_device{}; if (FAILED(device->QueryInterface(IID_PPV_ARGS(&dxgi_device)))) { spdlog::error("[VR] failed to get DXGI device from D3D11 device"); return; } ComPtr<IDXGIAdapter> adapter{}; if (FAILED(dxgi_device->GetAdapter(&adapter))) { spdlog::error("[VR] failed to get DXGI adapter from DXGI device"); return; } DXGI_ADAPTER_DESC desc{}; if (FAILED(adapter->GetDesc(&desc))) { spdlog::error("[VR] failed to get DXGI adapter description"); return; } XrGraphicsRequirementsD3D11KHR gr{XR_TYPE_GRAPHICS_REQUIREMENTS_D3D11_KHR}; gr.adapterLuid = desc.AdapterLuid; gr.minFeatureLevel = D3D_FEATURE_LEVEL_11_0; fn(VR::get()->m_openxr->instance, VR::get()->m_openxr->system, &gr); session_info.next = &this->binding; } std::optional<std::string> D3D11Component::OpenXR::create_swapchains() { std::scoped_lock _{this->mtx}; spdlog::info("[VR] Creating OpenXR swapchains for D3D11"); this->destroy_swapchains(); auto& hook = g_framework->get_d3d11_hook(); auto device = hook->get_device(); auto swapchain = hook->get_swap_chain(); // Get back buffer. ComPtr<ID3D11Texture2D> backbuffer{}; swapchain->GetBuffer(0, IID_PPV_ARGS(&backbuffer)); if (backbuffer == nullptr) { spdlog::error("[VR] Failed to get back buffer."); return "Failed to get back buffer."; } // Get backbuffer description. D3D11_TEXTURE2D_DESC backbuffer_desc{}; backbuffer->GetDesc(&backbuffer_desc); backbuffer_desc.BindFlags |= D3D11_BIND_RENDER_TARGET; auto vr = VR::get(); auto& openxr = *vr->m_openxr; this->contexts.clear(); this->contexts.resize(openxr.views.size()); // Create eye textures. for (auto i = 0; i < openxr.views.size(); ++i) { const auto& vp = openxr.view_configs[i]; spdlog::info("[VR] Creating swapchain for eye {}", i); spdlog::info("[VR] Width: {}", vr->get_hmd_width()); spdlog::info("[VR] Height: {}", vr->get_hmd_height()); backbuffer_desc.Width = vr->get_hmd_width(); backbuffer_desc.Height = vr->get_hmd_height(); XrSwapchainCreateInfo swapchain_create_info{XR_TYPE_SWAPCHAIN_CREATE_INFO}; swapchain_create_info.arraySize = 1; swapchain_create_info.format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; swapchain_create_info.width = backbuffer_desc.Width; swapchain_create_info.height = backbuffer_desc.Height; swapchain_create_info.mipCount = 1; swapchain_create_info.faceCount = 1; swapchain_create_info.sampleCount = backbuffer_desc.SampleDesc.Count; swapchain_create_info.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT; runtimes::OpenXR::Swapchain swapchain{}; swapchain.width = swapchain_create_info.width; swapchain.height = swapchain_create_info.height; if (xrCreateSwapchain(openxr.session, &swapchain_create_info, &swapchain.handle) != XR_SUCCESS) { spdlog::error("[VR] D3D11: Failed to create swapchain."); return "Failed to create swapchain."; } vr->m_openxr->swapchains.push_back(swapchain); uint32_t image_count{}; auto result = xrEnumerateSwapchainImages(swapchain.handle, 0, &image_count, nullptr); if (result != XR_SUCCESS) { spdlog::error("[VR] Failed to enumerate swapchain images."); return "Failed to enumerate swapchain images."; } auto& ctx = this->contexts[i]; ctx.textures.clear(); ctx.textures.resize(image_count); for (uint32_t j = 0; j < image_count; ++j) { spdlog::info("[VR] Creating swapchain image {} for swapchain {}", j, i); ctx.textures[j] = {XR_TYPE_SWAPCHAIN_IMAGE_D3D11_KHR}; if (FAILED(device->CreateTexture2D(&backbuffer_desc, nullptr, &ctx.textures[j].texture))) { spdlog::error("[VR] Failed to create swapchain texture {} {}", i, j); return "Failed to create swapchain texture."; } // get immediate context ComPtr<ID3D11DeviceContext> context{}; device->GetImmediateContext(&context); context->CopyResource(ctx.textures[j].texture, backbuffer.Get()); } result = xrEnumerateSwapchainImages(swapchain.handle, image_count, &image_count, (XrSwapchainImageBaseHeader*)&ctx.textures[0]); if (result != XR_SUCCESS) { spdlog::error("[VR] Failed to enumerate swapchain images after texture creation."); return "Failed to enumerate swapchain images after texture creation."; } } this->last_resolution = {vr->get_hmd_width(), vr->get_hmd_height()}; spdlog::info("[VR] Successfully created OpenXR swapchains for D3D11"); return std::nullopt; } void D3D11Component::OpenXR::destroy_swapchains() { std::scoped_lock _{this->mtx}; if (this->contexts.empty()) { return; } spdlog::info("[VR] Destroying swapchains."); for (auto i = 0; i < this->contexts.size(); ++i) { auto& ctx = this->contexts[i]; auto result = xrDestroySwapchain(VR::get()->m_openxr->swapchains[i].handle); if (result != XR_SUCCESS) { spdlog::error("[VR] Failed to destroy swapchain {}.", i); } else { spdlog::info("[VR] Destroyed swapchain {}.", i); } for (auto& tex : ctx.textures) { tex.texture->Release(); } ctx.textures.clear(); } this->contexts.clear(); VR::get()->m_openxr->swapchains.clear(); } void D3D11Component::OpenXR::copy(uint32_t swapchain_idx, ID3D11Texture2D* resource) { std::scoped_lock _{this->mtx}; auto vr = VR::get(); if (vr->m_openxr->frame_state.shouldRender != XR_TRUE) { return; } if (!vr->m_openxr->frame_began) { spdlog::error("[VR] OpenXR: Frame not begun when trying to copy."); //return; } if (this->contexts[swapchain_idx].num_textures_acquired > 0) { spdlog::info("[VR] Already acquired textures for swapchain {}?", swapchain_idx); } auto device = g_framework->get_d3d11_hook()->get_device(); // get immediate context ComPtr<ID3D11DeviceContext> context; device->GetImmediateContext(&context); const auto& swapchain = vr->m_openxr->swapchains[swapchain_idx]; auto& ctx = this->contexts[swapchain_idx]; XrSwapchainImageAcquireInfo acquire_info{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO}; uint32_t texture_index{}; LOG_VERBOSE("Acquiring swapchain image for {}", swapchain_idx); auto result = xrAcquireSwapchainImage(swapchain.handle, &acquire_info, &texture_index); if (result != XR_SUCCESS) { spdlog::error("[VR] xrAcquireSwapchainImage failed: {}", vr->m_openxr->get_result_string(result)); } else { ctx.num_textures_acquired++; XrSwapchainImageWaitInfo wait_info{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; //wait_info.timeout = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::seconds(1)).count(); wait_info.timeout = XR_INFINITE_DURATION; LOG_VERBOSE("Waiting on swapchain image for {}", swapchain_idx); result = xrWaitSwapchainImage(swapchain.handle, &wait_info); if (result != XR_SUCCESS) { spdlog::error("[VR] xrWaitSwapchainImage failed: {}", vr->m_openxr->get_result_string(result)); } else { LOG_VERBOSE("Copying swapchain image {} for {}", texture_index, swapchain_idx); context->CopyResource(ctx.textures[texture_index].texture, resource); XrSwapchainImageReleaseInfo release_info{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO}; LOG_VERBOSE("Releasing swapchain image for {}", swapchain_idx); auto result = xrReleaseSwapchainImage(swapchain.handle, &release_info); if (result != XR_SUCCESS) { spdlog::error("[VR] xrReleaseSwapchainImage failed: {}", vr->m_openxr->get_result_string(result)); return; } ctx.num_textures_acquired--; } } } } // namespace vrmod
33.388128
136
0.63642
769ab67ecf0ee03b324e9690cea3ba77cadf5b8a
912
cpp
C++
graph-source-code/463-D/8599017.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/463-D/8599017.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/463-D/8599017.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: MS C++ #include <iostream> #include <cstdio> #include <string> #include <cstring> #include <map> #include <vector> #include <stack> #include <queue> #include <set> #include <cassert> #include <cstdlib> #include <cmath> #include <algorithm> using namespace std; typedef long long ll; typedef pair<int,int> PII; typedef vector<int> VI; const int mod=1000000007; const int MAXN=1002; int n,K; int a[6][MAXN],pos[6][MAXN],dp[MAXN]; void solve(){ scanf("%d%d",&n,&K); for(int i=1;i<=K;i++) for(int j=1;j<=n;j++){ scanf("%d",&a[i][j]); pos[i][a[i][j]]=j; } int k,res=0; for(int j=1;j<=n;j++){ int mx=0; for(int i=1;i<j;i++){ for(k=2;k<=K && pos[k][a[1][i]]<pos[k][a[1][j]];k++); if(k==K+1 && mx<dp[i]) mx=dp[i]; } dp[j]=mx+1; res=max(res,dp[j]); } printf("%d\n",res); } int main() { solve(); return 0; }
15.724138
57
0.541667
769bdd7f174ebb9828896a352014acc70c9af3c4
14,894
cpp
C++
app/uart/main.cpp
wrmlab/wrmos
37067b659aa25e2d85f040ab0d2be85b6f4de485
[ "MIT" ]
16
2018-06-05T15:23:08.000Z
2022-01-06T13:41:44.000Z
app/uart/main.cpp
sergey-worm/wrmos
37067b659aa25e2d85f040ab0d2be85b6f4de485
[ "MIT" ]
null
null
null
app/uart/main.cpp
sergey-worm/wrmos
37067b659aa25e2d85f040ab0d2be85b6f4de485
[ "MIT" ]
3
2018-03-15T16:40:59.000Z
2021-04-01T22:55:15.000Z
//################################################################################################## // // uart - userspace UART driver. // //################################################################################################## #include <stdio.h> #include <string.h> #include <assert.h> #include "sys_utils.h" #include "l4_api.h" #include "wrmos.h" #include "cbuf.h" #define UART_WITH_VIDEO #include "uart.h" // one-directional stream struct Stream_t { Cbuf_t cbuf; // circular buffer Wrm_sem_t sem; // 'irq received' semaphore }; // driver data struct Driver_t { Stream_t tx; // Stream_t rx; // Wrm_mtx_t write_to_uart_mtx; // addr_t ioaddr; // }; static Driver_t driver; int wait_attach_msg(const char* thread_name, L4_thrid_t* client) { // register thread by name word_t key0 = 0; word_t key1 = 0; int rc = wrm_nthread_register(thread_name, &key0, &key1); if (rc) { wrm_loge("attach: wrm_nthread_register(%s) - rc=%u.\n", thread_name, rc); assert(false); } wrm_logi("attach: thread '%s' is registered, key: %lx/%lx.\n", thread_name, key0, key1); L4_utcb_t* utcb = l4_utcb(); // wait attach msg loop L4_thrid_t from = L4_thrid_t::Nil; while (1) { wrm_logi("attach: wait attach msg.\n"); int rc = l4_receive(L4_thrid_t::Any, L4_time_t::Never, &from); if (rc) { wrm_loge("attach: l4_receive() - rc=%u.\n", rc); continue; } word_t ecode = 0; L4_msgtag_t tag = utcb->msgtag(); word_t k0 = utcb->mr[1]; word_t k1 = utcb->mr[2]; if (tag.untyped() != 2 || tag.typed() != 0) { wrm_loge("attach: wrong msg format.\n"); ecode = 1; } if (!ecode && (k0 != key0 || k1 != key1)) { wrm_loge("attach: wrong key.\n"); ecode = 2; } // send reply tag.untyped(1); tag.typed(0); utcb->mr[0] = tag.raw(); utcb->mr[1] = ecode; rc = l4_send(from, L4_time_t::Zero); if (rc) wrm_loge("attach: l4_send(rep) - rc=%d.\n", rc); if (!ecode && !rc) break; // attached } *client = from; wrm_logi("attach: attached to %u.\n", from.number()); return 0; } // read from tx.cbuf and write to uart device // this func may be called from hw-thread and tx-thread void write_to_uart() { //wrm_logd("--: %s().\n", __func__); uart_tx_irq(driver.ioaddr, 0); // disable tx irq unsigned written = 0; // NOTE: The best way is write to UART FIFO char-by-char through uart_putc() // while fifo-is-not-full. But TopUART doesn't allow detect state // fifo-is-not-full. Therefore, we use uart_put_buf() and write FIFO_SZ // bytes. For most UARTs driver return FIFO_SZ=1 --> we will work // as uart_putc() while fifo-is-not-full. For TopUART FIFO_SZ=64, every // writing we put to UART FIFO_SZ bytes. #if 0 // char-by-char // write to uart char-by-char wrm_mtx_lock(&driver.write_to_uart_mtx); while (1) { static char txchar = 0; static int is_there_unsent = 0; // read charecter from tx-buffer if need if (!is_there_unsent) { unsigned read = driver.tx.cbuf.read(&txchar, 1); if (!read) break; is_there_unsent = 1; } // write charecter to uart int rc = uart_putc(driver.ioaddr, txchar); if (rc < 0) { wrm_loge("--: uart_put_buf() - rc=%d.\n", rc); break; // uart tx empty } if (!rc) { wrm_logd("--: uart_tx_full, enable tx irq.\n"); uart_tx_irq(driver.ioaddr, 1); break; } is_there_unsent = 0; written++; } wrm_mtx_unlock(&driver.write_to_uart_mtx); #else // put buf unsigned fifo_sz = 0; char buf[128]; fifo_sz = uart_fifo_size(driver.ioaddr); assert(fifo_sz); if (fifo_sz > sizeof(buf)) { wrm_logw("--: fifo_sz/%u > bufsz/%zu, use %zu.\n", fifo_sz, sizeof(buf), sizeof(buf)); fifo_sz = sizeof(buf); } // write to uart fifo-by-fifo wrm_mtx_lock(&driver.write_to_uart_mtx); while (1) { if (!(uart_status(driver.ioaddr) & Uart_status_tx_ready) && !driver.tx.cbuf.empty()) { //wrm_logd("--: uart_tx_not_ready, data exist -> enable tx irq.\n"); uart_tx_irq(driver.ioaddr, 1); break; } // read charecters from tx-buffer if need unsigned read = driver.tx.cbuf.read(buf, fifo_sz); //wrm_logd("--: read from cbuf %d bytes.\n", read); if (!read) break; // no data anymore // write charecter to uart int rc = uart_put_buf(driver.ioaddr, buf, read); if (rc < 0) { wrm_loge("--: uart_put_buf() - rc=%d.\n", rc); break; } written += rc; if (read != (unsigned) rc) { wrm_loge("--: uart_put_buf() - wr=%u, lost %u bytes.\n", read, read - rc); break; } } wrm_mtx_unlock(&driver.write_to_uart_mtx); #endif //wrm_logd("--: written=%u.\n", written); } size_t put_to_txbuf(const char* buf, unsigned sz) { // put line by line and add '\r' unsigned written = 0; while (written < sz) { const char* pos = buf + written; const char* end = strchr(pos, '\n'); unsigned l = end ? (end + 1 - pos) : (sz - written); // length for line or tail // write all line unsigned wr = driver.tx.cbuf.write(pos, l); written += wr; if (wr != l) { wrm_loge("tx: buffer full, write=%u, written=%u, lost=%u.\n", l, wr, l - wr); break; // buf full } if (end) { wr = driver.tx.cbuf.write("\r", 1); if (wr != 1) { wrm_loge("tx: buffer full, write=1, written=%u.\n", wr); break; // buf full } } } return written; } long tx_thread(long unused) { wrm_logi("tx: hello: %s.\n", __func__); wrm_logi("tx: myid=%u.\n", l4_utcb()->global_id().number()); // wait for attach message L4_thrid_t client = L4_thrid_t::Nil; int rc = wait_attach_msg("uart-tx-stream", &client); if (rc) { wrm_loge("tx: wait_attach_msg() - rc=%d.\n", rc); assert(false); } wrm_logi("tx: attached to client=%u\n", client.number()); // prepare for requests L4_utcb_t* utcb = l4_utcb(); static char tx_buf[0x1000]; L4_acceptor_t acceptor = L4_acceptor_t::create(L4_fpage_t::create_nil(), true); // allow strings L4_string_item_t bitem = L4_string_item_t::create_simple((word_t)tx_buf, sizeof(tx_buf)-1); utcb->br[0] = acceptor.raw(); utcb->br[1] = bitem.word0(); utcb->br[2] = bitem.word1(); // wait request loop while (1) { //wrm_logi("tx: wait request.\n"); L4_thrid_t from = L4_thrid_t::Nil; int rc = l4_receive(client, L4_time_t::Never, &from); if (rc) { wrm_loge("tx: l4_receive() - rc=%u.\n", rc); assert(false); } L4_msgtag_t tag = utcb->msgtag(); word_t mr[L4_utcb_t::Mr_words]; memcpy(mr, utcb->mr, (1 + tag.untyped() + tag.typed()) * sizeof(word_t)); from = tag.propagated() ? utcb->sender() : from; //wrm_logi("tx: received: from=%u, tag=0x%x, u=%u, t=%u, mr[1]=0x%x, mr[2]=0x%x.\n", // from.number(), tag.raw(), tag.untyped(), tag.typed(), mr[1], mr[2]); L4_typed_item_t item = L4_typed_item_t::create(mr[1], mr[2]); L4_string_item_t sitem = L4_string_item_t::create(mr[1], mr[2]); assert(tag.untyped() == 0); assert(tag.typed() == 2); assert(item.is_string_item()); //wrm_logi("tx: request is got: sz=%u.\n", sitem.length()); //wrm_logi("tx: request is got: buf=0x%x, sz=%u, txbf=0x%p: %.*s.\n", // sitem.pointer(), sitem.length(), tx_buf, sitem.length(), (char*)sitem.pointer()); ((char*)sitem.pointer())[sitem.length()] = '\0'; // add terminator unsigned written = put_to_txbuf((char*)sitem.pointer(), sitem.length()); if (written != sitem.length()) { wrm_loge("tx: buffer full, write=%u, written=%u, lost=%u.\n", sitem.length(), written, sitem.length() - written); } //wrm_logd("tx: written=%u to cbuf.\n", written); if (written) { write_to_uart(); } // send reply to client tag.propagated(false); tag.ipc_label(0); tag.untyped(2); tag.typed(0); utcb->mr[0] = tag.raw(); utcb->mr[1] = rc; // ecode utcb->mr[2] = written; // bytes written rc = l4_send(from, L4_time_t::Zero); if (rc) { wrm_loge("l4_send(rep) - rc=%u.\n", rc); l4_kdb("tx: l4_send(cli) is failed"); } } return 0; } long rx_thread(long unused) { wrm_logi("rx: hello: %s.\n", __func__); wrm_logi("rx: myid=%u.\n", l4_utcb()->global_id().number()); // wait for attach message L4_thrid_t client = L4_thrid_t::Nil; int rc = wait_attach_msg("uart-rx-stream", &client); if (rc) { wrm_loge("rx: wait_attach_msg() - rc=%u.\n", rc); assert(false); } wrm_logi("rx: attached to client=%u\n", client.number()); // prepare for requests L4_utcb_t* utcb = l4_utcb(); static char rx_buf[0x1000]; L4_acceptor_t acceptor = L4_acceptor_t::create(L4_fpage_t::create_nil(), false); utcb->br[0] = acceptor.raw(); // wait request loop while (1) { //wrm_logi("rx: wait request.\n"); L4_thrid_t from = L4_thrid_t::Nil; int rc = l4_receive(client, L4_time_t::Never, &from); L4_msgtag_t tag = utcb->msgtag(); if (rc) { wrm_loge("rx: l4_receive() - rc=%u.\n", rc); assert(false); } word_t mr[256]; memcpy(mr, utcb->mr, (1 + tag.untyped() + tag.typed()) * sizeof(word_t)); from = tag.propagated() ? utcb->sender() : from; //wrm_logi("rx: received ipc: from=%u, tag=0x%lx, u=%u, t=%u, mr[1]=0x%lx, mr[2]=0x%lx.\n", // from.number(), tag.raw(), tag.untyped(), tag.typed(), mr[1], mr[2]); assert(tag.untyped() == 1); assert(tag.typed() == 0); size_t cli_bfsz = mr[1]; size_t read = 0; while (1) { read = driver.rx.cbuf.read(rx_buf, min(sizeof(rx_buf), cli_bfsz)); if (read) break; rc = wrm_sem_wait(&driver.rx.sem); // wait rx operation if (rc) { wrm_loge("wrm_sem_wait(rx) - rc=%d.\n", rc); rc = -1; break; } } //wrm_logi("rx: read=%u.\n", read); // send reply to client L4_string_item_t sitem = L4_string_item_t::create_simple((word_t)rx_buf, read); tag.propagated(false); tag.ipc_label(0); // ? tag.untyped(1); tag.typed(2); utcb->mr[0] = tag.raw(); utcb->mr[1] = rc; // ecode utcb->mr[2] = sitem.word0(); // utcb->mr[3] = sitem.word1(); // rc = l4_send(from, L4_time_t::Zero); if (rc) { wrm_loge("l4_send(rep) - rc=%u.\n", rc); l4_kdb("rx: l4_send(cli) is failed"); } } return 0; } void read_from_uart() { char buf[64]; unsigned read = 0; while (1) { // read data from uart unsigned rd = 0; char ch = 0; while (rd < sizeof(buf) && (ch = uart_getc(driver.ioaddr))) buf[rd++] = ch; //wrm_logd("hw: read from uart %d bytes.\n", rc); //wrm_logd("hw: rx(%u): '%.*s' (rx=%u, tx=%u all=%u)\n", // rc, rc, buf, cnt_rx, cnt_tx, cnt_all); read += rd; if (!rd) break; // write data to rx-buffer unsigned written = driver.rx.cbuf.write(buf, rd); if (written != rd) { wrm_loge("hw: rx_buf full, lost %u bytes.\n", rd - written); break; } //wrm_logi("post rx sem.\n"); int rc = wrm_sem_post(&driver.rx.sem); if (rc) wrm_loge("hw: wrm_sem_post(rx.sem) - rc=%d.\n", rc); } if (!read) wrm_loge("hw: no data for read in uart.\n"); } void irq_thread(const char* uart_dev_name) { // rename main thread memcpy(&l4_utcb()->tls[0], "u-hw", 4); // attach to IRQ unsigned intno = -1; int rc = wrm_dev_attach_int(uart_dev_name, &intno); wrm_logi("attach_int: dev=%s, irq=%u.\n", uart_dev_name, intno); if (rc) { wrm_loge("wrm_dev_attach_int() - rc=%d.\n", rc); return; } uart_rx_irq(driver.ioaddr, 1); unsigned icnt_rx = 0; unsigned icnt_tx = 0; unsigned icnt_all = 0; unsigned icnt_nil = 0; // wait interrupt loop while (1) { // wait interrupt //wrm_logd("hw: wait interrupt ... (irq: rx/tx/all/nil=%u/%u/%u/%u).\n", // icnt_rx, icnt_tx, icnt_all, icnt_nil); rc = wrm_dev_wait_int(intno, Uart_need_ack_irq_before_reenable); assert(!rc); icnt_all++; unsigned loop_cnt = 0; while (1) { int status = uart_status(driver.ioaddr); int tx_ready = !!(status & Uart_status_tx_ready); int rx_ready = !!(status & Uart_status_rx_ready); int tx_irq = !!(status & Uart_status_tx_irq); int rx_irq = !!(status & Uart_status_rx_irq); //wrm_logd("hw: status: loop=%u: ready_rx/tx=%d/%d, irq_rx/tx=%d/%d.\n", // loop_cnt, rx_ready, tx_ready, rx_irq, tx_irq); if (!rx_irq && !tx_irq) { // we got real irq but UART hasn't interrupt inside int_status register //wrm_loge("hw: no irq: loop=%u: ready_rx/tx=%d/%d, irq_rx/tx=%d/%d.\n", // loop_cnt, rx_ready, tx_ready, rx_irq, tx_irq); icnt_nil++; break; } if (rx_irq) icnt_rx++; if (tx_irq) icnt_tx++; if (rx_ready) read_from_uart(); if (tx_ready) write_to_uart(); loop_cnt++; int need_check_status = uart_clear_irq(driver.ioaddr); if (!need_check_status) break; } } } int main(int argc, const char* argv[]) { wrm_logi("hello.\n"); wrm_logi("argc=%d, argv=0x%p.\n", argc, argv); for (int i=0; i<argc; i++) wrm_logi("arg[%d] = %s.\n", i, argv[i]); wrm_logi("myid=%u.\n", l4_utcb()->global_id().number()); // map IO const char* uart_dev_name = argc>=2 ? argv[1] : ""; addr_t ioaddr = -1; size_t iosize = -1; int rc = wrm_dev_map_io(uart_dev_name, &ioaddr, &iosize); if (rc) { wrm_loge("wrm_dev_map_io() - rc=%d.\n", rc); return -1; } wrm_logi("map_io: addr=0x%lx, sz=0x%zx.\n", ioaddr, iosize); driver.ioaddr = ioaddr; static char rx_buf[0x1000]; static char tx_buf[0x2000]; driver.rx.cbuf.init(rx_buf, sizeof(rx_buf)); driver.tx.cbuf.init(tx_buf, sizeof(tx_buf)); rc = wrm_sem_init(&driver.rx.sem, Wrm_sem_binary, 0); if (rc) { wrm_loge("wrm_sem_init(rx.sem) - rc=%d.", rc); return -2; } rc = wrm_mtx_init(&driver.write_to_uart_mtx); if (rc) { wrm_loge("wrm_mtx_init(write_to_uart_mtx) - rc=%d.", rc); return -3; } // I do not known sys_freq. // Do not init, I hope uart was initialized by kernel. // uart_init(ioaddr, 115200, 40*1000*1000/*?*/); // create tx thread L4_fpage_t stack_fp = wrm_pgpool_alloc(Cfg_page_sz); L4_fpage_t utcb_fp = wrm_pgpool_alloc(Cfg_page_sz); assert(!stack_fp.is_nil()); assert(!utcb_fp.is_nil()); L4_thrid_t txid = L4_thrid_t::Nil; rc = wrm_thr_create(utcb_fp, tx_thread, 0, stack_fp.addr(), stack_fp.size(), 255, "u-tx", Wrm_thr_flag_no, &txid); wrm_logi("create_thread: rc=%d, id=%u.\n", rc, txid.number()); if (rc) { wrm_loge("wrm_thr_create(tx) - rc=%d.", rc); return -4; } // create rx thread stack_fp = wrm_pgpool_alloc(Cfg_page_sz); utcb_fp = wrm_pgpool_alloc(Cfg_page_sz); assert(!stack_fp.is_nil()); assert(!utcb_fp.is_nil()); L4_thrid_t rxid = L4_thrid_t::Nil; rc = wrm_thr_create(utcb_fp, rx_thread, 0, stack_fp.addr(), stack_fp.size(), 255, "u-rx", Wrm_thr_flag_no, &rxid); wrm_logi("create_thread: rc=%d, id=%u.\n", rc, rxid.number()); if (rc) { wrm_loge("wrm_thr_create(rx) - rc=%d.\n", rc); return -5; } irq_thread(uart_dev_name); wrm_loge("return from app uart - something going wrong.\n"); return 0; }
24.864775
100
0.606889
769cf243a888d3bcc6809d48babe1b071ff489e7
319
cpp
C++
WumbukDraw/staticimage.cpp
YangPeihao1203/WumbukDraw
e0854e62cc050c99deda04a849d46824f458cbbc
[ "MIT" ]
null
null
null
WumbukDraw/staticimage.cpp
YangPeihao1203/WumbukDraw
e0854e62cc050c99deda04a849d46824f458cbbc
[ "MIT" ]
null
null
null
WumbukDraw/staticimage.cpp
YangPeihao1203/WumbukDraw
e0854e62cc050c99deda04a849d46824f458cbbc
[ "MIT" ]
null
null
null
#include "staticimage.h" StaticImage::StaticImage() { } void StaticImage::inSertPicture(QString filePath,QGraphicsScene *parent) { QPixmap pixmap =QPixmap::fromImage(QImage(filePath)); this->setPixmap(pixmap); setFlag(QGraphicsItem::ItemIsMovable); }
19.9375
73
0.623824
371dbadc8e93569fead136aa3ca52d43f1fe2f8f
1,522
cpp
C++
pepnovo/src/QuickClustering.cpp
compomics/jwrapper-pepnovo
1bd21a4910d7515dfab7747711917176a6b5ce99
[ "Apache-2.0" ]
null
null
null
pepnovo/src/QuickClustering.cpp
compomics/jwrapper-pepnovo
1bd21a4910d7515dfab7747711917176a6b5ce99
[ "Apache-2.0" ]
null
null
null
pepnovo/src/QuickClustering.cpp
compomics/jwrapper-pepnovo
1bd21a4910d7515dfab7747711917176a6b5ce99
[ "Apache-2.0" ]
null
null
null
#include "QuickClustering.h" #include "PMCSQS.h" #include "auxfun.h" // the sim matrix stores the similarity distances computed between clusters int num_sim_matrix_spectra = 0; unsigned char * sim_matrix = NULL; unsigned char * max_sim_addr = NULL; void print_byte(unsigned char byte) { int i; unsigned char mask=0X1; for (i=0; i<8; i++) { cout << ( (byte & mask) ? '1' : '0'); mask <<= 1; } } void mark_bit_zero(unsigned char *addr, int position) { const unsigned char ANDmasks[]={254,253,251,247,239,223,191,127}; int bit_offset = (position & 0X7); int byte_offset = (position >> 3); *(addr+byte_offset) &= ANDmasks[bit_offset]; } void mark_bit_one(unsigned char *addr, int position) { const unsigned char ORmasks[] ={1,2,4,8,16,32,64,128}; int bit_offset = (position & 0X7); int byte_offset = (position >> 3); *(addr+byte_offset) |= ORmasks[bit_offset]; } // returns full int assumes we are at position 31 in the 4 bytes int get_matrix_32_bits(unsigned char *row_start, int position) { int cell_off = (position >> 5); return (*((int *)row_start+cell_off)); // return 1; } int get_matrix_val(unsigned char *row_start, int position) { const unsigned char masks[] ={1,2,4,8,16,32,64,128}; int bit_offset = (position & 0X7); int byte_offset = (position >> 3); return ((*(row_start+byte_offset) & masks[bit_offset])); // return 1; } // global debugging variable int wrongly_filtered_spectra;
20.293333
76
0.65046
372164b0b94deb130806f24ae1c6cf3f7bc02514
2,280
cpp
C++
src/stmt.cpp
magicmoremagic/bengine-sqlite
4e777cbbca9e64be5c49a24778847bf8e23fd99d
[ "MIT" ]
null
null
null
src/stmt.cpp
magicmoremagic/bengine-sqlite
4e777cbbca9e64be5c49a24778847bf8e23fd99d
[ "MIT" ]
null
null
null
src/stmt.cpp
magicmoremagic/bengine-sqlite
4e777cbbca9e64be5c49a24778847bf8e23fd99d
[ "MIT" ]
null
null
null
#include "pch.hpp" #include "stmt.hpp" #include "db.hpp" #include "result_code.hpp" #include "sqlite.hpp" #include <cassert> #include <limits> namespace be::sqlite { /////////////////////////////////////////////////////////////////////////////// /// \brief Compiles the provided SQL query against the provided database and /// constructs a Stmt object to represent it. /// /// \details A statement Id will be generated automatically by hashing the /// SQL text provided. /// /// \note The lifetime of the provided Db object must extend beyond the end /// of the newly created Stmt object. /// /// \param db The database on which the statement is to be executed. /// \param sql The SQL text of the statement to compile. Stmt::Stmt(Db& db, const S& sql) : Stmt(db, Id(sql), sql) { } /////////////////////////////////////////////////////////////////////////////// /// \brief Compiles the provided SQL query against the provided database and /// constructs a Stmt object to represent it using the provided ID. /// /// \note The lifetime of the provided Db object must extend beyond the end /// of the newly created Stmt object. /// /// \param db The database on which the statement is to be executed. /// \param id The Id of the statement. /// \param sql The SQL text of the statement to compile. Stmt::Stmt(Db& db, Id id, const S& sql) { sqlite3_stmt* stmt = nullptr; const char* tail = nullptr; const char* start = sql.c_str(); const char* end = start + sql.length(); assert(sql.length() + 1 < static_cast<std::size_t>(std::numeric_limits<int>::max())); int result = sqlite3_prepare_v2(db.raw(), start, static_cast<int>(sql.length() + 1), &stmt, &tail); if (result != SQLITE_OK || !stmt) { throw SqlTrace(db.raw(), ext_result_code(result), sql); } else if (tail && tail < end) { throw SqlTrace(ExtendedResultCode::api_misuse, "Multiple SQL statements provided to Stmt constructor!", sql); } else { stmt_ptr_ = sqlite3_stmt_ptr(stmt); stmt_ = stmt; con_ = db.raw(); id_ = id; } } /////////////////////////////////////////////////////////////////////////////// void Stmt::deleter::operator()(sqlite3_stmt* stmt) { sqlite3_finalize(stmt); } } // be::sqlite
37.377049
115
0.59386
3721ef1e6c9619445cf4d06c28898e68e94f01de
7,611
cpp
C++
library/Custom/fastIO.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
4
2021-01-05T09:25:59.000Z
2021-09-27T03:57:28.000Z
library/Custom/fastIO.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
null
null
null
library/Custom/fastIO.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
null
null
null
#ifndef CUST_DEBUG #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("unroll-loops") #endif #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define ALL(x) x.begin(),x.end() #define PB push_back #define F first #define S second #define ll long long #define double long double #define MP make_pair using namespace std; template <typename K, typename V = __gnu_pbds::null_type> using tree = __gnu_pbds::tree<K, V, less<K>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>; using llong = long long; auto isz = [](const auto& c) { return int(c.size()); }; mt19937 rng((size_t) make_shared<char>().get()); #ifndef _LIB_FASTIO_ #define _LIB_FASTIO_ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wall" #pragma GCC diagnostic ignored "-Wextra" #pragma GCC diagnostic ignored "-Wconversion" /** Fast allocation */ #ifdef FAST_ALLOCATOR_MEMORY int allocator_pos = 0; char allocator_memory[(int)FAST_ALLOCATOR_MEMORY]; inline void * operator new ( size_t n ) { char *res = allocator_memory + allocator_pos; allocator_pos += n; assert(allocator_pos <= (int)FAST_ALLOCATOR_MEMORY); return (void *)res; } inline void operator delete ( void * ) noexcept { } //inline void * operator new [] ( size_t ) { assert(0); } //inline void operator delete [] ( void * ) { assert(0); } #endif /** Fast input-output */ /** Read */ static const int buf_size = 4096; static unsigned char buf[buf_size]; static int buf_len = 0, buf_pos = 0; inline bool isEof() { if (buf_pos == buf_len) { buf_pos = 0, buf_len = fread(buf, 1, buf_size, stdin); if (buf_pos == buf_len) return 1; } return 0; } inline int getChar() { return isEof() ? -1 : buf[buf_pos++]; } inline int peekChar() { return isEof() ? -1 : buf[buf_pos]; } inline bool seekEof() { int c; while ((c = peekChar()) != -1 && c <= 32) buf_pos++; return c == -1; } inline void skipBlanks() { while (!isEof() && buf[buf_pos] <= 32U) buf_pos++; } inline int readChar() { int c = getChar(); while (c != -1 && c <= 32) c = getChar(); return c; } inline unsigned int readUInt() { int c = readChar(); unsigned int x = 0; while ('0' <= c && c <= '9') x = x * 10 + c - '0', c = getChar(); return x; } template <class T = int> inline T readInt() { int s = 1, c = readChar(); T x = 0; if (c == '-') s = -1, c = getChar(); else if (c == '+') c = getChar(); while ('0' <= c && c <= '9') x = x * 10 + c - '0', c = getChar(); return s == 1 ? x : -x; } inline long long readLong() { return readInt<long long>(); } inline double readDouble() { int s = 1, c = readChar(); double x = 0; if (c == '-') s = -1, c = getChar(); while ('0' <= c && c <= '9') x = x * 10 + c - '0', c = getChar(); if (c == '.') { c = getChar(); double coef = 1; while ('0' <= c && c <= '9') x += (c - '0') * (coef *= 1e-1), c = getChar(); } return s == 1 ? x : -x; } inline void readWord(char *s) { int c = readChar(); while (c > 32) *s++ = c, c = getChar(); *s = 0; } inline void readWord(string &s) { s.clear(); int c = readChar(); while (c > 32) s += c, c = getChar(); } inline bool readLine(char *s) { int c = getChar(); while (c != '\n' && c != -1) *s++ = c, c = getChar(); *s = 0; return c != -1; } inline bool readLine(string &s) { s.clear(); int c = getChar(); while (c != '\n' && c != -1) s += c, c = getChar(); return c != -1; } /** Write */ static int write_buf_pos = 0; static char write_buf[buf_size]; inline void writeChar(int x) { if (write_buf_pos == buf_size) fwrite(write_buf, 1, buf_size, stdout), write_buf_pos = 0; write_buf[write_buf_pos++] = x; } inline void flush() { if (write_buf_pos) { fwrite(write_buf, 1, write_buf_pos, stdout), write_buf_pos = 0; fflush(stdout); } } template <class T> inline void writeInt(T x, char end = 0, int output_len = -1) { if (x < 0) writeChar('-'), x = -x; char s[24]; int n = 0; while (x || !n) s[n++] = '0' + x % 10, x /= 10; while (n < output_len) s[n++] = '0'; while (n--) writeChar(s[n]); if (end) writeChar(end); } inline void writeWord(const char *s) { while (*s) writeChar(*s++); } inline void writeWord(const string& s) { writeWord(s.c_str()); } inline void writeDouble(double x, int output_len = 11) { if (x < 0) writeChar('-'), x = -x; int t = (int)x; writeInt(t), x -= t; writeChar('.'); for (int i = output_len - 1; i > 0; i--) { x *= 10; t = std::min(9, (int)x); writeChar('0' + t), x -= t; } x *= 10; t = std::min(9, (int)(x + 0.5)); writeChar('0' + t); } /** Buffer flusher */ static struct buffer_flusher_t { ~buffer_flusher_t() { flush(); } } buffer_flusher; /** Reader and writer */ struct fast_reader { fast_reader& operator>>(int& n) { n = readInt(); return *this; } fast_reader& operator>>(unsigned int& n) { n = readUInt(); return *this; } fast_reader& operator>>(llong& n) { n = readLong(); return *this; } fast_reader& operator>>(double& n) { n = readDouble(); return *this; } fast_reader& operator>>(float& n) { n = (float) readDouble(); return *this; } fast_reader& operator>>(string& s) { readWord(s); return *this; } fast_reader& operator>>(char& c) { c = (char) readChar(); return *this; } template<typename T> fast_reader& operator>>(vector<T>& a) { for (T& i : a) { (*this) >> i; } return *this; } } f_reader; struct fast_writer { template<typename T> fast_writer& operator<<(T n) { writeInt(n); return *this; } fast_writer& operator<<(double n) { writeDouble(n); return *this; } fast_writer& operator<<(float n) { writeDouble(n); return *this; } fast_writer& operator<<(const string& s) { writeWord(s); return *this; } fast_writer& operator<<(const char* s) { writeWord(s); return *this; } fast_writer& operator<<(char c) { writeChar(c); return *this; } template<typename T> fast_writer& operator<<(const vector<T>& a) { for (size_t i = 0; i < a.size(); ++i) { if (i) { (*this) << ' '; } (*this) << a[i]; } return *this; } void flush() { ::flush(); } } f_writer; #define cin f_reader #define cout f_writer #pragma GCC diagnostic pop #endif //_LIB_FASTIO_ #ifndef _LIB_UTILS_ #define _LIB_UTILS_ template <typename T, T val = T()> auto make_vector(size_t d) { return vector<T>(d, val); } template <typename T, T val = T(), typename ...Ds> auto make_vector(size_t d, Ds... ds) { return vector<decltype(make_vector<T, val>(ds...))>(d, make_vector<T, val>(ds...)); } #endif //_LIB_UTILS_ #ifdef CUST_DEBUG template<class K, class V>ostream& operator<<(ostream&s,const pair<K,V>&p){s<<'<'<<p.F<<','<<p.S<<'>';return s;} template<class T, class=typename T::value_type, class=typename enable_if<!is_same<T,string>::value>::type> ostream& operator<<(ostream&s,const T&v){s<<'[';for(auto&x:v){s<<x<<", ";}if(!v.empty()){s<<"\b\b";}s<<']';return s;} void __prnt(){cerr<<endl;} template<class T, class...Ts>void __prnt(T&&a,Ts&&...etc){cerr<<a<<' ';__prnt(etc...);} #define print(...) __prnt(__VA_ARGS__) #else #define print(...) #endif const long long MAXN = 1e5 +7; void check(){ } int32_t main(){ int t = 1; // cin >> t; for(int i = 1 ; i <= t ;i++){ check(); } return 0; }
22.189504
117
0.581658
3722de4415fda998571a8d968689831478fc0bf1
43
hpp
C++
src/boost_mpl_aux__type_wrapper.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_mpl_aux__type_wrapper.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_mpl_aux__type_wrapper.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/mpl/aux_/type_wrapper.hpp>
21.5
42
0.790698
372398f052543364536b3337a1043e781c804f22
7,932
cpp
C++
src/Modules/UI/Macro Elements/Options_Graphics.cpp
Yattabyte/reVision
014cb450d1c30b8f64abbacf00425b4f814b05a0
[ "MIT" ]
5
2018-10-12T17:40:17.000Z
2020-11-20T10:49:34.000Z
src/Modules/UI/Macro Elements/Options_Graphics.cpp
Yattabyte/reVision
014cb450d1c30b8f64abbacf00425b4f814b05a0
[ "MIT" ]
71
2018-07-19T01:59:38.000Z
2020-03-29T18:03:13.000Z
src/Modules/UI/Macro Elements/Options_Graphics.cpp
Yattabyte/reVision
014cb450d1c30b8f64abbacf00425b4f814b05a0
[ "MIT" ]
1
2022-03-24T13:21:25.000Z
2022-03-24T13:21:25.000Z
#include "Modules/UI/Macro Elements/Options_Graphics.h" #include "Modules/UI/Basic Elements/Slider.h" #include "Modules/UI/Basic Elements/SideList.h" #include "Modules/UI/Basic Elements/Toggle.h" #include "Engine.h" Options_Graphics::Options_Graphics(Engine& engine) : Options_Pane(engine) { // Title m_title->setText("Graphics Options"); // Material Size Option float materialSize = 1024; engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_MATERIAL_SIZE, materialSize); auto element_material_list = std::make_shared<SideList>(engine); element_material_list->setStrings({ "Low", "Medium", "High", "Very High", "Ultra" }); m_materialSizes = { 128.0F, 256.0F, 512.0F, 1024.0F, 2048.0F }; int counter = 0; int index = 0; for (const auto& size : m_materialSizes) { if (materialSize == size) index = counter; counter++; } element_material_list->setIndex(index); addOption(engine, element_material_list, 1.0F, "Texture Quality:", "Adjusts the resolution of in-game geometry textures.", static_cast<int>(SideList::Interact::on_index_changed), [&, element_material_list]() { setTextureResolution(element_material_list->getIndex()); }); // Shadow Size Option float shadowSize = 1024; engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_SHADOW_SIZE, shadowSize); auto element_shadow_list = std::make_shared<SideList>(engine); element_shadow_list->setStrings({ "Low", "Medium", "High", "Very High", "Ultra" }); m_shadowSizes = { 128.0F, 256.0F, 512.0F, 1024.0F, 2048.0F }; counter = 0; index = 0; for (const auto& size : m_shadowSizes) { if (shadowSize == size) index = counter; counter++; } element_shadow_list->setIndex(index); addOption(engine, element_shadow_list, 1.0F, "Shadow Quality:", "Adjusts the resolution of all dynamic light shadows textures.", static_cast<int>(SideList::Interact::on_index_changed), [&, element_shadow_list]() { setShadowSize(element_shadow_list->getIndex()); }); // Reflection Size Option float envSize = 1024; engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_ENVMAP_SIZE, envSize); auto element_env_list = std::make_shared<SideList>(engine); element_env_list->setStrings({ "Low", "Medium", "High", "Very High", "Ultra" }); m_reflectionSizes = { 128.0F, 256.0F, 512.0F, 1024.0F, 2048.0F }; counter = 0; index = 0; for (const auto& size : m_reflectionSizes) { if (envSize == size) index = counter; counter++; } element_env_list->setIndex(index); addOption(engine, element_env_list, 1.0F, "Reflection Quality:", "Adjusts the resolution of all environment map textures.", static_cast<int>(SideList::Interact::on_index_changed), [&, element_env_list]() { setReflectionSize(element_env_list->getIndex()); }); // Light Bounce Option float bounceSize = 1024; engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_RH_BOUNCE_SIZE, bounceSize); auto element_bounce_list = std::make_shared<SideList>(engine); element_bounce_list->setStrings({ "Very Low", "Low", "Medium", "High", "Very High", "Ultra" }); m_bounceQuality = { 8, 12, 16, 24, 32, 64 }; counter = 0; index = 0; for (const auto& size : m_bounceQuality) { if (bounceSize == size) index = counter; counter++; } element_bounce_list->setIndex(index); addOption(engine, element_bounce_list, 1.0F, "Light Bounce Quality:", "Adjusts the resolution of the real-time GI simulation.", static_cast<int>(SideList::Interact::on_index_changed), [&, element_bounce_list]() { setBounceQuality(element_bounce_list->getIndex()); }); // Shadow Count Option float maxShadowCasters = 6.0F; engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_SHADOW_MAX_PER_FRAME, maxShadowCasters); auto maxShadow_slider = std::make_shared<Slider>(engine, maxShadowCasters, glm::vec2(1.0F, 100.0F)); addOption(engine, maxShadow_slider, 0.75F, "Max Concurrent Shadows:", "Set the maximum number of shadows updated per frame.", static_cast<int>(Slider::Interact::on_value_change), [&, maxShadow_slider]() { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_SHADOW_MAX_PER_FRAME, maxShadow_slider->getValue()); }); // Envmap Count Option float maxReflectionCasters = 6.0F; engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_ENVMAP_MAX_PER_FRAME, maxReflectionCasters); auto maxReflection_slider = std::make_shared<Slider>(engine, maxReflectionCasters, glm::vec2(1.0F, 100.0F)); addOption(engine, maxReflection_slider, 0.75F, "Max Concurrent Reflections:", "Set the maximum number of reflections updated per frame.", static_cast<int>(Slider::Interact::on_value_change), [&, maxReflection_slider]() { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_ENVMAP_MAX_PER_FRAME, maxReflection_slider->getValue()); }); // Bloom Option bool element_bloom_state = true; engine.getPreferenceState().getOrSetValue<bool>(PreferenceState::Preference::C_BLOOM, element_bloom_state); auto element_bloom = std::make_shared<Toggle>(engine, element_bloom_state); addOption(engine, element_bloom, 0.5F, "Bloom:", "Turns the bloom effect on or off.", static_cast<int>(Toggle::Interact::on_toggle), [&, element_bloom]() { setBloom(element_bloom->isToggled()); }); // SSAO Option bool element_ssao_state = true; engine.getPreferenceState().getOrSetValue<bool>(PreferenceState::Preference::C_SSAO, element_ssao_state); auto element_ssao = std::make_shared<Toggle>(engine, element_ssao_state); addOption(engine, element_ssao, 0.5F, "SSAO:", "Turns screen-space ambient occlusion effect on or off. Works with baked AO.", static_cast<int>(Toggle::Interact::on_toggle), [&, element_ssao]() { setSSAO(element_ssao->isToggled()); }); // SSR Option bool element_ssr_state = true; engine.getPreferenceState().getOrSetValue<bool>(PreferenceState::Preference::C_SSR, element_ssr_state); auto element_ssr = std::make_shared<Toggle>(engine, element_ssr_state); addOption(engine, element_ssr, 0.5F, "SSR:", "Turns screen-space reflections on or off. Works with baked reflections.", static_cast<int>(Toggle::Interact::on_toggle), [&, element_ssr]() { setSSR(element_ssr->isToggled()); }); // FXAA Option bool element_fxaa_state = true; engine.getPreferenceState().getOrSetValue<bool>(PreferenceState::Preference::C_FXAA, element_fxaa_state); auto element_fxaa = std::make_shared<Toggle>(engine, element_fxaa_state); addOption(engine, element_fxaa, 0.5F, "FXAA:", "Turns fast approximate anti-aliasing on or off.", static_cast<int>(Toggle::Interact::on_toggle), [&, element_fxaa]() { setFXAA(element_fxaa->isToggled()); }); } void Options_Graphics::setTextureResolution(const size_t& index) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_MATERIAL_SIZE, m_materialSizes[index]); } void Options_Graphics::setShadowSize(const size_t& index) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_SHADOW_SIZE, m_shadowSizes[index]); } void Options_Graphics::setReflectionSize(const size_t& index) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_ENVMAP_SIZE, m_reflectionSizes[index]); } void Options_Graphics::setBounceQuality(const size_t& index) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_RH_BOUNCE_SIZE, m_bounceQuality[index]); } void Options_Graphics::setBloom(const bool& b) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_BLOOM, b ? 1.0F : 0.0F); } void Options_Graphics::setSSAO(const bool& b) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_SSAO, b ? 1.0F : 0.0F); } void Options_Graphics::setSSR(const bool& b) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_SSR, b ? 1.0F : 0.0F); } void Options_Graphics::setFXAA(const bool& b) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_FXAA, b ? 1.0F : 0.0F); }
50.522293
271
0.757186
3726cc4dcad99bf88a8ef4a4fd269dd02625331c
3,951
cc
C++
verilog/analysis/checkers/disable_statement_rule_test.cc
imphil/verible
cc9ec78b29e2e0190f6244a7d8981a2a90d77d79
[ "Apache-2.0" ]
487
2019-11-07T02:16:12.000Z
2021-07-08T14:44:12.000Z
verilog/analysis/checkers/disable_statement_rule_test.cc
hzeller/verible
c926ededf7953febb5f577b081474987d0f0209d
[ "Apache-2.0" ]
704
2019-11-12T18:00:12.000Z
2021-07-08T08:21:31.000Z
verilog/analysis/checkers/disable_statement_rule_test.cc
hzeller/verible
c926ededf7953febb5f577b081474987d0f0209d
[ "Apache-2.0" ]
96
2019-11-12T06:21:03.000Z
2021-07-06T23:20:39.000Z
// Copyright 2017-2020 The Verible Authors. // // 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 "verilog/analysis/checkers/disable_statement_rule.h" #include <initializer_list> #include "common/analysis/linter_test_utils.h" #include "common/analysis/syntax_tree_linter_test_utils.h" #include "common/text/symbol.h" #include "gtest/gtest.h" #include "verilog/CST/verilog_nonterminals.h" #include "verilog/CST/verilog_treebuilder_utils.h" #include "verilog/analysis/verilog_analyzer.h" #include "verilog/parser/verilog_token_enum.h" namespace verilog { namespace analysis { namespace { using verible::LintTestCase; using verible::RunLintTestCases; TEST(DisableStatementTest, FunctionPass) { const std::initializer_list<LintTestCase> kDisableStatementTestCases = { {""}, {"module m;\ninitial begin;\n", "fork\n", "begin\n#6;\nend\n", "begin\n#3;\nend\n", "join_any\n", "disable fork;\n", "end\nendmodule"}, {"module m;\ninitial begin\n", "fork\n", "begin : foo\n", "disable foo;\n", "end\n", "join_any\n", "end\nendmodule"}, {"module m;\ninitial begin\n", "fork\n", "begin : foo\n", "begin : foo_2\n", "disable foo_2;\n", "end\n", "end\n", "join_any\n", "end\nendmodule"}, {"module m;\ninitial begin\n", "fork\n", "begin : foo\n", "begin : foo_2\n", "disable foo;\n", "end\n", "end\n", "join_any\n", "end\nendmodule"}, }; RunLintTestCases<VerilogAnalyzer, DisableStatementNoLabelsRule>( kDisableStatementTestCases); } TEST(DisableStatementTest, ForkDisableStatementsFail) { constexpr int kToken = TK_disable; const std::initializer_list<LintTestCase> kDisableStatementTestCases = { {"module m;\ninitial begin\n", "fork\n", "begin\n#6;\nend\n", "begin\n#3;\nend\n", "join_any\n", {kToken, "disable"}, " fork_invalid;\n", "end\nendmodule"}, {"module m;\ninitial begin\n", "fork:fork_label\n", "begin\n#6;\nend\n", "begin\n#3;\nend\n", "join_any\n", {kToken, "disable"}, " fork_label;\n", "end\nendmodule"}, }; RunLintTestCases<VerilogAnalyzer, DisableStatementNoLabelsRule>( kDisableStatementTestCases); } TEST(DisableStatementTest, NonSequentialDisableStatementsFail) { constexpr int kToken = TK_disable; const std::initializer_list<LintTestCase> kDisableStatementTestCases = { {"module m;\n", "initial begin;\n", "fork\n", "begin : foo\n", "end\n", {kToken, "disable"}, " foo;\n", "join_any\n", "end\nendmodule"}, {"module m;\n", "initial begin:foo\n", "end\n", "initial begin:boo\n", {kToken, "disable"}, " foo;\n", "end\nendmodule"}, {"module m;\n", "initial begin:foo;\n", "begin : bar\n", {kToken, "disable"}, " foo;\n", "end\n", "end\nendmodule"}, {"module m;\n", "final begin:foo;\n", "begin : bar\n", {kToken, "disable"}, " foo;\n", "end\n", "end\nendmodule"}, {"module m;\n", "always_comb begin:foo;\n", "begin : bar\n", {kToken, "disable"}, " foo;\n", "end\n", "end\nendmodule"}, }; RunLintTestCases<VerilogAnalyzer, DisableStatementNoLabelsRule>( kDisableStatementTestCases); } } // namespace } // namespace analysis } // namespace verilog
31.608
79
0.628702
37309bee6eb272dc1b99f9659ca749ea8ee4cf80
9,450
cpp
C++
utils.cpp
Litvinovis/webserver
1d7156dcfb7bc0c4abeff650d2cf4114bbd8129e
[ "Apache-2.0" ]
2
2021-04-22T11:07:04.000Z
2022-01-04T13:57:57.000Z
utils.cpp
Litvinovis/webserver
1d7156dcfb7bc0c4abeff650d2cf4114bbd8129e
[ "Apache-2.0" ]
18
2021-05-10T15:33:00.000Z
2021-05-30T16:32:16.000Z
utils.cpp
Litvinovis/webserver
1d7156dcfb7bc0c4abeff650d2cf4114bbd8129e
[ "Apache-2.0" ]
2
2021-04-15T13:06:08.000Z
2021-05-26T18:08:41.000Z
#include <iostream> #include <unistd.h> #include <sys/stat.h> #include "utils.hpp" #include "Setting.hpp" #include <cstring> // for linux namespace utils { std::vector<char> read_file(std::string filename) { std::vector<char> buf; int fd; char* line; if ((fd = open(filename.c_str(), O_RDONLY)) < 0) utils::e_throw("open", __FILE__, __LINE__); while (get_next_line(fd, &line) > 0) buf.insert(buf.end(), line, line + std::strlen(line)); buf.insert(buf.end(), line, line + std::strlen(line)); close(fd); return buf; } std::vector<char> read_file_raw(std::string filename) { std::vector<char> buf; int fd; char line[5]; int m; if ((fd = open(filename.c_str(), O_RDONLY)) < 0) utils::e_throw("open", __FILE__, __LINE__); while ((m = read(fd, line, 5)) > 0) { if (m == -1) utils::e_throw("read", __FILE__, __LINE__); buf.insert(buf.end(), line, line + m); } close(fd); return buf; } void write_file_raw(std::string filename, std::vector<char> buf) { int fd; int m; int offset; offset = 0; m = 0; if ((fd = open(filename.c_str(), O_TRUNC | O_WRONLY | O_CREAT, 0644)) < 0) utils::e_throw("open", __FILE__, __LINE__); std::vector<char>::iterator it = buf.begin(); while (it != buf.end()) { if(lseek(fd, 0, SEEK_CUR) == -1) utils::e_throw("lseek", __FILE__, __LINE__); if ((m = write(fd, &buf[offset], buf.size())) < 0) utils::e_throw("write_file_raw", __FILE__, __LINE__); offset = offset + m; it = it + m; } close(fd); } bool file_exists (std::string filename) { struct stat buffer; return (stat (filename.c_str(), &buffer) == 0); } int file_dir_exists (std::string filename) { struct stat info; if( stat(filename.c_str(), &info ) != 0 ) return 0; else if( info.st_mode & S_IFDIR ) return 2; else return 1; } bool in_array(const std::string &value, const std::vector<std::string> &array) { for ( std::vector<std::string>::const_iterator it = array.begin(); it != array.end(); ++it) { if (value == *it) return true; } return false; } size_t get_current_time_in_ms(void) { struct timeval tv; size_t time_in_mill; gettimeofday(&tv, NULL); time_in_mill = tv.tv_sec * 1000 + tv.tv_usec / 1000; return (time_in_mill); } void ft_usleep(int ms) { size_t start_time; size_t end_time; int elapsed_time; start_time = get_current_time_in_ms(); end_time = get_current_time_in_ms(); elapsed_time = end_time - start_time; while (elapsed_time < ms) { usleep(10); end_time = get_current_time_in_ms(); elapsed_time = end_time - start_time; } } std::string ft_strtrim(const std::string &s1, const std::string& set) { size_t start = 0; size_t end = 0; size_t index = 0; while (s1.c_str()[index] && utils::ft_strchr(set, s1.c_str()[index]) != -1) { index++; } start = index; end = s1.length(); return s1.substr(start, end); } std::string ft_strtrim2(const std::string &s1, const std::string& set) { size_t start; size_t end; size_t index = 0; while (s1[index] && utils::ft_strchr(set, s1[index]) != -1) { index++; } start = index; end = s1.length(); while (end && utils::ft_strchr(set, s1[end]) != -1) { --end; } return s1.substr(start, end); } int ft_strchr(const std::string& str, int ch) { char *src; int index; src = (char *)str.c_str(); index = 0; while (src[index] != 0) if (src[index++] == ch) return (index); if (src[index] == ch) return (index); return (-1); } std::map<std::string, std::string> parseBufToHeaderMap(const std::map<std::string, std::string> & header, const std::vector<char> & buf) { // All headers in map (key - value) std::vector<char>::const_iterator head = buf.begin(); std::vector<char>::const_iterator tail = head; std::map<std::string, std::string> header_new = header; while (head != buf.end() && *head != '\r') { while (tail != buf.end() && *tail != '\r') ++tail; std::vector<char>::const_iterator separator = head; while (separator != buf.end() && separator != tail && *separator != ':') ++separator; if (separator == tail) break; std::string key(head, separator); std::vector<char>::const_iterator value = ++separator; while (value != tail && (*value == ' ' || *value == ':')) ++value; header_new[key] = std::string(value, tail); while (tail != buf.end() && (*tail == '\r' || *tail == '\n')) ++tail; head = tail; } return header_new; } std::string base64encode(std::vector<char> buf) { const char base64Keys[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; std::string output; char chr1, chr2, chr3; int enc1, enc2, enc3, enc4; size_t i = 0; size_t buf_len = buf.size(); output.reserve(4 * buf_len / 3); while (i < buf_len) { chr1 = (i < buf_len) ? buf[i++] : 0; chr2 = (i < buf_len) ? buf[i++] : 0; chr3 = (i < buf_len) ? buf[i++] : 0; enc1 = chr1 >> 2; enc2 = ((chr1 & 0x3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 0xF) << 2) | (chr3 >> 6); enc4 = chr3 & 0x3F; if (chr2 == 0) { enc3 = 64; enc4 = 64; } else if (chr3 == 0) { enc4 = 64; } output += base64Keys[enc1]; output += base64Keys[enc2]; output += base64Keys[enc3]; output += base64Keys[enc4]; } return output; } std::string base64decode(const std::string & s) { const char base64Keys[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string output; output.clear(); output.reserve(3 * s.length() / 4); std::vector<int> T(256, -1); for (int i = 0; i < 64; ++i) { T[base64Keys[i]] = i; } int val = 0; int valb = -8; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; if (T[c] == -1) break; val = (val << 6) + T[c]; valb += 6; if (valb >= 0) { output += char((val >> valb) & 0xFF); valb -= 8; } } return output; } std::string to_string(int n) { char * loc_num = ft_itoa(n); std::string msg = std::string(loc_num); free(loc_num); return msg; } std::string get_current_time_fmt() { struct timeval tv; time_t nowtime; struct tm *nowtm; char tmbuf[64]; gettimeofday(&tv, NULL); nowtime = tv.tv_sec; nowtm = localtime(&nowtime); strftime(tmbuf, sizeof(tmbuf), "%Y-%m-%d %H:%M:%S", nowtm); std::string str(tmbuf); return str; } void log_print_template(const char *color, const std::string & filename, const std::string & msg, int n) { std::cout << color; std::cout << get_current_time_fmt() << " "; std::cout << filename << ":" << RES << " " << msg; if (n != -1) std::cout << n; std::cout << std::endl; } void log(Setting & config, const std::string & filename, const std::string & msg, int n) { if (filename == "EventLoop.cpp" && config.getDebugLevel() == -9) log_print_template(GRA, filename, msg, n); if (filename == "Response.cpp" && config.getDebugLevel() > 1) log_print_template(CYN, filename, msg, n); if (filename == "ProcessMethod.cpp" && config.getDebugLevel() > 1) log_print_template(MAG, filename, msg, n); if (filename == "Client.cpp" && config.getDebugLevel() > 2) log_print_template(BLU, filename, msg, n); if (filename == "HTTP HEADER" && config.getDebugLevel() == -1) log_print_template(GRN, filename, msg, n); } void e_throw(const std::string & msg, const std::string & filename, int line) { throw std::runtime_error(msg + ": " + strerror(errno) + " at "+ filename + ":" + to_string(line)); } }
30.882353
108
0.480635
37332b84069848d85aeb8f925be6fd3454cd7939
604
hpp
C++
libs/Texturize.Codecs.EXR/include/Codecs/exr.hpp
Aschratt/Texturize
bba688d1afd60363f03e02d28e642a63845591d6
[ "MIT" ]
11
2019-05-17T12:23:12.000Z
2020-11-12T14:03:23.000Z
libs/Texturize.Codecs.EXR/include/Codecs/exr.hpp
crud89/Texturize
bba688d1afd60363f03e02d28e642a63845591d6
[ "MIT" ]
2
2019-04-01T08:37:36.000Z
2019-04-01T08:49:15.000Z
libs/Texturize.Codecs.EXR/include/Codecs/exr.hpp
crud89/Texturize
bba688d1afd60363f03e02d28e642a63845591d6
[ "MIT" ]
1
2019-06-25T01:04:35.000Z
2019-06-25T01:04:35.000Z
#pragma once #include <texturize.hpp> #include <analysis.hpp> #include <codecs.hpp> #include <string> #include <iostream> namespace Texturize { /// \brief class TEXTURIZE_API EXRCodec : public ISampleCodec { public: virtual void load(const std::string& fileName, Sample& sample) const override; virtual void load(std::istream& stream, Sample& sample) const override; virtual void save(const std::string& fileName, const Sample& sample, const int depth = CV_8U) const override; virtual void save(std::ostream& stream, const Sample& sample, const int depth = CV_8U) const override; }; }
27.454545
111
0.738411
3733399ac2e2ccfedf640afe18d3d4056fa00c11
1,757
cpp
C++
queue/queue_LL.cpp
vivekrajx/dsa
23351634652aaabfa40f8679ccff9f6fa9f844e9
[ "MIT" ]
null
null
null
queue/queue_LL.cpp
vivekrajx/dsa
23351634652aaabfa40f8679ccff9f6fa9f844e9
[ "MIT" ]
null
null
null
queue/queue_LL.cpp
vivekrajx/dsa
23351634652aaabfa40f8679ccff9f6fa9f844e9
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; struct Node { int data; Node* link; }; //declated glboally struct Node * front = NULL; struct Node * rear = NULL; //Enqueue from front & Dequeue from rear both take O(1) time here. //Enqueue from rear void Enqueue(int x) { Node* temp = new Node(); temp->data = x; temp->link = NULL; //if queue is empty if(front == NULL and rear == NULL) { front = rear = temp; //set both front and rear as to temp return; } rear->link = temp; //build new link while enqueuing rear = temp; //update rear } //Dequeue from front void Dequeue() { Node * temp = front; // we created this temp ptr to node in which we store //the addr of current head or current front //CASE 1: if queue is empty if(front == NULL) return; //CASE 2: only element in queue if(front == rear) { front = rear = NULL; //removed the only element in the queue } //CASE 3: all other cases else { front = front->link; } free(temp); //since front was incr, leaving a prev front in mem we free it } void Print(){ cout<<"Queue: "; Node* current = front; // Initialize current while (current != NULL) { cout<<current->data<<" "; current = current->link; } cout<<endl; } int Front(){ return front->data; //return front element of queue } int Rear(){ return rear->data; //return rear element of queue } bool isEmpty(){ if(front==NULL) return true; else return false; } int main(){ Enqueue(2); Print(); Enqueue(4); Print(); Enqueue(6); Print(); Dequeue(); Print(); Dequeue(); Print(); Dequeue(); Print(); }
19.307692
78
0.575982
3735173760e30d35d79fd6810a10f9c753be25fc
34,117
cpp
C++
closed/FuriosaAI/code/resnet50/resnet50.cpp
ctuning/inference_results_v1.1
d9176eca28fcf6d7a05ccb97994362a76a1eb5ab
[ "Apache-2.0" ]
12
2021-09-23T08:05:57.000Z
2022-03-21T03:52:11.000Z
closed/FuriosaAI/code/resnet50/resnet50.cpp
ctuning/inference_results_v1.1
d9176eca28fcf6d7a05ccb97994362a76a1eb5ab
[ "Apache-2.0" ]
11
2021-09-23T20:34:06.000Z
2022-01-22T07:58:02.000Z
closed/FuriosaAI/code/resnet50/resnet50.cpp
ctuning/inference_results_v1.1
d9176eca28fcf6d7a05ccb97994362a76a1eb5ab
[ "Apache-2.0" ]
16
2021-09-23T20:26:38.000Z
2022-03-09T12:59:56.000Z
#include <cassert> #include <sstream> #include <condition_variable> #include <deque> #include <iostream> #include <map> #include <mutex> #include <thread> #include <vector> #include <fstream> #include <streambuf> #include <atomic> #include <string.h> #include "loadgen.h" #include "query_sample_library.h" #include "system_under_test.h" #include "test_settings.h" #include "../common/nux.h" #include <stdlib.h> #include "../common/unlower.h" using namespace std::string_literals; // #define ASYNC // #define PROFILE // #define DEBUG #define POST_PROCESS #ifdef PROFILE std::string PROFILE_RECORD_INFERENCE = "Inference"; std::string PROFILE_RECORD_PREPARE_SUBMISSION = "PrepareSubmission"; std::string PROFILE_RECORD_POST_PROCESS = "PostProcess"; std::string PROFILE_RECORD_OUT_OF_TIMED = "OutOfTimed"; std::string build_profile_record(std::string record_name, std::string annotation) { return record_name + "(" + annotation + ")"; } #endif std::string DATA_PATH = "../preprocessed/imagenet-golden/raw/"; std::string VAL_MAP_PATH = "../common/val_map.txt"; const int IMAGE_SIZE = (224*224*3); int INPUT_SIZE = IMAGE_SIZE; int OUTPUT_SIZE = 1001; std::vector<std::unique_ptr<unsigned char[]>> images; std::optional<LoweringInfo> input_lowering; std::optional<LoweringInfo> output_lowering; std::optional<LoweringInfo> TensorDescToLoweringInfo(nux_tensor_desc_t desc, int unlowered_channel, int unlowered_height, int unlowered_width) { int dim = nux_tensor_dim_num(desc); if (dim != 6) return {}; if (nux_tensor_axis(desc, 0) != Axis::axis_batch) return {}; if (nux_tensor_axis(desc, 1) == Axis::axis_height_outer && nux_tensor_axis(desc, 2) == Axis::axis_channel_outer && nux_tensor_axis(desc, 3) == Axis::axis_height ) { if (nux_tensor_axis(desc, 4) == Axis::axis_channel && nux_tensor_axis(desc, 5) == Axis::axis_width) { return DynamicHCHCW( nux_tensor_dim(desc, 1), nux_tensor_dim(desc, 2), nux_tensor_dim(desc, 3), nux_tensor_dim(desc, 4), nux_tensor_dim(desc, 5), unlowered_channel, unlowered_height, unlowered_width ); } if (nux_tensor_axis(desc, 4) == Axis::axis_width && nux_tensor_axis(desc, 5) == Axis::axis_channel ) { return DynamicHCHWC( nux_tensor_dim(desc, 1), nux_tensor_dim(desc, 2), nux_tensor_dim(desc, 3), nux_tensor_dim(desc, 4), nux_tensor_dim(desc, 5), unlowered_channel, unlowered_height, unlowered_width ); } } return {}; } class QSL : public mlperf::QuerySampleLibrary { public: QSL(int sampleSize = 50000) : mSampleSize(sampleSize) { std::ifstream val_file(VAL_MAP_PATH.c_str()); std::string input_filename; std::cout << "sample size: " << std::to_string(sampleSize) << std::endl; int answer; while(val_file >> input_filename >> answer) { mItems.emplace_back(input_filename.substr(0, input_filename.size() - 5) + ".JPEG.raw", answer); } images.resize(mItems.size()); }; ~QSL() override{}; const std::string& Name() const override { return mName; } size_t TotalSampleCount() override { return mSampleSize; } size_t PerformanceSampleCount() override { std::cout << "PerformanceSampleCount" << 10240 << '\n'; return 10240; } void LoadSamplesToRam( const std::vector<mlperf::QuerySampleIndex>& samples) override { for(auto index : samples) { std::string filename = DATA_PATH + mItems[index].first; std::ifstream inf(filename.c_str(), std::ios::binary); if (input_lowering) { std::vector<char> buffer(IMAGE_SIZE); inf.read((char*)&buffer[0], 224*224*3); std::visit([&](auto info){ INPUT_SIZE = info.lowered_size(); images[index].reset((unsigned char*)std::aligned_alloc(64, info.lowered_size())); info.for_each([&](int c, int co, int ci, int h, int ho, int hi, int w) { images[index][info.index(co, ci, ho, hi, w)] = buffer[c*224*224+h*224+w]; }); }, *input_lowering); } else { images[index].reset((unsigned char*)std::aligned_alloc(64, IMAGE_SIZE)); inf.read((char*)&images[index][0], 224*224*3); } } } void UnloadSamplesFromRam( const std::vector<mlperf::QuerySampleIndex>& samples) override { for(auto index : samples) { //std::cout << "UNLOAD " << index << '\n'; images[index].reset(); } } private: std::string mName{"FuriosaAI-QSL"}; int mSampleSize; std::vector<std::pair<std::string, int>> mItems; }; class Resnet50Reporter { protected: void post_inference(unsigned char* buffer, mlperf::QuerySampleResponse& response) { float max_index = 0; char* data_arr = (char*)buffer; if (output_lowering) { std::visit([&](auto info){ for(int i = 1; i < 1001; i ++) { if (data_arr[info.index((int)max_index, 0, 0)] < data_arr[info.index(i, 0, 0)]) { max_index = i; } } }, *output_lowering); } else { for(int i = 1; i < 1001; i ++) { if (data_arr[(int)max_index] < data_arr[i]) { max_index = i; } } } *(float*)response.data = max_index; } }; class FuriosaBasicSUT : public mlperf::SystemUnderTest, Resnet50Reporter { public: nux_session_t mSession; nux_completion_queue_t mQueue; nux_session_option_t mSessionOption; nux_tensor_array_t mInputs; nux_tensor_array_t mOutputs; std::atomic<int> mIssued; std::atomic<int> mCompleted; FuriosaBasicSUT() { // Start with some large value so that we don't reallocate memory. initResponse(1); std::ifstream inf("mlcommons_resnet50_v1.5_int8.enf", std::ios::binary); mSessionOption = nux_session_option_create(); nux_session_option_set_device(mSessionOption, "npu0pe0-1"); std::vector<char> model_buf((std::istreambuf_iterator<char>(inf)), std::istreambuf_iterator<char>()); { auto err = nux_session_create((nux_buffer_t)model_buf.data(), model_buf.size(), mSessionOption, &mSession); if (err != nux_error_t_success) { std::cerr << "SUT:nux async session create error: " << err << '\n'; exit(-1); } } nux_model_t model = nux_session_get_model(mSession); mInputs = nux_tensor_array_create_inputs(model); mOutputs = nux_tensor_array_allocate_outputs(model); auto input_desc = nux_input_desc(model, 0); input_lowering = TensorDescToLoweringInfo(input_desc, 3, 224, 224); auto output_desc = nux_output_desc(model, 0); output_lowering = TensorDescToLoweringInfo(output_desc, 1001, 1, 1); if (output_lowering) std::visit([](auto info){OUTPUT_SIZE = info.lowered_size();}, *output_lowering); } std::vector<std::thread> mCompleteThreads; ~FuriosaBasicSUT() override { nux_session_destroy(mSession); } const std::string& Name() const override { return mName; } void IssueQuery(const std::vector<mlperf::QuerySample>& samples) override { int n = samples.size(); if (n > mResponses.size()) { std::cerr << "Warning: reallocating response buffer in BasicSUT. Maybe " "you should initResponse with larger value!?" << std::endl; initResponse(samples.size()); } for (int i = 0; i < n; i++) { mResponses[i].id = samples[i].id; auto tensor0 = nux_tensor_array_get(mInputs, 0); auto* data = images[samples[i].index].get(); nux_error_t err; //std::cout << "Issuing: " << samples[i].index << ' ' << i << '/' << n << ' ' << data.size() << '\n'; // Use allocated aligned buffer tensor_set_buffer(tensor0, (nux_buffer_t)data, INPUT_SIZE, nullptr); //auto err = tensor_set_buffer(tensor0, (nux_buffer_t)data.data(), data.size(), nullptr); err = nux_session_run(mSession, mInputs, mOutputs); if (err != 0) { std::cout << "Error: " << err << '\n'; } auto result = nux_tensor_array_get(mOutputs, 0); nux_buffer_t buffer; nux_buffer_len_t len; tensor_get_buffer(result, &buffer, &len); post_inference(buffer, mResponses[0]); mlperf::QuerySamplesComplete(mResponses.data(), 1); } } void FlushQueries() override {} void ReportLatencyResults( const std::vector<mlperf::QuerySampleLatency>& latencies_ns) override{}; private: void initResponse(int size) { mResponses.resize(size, {0, reinterpret_cast<uintptr_t>(&mBuf), sizeof(mBuf)}); } float mBuf{1}; std::string mName{"FuriosaAI-BasicSUT"}; std::vector<mlperf::QuerySampleResponse> mResponses; }; class FuriosaQueueSUT : public mlperf::SystemUnderTest, Resnet50Reporter { public: std::vector<nux_session_t> mSessions; FuriosaQueueSUT(int numCompleteThreads, int maxSize) { std::ifstream inf("mlcommons_resnet50_v1.5_int8_batch8.enf", std::ios::binary); std::vector<char> model_buf((std::istreambuf_iterator<char>(inf)), std::istreambuf_iterator<char>()); for(int npu_id = 0; npu_id < numCompleteThreads / 2; npu_id++) { for(int pe_id = 0; pe_id < 2; pe_id++) { std::stringstream ostr; ostr << "npu" << npu_id << "pe" << pe_id; auto sessionOption = nux_session_option_create(); nux_session_option_set_device(sessionOption, ostr.str().c_str()); nux_session_t session; auto err = nux_session_create((nux_buffer_t)model_buf.data(), model_buf.size(), sessionOption, &session); if (err != nux_error_t_success) { std::cerr << "SUT:nux session create error: " << err << '\n'; exit(-1); } mSessions.push_back(session); if (npu_id == 0 && pe_id == 0) { nux_model_t model = nux_session_get_model(session); auto input_desc = nux_input_desc(model, 0); input_lowering = TensorDescToLoweringInfo(input_desc, 3, 224, 224); auto output_desc = nux_output_desc(model, 0); output_lowering = TensorDescToLoweringInfo(output_desc, 1001, 1, 1); if (output_lowering) std::visit([](auto info){OUTPUT_SIZE = info.lowered_size();}, *output_lowering); } } } initResponse(numCompleteThreads, maxSize); for (int i = 0; i < numCompleteThreads; i++) { mThreads.emplace_back(&FuriosaQueueSUT::CompleteThread, this, i); } } ~FuriosaQueueSUT() override { { std::unique_lock<std::mutex> lck(mMtx); mDone = true; mCondVar.notify_all(); } for (auto& thread : mThreads) { thread.join(); } } const std::string& Name() const override { return mName; } void IssueQuery(const std::vector<mlperf::QuerySample>& samples) override { { std::unique_lock<std::mutex> lck(mMtx); mWorkQueue = &samples; mQueueTail = 0; } mCondVar.notify_one(); } void FlushQueries() override {} void ReportLatencyResults( const std::vector<mlperf::QuerySampleLatency>& latencies_ns) override{}; private: void CompleteThread(int threadIdx) { auto& inputs = mInputs[threadIdx]; auto& responses = mResponses[threadIdx]; auto& session = mSessions[threadIdx]; nux_model_t model = nux_session_get_model(session); auto input_tensor = nux_tensor_array_create_inputs(model); auto output_tensor = nux_tensor_array_allocate_outputs(model); size_t maxSize{responses.size()}; size_t actualSize{0}; while (true) { { std::unique_lock<std::mutex> lck(mMtx); mCondVar.wait(lck, [&]() { return mWorkQueue && mWorkQueue->size() != mQueueTail || mDone; }); if (mDone) { break; } auto* requests = &(*mWorkQueue)[mQueueTail]; actualSize = std::min(maxSize, mWorkQueue->size() - mQueueTail); mQueueTail += actualSize; for (int i = 0; i < actualSize; i++) { responses[i].id = requests[i].id; } if (mWorkQueue->size() == mQueueTail) { mWorkQueue = nullptr; } lck.unlock(); mCondVar.notify_one(); for(int i = 0; i < actualSize; i ++) { int index = requests[i].index; auto* data = images[index].get(); memcpy(&inputs[i*INPUT_SIZE] , data, INPUT_SIZE); } auto tensor0 = nux_tensor_array_get(input_tensor, 0); tensor_set_buffer(tensor0, (nux_buffer_t)&inputs[0], maxSize * INPUT_SIZE, nullptr); auto err = nux_session_run(session, input_tensor, output_tensor); if (err != 0) { std::cout << "Error: " << err << '\n'; } auto result = nux_tensor_array_get(output_tensor, 0); nux_buffer_t buffer; nux_buffer_len_t len; tensor_get_buffer(result, &buffer, &len); for(int i = 0; i < actualSize; i ++) post_inference((unsigned char*)buffer + OUTPUT_SIZE * i, responses[i]); } mlperf::QuerySamplesComplete(responses.data(), actualSize); } } void initResponse(int numCompleteThreads, int size) { mBuf.resize(numCompleteThreads*size); mInputs.resize(numCompleteThreads); for(int i = 0; i < numCompleteThreads; i ++) mInputs[i].reset((unsigned char*)std::aligned_alloc(64, INPUT_SIZE*size)); mResponses.resize(numCompleteThreads); for(int i = 0; i < numCompleteThreads; i ++) { for(int j = 0; j < size; j ++) { mResponses[i].emplace_back(mlperf::QuerySampleResponse{0, reinterpret_cast<uintptr_t>(&mBuf[i*size+j]), sizeof(float)}); } } } std::vector<float> mBuf; std::string mName{"FuriosaQueueSUT"}; std::vector<std::vector<mlperf::QuerySampleResponse>> mResponses; std::vector<std::unique_ptr<unsigned char[]>> mInputs; std::vector<std::thread> mThreads; const std::vector<mlperf::QuerySample>* mWorkQueue{nullptr}; size_t mQueueTail; std::mutex mMtx; std::condition_variable mCondVar; bool mDone{false}; }; struct Context { mlperf::ResponseId *ids; nux_tensor_array_t input; nux_tensor_array_t output; unsigned char *buffer; int len; }; class StreamSession : public Resnet50Reporter { public: // Nux Session nux_async_session_t mSession; nux_completion_queue_t mQueue; nux_handle_t mNux; nux_model_t mModel; // SessionWarpper options nux_session_option_t mSessionOption; // IOs nux_tensor_array_t mInput; nux_tensor_array_t mOutput; mlperf::ResponseId *mIds; unsigned char *mBuffer; Context *mContext; // Compltion thread std::thread mCompletionThread; int mModelBatch; const std::string& Name() const { return mName; } StreamSession( int numWorkers = 12, int modelBatch = 1, std::string deviceName = "npu0pe0-1", std::string source = "") { #ifdef DEBUG std::cout << "Constructing StreamSession(" << numWorkers << ")" << std::endl; #endif mModelBatch = modelBatch; mSessionOption = nux_session_option_create(); nux_session_option_set_worker_num(mSessionOption, numWorkers); nux_session_option_set_device(mSessionOption, deviceName.c_str()); nux_session_option_set_input_queue_size(mSessionOption, 8); nux_session_option_set_output_queue_size(mSessionOption, 256); #ifdef DEBUG std::cout << "Prepare Nux session with device name: " << deviceName << std::endl; #endif std::ifstream inf(source, std::ios::binary); std::vector<char> model_buf((std::istreambuf_iterator<char>(inf)), std::istreambuf_iterator<char>()); auto err = nux_async_session_create( (nux_buffer_t)model_buf.data(), model_buf.size(), mSessionOption, &mSession, &mQueue); #ifdef DEBUG std::cout << "create async session done: " << deviceName << std::endl; #endif if (err != nux_error_t_success) { std::cerr << "SUT:nux async session create error: " << err << std::endl; exit(-1); } mModel = nux_async_session_get_model(mSession); nux_async_session_get_nux_handle(mSession, &mNux); #ifdef DEBUG std::cout << "Prepare first submission" << std::endl; #endif mInput = nux_tensor_array_create_inputs(mModel); mOutput = nux_tensor_array_allocate_outputs(mModel); mContext = (Context *) malloc(sizeof(Context)); mIds = (mlperf::ResponseId *) malloc(sizeof(mlperf::ResponseId) * mModelBatch); mBuffer = (unsigned char*) std::aligned_alloc(64, INPUT_SIZE * mModelBatch); auto input_desc = nux_input_desc(mModel, 0); input_lowering = TensorDescToLoweringInfo(input_desc, 3, 224, 224); auto output_desc = nux_output_desc(mModel, 0); output_lowering = TensorDescToLoweringInfo(output_desc, 1001, 1, 1); if (output_lowering) std::visit([](auto info){OUTPUT_SIZE = info.lowered_size();}, *output_lowering); #ifdef DEBUG std::cout << "Run completion thread" << std::endl; #endif mCompletionThread = std::thread([this] { CompleteThread(); }); } ~StreamSession() { nux_tensor_array_destroy(mInput); nux_tensor_array_destroy(mOutput); free(mContext); free(mIds); nux_async_session_destroy(mSession); nux_completion_queue_destroy(mQueue); mCompletionThread.join(); } void SubmitQuery(std::vector<mlperf::QuerySample> samples, int begin, int len) { #ifdef PROFILE nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_INFERENCE, std::to_string(samples[begin].id)).c_str()); nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_PREPARE_SUBMISSION, std::to_string(samples[begin].id)).c_str()); #endif if (len == 1) { mIds[0] = samples[begin].id; auto tensor = nux_tensor_array_get(mInput, 0); auto* data = images[samples[begin].index].get(); auto err = tensor_set_buffer(tensor, (nux_buffer_t) data, INPUT_SIZE, nullptr); if (err != 0) { std::cout << "Error: " << err << '\n'; } } else { for(int i = 0; i < len ; i ++) { mIds[i] = samples[begin + i].id; auto* data = images[samples[begin + i].index].get(); memcpy(&mBuffer[i*INPUT_SIZE] , data, INPUT_SIZE); } auto tensor = nux_tensor_array_get(mInput, 0); auto err = tensor_set_buffer(tensor, (nux_buffer_t)&mBuffer[0], mModelBatch * INPUT_SIZE, nullptr); if (err != 0) { std::cout << "Error: " << err << '\n'; } } mContext->ids = mIds; mContext->input = mInput; mContext->output = mOutput; mContext->buffer = mBuffer; mContext->len = len; #ifdef PROFILE nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_PREPARE_SUBMISSION, std::to_string(samples[begin].id)).c_str()); #endif #ifdef DEBUG std::cout << "Submit ctx addr: " << (void *) mContext << ", ctx->output: " << (void *) mContext->output << ", ctx->input: " << (void *) mContext->input << std::endl; #endif auto err = nux_async_session_run(mSession, (nux_context_t) mContext, mInput, mOutput); if (err != 0) { std::cout << "nux session run error: " << err << '\n'; } #ifdef PROFILE nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_OUT_OF_TIMED, "alloc-for-next-" + std::to_string(samples[begin].id)).c_str()); #endif mInput = nux_tensor_array_create_inputs(mModel); mOutput = nux_tensor_array_allocate_outputs(mModel); mContext = (Context *) malloc(sizeof(Context)); mIds = (mlperf::ResponseId *) malloc(sizeof(mlperf::ResponseId) * mModelBatch); mBuffer = (unsigned char*) std::aligned_alloc(64, INPUT_SIZE * mModelBatch); #ifdef PROFILE nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_OUT_OF_TIMED, "alloc-for-next-" + std::to_string(samples[begin].id)).c_str()); #endif } void CompleteThread() { std::cout << "Completion Thread has been launched" << '\n'; nux_context_t context; nux_tensor_array_t output; float tempBuf[mModelBatch]; std::vector<mlperf::QuerySampleResponse> responses; for (int i = 0 ; i < mModelBatch ; i++) { responses.push_back(mlperf::QuerySampleResponse {0, reinterpret_cast<uintptr_t>(&tempBuf[i]), sizeof(float)}); } enum nux_error_t error; while (nux_completion_queue_next(mQueue, &context, &error)) { Context* ctx = (Context*) context; #ifdef DEBUG std::cout << "Recv ctx addr: " << (void *) ctx << ", ctx->output: " << (void *) ctx->output << ", ctx->input: " << (void *) ctx->input << std::endl; #endif #ifdef PROFILE nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_POST_PROCESS, std::to_string(ctx->ids[0])).c_str()); #endif auto result = nux_tensor_array_get(ctx->output, 0); nux_buffer_t buffer; nux_buffer_len_t buffer_len; tensor_get_buffer(result, &buffer, &buffer_len); for (int i = 0; i < ctx->len ; i ++) { responses[i].id = ctx->ids[i]; responses[i].size = sizeof(float); #ifdef POST_PROCESS post_inference((unsigned char*)buffer + OUTPUT_SIZE * i, responses[i]); #else responses[i].data = (uintptr_t)&buffer + OUTPUT_SIZE * i; #endif } #ifdef PROFILE nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_POST_PROCESS, std::to_string(ctx->ids[0])).c_str()); #endif mlperf::QuerySamplesComplete(responses.data(), ctx->len); #ifdef PROFILE nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_INFERENCE, std::to_string(ctx->ids[0])).c_str()); #endif #ifdef PROFILE nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_OUT_OF_TIMED, "dealloc-" + std::to_string(ctx->ids[0])).c_str()); #endif nux_tensor_array_destroy(ctx->input); nux_tensor_array_destroy(ctx->output); free(ctx->ids); free(ctx->buffer); free(ctx); #ifdef PROFILE nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_OUT_OF_TIMED, "dealloc-" + std::to_string(ctx->ids[0])).c_str()); #endif } } private: std::string mName{"FuriosaAI-StreamSession-SUT"}; }; class BlockingSession : public Resnet50Reporter { public: // Nux Session nux_session_t mSession; nux_handle_t mNux; nux_model_t mModel; // SessionWarpper options nux_session_option_t mSessionOption; // IOs nux_tensor_array_t mInput; nux_tensor_array_t mOutput; std::vector<mlperf::QuerySampleResponse> mResponses; const std::string& Name() const { return mName; } BlockingSession() { #ifdef DEBUG std::cout << "Constructing BlockingSession" << std::endl; #endif mSessionOption = nux_session_option_create(); nux_session_option_set_device(mSessionOption, "npu0pe0-1"); #ifdef DEBUG std::cout << "Prepare Nux session" << std::endl; #endif std::ifstream inf("mlcommons_resnet50_v1.5_int8.enf", std::ios::binary); std::vector<char> model_buf((std::istreambuf_iterator<char>(inf)), std::istreambuf_iterator<char>()); auto err = nux_session_create( (nux_buffer_t)model_buf.data(), model_buf.size(), mSessionOption, &mSession); if (err != nux_error_t_success) { std::cerr << "SUT:nux session create error: " << err << std::endl; exit(-1); } mModel = nux_session_get_model(mSession); nux_session_get_nux_handle(mSession, &mNux); auto input_desc = nux_input_desc(mModel, 0); input_lowering = TensorDescToLoweringInfo(input_desc, 3, 224, 224); auto output_desc = nux_output_desc(mModel, 0); output_lowering = TensorDescToLoweringInfo(output_desc, 1001, 1, 1); if (output_lowering) std::visit([](auto info){OUTPUT_SIZE = info.lowered_size();}, *output_lowering); #ifdef DEBUG std::cout << "Prepare first submission" << std::endl; #endif mInput = nux_tensor_array_create_inputs(mModel); mOutput = nux_tensor_array_allocate_outputs(mModel); int tempBuf{0}; mResponses.resize(1, {0, reinterpret_cast<uintptr_t>(&tempBuf), sizeof(int)}); } ~BlockingSession() { nux_tensor_array_destroy(mInput); nux_tensor_array_destroy(mOutput); nux_session_destroy(mSession); } void Run(mlperf::QuerySample sample) { #ifdef DEBUG std::cout << "run sample: " << std::to_string(sample.id) << std::endl; #endif #ifdef PROFILE nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_INFERENCE, std::to_string(sample.id)).c_str()); nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_PREPARE_SUBMISSION, std::to_string(sample.id)).c_str()); #endif auto tensor = nux_tensor_array_get(mInput, 0); auto* data = images[sample.index].get(); auto err = tensor_set_buffer(tensor, (nux_buffer_t) data, INPUT_SIZE, nullptr); #ifdef PROFILE nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_PREPARE_SUBMISSION, std::to_string(sample.id)).c_str()); #endif err = nux_session_run(mSession, mInput, mOutput); if (err != 0) { std::cout << "nux session run error: " << err << std::endl; } #ifdef PROFILE nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_POST_PROCESS, std::to_string(sample.id)).c_str()); #endif auto result = nux_tensor_array_get(mOutput, 0); nux_buffer_t buffer; nux_buffer_len_t len; tensor_get_buffer(result, &buffer, &len); mResponses[0].id = sample.id; mResponses[0].size = len; #ifdef POST_PROCESS post_inference(buffer, mResponses[0]); #else mResponses[0].data = (uintptr_t)&buffer; #endif #ifdef PROFILE nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_POST_PROCESS, std::to_string(sample.id)).c_str()); #endif mlperf::QuerySamplesComplete(mResponses.data(), 1); #ifdef PROFILE nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_INFERENCE, std::to_string(sample.id)).c_str()); #endif } private: std::string mName{"FuriosaAI-BlockingSession-SUT"}; }; class FuriosaSUTAlt : public mlperf::SystemUnderTest { public: #ifdef ASYNC std::unique_ptr<StreamSession> mSession; #else std::unique_ptr<BlockingSession> mSession; #endif FuriosaSUTAlt(int numWorkers = 12) { #ifdef DEBUG std::cout << "Constructing FuriosaSUTAlt" << std::endl; #endif #ifdef ASYNC mSession.reset(new StreamSession( numWorkers, 8, "npu0pe0-1", "mlcommons_resnet50_v1.5_int8.enf")); #else mSession.reset(new BlockingSession()); #endif } ~FuriosaSUTAlt() { mSession.reset(); } const std::string &Name() const override { return mSession->Name(); } void IssueQuery(const std::vector<mlperf::QuerySample> &samples) override { #ifdef ASYNC mSession->SubmitQuery(samples, 0, 1); #else mSession->Run(samples[0]); #endif } void FlushQueries() override {} void ReportLatencyResults( const std::vector<mlperf::QuerySampleLatency> &latencies_ns) override {}; }; class FuriosaMultiThreadSUT : public mlperf::SystemUnderTest { public: std::vector<std::unique_ptr<StreamSession>> mSessions; FuriosaMultiThreadSUT(int numWorkers = 4) { #ifdef DEBUG std::cout << "Constructing FuriosaMultiThreadSUT" << std::endl; #endif for (int peId = 0 ; peId < 2 ; peId++) { std::stringstream ostr; ostr << "npu0pe" << peId; mSessions.emplace_back(new StreamSession( numWorkers, 8, ostr.str(), "mlcommons_resnet50_v1.5_int8_batch8.enf")); } } ~FuriosaMultiThreadSUT() { mSessions.clear(); } const std::string &Name() const override { return mName; } void IssueQuery(const std::vector<mlperf::QuerySample> &samples) override { #pragma omp parallel for num_threads(2) for (int i = 0 ; i < 2 ; i++) { auto& session = mSessions[i]; int half = samples.size() / 2; int begin = i * half; int end = begin + half; int num_iter = (end - begin) / 8; int remainder = (end - begin) % 8; #ifdef DEBUG std::cout << "half: " << std::to_string(half) << ", begin: " << std::to_string(begin) << ", end: " << std::to_string(end) << ", num_iter: " << std::to_string(num_iter) << ", remainder: " << std::to_string(remainder) << std::endl; #endif for (int j = 0 ; j < num_iter ; j++) { session->SubmitQuery(samples, begin + j * 8, 8); } if (remainder > 0) { session->SubmitQuery(samples, begin + num_iter * 8, remainder); } } } void FlushQueries() override {} void ReportLatencyResults( const std::vector<mlperf::QuerySampleLatency> &latencies_ns) override {}; private: std::string mName{"FuriosaAI-FuriosaMultiThreadSUT"}; }; int main(int argc, char** argv) { enable_logging(); if (getenv("DATA")) { DATA_PATH = getenv("DATA"); } if (getenv("VAL_MAP")) { VAL_MAP_PATH = getenv("VAL_MAP"); } //assert(argc >= 2 && "Need to pass in at least one argument: target_qps"); int target_qps = 100; bool useQueue{false}; int numCompleteThreads{4}; int maxSize{1}; bool server_coalesce_queries{false}; int num_issue_threads{0}; bool isAccuracyRun = false; int num_samples = 50000; if (argc >= 2 && argv[1][0] >= '0' && argv[1][0] <= '9') { num_samples = std::stoi(argv[1]); isAccuracyRun = true; } mlperf::TestSettings testSettings; decltype(testSettings.scenario) arg_scenario = mlperf::TestScenario::SingleStream; for(int i = 1; i < argc; i ++) { if (i + 1 < argc && argv[i] == "--count"s) { num_samples = std::stoi(argv[i+1]); } if (i + 1 < argc && argv[i] == "--scenario"s) { if (argv[i+1] == "SingleStream"s) { std::cout << "Running the SingleStream scenario." << '\n'; } else if (argv[i+1] == "Offline"s) { arg_scenario = mlperf::TestScenario::Offline; std::cout << "Running the Offline scenario." << '\n'; } else { std::cout << "Not supported scenario: " << argv[i+1] << '\n'; return -1; } } if (argv[i] == "--accuracy"s) { isAccuracyRun = true; } } if (num_samples > 50000) num_samples = 50000; if (isAccuracyRun) { std::cout << "Accuracy mode." << '\n'; } else { std::cout << "Performance mode." << '\n'; } QSL qsl(num_samples); std::unique_ptr<mlperf::SystemUnderTest> sut; // Configure the test settings testSettings.FromConfig("../common/mlperf.conf", "resnet50", arg_scenario == mlperf::TestScenario::SingleStream ? "SingleStream" : "Offline"); testSettings.FromConfig("../common/user.conf", "resnet50", arg_scenario == mlperf::TestScenario::SingleStream ? "SingleStream" : "Offline"); testSettings.scenario = arg_scenario; testSettings.mode = mlperf::TestMode::PerformanceOnly; if (isAccuracyRun) testSettings.mode = mlperf::TestMode::AccuracyOnly; //testSettings.server_coalesce_queries = server_coalesce_queries; //std::cout << "testSettings.server_coalesce_queries = " //<< (server_coalesce_queries ? "True" : "False") << std::endl; //testSettings.server_num_issue_query_threads = num_issue_threads; //std::cout << "num_issue_threads = " << num_issue_threads << std::endl; // Configure the logging settings mlperf::LogSettings logSettings; logSettings.log_output.outdir = "build"; logSettings.log_output.prefix = "mlperf_log_"; logSettings.log_output.suffix = ""; logSettings.log_output.prefix_with_datetime = false; logSettings.log_output.copy_detail_to_stdout = false; logSettings.log_output.copy_summary_to_stdout = true; logSettings.log_mode = mlperf::LoggingMode::AsyncPoll; logSettings.log_mode_async_poll_interval_ms = 1000; logSettings.enable_trace = false; // Choose SUT if (arg_scenario == mlperf::TestScenario::SingleStream) { // sut.reset(new FuriosaBasicSUT()); sut.reset(new FuriosaSUTAlt(1)); } else { // sut.reset(new FuriosaQueueSUT(2, 8)); sut.reset(new FuriosaMultiThreadSUT(4)); } // Start test std::cout << "Start test..." << std::endl; mlperf::StartTest(sut.get(), &qsl, testSettings, logSettings); std::cout << "Test done. Clean up SUT..." << std::endl; sut.reset(); std::cout << "Done!" << std::endl; return 0; }
35.354404
154
0.619427
3735ac75271b959791cd33dbbaa242366ebba1cd
1,004
cpp
C++
Paperworks/src/Paperworks/Graphics/Renderer.cpp
codenobacon4u/paperworks
0e96cd2fb6070a2387ddd36aaa327b04733234fa
[ "MIT" ]
1
2019-08-15T18:58:54.000Z
2019-08-15T18:58:54.000Z
Paperworks/src/Paperworks/Graphics/Renderer.cpp
codenobacon4u/paperworks
0e96cd2fb6070a2387ddd36aaa327b04733234fa
[ "MIT" ]
null
null
null
Paperworks/src/Paperworks/Graphics/Renderer.cpp
codenobacon4u/paperworks
0e96cd2fb6070a2387ddd36aaa327b04733234fa
[ "MIT" ]
null
null
null
#include "pwpch.h" #include "Renderer.h" #include "Renderer2D.h" namespace Paperworks { Unique<Renderer::SceneData> Renderer::s_SceneData = CreateUnique<Renderer::SceneData>(); void Renderer::Init() { RenderCmd::Init(); Renderer2D::Init(); } void Renderer::Shutdown() { Renderer2D::Shutdown(); } void Renderer::Begin() { } void Renderer::Begin(Camera& camera) { s_SceneData->Projection = camera.GetProjectionMatrix(); s_SceneData->View = camera.GetViewMatrix(); } void Renderer::End() { } void Renderer::WindowResized(uint32_t width, uint32_t height) { RenderCmd::SetViewport(0, 0, width, height); } void Renderer::Submit(const Shared<VertexArray>& vertexArray, const Shared<Shader>& shader, const glm::mat4& transform) { shader->Bind(); shader->SetMat4("u_MVP.proj", s_SceneData->Projection); shader->SetMat4("u_MVP.view", s_SceneData->View); shader->SetMat4("u_MVP.modl", transform); vertexArray->Bind(); RenderCmd::DrawIndexed(vertexArray); } }
20.08
120
0.703187
373873ee580b26c3b2c1fe31b033556891245221
5,343
cpp
C++
RCSnail/rcsCommandLib.cpp
rcsnail/btcar
b803d4a59252689c9ed3b4af9d39679b6c4200b0
[ "MIT" ]
null
null
null
RCSnail/rcsCommandLib.cpp
rcsnail/btcar
b803d4a59252689c9ed3b4af9d39679b6c4200b0
[ "MIT" ]
null
null
null
RCSnail/rcsCommandLib.cpp
rcsnail/btcar
b803d4a59252689c9ed3b4af9d39679b6c4200b0
[ "MIT" ]
null
null
null
#include "rcsCommandLib.h" #include <avr/wdt.h> int btEnableValue = 0; // bt chip enable voltage after restart //SoftwareSerial mySerial(rxPin, txPin); // RX, TX // wdt_enable(WDTO_15MS); #define soft_reset() \ do \ { \ wdt_enable(WDTO_15MS); \ for(;;) \ { \ } \ } while(0) typedef enum _btParseState { BT_WAIT_START, BT_WAIT_LENGTH, BT_WAIT_COMMAND, BT_READ_DATA, BT_WAIT_CHECKSUM, BT_WAIT_RN4677_COMMAND, BT_WAIT_RN4677_DISRES, BT_WAIT_RN4677_END, BT_WAIT_ST500_BOOT_COMMAND } btParseState; typedef struct _btCommParseState { btParseState state; uint8_t readPos; uint8_t checksum; } btCommandParseState; btCommand _btCommand; btCommandParseState _btCommandParseState = {BT_WAIT_START}; void rn4677_enableFastData(void); btCommand * btGetNextCommand() { uint8_t b; while (Serial.available()) { b = Serial.read(); //Serial.println(b, HEX); switch (_btCommandParseState.state) { case BT_WAIT_START: if (b == BT_START_BYTE) { _btCommandParseState.state = BT_WAIT_LENGTH; } else if ('%' == b) { _btCommandParseState.state = BT_WAIT_RN4677_COMMAND; } else if ('0' == b) { _btCommandParseState.state = BT_WAIT_ST500_BOOT_COMMAND; } else { //for debugging //Serial.println(b, HEX); } break; case BT_WAIT_LENGTH: _btCommand.dataLength = b; if (0 < _btCommand.dataLength && _btCommand.dataLength <= BT_COMMAND_DATA_SIZE + 1) { _btCommandParseState.checksum = b; _btCommand.dataLength--; _btCommandParseState.state = BT_WAIT_COMMAND; } else { _btCommandParseState.state = BT_WAIT_START; } break; case BT_WAIT_COMMAND: _btCommand.command = b; _btCommandParseState.checksum += b; _btCommandParseState.readPos = 0; if (_btCommand.dataLength) _btCommandParseState.state = BT_READ_DATA; else _btCommandParseState.state = BT_WAIT_CHECKSUM; break; case BT_READ_DATA: _btCommand.data[_btCommandParseState.readPos++] = b; _btCommandParseState.checksum += b; if (_btCommandParseState.readPos == _btCommand.dataLength) { _btCommandParseState.state = BT_WAIT_CHECKSUM; } break; case BT_WAIT_CHECKSUM: _btCommandParseState.state = BT_WAIT_START; if (b == _btCommandParseState.checksum) { return &_btCommand; } else { //checksum error } break; case BT_WAIT_RN4677_COMMAND: if ('D' == b || 'R' == b) _btCommandParseState.state = BT_WAIT_RN4677_DISRES; else _btCommandParseState.state = BT_WAIT_RN4677_END; break; case BT_WAIT_RN4677_DISRES: if ('%' == b) { _delay_ms(1000); //rn4677_enableFastData(); _btCommandParseState.state = BT_WAIT_START; } break; case BT_WAIT_RN4677_END: if ('%' == b) { _btCommandParseState.state = BT_WAIT_START; } break; case BT_WAIT_ST500_BOOT_COMMAND: if (' ' == b) soft_reset(); _btCommandParseState.state = BT_WAIT_START; break; default: _btCommandParseState.state = BT_WAIT_START; } } return NULL; } void btSendResponse(uint8_t command, const uint8_t *data, uint8_t data_len) { uint8_t checksum = command + data_len + 1; Serial.write(BT_START_BYTE); Serial.write(data_len + 1); Serial.write(command); Serial.write(data, data_len); for(uint8_t i = 0; i < data_len; i++) { checksum += data[i]; } Serial.write(checksum); } void btSendDebugStr(const char *str) { btSendResponse(BT_RESPONSE_DEBUG, (uint8_t *)str, strlen(str)); } void btSendStr(const char *str) { while(*str) { Serial.write(*str++); delay(1); } } void rn4677_sendCmd(const char *str) { btSendStr(str); btSendStr("\r\n"); Serial.find('>'); } void rn4677_reset() { delay(50); pinMode(rn4677_sw_btn, OUTPUT); digitalWrite(rn4677_sw_btn, LOW); while(HIGH == digitalRead(rn4677_sw_btn)){ } delay(50); digitalWrite(rn4677_sw_btn, HIGH); while(LOW == digitalRead(rn4677_sw_btn)){ } delay(50); } void rn4677_modeCommand() { btSendStr("$$$\r\n"); delay(10); //btSendStr("+\r\n"); //echo on delay(10); } void rn4677_modeData() { btSendStr("---\r\n"); delay(10); } void rn4677_enableFastData(void) { rn4677_modeCommand(); rn4677_sendCmd("F,1"); //enable fast data mode rn4677_modeData(); _delay_ms(10); } // Function Pototype void wdt_init(void) __attribute__((naked)) __attribute__((section(".init3"))); // Function Implementation void wdt_init(void) { MCUSR = 0; wdt_disable(); return; } void btInit() { //wdt_disable(); btEnableValue = analogRead(rn4677_sw_btn); //0x1 - cold startup; 0x29C - reset; 0x114, 0x165 - ~1s power button off; ~2s - 0x7A pinMode(rn4677_sw_btn, OUTPUT); digitalWrite(rn4677_sw_btn, HIGH); //rn4677_reset(); Serial.begin(38400); //Serial.write("DONE"); }
23.959641
130
0.612203
37394af6b5687c87eb0fa892766db5a1918223c8
1,212
cpp
C++
main/substring-subsequence-problem/substring-subsequence-problem.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/substring-subsequence-problem/substring-subsequence-problem.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/substring-subsequence-problem/substring-subsequence-problem.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
#include <algorithm> #include <iostream> #include <iterator> #include <string> namespace { using It = std::string::const_iterator; // Helper for common_length(const std::string&, const std::string&). inline int common_length(const std::string& s, It t_first, const It& t_last) { auto len = 0; for (const auto c : s) { if (c == *t_first) { ++len; if (++t_first == t_last) break; } } return len; } // Returns the length of the longest (possibly noncontiguous) subsequence // of s that is a (contiguous) substring of t. int common_length(const std::string& s, const std::string& t) { auto maxlen = 0; const auto t_last = t.cend(); for (auto t_first = t.cbegin(); t_first != t_last; ++t_first) maxlen = std::max(maxlen, common_length(s, t_first, t_last)); return maxlen; } } int main() { auto tc = 0; for (std::cin >> tc; tc > 0; --tc) { std::string s, t; std::cin >> s >> t; std::cout << common_length(s, t) << '\n'; } }
24.734694
77
0.5033
373ebbffb8f88ef7396900b12828429e09e31da4
13,748
cc
C++
chrome/browser/chromeos/platform_keys/platform_keys_service_browsertest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/platform_keys/platform_keys_service_browsertest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/platform_keys/platform_keys_service_browsertest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium 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 <memory> #include <type_traits> #include <utility> #include "base/bind.h" #include "base/callback.h" #include "base/command_line.h" #include "base/containers/span.h" #include "base/location.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "base/task/post_task.h" #include "chrome/browser/chromeos/login/test/device_state_mixin.h" #include "chrome/browser/chromeos/login/test/login_manager_mixin.h" #include "chrome/browser/chromeos/login/test/scoped_policy_update.h" #include "chrome/browser/chromeos/login/test/user_policy_mixin.h" #include "chrome/browser/chromeos/platform_keys/platform_keys_service.h" #include "chrome/browser/chromeos/platform_keys/platform_keys_service_factory.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/scoped_test_system_nss_key_slot_mixin.h" #include "chrome/browser/policy/policy_test_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/mixin_based_in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/login/auth/user_context.h" #include "components/policy/core/common/cloud/policy_builder.h" #include "components/policy/core/common/policy_switches.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "crypto/signature_verifier.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { namespace platform_keys { namespace { constexpr char kTestUserEmail[] = "test@example.com"; constexpr char kTestAffiliationId[] = "test_affiliation_id"; enum class ProfileToUse { // A Profile that belongs to a user that is not affiliated with the device (no // access to the system token). kUnaffiliatedUserProfile, // A Profile that belongs to a user that is affiliated with the device (access // to the system token). kAffiliatedUserProfile, // The sign-in screen profile. kSigninProfile }; // Describes a test configuration for the test suite. struct TestConfig { // The profile for which PlatformKeysService should be tested. ProfileToUse profile_to_use; // The token IDs that are expected to be available. This will be checked by // the GetTokens test, and operation for these tokens will be performed by the // other tests. std::vector<std::string> token_ids; }; // A helper that waits until execution of an asynchronous PlatformKeysService // operation has finished and provides access to the results. // Note: all PlatformKeysService operations have a trailing const std::string& // error_message argument that is filled in case of an error. template <typename... ResultCallbackArgs> class ExecutionWaiter { public: ExecutionWaiter() = default; ~ExecutionWaiter() = default; ExecutionWaiter(const ExecutionWaiter& other) = delete; ExecutionWaiter& operator=(const ExecutionWaiter& other) = delete; // Returns the callback to be passed to the PlatformKeysService operation // invocation. base::RepeatingCallback<void(ResultCallbackArgs... result_callback_args, const std::string& error_message)> GetCallback() { return base::BindRepeating(&ExecutionWaiter::OnExecutionDone, weak_ptr_factory_.GetWeakPtr()); } // Waits until the callback returned by GetCallback() has been called. void Wait() { run_loop_.Run(); } // Returns the error message passed to the callback. const std::string& error_message() { EXPECT_TRUE(done_); return error_message_; } protected: // A std::tuple that is capable of storing the arguments passed to the result // callback. using ResultCallbackArgsTuple = std::tuple<std::decay_t<ResultCallbackArgs>...>; // Access to the arguments passed to the callback. const ResultCallbackArgsTuple& result_callback_args() const { EXPECT_TRUE(done_); return result_callback_args_; } private: void OnExecutionDone(ResultCallbackArgs... result_callback_args, const std::string& error_message) { EXPECT_FALSE(done_); done_ = true; result_callback_args_ = ResultCallbackArgsTuple( std::forward<ResultCallbackArgs>(result_callback_args)...); error_message_ = error_message; run_loop_.Quit(); } base::RunLoop run_loop_; bool done_ = false; ResultCallbackArgsTuple result_callback_args_; std::string error_message_; base::WeakPtrFactory<ExecutionWaiter> weak_ptr_factory_{this}; }; // Supports waiting for the result of PlatformKeysService::GetTokens. class GetTokensExecutionWaiter : public ExecutionWaiter<std::unique_ptr<std::vector<std::string>>> { public: GetTokensExecutionWaiter() = default; ~GetTokensExecutionWaiter() = default; const std::unique_ptr<std::vector<std::string>>& token_ids() const { return std::get<0>(result_callback_args()); } }; // Supports waiting for the result of the PlatformKeysService::GenerateKey* // function family. class GenerateKeyExecutionWaiter : public ExecutionWaiter<const std::string&> { public: GenerateKeyExecutionWaiter() = default; ~GenerateKeyExecutionWaiter() = default; const std::string& public_key_spki_der() const { return std::get<0>(result_callback_args()); } }; // Supports waiting for the result of the PlatformKeysService::Sign* function // family. class SignExecutionWaiter : public ExecutionWaiter<const std::string&> { public: SignExecutionWaiter() = default; ~SignExecutionWaiter() = default; const std::string& signature() const { return std::get<0>(result_callback_args()); } }; class GetAllKeysExecutionWaiter : public ExecutionWaiter<std::vector<std::string>> { public: GetAllKeysExecutionWaiter() = default; ~GetAllKeysExecutionWaiter() = default; const std::vector<std::string> public_keys() const { return std::get<0>(result_callback_args()); } }; } // namespace class PlatformKeysServiceBrowserTest : public MixinBasedInProcessBrowserTest, public ::testing::WithParamInterface<TestConfig> { public: PlatformKeysServiceBrowserTest() = default; ~PlatformKeysServiceBrowserTest() override = default; PlatformKeysServiceBrowserTest(const PlatformKeysServiceBrowserTest& other) = delete; PlatformKeysServiceBrowserTest& operator=( const PlatformKeysServiceBrowserTest& other) = delete; void SetUpInProcessBrowserTestFixture() override { MixinBasedInProcessBrowserTest::SetUpInProcessBrowserTestFixture(); // Call |Request*PolicyUpdate| even if not setting affiliation IDs so // (empty) policy blobs are prepared in FakeSessionManagerClient. auto user_policy_update = user_policy_mixin_.RequestPolicyUpdate(); auto device_policy_update = device_state_mixin_.RequestDevicePolicyUpdate(); if (GetParam().profile_to_use == ProfileToUse::kAffiliatedUserProfile) { device_policy_update->policy_data()->add_device_affiliation_ids( kTestAffiliationId); user_policy_update->policy_data()->add_user_affiliation_ids( kTestAffiliationId); } } void SetUpOnMainThread() override { MixinBasedInProcessBrowserTest::SetUpOnMainThread(); if (GetParam().profile_to_use == ProfileToUse::kSigninProfile) { profile_ = ProfileHelper::GetSigninProfile(); } else { ASSERT_TRUE(login_manager_mixin_.LoginAndWaitForActiveSession( LoginManagerMixin::CreateDefaultUserContext(test_user_info_))); profile_ = ProfileManager::GetActiveUserProfile(); } ASSERT_TRUE(profile_); platform_keys_service_ = PlatformKeysServiceFactory::GetForBrowserContext(profile_); ASSERT_TRUE(platform_keys_service_); } protected: PlatformKeysService* platform_keys_service() { return platform_keys_service_; } // Generates a key pair in the given |token_id| using platform keys service // and returns the SubjectPublicKeyInfo string encoded in DER format. std::string GenerateKeyPair(const std::string& token_id) { const unsigned int kKeySize = 2048; GenerateKeyExecutionWaiter generate_key_waiter; platform_keys_service()->GenerateRSAKey(token_id, kKeySize, generate_key_waiter.GetCallback()); generate_key_waiter.Wait(); return generate_key_waiter.public_key_spki_der(); } private: const AccountId test_user_account_id_ = AccountId::FromUserEmailGaiaId( kTestUserEmail, signin::GetTestGaiaIdForEmail(kTestUserEmail)); const LoginManagerMixin::TestUserInfo test_user_info_{test_user_account_id_}; ScopedTestSystemNSSKeySlotMixin system_nss_key_slot_mixin_{&mixin_host_}; LoginManagerMixin login_manager_mixin_{&mixin_host_, {test_user_info_}}; DeviceStateMixin device_state_mixin_{ &mixin_host_, DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED}; UserPolicyMixin user_policy_mixin_{&mixin_host_, test_user_account_id_}; // Unowned pointer to the profile selected by the current TestConfig. // Valid after SetUpOnMainThread(). Profile* profile_ = nullptr; // Unowned pointer to the PlatformKeysService for |profile_|. Valid after // SetUpOnMainThread(). PlatformKeysService* platform_keys_service_ = nullptr; }; // Tests that GetTokens() is callable and returns the expected tokens. IN_PROC_BROWSER_TEST_P(PlatformKeysServiceBrowserTest, GetTokens) { GetTokensExecutionWaiter get_tokens_waiter; platform_keys_service()->GetTokens(get_tokens_waiter.GetCallback()); get_tokens_waiter.Wait(); EXPECT_TRUE(get_tokens_waiter.error_message().empty()); ASSERT_TRUE(get_tokens_waiter.token_ids()); EXPECT_THAT(*get_tokens_waiter.token_ids(), ::testing::UnorderedElementsAreArray(GetParam().token_ids)); } // Generates a Rsa key pair and tests signing using that key pair. IN_PROC_BROWSER_TEST_P(PlatformKeysServiceBrowserTest, GenerateRsaAndSign) { const std::string data_to_sign = "test"; const unsigned int key_size = 2048; const HashAlgorithm hash_algorithm = HASH_ALGORITHM_SHA256; const crypto::SignatureVerifier::SignatureAlgorithm signature_algorithm = crypto::SignatureVerifier::RSA_PKCS1_SHA256; for (const std::string& token_id : GetParam().token_ids) { GenerateKeyExecutionWaiter generate_key_waiter; platform_keys_service()->GenerateRSAKey(token_id, key_size, generate_key_waiter.GetCallback()); generate_key_waiter.Wait(); EXPECT_TRUE(generate_key_waiter.error_message().empty()); const std::string public_key_spki_der = generate_key_waiter.public_key_spki_der(); EXPECT_FALSE(public_key_spki_der.empty()); SignExecutionWaiter sign_waiter; platform_keys_service()->SignRSAPKCS1Digest( token_id, data_to_sign, public_key_spki_der, hash_algorithm, sign_waiter.GetCallback()); sign_waiter.Wait(); EXPECT_TRUE(sign_waiter.error_message().empty()); crypto::SignatureVerifier signature_verifier; ASSERT_TRUE(signature_verifier.VerifyInit( signature_algorithm, base::as_bytes(base::make_span(sign_waiter.signature())), base::as_bytes(base::make_span(public_key_spki_der)))); signature_verifier.VerifyUpdate( base::as_bytes(base::make_span(data_to_sign))); EXPECT_TRUE(signature_verifier.VerifyFinal()); } } // Generates a key pair in tokens accessible from the profile under test and // retrieves them. IN_PROC_BROWSER_TEST_P(PlatformKeysServiceBrowserTest, GetAllKeys) { // Generate key pair in every token. std::map<std::string, std::string> token_key_map; for (const std::string& token_id : GetParam().token_ids) { const std::string public_key_spki_der = GenerateKeyPair(token_id); ASSERT_FALSE(public_key_spki_der.empty()); token_key_map[token_id] = public_key_spki_der; } // Only keys in the requested token should be retrieved. for (const std::string& token_id : GetParam().token_ids) { GetAllKeysExecutionWaiter get_all_keys_waiter; platform_keys_service()->GetAllKeys(token_id, get_all_keys_waiter.GetCallback()); get_all_keys_waiter.Wait(); EXPECT_TRUE(get_all_keys_waiter.error_message().empty()); std::vector<std::string> public_keys = get_all_keys_waiter.public_keys(); EXPECT_EQ(public_keys.size(), 1U); EXPECT_EQ(public_keys[0], token_key_map[token_id]); } } IN_PROC_BROWSER_TEST_P(PlatformKeysServiceBrowserTest, GetAllKeysWhenNoKeysGenerated) { for (const std::string& token_id : GetParam().token_ids) { GetAllKeysExecutionWaiter get_all_keys_waiter; platform_keys_service()->GetAllKeys(token_id, get_all_keys_waiter.GetCallback()); get_all_keys_waiter.Wait(); EXPECT_TRUE(get_all_keys_waiter.error_message().empty()); std::vector<std::string> public_keys = get_all_keys_waiter.public_keys(); EXPECT_EQ(public_keys.size(), 0U); } } INSTANTIATE_TEST_SUITE_P( AllSupportedProfileTypes, PlatformKeysServiceBrowserTest, ::testing::Values( TestConfig{ProfileToUse::kSigninProfile, {"system"}}, TestConfig{ProfileToUse::kUnaffiliatedUserProfile, {"user"}}, TestConfig{ProfileToUse::kAffiliatedUserProfile, {"user", "system"}})); } // namespace platform_keys } // namespace chromeos
38.188889
80
0.752109
3741ebbac3567d9bd1d0fb3eee75a5c2a9b3a458
2,817
cpp
C++
src/input/SDLJoystickInput.cpp
benlamonica/tetra-table
521082f2a848d04608ef6368004e90e780ef62ea
[ "Apache-2.0" ]
null
null
null
src/input/SDLJoystickInput.cpp
benlamonica/tetra-table
521082f2a848d04608ef6368004e90e780ef62ea
[ "Apache-2.0" ]
null
null
null
src/input/SDLJoystickInput.cpp
benlamonica/tetra-table
521082f2a848d04608ef6368004e90e780ef62ea
[ "Apache-2.0" ]
null
null
null
// // SDLJoystickInput.cpp // TetraTable // // Created by Ben La Monica on 3/23/15. // Copyright (c) 2015 Benjamin Alan La Monica. All rights reserved. // #include "SDLJoystickInput.hpp" #include "../util/SDLUtil.hpp" #include <syslog.h> #include <SDL2/SDL.h> #include "../util/TimeUtil.hpp" SDLJoystickInput::SDLJoystickInput(TetraTable *game, TetraTableInput::Ptr delegate) : TetraTableInput(game, delegate), m_direction(pieces::NONE){ } SDLJoystickInput::~SDLJoystickInput() { } void SDLJoystickInput::getNextMove(std::vector<pieces::Move>& moves) { SDLUtil& sdl = SDLUtil::instance(); using namespace pieces; using namespace util; SDLEvent::Ptr event = sdl.getNextEvent(); if (event && event->m_event.type >= 0x600 && event->m_event.type < 0x700) { switch(event->m_event.type) { case SDL_JOYAXISMOTION: { Sint16 x = SDL_JoystickGetAxis(event->joy,0); Sint16 y = SDL_JoystickGetAxis(event->joy,1); syslog(LOG_WARNING, "axis event: x,y (%d,%d)", x, y); if (x < 128) { m_direction.store(LEFT); m_repeatingStarts.store(now() + 200000000); syslog(LOG_WARNING, "LEFT %lld (%lld)", m_repeatingStarts.load(), now()); } else if (x > 128) { m_direction.store(RIGHT); m_repeatingStarts.store(now() + 200000000); syslog(LOG_WARNING, "RIGHT"); } else if (y > 128) { syslog(LOG_WARNING, "DOWN"); m_repeatingStarts.store(now() + 200000000); m_direction.store(DOWN); } else { m_repeatingStarts.store(INT64_MAX); m_direction.store(NONE); } break; } case SDL_JOYBUTTONDOWN: { Uint8 button = event->m_event.jbutton.button; syslog(LOG_WARNING, "button %d %s", button, event->m_event.jbutton.state == SDL_PRESSED ? "pressed" : "released"); if (button == 0) { moves.push_back(ROTATE_LEFT); } else if (button == 1) { moves.push_back(DROP); } else if (button == 2) { moves.push_back(HOLD_PIECE); } else if (button == 3) { moves.push_back(ROTATE_RIGHT); } else if (button == 4) { //moves.push_back(QUIT); } break; } } moves.push_back(m_direction.load()); } else { if (m_repeatingStarts.load() <= util::now()) { moves.push_back(m_direction.load()); } util::millisleep(30); } }
36.584416
145
0.520412
37425be6f8b39cf8ee3f838d459363812d7e47df
259
cpp
C++
ASCIIGen/src/bmp.cpp
KrystofSuk/Sandbox-CPP
956747088fa502d3acf32aad1428eec0bdbcfd34
[ "MIT" ]
null
null
null
ASCIIGen/src/bmp.cpp
KrystofSuk/Sandbox-CPP
956747088fa502d3acf32aad1428eec0bdbcfd34
[ "MIT" ]
null
null
null
ASCIIGen/src/bmp.cpp
KrystofSuk/Sandbox-CPP
956747088fa502d3acf32aad1428eec0bdbcfd34
[ "MIT" ]
null
null
null
#include "bmp.h" BMP::BMP(int _x, int _y, int _colorNumber) { x = _x; y = _y; colorNumber = _colorNumber; } int BMP::GetColorNumber(){ return colorNumber; } int BMP::GetX(){ return x; } int BMP::GetY(){ return y; } BMP::~BMP() { }
10.791667
42
0.571429
374816a086693c8e9be578dd2257e444b6fe5ab8
506
cpp
C++
Snipets/01_Decisiones/IfeIfAnidado.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
Snipets/01_Decisiones/IfeIfAnidado.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
Snipets/01_Decisiones/IfeIfAnidado.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
// IfeIfAnidado.cpp // Programa para saber si el numero introducido es par o impar utilizando un bucle if #include <iostream> #include <stdlib.h> int main() { int n; std::cout << "Introduce un numero: "; std::cin >> n; if(n%2 == 0) // Calculamos el residuo del numero al dividirlo entre 2. Si el residuo es 0 el numero es par std::cout << "El numero introducido es par" << std::endl; else std::cout << "El numero introducido es impar" << std::endl; system("pause"); return 0; }
22
114
0.65415
374e0ac796062606a9bbe986e290ee0a8b828c29
7,883
hpp
C++
Library/include/mavlink/v2.0/matrixpilot/mavlink_msg_serial_udb_extra_f2_a.hpp
Dieptranivsr/Ros_Diep
d790e75e6f5da916701b11a2fdf3e03b6a47086b
[ "MIT" ]
10
2021-03-15T03:58:06.000Z
2021-12-30T15:33:38.000Z
devel/include/mavlink/v2.0/matrixpilot/mavlink_msg_serial_udb_extra_f2_a.hpp
arijitnoobstar/UAVProjectileCatcher
3c1bed80df167192cb4b971b58c891187628142e
[ "Apache-2.0" ]
1
2021-09-09T15:29:31.000Z
2021-09-09T15:29:31.000Z
Library/include/mavlink/v2.0/matrixpilot/mavlink_msg_serial_udb_extra_f2_a.hpp
Dieptranivsr/Ros_Diep
d790e75e6f5da916701b11a2fdf3e03b6a47086b
[ "MIT" ]
4
2021-03-06T09:35:58.000Z
2021-05-24T14:34:11.000Z
// MESSAGE SERIAL_UDB_EXTRA_F2_A support class #pragma once namespace mavlink { namespace matrixpilot { namespace msg { /** * @brief SERIAL_UDB_EXTRA_F2_A message * * Backwards compatible MAVLink version of SERIAL_UDB_EXTRA - F2: Format Part A */ struct SERIAL_UDB_EXTRA_F2_A : mavlink::Message { static constexpr msgid_t MSG_ID = 170; static constexpr size_t LENGTH = 61; static constexpr size_t MIN_LENGTH = 61; static constexpr uint8_t CRC_EXTRA = 103; static constexpr auto NAME = "SERIAL_UDB_EXTRA_F2_A"; uint32_t sue_time; /*< Serial UDB Extra Time */ uint8_t sue_status; /*< Serial UDB Extra Status */ int32_t sue_latitude; /*< Serial UDB Extra Latitude */ int32_t sue_longitude; /*< Serial UDB Extra Longitude */ int32_t sue_altitude; /*< Serial UDB Extra Altitude */ uint16_t sue_waypoint_index; /*< Serial UDB Extra Waypoint Index */ int16_t sue_rmat0; /*< Serial UDB Extra Rmat 0 */ int16_t sue_rmat1; /*< Serial UDB Extra Rmat 1 */ int16_t sue_rmat2; /*< Serial UDB Extra Rmat 2 */ int16_t sue_rmat3; /*< Serial UDB Extra Rmat 3 */ int16_t sue_rmat4; /*< Serial UDB Extra Rmat 4 */ int16_t sue_rmat5; /*< Serial UDB Extra Rmat 5 */ int16_t sue_rmat6; /*< Serial UDB Extra Rmat 6 */ int16_t sue_rmat7; /*< Serial UDB Extra Rmat 7 */ int16_t sue_rmat8; /*< Serial UDB Extra Rmat 8 */ uint16_t sue_cog; /*< Serial UDB Extra GPS Course Over Ground */ int16_t sue_sog; /*< Serial UDB Extra Speed Over Ground */ uint16_t sue_cpu_load; /*< Serial UDB Extra CPU Load */ uint16_t sue_air_speed_3DIMU; /*< Serial UDB Extra 3D IMU Air Speed */ int16_t sue_estimated_wind_0; /*< Serial UDB Extra Estimated Wind 0 */ int16_t sue_estimated_wind_1; /*< Serial UDB Extra Estimated Wind 1 */ int16_t sue_estimated_wind_2; /*< Serial UDB Extra Estimated Wind 2 */ int16_t sue_magFieldEarth0; /*< Serial UDB Extra Magnetic Field Earth 0 */ int16_t sue_magFieldEarth1; /*< Serial UDB Extra Magnetic Field Earth 1 */ int16_t sue_magFieldEarth2; /*< Serial UDB Extra Magnetic Field Earth 2 */ int16_t sue_svs; /*< Serial UDB Extra Number of Sattelites in View */ int16_t sue_hdop; /*< Serial UDB Extra GPS Horizontal Dilution of Precision */ inline std::string get_name(void) const override { return NAME; } inline Info get_message_info(void) const override { return { MSG_ID, LENGTH, MIN_LENGTH, CRC_EXTRA }; } inline std::string to_yaml(void) const override { std::stringstream ss; ss << NAME << ":" << std::endl; ss << " sue_time: " << sue_time << std::endl; ss << " sue_status: " << +sue_status << std::endl; ss << " sue_latitude: " << sue_latitude << std::endl; ss << " sue_longitude: " << sue_longitude << std::endl; ss << " sue_altitude: " << sue_altitude << std::endl; ss << " sue_waypoint_index: " << sue_waypoint_index << std::endl; ss << " sue_rmat0: " << sue_rmat0 << std::endl; ss << " sue_rmat1: " << sue_rmat1 << std::endl; ss << " sue_rmat2: " << sue_rmat2 << std::endl; ss << " sue_rmat3: " << sue_rmat3 << std::endl; ss << " sue_rmat4: " << sue_rmat4 << std::endl; ss << " sue_rmat5: " << sue_rmat5 << std::endl; ss << " sue_rmat6: " << sue_rmat6 << std::endl; ss << " sue_rmat7: " << sue_rmat7 << std::endl; ss << " sue_rmat8: " << sue_rmat8 << std::endl; ss << " sue_cog: " << sue_cog << std::endl; ss << " sue_sog: " << sue_sog << std::endl; ss << " sue_cpu_load: " << sue_cpu_load << std::endl; ss << " sue_air_speed_3DIMU: " << sue_air_speed_3DIMU << std::endl; ss << " sue_estimated_wind_0: " << sue_estimated_wind_0 << std::endl; ss << " sue_estimated_wind_1: " << sue_estimated_wind_1 << std::endl; ss << " sue_estimated_wind_2: " << sue_estimated_wind_2 << std::endl; ss << " sue_magFieldEarth0: " << sue_magFieldEarth0 << std::endl; ss << " sue_magFieldEarth1: " << sue_magFieldEarth1 << std::endl; ss << " sue_magFieldEarth2: " << sue_magFieldEarth2 << std::endl; ss << " sue_svs: " << sue_svs << std::endl; ss << " sue_hdop: " << sue_hdop << std::endl; return ss.str(); } inline void serialize(mavlink::MsgMap &map) const override { map.reset(MSG_ID, LENGTH); map << sue_time; // offset: 0 map << sue_latitude; // offset: 4 map << sue_longitude; // offset: 8 map << sue_altitude; // offset: 12 map << sue_waypoint_index; // offset: 16 map << sue_rmat0; // offset: 18 map << sue_rmat1; // offset: 20 map << sue_rmat2; // offset: 22 map << sue_rmat3; // offset: 24 map << sue_rmat4; // offset: 26 map << sue_rmat5; // offset: 28 map << sue_rmat6; // offset: 30 map << sue_rmat7; // offset: 32 map << sue_rmat8; // offset: 34 map << sue_cog; // offset: 36 map << sue_sog; // offset: 38 map << sue_cpu_load; // offset: 40 map << sue_air_speed_3DIMU; // offset: 42 map << sue_estimated_wind_0; // offset: 44 map << sue_estimated_wind_1; // offset: 46 map << sue_estimated_wind_2; // offset: 48 map << sue_magFieldEarth0; // offset: 50 map << sue_magFieldEarth1; // offset: 52 map << sue_magFieldEarth2; // offset: 54 map << sue_svs; // offset: 56 map << sue_hdop; // offset: 58 map << sue_status; // offset: 60 } inline void deserialize(mavlink::MsgMap &map) override { map >> sue_time; // offset: 0 map >> sue_latitude; // offset: 4 map >> sue_longitude; // offset: 8 map >> sue_altitude; // offset: 12 map >> sue_waypoint_index; // offset: 16 map >> sue_rmat0; // offset: 18 map >> sue_rmat1; // offset: 20 map >> sue_rmat2; // offset: 22 map >> sue_rmat3; // offset: 24 map >> sue_rmat4; // offset: 26 map >> sue_rmat5; // offset: 28 map >> sue_rmat6; // offset: 30 map >> sue_rmat7; // offset: 32 map >> sue_rmat8; // offset: 34 map >> sue_cog; // offset: 36 map >> sue_sog; // offset: 38 map >> sue_cpu_load; // offset: 40 map >> sue_air_speed_3DIMU; // offset: 42 map >> sue_estimated_wind_0; // offset: 44 map >> sue_estimated_wind_1; // offset: 46 map >> sue_estimated_wind_2; // offset: 48 map >> sue_magFieldEarth0; // offset: 50 map >> sue_magFieldEarth1; // offset: 52 map >> sue_magFieldEarth2; // offset: 54 map >> sue_svs; // offset: 56 map >> sue_hdop; // offset: 58 map >> sue_status; // offset: 60 } }; } // namespace msg } // namespace matrixpilot } // namespace mavlink
47.775758
83
0.523024
374ebc05844425a2785be3d7ac1b445de32c8207
12,027
cpp
C++
src/mesh/mechanical/plane/fem_submesh.cpp
annierhea/neon
4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1
[ "MIT" ]
null
null
null
src/mesh/mechanical/plane/fem_submesh.cpp
annierhea/neon
4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1
[ "MIT" ]
null
null
null
src/mesh/mechanical/plane/fem_submesh.cpp
annierhea/neon
4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1
[ "MIT" ]
null
null
null
#include "fem_submesh.hpp" #include "exceptions.hpp" #include "constitutive/constitutive_model_factory.hpp" #include "geometry/projection.hpp" #include "interpolations/interpolation_factory.hpp" #include "material/material_property.hpp" #include "mesh/material_coordinates.hpp" #include "mesh/dof_allocator.hpp" #include "numeric/mechanics" #include "traits/mechanics.hpp" #include <cfenv> #include <chrono> #include <termcolor/termcolor.hpp> namespace neon::mechanical::plane { fem_submesh::fem_submesh(json const& material_data, json const& simulation_data, std::shared_ptr<material_coordinates>& coordinates, basic_submesh const& submesh) : detail::fem_submesh<plane::fem_submesh, plane::internal_variables_t>(submesh), coordinates{coordinates}, sf(make_surface_interpolation(topology(), simulation_data)), view(sf->quadrature().points()), variables(std::make_shared<internal_variables_t>(elements() * sf->quadrature().points())), cm(make_constitutive_model(variables, material_data, simulation_data)) { // Allocate storage for the displacement gradient variables->add(variable::second::displacement_gradient, variable::second::deformation_gradient, variable::second::cauchy_stress, variable::scalar::DetF); // Get the old data to the undeformed configuration for (auto& F : variables->get(variable::second::deformation_gradient)) { F = matrix2::Identity(); } variables->commit(); dof_allocator(node_indices, dof_list, traits::dof_order); } void fem_submesh::save_internal_variables(bool const have_converged) { if (have_converged) { variables->commit(); } else { variables->revert(); } } std::pair<index_view, matrix> fem_submesh::tangent_stiffness(std::int64_t const element) const { auto const x = geometry::project_to_plane( coordinates->current_configuration(local_node_view(element))); matrix ke = material_tangent_stiffness(x, element); if (!cm->is_finite_deformation()) return {local_dof_view(element), ke}; ke.noalias() += geometric_tangent_stiffness(x, element); return {local_dof_view(element), ke}; } std::pair<index_view, vector> fem_submesh::internal_force(std::int64_t const element) const { auto const x = geometry::project_to_plane( coordinates->current_configuration(local_node_view(element))); return {local_dof_view(element), internal_nodal_force(x, element)}; } matrix fem_submesh::geometric_tangent_stiffness(matrix2x const& x, std::int64_t const element) const { auto const& cauchy_stresses = variables->get(variable::second::cauchy_stress); auto const n = nodes_per_element(); matrix const kgeo = sf->quadrature() .integrate(matrix::Zero(n, n).eval(), [&](auto const& femval, auto const& l) -> matrix { auto const& [N, rhea] = femval; matrix2 const Jacobian = local_deformation_gradient(rhea, x); auto const cauchy = cauchy_stresses[view(element, l)]; // Compute the symmetric gradient operator auto const L = (rhea * Jacobian.inverse()).transpose(); return L.transpose() * cauchy * L * Jacobian.determinant(); }); return identity_expansion(kgeo, dofs_per_node()); } matrix fem_submesh::material_tangent_stiffness(matrix2x const& x, std::int64_t const element) const { auto const local_dofs = nodes_per_element() * dofs_per_node(); auto const& tangent_operators = variables->get(variable::fourth::tangent_operator); return sf->quadrature().integrate(matrix::Zero(local_dofs, local_dofs).eval(), [&](auto const& femval, auto const& l) -> matrix { auto const& [N, rhea] = femval; auto const& D = tangent_operators[view(element, l)]; matrix2 const Jacobian{local_deformation_gradient(rhea, x)}; auto const B = fem::sym_gradient<2>( (rhea * Jacobian.inverse()).transpose()); return B.transpose() * D * B * Jacobian.determinant(); }); } vector fem_submesh::internal_nodal_force(matrix2x const& x, std::int64_t const element) const { auto const& cauchy_stresses = variables->get(variable::second::cauchy_stress); auto const [m, n] = std::make_tuple(nodes_per_element(), dofs_per_node()); vector fint = vector::Zero(m * n); sf->quadrature().integrate(Eigen::Map<row_matrix>(fint.data(), m, n), [&](auto const& femval, auto const& l) -> row_matrix { auto const& [N, dN] = femval; matrix2 const Jacobian = local_deformation_gradient(dN, x); auto const& cauchy_stress = cauchy_stresses[view(element, l)]; // Compute the symmetric gradient operator auto const Bt = dN * Jacobian.inverse(); return Bt * cauchy_stress * Jacobian.determinant(); }); return fint; } std::pair<index_view, matrix> fem_submesh::consistent_mass(std::int64_t const element) const { auto const X = coordinates->initial_configuration(local_node_view(element)); return {local_dof_view(element), X}; // auto const density_0 = cm->intrinsic_material().initial_density(); // // auto m = sf->quadrature().integrate(matrix::Zero(nodes_per_element(), nodes_per_element()).eval(), // [&](auto const& femval, auto const& l) -> matrix { // auto const & [N, dN] = femval; // // auto const Jacobian = local_deformation_gradient(dN, X); // // return N * density_0 * N.transpose() // * Jacobian.determinant(); // }); // return {local_dof_view(element), identity_expansion(m, dofs_per_node())}; } std::pair<index_view, vector> fem_submesh::diagonal_mass(std::int64_t const element) const { auto const& [dofs, consistent_m] = this->consistent_mass(element); vector diagonal_m(consistent_m.rows()); for (auto i = 0; i < consistent_m.rows(); ++i) { diagonal_m(i) = consistent_m.row(i).sum(); } return {local_dof_view(element), diagonal_m}; } void fem_submesh::update_internal_variables(double const time_step_size) { std::feclearexcept(FE_ALL_EXCEPT); update_deformation_measures(); update_Jacobian_determinants(); cm->update_internal_variables(time_step_size); if (std::fetestexcept(FE_INVALID)) { throw computational_error("Floating point error reported\n"); } } void fem_submesh::update_deformation_measures() { auto& H_list = variables->get(variable::second::displacement_gradient); auto& F_list = variables->get(variable::second::deformation_gradient); for (std::int64_t element{0}; element < elements(); ++element) { // Gather the material coordinates auto const X = geometry::project_to_plane( coordinates->initial_configuration(local_node_view(element))); auto const x = geometry::project_to_plane( coordinates->current_configuration(local_node_view(element))); sf->quadrature().for_each([&](auto const& femval, const auto& l) { auto const& [N, rhea] = femval; // Local deformation gradient for the initial configuration matrix2 const F_0 = local_deformation_gradient(rhea, X); matrix2 const F = local_deformation_gradient(rhea, x); // Gradient operator in index notation auto const& B_0t = rhea * F_0.inverse(); // Displacement gradient matrix2 const H = (x - X) * B_0t; H_list[view(element, l)] = H; F_list[view(element, l)] = F * F_0.inverse(); }); } } void fem_submesh::update_Jacobian_determinants() { auto const& F = variables->get(variable::second::deformation_gradient); auto& F_det = variables->get(variable::scalar::DetF); std::transform(begin(F), end(F), begin(F_det), [](auto const& F) { return F.determinant(); }); auto const found = std::find_if(begin(F_det), end(F_det), [](auto const value) { return value <= 0.0; }); if (found != F_det.end()) { auto const i = std::distance(begin(F_det), found); auto const [element, quadrature_point] = std::div(i, sf->quadrature().points()); throw computational_error("Positive Jacobian assumption violated at element " + std::to_string(element) + " and local quadrature point " + std::to_string(quadrature_point) + " (" + std::to_string(*found) + ")"); } } std::pair<vector, vector> fem_submesh::nodal_averaged_variable(variable::scalar const scalar_name) const { vector count = vector::Zero(coordinates->size()); vector value = count; auto const& scalar_list = variables->get(scalar_name); auto const& E = sf->local_quadrature_extrapolation(); // vector format of values vector component = vector::Zero(sf->quadrature().points()); for (std::int64_t element{0}; element < elements(); ++element) { for (std::size_t l{0}; l < sf->quadrature().points(); ++l) { component(l) = scalar_list[view(element, l)]; } // Local extrapolation to the nodes vector const nodal_component = E * component; // Assemble these into the global value vector auto const& node_list = local_node_view(element); for (auto n = 0; n < nodal_component.rows(); n++) { value(node_list[n]) += nodal_component(n); count(node_list[n]) += 1.0; } } return {value, count}; } std::pair<vector, vector> fem_submesh::nodal_averaged_variable(variable::second const tensor_name) const { vector count = vector::Zero(coordinates->size() * 4); vector value = count; auto const& tensor_list = variables->get(tensor_name); matrix const E = sf->local_quadrature_extrapolation(); // vector format of values vector component(sf->quadrature().points()); for (std::int64_t element{0}; element < elements(); ++element) { // Assemble these into the global value vector auto const& node_list = local_node_view(element); for (auto ci = 0; ci < 2; ++ci) { for (auto cj = 0; cj < 2; ++cj) { for (std::size_t l{0}; l < sf->quadrature().points(); ++l) { component(l) = tensor_list[view(element, l)](ci, cj); } // Local extrapolation to the nodes vector const nodal_component = E * component; for (auto n = 0; n < nodal_component.rows(); n++) { value(node_list[n] * 4 + ci * 2 + cj) += nodal_component(n); count(node_list[n] * 4 + ci * 2 + cj) += 1.0; } } } } return {value, count}; } }
36.445455
105
0.579529
3753e8029f41cd6f3f89d6a217e100fa572871af
20,003
cpp
C++
src/zutil/conn.cpp
mgwoo/OpenDB
8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4
[ "BSD-3-Clause" ]
1
2021-03-04T02:35:47.000Z
2021-03-04T02:35:47.000Z
src/zutil/conn.cpp
mgwoo/OpenDB
8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4
[ "BSD-3-Clause" ]
null
null
null
src/zutil/conn.cpp
mgwoo/OpenDB
8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (c) 2019, Nefelus Inc // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "conn.h" #include "wire.h" #include "zui.h" Ath__connWord::Ath__connWord(uint r1, uint c1) { _conn._fromRow= r1; _conn._fromCol= c1; _conn._toRow= 0; _conn._toCol= 0; _conn._ordered= 0; _conn._placed= 0; _conn._posFlow= 0; _conn._corner= 0; _conn._straight= 0; _conn._dir= 0; } Ath__connWord::Ath__connWord(uint r1, uint c1, uint type) { _conn._fromRow= r1; _conn._fromCol= c1; _conn._toRow= type; _conn._toCol= type; _conn._ordered= 0; _conn._placed= 0; _conn._posFlow= 0; _conn._corner= 0; _conn._straight= 0; _conn._dir= 0; } bool Ath__connWord::ordered() { return (_conn._ordered>0) ? true : false; } void Ath__connWord::orderByRow(uint r1, uint c1, uint r2, uint c2, uint colCnt) { if (r1>r2) { set(r2, c2, r1, c1, colCnt); _conn._ordered= 1; } else { set(r1, c1, r2, c2, colCnt); } } Ath__connWord::Ath__connWord(uint r1, uint c1, uint r2, uint c2, uint colCnt) { set(r1, c1, r2, c2, colCnt); _conn._ordered= 0; _conn._placed= 0; _conn._posFlow= 0; _conn._corner= 0; _conn._straight= 0; _conn._dir= 0; if (getRowDist()==0) { _conn._straight= 1; if (c1>c2) { set(r1, c1, r2, c2, colCnt); _conn._fromCol= c2; _conn._toCol= c1; _conn._ordered= 1; } } else if (getColDist()==0) { _conn._straight= 1; _conn._dir= 1; if (r1>r2) { _conn._fromRow= r2; _conn._toRow= r1; _conn._ordered= 1; } } else { orderByRow(r1, c1, r2, c2, colCnt); _conn._corner= 1; } } int Ath__connWord::getStraight() { if (_conn._straight>0) return _conn._dir; else return -1; } int Ath__connWord::getRowDist() { return _conn._toRow - _conn._fromRow; } int Ath__connWord::getColDist() { return _conn._toCol - _conn._fromCol; } uint Ath__connWord::getDist() { return ath__max(getRowDistAbs(), getColDistAbs()) ; } uint Ath__connWord::getMinDist() { return ath__min(getRowDistAbs(), getColDistAbs()) ; } uint Ath__connWord::getMaxDist() { return ath__max(getRowDistAbs(), getColDistAbs()) ; } uint Ath__connWord::getRowDistAbs() { int dist= getRowDist(); if (dist<0) return -dist; else return dist; } uint Ath__connWord::getSeg(uint *c1, uint *c2) { if (_conn._straight==0) return 0; if (_conn._dir==0) { *c2= _conn._toCol; *c1= _conn._fromCol; return _conn._fromRow; } else { *c2= _conn._toRow; *c1= _conn._fromRow; return _conn._fromCol; } } uint Ath__connWord::getColDistAbs() { int dist= getColDist(); if (dist<0) return -dist; else return dist; } Ath__connWord::Ath__connWord(uint v) { setAll(v); } uint Ath__connWord::getAll() { return _all; } void Ath__connWord::setAll(uint v) { _all= v; } uint Ath__connWord::getFromRowCol(uint *col) { *col= _conn._fromCol; return _conn._fromRow; } uint Ath__connWord::getToRowCol(uint *col) { *col= _conn._toCol; return _conn._toRow; } uint Ath__connWord::getFrom() { return _conn._colCnt * _conn._fromRow + _conn._fromCol; } uint Ath__connWord::getTo() { return _conn._colCnt * _conn._toRow + _conn._toCol; } uint Ath__connWord::set(uint x1, uint y1, uint x2, uint y2, uint colCnt) { _conn._fromRow= x1; _conn._fromCol= y1; _conn._toRow= x2; _conn._toCol= y2; _conn._colCnt= colCnt; return _all; } void Ath__p2pConn::setNext(Ath__p2pConn *v) { _next= v; } void Ath__p2pConn::setPin(Ath__qPin *q) { _srcPin= q; } Ath__qPin *Ath__p2pConn::getSrcPin() { return _srcPin; } Ath__connTable::Ath__connTable(AthPool<Ath__p2pConn> *pool, uint n, uint pinLength, uint tileSize) { if (n==0) n=32; _nextSegCnt= 2; _tileSize= 0; _pinLength= 0; if (tileSize>0) { _nextSegCnt= tileSize/pinLength+1; _tileSize= tileSize; _pinLength= pinLength; } _maxBankCnt= n; _straightTable[0]= new Ath__array2d<Ath__p2pConn*>(n, true); _straightTable[1]= new Ath__array2d<Ath__p2pConn*>(n, true); _nextTable[0]= new Ath__array2d<Ath__p2pConn*>(_nextSegCnt); _nextTable[1]= new Ath__array2d<Ath__p2pConn*>(_nextSegCnt); _cornerTable= new Ath__array2d<Ath__p2pConn*>(2*n, true); _tmpTablePtr= NULL; _tmpArrayPtr= NULL; _poolPtr= pool; //_poolPtr= new AthPool<Ath__p2pConn>(1024); } uint Ath__connTable::getSegmentIndex(uint dir, uint dx, uint dy) { if (_pinLength==0) return 0; if (dir>0) { // vertical return dy/_pinLength; } else { return dx/_pinLength; } } Ath__p2pConn* Ath__connTable::addConn(uint netId, Ath__connWord w, uint dx, uint dy) { Ath__p2pConn* conn= _poolPtr->alloc(); conn->_netId= netId; conn->_conn= w; uint dist= w.getDist(); int dir= w.getStraight(); if (dir<0) { _cornerTable->add(dist, conn); } else { if (dist>1) { _straightTable[dir]->add(dist, conn); } else { if (dy==0) { // default _nextTable[dir]->add(0, conn); } else { uint kk= getSegmentIndex(dir, dx, dy); _nextTable[dir]->add(kk, conn); } } } return conn; } uint Ath__connTable::addStraightConn(uint dir, uint dist, Ath__p2pConn* p2p) { return _straightTable[dir]->add(dist, p2p); } uint Ath__connTable::addCornerConn2(uint type, Ath__p2pConn* p2p, uint ii, uint jj) { Ath__connWord w(ii, jj, type); p2p->_conn= w; return _cornerTable->add(type, p2p); } void Ath__connTable::printConnStats(FILE *fp) { fprintf(fp, "\n\nNet length distribution per tile unit length\n"); fprintf(fp, "--------------------------------------------\n"); char buff[128]; for (uint ii= 0; ii<_nextSegCnt; ii++) { sprintf(buff, " next tile HORIZONTAL conns - Length= %7d", (ii+1)*_pinLength); _nextTable[0]->printCnt(fp, ii, buff); } fprintf(fp, "\n"); for (uint jj= 0; jj<_nextSegCnt; jj++) { sprintf(buff, " next tile VERTICAL conns - Length= %7d", (jj+1)*_pinLength); _nextTable[1]->printCnt(fp, jj, buff); } fprintf(fp, "\n\n--------- straight tile-feedthru's\n"); _straightTable[0]->printAllCnts(fp, "tile-dist", " HORIZONTAL"); _straightTable[1]->printAllCnts(fp, "tile-dist", " VERTICAL"); fprintf(fp, "\n\n--------- corner tile-feedthru's\n"); _cornerTable->printAllCnts(fp, "tile-dist", "CORNER"); } uint Ath__connTable::startNextIterator(uint dir, uint seg) { _tmpTablePtr= _nextTable[dir]; return _tmpTablePtr->startIterator(seg); } uint Ath__connTable::startCornerIterator(uint dist) { _tmpTablePtr= _cornerTable; return _tmpTablePtr->startIterator(dist); } uint Ath__connTable::startStraightIterator(uint dir, uint dist) { _tmpTablePtr= _straightTable[dir]; return _tmpTablePtr->startIterator(dist); } int Ath__connTable::getNextConn(Ath__connWord *conn, uint *netId) { Ath__p2pConn* p2p= NULL; uint next= _tmpTablePtr->getNext(&p2p); if (next==0) return 0; *netId= p2p->_netId; *conn= p2p->_conn; return next; } Ath__p2pConn* Ath__connTable::getNextConn() { Ath__p2pConn* p2p= NULL; if (_tmpTablePtr->getNext(&p2p)==0) return NULL; return p2p; } Ath__array2d<Ath__p2pConn*>* Ath__connTable::startStraightArrayIterator(uint dir) { _tmpArrayPtr= _straightTable[dir]; for (uint ii= 0; ii<_maxBankCnt; ii++) { _tmpCurrentIndex[ii]= 0; _tmpCnt[ii]= _tmpArrayPtr->getCnt(ii); } return _tmpArrayPtr; } bool Ath__connTable::getNextArrayConn(uint ii, Ath__connWord *conn, uint *netId) { if (_tmpCurrentIndex[ii]>=_tmpCnt[ii]) return false; Ath__p2pConn* p2p= _tmpArrayPtr->get(ii, _tmpCurrentIndex[ii]); _tmpCurrentIndex[ii] ++; *netId= p2p->_netId; *conn= p2p->_conn; return true; } uint Ath__qPin::getToRowCol(uint *col) { return _conn.getToRowCol(col); } uint Ath__qPin::getTurnRowCol(uint *row, uint *col) { Ath__qPin* src= getSrcPin(); *row= src->_head->_conn.getFromRowCol(col); uint tmp1; //TODO return src->_head->_conn.getToRowCol(&tmp1); } int Ath__qPin::getTurnDist(uint *row, uint *col, int *dir) { uint turnRow, turnCol; getTurnRowCol(&turnRow, &turnCol); int rowDist= turnRow - *row; int colDist= turnCol - *col; if (rowDist==0) // horizontal { *dir= 1; if (colDist<0) { *col= turnCol; return -colDist; } return colDist; } if (colDist==0) // vertical { *dir= 0; if (rowDist<0) { *row= turnRow; return -rowDist; } return rowDist; } *dir= -1; return -1; } bool Ath__qPin::isTargeted() { return (_targeted>0) ? true : false; } bool Ath__qPin::isAssigned() { return (_assigned>0) ? true : false; } void Ath__qPin::setTargeted() { _targeted= 1; } void Ath__qPin::setPlaced() { _placed= 1; } bool Ath__qPin::isPlaced() { return (_placed>0) ? true : false; } bool Ath__qPin::isSrc() { return (_src>0) ? true : false; } Ath__qPin* Ath__qPin::getSrcPin() { if (_src>0) return this; else return _head->getSrcPin(); } Ath__qPin* Ath__qPin::getDstPin() { if (_src>0) return _next; else return this; } Ath__box *Ath__qPin::getInstBox() { return _instBB; } uint Ath__qPin::getLayer() { if (_portBB!=NULL) return _portBB->_layer; if (_targetBB!=NULL) return _targetBB->_layer; if (_instBB!=NULL) return _instBB->_layer; return 0; } void Ath__qPin::addBusBox(Ath__box *bb) { bb->_next= _busList; _busList= bb; } void Ath__qPin::setInstBox(Ath__box *bb) { _instBB= bb; } void Ath__qPin::getNextObsBox(Ath__searchBox *sbb) { Ath__box *bb= _obsList; if (_obsList->_next!=NULL) bb= _obsList->_next; sbb->set(bb->_xlo, bb->_ylo, bb->_xhi, bb->_yhi, bb->_layer, 0); } void Ath__qPin::getObsBox(Ath__searchBox *sbb) { Ath__box *bb= _obsList; sbb->set(bb->_xlo, bb->_ylo, bb->_xhi, bb->_yhi, bb->_layer, 0); } void Ath__qPin::getTargetBox(Ath__searchBox *bb) { bb->set(_targetBB->_xlo, _targetBB->_ylo, _targetBB->_xhi, _targetBB->_yhi, _targetBB->_layer, 0); } uint Ath__qPin::makeZuiObject(Ath__zui *zui, uint width, bool actual, bool instFlag) { if (width<=0) width= 1000; if (instFlag) { uint w2= width/2; zui->addBox(_nameId, Ath_box__pin, Ath_hier__tile, _instBB->_layer, _instBB->getMidX()-w2, _instBB->getMidY()-w2, _instBB->getMidX()+w2, _instBB->getMidY()+w2); return _instBB->_layer; } if (actual && (_portBB!=NULL)) { int x1= _portBB->_xlo; int y1= _portBB->_ylo; int x2= _portBB->_xhi; int y2= _portBB->_yhi; zui->addBox(_nameId, Ath_box__pin, Ath_hier__tile, _portBB->_layer, x1, y1, x2, y2); return _portBB->_layer; } if (_targetBB!=NULL) { uint w2= width/2; int x1= _targetBB->_xlo; int y1= _targetBB->_ylo; int x2= _targetBB->_xhi; int y2= _targetBB->_yhi; if (x1==x2) { x1 -= w2; x2 += w2; } else if (y1==y2) { y1 -= w2; y2 += w2; } zui->addBox(_nameId, Ath_box__pin, Ath_hier__tile, _targetBB->_layer, x1, y1, x2, y2); return _targetBB->_layer; } } Ath__box* Ath__qPin::getPortCoords(int *x1, int *y1, int *x2, int *y2, uint *layer) { if (_portBB==NULL) return NULL; *x1= _portBB->_xlo; *y1= _portBB->_ylo; *x2= _portBB->_xhi; *y2= _portBB->_yhi; *layer= _portBB->_layer; return _portBB; } Ath__box* Ath__qPin::getBusList() { return _busList; } uint Ath__qPin::makePinObsZui(Ath__zui *zui, int width, int x1, int y1, int x2, int y2, int layer) { uint w2= width/2; if (x1==x2) { x1 -= w2; x2 += w2; } else if (y1==y2) { y1 -= w2; y2 += w2; } return zui->addBox(_nameId, Ath_box__bus, Ath_hier__tile, layer, x1, y1, x2, y2); } uint Ath__qPin::makeBusZuiObject(Ath__zui *zui, uint width) { uint cnt= 0; // if (obs==NULL) // nextTile shapes don't have shapes for (Ath__box *obs= _obsList; obs!=NULL; obs= obs->_next) { cnt += makePinObsZui(zui, width, obs->_xlo, obs->_ylo, obs->_xhi, obs->_yhi, obs->_layer); } return cnt; } void Ath__qPin::reset() { _src= 0; _tjunction= 0; _placed= 0; _fixed= 0; _assigned= 0; _targeted= 0; _nameId= 0; _instBB= NULL; _targetBB= NULL; _portBB= NULL; _portWireId= 0; _obsList= NULL; _busList= NULL; } void Ath__qPin::setPortWireId(uint id) { _portWireId= id; } void Ath__qPin::pinBoxDef(FILE *fp, char *layerName, char *orient, int defUnits) { fprintf(stdout, "TODO: pinBoxDef\n"); return; /* fprintf(fp, " ( %d %d ) %s ", _bb->_xlo/defUnits, _bb->_ylo/defUnits, orient); fprintf(fp, " + LAYER %s ( %d %d ) ( %d %d ) ", layerName, 0, 0, _bb->getDX()/defUnits, _bb->getDY()/defUnits); */ } Ath__qPinTable::Ath__qPinTable(AthPool<Ath__qPin> *qPinPool, AthPool<Ath__box> *boxPool, uint n) { _table= new Ath__array1D<Ath__qPin*>(n); for (uint jj= 0; jj<2; jj++) { _nextPinShape[jj]= NULL; _straightPinShape[jj]= NULL; _thruObsShape[jj]= NULL; } for (uint ii= 0; ii<4; ii++) { _cornerPinShape[ii]= NULL; _cornerObsShape[ii]= NULL; } _pool= qPinPool; //_pool->setDbg(1); _pinBoxPool= boxPool; } Ath__box* Ath__qPinTable::getHeadStraightPinShape(uint dir) { return _straightPinShape[dir]; } Ath__box* Ath__qPinTable::getHeadNextPinShape(uint dir) { return _nextPinShape[dir]; } Ath__box* Ath__qPinTable::getHeadCornerPinShape(uint type) { return _cornerPinShape[type]; } Ath__box* Ath__qPinTable::getHeadCornerObsShape(uint type) { return _cornerObsShape[type]; } Ath__box* Ath__qPinTable::getHeadObsShape(uint dir) { return _thruObsShape[dir]; } void Ath__qPinTable::freeBoxes(Ath__box *head) { Ath__box *e= head; while (e!=NULL) { Ath__box *f= e->_next; _pinBoxPool->free(e); e= f; } } void Ath__qPinTable::freeNextPinShapes() { freeBoxes(_nextPinShape[0]); freeBoxes(_nextPinShape[1]); _nextPinShape[0]= NULL; _nextPinShape[1]= NULL; } Ath__box* Ath__qPinTable::newPinBox(uint layer, int x1, int y1, int x2, int y2) { uint n; Ath__box *a= _pinBoxPool->alloc(NULL, &n); a->set(x1, y1, x2, y2); a->_id= n; a->_layer= layer; return a; } Ath__box* Ath__qPinTable::addPinBox(Ath__box *e, Ath__box *head) { e->_next= head; return e; } Ath__box* Ath__qPinTable::addNextPinBox(uint pinId, uint dir, uint layer, int x1, int y1, int x2, int y2) { Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2); bbPin->setIdentity(Ath_box__pin, pinId, Ath_hier__tile); _nextPinShape[dir]= addPinBox(bbPin, _nextPinShape[dir]); return bbPin; } Ath__box* Ath__qPinTable::addThruObsBox(uint netId, uint dir, uint layer, int x1, int y1, int x2, int y2) { Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2); bbPin->setIdentity(Ath_box__bus, netId, Ath_hier__tile); _thruObsShape[dir]= addPinBox(bbPin, _thruObsShape[dir]); return _thruObsShape[dir]; } Ath__box* Ath__qPinTable::addCornerPinBox(uint pinId, uint type, uint layer, int x1, int y1, int x2, int y2) { Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2); bbPin->setIdentity(Ath_box__pin, pinId, Ath_hier__tile); _cornerPinShape[type]= addPinBox(bbPin, _cornerPinShape[type]); return _cornerPinShape[type]; } Ath__box* Ath__qPinTable::addCornerObsBox(uint netId, uint type, uint layer, int x1, int y1, int x2, int y2) { Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2); bbPin->setIdentity(Ath_box__bus, netId, Ath_hier__tile); _cornerObsShape[type]= addPinBox(bbPin, _cornerObsShape[type]); return bbPin; } Ath__box* Ath__qPinTable::addStraightPinBox(uint pinId, uint dir, uint layer, int x1, int y1, int x2, int y2) { Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2); bbPin->setIdentity(Ath_box__pin, pinId, Ath_hier__tile); _straightPinShape[dir]= addPinBox(bbPin, _straightPinShape[dir]); return bbPin; } Ath__qPinTable::~Ath__qPinTable() { for (uint jj= 0; jj<2; jj++) { freeBoxes(_nextPinShape[jj]); freeBoxes(_straightPinShape[jj]); freeBoxes(_thruObsShape[jj]); freeBoxes(_cornerPinShape[jj]); } freeBoxes(_cornerPinShape[2]); freeBoxes(_cornerPinShape[3]); } Ath__qPin* Ath__qPinTable::addPin(Ath__qPin* next, uint netId, uint ioNetId, Ath__connWord w, AthPool<Ath__qPin> *pool) { uint id; Ath__qPin* pin= _pool->alloc(NULL, &id); pin->_conn= w; pin->reset(); pin->_netId= netId; pin->_ioNetId= ioNetId; pin->_nameId= id; pin->_next= NULL; if (next!=NULL) { next->_next= pin; pin->_src= 0; } else { _table->add(pin); pin->_src= 1; } return pin; } Ath__qPin *Ath__qPinTable::getNextSrcPin_next() { Ath__qPin *srcPin; while (_table->getNext(srcPin)) { if (srcPin->_src==0) continue; int cornerFlag= srcPin->_conn.getStraight(); if (cornerFlag<0) continue; if (srcPin->_conn.getDist()>1) continue; return srcPin; } return NULL; } Ath__qPin *Ath__qPinTable::getNextSrcPin_thru() { Ath__qPin *srcPin; while (_table->getNext(srcPin)) { if (srcPin->_src==0) continue; if (srcPin->_conn.getStraight()<0) continue; if (srcPin->_conn.getDist()<2) continue; return srcPin; } return NULL; } Ath__qPin *Ath__qPinTable::getNextSrcPin_corner() { Ath__qPin *srcPin; while (_table->getNext(srcPin)) { if (srcPin->_src==0) continue; int cornerFlag= srcPin->_conn.getStraight(); if (cornerFlag>=0) continue; // if (srcPin->_conn.getDist()>1) // continue; if (srcPin->_assigned==0) continue; return srcPin; } return NULL; } Ath__qPin *Ath__qPinTable::getNextSrcPin_all() { Ath__qPin *srcPin; while (_table->getNext(srcPin)) { if (srcPin->_src==0) continue; return srcPin; } return NULL; } bool Ath__qPinTable::startIterator() { if (_table->getCnt()<=0) return false; _table->resetIterator(); return true; } uint Ath__qPinTable::getCnt() { return _table->getCnt(); } Ath__qPin *Ath__qPinTable::get(uint ii) { return _table->get(ii); } Ath__qBus::Ath__qBus(uint n) { _table= new Ath__array1D<Ath__p2pConn*>(n); } void Ath__qBus::addConn(Ath__p2pConn *conn) { _table->add(conn); } uint Ath__qBus::getCnt() { return _table->getCnt(); } Ath__p2pConn *Ath__qBus::get(uint ii) { return _table->get(ii); }
22.399776
120
0.653602
375eaa78b581f84c658ae81f2e900ae9266ba765
212
hpp
C++
archive/stan/src/stan/lang/ast/node/omni_idx_def.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
archive/stan/src/stan/lang/ast/node/omni_idx_def.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
archive/stan/src/stan/lang/ast/node/omni_idx_def.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_LANG_AST_NODE_OMNI_IDX_DEF_HPP #define STAN_LANG_AST_NODE_OMNI_IDX_DEF_HPP #include <stan/lang/ast.hpp> namespace stan { namespace lang { omni_idx::omni_idx() { } } } #endif
15.142857
44
0.707547
37614210247916dca3bae49177d706bb01b9dda6
886
cc
C++
test/unit/logging_test.cc
onedata/helpers
bf14082d5a8de384c1f126b2fa522c3b360ad500
[ "MIT" ]
1
2018-06-04T08:08:11.000Z
2018-06-04T08:08:11.000Z
test/unit/logging_test.cc
onedata/helpers
bf14082d5a8de384c1f126b2fa522c3b360ad500
[ "MIT" ]
1
2019-03-26T11:15:13.000Z
2019-03-26T11:15:13.000Z
test/unit/logging_test.cc
onedata/helpers
bf14082d5a8de384c1f126b2fa522c3b360ad500
[ "MIT" ]
1
2018-02-05T09:19:45.000Z
2018-02-05T09:19:45.000Z
/** * @file logging_test.cc * @author Bartek Kryza * @copyright (C) 2018 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "helpers/logging.h" #include "testUtils.h" #include "boost/algorithm/string.hpp" #include <gtest/gtest.h> #include <sstream> #include <string> using namespace ::testing; using namespace one; using namespace one::logging; struct LoggingTest : public ::testing::Test { LoggingTest() { } ~LoggingTest() { } void SetUp() override { } void TearDown() override { } }; std::string function2() { return one::logging::print_stacktrace(); } std::string function1() { return function2(); } TEST_F(LoggingTest, loggingStackTraceShouldWork) { auto log = function1(); ASSERT_TRUE(boost::contains(log, "function1")); ASSERT_TRUE(boost::contains(log, "function2")); }
20.604651
70
0.691874
3764cc4b84406d41e5a8ca372a2e8f204b4dfab6
1,144
cpp
C++
src/input/InputHandler.cpp
Estebanan/glSolarSystem
fd57ca572a039d57f7944cc03bced96159918dfa
[ "MIT" ]
3
2019-07-31T06:13:41.000Z
2021-04-04T15:32:40.000Z
src/input/InputHandler.cpp
MarcelIwanicki/glSolarSystem
fd57ca572a039d57f7944cc03bced96159918dfa
[ "MIT" ]
null
null
null
src/input/InputHandler.cpp
MarcelIwanicki/glSolarSystem
fd57ca572a039d57f7944cc03bced96159918dfa
[ "MIT" ]
null
null
null
#include "InputHandler.h" static constexpr unsigned int MAX_KEYS = 1024; static constexpr unsigned int MAX_MOUSEBUTTONS = 32; static bool keys[MAX_KEYS] = {false}; static bool mousebuttons[MAX_MOUSEBUTTONS] = {false}; static int mouse_x; static int mouse_y; bool InputHandler::isKeyPressed(unsigned int key) { if(key >= 0 && key < MAX_KEYS) return keys[key]; else return false; } bool InputHandler::isMouseButtonPressed(unsigned int mousebutton) { if(mousebutton >= 0 && mousebutton < MAX_MOUSEBUTTONS) return mousebuttons[mousebutton]; else return false; } void InputHandler::keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { keys[key] = action != GLFW_RELEASE; } void InputHandler::mouseButtonCallback(GLFWwindow *window, int button, int action, int mods) { mousebuttons[button] = action != GLFW_RELEASE; } void InputHandler::cursorPositionCallback(GLFWwindow *window, double xpos, double ypos) { mouse_x = xpos; mouse_y = ypos; } int InputHandler::getMouseX() { return mouse_x; } int InputHandler::getMouseY() { return mouse_y; }
24.869565
97
0.714161
37654c97f91966541fcc3b4bc85c43fe9b7165f3
2,745
cc
C++
oak/server/module_invocation.cc
satnam6502/oak
81a90bbbd357fdbb7e320fc91561edb1cd6db6a2
[ "Apache-2.0" ]
1
2021-03-28T17:26:37.000Z
2021-03-28T17:26:37.000Z
oak/server/module_invocation.cc
satnam6502/oak
81a90bbbd357fdbb7e320fc91561edb1cd6db6a2
[ "Apache-2.0" ]
null
null
null
oak/server/module_invocation.cc
satnam6502/oak
81a90bbbd357fdbb7e320fc91561edb1cd6db6a2
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 The Project Oak Authors * * 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 "oak/server/module_invocation.h" #include "asylo/util/logging.h" namespace oak { namespace { // Converts a gRPC ByteBuffer into a vector of bytes. std::vector<char> Unwrap(const grpc::ByteBuffer& buffer) { std::vector<char> bytes; std::vector<::grpc::Slice> slices; grpc::Status status = buffer.Dump(&slices); if (!status.ok()) { LOG(QFATAL) << "Could not unwrap buffer"; } for (const auto& slice : slices) { bytes.insert(bytes.end(), slice.begin(), slice.end()); } return bytes; } // Converts a vector of bytes into a gRPC ByteBuffer. const grpc::ByteBuffer Wrap(const std::vector<char>& bytes) { grpc::Slice slice(bytes.data(), bytes.size()); grpc::ByteBuffer buffer(&slice, /*nslices=*/1); return buffer; } } // namespace void ModuleInvocation::Start() { auto* callback = new std::function<void(bool)>( std::bind(&ModuleInvocation::ReadRequest, this, std::placeholders::_1)); service_->RequestCall(&context_, &stream_, queue_, queue_, callback); } void ModuleInvocation::ReadRequest(bool ok) { if (!ok) { delete this; return; } auto* callback = new std::function<void(bool)>( std::bind(&ModuleInvocation::ProcessRequest, this, std::placeholders::_1)); stream_.Read(&request_, callback); } void ModuleInvocation::ProcessRequest(bool ok) { if (!ok) { delete this; return; } std::vector<char> request_data = Unwrap(request_); std::vector<char> response_data; grpc::Status status = node_->ProcessModuleInvocation(&context_, request_data, &response_data); // Restarts the gRPC flow with a new ModuleInvocation object for the next request // after processing this request. This ensures that processing is serialized. auto* request = new ModuleInvocation(service_, queue_, node_); request->Start(); response_ = Wrap(response_data); grpc::WriteOptions options; auto* callback = new std::function<void(bool)>( std::bind(&ModuleInvocation::Finish, this, std::placeholders::_1)); stream_.WriteAndFinish(response_, options, status, callback); } void ModuleInvocation::Finish(bool ok) { delete this; } } // namespace oak
31.551724
96
0.708197
3766f6f9125d4549e0161570c5f138a8acec49e9
1,991
cpp
C++
fluffy/core/src/api/modules.cpp
Lo-X/fluffy
24acf297ca81c611053fd4f55ea0988d65e84168
[ "WTFPL" ]
3
2015-12-27T14:42:53.000Z
2018-04-18T07:28:05.000Z
fluffy/core/src/api/modules.cpp
lazybobcat/fluffy
24acf297ca81c611053fd4f55ea0988d65e84168
[ "WTFPL" ]
3
2018-04-27T14:26:29.000Z
2021-01-29T16:28:18.000Z
fluffy/core/src/api/modules.cpp
lazybobcat/fluffy
24acf297ca81c611053fd4f55ea0988d65e84168
[ "WTFPL" ]
null
null
null
#include <fluffy/api/context.hpp> #include <fluffy/api/modules.hpp> #include <fluffy/graphics/shader.hpp> #include <fluffy/graphics/texture.hpp> #include <fluffy/input/input.hpp> #include <fluffy/resources/resource_library.hpp> using namespace Fluffy; void ModuleRegistry::registerModule(BaseModule* module) { ModuleType type = module->getType(); auto it = mRegistry.find(type); if (it != mRegistry.end()) { FLUFFY_LOG_WARN("Module '{}' of type '{}' has already been registered. Removing it.", it->second->getName(), EnumNames::ModuleType[(int)type]); delete it->second; } mRegistry[type] = module; } std::map<ModuleType, BaseModule*> ModuleRegistry::getModules() const { return mRegistry; } BaseModule* ModuleRegistry::getModule(ModuleType type) const { auto it = mRegistry.find(type); if (it != mRegistry.end()) { return it->second; } return nullptr; } /**********************************************************************************************************************/ void SystemModule::initialize(const Context& context) { mResources = CreateUnique<ResourceLibrary>(context); mResources->init<Texture2D>(); // mResources->init<Shader>(); } void SystemModule::terminate() { } ResourceLibrary& SystemModule::getResources() const { return *mResources; } /**********************************************************************************************************************/ VideoModule::VideoModule(Window::Definition&& windowDefinition) : mWindowDefinition(windowDefinition) { } void VideoModule::initialize(const Context& context) { mWindow = createWindow(mWindowDefinition); } void VideoModule::terminate() { } /**********************************************************************************************************************/ void InputModule::initialize(const Context& context) { Input::create(context.video->getWindow()); } void InputModule::terminate() { }
24.580247
151
0.575088
376853218b7f464eea1549c8f70589ea89b5519c
634
cpp
C++
test/testworker.cpp
43437/EventLoop
46a8f6d67201669e9f57a51df83263a5e5d5eddb
[ "MIT" ]
null
null
null
test/testworker.cpp
43437/EventLoop
46a8f6d67201669e9f57a51df83263a5e5d5eddb
[ "MIT" ]
null
null
null
test/testworker.cpp
43437/EventLoop
46a8f6d67201669e9f57a51df83263a5e5d5eddb
[ "MIT" ]
null
null
null
#include "testall.h" #include "cworkplace.h" #include <iostream> #include "cworkerbuilder.h" #include "cluaworker.h" namespace KOT { void TestWorker() { std::cout << "===========TestWorker==========" << std::endl; CLuaWorkerBuilder builder; builder.SetWorkerPath("../script/test/"); // builder.AddEnvPath("../script/test/?.lua"); // TestWorkerBuilder builder; CWorkPlace::GetInstance().AddWorker(builder.SetWorkerID("worker1")); CWorkPlace::GetInstance().AddWorker(builder.SetWorkerID("worker2")); CWorkPlace::GetInstance().Exec(); std::cout << "=============================" << std::endl; } }
26.416667
72
0.623028
3769d204cf627abd6b7049c46d29850bf6eade8b
3,454
cpp
C++
src/Game.cpp
Mobiletainment/Connect-Four
5627d103dc977af19447136fb1fb9f8a925d8cec
[ "MIT", "Unlicense" ]
6
2016-06-08T05:29:49.000Z
2020-05-26T14:07:01.000Z
src/Game.cpp
Mobiletainment/Connect-Four
5627d103dc977af19447136fb1fb9f8a925d8cec
[ "MIT", "Unlicense" ]
null
null
null
src/Game.cpp
Mobiletainment/Connect-Four
5627d103dc977af19447136fb1fb9f8a925d8cec
[ "MIT", "Unlicense" ]
null
null
null
#include "precomp.h" #include "Game.h" using namespace std; CL_GraphicContext *Game::gc; string Game::winner; Game::Game(CL_DisplayWindow &window) { gc = &window.get_gc(); board = &Board::GetInstance(); startMessage = new string("Press [1] to start first, or\n\n\nPress [2] to start with computer"); whichPlayer[0] = "Player White (You)"; whichPlayer[1] = "Player Black (Computer)"; } Game::~Game(){ delete player; delete computer; } void Game::Run(CL_DisplayWindow &window){ game_display_window = window; *gc = window.get_gc(); quit = false; CL_Slot slot_key_down = window.get_ic().get_keyboard().sig_key_down().connect(this, &Game::OnKeyDown); function<void(string)> callbackFunction; callbackFunction = &(Game::PlayerHasWonNotification); player = new Player(*gc, callbackFunction); player->AttachKeyboard(game_display_window); computer = new PlayerNPC(*gc,callbackFunction); sprintf_s(horizonMessage, "Horizon: %d", PlayerNPC::Horizon); //Set up font CL_FontDescription system_font_desc; system_font_desc.set_typeface_name("courier new"); CL_Font_System system_font(*gc, system_font_desc); system_font.set_font_metrics(CL_FontMetrics(7.0f)); string spacing = " "; string columnIdentifiers = "Use keys: [1] [2] [3] [4] [5] [6] [7]"; system_font.draw_text(*gc, 10, 20, *startMessage); window.flip(0); while (startMessage != nullptr) { CL_KeepAlive::process(); } char numberOfMinMaxCalls[32]; numberOfMinMaxCalls[0] = '\0'; while (!quit) { gc->clear(CL_Colorf(20, 56, 108)); int currentPlayer = board->Turn % 2; if (currentPlayer == 0) system_font.draw_text(*gc, 10, 20, "Current Turn: " + whichPlayer[0]); else system_font.draw_text(*gc, 10, 20, "Current Turn: " + whichPlayer[1]); //Draw column numbers system_font.draw_text(*gc, 10, 120, columnIdentifiers); board->Draw(*gc); system_font.draw_text(*gc, 350, 50, numberOfMinMaxCalls); system_font.draw_text(*gc, 410, 80, horizonMessage); if(!winner.empty()) { system_font.draw_text(*gc, 10, 60, winner); } window.flip(0); CL_KeepAlive::process(); if (currentPlayer == 0) player->WaitForTurn(); else { int minMaxCalls = computer->WaitForTurn(); sprintf_s(numberOfMinMaxCalls, "#MinMaxCalls: %d", minMaxCalls); } } } string Game::GetActivePlayerName(Player *playerKI) { if(playerKI->PlayerIdentifier() == 'o') { return "Black Player"; } else return "White Player"; } void Game::PlayerHasWonNotification(string whosTheWinner) { if (winner.empty()) //only assign winner the first time a winner is determined winner = whosTheWinner; } void Game::OnKeyDown(const CL_InputEvent &key, const CL_InputState &state) { if (key.id == CL_KEY_ESCAPE) quit = true; else if (startMessage != nullptr && key.id == CL_KEY_1) { board->Turn = 0; //player 1 makes all even turns, computer all odd delete startMessage; startMessage = nullptr; } else if (startMessage != nullptr && key.id == CL_KEY_2) { board->Turn = 1; //cheap trick to start with computer instead of player delete startMessage; startMessage = nullptr; } else if (key.id == CL_KEY_UP) { if (PlayerNPC::Horizon < 42) { PlayerNPC::Horizon += 1; sprintf_s(horizonMessage, "Horizon: %d", PlayerNPC::Horizon); } } else if (key.id == CL_KEY_DOWN) { if (PlayerNPC::Horizon > 0) { PlayerNPC::Horizon -= 1; sprintf_s(horizonMessage, "Horizon: %d", PlayerNPC::Horizon); } } }
24.671429
103
0.690214
3769fa67cbbf10f4f4b80414b2bc8a4a39fb5aed
6,302
cpp
C++
libace/filesystem/Path.cpp
xguerin/ace
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
[ "MIT" ]
5
2016-06-14T17:56:47.000Z
2022-02-10T19:54:25.000Z
libace/filesystem/Path.cpp
xguerin/ace
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
[ "MIT" ]
42
2016-06-21T20:48:22.000Z
2021-03-23T15:20:51.000Z
libace/filesystem/Path.cpp
xguerin/ace
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
[ "MIT" ]
1
2016-10-02T02:58:49.000Z
2016-10-02T02:58:49.000Z
/** * Copyright (c) 2016 Xavier R. Guerin * * 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 <ace/filesystem/Path.h> #include <ace/common/String.h> #include <sstream> #include <string> #include <vector> namespace ace { namespace fs { Path::Path(std::string const& v, bool enforceDir) : Path() { std::vector<std::string> elems; common::String::split(v, '/', elems); for (size_t i = 0; i < elems.size(); i += 1) { if (not elems[i].empty() || (elems[i].empty() && (i == 0 or i == elems.size() - 1))) { m_elements.push_back(elems[i]); } } if (not isDirectory() and enforceDir) { m_elements.push_back(std::string()); } } Path::Path(std::vector<std::string> const& c) : m_elements(c) {} Path Path::operator-(Path const& o) const { if (m_elements.empty()) { return Path(); } if (o.empty()) { return Path(*this); } std::vector<std::string> vals; auto ita = m_elements.begin(); auto itb = o.m_elements.begin(); while (ita != m_elements.end() and itb != o.m_elements.end()) { if (*ita != *itb) { break; } ita++, itb++; } if (ita == m_elements.end() || (itb != o.m_elements.end() && not itb->empty())) { return Path(); } while (ita != m_elements.end()) { vals.push_back(*ita++); } return Path(vals); } Path Path::operator/(Path const& o) const { if (o.isAbsolute()) { return Path(); } if (m_elements.empty() or not isDirectory()) { return Path(); } std::vector<std::string> elems(m_elements); elems.erase(--elems.end()); for (auto& e : o.m_elements) { elems.push_back(e); } return Path(elems); } std::string Path::toString() const { std::ostringstream oss; oss << *this; return oss.str(); } Path Path::prune() const { std::vector<std::string> elems(m_elements); if (not elems.empty()) { if ((--elems.end())->empty()) { elems.erase(--elems.end()); } elems.erase(--elems.end()); if (not elems.empty()) { elems.push_back(""); } } return Path(elems); } Path Path::compress() const { std::vector<std::string> elems; for (auto& e : m_elements) { if (e == ".") { continue; } elems.push_back(e); } return Path(elems); } bool Path::isAbsolute() const { if (m_elements.empty()) { return false; } return (*m_elements.begin()).empty(); } bool Path::isDirectory() const { if (m_elements.empty()) { return false; } return (*m_elements.rbegin()).empty(); } std::string Path::prefix(std::string const& a, std::string const& b) { Path pa(a), pb(b); return prefix(pa, pb).toString(); } Path Path::prefix(Path const& a, Path const& b) { std::vector<std::string> vals; if (a.empty() or b.empty()) { return Path(); } auto ita = a.begin(); auto itb = b.begin(); while (ita != a.end() and itb != b.end()) { if (*ita != *itb) { break; } vals.push_back(*ita); ita++, itb++; } if (ita == a.end() and itb == b.end()) { return Path(vals); } else if (ita != a.end() and itb != b.end()) { vals.push_back(std::string()); return Path(vals); } else if ((ita != a.end() and itb == b.end()) || (ita == a.end() and itb != b.end())) { if (not vals.empty()) { vals.erase(--vals.end()); vals.push_back(std::string()); return Path(vals); } } return Path(); } std::ostream& operator<<(std::ostream& o, Path const& p) { for (size_t i = 0; i < p.m_elements.size(); i += 1) { o << p.m_elements[i]; if (i < p.m_elements.size() - 1) { o << "/"; } } return o; } bool Path::operator==(Path const& o) const { return m_elements == o.m_elements; } bool Path::operator!=(Path const& o) const { return m_elements != o.m_elements; } bool Path::empty() const { return m_elements.empty(); } Path::iterator Path::begin() { return m_elements.begin(); } Path::const_iterator Path::begin() const { return m_elements.begin(); } Path::iterator Path::end() { return m_elements.end(); } Path::const_iterator Path::end() const { return m_elements.end(); } Path::reverse_iterator Path::rbegin() { return m_elements.rbegin(); } Path::const_reverse_iterator Path::rbegin() const { return m_elements.rbegin(); } Path::reverse_iterator Path::rend() { return m_elements.rend(); } Path::const_reverse_iterator Path::rend() const { return m_elements.rend(); } Path::iterator Path::up(iterator const& i) { Path::iterator n(i); return --n; } Path::const_iterator Path::up(const_iterator const& i) const { Path::const_iterator n(i); return --n; } Path::iterator Path::down(iterator const& i) { Path::iterator n(i); return ++n; } Path::const_iterator Path::down(const_iterator const& i) const { Path::const_iterator n(i); return ++n; } Path::reverse_iterator Path::up(reverse_iterator const& i) { Path::reverse_iterator n(i); return ++n; } Path::const_reverse_iterator Path::up(const_reverse_iterator const& i) const { Path::const_reverse_iterator n(i); return ++n; } Path::reverse_iterator Path::down(reverse_iterator const& i) { Path::reverse_iterator n(i); return --n; } Path::const_reverse_iterator Path::down(const_reverse_iterator const& i) const { Path::const_reverse_iterator n(i); return --n; } }}
19.571429
80
0.631387
376a7ab1b23739b7e20d45adf6fb0641e9c95b0f
2,616
hpp
C++
Axis.CommonLibrary/domain/analyses/ReducedNumericalModel.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.CommonLibrary/domain/analyses/ReducedNumericalModel.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.CommonLibrary/domain/analyses/ReducedNumericalModel.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#pragma once #include "foundation/axis.SystemBase.hpp" #include "domain/fwd/numerical_model.hpp" #include "foundation/memory/RelativePointer.hpp" #include "Foundation/Axis.CommonLibrary.hpp" namespace axis { namespace domain { namespace analyses { class ModelOperatorFacade; /** * Implements a version of the numerical model with reduced functionality, * so that it can be used with external processing devices. **/ class AXISCOMMONLIBRARY_API ReducedNumericalModel { public: ReducedNumericalModel(NumericalModel& sourceModel, ModelOperatorFacade& op); ~ReducedNumericalModel(void); const ModelDynamics& Dynamics(void) const; ModelDynamics& Dynamics(void); const ModelKinematics& Kinematics(void) const; ModelKinematics& Kinematics(void); size_type GetElementCount(void) const; size_type GetNodeCount(void) const; const axis::domain::elements::FiniteElement& GetElement(size_type index) const; axis::domain::elements::FiniteElement& GetElement(size_type index); const axis::foundation::memory::RelativePointer GetElementPointer(size_type index) const; axis::foundation::memory::RelativePointer GetElementPointer(size_type index); const axis::domain::elements::Node& GetNode(size_type index) const; axis::domain::elements::Node& GetNode(size_type index); const axis::foundation::memory::RelativePointer GetNodePointer(size_type index) const; axis::foundation::memory::RelativePointer GetNodePointer(size_type index); ModelOperatorFacade& GetOperator(void); /** * Creates a facade with reduced functionality that operates on components of an existing * numerical model. * * @param [in,out] sourceModel Source numerical model. * @param [in,out] op The object which provides an interface to external processing * using this model. * * @return A pointer to the reduced numerical model, located in model memory. **/ static axis::foundation::memory::RelativePointer Create(NumericalModel& sourceModel, ModelOperatorFacade& op); private: void *operator new (size_t, void *ptr); void operator delete(void *, void *); ModelOperatorFacade *operator_; axis::foundation::memory::RelativePointer nodeArrayPtr_; axis::foundation::memory::RelativePointer elementArrayPtr_; axis::foundation::memory::RelativePointer outputBucketArrayPtr_; size_type elementCount_; size_type nodeCount_; axis::foundation::memory::RelativePointer kinematics_; axis::foundation::memory::RelativePointer dynamics_; }; } } } // namespace axis::domain::analyses
40.875
96
0.748853
376d29ea569b01e2b5a72774aafbc174d75b438a
2,426
cpp
C++
third_party/WebKit/Source/core/css/cssom/CSSNumericValue.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/css/cssom/CSSNumericValue.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/css/cssom/CSSNumericValue.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium 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 "core/css/cssom/CSSNumericValue.h" #include "bindings/core/v8/ExceptionState.h" #include "core/css/CSSPrimitiveValue.h" #include "core/css/cssom/CSSUnitValue.h" namespace blink { bool CSSNumericValue::IsValidUnit(CSSPrimitiveValue::UnitType unit) { // UserUnits returns true for CSSPrimitiveValue::IsLength below. if (unit == CSSPrimitiveValue::UnitType::kUserUnits) return false; if (unit == CSSPrimitiveValue::UnitType::kNumber || unit == CSSPrimitiveValue::UnitType::kPercentage || CSSPrimitiveValue::IsLength(unit) || CSSPrimitiveValue::IsAngle(unit) || CSSPrimitiveValue::IsTime(unit) || CSSPrimitiveValue::IsFrequency(unit) || CSSPrimitiveValue::IsResolution(unit) || CSSPrimitiveValue::IsFlex(unit)) return true; return false; } CSSPrimitiveValue::UnitType CSSNumericValue::UnitFromName(const String& name) { if (EqualIgnoringASCIICase(name, "number")) return CSSPrimitiveValue::UnitType::kNumber; if (EqualIgnoringASCIICase(name, "percent") || name == "%") return CSSPrimitiveValue::UnitType::kPercentage; return CSSPrimitiveValue::StringToUnitType(name); } CSSNumericValue* CSSNumericValue::parse(const String& css_text, ExceptionState&) { // TODO(meade): Implement return nullptr; } CSSNumericValue* CSSNumericValue::FromCSSValue(const CSSPrimitiveValue& value) { if (value.IsCalculated()) { // TODO(meade): Implement this case. return nullptr; } return CSSUnitValue::FromCSSValue(value); } CSSNumericValue* CSSNumericValue::to(const String& unit_string, ExceptionState& exception_state) { CSSPrimitiveValue::UnitType unit = UnitFromName(unit_string); if (!IsValidUnit(unit)) { exception_state.ThrowDOMException(kSyntaxError, "Invalid unit for conversion"); return nullptr; } if (IsCalculated()) { exception_state.ThrowTypeError( "Conversion of CSSCalcValue is not supported yet"); return nullptr; } CSSUnitValue* result = ToCSSUnitValue(this)->to(unit); if (!result) { exception_state.ThrowTypeError("Incompatible units for conversion"); return nullptr; } return result; } } // namespace blink
34.657143
80
0.706925
3770ca1dd46873dd38256f23ab25bafeb9f6febb
37,357
cpp
C++
TommyGun/FrameWork/fMain.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
34
2017-05-08T18:39:13.000Z
2022-02-13T05:05:33.000Z
TommyGun/FrameWork/fMain.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
null
null
null
TommyGun/FrameWork/fMain.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
6
2017-05-27T01:14:20.000Z
2020-01-20T14:54:30.000Z
/*--------------------------------------------------------------------------- (c) 2004 Scorpio Software 19 Wittama Drive Glenmore Park Sydney NSW 2745 Australia ----------------------------------------------------------------------------- $Workfile:: $ $Revision:: $ $Date:: $ $Author:: $ ---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop //--------------------------------------------------------------------------- #include "..\SafeMacros.h" #include "..\Logging\MessageLogger.h" //--------------------------------------------------------------------------- #include <shfolder.h> //--------------------------------------------------------------------------- #include "FrameWorkInterface.h" #include "ZXLogFile.h" #include "ZXPluginManager.h" #include "ZXProjectManager.h" #include "ZXGuiManager.h" #include "fMain.h" #include "fAbout.h" #include "fRenameProject.h" #include "fCopyProject.h" //-- PRAGMA'S --------------------------------------------------------------- #pragma package(smart_init) #pragma link "KRegistry" #pragma link "pngimage" #pragma resource "*.dfm" //--------------------------------------------------------------------------- using namespace Scorpio; using namespace GUI; using namespace Logging; using namespace Interface; using namespace Plugin; using namespace Project; //--------------------------------------------------------------------------- TMRUProjectsVector g_mruList; const TColor g_Colors[] = { clRed, clYellow, clLime, clAqua }; //--------------------------------------------------------------------------- // Constructor /** * Initializes the main form * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- __fastcall TfrmMain::TfrmMain(TComponent* Owner) : TForm(Owner), m_bClosing(false), m_iTopOfButtons(8) { RL_METHOD } //--------------------------------------------------------------------------- // Denstructor /** * Checks all allocate memory is freed * @author Tony Thompson * @date Created 23 April 2005 */ //--------------------------------------------------------------------------- __fastcall TfrmMain::~TfrmMain() { if (NULL != frmAbout) { ZX_LOG_ERROR(lfGeneral, "frmAbout is not freed"); } if (0 != m_SwitcherButtons.size()) { ZX_LOG_ERROR(lfGeneral, "Not all the Switcher Buttons have been freed"); } } //--------------------------------------------------------------------------- // FormCreate /** * Event handler for the when the form is created * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormCreate(TObject *Sender) { RL_METHOD PROTECT_BEGIN RestoreStates(); panTitle->DoubleBuffered = true; // panMRUList->DoubleBuffered = true; panPluginButtons->DoubleBuffered = true; GetLocation(); GetMachines(); UpdateGUI(); edtNewProjectLocation->Text = GetMyDocumentsFolder() + "\\TommyGun\\"; //pgcPlugins->DoubleBuffered = true; Registration(); PROTECT_END } //--------------------------------------------------------------------------- // FormActivate /** * Repositions the form when it is activate (only once though) * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormActivate(TObject *Sender) { RL_METHOD PROTECT_BEGIN static bool bRepositioned = false; if (false == bRepositioned) { bRepositioned = true; int iValue = 0; bool bState = false; if (regScorpio->Read("States", "Top" , iValue)) Top = iValue; if (regScorpio->Read("States", "Left" , iValue)) Left = iValue; if (regScorpio->Read("States", "Maximized" , bState) && bState) WindowState = wsMaximized; } FormResize(NULL); PROTECT_END } //--------------------------------------------------------------------------- // FormCloseQuery /** * Queries the form to see if its OK to close * @param Sender the VCL object that called the method * @param CanClose true if canclose, false if not * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormCloseQuery(TObject *Sender, bool &CanClose) { RL_METHOD PROTECT_BEGIN CanClose = false; if (S_OK == g_PluginManager.Notify(g_PluginManager.Handle, TZX_VERB_NEW, NULL, 0, 0)) { // notify of closing g_PluginManager.Notify(g_PluginManager.Handle, TZX_VERB_EXIT, NULL, 0, 0); m_bClosing = true; // can close application CanClose = true; } PROTECT_END } //--------------------------------------------------------------------------- // FormClose /** * Event handler for the when the form is created * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormClose(TObject *Sender, TCloseAction &Action) { RL_METHOD PROTECT_BEGIN if (WindowState != wsMaximized) { regScorpio->Write("States", "Top" , Top ); regScorpio->Write("States", "Left" , Left ); regScorpio->Write("States", "Width" , Width ); regScorpio->Write("States", "Height" , Height ); } regScorpio->Write("States", "Maximized" , WindowState == wsMaximized); PROTECT_END } //--------------------------------------------------------------------------- // FormResize /** * Event handler for the when the form is resized * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormResize(TObject *Sender) { stsStatus->Panels->Items[0]->Width = stsStatus->ClientWidth - 260 - stsStatus->Panels->Items[1]->Width; stsStatus->Update(); if (pgcPlugins->Width != panPageContainer->Width + 8) { pgcPlugins->Width = panPageContainer->Width + 8; pgcPlugins->Left = -4; } if (pgcPlugins->Height!= panPageContainer->Height + 9) { pgcPlugins->Height = panPageContainer->Height + 9; pgcPlugins->Top = -8; } pgcPlugins->Update(); } //--------------------------------------------------------------------------- // appEventsException /** * Event handler for when an exception occurs * @param Sender the vcl object that caused the event * @param E the exception object * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::appEventsException(TObject *Sender, Exception *E) { RL_METHOD ZXPlugin* Plugin = g_PluginManager.CheckException(); if (true == SAFE_PTR(Plugin)) { m_MessageBox.ShowExceptionMessage(Plugin->Description, Plugin->Vendor, (DWORD)Plugin->ModuleAddress, (DWORD)ExceptAddr(), E->Message, true); Plugin->Unload(); } else { if (0 < g_Exceptions.size()) { for (unsigned int i = 0; i < g_Exceptions.size(); ++i) { m_MessageBox.ShowExceptionMessage(g_Exceptions[i].sMessage, g_Exceptions[i].sFile, g_Exceptions[i].sFunc, g_Exceptions[i].iLine); } g_Exceptions.clear(); } else { m_MessageBox.ShowExceptionMessage(E->Message, __FILE__, __FUNC__, __LINE__); } } } //--------------------------------------------------------------------------- // appEventsHint /** * Event handler for when a hint occurs * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::appEventsHint(TObject *Sender) { stsStatus->Panels->Items[0]->Text = Application->Hint; } //--------------------------------------------------------------------------- // mnuHelpAboutClick /** * Event handler for the about menu * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::mnuHelpAboutClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN frmAbout = new TfrmAbout(Application); frmAbout->Execute(); SAFE_DELETE(frmAbout); PROTECT_END } //--------------------------------------------------------------------------- // mnuViewPluginSwitcherClick /** * Toggles the visibility of the plugin switcher * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::mnuViewPluginSwitcherClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN mnuViewPluginSwitcher->Checked = !mnuViewPluginSwitcher->Checked; panPluginSwitcher->Visible = mnuViewPluginSwitcher->Checked; regScorpio->Write("States", "Switcher", mnuViewPluginSwitcher->Checked); PROTECT_END } //--------------------------------------------------------------------------- // mnuViewStandardClick /** * Toggles the visibility of the standard toolbar * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::mnuViewStandardClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN mnuViewStandard->Checked = !mnuViewStandard->Checked; //tbrStandard->Visible = mnuViewStandard->Checked; panToolbars->Visible = mnuViewStandard->Checked; regScorpio->Write("States", "Standard", mnuViewStandard->Checked); PROTECT_END } //--------------------------------------------------------------------------- // spdPluginsUpClick /** * Scrolls the plugin buttons down into view within the browser * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::spdPluginsUpClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN panPluginButtons->Top = std::min(0, panPluginButtons->Top + 76); PROTECT_END } //--------------------------------------------------------------------------- // spdPluginsDownClick /** * Scrolls the plugin buttons up into view within the browser * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::spdPluginsDownClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN panPluginButtons->Height = std::max(m_iTopOfButtons, panPluginButtonsContainer->Height); panPluginButtons->Top = std::min(0, std::max(panPluginButtonsContainer->Height - m_iTopOfButtons + 64, panPluginButtons->Top - 76)); PROTECT_END } //--------------------------------------------------------------------------- // panPluginButtonsContainerResize /** * Resizes the plugin browser panels * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::panPluginButtonsContainerResize(TObject *Sender) { RL_METHOD PROTECT_BEGIN panPluginButtons->Height = std::max(m_iTopOfButtons, panPluginButtonsContainer->Height); panPluginButtons->Top = 0; PROTECT_END } //--------------------------------------------------------------------------- // actSwitch01Execute /** * Switches to plugin using the Ctrl+Fn keys * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::actSwitch01Execute(TObject *Sender) { RL_METHOD PROTECT_BEGIN int iPluginIndex = ((TAction*)Sender)->Tag; if (0 <= iPluginIndex && iPluginIndex < (int)m_SwitcherButtons.size()) { PostNotifyEvent(m_SwitcherButtons[iPluginIndex].PluginHandle, TZX_VERB_SWITCH_PLUGIN, NULL, 0, 0); UpdateGUI(); } PROTECT_END } //--------------------------------------------------------------------------- // OnPluginButtonClick /** * Event handler for when a plugin buttons is pressed * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::OnPluginButtonClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN //ClearStatusSlots(); //pgcPlugins->ActivePageIndex = ((TComponent*)Sender)->Tag; PostNotifyEvent(m_SwitcherButtons[((TComponent*)Sender)->Tag].PluginHandle, TZX_VERB_SWITCH_PLUGIN, NULL, 0, 0); UpdateGUI(); PROTECT_END } //--------------------------------------------------------------------------- // RestoreStates /** * Restores the states of some form objects * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::RestoreStates(void) { RL_METHOD PROTECT_BEGIN bool bState = true; int iValue = 0; regScorpio->Read("States", "Switcher" , bState); if (bState) mnuViewPluginSwitcherClick(NULL); if (regScorpio->Read("States", "Standard" , bState) && false == bState) mnuViewStandardClick(NULL); if (regScorpio->Read("States", "Width" , iValue) && false == bState) Width = iValue; if (regScorpio->Read("States", "Height" , iValue) && false == bState) Height = iValue; PROTECT_END } //--------------------------------------------------------------------------- void __fastcall TfrmMain::mnuViewOptionsClick(TObject *Sender) { PROTECT_BEGIN g_GuiManager.OptionsShow(); tbrStandard->AutoSize = false; tbrStandard->AutoSize = true; String sFolder; if (regScorpio->Read("ProjectFolder", sFolder)) { edtNewProjectLocation->Text = sFolder; } PROTECT_END } //--------------------------------------------------------------------------- void __fastcall TfrmMain::UpdateOptions(void) { bool bValue = true; regScorpio->Read("ShowPluginIcons", bValue); stsStatus->Panels->Items[1]->Width = bValue ? 200 : 0; FormResize(NULL); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::AddSwitcherButton(TZX_HPLUGIN PluginHandle, const String& sCaption) { TSwitcherButton Button; Button.PluginHandle = PluginHandle; Button.IconButton = new KIconButton(NULL); Button.IconButton->Name = "Button" + IntToStr(PluginHandle); Button.IconButton->Caption = sCaption; Button.IconButton->Parent = panPluginButtons; Button.IconButton->Left = 4; Button.IconButton->Top = 8 + (m_SwitcherButtons.size() * 76); Button.IconButton->Height = 68; Button.IconButton->Width = 68; Button.IconButton->Tag = m_SwitcherButtons.size(); Button.IconButton->IconsCold = imgLarge; Button.IconButton->IconsHot = imgLarge; Button.IconButton->IconIndex = -1; Button.IconButton->Grouped = true; Button.IconButton->ColorHighlight = (TColor)0x00F6E8E0;//clInfoBk; Button.IconButton->ColorSelected = (TColor)0x00EED2C1;//clWhite; Button.IconButton->Color = (TColor)0x00846142;//panPluginButtons->Color; //clBtnFace; Button.IconButton->ColorBorder = (TColor)0x00846142; Button.IconButton->ColorBackground = panPluginButtons->Color; //Button.IconButton->Color = clBtnShadow; //Button.IconButton->ColorBorderSelected = clWhite; //Button.IconButton->ColorHighlight = 0x00F6E8E0; //Button.IconButton->ColorSelected = 0x00EED2C1; Button.IconButton->Font->Name = "Octin Stencil Rg"; Button.IconButton->Font->Size = 8; Button.IconButton->CornerWidth = 10; Button.IconButton->CornerHeight = 10; Button.IconButton->OnClick = OnPluginButtonClick; m_SwitcherButtons.push_back(Button); m_SwitcherButtons[0].IconButton->Selected = true; m_iTopOfButtons = 4 + ((m_SwitcherButtons.size()) * 84); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::RemoveSwitcherButton(TZX_HPLUGIN PluginHandle) { // remove the button TSwitcherButtonIterator it = m_SwitcherButtons.begin(); for (it = m_SwitcherButtons.begin(); it != m_SwitcherButtons.end(); it++) { if ((*it).PluginHandle == PluginHandle) { SAFE_DELETE((*it).IconButton); //SAFE_DELETE((*it).Panel); m_SwitcherButtons.erase(it); break; } } // reposition the remaining buttons for (unsigned int i = 0; i < m_SwitcherButtons.size(); ++i) { m_SwitcherButtons[i].IconButton->Top = 4 + (i * 84); m_SwitcherButtons[i].IconButton->Tag = i; } // resize the panel m_iTopOfButtons = 4 + (m_SwitcherButtons.size() * 84); panPluginButtons->Height = std::max(m_iTopOfButtons, panPluginButtonsContainer->Height); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::SetSwitcherBitmap(TZX_HPLUGIN PluginHandle, TImage* Image) { TSwitcherButtonIterator it = m_SwitcherButtons.begin(); for (it = m_SwitcherButtons.begin(); it != m_SwitcherButtons.end(); it++) { if ((*it).PluginHandle == PluginHandle) { int iIndex = imgLarge->AddMasked(Image->Picture->Bitmap, Image->Picture->Bitmap->Canvas->Pixels[0][0]); (*it).IconButton->IconIndex = iIndex; } } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::ClearStatusSlots(void) { // clear the status bar slots for the next plugin stsStatus->Panels->Items[2]->Text = ""; stsStatus->Panels->Items[3]->Text = ""; stsStatus->Panels->Items[4]->Text = ""; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFileNewProjectExecute(TObject *Sender) { if (g_ProjectManager.Close()) { ActiveControl = edtNewProjectName; } FillProjectList(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFileOpenProjectAccept(TObject *Sender) { g_ProjectManager.Load(actFileOpenProject->Dialog->FileName); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFileSaveProjectExecute(TObject *Sender) { g_ProjectManager.Save(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFileCloseProjectExecute(TObject *Sender) { g_ProjectManager.Close(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::SwitchToPlugin(TZX_HPLUGIN PluginHandle) { int iPluginIndex = -1; for (int i = 0; i < (int)m_SwitcherButtons.size(); i++) { if (m_SwitcherButtons[i].PluginHandle == PluginHandle) { iPluginIndex = i; break; } } if (0 <= iPluginIndex && iPluginIndex < pgcPlugins->PageCount) { ClearStatusSlots(); m_SwitcherButtons[iPluginIndex].IconButton->Selected = true; pgcPlugins->ActivePageIndex = iPluginIndex; UpdateGUI(); } } //--------------------------------------------------------------------------- AnsiString __fastcall TfrmMain::GetMyDocumentsFolder() { CHAR my_documents[MAX_PATH]; HRESULT result = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, my_documents); if (SUCCEEDED(result)) { AnsiString folder = AnsiString(my_documents); AnsiString myDocFolder = StringReplace(folder, "Documents", "My Documents", TReplaceFlags() << rfReplaceAll); if (DirectoryExists(folder)) { return folder; } if (DirectoryExists(myDocFolder)) { return myDocFolder; } } return ""; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::cmdOpenProjectClick(TObject *Sender) { if (DirectoryExists(edtNewProjectLocation->Text)) { actFileOpenProject->Dialog->InitialDir = edtNewProjectLocation->Text; } else { actFileOpenProject->Dialog->InitialDir = GetMyDocumentsFolder() + "\\TommyGun\\"; } actFileOpenProject->Execute(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::edtNewProjectNameChange(TObject *Sender) { lblMessage->Visible = false; UpdateOk(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::cmdCreateProjectClick(TObject *Sender) { String sBaseFolder = edtNewProjectLocation->Text; if (sBaseFolder[sBaseFolder.Length()] != '\\') { sBaseFolder += "\\"; } String sProjectFolder = sBaseFolder + edtNewProjectName->Text + "\\"; if (ForceDirectories(sBaseFolder)) { regScorpio->Write("Plugins", "MachineFolder", cmbNewProjectMachine->Text); regScorpio->Write("ProjectFolder", sBaseFolder); String sProjectFile = sProjectFolder + "project.xml" ; //sProjectFile = ChangeFileExt(sProjectFile, ".xml"); if (false == DirectoryExists(sProjectFolder)) { if (ForceDirectories(sProjectFolder)) { // add the file name to the projects list g_ProjectManager.New(sProjectFile, cmbNewProjectMachine->Text); } else { lblMessage->Caption = "Location is not valid please select a new Location"; lblMessage->Visible = true; } } else { lblMessage->Caption = "A Project file with that Name already exists at the Location"; lblMessage->Visible = true; } } else { lblMessage->Caption = "Location is not valid please select a new Location"; lblMessage->Visible = true; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::UpdateOk(void) { cmdCreateProject->Enabled = !edtNewProjectName->Text.Trim().IsEmpty() && !edtNewProjectLocation->Text.Trim().IsEmpty() && -1 != cmbNewProjectMachine->ItemIndex; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::GetMachines(void) { cmbNewProjectMachine->Items->Clear(); // read the registry setting and set it to the appropreiate folder String sRegFolder; regScorpio->Read("Plugins", "MachineFolder", sRegFolder); cmbNewProjectMachine->Clear(); cmbNewProjectMachine->ItemIndex = -1; String sPluginsFolder = ExtractFilePath(Application->ExeName) + "Plugins\\_*"; // find the machine specific plugin folders TSearchRec sr; if (0 == FindFirst(sPluginsFolder, faAnyFile, sr)) { do { if ((sr.Attr & faDirectory) == faDirectory) { String sFolder = sr.Name.SubString(2, sr.Name.Length()); cmbNewProjectMachine->Items->Add(sFolder); if (sFolder.LowerCase() == sRegFolder.LowerCase()) { cmbNewProjectMachine->ItemIndex = cmbNewProjectMachine->Items->Count - 1; } } } while(0 == FindNext(sr)); FindClose(sr); } if (cmbNewProjectMachine->ItemIndex == -1 && cmbNewProjectMachine->Items->Count > 0) { cmbNewProjectMachine->ItemIndex = 0; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::GetLocation(void) { String sProjectFolder; if (regScorpio->Read("ProjectFolder", sProjectFolder)) { edtNewProjectLocation->Text = sProjectFolder; } else { edtNewProjectLocation->Text = ExtractFilePath(Application->ExeName) + "Projects\\"; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::FillProjectList(void) { lstProjects->Items->Clear(); g_ProjectManager.GetMRUList(g_mruList, true); if (g_mruList.size()) { // fill the projects list view with the time stamp sorted items for (int i = 0; i < (int)g_mruList.size(); ++i) { TListItem *item = lstProjects->Items->Add(); String sProjectFolder = ExtractFilePath(g_mruList[i].File); sProjectFolder.SetLength(sProjectFolder.Length() - 1); String sFolder = ExtractFileName(sProjectFolder); if (g_mruList[i].Exists) { item->Caption = sFolder; // set the machine name //item->SubItems->Add(g_mruList[i].Machine); item->SubItems->Add(sProjectFolder); item->ImageIndex = -1; int iDate = Now(); if ((int)g_mruList[i].TimeStamp == iDate) { item->SubItems->Add("Today"); } else if ((int)g_mruList[i].TimeStamp == iDate - 1) { item->SubItems->Add("Yesterday"); } else { item->SubItems->Add(g_mruList[i].TimeStamp.FormatString("dddddd")); } } else { item->Caption = sFolder + " (missing)"; // set the machine name item->SubItems->Add("Unknown"); item->SubItems->Add("Unknown"); } } } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsChange(TObject *Sender, TListItem *Item, TItemChange Change) { cmdProjectRemove->Visible = lstProjects->ItemIndex != -1; cmdProjectRestore->Visible = lstProjects->ItemIndex != -1; cmdProjectCopy->Visible = lstProjects->ItemIndex != -1; // load the selected file if (lstProjects->ItemIndex != -1 && lstProjects->ItemIndex < (int)g_mruList.size()) { cmdProjectRemove->Top = 47 + ((lstProjects->Selected->Index - lstProjects->TopItem->Index) * 17/*cmdProjectRemove->Height*/); cmdProjectRestore->Top = cmdProjectRemove->Top; cmdProjectCopy->Top = cmdProjectRemove->Top; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsClick(TObject *Sender) { lstProjectsChange(NULL, NULL, TItemChange()); // load the selected file if (lstProjects->ItemIndex != -1 && lstProjects->ItemIndex < (int)g_mruList.size()) { g_ProjectManager.Load(g_mruList[lstProjects->ItemIndex].File); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::cmdBrowseClick(TObject *Sender) { dlgBrowse->DefaultFolder = edtNewProjectLocation->Text; dlgBrowse->Title = "Select Project Folder"; if (dlgBrowse->Execute()) { edtNewProjectLocation->Text = dlgBrowse->FileName; } UpdateOk(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::cmdCleanMissingProjectsClick(TObject *Sender) { g_ProjectManager.GetMRUList(g_mruList, true); if (g_mruList.size()) { // fill the projects list view with the time stamp sorted items for (int i = 0; i < (int)g_mruList.size(); ++i) { String sFile = ExtractFileName(g_mruList[i].File); sFile = ChangeFileExt(sFile, ""); if (false == g_mruList[i].Exists || g_mruList[i].Machine.LowerCase() == "unknown") { regScorpio->ClearValue("MRU", IntToStr(i)); } } } FillProjectList(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFindExecute(TObject *Sender) { TAction* action = dynamic_cast<TAction*>(Sender); if (true == SAFE_PTR(action)) { // send the find message to the active plugin g_PluginManager.NotifyPlugin(TZXN_EDIT_FIND + action->Tag, NULL, 0, 0); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::UpdateGUI(void) { // query the active plugin to see what it supports and update the gui bool bEnableFind = S_QUERY_YES == g_PluginManager.NotifyPlugin(TZX_QUERY_FIND, NULL, 0, 0); actFind->Enabled = bEnableFind; actFindReplace->Enabled = bEnableFind; actFindNext->Enabled = bEnableFind; actFindPrev->Enabled = bEnableFind; mnuEditFindReplace->Enabled = bEnableFind; bool bEnableCopyCutPaste = S_QUERY_YES == g_PluginManager.NotifyPlugin(TZX_QUERY_COPYPASTE, NULL, 0, 0); actEditCopy2->Enabled = bEnableCopyCutPaste; actEditCut2->Enabled = bEnableCopyCutPaste; actEditPaste2->Enabled = bEnableCopyCutPaste; //actEditUndo->Enabled = S_QUERY_YES == g_PluginManager.NotifyPlugin(TZX_QUERY_UNDO, NULL, 0, 0); //actEditRedo->Enabled = S_QUERY_YES == g_PluginManager.NotifyPlugin(TZX_QUERY_REDO, NULL, 0, 0); //actEditUndoList->Enabled = actEditUndo->Enabled && actEditRedo->Enabled; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::pgcPluginsChange(TObject *Sender) { PostNotifyEvent(m_SwitcherButtons[pgcPlugins->ActivePageIndex].PluginHandle, TZX_VERB_SWITCH_PLUGIN, NULL, 0, 0); UpdateGUI(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actEditDeleteExecute(TObject *Sender) { bool bSendDelToControl = false; String sClass = ActiveControl->ClassName(); TCustomEdit* pEdit = dynamic_cast<TCustomEdit*>(ActiveControl); bSendDelToControl = (true == SAFE_PTR(pEdit) && true == pEdit->Enabled); if (bSendDelToControl) { SendMessage(ActiveControl->Handle, WM_KEYDOWN, VK_DELETE, 0); } else { g_PluginManager.NotifyPlugin(TZX_VERB_DELETE, NULL, 0, 0); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popRemoveProjectClick(TObject *Sender) { int iAnswer = 0; Message ( mbtError, "Remove or Delete the project?", "You can choose to Remove or Delete the project from the list", "You can choose to either just Remove the project from the list, " "Delete the project folder entirely or " "Cancel this operation and leave the list unchanged.\n\n" "Click,\n\tDelete\tto Delete the project permanently.\n" "\tRemove\tto just Remove the entry from the list.\n" "\tCancel\tto Cancel this operation and leave the entry in the list.", "Cancel", "Remove", "Delete", iAnswer ); if (iAnswer != 0) { g_ProjectManager.Remove(lstProjects->Items->Item[lstProjects->ItemIndex]->Caption, iAnswer == 2); FillProjectList(); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popRenameProjectClick(TObject *Sender) { if (false == SAFE_PTR(frmRenameProject)) { frmRenameProject = new TfrmRenameProject(NULL); } if (true == SAFE_PTR(frmRenameProject) && lstProjects->ItemIndex != -1) { String sOldName = lstProjects->Items->Item[lstProjects->ItemIndex]->Caption; if (frmRenameProject->Execute(sOldName)) { // rename the project g_ProjectManager.Rename(sOldName, frmRenameProject->edtNewName->Text.Trim()); } SAFE_DELETE(frmRenameProject); FillProjectList(); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popMRUListPopup(TObject *Sender) { popRemoveProject->Enabled = lstProjects->ItemIndex != -1; popRenameProject->Enabled = lstProjects->ItemIndex != -1; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsColumnClick(TObject *Sender, TListColumn *Column) { static TListColumn *LastColumn = NULL; if (lstProjects->Items->Count) { if (LastColumn) { //LastColumn->ImageIndex = 0; } bool bAscending = g_ProjectManager.SortProjects(Column->Index); //Column->ImageIndex = bAscending ? 2 : 1; LastColumn = Column; FillProjectList(); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsMouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { if (ActiveControl != Sender) { ActiveControl = dynamic_cast<TWinControl*>(Sender); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actEditCopyExecute(TObject *Sender) { g_PluginManager.NotifyPlugin(TZX_VERB_COPY, NULL, 0, 0); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actEditCutExecute(TObject *Sender) { g_PluginManager.NotifyPlugin(TZX_VERB_CUT, NULL, 0, 0); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actEditPasteExecute(TObject *Sender) { g_PluginManager.NotifyPlugin(TZX_VERB_PASTE, NULL, 0, 0); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popRestoreProjectClick(TObject *Sender) { String sProject = lstProjects->Items->Item[lstProjects->ItemIndex]->Caption; if (sProject.SubString(sProject.Length() - 9, 10) == " (missing)") { sProject = sProject.SubString(1, sProject.Length() - 10); } g_ProjectManager.Restore(sProject); FillProjectList(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popCopyProjectClick(TObject *Sender) { if (false == SAFE_PTR(frmCopyProject)) { frmCopyProject = new TfrmCopyProject(NULL); } if (true == SAFE_PTR(frmCopyProject) && lstProjects->ItemIndex != -1) { String sOldName = lstProjects->Items->Item[lstProjects->ItemIndex]->Caption; if (frmCopyProject->Execute(sOldName)) { // rename the project g_ProjectManager.Copy(sOldName, frmCopyProject->edtNewName->Text.Trim()); } SAFE_DELETE(frmCopyProject); FillProjectList(); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsKeyPress(TObject *Sender, char &Key) { if (Key == VK_RETURN && lstProjects->ItemIndex != -1) { lstProjectsClick(NULL); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actRunExecute(TObject *Sender) { // send play message g_PluginManager.Notify(NULL, TZXN_GAME_PLAY, NULL, 0, 0); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::Registration(void) { /*const int cVersion = 0x1350; int iVersion = cVersion; bool bState = false; regScorpio->Read("States", "Registered" , bState); regScorpio->Read("States", "RegisteredVersion" , iVersion); if (!bState || iVersion != cVersion) { regScorpio->Write("States", "Registered", true); regScorpio->Write("States", "RegisteredVersion", cVersion); new TRegistrationThread(IdSMTP1, IdMessage1); }*/ } //---------------------------------------------------------------------------
37.171144
164
0.530048
3774044e50975e12b15187b791397878d3fa4378
1,654
cpp
C++
CodeFromLectures/Structures (2)/Structures/main.cpp
Stoefff/Object-Oriented-Programming-FMI-2017
d2f8083ff146fb3cc68425cbd9af50bc37581e19
[ "MIT" ]
3
2018-03-05T13:57:56.000Z
2018-05-03T19:25:05.000Z
CodeFromLectures/Structures (2)/Structures/main.cpp
Stoefff/Object-Oriented-Programming-FMI-2017
d2f8083ff146fb3cc68425cbd9af50bc37581e19
[ "MIT" ]
null
null
null
CodeFromLectures/Structures (2)/Structures/main.cpp
Stoefff/Object-Oriented-Programming-FMI-2017
d2f8083ff146fb3cc68425cbd9af50bc37581e19
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> using namespace std; #include "address.h" #include "student.h" void generateStudentFile() { Student students[5]; for (int i = 0; i < 5; ++i) { students[i].name = NULL; readStudent(students[i]); } fstream file("students.dat", ios::out | ios::binary | ios::trunc); if (!file) { cerr << "Problem with the file..."; return; } for (int i = 0; i < 5; ++i) { if (!store(students[i], file)) break; } file.close(); } void printStudentsFromFile() { Student s; s.name = NULL; fstream file("students.dat", ios::in | ios::binary); while (load(s, file)) printStudent(s); file.close(); } void toUpper(char* text) { while (*text) { if (*text >= 'a' && *text <= 'z') { *text = *text - 'a' + 'A'; } ++text; } } void changeNameOfAllInf() { Student s; s.name = NULL; fstream file("students.dat", ios::in | ios::out | ios::binary); if (!file) return; streampos begin = 0; while (load(s, file)) { if (s.program == INFORMATICS) { toUpper(s.name); streampos end = file.tellg(); file.seekp(begin, ios::beg); store(s, file); file.seekg(end, ios::beg); } begin = file.tellg(); } file.close(); } int main() { // generateStudentFile(); printStudentsFromFile(); // changeNameOfAllInf(); // printStudentsFromFile(); }
19.011494
71
0.476421
3779477a90842c9ea994f741358951e2e030df74
105
hpp
C++
kernel/thor/arch/arm/thor-internal/arch/timer.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
935
2018-05-23T14:56:18.000Z
2022-03-29T07:27:20.000Z
kernel/thor/arch/arm/thor-internal/arch/timer.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
314
2018-05-04T15:58:06.000Z
2022-03-30T16:24:17.000Z
kernel/thor/arch/arm/thor-internal/arch/timer.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
65
2019-04-21T14:26:51.000Z
2022-03-12T03:16:41.000Z
#pragma once namespace thor { void initializeTimers(); void initTimerOnThisCpu(); } // namespace thor
11.666667
26
0.742857
377c25f611fb8ce80317421179313c9ea52cc430
1,956
cpp
C++
userland/src/uname.cpp
Marc-JB/PeregrineOS
2f4069211bca2341f0bab050bfb9cc803a59f510
[ "BSD-2-Clause" ]
null
null
null
userland/src/uname.cpp
Marc-JB/PeregrineOS
2f4069211bca2341f0bab050bfb9cc803a59f510
[ "BSD-2-Clause" ]
null
null
null
userland/src/uname.cpp
Marc-JB/PeregrineOS
2f4069211bca2341f0bab050bfb9cc803a59f510
[ "BSD-2-Clause" ]
null
null
null
#include <stdio.h> #include <sys/utsname.h> #include <string> #include <vector> #include <any> using namespace std; typedef unsigned short int ushort; void run(vector<string>); utsname getUname() { utsname uts; if (uname(&uts) < 0) throw "uname() failed"; return uts; } int main(int argc, char** argv){ vector<string> args; for(int i = 0; i < argc; ++i) args.push_back(string(argv[i])); try { run(args); } catch (string errorMessage){ perror(errorMessage.c_str()); return 1; } catch (any error) { return 1; } return 0; } void run(vector<string> args) { utsname uts = getUname(); bool flag_s = args.size() == 1; bool flag_n = false; bool flag_r = false; bool flag_m = false; if (args.size() > 1) { for (ushort i = 1u; i < args.size(); ++i) { if (args[i][0] == '-') { for (ushort j = 1u; j < args[i].length(); ++j) { switch (args[i][j]) { case 's': flag_s = true; break; case 'n': flag_n = true; break; case 'r': flag_r = true; break; case 'm': flag_m = true; break; case 'a': flag_s = flag_n = flag_r = flag_m = true; break; } } } } } if (!flag_s && !flag_n && !flag_r && !flag_m) flag_s = true; if (flag_s) printf("%s ", uts.sysname); if (flag_n) printf("%s ", uts.nodename); if (flag_r) printf("%s ", uts.release); if (flag_m) printf("%s ", uts.machine); printf("\n"); return void(); }
26.794521
69
0.416155
3780ccd6e1370bf0a3ac7d3677c50f0c0d0e0db2
2,000
cpp
C++
Gecko/src/Gecko/Core/Window.cpp
Liamcreed/Gecko
d3f468f7e809148ad962f0fe969c28aac21236c7
[ "MIT" ]
null
null
null
Gecko/src/Gecko/Core/Window.cpp
Liamcreed/Gecko
d3f468f7e809148ad962f0fe969c28aac21236c7
[ "MIT" ]
null
null
null
Gecko/src/Gecko/Core/Window.cpp
Liamcreed/Gecko
d3f468f7e809148ad962f0fe969c28aac21236c7
[ "MIT" ]
null
null
null
#include "gkpch.h" #include "Input.h" #include "Window.h" namespace Gecko { void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods); void cursor_position_callback(GLFWwindow *window, double xpos, double ypos); void mouse_button_callback(GLFWwindow *window, int button, int action, int mods); void scroll_callback(GLFWwindow *window, double xoffset, double yoffset); Window::Window(const std::string t, int w, int h) : m_Title(t), m_Width(w), m_Height(h) { if (!glfwInit()) { glfwTerminate(); GK_LOG(GK_ERROR) << "Failed to initialize GLFW!\n"; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif m_GLFWWindow = glfwCreateWindow(m_Width, m_Height, m_Title.c_str(), NULL, NULL); if (m_GLFWWindow == nullptr) { glfwTerminate(); GK_LOG(GK_ERROR) << "Failed to create GLFWWindow!\n"; } glfwMakeContextCurrent(m_GLFWWindow); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { GK_LOG(GK_ERROR) << "Failed to initialize GLAD!\n"; } glfwSwapInterval(1); glfwSetKeyCallback(m_GLFWWindow, key_callback); glfwSetCursorPosCallback(m_GLFWWindow, cursor_position_callback); glfwSetMouseButtonCallback(m_GLFWWindow, mouse_button_callback); glfwSetScrollCallback(m_GLFWWindow, scroll_callback); } void Window::Update() { glfwPollEvents(); glfwGetWindowSize(m_GLFWWindow, &m_Width, &m_Height); glfwSwapBuffers(m_GLFWWindow); } void Window::Clean() { glfwDestroyWindow(m_GLFWWindow); glfwTerminate(); } Window::~Window() { Clean(); } } // namespace Gecko
32.258065
88
0.6525
3786ccf7530bb04fb445a71d1f144c15e5628757
11,406
cpp
C++
integrations/Raknet/NetworkSystem.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
integrations/Raknet/NetworkSystem.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
integrations/Raknet/NetworkSystem.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
/****************************************************************************** Copyright (c) 2015 Teardrop Games 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 "stdafx.h" #include "NetworkSystem.h" #include "Peer.h" #include "Stream.h" #include "Memory/Allocators.h" #include "Util/Environment.h" #include "Util/Logger.h" #include "Util/_String.h" #include "Network/Messages/ConnectionRequestAccepted.h" #include "Network/Messages/PingResponse.h" #include "Network/Messages/ConnectionLost.h" using namespace Teardrop; using namespace Integration; Raknet::System::System(int maxIncomingConnections, short listenPort) : mMe(0) , mGuid(0) { mMaxIncomingConnections = maxIncomingConnections; mListenPort = listenPort; } Raknet::System::~System() { } Allocator* Raknet::System::s_pAllocator = TD_GET_ALLOCATOR(DEFAULT); void* Raknet::System::malloc(size_t sz) { return s_pAllocator->Allocate(sz TD_ALLOC_SITE); } void* Raknet::System::realloc(void* pMem, size_t sz) { return s_pAllocator->Reallocate(pMem, sz TD_ALLOC_SITE); } void Raknet::System::free(void* pMem) { return s_pAllocator->Deallocate(pMem); } void Raknet::System::setAllocator(Allocator* pAlloc) { assert(pAlloc); s_pAllocator = pAlloc; } Allocator* Raknet::System::getAllocator() { return s_pAllocator; } void Raknet::System::getTypes(Type* typeArray, int& typeCount) { if (typeCount < 1) { typeCount = 0; return; // TODO: throw? } typeArray[0] = System::SYSTEM_NETWORK; typeCount = 1; } Net::Message* Raknet::System::createMessage(unsigned char msgId) { // for now, the TD msg ID is still an unsigned char (tho this // is likely to change once we get lots of messages) if (s_factory[msgId]) return s_factory[msgId](); return 0; } unsigned long long Raknet::System::getTime() { return RakNet::GetTime(); } bool Raknet::System::connect(const String& address, unsigned short port) { return mMe->Connect(address, port, 0, 0); } Teardrop::Net::Peer* Raknet::System::createPeer(Net::Message& msg) { Raknet::Peer* pPeer = static_cast<Raknet::Peer*>(msg.m_pPeer); return new Raknet::Peer(pPeer->mGuid); } void Raknet::System::destroyPeer(Teardrop::Net::Peer* pPeer) { delete pPeer; } Net::MessagePtr Raknet::System::getNextMessage() { Net::MessagePtr pMsg; Packet* pPacket = mMe->Receive(); // we only want to deal with TD messages here -- system/API messages // should be dealt with in a different path if (pPacket) { #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Incoming packet: id=%d, len=%d", pPacket->data[0], pPacket->length); Environment::get().pLogger->logMessage(buf); #endif Raknet::Stream bs(pPacket->data, pPacket->length, false); // connected messages need to have their remote endpoint information set up bool bIsConnected = false; switch (pPacket->data[0]) { // disconnected connection request, no guid or systemaddr available case ID_NEW_INCOMING_CONNECTION: Environment::get().pLogger->logMessage("\nNEW INCOMING CONNECTION\n"); break; // Non-system/control messages have their message ID in the second byte case ID_USER_PACKET_ENUM+1: pMsg = createMessage(pPacket->data[1]); if (pMsg) { pMsg->deserialize(bs); bIsConnected = true; } break; // disconnected ping response, no guid or systemaddr available case ID_PONG: pMsg = TD_NEW Net::PingResponse; pMsg->deserialize(bs); break; // we sent out a connect request, and the other end replied in the affirmative; // this is where we set up the ID info for "the other guy", which should be extracted // by whoever processes this message and stored for later use in sending messages // to this remote endpoint case ID_CONNECTION_REQUEST_ACCEPTED: pMsg = TD_NEW Net::ConnectionRequestAccepted; pMsg->deserialize(bs); bIsConnected = true; break; // connected disconnect notice, we need to case ID_CONNECTION_LOST: case ID_DISCONNECTION_NOTIFICATION: pMsg = TD_NEW Net::ConnectionLost; pMsg->deserialize(bs); bIsConnected = true; break; } if (bIsConnected) { pMsg->m_pPeer = TD_NEW Raknet::Peer(pPacket->guid, pPacket->systemAddress); } } return pMsg; } // broadcast to all peers void Raknet::System::send(Net::Message& msg) { SystemAddress dest; Raknet::Stream bs; msg.serialize(bs); #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Outgoing packet (broadcast): id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif mMe->Send( &bs.mBS, (PacketPriority)msg.m_priority, (PacketReliability)msg.m_reliability, char(msg.m_channel), dest, true); } // send to single peer void Raknet::System::send(Net::Message& msg, Teardrop::Net::Peer* pRecipient) { Raknet::Stream bs; msg.serialize(bs); Raknet::Peer* pPeer = static_cast<Raknet::Peer*>(pRecipient); SystemAddress dest; if (pPeer) dest = mMe->GetSystemAddressFromGuid(pPeer->mGuid); else { #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Failed to send outgoing packet (null recipient): id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif return; } #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Outgoing packet: id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif mMe->Send( &bs.mBS, (PacketPriority)msg.m_priority, (PacketReliability)msg.m_reliability, char(msg.m_channel), dest, false); } // send to multiple peers void Raknet::System::send(Net::Message& msg, Teardrop::Net::Peer** pRecipients, int nRecipients) { Raknet::Stream bs; msg.serialize(bs); for (int i=0; i<nRecipients; ++i) { Raknet::Peer* pPeer = static_cast<Raknet::Peer*>(pRecipients[i]); SystemAddress dest; if (pPeer) dest = mMe->GetSystemAddressFromGuid(pPeer->mGuid); else { #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Failed to send outgoing packet (null recipient): id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif return; } #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Outgoing packet: id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif mMe->Send( &bs.mBS, (PacketPriority)msg.m_priority, (PacketReliability)msg.m_reliability, char(msg.m_channel), dest, false); } } void Raknet::System::disconnect(Net::Peer* pPeer) { // sending a zero to this method means disconnect ourselves if (pPeer) { Raknet::Peer* pP = static_cast<Raknet::Peer*>(pPeer); mMe->CloseConnection(pP->mAddr, true, 0, HIGH_PRIORITY); } //else // m_pPeer->CloseConnection(UNASSIGNED_SYSTEM_ADDRESS, true, 0, HIGH_PRIORITY); Sleep(500); } void Raknet::System::disconnect(unsigned int addr, unsigned short port) { mMe->CloseConnection( SystemAddress(addr, port), true, 0, HIGH_PRIORITY); Sleep(500); } // for unconnected systems (i.e servers in a server list) void Raknet::System::ping(const char* addr, unsigned short port) { mMe->Ping(addr, port, false); } void Raknet::System::setDisconnectedPingResponse(const char *data, unsigned int dataSize) { mMe->SetOfflinePingResponse(data, dataSize); } // for unconnected systems (i.e available servers on the LAN) void Raknet::System::requestServerInfo(const char* addr) { //InterrogateServer msg; //send(&msg, addr, PORT_GAME_SERVER_CLIENT_LISTENER); } bool Raknet::System::isLocalOrigination(Net::Message* pMsg) { Raknet::Peer* pPeer = static_cast<Raknet::Peer*>(pMsg->m_pPeer); return (mMe->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) == pPeer->mGuid); } unsigned int Raknet::System::getLocalIpV4() { const char * localIp = mMe->GetLocalIP(0); unsigned char ip[4]; unsigned int a, b, c, d; sscanf_s(localIp, "%d.%d.%d.%d", &a, &b, &c, &d); ip[0] = d; ip[1] = c; ip[2] = b; ip[3] = a; return *((unsigned int*)ip); } #include "Network/Messages/Advertise.h" #include "Network/Messages/Unadvertise.h" #include "Network/Messages/PlayerJoinServer.h" #include "Network/Messages/PlayerLeaveServer.h" #include "Network/Messages/PlayerJoinGame.h" #include "Network/Messages/PlayerLeaveGame.h" #include "Network/Messages/UpdateServerState.h" #include "Network/Messages/UpdatePlayerState.h" #include "Network/Messages/GameStarted.h" #include "Network/Messages/GameEnded.h" #include "Network/Messages/PlayerPositionSync.h" #include "Network/Messages/PlayerCommand.h" #include "Network/Messages/InterrogateServer.h" #include "Network/Messages/QueryIFF.h" #include "Network/Messages/ResponseIFF.h" #include "Network/Messages/PlayerEntityVariantChanged.h" #include "RakMemoryOverride.h" #include "PacketLogger.h" class MyLogger : public PacketLogger { public: void WriteLog(const char* msg) { #if defined(_DEBUG) Teardrop::Environment::get().pLogger->logMessage(msg); #endif } }; MyLogger s_logger; using namespace Teardrop::Net; using namespace Raknet; void Raknet::System::initialize() { rakMalloc = Raknet::System::malloc; rakRealloc = Raknet::System::realloc; rakFree = Raknet::System::free; Advertise _a; Unadvertise _u; PlayerJoinServer _pjs; PlayerLeaveServer _pls; PlayerJoinGame _pjg; PlayerLeaveGame _plg; UpdatePlayerState _ups; UpdateServerState _uss; GameStarted _gs; GameEnded _ge; PlayerPositionSync _pps; PlayerCommand _pc; InterrogateServer _ic; QueryIFF _qi; ResponseIFF _ri; PlayerVariantChanged _pvc; // initialize Raknet mMe = RakNetworkFactory::GetRakPeerInterface(); mMe->AttachPlugin(&s_logger); // for now, prevent ping responses entirely (server can reset this later) mMe->SetOfflinePingResponse(0, 0); // startup our peer -- we talk to the master server as well as // game clients through this peer, so make enough to go around SocketDescriptor desc(mListenPort, 0); bool rtn = mMe->Startup(mMaxIncomingConnections, 30, &desc, 1); if (rtn && mMaxIncomingConnections > 2) { mMe->SetMaximumIncomingConnections(mMaxIncomingConnections); } // set our guid and address members mGuid = new RakNetGUID; *mGuid = mMe->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); } void Raknet::System::shutdown() { delete mGuid; mGuid = 0; mMe->Shutdown(300); RakNetworkFactory::DestroyRakPeerInterface(mMe); mMe = 0; }
26.711944
131
0.722865