blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
e02fdfe2d93b9b22c90fad92e81927c8fd84496e
cbc9bcc24ae419bba0c45bf11dd842a2d6bbf838
/DRAMSysCustomBuild/library/src/configuration/memspec/MemSpecWideIO.h
2ce092ff0514722c3482b88040e5cfb85138a351
[]
no_license
abinavkrishna/DRAMSysCustomBuild
17fbd72d80b44585a1f3664ff96b1c2ba1b06a19
8530cfbb1bceb46e86d2b138a36ffe7eb6fe4adc
refs/heads/main
2023-01-11T15:15:11.158308
2020-11-10T08:46:25
2020-11-10T08:46:25
311,592,256
0
0
null
null
null
null
UTF-8
C++
false
false
3,366
h
/* * Copyright (c) 2019, Technische Universität Kaiserslautern * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. 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. * * Authors: * Lukas Steiner */ #ifndef MEMSPECWIDEIO_H #define MEMSPECWIDEIO_H #include "MemSpec.h" #include "../../common/third_party/nlohmann/single_include/nlohmann/json.hpp" class MemSpecWideIO final : public MemSpec { public: MemSpecWideIO(nlohmann::json &memspec); // Memspec Variables: const sc_time tCKE; const sc_time tCKESR; const sc_time tRAS; const sc_time tRC; const sc_time tRCD; const sc_time tRL; const sc_time tWL; const sc_time tWR; const sc_time tXP; const sc_time tXSR; const sc_time tREFI; const sc_time tRFC; const sc_time tRP; const sc_time tDQSCK; const sc_time tAC; const sc_time tCCD_R; const sc_time tCCD_W; const sc_time tRRD; const sc_time tTAW; const sc_time tWTR; const sc_time tRTRS; // Currents and Voltages: const double iDD0; const double iDD2N; const double iDD3N; const double iDD4R; const double iDD4W; const double iDD5; const double iDD6; const double vDD; const double iDD02; const double iDD2P0; const double iDD2P02; const double iDD2P1; const double iDD2P12; const double iDD2N2; const double iDD3P0; const double iDD3P02; const double iDD3P1; const double iDD3P12; const double iDD3N2; const double iDD4R2; const double iDD4W2; const double iDD52; const double iDD62; const double vDD2; virtual sc_time getRefreshIntervalPB() const override; virtual sc_time getRefreshIntervalAB() const override; virtual sc_time getExecutionTime(Command, const tlm::tlm_generic_payload &) const override; virtual TimeInterval getIntervalOnDataStrobe(Command) const override; }; #endif // MEMSPECWIDEIO_H
[ "abinav.s.krishna@gmail.com" ]
abinav.s.krishna@gmail.com
5ff25fb3f501753d5d63585c4ec9f0ad87f68452
2b631cb14b185044e4201c9cc8be8219c5ab7556
/ml/nn/runtime/test/generated/models/reshape_quant8.model.cpp
be4702cee38b6815d4ca27b1784e1787d308733c
[ "Apache-2.0" ]
permissive
yuchuangu85/Android-framework-code
59837ba3e41ebdda7de74ce82e1af2d0367610ce
fb27715328b4b0064b0f4e7b499b8c0f2e728d61
refs/heads/master
2020-09-03T09:00:20.642461
2019-11-04T16:21:25
2019-11-04T16:21:25
219,429,555
2
3
null
null
null
null
UTF-8
C++
false
false
1,681
cpp
// clang-format off // Generated file (from: reshape_quant8.mod.py). Do not edit void CreateModel(Model *model) { OperandType type0(Type::TENSOR_QUANT8_ASYMM, {1, 1, 3, 3}, 1.0f, 0); OperandType type1(Type::TENSOR_INT32, {1}); OperandType type2(Type::TENSOR_QUANT8_ASYMM, {9}, 1.0f, 0); // Phase 1, operands auto op1 = model->addOperand(&type0); auto op2 = model->addOperand(&type1); auto op3 = model->addOperand(&type2); // Phase 2, operations static int32_t op2_init[] = {-1}; model->setOperandValue(op2, op2_init, sizeof(int32_t) * 1); model->addOperation(ANEURALNETWORKS_RESHAPE, {op1, op2}, {op3}); // Phase 3, inputs and outputs model->identifyInputsAndOutputs( {op1}, {op3}); assert(model->isValid()); } inline bool is_ignored(int i) { static std::set<int> ignore = {}; return ignore.find(i) != ignore.end(); } void CreateModel_dynamic_output_shape(Model *model) { OperandType type0(Type::TENSOR_QUANT8_ASYMM, {1, 1, 3, 3}, 1.0f, 0); OperandType type1(Type::TENSOR_INT32, {1}); OperandType type3(Type::TENSOR_QUANT8_ASYMM, {0}, 1.0f, 0); // Phase 1, operands auto op1 = model->addOperand(&type0); auto op2 = model->addOperand(&type1); auto op3 = model->addOperand(&type3); // Phase 2, operations static int32_t op2_init[] = {-1}; model->setOperandValue(op2, op2_init, sizeof(int32_t) * 1); model->addOperation(ANEURALNETWORKS_RESHAPE, {op1, op2}, {op3}); // Phase 3, inputs and outputs model->identifyInputsAndOutputs( {op1}, {op3}); assert(model->isValid()); } inline bool is_ignored_dynamic_output_shape(int i) { static std::set<int> ignore = {}; return ignore.find(i) != ignore.end(); }
[ "yuchuangu85@gmail.com" ]
yuchuangu85@gmail.com
c60e17ee96ec8ce8271ffb60c55450ad4787364c
5674936bd1810d80cbd0ecfd3204f38ac47f9f1b
/gearbox/job/JobResponse.cc
0364a4fed77548151628d2cf4b6c470d000f94eb
[ "PHP-3.01", "BSD-3-Clause", "Artistic-2.0", "Artistic-1.0-Perl" ]
permissive
coryb/gearbox
ae778029c955d5b3d7d5828596d4d5bd095e6420
88027f2f101c2d1fab16093928963052b9d3294d
refs/heads/master
2016-09-05T14:32:18.972793
2013-11-10T05:17:18
2013-11-10T05:17:18
3,802,109
4
0
null
2013-11-10T05:17:20
2012-03-22T20:39:03
C++
UTF-8
C++
false
false
2,329
cc
// Copyright (c) 2012, Yahoo! Inc. All rights reserved. // Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. #include <gearbox/job/JobResponse.h> namespace Gearbox { struct JobResponse::Private { std::string content; Hash headers; StatusPtr status; int code; JobPtr job; Private() : code(-1) {} Private(const Private & other) : content(other.content), headers(other.headers), status(other.status), code(other.code), job(other.job) {} }; JobResponse::JobResponse() : impl(new Private()) {} JobResponse::JobResponse(const JobResponse & copy) : impl( new Private(*(copy.impl)) ) {} JobResponse & JobResponse::operator=(const JobResponse & copy) { if( this == &copy ) return *this; this->impl->content = copy.impl->content; this->impl->headers = copy.impl->headers; this->impl->status = copy.impl->status; this->impl->code = copy.impl->code; this->impl->job = copy.impl->job; return *this; } JobResponse::~JobResponse() { if( impl ) delete impl; } void JobResponse::content( const std::string & content ) { this->impl->content = content; } const std::string & JobResponse::content() const { return this->impl->content; } void JobResponse::headers( const Hash & headers ) { this->impl->headers = headers; } void JobResponse::add_header( const std::string & name, const std::string & value ) { this->impl->headers[name] = value; } const Hash & JobResponse::headers() const { return this->impl->headers; } void JobResponse::status( const Status & status ) { this->impl->status.reset(new Status(status)); } const StatusPtr & JobResponse::status() const { return this->impl->status; } void JobResponse::code( int code ) { this->impl->code = code; } int JobResponse::code() const { return this->impl->code; } void JobResponse::job( const JobPtr & job ) { this->impl->job = job; } const JobPtr & JobResponse::job() const { return this->impl->job; } }
[ "coryb@streetcry.corp.yahoo.com" ]
coryb@streetcry.corp.yahoo.com
07a4fff834594f1da7cbfc6ba8b272249c2b5f27
bbcaaebddba6c2c422c75e7fa6614e75db033d1c
/Qt/5.9/clang_64/lib/QtQuickTemplates2.framework/Versions/5/Headers/5.9.0/QtQuickTemplates2/private/qquickcontrol_p_p.h
4dd6f32a1ed31f4fdc01dd4bd0955b9fe069d18c
[]
no_license
heatherThida/CS10
178862a55adb35bb1ba22004d401010a93046e9b
b05d1c30359943470cbbd348d58d2bd4b5148fae
refs/heads/master
2020-12-03T04:01:23.896399
2017-07-26T19:12:38
2017-07-26T19:12:38
95,803,381
1
1
null
null
null
null
UTF-8
C++
false
false
5,186
h
/**************************************************************************** ** ** Copyright (C) 2017 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Quick Templates 2 module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL3$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPLv3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or later as published by the Free ** Software Foundation and appearing in the file LICENSE.GPL included in ** the packaging of this file. Please review the following information to ** ensure the GNU General Public License version 2.0 requirements will be ** met: http://www.gnu.org/licenses/gpl-2.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QQUICKCONTROL_P_P_H #define QQUICKCONTROL_P_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include "qquickcontrol_p.h" #include <QtQuick/private/qquickitem_p.h> #include <QtQml/private/qlazilyallocated_p.h> #include <qpa/qplatformtheme.h> #if QT_CONFIG(accessibility) #include <QtGui/qaccessible.h> #endif QT_BEGIN_NAMESPACE class QQuickAccessibleAttached; class Q_QUICKTEMPLATES2_PRIVATE_EXPORT QQuickControlPrivate : public QQuickItemPrivate #if QT_CONFIG(accessibility) , public QAccessible::ActivationObserver #endif { Q_DECLARE_PUBLIC(QQuickControl) public: QQuickControlPrivate(); virtual ~QQuickControlPrivate(); static QQuickControlPrivate *get(QQuickControl *control) { return control->d_func(); } virtual bool acceptTouch(const QTouchEvent::TouchPoint &point); virtual void handlePress(const QPointF &point); virtual void handleMove(const QPointF &point); virtual void handleRelease(const QPointF &point); virtual void handleUngrab(); void mirrorChange() override; void setTopPadding(qreal value, bool reset = false); void setLeftPadding(qreal value, bool reset = false); void setRightPadding(qreal value, bool reset = false); void setBottomPadding(qreal value, bool reset = false); void resizeBackground(); virtual void resizeContent(); virtual QQuickItem *getContentItem(); #if QT_CONFIG(accessibility) void accessibilityActiveChanged(bool active) override; QAccessible::Role accessibleRole() const override; #endif void updateFont(const QFont &f); static void updateFontRecur(QQuickItem *item, const QFont &f); inline void setFont_helper(const QFont &f) { if (resolvedFont.resolve() == f.resolve() && resolvedFont == f) return; updateFont(f); } virtual void resolveFont(); void inheritFont(const QFont &f); static QFont parentFont(const QQuickItem *item); static QFont themeFont(QPlatformTheme::Font type); void updateLocale(const QLocale &l, bool e); static void updateLocaleRecur(QQuickItem *item, const QLocale &l); static QLocale calcLocale(const QQuickItem *item); #if QT_CONFIG(quicktemplates2_hover) void updateHoverEnabled(bool enabled, bool xplicit); static void updateHoverEnabledRecur(QQuickItem *item, bool enabled); static bool calcHoverEnabled(const QQuickItem *item); #endif static void destroyDelegate(QObject *object, QObject *parent); struct ExtraData { ExtraData(); QFont font; }; QLazilyAllocated<ExtraData> extra; QFont resolvedFont; bool hasTopPadding; bool hasLeftPadding; bool hasRightPadding; bool hasBottomPadding; bool hasLocale; bool wheelEnabled; #if QT_CONFIG(quicktemplates2_hover) bool hovered; bool explicitHoverEnabled; #endif int touchId; qreal padding; qreal topPadding; qreal leftPadding; qreal rightPadding; qreal bottomPadding; qreal spacing; QLocale locale; Qt::FocusPolicy focusPolicy; Qt::FocusReason focusReason; QQuickItem *background; QQuickItem *contentItem; QQuickAccessibleAttached *accessibleAttached; }; QT_END_NAMESPACE #endif // QQUICKCONTROL_P_P_H
[ "shellthakhin@gmail.com" ]
shellthakhin@gmail.com
c62aefa33c042eba2db984755c47d4a939917e9b
abc6652b297ebe4446204c391bb513c70ddd0b92
/OutputWindow.cpp
cf2b5314a9d7c3507fa64dfff9ae4055d7c731bb
[]
no_license
stupidsing/CrimsonEditor
9a8fb82bff3e64e043f43db48e0112cee0aa11d9
c7ed10a7df75d555a0457f7fb74096e49882b507
refs/heads/master
2021-01-10T03:08:37.074835
2016-10-18T14:39:04
2016-10-18T14:39:17
47,800,895
1
0
null
null
null
null
UTF-8
C++
false
false
9,280
cpp
// OutputWindow.cpp : implementation file // #include "stdafx.h" #include "cedtHeader.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif COutputWindow::COutputWindow() { memset( m_tbiToolbarOutput, 0x00, sizeof(m_tbiToolbarOutput) ); memset( m_tbiWinButtons, 0x00, sizeof(m_tbiWinButtons) ); m_tbiToolbarOutput[0].iBitmap = 0; m_tbiToolbarOutput[0].idCommand = ID_DIRECTORY_ITEM_REFRESH; m_tbiToolbarOutput[0].fsState = TBSTATE_ENABLED | TBSTATE_WRAP; m_tbiToolbarOutput[0].fsStyle = TBSTYLE_BUTTON; m_tbiToolbarOutput[1].fsState = TBSTATE_ENABLED | TBSTATE_WRAP; m_tbiToolbarOutput[1].fsStyle = TBSTYLE_SEP; m_tbiToolbarOutput[2].iBitmap = 1; m_tbiToolbarOutput[2].idCommand = ID_DIRECTORY_ITEM_COPY; m_tbiToolbarOutput[2].fsState = TBSTATE_ENABLED | TBSTATE_WRAP; m_tbiToolbarOutput[2].fsStyle = TBSTYLE_BUTTON; m_tbiToolbarOutput[3].iBitmap = 2; m_tbiToolbarOutput[3].idCommand = ID_DIRECTORY_ITEM_MOVE; m_tbiToolbarOutput[3].fsState = TBSTATE_ENABLED | TBSTATE_WRAP; m_tbiToolbarOutput[3].fsStyle = TBSTYLE_BUTTON; m_tbiToolbarOutput[4].iBitmap = 3; m_tbiToolbarOutput[4].idCommand = ID_DIRECTORY_ITEM_DELETE; m_tbiToolbarOutput[4].fsState = TBSTATE_ENABLED | TBSTATE_WRAP; m_tbiToolbarOutput[4].fsStyle = TBSTYLE_BUTTON; m_tbiToolbarOutput[5].fsState = TBSTATE_ENABLED | TBSTATE_WRAP; m_tbiToolbarOutput[5].fsStyle = TBSTYLE_SEP; m_tbiWinButtons[0].iBitmap = 1; m_tbiWinButtons[0].idCommand = ID_OUTPUT_WINDOW_HIDE; m_tbiWinButtons[0].fsState = TBSTATE_ENABLED | TBSTATE_WRAP; m_tbiWinButtons[0].fsStyle = TBSTYLE_BUTTON; } COutputWindow::~COutputWindow() { m_imgToolbarOutput.Detach(); m_imgWinButtons.Detach(); } BEGIN_MESSAGE_MAP(COutputWindow, CSizingControlBar) //{{AFX_MSG_MAP(COutputWindow) ON_WM_CREATE() ON_WM_SIZE() ON_LBN_DBLCLK(IDC_OUTPUT, OnDblclkOutput) ON_WM_CONTEXTMENU() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // COutputWindow message handlers int COutputWindow::OnCreate(LPCREATESTRUCT lpCreateStruct) { CRect rect(0, 0, 1, 1); DWORD dwStyle; if (CSizingControlBar::OnCreate(lpCreateStruct) == -1) return -1; dwStyle = WS_VISIBLE | WS_CHILD; CString szText( (LPCTSTR)IDS_CTRL_OUTPUT_WINDOW ); m_stcCaptionOutput.Create(szText, dwStyle, rect, this, IDC_OUTPUT_CAPTION); dwStyle = WS_VISIBLE | WS_CHILD | CCS_NORESIZE | CCS_NODIVIDER | TBSTYLE_FLAT | TBSTYLE_TOOLTIPS; m_btnWinButtons.Create(dwStyle, rect, this, IDC_OUTPUT_TOOLBAR); dwStyle = WS_VISIBLE | WS_CHILD | WS_VSCROLL | WS_HSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | LBS_USETABSTOPS; m_lstConsoleOutput.Create(dwStyle, rect, this, IDC_OUTPUT_LIST); m_lstConsoleOutput.ModifyStyleEx(0, WS_EX_CLIENTEDGE, 0); m_lstConsoleOutput.SetHorizontalExtent(2560); m_lstConsoleOutput.SetTabStops(32); // dialog based unit (approximately 4 character) dwStyle = WS_VISIBLE | WS_CHILD; m_edtConsoleInput.Create(dwStyle, rect, this, IDC_OUTPUT_EDIT); m_edtConsoleInput.ModifyStyleEx(0, WS_EX_CLIENTEDGE, 0); m_edtConsoleInput.SetReadOnly(TRUE); // set image list // m_imgToolbarOutput.Create(IDB_OUTPUT_TOOLBAR, 16, 0, RGB(255, 0, 255)); // m_btnToolbarOutput.SetImageList( & m_imgToolbarOutput ); m_imgWinButtons.Create(IDB_WIN_BUTTONS, 12, 0, RGB(255, 0, 255)); m_btnWinButtons.SetImageList( & m_imgWinButtons ); // set control font CFont * pFont = CFont::FromHandle((HFONT)::GetStockObject(DEFAULT_GUI_FONT)); LOGFONT lf; pFont->GetLogFont( & lf ); m_fontControl.CreateFontIndirect( & lf ); m_stcCaptionOutput.SetFont( & m_fontControl, FALSE ); // set output font ApplyOutputFont( FALSE ); // initialize toolbar // m_btnToolbarOutput.AddButtons( 6, m_tbiToolbarOutput ); m_btnWinButtons.AddButtons( 1, m_tbiWinButtons ); // set occupied flag m_bOccupied = FALSE; return 0; } void COutputWindow::OnSize(UINT nType, int cx, int cy) { CSizingControlBar::OnSize(nType, cx, cy); INT nBegX = 2, nEndX = cx - 4; // nBegX = 2; m_btnToolbarOutput.MoveWindow(nBegX, 2, 22, 106); nBegX += 0; m_stcCaptionOutput.MoveWindow(nBegX, 24, 18, cy-26); nBegX += 2; m_btnWinButtons.MoveWindow(nBegX, 4, 19, 18); nBegX += 20; m_lstConsoleOutput.MoveWindow(nBegX, 2, nEndX-nBegX, cy-24); nBegX += 0; m_edtConsoleInput.MoveWindow(nBegX, cy-22, nEndX-nBegX, 20); } void COutputWindow::OnDblclkOutput() { INT nSelect = m_lstConsoleOutput.GetCurSel(); if( nSelect == LB_ERR ) return; CString szString; m_lstConsoleOutput.GetText(nSelect, szString); if( ! szString.GetLength() ) return; INT nIndex1 = szString.Find('('); if( nIndex1 < 0 ) return; INT nIndex2 = szString.Find(')'); if( nIndex2 < 0 ) return; if( nIndex2 < nIndex1 ) return; CString szPathName = szString.Left(nIndex1); if( ! VerifyFilePath(szPathName) ) return; CString szLineNum = szString.Mid(nIndex1+1, nIndex2-nIndex1-1); INT nLineNum = atoi(szLineNum); if( ! nLineNum ) return; CCedtApp * pApp = (CCedtApp *)AfxGetApp(); if( ! pApp ) return; pApp->PostOpenDocumentFile( szPathName, nLineNum ); } void COutputWindow::OnContextMenu(CWnd* pWnd, CPoint point) { CMenu * pMenu, context; context.LoadMenu(IDR_OUTPUT_WINDOW); pMenu = context.GetSubMenu(0); UINT nFlags = TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON; pMenu->TrackPopupMenu(nFlags, point.x, point.y, AfxGetMainWnd()); } ///////////////////////////////////////////////////////////// // Operations void COutputWindow::ApplyOutputFont(BOOL bRedraw) { if( m_fontOutput.m_hObject ) m_fontOutput.DeleteObject(); LOGFONT lf; memcpy( & lf, & CCedtView::m_lfMiscel[0x01], sizeof(LOGFONT) ); CDC * pDC = m_lstConsoleOutput.GetDC(); lf.lfHeight = -MulDiv( lf.lfHeight, pDC->GetDeviceCaps(LOGPIXELSY), 720 ); m_lstConsoleOutput.ReleaseDC( pDC ); m_fontOutput.CreateFontIndirect( & lf ); m_lstConsoleOutput.SetFont( & m_fontOutput, bRedraw ); m_edtConsoleInput.SetFont( & m_fontOutput, bRedraw ); } void COutputWindow::EnableInputConsole(BOOL bEnable) { m_edtConsoleInput.SetWindowText(""); m_edtConsoleInput.SetReadOnly(!bEnable); } void COutputWindow::CopyAllTheContents() { CMemText Block; TCHAR szText[2048]; INT nCount = m_lstConsoleOutput.GetCount(); for(INT i = 0; i < nCount; i++) { m_lstConsoleOutput.GetText(i, szText); Block.AddTail( szText ); } CCedtView::SetClipboardData( Block ); } void COutputWindow::ClearAllTheContents() { m_lstConsoleOutput.ResetContent(); } BOOL COutputWindow::AddStringToTheLast(LPCTSTR lpszString) { if( m_lstConsoleOutput.GetCount() >= OUTPUT_MAX_LINE_COUNT ) { m_lstConsoleOutput.SetRedraw(FALSE); m_lstConsoleOutput.DeleteString(0); m_lstConsoleOutput.SetRedraw(TRUE); } INT nIndex = m_lstConsoleOutput.AddString(lpszString); if( nIndex == LB_ERR || nIndex == LB_ERRSPACE ) return FALSE; CRect rectClient; m_lstConsoleOutput.GetClientRect( & rectClient ); CRect rectItem; m_lstConsoleOutput.GetItemRect(nIndex, & rectItem); INT nLineCount = rectClient.Height() / rectItem.Height(); INT nTop = m_lstConsoleOutput.GetTopIndex(); if( nIndex - nTop + 1 > nLineCount ) m_lstConsoleOutput.SetTopIndex( nIndex - nLineCount + 1); return TRUE; } BOOL COutputWindow::ReplaceTheLastString(LPCTSTR lpszString) { INT nCount = m_lstConsoleOutput.GetCount(); if( nCount > 0 ) m_lstConsoleOutput.DeleteString(nCount-1); INT nIndex = m_lstConsoleOutput.AddString(lpszString); if( nIndex == LB_ERR || nIndex == LB_ERRSPACE ) return FALSE; CRect rectClient; m_lstConsoleOutput.GetClientRect( & rectClient ); CRect rectItem; m_lstConsoleOutput.GetItemRect(nIndex, & rectItem); INT nLineCount = rectClient.Height() / rectItem.Height(); INT nTop = m_lstConsoleOutput.GetTopIndex(); if( nIndex - nTop + 1 > nLineCount ) m_lstConsoleOutput.SetTopIndex( nIndex - nLineCount + 1); return TRUE; } BOOL COutputWindow::GetTheLastString(CString & szString) { INT nCount = m_lstConsoleOutput.GetCount(); if( nCount > 0 ) m_lstConsoleOutput.GetText(nCount-1, szString); else szString = ""; return TRUE; } BOOL COutputWindow::PreTranslateMessage(MSG* pMsg) { switch( pMsg->message ) { case WM_KEYDOWN: switch( pMsg->wParam ) { case VK_RETURN: OnKeyReturn(); return TRUE; case VK_ESCAPE: OnKeyEscape(); return TRUE; } break; } if( pMsg->message == WM_KEYDOWN || pMsg->message == WM_KEYUP ) { TranslateMessage( pMsg ); DispatchMessage( pMsg ); return TRUE; } else return CSizingControlBar::PreTranslateMessage(pMsg); } void COutputWindow::OnKeyReturn() { if( m_edtConsoleInput.GetStyle() & ES_READONLY ) return; // PostMessage( WM_COMMAND, ID_COMMAND_SEND_INPUT, 0L ); TCHAR szInputString[4096]; m_edtConsoleInput.GetLine(0, szInputString, 4096); CCedtView::SetChildInputString( szInputString ); m_edtConsoleInput.SetWindowText(""); // clear input console } void COutputWindow::OnKeyEscape() { if( m_edtConsoleInput.GetStyle() & ES_READONLY ) return; // PostMessage( WM_COMMAND, ID_COMMAND_KILL_PROCESS, 0L ); CCedtView::KillChildProcess(); }
[ "stupidsing@gmail.com" ]
stupidsing@gmail.com
a0dbbaea7855ff772d9d62db857f2042fe413728
404547b1ec3237f02342fe65e957f32851ce1495
/SharedBase/ge_vector.h
1c38b57fd5ac5217bb2b6d34a770364d21408775
[]
no_license
Adanos-Gotoman/GenomeSDK-R
c5e3a5d57c4fb721b15bb7f572454f2a3021561a
cf87f21fca83b37d2e186fb69b083b72932f9c8c
refs/heads/master
2023-03-16T07:05:00.799421
2021-02-19T16:07:09
2021-02-19T16:07:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,352
h
#ifndef GE_VECTOR_H_INCLUDED #define GE_VECTOR_H_INCLUDED #pragma warning( push ) #pragma warning( disable : 4201 ) // nonstandard extension used : nameless struct/union class GE_DLLIMPORT bCVector { public: enum bECoordinate { bECoordinate_X, bECoordinate_Y, bECoordinate_Z, bECoordinate_Count, bECoordinate_ForceDWORD = GE_FORCE_DWORD }; private: union { GEFloat m_fCoordinates[ bECoordinate_Count ]; struct { GEFloat m_fX; GEFloat m_fY; GEFloat m_fZ; }; }; public: static bCVector GE_STDCALL CrossProduct( bCVector const &, bCVector const & ); static GEFloat GE_STDCALL DotProduct( bCVector const &, bCVector const & ); static bCVector const & GE_STDCALL GetForward( void ); static bCVector const & GE_STDCALL GetRight( void ); static bCVector const & GE_STDCALL GetUnit( void ); static bCVector const & GE_STDCALL GetUp( void ); static bCVector const & GE_STDCALL GetZero( void ); public: GEFloat & AccessCoordinate( GEInt ); GEFloat (& AccessCoordinates( void )) [ bECoordinate_Count ]; GEFloat & AccessX( void ); GEFloat & AccessY( void ); GEFloat & AccessZ( void ); void Clear( void ); void CrossProduct( bCVector const & ); void Decompose( bCVector const &, bCVector &, bCVector & ) const; GEFloat GetAngleDeg( bCVector const & ) const; GEFloat GetAngleRad( bCVector const & ) const; GEFloat GetAngleUnitDeg( bCVector const & ) const; GEFloat GetAngleUnitRad( bCVector const & ) const; void GetAziElev( GEFloat &, GEFloat & ) const; void GetAziElevApprox( GEFloat &, GEFloat & ) const; void GetAziElevUnit( GEFloat &, GEFloat & ) const; GEFloat const & GetCoordinate( GEInt ) const; void GetCoordinate( GEInt, GEFloat & ) const; GEFloat const (& GetCoordinates( void ) const) [ bECoordinate_Count ]; void GetCoordinates( GEFloat &, GEFloat &, GEFloat & ) const; void GetCoordinates( GEFloat [ bECoordinate_Count ] ) const; bCVector GetCrossProduct( bCVector const & ) const; GEFloat GetDotProduct( bCVector const & ) const; bCVector GetInvScaled( bCVector const & ) const; bCVector GetInvScaled( GEFloat ) const; bCVector GetInvTransformed( bCMatrix3 const & ) const; bCVector GetInvTransformed( bCMatrix const & ) const; bCVector GetInvTransformedDirection( bCMatrix const & ) const; bCVector GetInvTranslated( bCVector const & ) const; bCVector GetInvTranslated( GEFloat ) const; bCVector GetInverted( void ) const; bCVector GetLerp( bCVector const &, GEFloat ) const; GEFloat GetMagnitude2D( bECoordinate ) const; GEFloat GetMagnitude( void ) const; GEFloat GetMagnitudeApprox( void ) const; GEFloat GetMagnitudeNormalize( void ); bCVector GetNormalized( void ) const; bCVector GetNormalizedSafe( void ) const; bCVector GetRemovedByDimension( bECoordinate ) const; bCVector GetRemovedByDimensionKeepMagnitude( bECoordinate ) const; bCVector GetRemovedByDimensionNormalize( bECoordinate ) const; bCVector GetScaled( bCVector const & ) const; bCVector GetScaled( GEFloat ) const; bCVector GetSlerp( bCVector const &, GEFloat ) const; GEFloat GetSquareMagnitude2D( bECoordinate ) const; GEFloat GetSquareMagnitude( void ) const; bCVector GetTransformed( bCMatrix3 const & ) const; bCVector GetTransformed( bCMatrix const & ) const; bCVector GetTransformedDirection( bCMatrix const & ) const; bCVector GetTranslated( bCVector const & ) const; bCVector GetTranslated( GEFloat ) const; GEFloat GetX( void ) const; void GetX( GEFloat & ) const; GEFloat GetY( void ) const; void GetY( GEFloat & ) const; GEFloat GetZ( void ) const; void GetZ( GEFloat & ) const; GEBool HasZeroMagnitude2D( bECoordinate ) const; GEBool HasZeroMagnitude2DApprox( bECoordinate ) const; GEBool HasZeroMagnitude( void ) const; GEBool HasZeroMagnitudeApprox( void ) const; void InvScale( bCVector const & ); void InvScale( GEFloat ); void InvTransform( bCMatrix3 const & ); void InvTransform( bCMatrix const & ); void InvTransformDirection( bCMatrix const & ); void InvTranslate( bCVector const & ); void InvTranslate( GEFloat ); void Invert( void ); GEBool IsEqual( bCVector const & ) const; GEBool IsValid( bCString const & ) const; bCVector const & Normalize( void ); bCVector const & NormalizeApprox( void ); bCVector const & NormalizeSafe( void ); void PrintDebug( bCString const & ) const; bCVector Reflect( bCVector const & ) const; void RemoveDimension( bECoordinate ); GEBool RemoveDimensionKeepMagnitude( bECoordinate ); void RemoveDimensionNormalize( bECoordinate ); void Scale( bCVector const & ); void Scale( GEFloat ); void SetCoordinate( GEInt, GEFloat ); void SetCoordinates( GEFloat, GEFloat, GEFloat ); void SetCoordinates( GEFloat const [ bECoordinate_Count ] ); void SetCrossProduct( bCVector const &, bCVector const & ); void SetLerp( bCVector const &, bCVector const &, GEFloat ); void SetSlerp( bCVector, bCVector, GEFloat ); void SetTransformed( bCVector const &, bCMatrix3 const & ); void SetTransformed( bCVector const &, bCMatrix const & ); void SetTransformedDirection( bCVector const &, bCMatrix const & ); void SetTransposedTransformed( bCVector const &, bCMatrix3 const & ); void SetTransposedTransformedDirection( bCVector const &, bCMatrix const & ); void SetVector( bCVector const & ); void SetVector( NxVec3 const & ); void SetVector( GEFloat ); void SetVector( GEFloat, GEFloat, GEFloat ); void SetX( GEFloat const & ); void SetY( GEFloat const & ); void SetZ( GEFloat const & ); bCString ToString( GEInt ) const; void Transform( bCMatrix3 const & ); void Transform( bCMatrix const & ); void TransformDirection( bCMatrix const & ); void Translate( bCVector const & ); void Translate( GEFloat ); void TransposedTransform( bCMatrix3 const & ); void TransposedTransformDirection( bCMatrix const & ); public: GEBool operator == ( bCVector const & ) const; GEBool operator != ( bCVector const & ) const; GEFloat & operator [] ( GEInt ); GEFloat const & operator [] ( GEInt ) const; operator NxVec3 & ( void ); operator NxVec3 const & ( void ) const; bCVector operator * ( bCVector const & ) const; bCVector operator * ( bCMatrix const & ) const; bCVector operator * ( GEFloat ) const; bCVector operator - ( bCVector const & ) const; bCVector operator - ( void ) const; bCVector operator + ( bCVector const & ) const; bCVector operator / ( bCMatrix const & ) const; bCVector operator / ( GEFloat ) const; bCVector & operator *= ( bCVector const & ); bCVector & operator *= ( bCMatrix3 const & ); bCVector & operator *= ( bCMatrix const & ); bCVector & operator *= ( GEFloat ); bCVector & operator += ( bCVector const & ); bCVector & operator -= ( bCVector const & ); bCVector & operator /= ( bCMatrix3 const & ); bCVector & operator /= ( bCMatrix const & ); bCVector & operator /= ( GEFloat ); bCIStream & operator << ( bCIStream & ); bCOStream & operator >> ( bCOStream & ) const; bCVector & operator = ( bCVector const & ); public: bCVector( NxVec3 const & ); explicit bCVector( GEFloat ); explicit bCVector( GEFloat const [ bECoordinate_Count ] ); bCVector( GEFloat, GEFloat, GEFloat ); bCVector( bCVector const & ); bCVector( void ); ~bCVector( void ); }; GE_ASSERT_SIZEOF( bCVector, 0x000C ) #pragma warning( pop ) typedef bCVector bCVector3; #endif
[ "gothicgame29@gmail.com" ]
gothicgame29@gmail.com
9e049dd6804d7bf2594fd1169e8b6767f2294979
930c00503cf6edb43325da48b4f12e38359a422d
/Numbering Roads.cpp
7b6865ad921e6a2e3673045cba3c8fab68161f8b
[]
no_license
merpatiboy/code_uri
c4b3a08fb865c04eabf24d8ef4e59eff72477490
976beeb8c85a2dea64b6f28aab47fd4966507812
refs/heads/master
2021-01-25T05:57:51.957812
2016-01-21T09:08:36
2016-01-21T09:08:36
42,811,024
1
0
null
null
null
null
UTF-8
C++
false
false
523
cpp
#include <iostream> #include <stdio.h> using namespace std; int main() { int x,y,Case = 1; while(1) { cin >> x; cin >> y; if(x==0 && y==0) break; int flag = 0; for(int a=1;a<=y;a++) { if(a*24>=x) { flag = a; break; } } if(flag==0) printf("Case %d: impossible\n",Case); else printf("Case %d: %d\n",Case,flag); Case ++; } }
[ "dicky12@mhs.if.its.ac.id" ]
dicky12@mhs.if.its.ac.id
b233496ab774cd3f8b35d3a21575d2da3e6ba72a
d171713d99ac27c4a369084dfa4b874823887648
/TCPclient/TCPbase.h
eb7880c59f45fc58dd81c15891880654ba2236fc
[]
no_license
bigeyesung/Modules
d1ed3fbc262c59dfa86cea93e29a271c09ff4b89
567859971c58fa7bc425696850123c13db068d0d
refs/heads/master
2020-09-02T19:38:18.446442
2019-11-07T21:27:41
2019-11-07T21:27:41
219,291,045
0
0
null
null
null
null
UTF-8
C++
false
false
518
h
#pragma once //boost #include <boost\asio.hpp> #include <string> #include <sstream> #define Bufsize 10000000 //Point using namespace std; using namespace boost::asio; typedef std::shared_ptr<ip::tcp::socket> pTcpServerRef; typedef boost::asio::io_service tIOService; typedef std::shared_ptr<tIOService> tIOServiceRef; class TCPbase { public: TCPbase(); ~TCPbase(); pTcpServerRef CreatSocket(); boost::asio::io_service & getIOService(); protected: char* Buf; private: tIOServiceRef m_ioService; };
[ "sungchenhsi@gmail.com" ]
sungchenhsi@gmail.com
8a3cf257943bfac4597db7fc0bd0a30ad2f2ab24
e7c978f192bbd964e3bdc2382f4a62b3f50b76c7
/ExternSort/ExSort.h
144006bccba154b1795a78574591de88735aa26a
[]
no_license
zheng-ji/ToyCollection
e169407217d2a1bda0b0114804a6a61aceb62ca6
7f2f171815f649afbee07383b4cd11992ffcf846
refs/heads/master
2023-03-15T12:15:07.193382
2022-06-11T12:49:16
2022-06-11T12:49:16
7,949,326
21
9
null
2023-03-04T20:54:15
2013-02-01T01:12:35
Go
UTF-8
C++
false
false
706
h
#ifndef EXTERN_SORT_H #define EXTERN_SORT_H #include <string.h> #include <stdlib.h> #include <stdio.h> #include <time.h> class ExternSort { public: void sort(); ExternSort(const char * input_file,const char* out_file,int count,int target_num); virtual ~ExternSort(); private: int m_count; int m_target_num; char * m_in_file; char * m_out_file; protected: int read_data(FILE *f,int a[],int n); void write_data(FILE *f,int a[],int n); char * temp_filename(int index); static int cmp_int(const void *a,const void *b); int memory_sort(); void merge_sort(int file_count); }; #endif
[ "407562752@qq.com" ]
407562752@qq.com
6a7ddd71571a1021f2a5b28cf9efa78392a9e8c3
c71d9862169295dd650390ca44f2ebeb2e6740af
/src/gui/kernel/qplatformclipboard_qpa.cpp
6bc76415b65d5a0b2069d9a28ec8f2fdcb1c5a9c
[]
no_license
maoxingda/qt-src
d23c8d0469f234f89fdcbdbe6f3d50fa16e7a0e3
e01aee06520bf526975b0bedafe78eb003b5ead6
refs/heads/master
2020-04-14T00:05:16.292626
2019-01-05T05:49:42
2019-01-05T05:49:42
163,524,224
1
0
null
null
null
null
UTF-8
C++
false
false
3,004
cpp
/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qplatformclipboard_qpa.h" #ifndef QT_NO_CLIPBOARD #include <QtGui/private/qapplication_p.h> QT_BEGIN_NAMESPACE class QClipboardData { public: QClipboardData(); ~QClipboardData(); void setSource(QMimeData* s) { if (s == src) return; delete src; src = s; } QMimeData* source() { return src; } private: QMimeData* src; }; QClipboardData::QClipboardData() { src = 0; } QClipboardData::~QClipboardData() { delete src; } Q_GLOBAL_STATIC(QClipboardData,q_clipboardData); QPlatformClipboard::~QPlatformClipboard() { } QMimeData *QPlatformClipboard::mimeData(QClipboard::Mode mode) { //we know its clipboard Q_UNUSED(mode); return q_clipboardData()->source(); } void QPlatformClipboard::setMimeData(QMimeData *data, QClipboard::Mode mode) { //we know its clipboard Q_UNUSED(mode); q_clipboardData()->setSource(data); } bool QPlatformClipboard::supportsMode(QClipboard::Mode mode) const { return mode == QClipboard::Clipboard; } void QPlatformClipboard::emitChanged(QClipboard::Mode mode) { QApplication::clipboard()->emitChanged(mode); } QT_END_NAMESPACE #endif //QT_NO_CLIPBOARD
[ "39357378+maoxingda@users.noreply.github.com" ]
39357378+maoxingda@users.noreply.github.com
5d42caafd7936770f9ac048427571cf31db36d53
f3ed9c1cc881d01efdd8a760853b18a905b210c3
/vessel_viewer/3dtoolDialog/hh3dtoolswidget.h
1a70fe5d0e00244671e099e5f9c7533bdf84535b
[]
no_license
greenleaf01-dev/vessel_osg
ca7f8ffe6d9ac70103f2eb326d7830489b798496
df29d359fdd030420703801c70398cc6a3f1a6ac
refs/heads/master
2023-05-08T23:46:28.488344
2021-05-30T06:45:56
2021-05-30T06:45:56
334,600,806
1
1
null
null
null
null
UTF-8
C++
false
false
1,371
h
#ifndef HH3DTOOLSWIDGET_H #define HH3DTOOLSWIDGET_H #include <QWidget> #include <QVariantMap> #include <QMouseEvent> #include <QPainter> #include "src_toolbar/hhtoolbarbuttonpanel.h" class IHHApplication; class HH3DToolsWidget : public QWidget { Q_OBJECT public: HH3DToolsWidget(QWidget *parent=0); ~HH3DToolsWidget(); void setIHHApplication(IHHApplication* pIApp); void init(const QVariantMap &params); void retranslateUi(); void setViewerHeight( int nHeight );//2017.9.5 wyp /*/TTQX-zhaozhengze-[B160725-038]【工具】三维工具,涂色问题 /*/ QToolButton* getToolBarButtonById(const QString& strID); //*/ HHToolbarButtonPanel* m_pHHToolbar_Pyramid; HHToolbarButtonPanel* m_pHHToolbar_Prism; signals: void sigSendEventToApp(bool); void signalClickButton(QString strID, QVariantMap param); public slots: void slotClickButton(QString strID, QVariantMap param); protected: virtual void closeEvent(QCloseEvent *event); private: void connectSignals(); void createToolBars(); void setWidgetsToLayout(); HHToolbarButtonPanel* m_pHHToolbar_left; HHToolbarButtonPanel* m_pHHToolbar_right_top; HHToolbarButtonPanel* m_pHHToolbar_right_bottom; QVariantMap m_params; IHHApplication* m_pIApp; QWidget* m_pView; double m_scale; }; #endif // HH3DTOOLSWIDGET_H
[ "43130324@qq.com" ]
43130324@qq.com
c173f247ae7cdfc970721e1954445d06294f7a2e
4524f2ac7ef8c5a033d40663f75256fb98033404
/GameSFML/CollidableUI.h
be1d9983fc1037ce3e69984140089841bd198172
[]
no_license
rodrigobmg/Game-SFML
93f8d36de153b79f756fd957d03ec496550c4be4
4d0436894cbbdd051f9dbe80174d0df449957e92
refs/heads/master
2020-07-02T22:00:29.251183
2019-03-13T15:14:20
2019-03-13T15:14:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,378
h
#pragma once #include <functional> #include <memory> #include "Box2D/Box2D.h" class CollidableUI { public: //contructor for GUI CollidableUI(b2World& box2DEngine, const b2Vec2& worldPos, float width, float height, bool isCircle = false) { { b2BodyDef bodyDef; bodyDef.type = b2_kinematicBody; //change body type bodyDef.fixedRotation = true; bodyDef.position.Set(worldPos.x, worldPos.y); //middle, bottom body = { box2DEngine.CreateBody(&bodyDef),[&box2DEngine](b2Body* pBody) {box2DEngine.DestroyBody(pBody); } }; } if (isCircle) { b2CircleShape kinematicCircle; kinematicCircle.m_radius = width; b2FixtureDef fixtureDef; fixtureDef.shape = &kinematicCircle; fixtureDef.isSensor = true; body->CreateFixture(&fixtureDef); } else { b2PolygonShape kinematicBox; kinematicBox.SetAsBox(std::max(width - 1.5f, 0.1f), std::max(height - 0.7f, 0.1f)); b2FixtureDef fixtureDef; fixtureDef.shape = &kinematicBox; fixtureDef.isSensor = true; body->CreateFixture(&fixtureDef); } } b2Body& getBody() { return *body; } const b2Body& getBody() const { return *body; } bool GetMouseState() const { return isMouseIn; } void MouseContact() { isMouseIn = true; } void MouseLeave() { isMouseIn = false; } private: std::unique_ptr<b2Body, std::function<void(b2Body*)>> body; bool isMouseIn = false; };
[ "duongnam267@gmail.com" ]
duongnam267@gmail.com
e05f235b70232ba22d1af92b4756eaacc5440393
b63498c31cdd1b7e66553144c7a2b94233141fe1
/codeforces/1249/E.cpp
980940b67dfaa9e33d580afb632ab6f8bf4c19ec
[]
no_license
ABHIINAV12/codeforces_code
63388646f6ddbe2f933d4c49ba2e32cf8b9cf9d5
5ba69c27fbce36e4e5d8920316c690cc4eaad9e4
refs/heads/master
2023-02-24T21:41:41.053263
2020-09-27T05:18:00
2021-01-26T07:33:59
332,990,962
0
0
null
null
null
null
UTF-8
C++
false
false
2,031
cpp
// You're not going to master the rest of your life in one day. // Just relax. Master the day. // Then just keep doing that every day. #include<bits/stdc++.h> using namespace std; #define int long long #define ld long double #define pb push_back #define ff first #define ss second #define f(i,x,n) for(int i=x;i<(int)n;++i) #define vi vector<int> #define vvi vector<vector<int>> #define vvvi vector<vector<vector<int>>> #define pq priority_queue<int> #define pqs priority_queue<int,vi,greater<int>> #define vpii vector<pair<int,int>> #define pii pair<int,int> #define all(x) x.begin(),x.end() #define sz(x) (int)x.size() #define mpi map<int,int> #define d1(x,y) cout<<x<<" ----------------------------- "<<y<<"\n" int mod=1e9+7; int fx(vector<int> &a){ sort(all(a)); int ret=0; f(i,1,sz(a)) ret+=a[i]-a[0]; int curr=ret; f(i,1,sz(a)){ int dec=a[i]-a[i-1]; dec*=(sz(a)-i); curr-=dec; ret+=curr; } return ret; } const int mxn=2200000; int a[mxn],n; int rec(int rem){ if(rem==-1) return 0; if(a[rem]==0) return 1ll<<(rem) + rec(rem-1); return rec(rem-1); } int32_t main(){ ios_base::sync_with_stdio(false);cin.tie(NULL); srand(time(0)); #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif int t=1; //cin>>t; while(t--){ int n,c; cin>>n>>c; int a[n-1]; f(i,0,n-1) cin>>a[i]; int b[n-1]; f(i,0,n-1) cin>>b[i]; int dp[n][2]; dp[0][0]=0; dp[0][1]=c; f(i,1,n){ dp[i][0]=min(dp[i-1][0]+a[i-1],dp[i-1][1]+a[i-1]); dp[i][1]=min(dp[i-1][0]+c+b[i-1],dp[i-1][1]+b[i-1]); } f(i,0,n) cout<<min(dp[i][0],dp[i][1])<<" "; cout<<"\n"; } return 0; } // ============== Notes =============== // /* the idea is to think of problem as when you arrived at state i, were you in elevator or in stairs ? i -- by stairs -- i-1 you were at stairs i -- by stairs -- i-1 you were at elevator i -- by elevator -- i-1 at stairs i -- by elevator -- i-1 at elevator too. */
[ "iit2018010@iiita.ac.in" ]
iit2018010@iiita.ac.in
b1149e242732d60f4bbc6c45f21503aa0d7453b5
c3de1f41bb7fd4e0160728c1493c3082df81f39f
/t1_n3_rational/Rational.cpp
3b82580476d7ecb55593cc94ad6fce4c65e64e02
[]
no_license
bogdanov-d-a/oop_lab5
1eeb02ab69458c153f6a8ee241e384b4ae18863f
08f0fa39b88814a2ace53ca603f012896f9ed3dc
refs/heads/master
2020-12-30T09:37:57.482889
2015-05-08T15:27:45
2015-05-08T15:27:45
34,907,802
0
0
null
null
null
null
UTF-8
C++
false
false
3,605
cpp
#include "stdafx.h" #include "Rational.h" using namespace std; CRational::CRational(int numerator, int denominator) :m_numerator(numerator) ,m_denominator(denominator) { if (m_denominator == 0) { m_numerator = 0; m_denominator = 1; } else if (m_denominator < 0) { m_numerator *= -1; m_denominator *= -1; } Normalize(); } int CRational::GetNumerator() const { return m_numerator; } int CRational::GetDenominator() const { return m_denominator; } double CRational::ToDouble() const { return (1.0 * m_numerator / m_denominator); } CRational const CRational::operator+() const { return *this; } CRational const CRational::operator-() const { return CRational(-m_numerator, m_denominator); } CRational& CRational::operator+=(CRational const& other) { *this = *this + other; return *this; } CRational& CRational::operator-=(CRational const& other) { *this = *this - other; return *this; } CRational& CRational::operator*=(CRational const& other) { *this = *this * other; return *this; } CRational& CRational::operator/=(CRational const& other) { *this = *this / other; return *this; } pair<int, CRational> CRational::ToCompoundFraction() const { int const signMultiplier = (m_numerator < 0) ? -1 : 1; return pair<int, CRational>(signMultiplier * (abs(m_numerator) / m_denominator), CRational(signMultiplier * (abs(m_numerator) % m_denominator), m_denominator)); } void CRational::Normalize() { const int gcd = GCD(abs(m_numerator), m_denominator); m_numerator /= gcd; m_denominator /= gcd; } unsigned GCD(unsigned a, unsigned b) { while (b != 0) { swap(a, b); b = b % a; } return (a != 0) ? a : 1; } unsigned LCM(unsigned a, unsigned b) { return (a / GCD(a, b) * b); } bool const operator==(CRational const& a, CRational const& b) { return (a.GetNumerator() == b.GetNumerator() && a.GetDenominator() == b.GetDenominator()); } bool const operator!=(CRational const& a, CRational const& b) { return !(a == b); } CRational const operator+(CRational const& a, CRational const& b) { unsigned const lcm = LCM(a.GetDenominator(), b.GetDenominator()); return CRational(a.GetNumerator() * (lcm / a.GetDenominator()) + b.GetNumerator() * (lcm / b.GetDenominator()), lcm); } CRational const operator-(CRational const& a, CRational const& b) { return (a + (-b)); } CRational const operator*(CRational const& a, CRational const& b) { return CRational(a.GetNumerator() * b.GetNumerator(), a.GetDenominator() * b.GetDenominator()); } CRational const operator/(CRational const& a, CRational const& b) { if (b.GetNumerator() == 0) { throw invalid_argument("Can't divide by zero"); } return CRational(a.GetNumerator() * b.GetDenominator(), a.GetDenominator() * b.GetNumerator()); } bool const operator<(CRational const& a, CRational const& b) { return (a.ToDouble() < b.ToDouble()); } bool const operator<=(CRational const& a, CRational const& b) { return (a == b || a < b); } bool const operator>(CRational const& a, CRational const& b) { return (a.ToDouble() > b.ToDouble()); } bool const operator>=(CRational const& a, CRational const& b) { return (a == b || a > b); } ostream& operator<<(ostream &out, CRational const& num) { return (out << num.GetNumerator() << "/" << num.GetDenominator()); } istream& operator>>(istream &in, CRational &num) { streamoff const startPos = in.tellg(); int numerator, denominator; if ((in >> numerator) && (in.get() == '/') && (in >> denominator)) { num = CRational(numerator, denominator); } else { in.seekg(startPos); in.setstate(in.rdstate() | ios_base::failbit); } return in; }
[ "bogdanov.d.a.1994@gmail.com" ]
bogdanov.d.a.1994@gmail.com
af5ebf8a6e80a27b663f0861936ee27a3dcecc02
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/drivers/published/sdk/inc/kcom.w
4a818e60f1ef9bba020f55bd283217edfe85deab
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
7,899
w
/*++ Copyright (c) Microsoft Corporation. All rights reserved. Module Name: kcom.h Abstract: Kernel COM --*/ #if !defined(_KS_) #error KS.H must be included before KCOM.H #endif // !defined(_KS_) #if !defined(_KCOM_) #define _KCOM_ #if defined(__cplusplus) extern "C" { #endif // defined(__cplusplus) #define STATIC_KoCreateObject \ 0x72CF721CL, 0x525A, 0x11D1, 0x9A, 0xA1, 0x00, 0xa0, 0xc9, 0x22, 0x31, 0x96 DEFINE_GUIDSTRUCT("72CF721C-525A-11D1-9AA1-00A0C9223196", KoCreateObject); #define KOSTRING_CreateObject L"{72CF721C-525A-11D1-9AA1-00A0C9223196}" #ifndef CLSCTX_KERNEL_SERVER #define CLSCTX_KERNEL_SERVER 0x00000200 #endif typedef NTSTATUS (*KoCreateObjectHandler)( IN REFCLSID ClassId, IN IUnknown* UnkOuter OPTIONAL, IN REFIID InterfaceId, OUT PVOID* Interface ); #undef INTERFACE #define INTERFACE INonDelegatedUnknown DECLARE_INTERFACE(INonDelegatedUnknown) { STDMETHOD(NonDelegatedQueryInterface)( THIS_ IN REFIID InterfaceId, OUT PVOID* Interface ) PURE; STDMETHOD_(ULONG,NonDelegatedAddRef)( THIS ) PURE; STDMETHOD_(ULONG,NonDelegatedRelease)( THIS ) PURE; }; #undef INTERFACE #define INTERFACE IIndirectedUnknown DECLARE_INTERFACE(IIndirectedUnknown) { STDMETHOD(IndirectedQueryInterface)( THIS_ IN REFIID InterfaceId, OUT PVOID* Interface ) PURE; STDMETHOD_(ULONG,IndirectedAddRef)( THIS ) PURE; STDMETHOD_(ULONG,IndirectedRelease)( THIS ) PURE; }; #if !defined(__cplusplus) || _MSC_VER < 1100 #define STATIC_IID_IKoInitializeParentDeviceObject\ 0x21B36996L, 0x8DE3, 0x11D1, 0x8A, 0xE0, 0x00, 0xA0, 0xC9, 0x22, 0x31, 0x96 DEFINE_GUIDEX(IID_IKoInitializeParentDeviceObject); #else interface __declspec(uuid("21B36996-8DE3-11D1-8AE0-00A0C9223196")) IKoInitializeParentDeviceObject; #endif #undef INTERFACE #define INTERFACE IKoInitializeParentDeviceObject DECLARE_INTERFACE_(IKoInitializeParentDeviceObject, IUnknown) { STDMETHOD(SetParentDeviceObject)( THIS_ IN PDEVICE_OBJECT ParentDeviceObject ) PURE; }; #ifndef COMDDKMETHOD #ifdef _COMDDK_ #define COMDDKMETHOD #else // !_COMDDK_ #define COMDDKMETHOD DECLSPEC_IMPORT #endif // _COMDDK_ #endif // !COMDDKMETHOD #ifdef _COMDDK_ #define COMDDKAPI #else // !_COMDDK_ #define COMDDKAPI DECLSPEC_IMPORT #endif // _COMDDK_ #if defined(__cplusplus) class CBaseUnknown : public INonDelegatedUnknown, public IIndirectedUnknown { protected: LONG m_RefCount; private: BOOLEAN m_UsingClassId; CLSID m_ClassId; protected: IUnknown* m_UnknownOuter; public: COMDDKMETHOD CBaseUnknown( IN REFCLSID ClassId, IN IUnknown* UnknownOuter OPTIONAL = NULL ); COMDDKMETHOD CBaseUnknown( IN IUnknown* UnknownOuter OPTIONAL = NULL ); COMDDKMETHOD virtual ~CBaseUnknown(); // INonDelegatedUnknown COMDDKMETHOD STDMETHODIMP_(ULONG) NonDelegatedAddRef(); COMDDKMETHOD STDMETHODIMP_(ULONG) NonDelegatedRelease(); COMDDKMETHOD STDMETHODIMP NonDelegatedQueryInterface( IN REFIID InterfaceId, OUT PVOID* Interface ); //IIndirectedUnknown COMDDKMETHOD STDMETHODIMP_(ULONG) IndirectedAddRef(); COMDDKMETHOD STDMETHODIMP_(ULONG) IndirectedRelease(); COMDDKMETHOD STDMETHODIMP IndirectedQueryInterface( IN REFIID InterfaceId, OUT PVOID* Interface ); }; #if !defined(DEFINE_ABSTRACT_UNKNOWN) #define DEFINE_ABSTRACT_UNKNOWN() \ STDMETHOD(QueryInterface)(THIS_ \ REFIID InterfaceId, \ PVOID* Interface \ ) PURE; \ STDMETHOD_(ULONG,AddRef)(THIS) PURE; \ STDMETHOD_(ULONG,Release)(THIS) PURE; #endif //!defined(DEFINE_ABSTRACT_UNKNOWN) #define DEFINE_STD_UNKNOWN() \ STDMETHODIMP NonDelegatedQueryInterface( \ REFIID InterfaceId, \ PVOID* Interface \ ); \ STDMETHODIMP QueryInterface( \ REFIID InterfaceId, \ PVOID* Interface \ ); \ STDMETHODIMP_(ULONG) AddRef(); \ STDMETHODIMP_(ULONG) Release(); #define IMPLEMENT_STD_UNKNOWN(Class) \ STDMETHODIMP Class::QueryInterface( \ REFIID InterfaceId, \ PVOID* Interface \ ) \ { \ return m_UnknownOuter->QueryInterface(InterfaceId, Interface);\ } \ STDMETHODIMP_(ULONG) Class::AddRef() \ { \ return m_UnknownOuter->AddRef(); \ } \ STDMETHODIMP_(ULONG) Class::Release() \ { \ return m_UnknownOuter->Release(); \ } #else // !__cplusplus COMDDKAPI void NTAPI KoRelease( IN REFCLSID ClassId ); #endif // !__cplusplus COMDDKAPI NTSTATUS NTAPI KoCreateInstance( IN REFCLSID ClassId, IN IUnknown* UnkOuter OPTIONAL, IN ULONG ClsContext, IN REFIID InterfaceId, OUT PVOID* Interface ); COMDDKAPI NTSTATUS NTAPI KoDriverInitialize( IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPathName, IN KoCreateObjectHandler CreateObjectHandler ); COMDDKAPI NTSTATUS NTAPI KoDeviceInitialize( IN PDEVICE_OBJECT DeviceObject ); #if defined(__cplusplus) } #endif // defined(__cplusplus) #ifdef __cplusplus #ifndef _NEW_DELETE_OPERATORS_ #define _NEW_DELETE_OPERATORS_ inline PVOID operator new ( size_t iSize, POOL_TYPE poolType ) { PVOID result = ExAllocatePoolWithTag(poolType,iSize,'wNCK'); if (result) { RtlZeroMemory(result,iSize); } return result; } inline PVOID operator new ( size_t iSize, POOL_TYPE poolType, ULONG tag ) { PVOID result = ExAllocatePoolWithTag(poolType,iSize,tag); if (result) { RtlZeroMemory(result,iSize); } return result; } inline void __cdecl operator delete ( PVOID pVoid ) { ExFreePool(pVoid); } #endif //!_NEW_DELETE_OPERATORS_ #if defined(_SYS_GUID_OPERATOR_EQ_) // Define _SYS_GUID_OPERATOR_EQ_ before including guiddef.h to get the aligned guid test. #define _GUID_OPERATORS_ #pragma message("WARNING: Using system operator==/!= for GUIDs") #endif #ifndef _GUID_OPERATORS_ #define _GUID_OPERATORS_ __inline BOOL operator==(const GUID& guidOne, const GUID& guidOther) { return IsEqualGUIDAligned(guidOne,guidOther); } __inline BOOL operator!=(const GUID& guidOne, const GUID& guidOther) { return !(guidOne == guidOther); } #endif // _GUID_OPERATORS_ #endif // __cplusplus #endif // !_KCOM_
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
a7b8d88426539d89967a8b93b46153dfbf966b42
333b58a211c39f7142959040c2d60b69e6b20b47
/Odyssey/DdmPTS/Rows.cpp
3af39aa8d1af024d3a38238b7933d772a96a52c7
[]
no_license
JoeAltmaier/Odyssey
d6ef505ade8be3adafa3740f81ed8d03fba3dc1a
121ea748881526b7787f9106133589c7bd4a9b6d
refs/heads/master
2020-04-11T08:05:34.474250
2015-09-09T20:03:29
2015-09-09T20:03:29
42,187,845
0
0
null
null
null
null
UTF-8
C++
false
false
39,073
cpp
/*************************************************************************/ // This material is a confidential trade secret and proprietary // information of ConvergeNet Technologies, Inc. which may not be // reproduced, used, sold or transferred to any third party without the // prior written consent of ConvergeNet Technologies, Inc. This material // is also copyrighted as an unpublished work under sections 104 and 408 // of Title 17 of the United States Code. Law prohibits unauthorized // use, copying or reproduction. // // (c) Copyright 1999 ConvergeNet Technologies, Inc. // All Rights Reserved. // // Description: // This file is the declaration of an object interface to the Row(s) // API of the Table Service. // // $Log: /Gemini/Odyssey/DdmPTS/Rows.cpp $ // // 36 10/27/99 12:06p Ewedel // Changed Initialize() members to take CPtsRecordBase* argument as row // data specifier. For non-varfield classes, this is added as an // overload. For varfield classes, this is now the *only* way of // specifying row data (i.e., varfield table rows must be derived from // CPtsRecordBase). // // 35 10/12/99 10:02a Jlane // Remove unused route by slot code. Use strlen()+1for name SGLs // throughout. // // 34 10/06/99 3:27p Sgavarre // add variable length fields // // 32 8/30/99 9:13a Sgavarre // clear getsgl size // // 31 8/28/99 5:39p Sgavarre // add dynamic reply buffers for returned data; no change to client // interface // // 30 8/13/99 4:58p Sgavarre // Update ModifyRow, DeleteRows for multiRow operation // // 29 7/22/99 3:11p Hdo // // 28 7/21/99 7:02p Hdo // Change the return type of Send() from STATUS to void // Call the user callback routine when error // Add error checking // // 27 7/19/99 9:12a Sgavarre // remove pcRowsModified as not being used by interface // // 26 7/13/99 10:04a Sgavarre // Fix DeleteRow parameter list: does not return rowId // // 25 7/12/99 5:00p Sgavarre // fix bugs in ModifyRow params // // 24 6/30/99 12:54p Mpanas // Change Tracef to TRACEF and set level 8 // for real trace info // // 23 6/22/99 3:55p Jhatwich // updated for windows // // 22 6/08/99 3:45p Sgavarre // remove reply payloads // // 21 6/07/99 8:05p Tnelson // Fix all warnings... // // 20 5/24/99 8:29p Hdo // // 19 5/24/99 10:41a Hdo // Remove the GetSgl call in HandlInsertRowReply // // 18 5/18/99 1:59p Jlane // In ModifyRow::Send() cbKeyFieldvalue and cbRowData were being reversed // in SGL creation. Don't do that. // // 17 5/11/99 10:55a Jhatwich // win32 // // 16 4/15/99 3:21p Jlane // Delete pMsg in all reply handlers. // // 15 4/07/99 5:16p Ewedel // Changed to use new payload size argument to Message() constructor. // // 3/22/99 HD Update the PTS document and clean up // 02/20/99 JL Pass sizeof(rowID) instead of sizeof(rowID*) in InsertRow(). // 01/13/99 HD Implement TSModifyRow, TSReadRow, TSDeleteRow // Modify TSInsert converting message payload to SGL // 12/14/98 HD modify the header file and implement it // 11/23/98 HD Created. // /*************************************************************************/ #include "Trace_Index.h" #define TRACE_INDEX TRACE_PTS #include "Odyssey_Trace.h" #include "Rows.h" /**********************************************************************/ // TSInsertRow Class Interface - Insert a new row into a table // /**********************************************************************/ // Initialize - Store the operation parameters in the object. // // Parameters: // pDdmServices - Pointer to client's DDM. Used to access Send(). // rgbTableName - Null terminated name of the table to create. // prgbRowData - Pointer to the row data to insert. // cbRowData - size of the row data in bytes. // pRowIDRet - Pointer to returned RowID for newly inserted row. // pCallback - Pointer to static callback function called upon reply. // pContext - Context pointer that is passed to the Callback method // /**********************************************************************/ STATUS TSInsertRow::Initialize( DdmServices *pDdmServices, String64 rgbTableName, void *prgbRowData, U32 cbRowData, rowID *pRowIDRet, pTSCallback_t pCallback, void *pContext ) { TRACE_ENTRY(TSInsertRow::Initialize); // Check for null in required parameters. if (( pDdmServices == NULL ) || ( rgbTableName == NULL ) || ( prgbRowData == NULL ) || ( cbRowData == 0 )) return ercBadParameter; // Initialize our base class. SetParentDdm(pDdmServices); m_pDdmServices = pDdmServices; // Stash parameters in member variables. strcpy(m_rgbTableName, rgbTableName); m_prgbRowData = prgbRowData; m_cbRowData = cbRowData; m_pRowIDRet = pRowIDRet; m_pCallback = pCallback; m_pContext = pContext; return OS_DETAIL_STATUS_SUCCESS; } /**********************************************************************/ // STATUS Send() - Packs up the payload, allocates a message and attaches the // payload, and sends the msg to the table service specifying our own // callback handler (HandleInsertRowsReply) to unpack the reply. // /**********************************************************************/ void TSInsertRow::Send() { TRACE_ENTRY(TSInsertRow::Send); STATUS status; // Allocate a message to send to the table service. Message *pMsg = new Message(TS_FUNCTION_INSERT_ROW, sizeof(InsertRowsPayload)); // Build the SGL, first insert TableName pMsg->AddSgl( INSERT_ROWS_MSG_TABLENAME_SGI, m_rgbTableName, strlen(m_rgbTableName)+1, SGL_SEND); // Insert the row data pMsg->AddSgl( INSERT_ROWS_MSG_DATA_BUFFER_SGI, m_prgbRowData, m_cbRowData, SGL_SEND); // Add the return buffer to the message as SGL pMsg->AddSgl( INSERT_ROWS_REPLY_ROWIDS_SGI, NULL, //m_pRowIDRet, NULL, //sizeof(rowID), SGL_DYNAMIC_REPLY ); //SGL_REPLY); // Call the Table Service to insert the row. Pass our object pointer as pContext // and specify our own callback handler to be called upon reply. status = DdmOsServices::Send(pMsg, NULL, REPLYCALLBACK(TSInsertRow, HandleInsertRowsReply)); // If the Send failed delete the message before returning if (status != OS_DETAIL_STATUS_SUCCESS) { TRACEF(TRACE_PTS, ("TSInsertRow::Send status=%d\n", status)); if( m_pDdmServices && m_pCallback) (m_pDdmServices->*m_pCallback)( m_pContext, status ); delete pMsg; delete this; } } // TSInsertRow::Send() /**************************************************************************/ // STATUS HandleInsertRowReply() - This is the function specified as the // callback in the Send method. It deletes the message and calls the // user's callback. // // Parameters: // pMsg - The replied message /**************************************************************************/ STATUS TSInsertRow::HandleInsertRowsReply(MessageReply *pMsg ) { TRACE_ENTRY(TSInsertRow::HandleInsertRowsReply); InsertRowsPayload *pInsertRowsReplyPayload; STATUS status = pMsg->DetailedStatusCode; void *pRowIDRet; U32 cbMaxRowID = 0; // Get a pointer to the reply payload and cast it to our reply structure. pInsertRowsReplyPayload = (InsertRowsPayload*)pMsg->GetPPayload(); m_cRowsInsertedRet = pInsertRowsReplyPayload->cIDsRet; // currently not returned to user if (m_pRowIDRet != NULL) { // Add the return buffer to the message as SGL pMsg->GetSgl ( INSERT_ROWS_REPLY_ROWIDS_SGI, &pRowIDRet, &cbMaxRowID); if (cbMaxRowID > (sizeof(rowID))) // only copy as many as will fit cbMaxRowID = sizeof(rowID); // currently, interface only allows one memcpy (m_pRowIDRet, pRowIDRet, cbMaxRowID); // copy the rowIDs into the user's buffer } // Call the user's specified callback. if( m_pDdmServices && m_pCallback) status = (m_pDdmServices->*m_pCallback)( m_pContext, status ); // Delete our message delete ourselves. delete pMsg; delete this; return status; } /**********************************************************************/ // TSInsertVLRow Class Interface - Insert a new variable length row into a table // /**********************************************************************/ // Initialize - Store the operation parameters in the object. // // Parameters: // pDdmServices - Pointer to client's DDM. Used to access Send(). // rgbTableName - Null terminated name of the table to create. // pRowData - Pointer to the row data to insert. This must be // a CPtsRecordBase derivative. // pRowIDRet - Pointer to returned RowID for newly inserted row. // pCallback - Pointer to static callback function called upon reply. // pContext - Context pointer that is passed to the Callback method // /**********************************************************************/ STATUS TSInsertVLRow::Initialize ( DdmServices *pDdmServices, String64 rgbTableName, const CPtsRecordBase *pRowData, rowID *pRowIDRet, pTSCallback_t pCallback, void *pContext ) { TRACE_ENTRY(TSInsertVLRow::Initialize); // Check for null in required parameters. if ((pDdmServices == NULL) || (rgbTableName == NULL) || (pRowData == NULL)) return ercBadParameter; // Initialize our base class. SetParentDdm(pDdmServices); m_pDdmServices = pDdmServices; // Stash parameters in member variables. strcpy(m_rgbTableName, rgbTableName); m_pRowData = pRowData; m_pRowIDRet = pRowIDRet; m_pCallback = pCallback; m_pContext = pContext; return OS_DETAIL_STATUS_SUCCESS; } /**********************************************************************/ // STATUS Send() - Packs up the payload, allocates a message and attaches the // payload, and sends the msg to the table service specifying our own // callback handler (HandleInsertRowsReply) to unpack the reply. // /**********************************************************************/ void TSInsertVLRow::Send() { TRACE_ENTRY(TSInsertVLRow::Send); STATUS status; // Allocate a message to send to the table service. Message *pMsg = new Message(TS_FUNCTION_INSERT_VLROW, sizeof(InsertVarLenRowPayload)); // Build the SGL, first insert TableName pMsg->AddSgl (INSERT_VLROW_MSG_TABLENAME_SGI, m_rgbTableName, strlen(m_rgbTableName)+1, SGL_SEND); // Insert the (potentially) variable length row data // (does conversion from varfield pointers into offsets) m_pRowData->WriteRecordAsSgl(pMsg, INSERT_VLROW_MSG_DATA_SGI); // Call the Table Service to insert the row. Pass our object pointer as pContext // and specify our own callback handler to be called upon reply. status = DdmOsServices::Send(pMsg, NULL, REPLYCALLBACK(TSInsertRow, HandleInsertVarLenRowReply)); // If the Send failed delete the message before returning if (status != OS_DETAIL_STATUS_SUCCESS) { TRACEF(TRACE_PTS, ("TSInsertRow::Send status=%d\n", status)); if( m_pDdmServices && m_pCallback) (m_pDdmServices->*m_pCallback)( m_pContext, status ); delete pMsg; delete this; } } // TSInsertVLRow::Send() /**************************************************************************/ // STATUS HandleInsertVarLenRowReply() - This is the function specified as the // callback in the Send method. It deletes the message and calls the // user's callback. // // Parameters: // pMsg - The replied message /**************************************************************************/ STATUS TSInsertVLRow::HandleInsertVarLenRowReply(MessageReply *pMsg ) { TRACE_ENTRY(TSInsertVLRow::HandleInsertVLRowReply); InsertVarLenRowPayload *pInsertVLRowPayload; STATUS status = pMsg->DetailedStatusCode; // Get a pointer to the reply payload and cast it to our reply structure. pInsertVLRowPayload = (InsertVarLenRowPayload*)pMsg->GetPPayload(); if (m_pRowIDRet != NULL) *m_pRowIDRet = pInsertVLRowPayload->rowId; // Call the user's specified callback. if( m_pDdmServices && m_pCallback) status = (m_pDdmServices->*m_pCallback)( m_pContext, status ); // Delete our message, and delete ourselves. delete pMsg; delete this; return status; } /**************************************************************************/ // TSModifyRow Class Interface - Modify the contents of a row in a table. // /**************************************************************************/ // Initialize() --> Store the operation parameters in the object. // // Parameters: // pDdmServices - Pointer to client's DDM. Used to access Send(). // rgbTableName - Null terminated name of the table. // rgbKeyFieldName - The key field name used to identify the row to modify // pKeyFieldValue - The key field value used to search for the row to modify. // cbKeyFieldValue - the size of the key field value in bytes. // prgbRowData - Pointer to the row data to insert. // cbRowData - size of the row data in bytes. // cRowsToModify - count of rows to modify; '0' means ALL that match // pcRowsModifiedRet - pointer to the U32 that will have the # of rows modified. // pRowIDRet - Pointer to returned RowID for newly modified row. // cbMaxRowIDs - size of buffer for rowIDs // pcRowsModifiedRet - pointer to the U32 that will have the # of rows modified.// pCallback - Pointer to static callback function called upon reply. // pContext - Context pointer that is passed to the Callback method // /**************************************************************************/ STATUS TSModifyRow::Initialize( DdmServices *pDdmServices, String64 rgbTableName, String64 rgbKeyFieldName, void *pKeyFieldValue, U32 cbKeyFieldValue, void *prgbRowData, U32 cbRowData, U32 cRowsToModify, U32 *pcRowsModifiedRet, rowID *pRowIDRet, U32 cbMaxRowID, pTSCallback_t pCallback, void* pContext ) { TRACE_ENTRY(TSModifyRow::Initialize); if ((pDdmServices == NULL) || (rgbTableName == NULL) || (rgbKeyFieldName == NULL) || (prgbRowData == NULL) || (cbRowData == 0)) return ercBadParameter; // Initialize our base class. SetParentDdm(pDdmServices); m_pDdmServices = pDdmServices; strcpy(m_rgbTableName, rgbTableName); strcpy(m_rgbKeyFieldName, rgbKeyFieldName); m_pKeyFieldValue = pKeyFieldValue; m_cbKeyFieldValue = cbKeyFieldValue; m_prgbRowData = prgbRowData; m_cbRowData = cbRowData; m_cRowsToModify = cRowsToModify; m_pcRowsModifiedRet = pcRowsModifiedRet; m_cbMaxRowID = cbMaxRowID; m_pRowIDRet = pRowIDRet; m_pCallback = pCallback; m_pContext = pContext; // we assume that we are given just a raw buffer, unless told otherwise m_fHasPtsRecBase = FALSE; return OS_DETAIL_STATUS_SUCCESS; } // TSModifyRow::Initialize() /**********************************************************************/ // STATUS Send() - Packs up the payload, allocates a message and attaches the // payload, and sends the msg to the table service specifying our own // callback handler (HandleInsertRowsReply) to unpack the reply. // /**********************************************************************/ void TSModifyRow::Send() { TRACE_ENTRY(TSModifyRow::Send); STATUS status; ModifyRowsPayload myModifyRowsPayload; // Allocate a message to send to the table service. Message *pMsg=new Message(TS_FUNCTION_MODIFY_ROW, sizeof (ModifyRowsPayload)); myModifyRowsPayload.cRowsToModify = m_cRowsToModify; // Add payload structure to the message. pMsg->AddPayload( &myModifyRowsPayload, sizeof(myModifyRowsPayload)); // Add the Table Name to SGL pMsg->AddSgl( MODIFY_ROWS_MSG_TABLENAME_SGI, m_rgbTableName, strlen(m_rgbTableName)+1, SGL_SEND); // Insert the key field name pMsg->AddSgl( MODIFY_ROWS_MSG_KEY_NAMES_SGI, m_rgbKeyFieldName, strlen(m_rgbKeyFieldName)+1, SGL_SEND); // Insert the key field value pMsg->AddSgl( MODIFY_ROWS_MSG_KEY_VALUES_SGI, m_pKeyFieldValue, m_cbKeyFieldValue, SGL_SEND); // Insert the data if (m_fHasPtsRecBase) { // write standard varfield-aware record to SGL ((CPtsRecordBase *) m_prgbRowData)-> WriteRecordAsSgl(pMsg, MODIFY_ROWS_MSG_DATA_BUFFER_SGI); } else { // write caller's data as raw buffer pMsg->AddSgl( MODIFY_ROWS_MSG_DATA_BUFFER_SGI, m_prgbRowData, m_cbRowData, SGL_SEND); } // Add the return buffer to the message as SGL pMsg->AddSgl( MODIFY_ROWS_REPLY_ROWIDS_SGI, NULL, //m_pRowIDRet, NULL, //m_cbMaxRowID, SGL_DYNAMIC_REPLY ); // Call the Table Service to modify the row. Pass our object pointer as pContext // and specify our own callback handler to be called upon reply. status = DdmServices::Send( pMsg, NULL, REPLYCALLBACK(TSModifyRow, HandleModifyRowsReply)); // If the Send failed delete the message before returning if (status != OS_DETAIL_STATUS_SUCCESS) { TRACEF(TRACE_PTS, ("TSModifyRow::Send status=%d\n", status)); if( m_pDdmServices && m_pCallback) (m_pDdmServices->*m_pCallback)( m_pContext, status ); delete pMsg; delete this; } } // TSModifyRow::Send() /**************************************************************************/ // STATUS HandleModifyRowsReply() - This is the function specified as the // callback in the Send method. It deletes the message and calls the // user's callback. // // Parameters: // pMsg - The replied message /**************************************************************************/ STATUS TSModifyRow::HandleModifyRowsReply(MessageReply *pMsg) { TRACE_ENTRY(TSModifyRow::HandleModifyRowsReply); ModifyRowsPayload *pModifyRowsReplyPayload; STATUS status = pMsg->DetailedStatusCode; void *pRowIDRet; U32 cbMaxRowID = 0; // Get a pointer to the reply payload and cast it to our reply structure. pModifyRowsReplyPayload = (ModifyRowsPayload*)pMsg->GetPPayload(); if (m_pcRowsModifiedRet != NULL) *m_pcRowsModifiedRet = pModifyRowsReplyPayload->cRowsModifiedRet; if (m_pRowIDRet != NULL ) { pMsg->GetSgl( MODIFY_ROWS_REPLY_ROWIDS_SGI, &pRowIDRet, &cbMaxRowID ); if (cbMaxRowID > m_cbMaxRowID) // only copy as many as will fit cbMaxRowID = m_cbMaxRowID; memcpy (m_pRowIDRet, pRowIDRet, cbMaxRowID); // copy the rowIDs into the user's buffer } // Call the user's specified callback. if( m_pDdmServices && m_pCallback) status = (m_pDdmServices->*m_pCallback)( m_pContext, status ); // Delete our message, delete ourselves. delete pMsg; delete this; return status; } // TSModifyRow::HandleModifyRowReply() /**************************************************************************/ // TSReadRow Class Interface - Read a specified row from the specified table // /**************************************************************************/ // Initialize - Store the operation parameters in the object. // // Parameters: // pDdmServices - Pointer to client's DDM. Used to access Send(). // rgbTableName - Null terminated name of the table. // rgbKeyFieldName - The key field name used to identify the row to modify // pKeyFieldValue - The key field value used to search for the row to modify. // cbKeyFieldValue - the size of the key field value in bytes. // prgbRowDataRet - Pointer to the row data to insert. // cbRowDataRetMax - size of the row data in bytes. // pcRowsReadRet - pointer to count of rows read. // pCallback - Pointer to static callback function called upon reply. // pContext - Context pointer that is passed to the Callback method // /**************************************************************************/ STATUS TSReadRow::Initialize( DdmServices *pDdmServices, String64 rgbTableName, String64 prgbKeyFieldName, void *pKeyFieldValue, U32 cbKeyFieldValue, void *prgbRowDataRet, U32 cbRowDataRetMax, U32 *pcRowsReadRet, pTSCallback_t pCallback, void *pContext ) { TRACE_ENTRY(TSReadRow::Initialize); if ((pDdmServices == NULL) || (rgbTableName == NULL) || (prgbKeyFieldName == NULL)) return ercBadParameter; // Initialize our base class. SetParentDdm(pDdmServices); // Stash parameters in member variables. m_pDdmServices = pDdmServices; strcpy(m_rgbTableName, rgbTableName); strcpy(m_rgbKeyFieldName, prgbKeyFieldName); m_pKeyFieldValue = pKeyFieldValue; m_cbKeyFieldValue = cbKeyFieldValue; m_prgbRowDataRet = prgbRowDataRet; m_cbRowDataRetMax = cbRowDataRetMax; m_pcRowsReadRet = pcRowsReadRet; m_pCallback = pCallback; m_pContext = pContext; return OS_DETAIL_STATUS_SUCCESS; } // TSReadRow::Initialize /**********************************************************************/ // STATUS Send() - Packs up the payload, allocates a message and attaches the // payload, and sends the msg to the table service specifying our own // callback handler (HandleReadRowsReply) to unpack the reply. // /**********************************************************************/ void TSReadRow::Send() { TRACE_ENTRY(TSReadRow::Send); STATUS status; // Allocate a message to send to the table service. Message *pMsg=new Message(TS_FUNCTION_READ_ROW, sizeof(ReadRowsPayload)); // Add the Table Name to SGL pMsg->AddSgl( READ_ROWS_MSG_TABLENAME_SGI, m_rgbTableName, strlen(m_rgbTableName)+1, SGL_SEND); // Insert the key field name pMsg->AddSgl( READ_ROWS_MSG_KEY_NAMES_SGI, m_rgbKeyFieldName, strlen(m_rgbKeyFieldName)+1, SGL_SEND); // Insert the key field value pMsg->AddSgl( READ_ROWS_MSG_KEY_VALUES_SGI, m_pKeyFieldValue, m_cbKeyFieldValue, SGL_SEND); // Add the returned data buffer to the message as a SGL item. pMsg->AddSgl( READ_ROWS_REPLY_DATA_BUFFER_SGI, NULL, // m_prgbRowDataRet, NULL, // m_cbRowDataRetMax, SGL_DYNAMIC_REPLY ); // Call the Table Service to read the table. Pass our object pointer as pContext // and specify our own callback handler to be called upon reply. status = DdmServices::Send(pMsg, NULL, REPLYCALLBACK(TSReadRow, HandleReadRowsReply)); // If the Send failed delete the message before returning if (status != OS_DETAIL_STATUS_SUCCESS) { TRACEF(TRACE_PTS, ("TSReadRow::Send status=%d\n", status)); if( m_pDdmServices && m_pCallback) (m_pDdmServices->*m_pCallback)( m_pContext, status ); delete pMsg; delete this; } } // TSReadRow::Send /**************************************************************************/ // STATUS HandleReadRowsReply() - This is the function specified as the // callback in the Send method. It deletes the message and calls the // user's callback. // // Parameters: // pMsg - The replied message /**************************************************************************/ STATUS TSReadRow::HandleReadRowsReply(MessageReply *pMsg) { TRACE_ENTRY(TSReadRow::HandleReadRowsReply); ReadRowsPayload *pReadRowsPayload; STATUS status = pMsg->DetailedStatusCode; U32 cbRowDataRetMax = 0; // Get a pointer to the reply payload and cast it to our reply structure. pReadRowsPayload = (ReadRowsPayload*)pMsg->GetPPayload(); // Return the number of rows read if the caller so desires. if (m_pcRowsReadRet) *m_pcRowsReadRet = pReadRowsPayload->cRowsReadRet; if (m_prgbRowDataRet != NULL) { // copy the caller's returned data into the caller's own buffer // find out how big SGL data is cbRowDataRetMax = pMsg->GetSglDataSize (READ_ROWS_REPLY_DATA_BUFFER_SGI); // only copy as much as will fit in caller's buffer if (cbRowDataRetMax > m_cbRowDataRetMax) cbRowDataRetMax = m_cbRowDataRetMax; pMsg->CopyFromSgl (READ_ROWS_REPLY_DATA_BUFFER_SGI, 0, m_prgbRowDataRet, cbRowDataRetMax); } // Call the user's specified callback. if( m_pDdmServices && m_pCallback) status = (m_pDdmServices->*m_pCallback)( m_pContext, status ); // Delete our message delete ourselves. delete pMsg; delete this; return status; } // TSReadRow::HandleTSReadRowReply /**********************************************************************/ // TSReadVLRow Class Interface - Read a new variable length row into a table // /**********************************************************************/ // Initialize - Store the operation parameters in the object. // // Parameters: // pDdmServices - Pointer to client's DDM. Used to access Send(). // rgbTableName - Null terminated name of the table to create. // rgbKeyFieldName - The key field name used to identify the row to modify // pKeyFieldValue - The key field value used to search for the row to modify. // cbKeyFieldValue - the size of the key field value in bytes. // ppRowDataRet - Pointer to user pointer where address of the row data is returned. // pcbRowDataRet - Return pointer where size of the row data is written. // pcRowsReadRet - pointer to count of rows read. // // pCallback - Pointer to static callback function called upon reply. // pContext - Context pointer that is passed to the Callback method // /**********************************************************************/ STATUS TSReadVLRow::Initialize ( DdmServices *pDdmServices, String64 rgbTableName, String64 prgbKeyFieldName, void *pKeyFieldValue, U32 cbKeyFieldValue, CPtsRecordBase **ppRowDataRet, U32 *pcbRowDataRet, U32 *pcRowsReadRet, pTSCallback_t pCallback, void *pContext ) { TRACE_ENTRY(TSReadVLRow::Initialize); // Check for null in required parameters. if ((pDdmServices == NULL) || (rgbTableName == NULL) || (prgbKeyFieldName == NULL)) return ercBadParameter; // Initialize our base class. SetParentDdm(pDdmServices); m_pDdmServices = pDdmServices; strcpy(m_rgbTableName, rgbTableName); strcpy(m_rgbKeyFieldName, prgbKeyFieldName); m_pKeyFieldValue = pKeyFieldValue; m_cbKeyFieldValue = cbKeyFieldValue; m_ppRowDataRet = ppRowDataRet; m_pcbRowDataRet = pcbRowDataRet; m_pcRowsReadRet = pcRowsReadRet; m_pCallback = pCallback; m_pContext = pContext; return OS_DETAIL_STATUS_SUCCESS; } /**********************************************************************/ // Send() - Packs up the payload, allocates a message and attaches the // payload, and sends the msg to the table service specifying our own // callback handler (HandleInsertRowsReply) to unpack the reply. // /**********************************************************************/ void TSReadVLRow::Send() { TRACE_ENTRY(TSReadVLRow::Send); STATUS status; // Allocate a message to send to the table service. Message *pMsg = new Message(TS_FUNCTION_READ_VARLEN_ROW, sizeof(ReadVarLenRowsPayload)); // Build the SGL, first insert TableName pMsg->AddSgl (READ_VLROWS_MSG_TABLENAME_SGI, m_rgbTableName, strlen(m_rgbTableName)+1, SGL_SEND); // Insert the key field name pMsg->AddSgl (READ_VLROWS_MSG_KEY_NAMES_SGI, m_rgbKeyFieldName, strlen(m_rgbKeyFieldName)+1, SGL_SEND); // Insert the key field value pMsg->AddSgl (READ_VLROWS_MSG_KEY_VALUES_SGI, m_pKeyFieldValue, m_cbKeyFieldValue, SGL_SEND); if (m_ppRowDataRet != NULL ) { // Add the return row data SGL item // NULL pb indicates data buffer to be alloc'd by transport. // NULL cb will tell transport to get allocate size when the // PTS calls GetSGL. READ_VLROWS_REPLY_ROWDATA_SGI pMsg->AddSgl ( READ_VLROWS_REPLY_ROWDATA_SGI, NULL, NULL, SGL_DYNAMIC_REPLY ); } // no support for separate varfield descriptors SGL now //* if (m_ppVarLenFieldsRet != NULL ) //* { // Add the return ID and optional row data buffer as an SGL item //* // NULL pb indicates data buffer to be alloc'd by transport. //* pMsg->AddSgl ( READ_VLROWS_REPLY_VLFS_SGI, //* NULL, //* NULL, //* SGL_DYNAMIC_REPLY); //* } // Call the Table Service to insert the row. Pass our object pointer as pContext // and specify our own callback handler to be called upon reply. status = DdmOsServices::Send(pMsg, NULL, REPLYCALLBACK(TSInsertRow, HandleReadVarLenRowReply)); // If the Send failed delete the message before returning if (status != OS_DETAIL_STATUS_SUCCESS) { TRACEF(TRACE_PTS, ("TSInsertRow::Send status=%d\n", status)); if( m_pDdmServices && m_pCallback) (m_pDdmServices->*m_pCallback)( m_pContext, status ); delete pMsg; delete this; } } // TSReadVLRow::Send() /**************************************************************************/ // STATUS HandleReadVarLenRowReply() - This is the function specified as the // callback in the Send method. It deletes the message and calls the // user's callback. // // Parameters: // pMsg - The replied message /**************************************************************************/ STATUS TSReadVLRow::HandleReadVarLenRowReply(MessageReply *pMsg ) { TRACE_ENTRY(TSReadVLRow::HandleReadVLRowReply); ReadVarLenRowsPayload *pReadVLRowPayload; STATUS status = pMsg->DetailedStatusCode; U8 *pLocalBuf; // buffer to free, sometimes U8 *pbRowData; // pointer to contig. row data U32 cbRowData; // count of bytes in *pbRowData CPtsRecordBase *pCurRec; U32 cbTotalRecSize; // Get a pointer to the reply payload and cast it to our reply structure. pReadVLRowPayload = (ReadVarLenRowsPayload*)pMsg->GetPPayload(); // Return the number of rows read if the caller so desires. if (m_pcRowsReadRet) *m_pcRowsReadRet = pReadVLRowPayload->cRowsReadRet; // Get the return record buffer if the user wanted it. if ((m_ppRowDataRet != NULL) && (m_pcbRowDataRet != NULL)) { // user wants data, figure out what we have to do to give it to them. // we have to do different stuff, based on whether the returned // SGL data is large enough to be fragmented if (pMsg->GetCFragment (READ_VLROWS_REPLY_ROWDATA_SGI) <= 1) { // cool, all data fits in a single, contiguous SGL fragment. // Just return a pointer to that fragment's own buffer. pMsg->GetSgl ( READ_VLROWS_REPLY_ROWDATA_SGI, (void **) m_ppRowDataRet, &cbRowData); // indicate that we have no allocation to free. pLocalBuf = NULL; } else { // whoops, SGL consists of multiple fragments. So we make // a copy, which uses a single contiguous buffer. pLocalBuf = (U8 *) pMsg->GetSglDataCopy (READ_VLROWS_REPLY_ROWDATA_SGI, &cbRowData); // return allocated buf ptr to requestor also *m_ppRowDataRet = (CPtsRecordBase *) pLocalBuf; } // if user wanted data size, let 'em know if (m_pcbRowDataRet != NULL) { *m_pcbRowDataRet = cbRowData; } // by hook or by crook, we have a contiguous buffer // containing the SGL's complete data. // now we scoot through it, converting each enclosed record // into pointer-normal form. assert (*m_ppRowDataRet != NULL); pbRowData = (U8 *) *m_ppRowDataRet; while (cbRowData > sizeof (CPtsRecordBase)) { pCurRec = (CPtsRecordBase *) pbRowData; // returned records should always be complete cbTotalRecSize = pCurRec->TotalRecSize(); assert (cbRowData >= cbTotalRecSize); if (cbRowData >= cbTotalRecSize) { // convert this record's offsets into pointers pCurRec->ConvertVarFieldOffsetsToPointers(cbTotalRecSize); } else { // whoops, all done. break; } // advance to next row cbRowData -= cbTotalRecSize; pbRowData += cbTotalRecSize; } // shouldn't have any left over bits assert (cbRowData == 0); } else { // user doesn't want row data (how peculiar!), so flag that we have // no buffer to delete pLocalBuf = NULL; } // right now, we ignore the separate varfield descriptors SGL item //* if ((m_ppVarLenFieldsRet != NULL) && (m_pcbVarLenFieldsRet)) //* { //* // Add the return buffer to the message as SGL //* pMsg->GetSgl ( READ_VLROWS_REPLY_VLFS_SGI, //* m_ppVarLenFieldsRet, //* m_pcbVarLenFieldsRet); //* } // Call the user's specified callback. if( m_pDdmServices && m_pCallback) status = (m_pDdmServices->*m_pCallback)( m_pContext, status ); // Delete our message, our optional row data buffer, and delete ourselves. delete pMsg; delete [] pLocalBuf; delete this; return status; } /**************************************************************************/ // TSDeleteRow Class Interface - Delete a specified row from the specified table // /**************************************************************************/ // Initialize - Store the operation parameters in the object. // // Parameters: // pDdmServices - Pointer to client's DDM. Used to access Send(). // rgbTableName - Null terminated name of the table. // rgbKeyFieldName - The key field name used to identify the row to modify // pKeyFieldValue - The key field value used to search for the row to modify. // cbKeyFieldValue - the size of the key field value in bytes. // pcRowsDel - Pointer to returned number of rows deleted // pCallback - Pointer to static callback function called upon reply. // pContext - Context pointer that is passed to the Callback method // /**************************************************************************/ STATUS TSDeleteRow::Initialize( DdmServices *pDdmServices, String64 rgbTableName, String64 prgbKeyFieldName, void *pKeyFieldValue, U32 cbKeyFieldValue, U32 cRowsToDelete, U32 *pcRowsDelRet, pTSCallback_t pCallback, void *pContext ) { TRACE_ENTRY(TSDeleteRow::Initialize); if ((pDdmServices == NULL) || (rgbTableName == NULL) || (prgbKeyFieldName == NULL)) return ercBadParameter; // Initialize our base class. SetParentDdm(pDdmServices); // Stash parameters in member variables. m_pDdmServices = pDdmServices; strcpy(m_rgbTableName, rgbTableName); strcpy(m_rgbKeyFieldName, prgbKeyFieldName); m_pKeyFieldValue = pKeyFieldValue; m_cbKeyFieldValue = cbKeyFieldValue; m_cRowsToDelete = cRowsToDelete; m_pcRowsDelRet = pcRowsDelRet; m_pCallback = pCallback; m_pContext = pContext; return OS_DETAIL_STATUS_SUCCESS; } // TSDeleteRow::Initialize /**********************************************************************/ // STATUS Send() - Packs up the payload, allocates a message and attaches the // payload, and sends the msg to the table service specifying our own // callback handler (HandleDeleteRowsReply) to unpack the reply. // /**********************************************************************/ void TSDeleteRow::Send() { TRACE_ENTRY(TSDeleteRow::Send); STATUS status; DeleteRowsPayload myDeleteRowsPayload; // Allocate a message to send to the table service. Message *pMsg=new Message(TS_FUNCTION_DELETE_ROW, sizeof(DeleteRowsPayload)); myDeleteRowsPayload.cRowsToDelete = m_cRowsToDelete; // Add payload structure to the message. pMsg->AddPayload( &myDeleteRowsPayload, sizeof(myDeleteRowsPayload)); // Add the Table Name to SGL pMsg->AddSgl( DELETE_ROWS_MSG_TABLENAME_SGI, m_rgbTableName, strlen(m_rgbTableName)+1, SGL_SEND); // Insert the key field name pMsg->AddSgl( DELETE_ROWS_MSG_KEY_NAMES_SGI, m_rgbKeyFieldName, strlen(m_rgbKeyFieldName)+1, SGL_SEND); // Insert the key field value pMsg->AddSgl( DELETE_ROWS_MSG_KEY_VALUES_SGI, m_pKeyFieldValue, m_cbKeyFieldValue, SGL_SEND); // Call the Table Service to delete the row. Pass our object pointer as pContext // and specify our own callback handler to be called upon reply. status = DdmServices::Send(pMsg, NULL, REPLYCALLBACK(TSDeleteRow, HandleDeleteRowsReply)); // If the Send failed delete the message before returning if (status != OS_DETAIL_STATUS_SUCCESS) { TRACEF(TRACE_PTS, ("TSDeleteRow::Send status=%d\n", status)); if( m_pDdmServices && m_pCallback) (m_pDdmServices->*m_pCallback)( m_pContext, status ); delete pMsg; delete this; } } // TSDeleteRow::Send /**************************************************************************/ // STATUS HandleDeleteRowsReply() - This is the function specified as the // callback in the Send method. It deletes the message and calls the // user's callback. // // Parameters: // pMsg - The replied message /**************************************************************************/ STATUS TSDeleteRow::HandleDeleteRowsReply(MessageReply *pMsg) { TRACE_ENTRY(TSDeleteRow::HandleDeleteRowsReply); DeleteRowsPayload *pDeleteRowsReplyPayload; STATUS status = pMsg->DetailedStatusCode; // Get a pointer to the reply payload and cast it to our reply structure. pDeleteRowsReplyPayload = (DeleteRowsPayload*)pMsg->GetPPayload(); // Return count of rows deleted if the caller so desires. if (m_pcRowsDelRet) *m_pcRowsDelRet = pDeleteRowsReplyPayload->cRowsDeletedRet; // Call the user's specified callback. if( m_pDdmServices && m_pCallback) status = (m_pDdmServices->*m_pCallback)( m_pContext, status ); // Delete our message delete ourselves. delete pMsg; delete this; return status; } // TSDeleteRow::HandleDeleteRowReply // end of file
[ "joe.altmaier@sococo.com" ]
joe.altmaier@sococo.com
d67ab432a337181236076b22f3f24f5e66884cbd
4cc51211ef649d7d2bb9a7777ba3d78d2e405849
/codeforces/615A.cpp
225240647a28ca551db5c4d9ec5de95f6580988e
[ "MIT" ]
permissive
Shisir/Online-Judge
0044fe7d52e8c922dbc491fc00abbb2915ce995e
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
refs/heads/master
2021-01-12T14:59:50.878107
2016-11-08T16:22:13
2016-11-08T16:22:13
71,658,699
0
0
null
null
null
null
UTF-8
C++
false
false
320
cpp
#include <bits/stdc++.h> using namespace std; int arr[101]; int main() { int n,m,a,b,c; scanf("%d%d",&n,&m); for(int i=0; i<n; i++) { scanf("%d",&c); for(int j=0; j<c; j++) { scanf("%d",&a); arr[a]=1; } } for(int i=1; i<=m; i++) if(arr[i]==0) return printf("NO\n"),0; return printf("YES\n"), 0; }
[ "nazmul295iit@gmail.com" ]
nazmul295iit@gmail.com
6d80e86ec54cfbfb2cf22a65e06627398afd45e5
6f3324aa80a233dd9a28f08f179420ec19975d03
/01-职工管理系统/职工管理系统/boos.cpp
70d553024f924e5391d757fbb925b79b9849c2e7
[]
no_license
LionelBrain/cpp_learn
51b61727a4cadfdafd0a614d406000bf6efd4352
c8f0115a9146d947a459791748b91e15d34885a9
refs/heads/master
2023-01-01T21:48:13.091581
2020-10-23T03:11:14
2020-10-23T03:11:14
306,496,845
0
0
null
null
null
null
GB18030
C++
false
false
497
cpp
#include <iostream> #include "boos.h" using namespace std; // 构造函数 Boos::Boos(int id, string name, int did) { this->m_Id = id; this->m_Name = name; this->m_DId = did; } // 显示个人信息 void Boos::show_info() { cout << "职工编号: " << this->m_Id << "\t职工姓名: " << this->m_Name << "\t岗位: " << this->get_dep_name() << "\t岗位职责: 负责公司的日常运作." << endl; } // 获取岗位信息 string Boos::get_dep_name() { return string("总裁"); }
[ "libluewater@icloud.com" ]
libluewater@icloud.com
c627cded4a9830fa3d7eb93b882f66bca8b80f91
8d880f5378e350a2b35ddc5c1236b701b7586ab8
/Lib3D/Mesh3d.cpp
11c79170f3383da5287f670d1084b97f33b2911c
[]
no_license
heguanyu/JointDetection
64b8df1ab38275cedc473f21f0c753e3210a1b24
eb7cecdb612abb96667d31908dd684b2b82a6503
refs/heads/master
2020-04-09T03:04:03.144236
2013-11-14T18:57:33
2013-11-14T18:57:33
14,403,926
1
0
null
null
null
null
UTF-8
C++
false
false
60,749
cpp
//******************************************** // Mesh3d.cpp //******************************************** // class CMesh3d //******************************************** // alliez@usc.edu // Created : 15/01/98 // Modified : 15/01/98 //******************************************** #include "stdafx.h" #include <math.h> #include "Base3d.h" #include "Mesh3d.h" #include "ColorRamp.h" #include "AVLInd.h" // Gaspard Breton's stuff #include "WmfTools.h" ////////////////////////////////////////////// // CONSTRUCTORS ////////////////////////////////////////////// //******************************************** // Constructor //******************************************** CMesh3d::CMesh3d() { m_ListDone = 0; m_Modified = 1; m_NormalBinding = NORMAL_PER_FACE; m_ColorBinding = COLOR_PER_VERTEX; m_Name = _T("Mesh"); // Texture m_IndexTexture = -1; m_pTextureCoordinate = NULL; m_pTextureCoordinateIndex = NULL; m_Show = 1; } //******************************************** // Destructor //******************************************** CMesh3d::~CMesh3d() { Free(); } //******************************************** // Free //******************************************** void CMesh3d::Free() { //TRACE("Cleanup mesh %x\n",this); m_ArrayVertex.Free(); m_ArrayFace.Free(); m_ArrayLine.Free(); if(m_pTextureCoordinate != NULL) delete [] m_pTextureCoordinate; if(m_pTextureCoordinateIndex != NULL) delete [] m_pTextureCoordinateIndex; } ////////////////////////////////////////////// // OPENGL ////////////////////////////////////////////// //******************************************** // BuildList //******************************************** int CMesh3d::glBuildList(int DEBUGMODE) { //TRACE(" Start building list ...\n"); // Check for valid mesh if(m_ArrayVertex.GetSize() == 0 || (m_ArrayFace.GetSize() == 0 && m_ArrayLine.GetSize()==0)) { TRACE("CMesh3d::BuildList : empty mesh\n"); return 0; } if(!m_Modified && m_ListDone) return 0; // Erase last list ::glDeleteLists(m_ListOpenGL,1); // Search for a new list m_ListOpenGL = ::glGenLists(1); if(m_ListOpenGL == 0) { TRACE("CMesh3d::BuildList : unable to build DrawList\n"); return 0; } // Start list ::glNewList(m_ListOpenGL,GL_COMPILE_AND_EXECUTE); glDrawDirect(DEBUGMODE); ::glEndList(); // List is done now m_ListDone = 1; m_Modified = 0; return 1; } int CMesh3d::drawIt(int DEBUGMODE) { return glDrawDirect(DEBUGMODE); } //********************************* // glDrawDirect //********************************* int CMesh3d::glDrawDirect(int DEBUGMODE) { unsigned int NbVertex = (unsigned int)m_ArrayVertex.GetSize(); unsigned int NbFace = (unsigned int)m_ArrayFace.GetSize(); unsigned int NbLine = (unsigned int)m_ArrayLine.GetSize(); if((!NbVertex)) return 0; if((!NbFace) && (!NbLine)) return 0; CFace3d *pFace; CLine3d *pLine; CVector3d *pVector; CColor *pColorPrevious; if(DEBUGMODE==CHECKVISIBILITY) { glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); } if(DEBUGMODE==NODEBUG) { glDisable(GL_BLEND); } glShadeModel(GL_SMOOTH); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, GetMaterial()->GetAmbient()); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, GetMaterial()->GetDiffuse()); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, GetMaterial()->GetSpecular()); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, GetMaterial()->GetEmission()); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, GetMaterial()->GetShininess()); ::glPushMatrix(); // Position / translation / scaling glTranslatef(m_Transform.GetTranslation()->x(), m_Transform.GetTranslation()->y(), m_Transform.GetTranslation()->z()); glScalef(m_Transform.GetScale()->x(), m_Transform.GetScale()->y(), m_Transform.GetScale()->z()); glRotatef(m_Transform.GetValueRotation(), m_Transform.GetRotation()->x(), m_Transform.GetRotation()->y(), m_Transform.GetRotation()->z()); // Init color pFace = m_ArrayFace[0]; pColorPrevious = pFace->GetColor(); ::glColor3ub(pFace->GetColor()->r(),pFace->GetColor()->g(),pFace->GetColor()->b()); ::glLineWidth(0.5f); ::glBegin(GL_LINES); for(unsigned int i=0;i<NbLine;i++) { pLine = m_ArrayLine[i]; ASSERT(pLine!=NULL); glVertex3f(pLine->v1()->x(),pLine->v1()->y(),pLine->v1()->z()); glVertex3f(pLine->v2()->x(),pLine->v2()->y(),pLine->v2()->z()); } ::glEnd(); // Triangles GLuint nowName=0; for(unsigned int i=0;i<NbFace;i++) { { pFace = m_ArrayFace[i]; ASSERT(pFace != NULL); ::glLoadName(nowName); ::glBegin(GL_TRIANGLES); // Normal (per face) if(m_NormalBinding == NORMAL_PER_FACE) { pVector = pFace->GetNormal(); ::glNormal3f(pVector->x(),pVector->y(),pVector->z()); } // Color (per face) if(m_ColorBinding == COLOR_PER_FACE && pColorPrevious != pFace->GetColor()) { ::glColor3ub(pFace->GetColor()->r(),pFace->GetColor()->g(),pFace->GetColor()->b()); pColorPrevious = pFace->GetColor(); } for(int j=0;j<3;j++) { // Normal if(m_NormalBinding == NORMAL_PER_VERTEX) { pVector = pFace->v(j)->GetNormal(); ::glNormal3f(pVector->x(),pVector->y(),pVector->z()); } // Color (per vertex) if(m_ColorBinding == COLOR_PER_VERTEX && pColorPrevious != pFace->v(j)->GetColor()) { ::glColor3ub(pFace->v(j)->GetColor()->r(),pFace->v(j)->GetColor()->g(),pFace->v(j)->GetColor()->b()); pColorPrevious = pFace->v(j)->GetColor(); } // Texture coordinate (if needed) if(m_IndexTexture != -1) { glTexCoord2f(m_pTextureCoordinate[2*m_pTextureCoordinateIndex[3*i+j]], m_pTextureCoordinate[2*m_pTextureCoordinateIndex[3*i+j]+1]); } // Vertex ::glVertex3f(pFace->v(j)->x(),pFace->v(j)->y(),pFace->v(j)->z()); } ::glEnd(); nowName++; } } ::glPopMatrix(); glDepthMask(GL_TRUE); return 1; } //******************************************** // Draw //******************************************** int CMesh3d::glDraw(int DEBUGMODE) { if(!m_Show) return 0; // Build list at first if(!m_ListDone || m_Modified) glBuildList(DEBUGMODE); // Search for a new list if(::glIsList(m_ListOpenGL)==GL_TRUE) { ::glCallList(m_ListOpenGL); return 1; } else { TRACE(" CMesh3d::Draw : unable to draw list %d\n",m_ListOpenGL); return 0; } } ////////////////////////////////////////////// // DATAS ////////////////////////////////////////////// //******************************************** // Copy //******************************************** void CMesh3d::Copy(CMesh3d *pMesh) { // Vertices int NbVertex = pMesh->NbVertex(); m_ArrayVertex.SetSize(NbVertex); for(int i=0;i<NbVertex;i++) m_ArrayVertex.SetAt(i,new CVertex3d(pMesh->GetVertex(i))); // Faces int NbFace = pMesh->NbFace(); m_ArrayFace.SetSize(NbFace); for(int i=0;i<NbFace;i++) { CFace3d *pFace = pMesh->GetFace(i); m_ArrayFace.SetAt(i,new CFace3d( m_ArrayVertex[pMesh->IndexFrom(pFace->v1())], m_ArrayVertex[pMesh->IndexFrom(pFace->v2())], m_ArrayVertex[pMesh->IndexFrom(pFace->v3())])); } // Transform m_Transform.Copy(pMesh->GetTransform()); } //******************************************** // GetType //******************************************** int CMesh3d::GetType() { return TYPE_MESH3D; } //******************************************** // IsValid //******************************************** int CMesh3d::IsValid() { int NbFace = m_ArrayFace.GetSize(); for(int i=0;i<NbFace;i++) if(!m_ArrayFace[i]->IsValid()) return 0; return 1; } //******************************************** // DeleteVertex //******************************************** int CMesh3d::DeleteVertex(CVertex3d *pVertex) { int size = m_ArrayVertex.GetSize(); for(int i=0;i<size;i++) { CVertex3d *pV = m_ArrayVertex[i]; if(pV == pVertex) { m_ArrayVertex.RemoveAt(i); delete pVertex; return 1; } } return 0; } //******************************************** // DeleteVertex //******************************************** int CMesh3d::DeleteVertex(int index) { if(index < m_ArrayVertex.GetSize()) { CVertex3d *pVertex = (CVertex3d *)m_ArrayVertex[index]; m_ArrayVertex.RemoveAt(index); delete pVertex; return 1; } return 0; } //******************************************** // DeleteFace //******************************************** int CMesh3d::DeleteFaceNbNeighbors(int NbNeighbor) { TRACE("Delete faces which has %d neighbors...",NbNeighbor); int deleted = 0; for(int i=0;i<m_ArrayFace.GetSize();i++) { CFace3d *pFace = m_ArrayFace[i]; if(pFace->NbFaceNeighbor() == NbNeighbor) { m_ArrayFace.RemoveAt(i); delete pFace; i--; deleted++; } } TRACE("%d face(s) deleted\n",deleted); return deleted; } ////////////////////////////////////////////// // RANGE ////////////////////////////////////////////// //******************************************** // Range //******************************************** void CMesh3d::Range(int coord, float *min, float *max) { ASSERT(coord >= 0 && coord <= 2); int NbVertex = m_ArrayVertex.GetSize(); float Min = m_ArrayVertex[0]->Get(coord); float Max = Min; for(int i=1;i<NbVertex;i++) { float value = m_ArrayVertex[i]->Get(coord); if(value < Min) Min = value; if(value > Max) Max = value; } *min = Min; *max = Max; } //******************************************** // Range (apply) //******************************************** void CMesh3d::Range(int coord, float min, float max) { TRACE("Range mesh..."); float Min,Max; Range(coord,&Min,&Max); TRACE("old : (%g,%g) -> (%g %g)",Min,Max,min,max); Offset(coord,-Min); Scale(coord,(max-min)/(Max-Min)); Offset(coord,min); TRACE("ok\n"); } //******************************************** // Scale //******************************************** void CMesh3d::Scale(int coord, float scale) { int NbVertex = m_ArrayVertex.GetSize(); for(int i=0;i<NbVertex;i++) m_ArrayVertex[i]->Set(coord,m_ArrayVertex[i]->Get(coord) * scale); m_Modified = 1; } //******************************************** // Offset //******************************************** void CMesh3d::Offset(int coord, float offset) { int NbVertex = m_ArrayVertex.GetSize(); for(int i=0;i<NbVertex;i++) m_ArrayVertex[i]->Set(coord,m_ArrayVertex[i]->Get(coord) + offset); m_Modified = 1; } ////////////////////////////////////////////// // PROCESSING ////////////////////////////////////////////// //******************************************** // BuildAdjacency // From VertexArray and FaceArray, build // neighboring vertices and faces, using // edge and vertex sharing //******************************************** int CMesh3d::BuildAdjacency() { // Check for valid sizes int NbVertex = m_ArrayVertex.GetSize(); int NbFace = m_ArrayFace.GetSize(); TRACE("Build adjacency (%d faces, %d vertices)",NbFace,NbVertex); if(NbVertex < 3 || NbFace <= 0) { TRACE(" invalid array sizes\n"); return 0; } // At first, clear all neighbors for each face //TRACE(" clear face neighbors\n"); TRACE("."); for(int i=0;i<NbFace;i++) for(int k=0;k<6;k++) m_ArrayFace[i]->f(k,NULL); // At first, clear all neighbors for each vertex //TRACE(" clear vertex neighbors\n"); TRACE("."); for(int i=0;i<NbVertex;i++) { m_ArrayVertex[i]->RemoveAllFaceNeighbor(); m_ArrayVertex[i]->RemoveAllVertexNeighbor(); } //********************************************* // For each face, set face neighboring vertices //********************************************* //TRACE(" set face neighboring vertices\n"); TRACE("."); for(int i=0;i<NbFace;i++) { CFace3d *pFaceCurrent = m_ArrayFace[i]; for(int j=0;j<3;j++) pFaceCurrent->v(j)->AddNeighbor(pFaceCurrent); } //********************************************* // For each vertex, set vertex neighboring, // just look on neighboring faces //********************************************* //TRACE(" set vertices neighboring vertices\n"); TRACE("."); for(int i=0;i<NbVertex;i++) { CVertex3d *pVertexCurrent = m_ArrayVertex[i]; int NbFaceNeighbor = pVertexCurrent->NbFaceNeighbor(); for(int j=0;j<NbFaceNeighbor;j++) { CFace3d *pFace = pVertexCurrent->GetFaceNeighbor(j); for(int k=0;k<3;k++) pVertexCurrent->AddNeighbor(pFace->v(k)); } } //********************************************* // For each face, set face neighboring, // just look on faces neighboring vertices //********************************************* //TRACE(" set faces neighboring faces\n"); TRACE("."); for(int i=0;i<NbFace;i++) { CFace3d *pFaceCurrent = m_ArrayFace[i]; // For each edge for(int j=0;j<3;j++) { CVertex3d *pVertex = pFaceCurrent->v(j); CVertex3d *pNextVertex = pFaceCurrent->v((j+1)%3); int NbFaceNeighbor = pVertex->NbFaceNeighbor(); for(int k=0;k<NbFaceNeighbor;k++) { // This face contain pVertex CFace3d *pFace = pVertex->GetFaceNeighbor(k); if(pFace != pFaceCurrent) if(pFaceCurrent->f(j) == NULL) if(pFace->HasVertex(pVertex)) if(pFace->HasVertex(pNextVertex)) pFaceCurrent->f(j,pFace); } } } /* // Check for(i=0;i<NbFace;i++) { ASSERT(m_ArrayFace[i]->IsValid()); } */ TRACE("ok\n"); return TRUE; } //******************************************** // Rebuild //******************************************** void CMesh3d::Rebuild() { BuildAdjacency(); CalculateNormalPerFace(); CalculateNormalPerVertex(); SetModified(1); } ///////////////////////////////////////////// // DEBUG ////////////////////////////////////////////// //******************************************** // Trace //******************************************** void CMesh3d::Trace() { int NbVertex = m_ArrayVertex.GetSize(); int NbFace = m_ArrayFace.GetSize(); TRACE("\n"); TRACE(" Mesh \n"); TRACE("Vertex : %d\n",NbVertex); TRACE("Face : %d\n",NbFace); for(int i=0;i<NbVertex;i++) ((CVertex3d *)m_ArrayVertex[i])->Trace(); for(int j=0;j<NbFace;j++) ((CFace3d *)m_ArrayFace[j])->Trace(); } //******************************************** // IndexFrom // Return -1 if failed //******************************************** int CMesh3d::IndexFrom(CFace3d *pFace) { ASSERT(pFace != NULL); int NbFace = m_ArrayFace.GetSize(); for(int i=0;i<NbFace;i++) if(m_ArrayFace[i] == pFace) return i; return -1; } //******************************************** // IndexFrom // Return -1 if failed //******************************************** int CMesh3d::IndexFrom(CVertex3d *pVertex) { int NbVertex = m_ArrayVertex.GetSize(); for(int i=0;i<NbVertex;i++) if(m_ArrayVertex[i] == pVertex) return i; return -1; } //******************************************** // Move //******************************************** void CMesh3d::Move(float dx,float dy,float dz) { int NbVertex = m_ArrayVertex.GetSize(); for(int i=0;i<NbVertex;i++) m_ArrayVertex[i]->Move(dx,dy,dz); m_Modified = 1; } //******************************************** // FindVertexInFaces //******************************************** int CMesh3d::FindVertex(CVertex3d *pVertex) { int find = 0; int NbFace = m_ArrayFace.GetSize(); for(int j=0;j<NbFace;j++) if(m_ArrayFace[j]->HasVertex(pVertex)) { find = 1; TRACE("Find vertex [%x] in face %d\n",pVertex,j); } int NbVertex = m_ArrayVertex.GetSize(); for(int j=0;j<NbVertex;j++) if(m_ArrayVertex[j] == pVertex) { find = 1; TRACE("Find vertex [%x] at position %d\n",pVertex,j); } for(int j=0;j<NbVertex;j++) { CVertex3d *pV = m_ArrayVertex[j]; if(pV->HasNeighbor(pVertex)) { find = 1; TRACE("Find vertex [%x] in neighbors of vertex %d\n",pVertex,j); } } return find; } //******************************************** // FindFace //******************************************** int CMesh3d::FindFace(CFace3d *pFace) { int find = 0; int NbFace = m_ArrayFace.GetSize(); for(int j=0;j<NbFace;j++) { CFace3d *pF = m_ArrayFace[j]; if(pF == pFace) { find = 1; TRACE("Find face [%x] in mesh (index : %d)\n",pFace,j); } for(int i=0;i<3;i++) if(pF->f(i) == pFace) { find = 1; TRACE("Find face [%x] in neighbors %d of face %d\n",pFace,i,j); } } return find; } ////////////////////////////////////////////// // NORMALS ////////////////////////////////////////////// //******************************************** // CalculateNormalPerVertex //******************************************** int CMesh3d::CalculateNormalPerVertex(void) { int NbVertex = m_ArrayVertex.GetSize(); int NbFace = m_ArrayFace.GetSize(); TRACE("Calculate normal per vertex (%d faces, %d vertices)...",NbFace,NbVertex); for(int i=0;i<NbVertex;i++) { CVertex3d *pVertex = m_ArrayVertex[i]; int NbNormal = 0; CVector3d vector; int NbFaceNeighbor = pVertex->NbFaceNeighbor(); for(int j=0;j<NbFaceNeighbor;j++) { CFace3d *pFace = pVertex->GetFaceNeighbor(j); NbNormal += 1; vector += pFace->GetNormal(); } if(NbNormal>=1) { vector.NormalizeL2(); pVertex->SetNormal(vector); } } m_Modified = 1; TRACE("ok\n"); return 1; } //******************************************** // CalculateNormalPerFace //******************************************** int CMesh3d::CalculateNormalPerFace(void) { int size = m_ArrayFace.GetSize(); TRACE("Calculate normal per face (%d faces)...",size); for(int i=0;i<size;i++) { CFace3d *pFace = m_ArrayFace[i]; if(pFace->IsValid()) pFace->CalculateNormal(); } m_Modified = 1; TRACE("ok\n"); return 1; } //******************************************** // ColorSharpEdges //******************************************** int CMesh3d::ColorSharpEdge(float threshold, CColor &color) { int NbFace = m_ArrayFace.GetSize(); TRACE(" Start ColorSharpEdges\n"); TRACE(" Faces : %d\n",NbFace); for(int i=0;i<NbFace;i++) m_ArrayFace[i]->ColorSharpEdge(threshold,color); TRACE(" End ColorSharpEdges\n"); return 1; } //******************************************** // SetNormalBinding //******************************************** void CMesh3d::SetNormalBinding(int type) { m_NormalBinding = type; m_Modified = 1; } //******************************************** // GetNormalBinding //******************************************** int CMesh3d::GetNormalBinding(void) { return m_NormalBinding; } //******************************************** // SetColorBinding //******************************************** void CMesh3d::SetColorBinding(int type) { m_ColorBinding = type; m_Modified = 1; } //******************************************** // SetColor //******************************************** void CMesh3d::SetColor(CColor &color) { int size = m_ArrayFace.GetSize(); for(int i=0;i<size;i++) m_ArrayFace[i]->SetColor(color); m_Modified = 1; } //******************************************** // SetColor //******************************************** void CMesh3d::SetColor(unsigned char r, unsigned char g, unsigned char b) { for(int i=0;i<m_ArrayFace.GetSize();i++) m_ArrayFace[i]->SetColor(r,g,b); for(int i=0;i<m_ArrayVertex.GetSize();i++) m_ArrayVertex[i]->SetColor(r,g,b); m_Modified = 1; } //******************************************** // GetColorBinding //******************************************** int CMesh3d::GetColorBinding(void) { return m_ColorBinding; } //******************************************** // SetFlagOnFaces //******************************************** void CMesh3d::SetFlagOnFaces(int flag) { int size = m_ArrayFace.GetSize(); for(int i=0;i<size;i++) m_ArrayFace[i]->SetFlag(flag); } //******************************************** // GetMaxFlagOnFaces //******************************************** int CMesh3d::GetMaxFlagOnFaces() { int size = m_ArrayFace.GetSize(); int max = 0; for(int i=0;i<size;i++) { int tmp = m_ArrayFace[i]->GetFlag(); max = (tmp > max) ? tmp : max; } return max; } //******************************************** // SetFlagOnVertices //******************************************** void CMesh3d::SetFlagOnVertices(int flag) { int size = m_ArrayVertex.GetSize(); for(int i=0;i<size;i++) m_ArrayVertex[i]->SetFlag((char)flag); } //******************************************** // GetFirstVertexWithFlag //******************************************** float CMesh3d::GetMeanLengthEdge() { int size = m_ArrayVertex.GetSize(); double sum = 0; for(int i=0;i<size;i++) sum += m_ArrayVertex[i]->GetMeanLengthEdgeAround(); if(size) return (float)sum/size; else return 0.0f; } ////////////////////////////////////////////// // SUBDIVISION ////////////////////////////////////////////// //******************************************** // Alpha // From Piecewise smooth reconstruction (Hoppe) //******************************************** float CMesh3d::Alpha(int n) { float tmp = 3.0f + 2.0f * (float)cos(2.0f * 3.14159265359f/(float)n); float a = 5.0f/8.0f - (tmp*tmp)/64.0f; return (n*(1-a)/a); } //******************************************** // SubdivisionLoop // From Piecewise smooth reconstruction (Hoppe) //******************************************** // (SIGGRAPH 94) -> Charles Loop //******************************************** int CMesh3d::SubdivisionLoop() { // We assume adjacency is built int NbVertex = m_ArrayVertex.GetSize(); SetFlagOnVertices(0); // for boundaries // Create subdivision info (edge vertices) int NbFace = m_ArrayFace.GetSize(); TRACE("Start loop's subdivision (%d faces, %d vertices)\n",NbFace,NbVertex); TRACE(" subdivision info (%d vertices)\n",m_ArrayVertex.GetSize()); // For each face for(int i=0;i<NbFace;i++) { CFace3d *pFace = m_ArrayFace[i]; // Check valid neighboring if(!pFace->IsValid()) continue; // On each edge for(int IndexEdge=0;IndexEdge<3;IndexEdge++) { // Get IndexEdge on neighbor int IndexCurrent,IndexNeighbor; CFace3d *pFaceNeighbor = pFace->f(IndexEdge); // No neighbor on this edge, it is a boundary edge if(pFaceNeighbor == NULL) { // Two vertices involved CVertex3d *pVertex[2]; pVertex[0] = pFace->v(IndexEdge); pVertex[1] = pFace->v((IndexEdge+1)%3); float x = 0.5f*(pVertex[0]->x()+pVertex[1]->x()); float y = 0.5f*(pVertex[0]->y()+pVertex[1]->y()); float z = 0.5f*(pVertex[0]->z()+pVertex[1]->z()); CVertex3d *pNewVertex = new CVertex3d(x,y,z); m_ArrayVertex.Add(pNewVertex); pFace->v(3+IndexEdge,pNewVertex); // Boundary vertices pVertex[0]->SetFlag(1); pVertex[1]->SetFlag(1); } else // std case { VERIFY(pFace->Share2Vertex(pFaceNeighbor,&IndexCurrent,&IndexNeighbor)); ASSERT(IndexCurrent == IndexEdge); // If neighboring face has been treated, then get vertex // and go to next step if(pFaceNeighbor->GetFlag()) { CVertex3d *pVertex = pFaceNeighbor->v(3+(IndexNeighbor%3)); pFace->v(3+(IndexEdge%3),pVertex); continue; } // Vertex weighting // 0 & 1 : weight : 3, 2 & 3 : weight : 1 CVertex3d *pVertex[4]; // Weight : 3 pVertex[0] = pFace->v(IndexEdge); pVertex[1] = pFace->v((IndexEdge+1)%3); // Weight : 1 pVertex[2] = pFace->v((IndexEdge+2)%3); pVertex[3] = pFaceNeighbor->v((IndexNeighbor+2)%3); ASSERT(pVertex[0] != NULL && pVertex[1] != NULL && pVertex[2] != NULL && pVertex[3] != NULL); // For each composant float x = (3.0f * (pVertex[0]->x() + pVertex[1]->x()) + pVertex[2]->x() + pVertex[3]->x()) / 8.0f; float y = (3.0f * (pVertex[0]->y() + pVertex[1]->y()) + pVertex[2]->y() + pVertex[3]->y()) / 8.0f; float z = (3.0f * (pVertex[0]->z() + pVertex[1]->z()) + pVertex[2]->z() + pVertex[3]->z()) / 8.0f; // Add vertex to global mesh array, and set face's vertex CVertex3d *pNewVertex = new CVertex3d(x,y,z); m_ArrayVertex.Add(pNewVertex); pFace->v(3+IndexCurrent,pNewVertex); } } // Set flag pFace->SetFlag(1); } //***************************** // Create faces //***************************** TRACE(" creating faces (%d faces)\n",NbFace); // For each valid face for(int i=0;i<NbFace;i++) { CFace3d *pFace = m_ArrayFace[i]; pFace->SetFlag(0); // Valid face int NbVertex = pFace->NbVertex(); CFace3d *pNewFace; switch(NbVertex) { case 4: // Create one face // On edge 0 if(pFace->v(3) != NULL) { pNewFace = new CFace3d(pFace->v(3),pFace->v(1),pFace->v(2)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(1,pFace->v(3)); } else // On edge 1 if(pFace->v(4) != NULL) { pNewFace = new CFace3d(pFace->v(0),pFace->v(4),pFace->v(2)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(2,pFace->v(4)); } else // On edge 2 if(pFace->v(5) != NULL) { pNewFace = new CFace3d(pFace->v(5),pFace->v(1),pFace->v(2)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(2,pFace->v(5)); } break; case 5: // Create two faces // On edge 0 & 2 if(pFace->v(3) != NULL && pFace->v(5) != NULL) { pNewFace = new CFace3d(pFace->v(0),pFace->v(3),pFace->v(5)); m_ArrayFace.Add(pNewFace); pNewFace = new CFace3d(pFace->v(5),pFace->v(3),pFace->v(2)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(0,pFace->v(3)); } else // On edge 0 & 1 if(pFace->v(3) != NULL && pFace->v(4) != NULL) { pNewFace = new CFace3d(pFace->v(3),pFace->v(1),pFace->v(4)); m_ArrayFace.Add(pNewFace); pNewFace = new CFace3d(pFace->v(0),pFace->v(3),pFace->v(4)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(1,pFace->v(4)); } else // On edge 1 & 2 if(pFace->v(4) != NULL && pFace->v(5) != NULL) { pNewFace = new CFace3d(pFace->v(1),pFace->v(4),pFace->v(5)); m_ArrayFace.Add(pNewFace); pNewFace = new CFace3d(pFace->v(4),pFace->v(2),pFace->v(5)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(2,pFace->v(5)); } break; case 6: // Create three faces // First (v3,v1,v4) pNewFace = new CFace3d(pFace->v(3),pFace->v(1),pFace->v(4)); m_ArrayFace.Add(pNewFace); // Second (v3,v4,v5) pNewFace = new CFace3d(pFace->v(3),pFace->v(4),pFace->v(5)); m_ArrayFace.Add(pNewFace); // Third (v5,v4,v2) pNewFace = new CFace3d(pFace->v(5),pFace->v(4),pFace->v(2)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(1,pFace->v(3)); pFace->v(2,pFace->v(5)); break; } // Remove subdivision info for(int k=3;k<6;k++) pFace->v(k,NULL); } TRACE(" end creating faces (%d faces)\n",m_ArrayFace.GetSize()); //***************************** // Move original vertices //***************************** // Copy TRACE(" copy\n"); CArray3d<CVertex3d> ArrayVertex; ArrayVertex.SetSize(NbVertex); for(int i=0;i<NbVertex;i++) ArrayVertex.SetAt(i,new CVertex3d); // For each vertex (at least 2 neighbors) for(int i=0;i<NbVertex;i++) { CVertex3d *pVertex = m_ArrayVertex[i]; int n = pVertex->NbVertexNeighbor(); // Spline on boundaries, we need two vertices // remind that the adjacency has not been // updated yet // weighting: 1 6 1 if(pVertex->GetFlag()) { CVertex3d *pv[2]; int index = 0; for(int k=0;k<n;k++) { CVertex3d *pNVertex = pVertex->GetVertexNeighbor(k); if(pNVertex->GetFlag()) pv[index++] = pNVertex; } ASSERT(index == 2); ArrayVertex[i]->Set(0.125f*(6.0f*pVertex->x()+pv[0]->x()+pv[1]->x()), 0.125f*(6.0f*pVertex->y()+pv[0]->y()+pv[1]->y()), 0.125f*(6.0f*pVertex->z()+pv[0]->z()+pv[1]->z())); } else { float alpha = Alpha(n); float tmp = alpha + (float)n; // For each componant for(unsigned int j=0;j<3;j++) { float value = alpha * pVertex->Get(j); for(int k=0;k<n;k++) value += pVertex->GetVertexNeighbor(k)->Get(j); value /= tmp; ArrayVertex[i]->Set(j,value); } } } // Restore TRACE(" restore\n"); for(int i=0;i<NbVertex;i++) for(unsigned int j=0;j<3;j++) m_ArrayVertex[i]->Set(j,ArrayVertex[i]->Get(j)); ArrayVertex.Free(); // Rebuild adjacency and normals BuildAdjacency(); CalculateNormalPerFace(); CalculateNormalPerVertex(); m_Modified = 1; TRACE("End loop's subdivision (%d faces, %d vertices)\n", m_ArrayFace.GetSize(),m_ArrayVertex.GetSize()); return 1; } //******************************************** // Subdivision // Simple : 1->4 //******************************************** int CMesh3d::Subdivision(void) { // We assume adjacency is built int NbVertex = m_ArrayVertex.GetSize(); // Create subdivision info (edge vertices) int NbFace = m_ArrayFace.GetSize(); TRACE("Start subdivision (%d faces, %d vertices)\n",NbFace,NbVertex); TRACE(" subdivision info (%d vertices)\n",m_ArrayVertex.GetSize()); // For each face for(int i=0;i<NbFace;i++) { CFace3d *pFace = m_ArrayFace[i]; // On each edge for(int IndexEdge=0;IndexEdge<3;IndexEdge++) { // Get IndexEdge on neighbor int IndexCurrent,IndexNeighbor; CFace3d *pFaceNeighbor = pFace->f(IndexEdge); // No neighbor on this edge, go to next if(pFaceNeighbor != NULL) { VERIFY(pFace->Share2Vertex(pFaceNeighbor,&IndexCurrent,&IndexNeighbor)); ASSERT(IndexCurrent == IndexEdge); // If neighboring face has been treated, then get vertex // and go to next step if(pFaceNeighbor->GetFlag()) { CVertex3d *pVertex = pFaceNeighbor->v(3+(IndexNeighbor%3)); pFace->v(3+(IndexEdge%3),pVertex); continue; } } // Vertex weighting // 0 & 1 : weight : 1 CVertex3d *pVertex[2]; // Weight : 1 pVertex[0] = pFace->v(IndexEdge); pVertex[1] = pFace->v((IndexEdge+1)%3); ASSERT(pVertex[0] != NULL && pVertex[1] != NULL); // For each composant float coord[3]; for(int k=0;k<3;k++) coord[k] = (pVertex[0]->Get(k) + pVertex[1]->Get(k)) / 2.0f; // Add vertex to global mesh array, and set face's vertex CVertex3d *pNewVertex = new CVertex3d(coord[0],coord[1],coord[2]); m_ArrayVertex.Add(pNewVertex); pFace->v(3+IndexEdge,pNewVertex); } // Set flag pFace->SetFlag(1); } //***************************** // Create faces //***************************** TRACE(" creating faces (%d faces)\n",NbFace); // For each valid face for(int i=0;i<NbFace;i++) { CFace3d *pFace = m_ArrayFace[i]; pFace->SetFlag(0); // Valid face int NbVertex = pFace->NbVertex(); CFace3d *pNewFace; switch(NbVertex) { case 4: // Create one face // On edge 0 if(pFace->v(3) != NULL) { pNewFace = new CFace3d(pFace->v(3),pFace->v(1),pFace->v(2)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(1,pFace->v(3)); } else // On edge 1 if(pFace->v(4) != NULL) { pNewFace = new CFace3d(pFace->v(0),pFace->v(4),pFace->v(2)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(2,pFace->v(4)); } else // On edge 2 if(pFace->v(5) != NULL) { pNewFace = new CFace3d(pFace->v(5),pFace->v(1),pFace->v(2)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(2,pFace->v(5)); } break; case 5: // Create two faces // On edge 0 & 2 if(pFace->v(3) != NULL && pFace->v(5) != NULL) { pNewFace = new CFace3d(pFace->v(0),pFace->v(3),pFace->v(5)); m_ArrayFace.Add(pNewFace); pNewFace = new CFace3d(pFace->v(5),pFace->v(3),pFace->v(2)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(0,pFace->v(3)); } else // On edge 0 & 1 if(pFace->v(3) != NULL && pFace->v(4) != NULL) { pNewFace = new CFace3d(pFace->v(3),pFace->v(1),pFace->v(4)); m_ArrayFace.Add(pNewFace); pNewFace = new CFace3d(pFace->v(0),pFace->v(3),pFace->v(4)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(1,pFace->v(4)); } else // On edge 1 & 2 if(pFace->v(4) != NULL && pFace->v(5) != NULL) { pNewFace = new CFace3d(pFace->v(1),pFace->v(4),pFace->v(5)); m_ArrayFace.Add(pNewFace); pNewFace = new CFace3d(pFace->v(4),pFace->v(2),pFace->v(5)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(2,pFace->v(5)); } break; case 6: // Create three faces // First (v3,v1,v4) pNewFace = new CFace3d(pFace->v(3),pFace->v(1),pFace->v(4)); m_ArrayFace.Add(pNewFace); // Second (v3,v4,v5) pNewFace = new CFace3d(pFace->v(3),pFace->v(4),pFace->v(5)); m_ArrayFace.Add(pNewFace); // Third (v5,v4,v2) pNewFace = new CFace3d(pFace->v(5),pFace->v(4),pFace->v(2)); m_ArrayFace.Add(pNewFace); // Move current face pFace->v(1,pFace->v(3)); pFace->v(2,pFace->v(5)); break; } // Remove subdivision info for(int k=3;k<6;k++) pFace->v(k,NULL); } TRACE(" end creating faces (%d faces)\n",m_ArrayFace.GetSize()); // Rebuild adjacency and normals BuildAdjacency(); CalculateNormalPerFace(); CalculateNormalPerVertex(); m_Modified = 1; TRACE("End subdivision (%d faces, %d vertices)\n", m_ArrayFace.GetSize(),m_ArrayVertex.GetSize()); return 1; } //******************************************** // Smooth // 30/09/98 //******************************************** int CMesh3d::Smooth(int MoveOnBundary /* = 1 */) { // We assume adjacency is built int NbVertex = m_ArrayVertex.GetSize(); // Create subdivision info (edge vertices) int NbFace = m_ArrayFace.GetSize(); TRACE("Start smoothing (%d faces, %d vertices)",NbFace,NbVertex); //***************************** // Move original vertices //***************************** // Copy TRACE("."); CArray3d<CVertex3d> ArrayVertex; ArrayVertex.SetSize(NbVertex); for(int i=0;i<NbVertex;i++) ArrayVertex.SetAt(i,new CVertex3d); // For each vertex (at least 3 neighbors) for(int i=0;i<NbVertex;i++) { CVertex3d *pVertex = m_ArrayVertex[i]; if(!MoveOnBundary) if(pVertex->IsOnBoundary()) { ArrayVertex[i]->Set(pVertex); continue; } int n = pVertex->NbVertexNeighbor(); float alpha = Alpha(n); float tmp = alpha + (float)n; // For each composant for(unsigned int j=0;j<3;j++) { float value = alpha * pVertex->Get(j); for(int k=0;k<n;k++) value += pVertex->GetVertexNeighbor(k)->Get(j); value /= tmp; ArrayVertex[i]->Set(j,value); } } // Restore TRACE("."); for(int i=0;i<NbVertex;i++) for(unsigned int j=0;j<3;j++) m_ArrayVertex[i]->Set(j,ArrayVertex[i]->Get(j)); // Cleanup TRACE("."); ArrayVertex.Free(); TRACE("ok\n"); // Rebuild adjacency and normals BuildAdjacency(); CalculateNormalPerFace(); CalculateNormalPerVertex(); m_Modified = 1; return 1; } //******************************************** // ColorCurvature // Each face is colored, function of mean curvature //******************************************** void CMesh3d::ColorCurvature(CColorRamp *pRamp) { TRACE("Start coloring mesh (curvature)\n"); int NbVertex = m_ArrayVertex.GetSize(); TRACE(" %d vertices\n",NbVertex); double *pMax = new double[NbVertex]; // Store curvatures for(int i=0;i<NbVertex;i++) pMax[i] = m_ArrayVertex[i]->GetMaxAngleAround(); // Process extremas double min = MAX_DOUBLE; double max = 0.0f; for(int i=0;i<NbVertex;i++) { min = (pMax[i] < min) ? pMax[i] : min; max = (pMax[i] > max) ? pMax[i] : max; } min = (min < 0.0f) ? 0.0f : min; double amplitude = max-min;//max-min; TRACE(" min : %g\n",min); TRACE(" max : %g\n",max); TRACE(" amplitude : %g\n",amplitude); for(int i=0;i<NbVertex;i++) { unsigned char _grey = (unsigned char)((pMax[i]-min)/amplitude * 255.0f); unsigned char grey = _grey > (unsigned char)255 ? (unsigned char)255 : _grey; m_ArrayVertex[i]->SetColor(pRamp->Red(grey),pRamp->Green(grey),pRamp->Blue(grey)); } SetModified(); TRACE("End coloring mesh (curvature)\n"); } //******************************************** // ColorSpaceNormal // Each vertex is colored, function of // normal space (sum of angles between // adjacent faces) //******************************************** void CMesh3d::ColorNormalSpace(CColorRamp *pRamp) { TRACE("Start coloring mesh (space of normals)\n"); int NbVertex = m_ArrayVertex.GetSize(); TRACE(" %d vertices\n",NbVertex); double *pSum = new double[NbVertex]; // Store curvatures for(int i=0;i<NbVertex;i++) m_ArrayVertex[i]->NormalMax(&pSum[i]); // Process extremas double min = MAX_DOUBLE; double max = 0.0f; for(int i=0;i<NbVertex;i++) { min = (pSum[i] < min) ? pSum[i] : min; max = (pSum[i] > max) ? pSum[i] : max; } min = (min < 0.0f) ? 0.0f : min; double amplitude = max-min;//max-min; TRACE(" min : %g\n",min); TRACE(" max : %g\n",max); TRACE(" amplitude : %g\n",amplitude); for(int i=0;i<NbVertex;i++) { unsigned char _grey = (unsigned char)((pSum[i]-min)/amplitude * 255.0f); unsigned char grey = _grey > (unsigned char)255 ? (unsigned char)255 : _grey; //unsigned char grey = (unsigned char)((pCurvature[i]-min)/amplitude * 255.0f); m_ArrayVertex[i]->SetColor(pRamp->Red(grey),pRamp->Green(grey),pRamp->Blue(grey)); } SetModified(); delete [] pSum; TRACE("End coloring mesh (space of normals)\n"); } //******************************************** // ColorCompacity // Each face is colored, function of face // compacity //******************************************** void CMesh3d::ColorCompacity(CColorRamp *pRamp) { TRACE("Start coloring mesh (compacity)\n"); int NbFace = m_ArrayFace.GetSize(); TRACE(" %d face(s)\n",NbFace); double *pCompacity = new double[NbFace]; // Store compacity for(int i=0;i<NbFace;i++) pCompacity[i] = m_ArrayFace[i]->Compacity(); // Process extremas double min = MAX_DOUBLE; double max = 0.0f; for(int i=0;i<NbFace;i++) { min = (pCompacity[i] < min) ? pCompacity[i] : min; max = (pCompacity[i] > max) ? pCompacity[i] : max; } double amplitude = max-min;//max-min; TRACE(" min : %g\n",min); TRACE(" max : %g\n",max); TRACE(" amplitude : %g\n",amplitude); for(int i=0;i<NbFace;i++) { unsigned char _grey = (unsigned char)((pCompacity[i]-min)/amplitude * 255.0f); unsigned char grey = _grey > (unsigned char)255 ? (unsigned char)255 : _grey; //unsigned char grey = (unsigned char)((pCurvature[i]-min)/amplitude * 255.0f); m_ArrayFace[i]->SetColor(pRamp->Red(grey),pRamp->Green(grey),pRamp->Blue(grey)); } SetModified(); delete [] pCompacity; TRACE("End coloring mesh (compacity)\n"); } //******************************************** // ColorHeight // Each vertex is colored, function of height //******************************************** void CMesh3d::ColorHeight(CColorRamp *pRamp) { // Color vertices int NbVertex = m_ArrayVertex.GetSize(); double min = MAX_DOUBLE; double max = 0.0f; for(int i=0;i<NbVertex;i++) { float height = m_ArrayVertex[i]->y(); min = (height < min) ? height : min; max = (height > max) ? height : max; } double amplitude = max-min; for(int i=0;i<NbVertex;i++) { float height = m_ArrayVertex[i]->y(); unsigned char _grey = (unsigned char)((height-min)/amplitude * 255.0f); unsigned char grey = _grey > (unsigned char)255 ? (unsigned char)255 : _grey; m_ArrayVertex[i]->SetColor(pRamp->Red(grey),pRamp->Green(grey),pRamp->Blue(grey)); } // Color faces int NbFace = m_ArrayFace.GetSize(); TRACE(" %d faces\n",NbFace); for(int i=0;i<NbFace;i++) { float height = (m_ArrayFace[i]->v1()->y()+ m_ArrayFace[i]->v1()->y()+ m_ArrayFace[i]->v1()->y())/3.0f; unsigned char _grey = (unsigned char)((height-min)/amplitude * 255.0f); unsigned char grey = _grey > (unsigned char)255 ? (unsigned char)255 : _grey; m_ArrayFace[i]->SetColor(pRamp->Red(grey),pRamp->Green(grey),pRamp->Blue(grey)); } SetModified(); } ////////////////////////////////////////////// // PREDEFINED ////////////////////////////////////////////// //******************************************** // GenerateBox //******************************************** int CMesh3d::GenerateBox(float dx, float dy, float dz) { TRACE("Generate box..."); CVertex3d *pVertex; pVertex = new CVertex3d(-dx/2,-dy/2,-dz/2); m_ArrayVertex.Add(pVertex); pVertex = new CVertex3d(-dx/2,+dy/2,-dz/2); m_ArrayVertex.Add(pVertex); pVertex = new CVertex3d(+dx/2,+dy/2,-dz/2); m_ArrayVertex.Add(pVertex); pVertex = new CVertex3d(+dx/2,-dy/2,-dz/2); m_ArrayVertex.Add(pVertex); pVertex = new CVertex3d(-dx/2,-dy/2,+dz/2); m_ArrayVertex.Add(pVertex); pVertex = new CVertex3d(-dx/2,+dy/2,+dz/2); m_ArrayVertex.Add(pVertex); pVertex = new CVertex3d(+dx/2,+dy/2,+dz/2); m_ArrayVertex.Add(pVertex); pVertex = new CVertex3d(+dx/2,-dy/2,+dz/2); m_ArrayVertex.Add(pVertex); CFace3d *pFace; pFace = new CFace3d(m_ArrayVertex[0], m_ArrayVertex[1], m_ArrayVertex[3]); pFace->SetNormal(0.0f,0.0f,-1.0f); m_ArrayFace.Add(pFace); pFace = new CFace3d(m_ArrayVertex[3], m_ArrayVertex[1], m_ArrayVertex[2]); pFace->SetNormal(0.0f,0.0f,-1.0f); m_ArrayFace.Add(pFace); pFace = new CFace3d(m_ArrayVertex[0], m_ArrayVertex[4], m_ArrayVertex[1]); pFace->SetNormal(-1.0f,0.0f,0.0f); m_ArrayFace.Add(pFace); pFace = new CFace3d(m_ArrayVertex[1], m_ArrayVertex[4], m_ArrayVertex[5]); pFace->SetNormal(-1.0f,0.0f,0.0f); m_ArrayFace.Add(pFace); pFace = new CFace3d(m_ArrayVertex[3], m_ArrayVertex[2], m_ArrayVertex[7]); m_ArrayFace.Add(pFace); pFace->SetNormal(1.0f,0.0f,0.0f); pFace = new CFace3d(m_ArrayVertex[7], m_ArrayVertex[2], m_ArrayVertex[6]); m_ArrayFace.Add(pFace); pFace->SetNormal(1.0f,0.0f,0.0f); pFace = new CFace3d(m_ArrayVertex[4], m_ArrayVertex[0], m_ArrayVertex[3]); m_ArrayFace.Add(pFace); pFace->SetNormal(0.0f,-1.0f,0.0f); pFace = new CFace3d(m_ArrayVertex[7], m_ArrayVertex[4], m_ArrayVertex[3]); m_ArrayFace.Add(pFace); pFace->SetNormal(0.0f,-1.0f,0.0f); pFace = new CFace3d(m_ArrayVertex[6], m_ArrayVertex[4], m_ArrayVertex[7]); m_ArrayFace.Add(pFace); pFace->SetNormal(0.0f,0.0f,1.0f); pFace = new CFace3d(m_ArrayVertex[6], m_ArrayVertex[5], m_ArrayVertex[4]); m_ArrayFace.Add(pFace); pFace->SetNormal(0.0f,0.0f,1.0f); pFace = new CFace3d(m_ArrayVertex[1], m_ArrayVertex[5], m_ArrayVertex[6]); m_ArrayFace.Add(pFace); pFace->SetNormal(0.0f,1.0f,0.0f); pFace = new CFace3d(m_ArrayVertex[2], m_ArrayVertex[1], m_ArrayVertex[6]); m_ArrayFace.Add(pFace); pFace->SetNormal(0.0f,1.0f,0.0f); TRACE("ok\n"); return 1; } //******************************************** // GenerateMap //******************************************** int CMesh3d::GenerateMap(int line, int col, float min, float max) { TRACE("Generate map..."); float x,y,z; int i,j; // Set vertices for(i=0;i<col;i++) for(j=0;j<line;j++) { x = min + ((float)i/(float)line)*(max-min); z = min + ((float)j/(float)line)*(max-min); y = (float)(cos(x)*cos(z)); m_ArrayVertex.Add(new CVertex3d(x,y,z)); } // Set faces for(i=0;i<col-1;i++) for(j=0;j<line-1;j++) { CVertex3d *pVertex1 = m_ArrayVertex[line*i+j]; CVertex3d *pVertex2 = m_ArrayVertex[line*i+j+1]; CVertex3d *pVertex3 = m_ArrayVertex[line*(i+1)+j+1]; CVertex3d *pVertex4 = m_ArrayVertex[line*(i+1)+j]; m_ArrayFace.Add(new CFace3d(pVertex1,pVertex2,pVertex3)); m_ArrayFace.Add(new CFace3d(pVertex1,pVertex3,pVertex4)); } TRACE("ok\n"); return 1; } //******************************************** // GenerateMapFromImage //******************************************** int CMesh3d::GenerateMap(CTexture *pTexture, int width, int height, int FlagColor /* = 1 */) { // Cleanup Free(); int WidthImage = pTexture->GetWidth(); int HeightImage = pTexture->GetHeight(); unsigned char red,green,blue; // Vertices for(int j=0;j<height;j++) for(int i=0;i<width;i++) { int xImage = (int)((float)i/(float)width*(float)WidthImage); int yImage = (int)((float)j/(float)height*(float)HeightImage); int index = m_ArrayVertex.Add(new CVertex3d((float)i,(float)pTexture->Grey(xImage,yImage),(float)j)); if(FlagColor) { pTexture->Color(xImage,yImage,&red,&green,&blue); m_ArrayVertex[index]->SetColor(red,green,blue); } } // Faces for(int j=0;j<height-1;j++) for(int i=0;i<width-1;i++) { int index = m_ArrayFace.Add(new CFace3d(m_ArrayVertex[j*width+i+1], m_ArrayVertex[j*width+i], m_ArrayVertex[(j+1)*width+i+1])); m_ArrayFace.Add(new CFace3d(m_ArrayVertex[(j+1)*width+i+1], m_ArrayVertex[j*width+i], m_ArrayVertex[(j+1)*width+i])); if(FlagColor) { m_ArrayFace[index]->SetColor(*m_ArrayVertex[j*width+i]->GetColor()); m_ArrayFace[index+1]->SetColor(*m_ArrayVertex[j*width+i+1]->GetColor()); } } // Rebuild BuildAdjacency(); CalculateNormalPerFace(); CalculateNormalPerVertex(); return 1; } ///////////////////////////////////////////// // INTERSECTION ///////////////////////////////////////////// //******************************************** // NearestIntersectionWithLine // Non-optimized // Nearest -> distance from pV0 to pVertexResult //******************************************** int CMesh3d::NearestIntersectionWithLine(CVertex3d *pV0, CVertex3d *pV1, CVertex3d *pVertexResult, CFace3d **ppFaceResult, int *pNbFaceVisited) { return ::NearestIntersectionWithLine(&m_ArrayFace,pV0,pV1,pVertexResult,ppFaceResult,pNbFaceVisited); } ///////////////////////////////////////////// // I/O ///////////////////////////////////////////// //******************************************** // WriteFile //******************************************** int CMesh3d::WriteFile(CStdioFile &file) { CString string; TRY { // Comment string.Format("# Mesh : %d vertices, %d faces\n",NbVertex(),NbFace()); file.WriteString(string); // First line file.WriteString("DEF Mesh-ROOT Transform {\n"); // Transform string.Format(" translation %g %g %g\n",m_Transform.GetTranslation()->x(), m_Transform.GetTranslation()->y(), m_Transform.GetTranslation()->z()); file.WriteString(string); string.Format(" rotation %g %g %g %g\n",m_Transform.GetRotation()->x(), m_Transform.GetRotation()->y(), m_Transform.GetRotation()->z(), m_Transform.GetValueRotation()/360.0f*2*3.14159265359f); file.WriteString(string); string.Format(" scale %g %g %g\n",m_Transform.GetScale()->x(), m_Transform.GetScale()->y(), m_Transform.GetScale()->z()); file.WriteString(string); // Material file.WriteString(" children [\n"); file.WriteString(" Shape {\n"); file.WriteString(" appearance Appearance {\n"); file.WriteString(" material Material {\n"); file.WriteString(" diffuseColor 0 0 0\n"); // todo file.WriteString(" }\n"); file.WriteString(" }\n"); // Geometry file.WriteString(" geometry DEF Mesh-FACES IndexedFaceSet {\n"); file.WriteString(" ccw TRUE\n"); file.WriteString(" solid TRUE\n"); // Vertices file.WriteString(" coord DEF Mesh-COORD Coordinate { point [\n"); int NbVertex = m_ArrayVertex.GetSize(); for(int i=0;i<NbVertex;i++) { string.Format(" %g %g %g",m_ArrayVertex[i]->x(), m_ArrayVertex[i]->y(), m_ArrayVertex[i]->z()); file.WriteString(string); if(i!=(NbVertex-1)) file.WriteString(",\n"); else file.WriteString("]\n"); } file.WriteString(" }\n"); // Faces file.WriteString(" coordIndex [\n"); int NbFace = m_ArrayFace.GetSize(); for(int i=0;i<NbFace;i++) { string.Format(" %d, %d, %d, -1",m_ArrayVertex.IndexFrom(m_ArrayFace[i]->v(0)), m_ArrayVertex.IndexFrom(m_ArrayFace[i]->v(1)), m_ArrayVertex.IndexFrom(m_ArrayFace[i]->v(2))); file.WriteString(string); if(i!=(NbFace-1)) file.WriteString(",\n"); else file.WriteString("]\n"); } // End file.WriteString(" }\n"); file.WriteString(" }\n"); file.WriteString(" ]\n"); file.WriteString(" }\n\n"); } CATCH(CFileException, e) { #ifdef _DEBUG afxDump << "Error during writing transform" << e->m_cause << "\n"; #endif AfxMessageBox("Error during writing transform"); return 0; } END_CATCH return 1; } //******************************************** // WriteFileRaw (binary raw mode) //******************************************** int CMesh3d::WriteFileRaw(CFile &file) { // A mesh : //******************************************* // Transform : 10 * float 32 bits // NbVertices : UINT 32 bits // NbFaces : UINT 32 bits // Vertices : x y z : 3 x float 32 bits // Faces : v1 v2 v3 : 3 x UINT 32 bits //******************************************* // Cost : 40 + 8 + 12*(v+f) bytes CString string; TRY { // Transform // Translation (xyz) float x,y,z; x = m_Transform.GetTranslation()->x(); y = m_Transform.GetTranslation()->y(); z = m_Transform.GetTranslation()->z(); file.Write(&x,sizeof(float)); file.Write(&y,sizeof(float)); file.Write(&z,sizeof(float)); // Rotation (xyz) x = m_Transform.GetRotation()->x(); y = m_Transform.GetRotation()->y(); z = m_Transform.GetRotation()->z(); float v = m_Transform.GetValueRotation(); file.Write(&x,sizeof(float)); file.Write(&y,sizeof(float)); file.Write(&z,sizeof(float)); file.Write(&v,sizeof(float)); // Scale (xyz) x = m_Transform.GetScale()->x(); y = m_Transform.GetScale()->y(); z = m_Transform.GetScale()->z(); file.Write(&x,sizeof(float)); file.Write(&y,sizeof(float)); file.Write(&z,sizeof(float)); // Geometry // NbVertices // NbFaces unsigned int NbVertex = m_ArrayVertex.GetSize(); unsigned int NbFace = m_ArrayFace.GetSize(); file.Write(&NbVertex,sizeof(unsigned int)); file.Write(&NbFace,sizeof(unsigned int)); // Vertices for(unsigned int i=0;i<NbVertex;i++) { x = m_ArrayVertex[i]->x(); y = m_ArrayVertex[i]->y(); z = m_ArrayVertex[i]->z(); file.Write(&x,sizeof(float)); file.Write(&y,sizeof(float)); file.Write(&z,sizeof(float)); } // Faces unsigned int v1,v2,v3; for(int i=0;i<NbFace;i++) { v1 = m_ArrayVertex.IndexFrom(m_ArrayFace[i]->v1()); v2 = m_ArrayVertex.IndexFrom(m_ArrayFace[i]->v2()); v3 = m_ArrayVertex.IndexFrom(m_ArrayFace[i]->v3()); file.Write(&v1,sizeof(unsigned int)); file.Write(&v2,sizeof(unsigned int)); file.Write(&v3,sizeof(unsigned int)); } } CATCH(CFileException, e) { #ifdef _DEBUG afxDump << "Error during writing " << e->m_cause << "\n"; #endif AfxMessageBox("Error during writing"); return 0; } END_CATCH return 1; } //******************************************** // GetMinArea //******************************************** double CMesh3d::GetMinArea(CFace3d **ppFace /* NULL */) { double min = MAX_DOUBLE; int size = m_ArrayFace.GetSize(); for(int i=0;i<size;i++) { double area = m_ArrayFace[i]->Area(); if(area < min) { min = area; if(ppFace != NULL) *ppFace = m_ArrayFace[i]; } } return min; } //******************************************** // GetMeanArea //******************************************** double CMesh3d::GetMeanArea() { return ::GetMeanArea(&m_ArrayFace); } //********************************* // GenerateEdgeArray //********************************* int CMesh3d::GenerateEdgeArray(CArray3d<CEdge3d> *pArrayEdge, BOOL FlagOnBoundary, char flag, BOOL *pHasBoundary) { ASSERT(pArrayEdge != NULL); int NbVertex = m_ArrayVertex.GetSize(); // Set flags SetFlagOnVertices(0); TRACE(" begin generate edge array\n"); TRACE(" %d vertices\n",NbVertex); TRACE(" %d faces\n",NbFace()); int NbEdgePrevious = NbVertex+NbFace(); TRACE(" %d edges previous\n",NbEdgePrevious); pArrayEdge->SetSize(NbEdgePrevious); int NbEdge = 0; TRACE(" begin..."); for(int i=0;i<NbVertex;i++) { CVertex3d *pVertex = m_ArrayVertex[i]; int NbVertexNeighbor = pVertex->NbVertexNeighbor(); for(int j=0;j<NbVertexNeighbor;j++) { CVertex3d *pNeighbor = pVertex->GetVertexNeighbor(j); ASSERT(pNeighbor != NULL); if(pNeighbor->GetFlag() == 0) { // Alloc CEdge3d *pEdge = new CEdge3d(pVertex,pNeighbor); // Set faces (at least one) CArray3d<CFace3d> array; pVertex->FindFaceAroundContainVertex(pNeighbor,array); ASSERT(array.GetSize() >= 1); pEdge->f1(array[0]); if(array.GetSize() > 1) pEdge->f2(array[1]); if(NbEdge<NbEdgePrevious) pArrayEdge->SetAt(NbEdge,pEdge); else pArrayEdge->Add(pEdge); NbEdge++; // Flag (optional) if(FlagOnBoundary) if(pVertex->IsOnBoundary() && pNeighbor->IsOnBoundary()) { *pHasBoundary = TRUE; pEdge->SetFlag(flag); } } } pVertex->SetFlag(1); // done //if(i%(NbVertex/30)==0) { TRACE("."); } } TRACE("ok\n"); pArrayEdge->SetSize(NbEdge); TRACE(" %d edges\n",NbEdge); return 1; } //******************************************** // glDrawProjectLine // paint the current mesh via projection // in line mode //******************************************** void CMesh3d::glDrawProjectLine(CDC *pDC, double *modelMatrix, double *projMatrix, int *viewport, COLORREF ColorLine, double ratio, int height) { TRACE("Draw projected mesh in metafile-based device context\n"); TRACE(" line mode\n"); TRACE(" viewport : (%d;%d;%d;%d)\n",viewport[0],viewport[1],viewport[2],viewport[3]); TRACE(" model : %g\t%g\t%g\n",modelMatrix[0],modelMatrix[1],modelMatrix[2]); TRACE(" %g\t%g\t%g\n",modelMatrix[3],modelMatrix[4],modelMatrix[5]); TRACE(" %g\t%g\t%g\n",modelMatrix[6],modelMatrix[7],modelMatrix[8]); TRACE(" proj : %g\t%g\t%g\n",projMatrix[0],projMatrix[1],projMatrix[2]); TRACE(" %g\t%g\t%g\n",projMatrix[3],projMatrix[4],projMatrix[5]); TRACE(" %g\t%g\t%g\n",projMatrix[6],projMatrix[7],projMatrix[8]); // Generate edge array (it saves memory) CArray3d<CEdge3d> ArrayEdge; GenerateEdgeArray(&ArrayEdge); // Select pen CPen pen(PS_SOLID,0,ColorLine); CPen *pOldPen = pDC->SelectObject(&pen); double x1,y1,x2,y2,z; for(int i=0;i<ArrayEdge.GetSize();i++) { CEdge3d *pEdge = ArrayEdge[i]; ASSERT(pEdge != NULL); gluProject((double)pEdge->v1()->x(), (double)pEdge->v1()->y(), (double)pEdge->v1()->z(), modelMatrix, projMatrix, viewport,&x1,&y1,&z); gluProject((double)pEdge->v2()->x(), (double)pEdge->v2()->y(), (double)pEdge->v2()->z(), modelMatrix, projMatrix, viewport,&x2,&y2,&z); // Crop to window if(x1 < viewport[0] || y1 < viewport[1] || x1 > viewport[2] || y1 > viewport[3] || x2 < viewport[0] || y2 < viewport[1] || x2 > viewport[2] || y2 > viewport[3]) continue; // crop to window else // draw { pDC->MoveTo((int)(ratio*x1),(int)(ratio*((float)height-y1))); pDC->LineTo((int)(ratio*x2),(int)(ratio*((float)height-y2))); } } // Cleanup ArrayEdge.Free(); pDC->SelectObject(pOldPen); } //******************************************** // glDrawProjectFace //******************************************** void CMesh3d::glDrawProjectFace(CDC *pDC, double *modelMatrix, double *projMatrix, int *viewport, COLORREF ColorLine, COLORREF ColorFace, double ratio, int height, // window height float RatioNbFace) // default -> 1.0 { TRACE("Draw projected mesh in metafile-based device context\n"); TRACE(" face mode\n"); TRACE(" viewport : (%d;%d;%d;%d)\n",viewport[0],viewport[1],viewport[2],viewport[3]); TRACE(" model : %g\t%g\t%g\n",modelMatrix[0],modelMatrix[1],modelMatrix[2]); TRACE(" %g\t%g\t%g\n",modelMatrix[3],modelMatrix[4],modelMatrix[5]); TRACE(" %g\t%g\t%g\n",modelMatrix[6],modelMatrix[7],modelMatrix[8]); TRACE(" proj : %g\t%g\t%g\n",projMatrix[0],projMatrix[1],projMatrix[2]); TRACE(" %g\t%g\t%g\n",projMatrix[3],projMatrix[4],projMatrix[5]); TRACE(" %g\t%g\t%g\n",projMatrix[6],projMatrix[7],projMatrix[8]); CWmfFace *pArray = new CWmfFace[m_ArrayFace.GetSize()]; // Many thanks to Gaspard Breton for having // implemented the AVL fast z-sorting part. ASSERT(pArray); CAVL<CWmfFace,double> avl; CWmfFace bidon; avl.Register(&bidon,&bidon.zc,&bidon.avl); // z as key int NbFaces = m_ArrayFace.GetSize(); TRACE(" %d faces\n",NbFaces); int NbFacesToProcess = (int)(RatioNbFace*(float)NbFaces); TRACE(" %d faces to process\n",NbFacesToProcess); TRACE(" begin sort..."); int NbFaceValid = 0; for(int i=0;i<NbFaces;i++) { CFace3d *pFace = m_ArrayFace[i]; // Compute barycenter as z-reference // Sorting by a triangle average depth does not allow // to disambiguate some cases. Handling these cases would // require breaking up the primitives. Please mail any // improvement about this double xc = (pFace->v1()->x()+pFace->v2()->x()+pFace->v3()->x())/3; double yc = (pFace->v1()->y()+pFace->v2()->y()+pFace->v3()->y())/3; double zc = (pFace->v1()->z()+pFace->v2()->z()+pFace->v3()->z())/3; // Project center gluProject(xc,yc,zc, modelMatrix, projMatrix, viewport,&pArray[i].xc,&pArray[i].yc,&pArray[i].zc); // Project three vertices gluProject((double)pFace->v1()->x(), (double)pFace->v1()->y(), (double)pFace->v1()->z(), modelMatrix, projMatrix, viewport,&pArray[i].x1,&pArray[i].y1,&pArray[i].z1); gluProject((double)pFace->v2()->x(), (double)pFace->v2()->y(), (double)pFace->v2()->z(), modelMatrix, projMatrix, viewport,&pArray[i].x2,&pArray[i].y2,&pArray[i].z2); gluProject((double)pFace->v3()->x(), (double)pFace->v3()->y(), (double)pFace->v3()->z(), modelMatrix, projMatrix, viewport,&pArray[i].x3,&pArray[i].y3,&pArray[i].z3); // Crop & sort if(pArray[i].x1 < viewport[0] || pArray[i].y1 < viewport[1] || pArray[i].x1 > viewport[2] || pArray[i].y1 > viewport[3] || pArray[i].x2 < viewport[0] || pArray[i].y2 < viewport[1] || pArray[i].x2 > viewport[2] || pArray[i].y2 > viewport[3] || pArray[i].x3 < viewport[0] || pArray[i].y3 < viewport[1] || pArray[i].x3 > viewport[2] || pArray[i].y3 > viewport[3]) continue; else { pArray[i].m_Draw = 1; // yes, insert this triangle pArray[i].zc *= -1.0f; // back to front avl.Insert(pArray,i); // insert via sort NbFaceValid++; } } TRACE("ok\n"); // Draw CPen pen(PS_SOLID,0,ColorLine); CBrush BrushFace(ColorFace); CPen *pOldPen = pDC->SelectObject(&pen); POINT points[3]; // triangular faces only // Default CBrush *pOldBrush = pDC->SelectObject(&BrushFace); TRACE("begin draw..."); int nb = 0; for(int i=avl.GetFirst(pArray); (AVLNULL != i) && nb < NbFacesToProcess; i=avl.GetNext(pArray),nb++) { // Fill and outline the face points[0].x = (int)(ratio*pArray[i].x1); points[0].y = (int)(ratio*((float)height-pArray[i].y1)); points[1].x = (int)(ratio*pArray[i].x2); points[1].y = (int)(ratio*((float)height-pArray[i].y2)); points[2].x = (int)(ratio*pArray[i].x3); points[2].y = (int)(ratio*((float)height-pArray[i].y3)); // Fill triangle pDC->Polygon(points,3); // Outline triangle pDC->MoveTo(points[0]); pDC->LineTo(points[1]); pDC->LineTo(points[2]); pDC->LineTo(points[0]); } TRACE("ok\n"); // Restore and cleanup pDC->SelectObject(pOldPen); pDC->SelectObject(pOldBrush); delete [] pArray; } // ** EOF **
[ "heguanyu@seas.upenn.edu" ]
heguanyu@seas.upenn.edu
5a2c33aeb5c64c04f0b5ee575f9110e472bf504b
e097ca136d17ff092e89b3b54214ec09f347604f
/include/amtrs/graphics/g3d/vulkan/g3d-vulkan-vkvertexbuffer.hpp
6e1a8a544a71388f134db20e7500924c736d9ec5
[ "BSD-2-Clause" ]
permissive
isaponsoft/libamtrs
1c02063c06613cc43091d5341c132b45d3051ee0
0c5d4ebe7e0f23d260bf091a4ab73ab9809daa50
refs/heads/master
2023-01-14T16:48:23.908727
2022-12-28T02:27:46
2022-12-28T02:27:46
189,788,925
2
0
null
null
null
null
UTF-8
C++
false
false
784
hpp
/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. * * Use of this source code is governed by a BSD-style license that * * can be found in the LICENSE file. */ #ifndef __libamtrs__driver__g3d__vulkan__vkvertexbuffer__hpp #define __libamtrs__driver__g3d__vulkan__vkvertexbuffer__hpp AMTRS_G3D_VKUTIL_NAMESPACE_BEGIN class vkvertexbuffer : public ref_object { public: void initialize(vertexbuffer::instance_type* _owner, vkref<VkDevice> const& _device, void const* _data = nullptr, size_t _size = 0) { mOwner = _owner; mVertexBuff = vkref<VkBuffer>::create_vertex_buffer(_device, _data, _size); } vertexbuffer::instance_type* mOwner; vkref<VkBuffer> mVertexBuff; }; AMTRS_G3D_VKUTIL_NAMESPACE_END #endif
[ "isaponsoft@gmail.com" ]
isaponsoft@gmail.com
25900a1a59e48aa42c9dff581436030877768a36
0cb85cd0c88a9b9f0cca4472742c2bf9febef2d8
/CommonFiles/KLUtil/ObjectName.cpp
ecd0c57e4d5b1c523e59bc877cca1a1f39e30d52
[]
no_license
seth1002/antivirus-1
9dfbadc68e16e51f141ac8b3bb283c1d25792572
3752a3b20e1a8390f0889f6192ee6b851e99e8a4
refs/heads/master
2020-07-15T00:30:19.131934
2016-07-21T13:59:11
2016-07-21T13:59:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
895
cpp
// ObjectName.cpp: implementation of the ObjectName class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ObjectName.h" #include "OsVersion.h" CStdString KLUTIL::MakeMutexName(LPCTSTR szPrefix, const CStdString &sName) { CStdString sMutexName = szPrefix; for (int i = 0;i < sName.GetLength();i++) { if (sName[i] != _T('\\') && sName[i] != _T(':') && sName[i] != _T('/') && sName[i] != _T(';') && sName[i] != _T('+') && sName[i] != _T('.')) sMutexName += sName[i]; else sMutexName += _T("_"); } return sMutexName; } CStdString KLUTIL::MakeGlobalObjectName(LPCTSTR pszName) { CStdString rc; COSVersion ver; if (pszName && *pszName) { if (ver.IsGlobalNamespaceSupported()) rc.Format(_T("Global\\%s"), pszName); else rc = pszName; } return rc; }
[ "idrez.mochamad@gmail.com" ]
idrez.mochamad@gmail.com
5cc8de66e881914d88486567d0af332e1c02489a
6e09d72177402b133921a0cc611d4fbeabcf3aed
/Cpp/c++/Book/虚析构函数.cpp
0b1e83004a879fb85c8901d8fa76f9ae7384fa7e
[]
no_license
aravinda-kumar/Code
4f91617c79569cccb7bbf517a3699d16fa7e1377
eccdee6fe73237e2982b128a04813c854e4cfd4d
refs/heads/master
2020-05-01T10:31:20.940519
2019-03-24T05:09:01
2019-03-24T05:09:01
177,422,267
1
0
null
2019-03-24T13:59:14
2019-03-24T13:59:14
null
UTF-8
C++
false
false
388
cpp
//#include <iostream> //using namespace std; // //class Point //{ //public: // Point(){} // virtual ~Point(){cout << "Executing Point destructor!" << endl;} //}; // //class Circle:public Point //{ //public: // Circle(){} // ~Circle(){cout << "Executing Circle destructor!" << endl;} //}; // //int main() //{ // Point *pt = new Circle; // delete pt; // // system("pause"); // return 0; //}
[ "1109478681@qq.com" ]
1109478681@qq.com
4afae26e42c9d76e1506690b47534e19b3256254
414f101be9888b2e1c6db4cd157b995d54097528
/node_modules/@serialport/bindings/src/serialport.cpp
bb6ec6137c9d3ebb4fd8c3b7f3c760b72667adec
[ "MIT" ]
permissive
umair9747/Plixy
09a8155bec583b176134c9d4f968dac5a077fb0c
36e0fcd910a1b4ce3e5ed71008d5263331596a5e
refs/heads/master
2022-12-21T00:28:14.411823
2021-05-30T07:43:46
2021-05-30T07:43:46
193,962,917
5
4
MIT
2022-06-25T05:45:20
2019-06-26T19:07:00
JavaScript
UTF-8
C++
false
false
13,197
cpp
#include "./serialport.h" #ifdef __APPLE__ #include "./darwin_list.h" #endif #ifdef WIN32 #define strncasecmp strnicmp #include "./serialport_win.h" #else #include "./poller.h" #endif v8::Local<v8::Value> getValueFromObject(v8::Local<v8::Object> options, std::string key) { v8::Local<v8::String> v8str = Nan::New<v8::String>(key).ToLocalChecked(); return Nan::Get(options, v8str).ToLocalChecked(); } int getIntFromObject(v8::Local<v8::Object> options, std::string key) { return Nan::To<v8::Int32>(getValueFromObject(options, key)).ToLocalChecked()->Value(); } bool getBoolFromObject(v8::Local<v8::Object> options, std::string key) { return Nan::To<v8::Boolean>(getValueFromObject(options, key)).ToLocalChecked()->Value(); } v8::Local<v8::String> getStringFromObj(v8::Local<v8::Object> options, std::string key) { return Nan::To<v8::String>(getValueFromObject(options, key)).ToLocalChecked(); } double getDoubleFromObject(v8::Local<v8::Object> options, std::string key) { return Nan::To<double>(getValueFromObject(options, key)).FromMaybe(0); } NAN_METHOD(Open) { // path if (!info[0]->IsString()) { Nan::ThrowTypeError("First argument must be a string"); return; } Nan::Utf8String path(info[0]); // options if (!info[1]->IsObject()) { Nan::ThrowTypeError("Second argument must be an object"); return; } v8::Local<v8::Object> options = Nan::To<v8::Object>(info[1]).ToLocalChecked(); // callback if (!info[2]->IsFunction()) { Nan::ThrowTypeError("Third argument must be a function"); return; } OpenBaton* baton = new OpenBaton(); snprintf(baton->path, sizeof(baton->path), "%s", *path); baton->baudRate = getIntFromObject(options, "baudRate"); baton->dataBits = getIntFromObject(options, "dataBits"); baton->parity = ToParityEnum(getStringFromObj(options, "parity")); baton->stopBits = ToStopBitEnum(getDoubleFromObject(options, "stopBits")); baton->rtscts = getBoolFromObject(options, "rtscts"); baton->xon = getBoolFromObject(options, "xon"); baton->xoff = getBoolFromObject(options, "xoff"); baton->xany = getBoolFromObject(options, "xany"); baton->hupcl = getBoolFromObject(options, "hupcl"); baton->lock = getBoolFromObject(options, "lock"); baton->callback.Reset(info[2].As<v8::Function>()); #ifndef WIN32 baton->vmin = getIntFromObject(options, "vmin"); baton->vtime = getIntFromObject(options, "vtime"); #endif uv_work_t* req = new uv_work_t(); req->data = baton; uv_queue_work(uv_default_loop(), req, EIO_Open, (uv_after_work_cb)EIO_AfterOpen); } void EIO_AfterOpen(uv_work_t* req) { Nan::HandleScope scope; OpenBaton* data = static_cast<OpenBaton*>(req->data); v8::Local<v8::Value> argv[2]; if (data->errorString[0]) { argv[0] = v8::Exception::Error(Nan::New<v8::String>(data->errorString).ToLocalChecked()); argv[1] = Nan::Undefined(); } else { argv[0] = Nan::Null(); argv[1] = Nan::New<v8::Int32>(data->result); } data->callback.Call(2, argv, data); delete data; delete req; } NAN_METHOD(Update) { // file descriptor if (!info[0]->IsInt32()) { Nan::ThrowTypeError("First argument must be an int"); return; } int fd = Nan::To<int>(info[0]).FromJust(); // options if (!info[1]->IsObject()) { Nan::ThrowTypeError("Second argument must be an object"); return; } v8::Local<v8::Object> options = Nan::To<v8::Object>(info[1]).ToLocalChecked(); if (!Nan::Has(options, Nan::New<v8::String>("baudRate").ToLocalChecked()).FromMaybe(false)) { Nan::ThrowTypeError("\"baudRate\" must be set on options object"); return; } // callback if (!info[2]->IsFunction()) { Nan::ThrowTypeError("Third argument must be a function"); return; } ConnectionOptionsBaton* baton = new ConnectionOptionsBaton(); baton->fd = fd; baton->baudRate = getIntFromObject(options, "baudRate"); baton->callback.Reset(info[2].As<v8::Function>()); uv_work_t* req = new uv_work_t(); req->data = baton; uv_queue_work(uv_default_loop(), req, EIO_Update, (uv_after_work_cb)EIO_AfterUpdate); } void EIO_AfterUpdate(uv_work_t* req) { Nan::HandleScope scope; ConnectionOptionsBaton* data = static_cast<ConnectionOptionsBaton*>(req->data); v8::Local<v8::Value> argv[1]; if (data->errorString[0]) { argv[0] = v8::Exception::Error(Nan::New<v8::String>(data->errorString).ToLocalChecked()); } else { argv[0] = Nan::Null(); } data->callback.Call(1, argv, data); delete data; delete req; } NAN_METHOD(Close) { // file descriptor if (!info[0]->IsInt32()) { Nan::ThrowTypeError("First argument must be an int"); return; } // callback if (!info[1]->IsFunction()) { Nan::ThrowTypeError("Second argument must be a function"); return; } VoidBaton* baton = new VoidBaton(); baton->fd = Nan::To<v8::Int32>(info[0]).ToLocalChecked()->Value(); baton->callback.Reset(info[1].As<v8::Function>()); uv_work_t* req = new uv_work_t(); req->data = baton; uv_queue_work(uv_default_loop(), req, EIO_Close, (uv_after_work_cb)EIO_AfterClose); } void EIO_AfterClose(uv_work_t* req) { Nan::HandleScope scope; VoidBaton* data = static_cast<VoidBaton*>(req->data); v8::Local<v8::Value> argv[1]; if (data->errorString[0]) { argv[0] = v8::Exception::Error(Nan::New<v8::String>(data->errorString).ToLocalChecked()); } else { argv[0] = Nan::Null(); } data->callback.Call(1, argv, data); delete data; delete req; } NAN_METHOD(Flush) { // file descriptor if (!info[0]->IsInt32()) { Nan::ThrowTypeError("First argument must be an int"); return; } int fd = Nan::To<int>(info[0]).FromJust(); // callback if (!info[1]->IsFunction()) { Nan::ThrowTypeError("Second argument must be a function"); return; } v8::Local<v8::Function> callback = info[1].As<v8::Function>(); VoidBaton* baton = new VoidBaton(); baton->fd = fd; baton->callback.Reset(callback); uv_work_t* req = new uv_work_t(); req->data = baton; uv_queue_work(uv_default_loop(), req, EIO_Flush, (uv_after_work_cb)EIO_AfterFlush); } void EIO_AfterFlush(uv_work_t* req) { Nan::HandleScope scope; VoidBaton* data = static_cast<VoidBaton*>(req->data); v8::Local<v8::Value> argv[1]; if (data->errorString[0]) { argv[0] = v8::Exception::Error(Nan::New<v8::String>(data->errorString).ToLocalChecked()); } else { argv[0] = Nan::Null(); } data->callback.Call(1, argv, data); delete data; delete req; } NAN_METHOD(Set) { // file descriptor if (!info[0]->IsInt32()) { Nan::ThrowTypeError("First argument must be an int"); return; } int fd = Nan::To<int>(info[0]).FromJust(); // options if (!info[1]->IsObject()) { Nan::ThrowTypeError("Second argument must be an object"); return; } v8::Local<v8::Object> options = Nan::To<v8::Object>(info[1]).ToLocalChecked(); // callback if (!info[2]->IsFunction()) { Nan::ThrowTypeError("Third argument must be a function"); return; } v8::Local<v8::Function> callback = info[2].As<v8::Function>(); SetBaton* baton = new SetBaton(); baton->fd = fd; baton->callback.Reset(callback); baton->brk = getBoolFromObject(options, "brk"); baton->rts = getBoolFromObject(options, "rts"); baton->cts = getBoolFromObject(options, "cts"); baton->dtr = getBoolFromObject(options, "dtr"); baton->dsr = getBoolFromObject(options, "dsr"); uv_work_t* req = new uv_work_t(); req->data = baton; uv_queue_work(uv_default_loop(), req, EIO_Set, (uv_after_work_cb)EIO_AfterSet); } void EIO_AfterSet(uv_work_t* req) { Nan::HandleScope scope; SetBaton* data = static_cast<SetBaton*>(req->data); v8::Local<v8::Value> argv[1]; if (data->errorString[0]) { argv[0] = v8::Exception::Error(Nan::New<v8::String>(data->errorString).ToLocalChecked()); } else { argv[0] = Nan::Null(); } data->callback.Call(1, argv, data); delete data; delete req; } NAN_METHOD(Get) { // file descriptor if (!info[0]->IsInt32()) { Nan::ThrowTypeError("First argument must be an int"); return; } int fd = Nan::To<int>(info[0]).FromJust(); // callback if (!info[1]->IsFunction()) { Nan::ThrowTypeError("Second argument must be a function"); return; } GetBaton* baton = new GetBaton(); baton->fd = fd; baton->cts = false; baton->dsr = false; baton->dcd = false; baton->callback.Reset(info[1].As<v8::Function>()); uv_work_t* req = new uv_work_t(); req->data = baton; uv_queue_work(uv_default_loop(), req, EIO_Get, (uv_after_work_cb)EIO_AfterGet); } void EIO_AfterGet(uv_work_t* req) { Nan::HandleScope scope; GetBaton* data = static_cast<GetBaton*>(req->data); v8::Local<v8::Value> argv[2]; if (data->errorString[0]) { argv[0] = v8::Exception::Error(Nan::New<v8::String>(data->errorString).ToLocalChecked()); argv[1] = Nan::Undefined(); } else { v8::Local<v8::Object> results = Nan::New<v8::Object>(); results->Set(Nan::New<v8::String>("cts").ToLocalChecked(), Nan::New<v8::Boolean>(data->cts)); results->Set(Nan::New<v8::String>("dsr").ToLocalChecked(), Nan::New<v8::Boolean>(data->dsr)); results->Set(Nan::New<v8::String>("dcd").ToLocalChecked(), Nan::New<v8::Boolean>(data->dcd)); argv[0] = Nan::Null(); argv[1] = results; } data->callback.Call(2, argv, data); delete data; delete req; } NAN_METHOD(GetBaudRate) { // file descriptor if (!info[0]->IsInt32()) { Nan::ThrowTypeError("First argument must be an int"); return; } int fd = Nan::To<int>(info[0]).FromJust(); // callback if (!info[1]->IsFunction()) { Nan::ThrowTypeError("Second argument must be a function"); return; } GetBaudRateBaton* baton = new GetBaudRateBaton(); baton->fd = fd; baton->baudRate = 0; baton->callback.Reset(info[1].As<v8::Function>()); uv_work_t* req = new uv_work_t(); req->data = baton; uv_queue_work(uv_default_loop(), req, EIO_GetBaudRate, (uv_after_work_cb)EIO_AfterGetBaudRate); } void EIO_AfterGetBaudRate(uv_work_t* req) { Nan::HandleScope scope; GetBaudRateBaton* data = static_cast<GetBaudRateBaton*>(req->data); v8::Local<v8::Value> argv[2]; if (data->errorString[0]) { argv[0] = v8::Exception::Error(Nan::New<v8::String>(data->errorString).ToLocalChecked()); argv[1] = Nan::Undefined(); } else { v8::Local<v8::Object> results = Nan::New<v8::Object>(); results->Set(Nan::New<v8::String>("baudRate").ToLocalChecked(), Nan::New<v8::Integer>(data->baudRate)); argv[0] = Nan::Null(); argv[1] = results; } data->callback.Call(2, argv, data); delete data; delete req; } NAN_METHOD(Drain) { // file descriptor if (!info[0]->IsInt32()) { Nan::ThrowTypeError("First argument must be an int"); return; } int fd = Nan::To<int>(info[0]).FromJust(); // callback if (!info[1]->IsFunction()) { Nan::ThrowTypeError("Second argument must be a function"); return; } VoidBaton* baton = new VoidBaton(); baton->fd = fd; baton->callback.Reset(info[1].As<v8::Function>()); uv_work_t* req = new uv_work_t(); req->data = baton; uv_queue_work(uv_default_loop(), req, EIO_Drain, (uv_after_work_cb)EIO_AfterDrain); } void EIO_AfterDrain(uv_work_t* req) { Nan::HandleScope scope; VoidBaton* data = static_cast<VoidBaton*>(req->data); v8::Local<v8::Value> argv[1]; if (data->errorString[0]) { argv[0] = v8::Exception::Error(Nan::New<v8::String>(data->errorString).ToLocalChecked()); } else { argv[0] = Nan::Null(); } data->callback.Call(1, argv, data); delete data; delete req; } SerialPortParity NAN_INLINE(ToParityEnum(const v8::Local<v8::String>& v8str)) { Nan::HandleScope scope; Nan::Utf8String str(v8str); size_t count = strlen(*str); SerialPortParity parity = SERIALPORT_PARITY_NONE; if (!strncasecmp(*str, "none", count)) { parity = SERIALPORT_PARITY_NONE; } else if (!strncasecmp(*str, "even", count)) { parity = SERIALPORT_PARITY_EVEN; } else if (!strncasecmp(*str, "mark", count)) { parity = SERIALPORT_PARITY_MARK; } else if (!strncasecmp(*str, "odd", count)) { parity = SERIALPORT_PARITY_ODD; } else if (!strncasecmp(*str, "space", count)) { parity = SERIALPORT_PARITY_SPACE; } return parity; } SerialPortStopBits NAN_INLINE(ToStopBitEnum(double stopBits)) { if (stopBits > 1.4 && stopBits < 1.6) { return SERIALPORT_STOPBITS_ONE_FIVE; } if (stopBits == 2) { return SERIALPORT_STOPBITS_TWO; } return SERIALPORT_STOPBITS_ONE; } NAN_MODULE_INIT(init) { Nan::HandleScope scope; Nan::SetMethod(target, "set", Set); Nan::SetMethod(target, "get", Get); Nan::SetMethod(target, "getBaudRate", GetBaudRate); Nan::SetMethod(target, "open", Open); Nan::SetMethod(target, "update", Update); Nan::SetMethod(target, "close", Close); Nan::SetMethod(target, "flush", Flush); Nan::SetMethod(target, "drain", Drain); #ifdef __APPLE__ Nan::SetMethod(target, "list", List); #endif #ifdef WIN32 Nan::SetMethod(target, "write", Write); Nan::SetMethod(target, "read", Read); Nan::SetMethod(target, "list", List); #else Poller::Init(target); #endif } NODE_MODULE(serialport, init);
[ "umairnehri9747@Gmail.com" ]
umairnehri9747@Gmail.com
065ea041648b95c5941f03db16d0182a79d4bfa2
29868bf4aa31c1ca8b8c86e5b5b07cc3509caf64
/Nuevo, poli/Nuevo, poli/Funciones.cpp
8c7c20ca5d3ba051631f205ceb9989445a2f8a6a
[]
no_license
Laura-Mora/PC-2016-03
a137746a8c1939235a5176a0ecc2d8234ee87348
0cf0826bdb8a3be89c9da0e70a6726388c6ba0c6
refs/heads/master
2023-07-20T15:16:07.676365
2019-12-30T01:52:28
2019-12-30T01:52:28
222,524,088
0
0
null
null
null
null
UTF-8
C++
false
false
2,758
cpp
// // Funciones.cpp // Nuevo, poli // Polinomios sin Templates // Created by Laura Juliana Mora on 16/09/16. // Copyright © 2016 Laura Juliana Mora. All rights reserved. // #include <iostream> #include <math.h> #include "Funciones.hpp" using namespace std; Lista *crearlista(){ Lista *lista = new Lista; lista->tam=0; lista->cab=NULL; return lista; } void insertar(Lista *lista, int infonueva, int exponente){ Nodo *nuevo; nuevo= new Nodo; nuevo->info.num=infonueva; nuevo->info.expo=exponente; nuevo->sig=NULL; if(lista->tam==0){ lista->cab=nuevo; lista->tam++; } else{ Nodo *aux; aux=lista->cab; while(aux->sig!=NULL){ aux=aux->sig; } aux->sig=nuevo; lista->tam++; } } bool vacia (Lista *lista){ if(lista->tam==0) return true; else return false; } void imprimir(Lista *lista){ if(vacia(lista)) cout<<"La lista no tiene información"<<"\n"; else{ Nodo *aux; aux=lista->cab; int pos=1; while(aux!=NULL){ cout<<aux->info.num<<"x^"<<aux->info.expo; if(aux->sig!=NULL) cout<<" + "; aux=aux->sig; pos++; } } cout<<"\n"; } int obtenerDato(Lista * lista, int pos) { Nodo * aux; aux = lista->cab; while(aux != NULL) { if(pos == aux->info.expo) { return aux->info.num; } aux = aux->sig; } return 0; } bool esta(Lista *lista, int nume){ Nodo *aux; aux=lista->cab; while(aux!=NULL){ if(aux->info.expo==nume) return true; else aux=aux->sig; } return false; } void sumar(Lista *lista, Lista *lista2, Lista *listafinal){ Nodo *aux1,*aux2; int num=0,sum=0; aux1=lista->cab; aux2=lista2->cab; while(aux1 != NULL){ num=obtenerDato(lista2, aux1->info.expo); sum=num+aux1->info.num; if(sum!=0) insertar(listafinal, sum, aux1->info.expo); aux1=aux1->sig; } while(aux2 != NULL){ if(esta(listafinal,aux2->info.expo)) aux2=aux2->sig; else{ num=obtenerDato(lista, aux2->info.expo); sum=num+aux2->info.num; if(sum!=0) insertar(listafinal, sum, aux2->info.expo); aux2=aux2->sig; } } cout<<"Suma de Polinomios (Polinomio Final):\n"; imprimir(listafinal); } int solucion(Lista *lista, int x){ int sum=0,n=0; Nodo *aux; aux=lista->cab; while(aux!=NULL){ n=aux->info.num*pow(x, aux->info.expo); sum=sum+n; aux=aux->sig; } return sum; }
[ "noreply@github.com" ]
noreply@github.com
d80e734d2569e04f44c8b0a4a30f55f51675d94b
4f2f05fd53838af26a4535d37e69e554e59b93a3
/extensions/arduino/kit/QHRobot/lib/ArduinoJson6_8/examples/JsonGeneratorExample/JsonGeneratorExample.ino
f7833450bfba02487e473e31218cbcfa3d972f13
[ "MIT" ]
permissive
hm053/external-resources
432d7f2615ee86041cc81873fa961509cfe6fdbb
47a69922356636d0f059dd1f32917c50f19c4494
refs/heads/main
2023-07-03T10:53:34.095464
2021-08-09T11:37:29
2021-08-09T11:37:29
394,267,144
0
0
null
2021-08-09T11:36:43
2021-08-09T11:36:42
null
UTF-8
C++
false
false
1,553
ino
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2018 // MIT License // // This example shows how to generate a JSON document with ArduinoJson. #include <ArduinoJson6_8.h> void setup() { // Initialize Serial port Serial.begin(9600); while (!Serial) continue; // Allocate the JSON document // // Inside the brackets, 200 is the RAM allocated to this document. // Don't forget to change this value to match your requirement. // Use arduinojson.org/v6/assistant to compute the capacity. StaticJsonDocument<200> doc; // StaticJsonObject allocates memory on the stack, it can be // replaced by DynamicJsonDocument which allocates in the heap. // // DynamicJsonDocument doc(200); // Add values in the document // doc["sensor"] = "gps"; doc["time"] = 1351824120; // Add an array. // JsonArray data = doc.createNestedArray("data"); data.add(48.756080); data.add(2.302038); // Generate the minified JSON and send it to the Serial port. // serializeJson(doc, Serial); // The above line prints: // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]} // Start a new line Serial.println(); // Generate the prettified JSON and send it to the Serial port. // serializeJsonPretty(doc, Serial); // The above line prints: // { // "sensor": "gps", // "time": 1351824120, // "data": [ // 48.756080, // 2.302038 // ] // } } void loop() { // not used in this example } // Visit https://arduinojson.org/v6/example/generator/ for more.
[ "postmaster@mircoai.com" ]
postmaster@mircoai.com
af9ed6af03de264eba815832447ae245d6d935a5
88bae6f0f0cc9c9e71daf1435b6eb803e66d6a4d
/src/vector2.cpp
a4e018b87f298a03a591dcfd02671b30870c8d6d
[ "MIT" ]
permissive
AlphaZoneR/miniglm
666df1265dd1b3a471da1c0c80a28a7633934f53
8f99785379660561a7d5669b283033e6bc831d7c
refs/heads/master
2021-08-30T16:42:55.426587
2017-11-27T15:47:38
2017-11-27T15:47:38
112,213,143
0
0
null
2017-11-27T15:25:07
2017-11-27T15:25:07
null
UTF-8
C++
false
false
10,652
cpp
#include "common.hpp" #define N 2 PyObject * GLMVec2_tp_new(PyTypeObject * type, PyObject * args, PyObject * kwargs) { GLMVec2 * self = (GLMVec2 *)type->tp_alloc(type, 0); if (self) { } return (PyObject *)self; } void GLMVec2_tp_dealloc(GLMVec2 * self) { Py_TYPE(self)->tp_free((PyObject *)self); } int GLMVec2_tp_init(GLMVec2 * self, PyObject * args, PyObject * kwargs) { PyObject * iterable = PyTuple_GetItem(args, 0); if (Py_TYPE(iterable) == &PyTuple_Type && PyTuple_GET_SIZE(iterable) == N) { self->val[0] = (float)PyFloat_AsDouble(PyTuple_GET_ITEM(iterable, 0)); self->val[1] = (float)PyFloat_AsDouble(PyTuple_GET_ITEM(iterable, 1)); if (PyErr_Occurred()) { return -1; } return 0; } self->val = vec2_from_iterable(iterable); if (PyErr_Occurred()) { return -1; } return 0; } PyObject * GLMVec2_tp_repr(GLMVec2 * self) { PyObject * temp = GLMVec2_Tuple(self); PyObject * res = PyObject_Repr(temp); Py_DECREF(temp); return res; } PyObject * GLMVec2_nb_add(PyObject * lhs, PyObject * rhs) { if (Py_TYPE(lhs) == &GLMVec2_Type && Py_TYPE(rhs) == &GLMVec2_Type) { GLMVec2 * res = (GLMVec2 *)GLMVec2_tp_new(&GLMVec2_Type, 0, 0); res->val = ((GLMVec2 *)lhs)->val + ((GLMVec2 *)rhs)->val; return (PyObject *)res; } Py_RETURN_NOTIMPLEMENTED; } PyObject * GLMVec2_nb_subtract(PyObject * lhs, PyObject * rhs) { if (Py_TYPE(lhs) == &GLMVec2_Type && Py_TYPE(rhs) == &GLMVec2_Type) { GLMVec2 * res = (GLMVec2 *)GLMVec2_tp_new(&GLMVec2_Type, 0, 0); res->val = ((GLMVec2 *)lhs)->val - ((GLMVec2 *)rhs)->val; return (PyObject *)res; } Py_RETURN_NOTIMPLEMENTED; } PyObject * GLMVec2_nb_multiply(PyObject * lhs, PyObject * rhs) { if (Py_TYPE(lhs) == &GLMVec2_Type && Py_TYPE(rhs) == &GLMVec2_Type) { GLMVec2 * res = (GLMVec2 *)GLMVec2_tp_new(&GLMVec2_Type, 0, 0); res->val = ((GLMVec2 *)lhs)->val * ((GLMVec2 *)rhs)->val; return (PyObject *)res; } if (Py_TYPE(lhs) == &GLMVec2_Type) { float rhs_float = (float)PyFloat_AsDouble(rhs); if (!PyErr_Occurred()) { GLMVec2 * res = (GLMVec2 *)GLMVec2_tp_new(&GLMVec2_Type, 0, 0); res->val = ((GLMVec2 *)lhs)->val * rhs_float; return (PyObject *)res; } } if (Py_TYPE(rhs) == &GLMVec2_Type) { glm::mat2 mat2_lhs = mat2_from_iterable(lhs); if (!PyErr_Occurred()) { GLMVec2 * res = (GLMVec2 *)GLMVec2_tp_new(&GLMVec2_Type, 0, 0); res->val = mat2_lhs * ((GLMVec2 *)rhs)->val; return (PyObject *)res; } } PyErr_Clear(); Py_RETURN_NOTIMPLEMENTED; } PyObject * GLMVec2_nb_true_divide(PyObject * lhs, PyObject * rhs) { if (Py_TYPE(lhs) == &GLMVec2_Type && Py_TYPE(rhs) == &GLMVec2_Type) { GLMVec2 * res = (GLMVec2 *)GLMVec2_tp_new(&GLMVec2_Type, 0, 0); res->val = ((GLMVec2 *)lhs)->val / ((GLMVec2 *)rhs)->val; return (PyObject *)res; } if (Py_TYPE(lhs) == &GLMVec2_Type) { float rhs_float = (float)PyFloat_AsDouble(rhs); if (!PyErr_Occurred()) { GLMVec2 * res = (GLMVec2 *)GLMVec2_tp_new(&GLMVec2_Type, 0, 0); res->val = ((GLMVec2 *)lhs)->val / rhs_float; return (PyObject *)res; } } PyErr_Clear(); Py_RETURN_NOTIMPLEMENTED; } PyObject * GLMVec2_nb_inplace_add(PyObject * lhs, PyObject * rhs) { if (Py_TYPE(rhs) == &GLMVec2_Type) { ((GLMVec2 *)lhs)->val += ((GLMVec2 *)rhs)->val; Py_INCREF(lhs); return lhs; } Py_RETURN_NOTIMPLEMENTED; } PyObject * GLMVec2_nb_inplace_subtract(PyObject * lhs, PyObject * rhs) { if (Py_TYPE(rhs) == &GLMVec2_Type) { ((GLMVec2 *)lhs)->val -= ((GLMVec2 *)rhs)->val; Py_INCREF(lhs); return lhs; } Py_RETURN_NOTIMPLEMENTED; } PyObject * GLMVec2_nb_inplace_multiply(PyObject * lhs, PyObject * rhs) { if (Py_TYPE(rhs) == &GLMVec2_Type) { ((GLMVec2 *)lhs)->val *= ((GLMVec2 *)rhs)->val; Py_INCREF(lhs); return lhs; } float rhs_float = (float)PyFloat_AsDouble(rhs); if (!PyErr_Occurred()) { ((GLMVec2 *)lhs)->val *= rhs_float; Py_INCREF(lhs); return lhs; } PyErr_Clear(); Py_RETURN_NOTIMPLEMENTED; } PyObject * GLMVec2_nb_inplace_true_divide(PyObject * lhs, PyObject * rhs) { if (Py_TYPE(rhs) == &GLMVec2_Type) { ((GLMVec2 *)lhs)->val /= ((GLMVec2 *)rhs)->val; Py_INCREF(lhs); return lhs; } float rhs_float = (float)PyFloat_AsDouble(rhs); if (!PyErr_Occurred()) { ((GLMVec2 *)lhs)->val /= rhs_float; Py_INCREF(lhs); return lhs; } PyErr_Clear(); Py_RETURN_NOTIMPLEMENTED; } PyObject * GLMVec2_nb_negative(GLMVec2 * self) { GLMVec2 * res = (GLMVec2 *)GLMVec2_tp_new(&GLMVec2_Type, 0, 0); res->val = -((GLMVec2 *)self)->val; return (PyObject *)res; } PyObject * GLMVec2_nb_positive(GLMVec2 * self) { GLMVec2 * res = (GLMVec2 *)GLMVec2_tp_new(&GLMVec2_Type, 0, 0); res->val = +((GLMVec2 *)self)->val; return (PyObject *)res; } PyNumberMethods GLMVec2_tp_as_number = { (binaryfunc)GLMVec2_nb_add, // binaryfunc nb_add; (binaryfunc)GLMVec2_nb_subtract, // binaryfunc nb_subtract; (binaryfunc)GLMVec2_nb_multiply, // binaryfunc nb_multiply; 0, // binaryfunc nb_remainder; 0, // binaryfunc nb_divmod; 0, // ternaryfunc nb_power; (unaryfunc)GLMVec2_nb_negative, // unaryfunc nb_negative; (unaryfunc)GLMVec2_nb_positive, // unaryfunc nb_positive; 0, // unaryfunc nb_absolute; 0, // inquiry nb_bool; 0, // unaryfunc nb_invert; 0, // binaryfunc nb_lshift; 0, // binaryfunc nb_rshift; 0, // binaryfunc nb_and; 0, // binaryfunc nb_xor; 0, // binaryfunc nb_or; 0, // unaryfunc nb_int; 0, // void *nb_reserved; 0, // unaryfunc nb_float; (binaryfunc)GLMVec2_nb_inplace_add, // binaryfunc nb_inplace_add; (binaryfunc)GLMVec2_nb_inplace_subtract, // binaryfunc nb_inplace_subtract; (binaryfunc)GLMVec2_nb_inplace_multiply, // binaryfunc nb_inplace_multiply; 0, // binaryfunc nb_inplace_remainder; 0, // ternaryfunc nb_inplace_power; 0, // binaryfunc nb_inplace_lshift; 0, // binaryfunc nb_inplace_rshift; 0, // binaryfunc nb_inplace_and; 0, // binaryfunc nb_inplace_xor; 0, // binaryfunc nb_inplace_or; 0, // binaryfunc nb_floor_divide; (binaryfunc)GLMVec2_nb_true_divide, // binaryfunc nb_true_divide; 0, // binaryfunc nb_inplace_floor_divide; (binaryfunc)GLMVec2_nb_inplace_true_divide, // binaryfunc nb_inplace_true_divide; 0, // unaryfunc nb_index; // binaryfunc nb_matrix_multiply; // binaryfunc nb_inplace_matrix_multiply; }; Py_ssize_t GLMVec2_sq_length(GLMVec2 * self) { return N; } PyObject * GLMVec2_sq_item(GLMVec2 * self, Py_ssize_t key) { if (key < N) { return PyFloat_FromDouble(self->val[key]); } else { return 0; } } int GLMVec2_sq_ass_item(GLMVec2 * self, Py_ssize_t key, PyObject * value) { if (key < N) { float x = (float)PyFloat_AsDouble(value); if (PyErr_Occurred()) { return -1; } self->val[key] = x; return 0; } else { return -1; } } PySequenceMethods GLMVec2_tp_as_sequence = { (lenfunc)GLMVec2_sq_length, // lenfunc sq_length; 0, // binaryfunc sq_concat; 0, // ssizeargfunc sq_repeat; (ssizeargfunc)GLMVec2_sq_item, // ssizeargfunc sq_item; 0, // void *was_sq_slice; (ssizeobjargproc)GLMVec2_sq_ass_item, // ssizeobjargproc sq_ass_item; 0, // void *was_sq_ass_slice; 0, // objobjproc sq_contains; 0, // binaryfunc sq_inplace_concat; 0, // ssizeargfunc sq_inplace_repeat; }; int GLMVec2_bf_getbuffer(GLMVec2 * self, Py_buffer * view, int flags) { view->buf = (void *)&self->val; view->len = sizeof(self->val); view->itemsize = 1; view->format = 0; view->ndim = 0; view->shape = 0; view->strides = 0; view->suboffsets = 0; Py_INCREF(self); view->obj = (PyObject *)self; return 0; } PyBufferProcs GLMVec2_tp_as_buffer = { (getbufferproc)GLMVec2_bf_getbuffer, // getbufferproc bf_getbuffer; 0, // releasebufferproc bf_releasebuffer; }; PyObject * GLMVec2_tp_meth_dot(GLMVec2 * lhs, PyObject * args) { PyObject * rhs = PyTuple_GetItem(args, 0); if (Py_TYPE(rhs) == &GLMVec2_Type) { return PyFloat_FromDouble(glm::dot(lhs->val, ((GLMVec2 *)rhs)->val)); } return 0; } PyObject * GLMVec2_tp_meth_reflect(GLMVec2 * self, PyObject * args) { PyObject * norm = PyTuple_GetItem(args, 0); if (Py_TYPE(norm) == &GLMVec2_Type) { GLMVec2 * res = (GLMVec2 *)GLMVec2_tp_new(&GLMVec2_Type, 0, 0); res->val = glm::reflect(self->val, ((GLMVec2 *)norm)->val); return (PyObject *)res; } return 0; } PyObject * GLMVec2_tp_meth_refract(GLMVec2 * self, PyObject * args) { PyObject * norm = PyTuple_GetItem(args, 0); float eta = (float)PyFloat_AsDouble(PyTuple_GetItem(args, 1)); if (PyErr_Occurred()) { return 0; } if (Py_TYPE(norm) == &GLMVec2_Type) { GLMVec2 * res = (GLMVec2 *)GLMVec2_tp_new(&GLMVec2_Type, 0, 0); res->val = glm::refract(self->val, ((GLMVec2 *)norm)->val, eta); return (PyObject *)res; } return 0; } PyMethodDef GLMVec2_tp_methods[] = { {"dot", (PyCFunction)GLMVec2_tp_meth_dot, METH_VARARGS, 0}, {"reflect", (PyCFunction)GLMVec2_tp_meth_reflect, METH_VARARGS, 0}, {"refract", (PyCFunction)GLMVec2_tp_meth_refract, METH_VARARGS, 0}, {0}, }; PyObject * GLMVec2_tp_get_length(GLMVec2 * self, void * closure) { return PyFloat_FromDouble(glm::length(self->val)); } PyObject * GLMVec2_tp_get_normal(GLMVec2 * self, void * closure) { GLMVec2 * res = (GLMVec2 *)GLMVec2_tp_new(&GLMVec2_Type, 0, 0); res->val = glm::normalize(self->val); return (PyObject *)res; } PyObject * GLMVec2_tp_get_tup(GLMVec2 * self, void * closure) { return GLMVec2_Tuple(self); } PyGetSetDef GLMVec2_tp_getseters[] = { {(char *)"length", (getter)GLMVec2_tp_get_length, 0, 0, 0}, {(char *)"normal", (getter)GLMVec2_tp_get_normal, 0, 0, 0}, {(char *)"tup", (getter)GLMVec2_tp_get_tup, 0, 0, 0}, {0}, }; PyTypeObject GLMVec2_Type = { PyVarObject_HEAD_INIT(0, 0) "glm.Vec2", // tp_name sizeof(GLMVec2), // tp_basicsize 0, // tp_itemsize (destructor)GLMVec2_tp_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_reserved (reprfunc)GLMVec2_tp_repr, // tp_repr &GLMVec2_tp_as_number, // tp_as_number &GLMVec2_tp_as_sequence, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro &GLMVec2_tp_as_buffer, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags 0, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext GLMVec2_tp_methods, // tp_methods 0, // tp_members GLMVec2_tp_getseters, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset (initproc)GLMVec2_tp_init, // tp_init 0, // tp_alloc GLMVec2_tp_new, // tp_new }; PyObject * GLMVec2_Tuple(GLMVec2 * self) { PyObject * tuple = PyTuple_New(N); PyTuple_SET_ITEM(tuple, 0, PyFloat_FromDouble(self->val[0])); PyTuple_SET_ITEM(tuple, 1, PyFloat_FromDouble(self->val[1])); return tuple; }
[ "cprogrammer1994@gmail.com" ]
cprogrammer1994@gmail.com
37ab3b027acaa8f3c9445f2af5450e008c967bc2
5badecb58c1b13c07056c5d60a155fa619417541
/pe/include/Policy.h
a607e884ebbc8d1eb2de4ebe2eb4fcb5e77038ff
[]
no_license
XiaBoyang/pe
773467ba57367b9884994642e334aa746df6b1ca
ea9aad21d544d99655d94f1b1bcbf22e4b03b35b
refs/heads/master
2020-08-10T14:18:08.038681
2019-10-10T03:14:35
2019-10-10T03:14:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
644
h
#ifndef POLICY_H #define POLICY_H #include <string> #include <set> #include "Value.h" #include "policy_engine.h" class Subject; class AstExpr; class Policy { public: Policy() : _expr(nullptr) {} ~Policy(); PolicyEngineReturn ParseFromJson(const std::string& json_string); void GetAction(std::set<std::string>& ractions); void GetSubjectAttributes(std::set<std::string>& rattributes); PolicyEngineReturn TryMatch(const Subject *subject, const std::string& action, BOOLEAN& rboolean); void Dump(); /* print the policy for debug */ private: std::string _json_string; AstExpr *_expr; }; #endif
[ "2010301140007@whu.edu.cn" ]
2010301140007@whu.edu.cn
402e4ff00f28028c32825a0f45a2719f04a76bf7
710dc55388342a7b358610837f3cd276bc4393f3
/include/Constants.hpp
b7bdc019df84817754805c3e3a95412f48945d7a
[ "Zlib" ]
permissive
BastienCramillet/SGE
5d3a0107dde831a2494cf86b21b8684385b566a5
e8240207aa483652966f9be2846aecfbee58c60b
refs/heads/master
2020-12-24T14:01:01.400683
2014-09-12T09:57:06
2014-09-12T09:57:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
333
hpp
#ifndef CONSTANTES_HPP_INCLUDED #define CONSTANTES_HPP_INCLUDED const float BOX2D_SIZE_REDUCTION = 100.f; // Foncteur servant à libérer un pointeur - applicable à n'importe quel type struct Delete { template <class T> void operator ()(T*& p) const { delete p; p = 0; } }; #endif // CONSTANTES_HPP_INCLUDED
[ "bastien.cramillet@gmail.com" ]
bastien.cramillet@gmail.com
a8406f89469ebd14b1f34c53fa064fffd712fbd9
ad5aed2298caffcf4117713cd68aab5e693b0ee2
/msl-fl/msl-fl.h
6fb8e25f82eefed97e6748a872dcffc1e0a07575
[ "MIT" ]
permissive
mikelsv/msvcore2
592bb590c55f43975d7ffd16a2894ef5733b2c34
128b4b9523218da1eb056f6b11ada0bdc72b5c93
refs/heads/master
2021-11-24T04:35:16.906691
2021-11-10T21:26:11
2021-11-10T21:26:11
75,662,966
1
0
null
null
null
null
WINDOWS-1251
C++
false
false
55,743
h
// My Server Language - Fast Line Versions msl_fl_version[]={ "0.0.1.2", "09.12.2016 20:43", "0.0.1.1", "12.06.2015 12:06", "0.0.1.0", "30.11.2013 15:12", "0.0.0.8", "19.10.2013 21:29", "0.0.0.7", "18.10.2013 21:48", "0.0.0.6", "17.10.2013 23:13", "0.0.0.5", "16.10.2013 05:06", "0.0.0.4", "15.10.2013 17:24", "0.0.0.3", "14.10.2013 16:22", "0.0.0.2", "14.10.2013 01:08", "0.0.0.1", "13.10.2013 21:05" }; //#ifndef USEMSV_MLIST //#error Please #define USEMSV_MLIST //#endif // //#ifndef USEMSV_ITOS //#error Please #define USEMSV_ITOS //#endif TLock msl_value_test_loc; int msl_value_test_count; #include "../msl/msl-value-def.h" #ifdef USEMSV_MSL_FASTVAL #include "../msl/msl-val-fast.h" #else #define msl_fvalue msl_value #endif #ifdef USEMSV_MSL_TMPVAL #include "../msl/msl-value-tmp.h" #else #define msl_tvalue msl_value #endif #define msl_value msl_value_template<msl_value_base> #ifdef USEMSV_XDATACONT void JsonToMsl(XDataEl *el, msl_value &val, int clear = 1); #endif // Function Arguments class msl_fl_farg{ public: // in msl_value val, *ppval, *pval; // ($key=val) VString fkey, fval; }; class msl_fl_fargs{ MString _args; // memory buffer msl_fl_farg *args; // int asz, usz; // all sz & use sz int UpSize(){ // reserv memory _args.Reserve(sizeof(msl_fl_farg)*(asz+16)); // if error if(!_args){ asz=0; usz=0; return 0; } // update asz+=16; args=(msl_fl_farg*)_args.data; return 1; } public: // constructor & destructor msl_fl_fargs(){ args=0; asz=0; usz=0; } ~msl_fl_fargs(){ Clear(); } // vals[id]; msl_fl_farg &operator[](const int i){ if(i>usz){ globalerror("msl_fl_fargs epic fail"); } return args[i]; } // add value msl_fl_farg* Add(msl_value &val, msl_value *pval, msl_value *ppval){ if(usz>=asz){ if(!UpSize()) return 0; } // add args[usz].val.Move(val); args[usz].pval=pval; args[usz].ppval=ppval; return &args[usz++]; } // add value msl_fl_farg* AddF(VString k, VString v){ if(usz>=asz){ if(!UpSize()) return 0; } // add args[usz].fkey=k; args[usz].fval=v; args[usz].pval=0; return &args[usz++]; } int Sz(){ return usz; } int MSz(){ for(int i=0; i<usz; i++){ if(args[i].fval.data) return i; } return usz; } void Clear(){ for(int i=0; i<usz; i++){ args[i].val.ClearFull(); } args = 0; asz = 0; usz = 0; return ; } }; class msl_function_d{ public: msl_function_d(){ use=0; } msl_function_d *_p, *_n; VString name; msl_fl_fargs args, globals; MString code; int use; void UseIt(int v=1){ use=v; } }; class msl_function{ // : public OMatrixT<msl_function_d>{ msl_function_d *_a, *_e; public: msl_function(){ _a = 0; _e = 0; } ~msl_function(){ Clear(); } msl_function_d* New(){ msl_function_d *p = new msl_function_d; OMatrixTemplateAdd(_a, _e, p); return p; } msl_function_d *Find(VString name, int args){ for(msl_function_d *p=_a; p; p=p->_n){ if(p->use && p->name==name && args>=p->args.MSz() && args<=p->args.Sz()) return p; } return 0; } void Del(msl_function_d *p){ OMatrixTemplateDel(_a, _e, p); delete p; } void Clear(){ msl_function_d *p = _a, *d; while(p){ d = p; p = p->_n; delete d; } _a = 0; _e = 0; //OMClear(); } }; class msl_globals_d{ public: msl_globals_d *_p, *_n; VString name; msl_value *glob; msl_value *used; }; class msl_globals{ // : public OMatrixT<msl_globals_d>{ msl_globals_d *_a, *_e; public: msl_globals(){ _a = 0; _e = 0; } ~msl_globals(){ Clear(); } msl_globals_d* New(){ msl_globals_d *p = new msl_globals_d; OMatrixTemplateAdd(_a, _e, p); return p; } msl_globals_d *Find(msl_value *val){ for(msl_globals_d *p = _a; p; p = p->_n){ if(p->glob == val) return p; } return 0; } void Del(msl_globals_d *p){ OMatrixTemplateDel(_a, _e, p); //OMRealDel(p); delete p; } void Clear(){ msl_globals_d *p = _a, *d; while(p){ d = p; p = p->_n; delete d; } _a = 0; _e = 0; //OMClear(); } }; //#include "omatrix-msl_value.h" // Hints: // msl_value. Механизм балансировки возвращаемых значений. Чтобы не копировать лишний раз структуру с данными. // class msl_fl_extfunc{ public: virtual int DoCodeFunctionExec(VString name, msl_fl_fargs &args, msl_value &val){ // exec //if(name=="print" || name=="echo"){ // //for(int i=0; i<args.Sz(); i++){ // //SetOutput(args[i].val.val); // //print(args[i].val.val); // //} // //return 1; //} if(name=="testextfunc"){ val.val="ok"; return 1; } return 0; } }; class msl_cursor_d{ public: msl_value *val, *cur; }; int msl_cursor_find(msl_cursor_d &d, msl_value *&val){ return d.val==val; } class msl_cursor : public OList<msl_cursor_d>{ public: void reset(msl_value *val){ if(!val) return ; UGLOCK(this); msl_cursor_d *d = Search(msl_cursor_find, val); if(d) d->cur=0; return ; } msl_cursor_d* Get(msl_value* val){ msl_cursor_d *d=Search(msl_cursor_find, val); if(!d){ d=NewE(); d->val=val; d->cur=0; } if(d && !d->cur) d->cur=d->val->_a; return d; } msl_value* current(msl_value *val){ if(!val) return 0; UGLOCK(this); msl_cursor_d *d=Get(val); if(d){ if(val->GetV(d->cur)){ return d->cur; } } return 0; } msl_value* prev(msl_value *val){ if(!val) return 0; UGLOCK(this); msl_cursor_d *d=Get( val); if(d){ if(val->GetV(d->cur)){ if(!d->cur->_p) return 0; d->cur=d->cur->_p; return d->cur; } } return 0; } msl_value* next(msl_value *val){ if(!val) return 0; UGLOCK(this); msl_cursor_d *d=Get(val); if(d){ if(val->GetV(d->cur)){ if(!d->cur->_n) return 0; d->cur=d->cur->_n; return d->cur; } } return 0; } msl_value* end(msl_value *val){ if(!val) return 0; UGLOCK(this); msl_cursor_d *d=Get(val); if(d){ d->cur=val->_e; return d->cur; } return 0; } }; #ifdef USEMSV_MYSQL class msl_extension_mysql_con{ public: int cid; MySQLCon con; }; class msl_extension_mysql{ OList<msl_extension_mysql_con> cons; int cids; public: msl_extension_mysql(){ cids = 100 + (rand() % 100000); } msl_extension_mysql_con* GetConnection(int cid){ msl_extension_mysql_con *con = 0; while(con = cons.Next(con)){ if(con->cid == cid) return con; } return 0; } int mysql_connect(VString host, VString user, VString pass, int port){ msl_extension_mysql_con * con = cons.NewE(); con->cid = cids; cids += 1 + (rand() % 5); if(con->con.Connect(host, user, pass, "", port ? port : 3306)) return con->cid; cons.Free(con); return 0; } int mysql_select_db(int cid, VString db){ msl_extension_mysql_con *con = GetConnection(cid); if(con) return con->con.SelectDB(db); return 0; } int mysql_query(int cid, VString query){ msl_extension_mysql_con *con = GetConnection(cid); if(con) return con->con.Query(query); return 0; } int mysql_fetch_array(int cid, msl_value &val){ msl_extension_mysql_con *con = GetConnection(cid); if(con){ if(con->con.GetRow()){ for(int i = 0; i < con->con.GetNumFields(); i++){ val.Add(con->con.GetFieldName(i), con->con.GetRowVal(i)); } } } return 0; } MString mysql_error(int cid){ msl_extension_mysql_con *con = GetConnection(cid); if(con) return con->con.GetError(); return "connection id is fail"; } ~msl_extension_mysql(){ // auto clean } virtual int DoCodeFunctionExec(VString name, msl_fl_fargs &args, msl_value &val){ if(name == "mysql_connect" && (args.Sz() == 3 || args.Sz() == 4)){ val.val = itos(mysql_connect(args[0].val.val, args[1].val.val, args[2].val.val, args.Sz() == 4 ? args[3].val.val.toi() : 0)); } else if(name == "mysql_select_db" && args.Sz() == 2){ val.val = mysql_select_db(args[1].val.val.toi(), args[0].val.val) ? "1" : "0"; } else if(name == "mysql_query" && args.Sz() == 2){ val.val = mysql_query(args[1].val.val.toi(), args[0].val.val) ? "1" : "0"; } else if(name == "mysql_fetch_array" && args.Sz() == 1){ mysql_fetch_array(args[0].val.val.toi(), val); } else if(name == "mysql_error" && args.Sz() == 1){ val.val = mysql_error(args[0].val.val.toi()); } else return 0; return 1; } }; #endif // msl mathematical operations void msl_math_ops(int op, VString a, VString b, msl_value *ret){ SString it; double da = stod(a, a, 10); double db = stod(b, b, 10); double dr; switch(op){ case '+': dr = da + db; break; case '-': dr = da - db; break; case '*': dr = da * db; break; case '/': dr = da / db; break; case '%': dr = (double)((int64)da % (int64)db); break; default: dr = 0; break; } ret->val = it.dtos(dr); } #include "../msl/msl-func-dir.h" // spaces // Do() - all process operations // Set () - set // Get () - get //#define MSL_DOOPT_ERROR 0 //#define MSL_DOOPT_STOPIT (MSL_DOOPT_ERROR) #define MSLCBR_NULL 0 #define MSLCBR_CONT 1 #define MSLCBR_BREAK 2 #define MSLCBR_RET 3 #define MSLCBR_DIE 4 class msl_fl{ // result LString output; int opt_outcon; // options int do_opt, do_opt_stopit, do_opt_ifw, do_opt_cbr, do_opt_active; // positions line count, char *line, char this pos in line int do_line_count, do_line_count_ignore; unsigned char *do_line, *do_line_t; // values msl_value global_value; msl_value *local_value; msl_value null_value; // functions msl_function functions; // used flag msl_value functions_uf; //IList <msl_value*> functions_global; // globals msl_globals globals; msl_fl_extfunc* extfunc; // cursor reset(), prev(), current(), next(), end(); msl_cursor cursor; msl_value *cursor_value, *cursor_value_p; // this path VString file_path; // extensions #ifdef USEMSV_MYSQL msl_extension_mysql extension_mysql; #endif //#ifdef USEMSV_MYSQL msl_extension_file extension_dir; //#endif LString temp_data; public: // init msl_fl(){ do_opt=0; do_opt_stopit=0; do_opt_cbr=0; local_value=&global_value; extfunc=0; opt_outcon = 0; #ifdef MSL_FL_EXTFUNC_DEFAULT extfunc = MSL_FL_EXTFUNC_DEFAULT; #endif } ~msl_fl(){ } void OutToCon(int v = 1){ opt_outcon = v; } void DoFile(VString file){ file_path = file; if(IsFile(file)) Do(LoadFile(file)); else SetError(LString() + "include('" + file + "') file not found"); return ; } // process void Do(VString code){ unsigned char *line=code, *pline=line, *to=code.endu(); // stop it & active do_opt_stopit=0; do_opt_active=1; do_opt_ifw=0; do_opt_cbr=0; do_line_count=0; do_line_count_ignore = 0; do_line=line; do_line_t=line; // value; msl_value outval; while(line<to && !do_opt_stopit){ if(*line=='<' && line+1<to && *(line+1)=='?'){ // set result SetOutput(VString(pline, line-pline)); // *line='<?...' skip this 2 sumbols line+=2; //while(!do_opt_stopit){ // do msl // DoCode(line, to, outval, ';'); // if(line>=to || *line!=';') break; // line++; //} if(line + 3 < to && *(line + 0) == 'm' && *(line + 1) == 's' && *(line + 2) == 'l') line += 3; DoCodeMulti(line, to, outval); // if(line='?>') if(line+1>=to || *line!='?' || *(line+1)!='>'){ // oh no if(!do_opt_stopit) SetError("No find '?>'"); // exit return ; } else{ // *line='?>...' skip this 2 sumbols line+=2; pline=line+1; } }else if(*line=='\n'){ do_line_count++; do_line=line+1; } line++; } if(!DoTestCBR()) return ; // set result SetOutput(VString(pline, line-pline)); return ; } // test continue, break, return int DoTestCBR(){ if(do_opt_cbr){ if(do_opt_cbr==MSLCBR_CONT){ SetError("for/while for continue; not found"); return 0; } if(do_opt_cbr==MSLCBR_BREAK){ SetError("for/while for break; not found"); return 0; } if(do_opt_cbr==MSLCBR_RET) do_opt_cbr = MSLCBR_NULL; } return 1; } // "text" to string MString ModQuoteToString(VString line){ SString ret; ret.Reserve(line.sz); unsigned char *ln = line, *to = line.endu(), *r = ret; while(ln<to){ if(ln + 1 < to && *ln == '\\' && (*(ln + 1) == '\r' || *(ln + 1) == '\n' || *(ln + 1) == '\t')){ ln ++; if(*ln == 'r') *r = '\r'; else if(*ln == 'n') *r = '\n'; else if(*ln == 't') *r = '\t'; } else *r++ = *ln; ln ++; } return ret.str(0, r - ret.data); } // do code; code; code void DoCodeMulti(unsigned char*&line, unsigned char *to, msl_value &outval, unsigned char ecode = 1){ msl_value val; int opt_ret = 0; while(!do_opt_stopit){ // do msl DoCode(line, to, val, ';', ecode); if(do_opt_cbr == MSLCBR_RET && !opt_ret){ outval.Move(val); opt_ret = 1; } if(line >= to || *line != ';' || ecode == ';') break; line++; } return ; } void DoCode(unsigned char*&line, unsigned char *to, msl_value &outval, unsigned char ecode=1, unsigned char ecodet=1){ msl_value *value=0, *pdvalue=0, *dvalue=0, *pvalue; msl_value valueline; unsigned char *pline=0; int msl_do_inc=0; // 1 - ++, 2 - -- int opt_ret = 0; while(line<to && !do_opt_stopit){ // skip space _skipspace(line, to); //while(line<to && (*line==' ' || *line=='\t' || *line=='\r' || *line=='\n')) line++; // $value if(*line=='$'){ if(dvalue){ pdvalue->Del(dvalue); dvalue=0; } if(value){ SetError("double $value"); return ; } value=DoCodeValue(++line, to, pdvalue, dvalue, pvalue); if(!value) return ; if(msl_do_inc){ value->val=itos(value->val.toi()+ (msl_do_inc==1 ? 1 : -1)); msl_do_inc=0; } valueline.Add("t", value); cursor_value=value; cursor_value_p=pvalue; //outval.val=value->val; continue; }else // function if(*line>='a' && *line<='z' || *line>='A' && *line<='Z' || *line=='_'){ msl_value val; int df=0; DoCodeFunction(line, to, val, df); if(!df){ msl_value *v=valueline.New(); v->Move(val); v->key="t"; } else if(do_opt_cbr == MSLCBR_RET && !opt_ret){ outval.Move(val); opt_ret = 1; } continue; } // ecode else if(*line==ecode || *line==ecodet){ if(msl_do_inc){ SetError("Increment found!"); return ; } if(dvalue){ pdvalue->Del(dvalue); if(cursor_value == dvalue) cursor_value = 0; dvalue=0; } if(!opt_ret) DoCodeOneValue(valueline, outval); //if(value) outval.val=value->val; return ; } // string else if(*line=='"' || *line=='\''){ pline=++line; if(*(line-1)=='"') while(line<to){ if(*line == '\\'){ if(line + 1 < to){ if(line != pline){ valueline.Add("t", VString(pline, line - pline)); valueline.Add("o", "."); } line ++; unsigned char c = *line; if(c == 'r') c = '\r'; else if(c == 'n') c = '\n'; else if(c == 't') c = '\t'; valueline.Add("t", VString(&c, 1)); valueline.Add("o", "."); pline = ++ line; continue; } } if(*line=='"'){ if(pline<line && *(line-1)=='\\'){ valueline.Add("t", VString(pline, line-pline-1)); valueline.Add("o", "."); pline=line+1; line++; continue; } break; } if(*line=='{' && line+1<to && *(line+1)=='$'){ msl_value val; valueline.Add("t", VString(pline, line - pline)); valueline.Add("o", "."); line++; DoCode(line, to, val, '}'); valueline.Add("t", val.val); valueline.Add("o", "."); pline=line+1; } line++; } else while(line<to && *line!='\'') line++; if(line>=to){ SetError("closed \" or ' not found"); return ; } //outval.val=VString(pline, line-pline); valueline.Add("t", VString(pline, line-pline)); line++; continue; } // numbers else if(*line>='0' && *line<='9'){ pline=line; while(line<to && (*line>='0' && *line<='9' || *line == '.')) line++; //outval.val=VString(pline, line-pline); valueline.Add("t", VString(pline, line-pline)); continue; } // comments else if(*line=='/' && line+1<to && ( *(line+1)=='/' || *(line+1)=='*')){ line+=2; if(*(line-1)=='/'){ while(line<to && ( *line!='\r' && *line!='\n')) line++; } else{ while(line<to && ( *line!='/' || *(line-1)!='*')){ if(*line=='\n') ++do_line_count; line++; } line++; } continue; } // EOF else if(*line == '<' && line + 6 < to && compare((char*)line, 6, "<<<EOF", 6)){ line += 6; pline = line; while(line < to){ if(*line == '\n' && line + 3 < to && *(line + 1) == 'E' && *(line + 2) =='O' && *(line + 3) =='F'){ unsigned char *l = line + 3; if(*(line - 1) != '\r') line++; valueline.Add("t", VString(pline, line-pline)); line = l; break; } else if(*line=='{' && line+1<to && *(line+1)=='$'){ msl_value val; valueline.Add("t", VString(pline, line-pline)); valueline.Add("o", "."); line++; DoCode(line, to, val, '}'); valueline.Add("t", val.val); valueline.Add("o", "."); pline=line+1; } line ++; } } // operators else if(*line=='+' || *line=='-' || *line=='*' || *line=='/' || *line=='.' || *line=='!' || *line=='<' || *line=='>' || *line=='=' || *line=='|' || *line=='&' || *line=='%'){ pline=line++; while(*line=='+' || *line=='-' || *line=='*' || *line=='/' || *line=='.' || *line=='!' || *line=='<' || *line=='>' || *line=='=' || *line=='|' || *line=='&' || *line=='%') line++; if(line>=to){ SetError("EOF"); return ; } VString name(pline, line-pline); if(line-pline>1 && *(pline+1)=='-' && *pline=='='){ name.sz=1; line-=line-pline-1; } // = if(*(line-1)=='=' && !((*(pline)=='=' || *(pline)=='>' || *(pline)=='<' || *(pline)=='!' ) && line-pline==2)){ msl_value val; DoCode(line, to, val, ecode, ecodet); if(!value || valueline._e->key!="t"){ SetError("lvalue for = not set"); return ; } if(name=="="){ value->Move(val); }else if(name=="+="){ msl_math_ops('+', value->val, val.val, value); //value->val = itos(value->val.toi() + val.val.toi()); }else if(name=="-="){ msl_math_ops('-', value->val, val.val, value); //value->val = itos(value->val.toi() - val.val.toi()); }else if(name=="*="){ msl_math_ops('*', value->val, val.val, value); //value->val = itos(value->val.toi() * val.val.toi()); }else if(name=="/="){ if(!val.val.toi()){ SetWarning("Divide by zero"); value->val="0"; } else msl_math_ops('/', value->val, val.val, value); //value->val = itos(value->val.toi() / val.val.toi()); }else if(name==".="){ value->val.Add(value->val, val.val); } if(dvalue){ dvalue=0; } valueline._e->Copy(value); value=0; continue; } if(name=="++" || name=="--"){ if(msl_do_inc){ SetError("Increment found!"); return ; } if(value){ value->val=itos(value->val.toi()+ (name=="++" ? 1 : -1)); valueline._e->val=value->val; value=0; dvalue=0; continue; } msl_do_inc = name=="++" ? 1 : 2; value=0; continue; } valueline.Add("o", name); value=0; //DoCodeOperation(VString(pline, line-pline), value, continue; } // () else if(*line=='('){ msl_value val; DoCode(++line, to, val, ')'); if(line>=to || *line!=')'){ SetError("Close ')' not found"); return ; } line++; valueline.Add("t", val.val); continue; } // '?>' end do code else if(*line=='?' && line+1<to && *(line+1)=='>'){ return ; } // what the sumbol? else{ SetError(LString()+"Unknown sumbol: '"+VString(line, 1)+"'."); return ; } // skip space _skipspace(line, to); //while(line<to && (*line==' ' || *line=='\t' || *line=='\r' || *line=='\n')) line++; line++; } if(!do_opt_stopit) SetError("EOF"); return ; } void DoCodeInclude(VString file){ // save int _do_line_count = do_line_count; VString old_file_path = file_path; ILink il; il.Link(file_path); il.SetFile(file); if(IsFile(il.GetPathFile())){ // do Do(LoadFile(il.GetPathFile())); } else { SetError(LString() + "include('" + il.GetPathFile() + "') file not found"); } // load do_line_count = _do_line_count; file_path = old_file_path; return ; } void DoCodeOneValue(msl_value &line, msl_value &outval){ int sz=line.Size(); for(int i=0; i<8; i++){ msl_value *val=line._a; for(val; val && sz!=1; val=val->_n){ switch(i){ case 0: if(val->key=="o" && val->val=="!"){ if(!val->_n || val->_n->key!="t"){ SetError("Operator ! no have value"); return ; } val->key="t"; val->val= (val->_n->val && val->_n->val!="0" || val->_n->_a)==0 ? "1" : "0"; line.Del(val->_n); sz--; } if(val->key=="o" && val->val=="-" && (!val->_p || val->_p->key!="t")){ if(!val->_n || val->_n->key!="t"){ SetError("Operator - no have value"); return ; } val->key="t"; val->val.Add("-", val->_n->val); line.Del(val->_n); sz--; } break; case 1: case 2: case 3: case 4: case 5: case 6: case 7: if(val->key=="o"){ if(!val->_p || val->_p->key!="t" || !val->_n || val->_n->key!="t"){ SetError(LString()+"Operator'"+val->val+"'no have value"); return ; } // */% if(i==1 && (val->val=="*" || val->val=="/" || val->val=="%")){ if(val->val=="/" && !val->_n->val.toi()){ SetWarning("Divide by zero"); val->val="0"; }else{ if(val->val=="*") msl_math_ops('*', val->_p->val, val->_n->val, val); //val->val= itos(val->_p->val.toi()*val->_n->val.toi()); else if(val->val=="/") msl_math_ops('/', val->_p->val, val->_n->val, val); //val->val= itos(val->_p->val.toi()/val->_n->val.toi()); else if(val->val=="%") msl_math_ops('%', val->_p->val, val->_n->val, val); //val->val= itos(val->_p->val.toi()%val->_n->val.toi()); } } else // +- if(i==2 && (val->val=="+" || val->val=="-" || val->val==".")){ if(val->val=="+") msl_math_ops('+', val->_p->val, val->_n->val, val); //val->val = itos(val->_p->val.toi()+val->_n->val.toi()); else if(val->val=="-") msl_math_ops('-', val->_p->val, val->_n->val, val); //val->val= itos(val->_p->val.toi()-val->_n->val.toi()); else if(val->val==".") val->val.Add(val->_p->val, val->_n->val); //val->val=itos("+" ? val->_p->val.toi()+val->_n->val.toi() : val->_p->val.toi()-val->_n->val.toi() ); }else // >> << if(i==3 && (val->val==">>" || val->val=="<<")){ val->val=itos(">>" ? val->_p->val.toi()>>val->_n->val.toi() : val->_p->val.toi()<<val->_n->val.toi() ); }else //< <= > >= if(i==4 && (val->val==">" || val->val=="<" || val->val==">=" || val->val=="<=")){ if(val->val==">") val->val= itos(val->_p->val.toi()>val->_n->val.toi()); else if(val->val=="<")val->val= itos(val->_p->val.toi()<val->_n->val.toi()); else if(val->val==">=") val->val= itos(val->_p->val.toi()>=val->_n->val.toi()); else if(val->val=="<=") val->val= itos(val->_p->val.toi()<=val->_n->val.toi()); } else // == != if(i==5 && (val->val=="==" || val->val=="!=")){ val->val= (val->val=="==" ? val->_p->val==val->_n->val : val->_p->val!=val->_n->val) ? "1" : "0"; }else // & ^ | if(i==6 && (val->val=="&" || val->val=="^" || val->val=="|")){ if(val->val=="&") val->val= itos(val->_p->val.toi()&val->_n->val.toi()); else if(val->val=="^") val->val= itos(val->_p->val.toi()^val->_n->val.toi()); else if(val->val=="|") val->val= itos(val->_p->val.toi()|val->_n->val.toi()); } else // && || if(i==7 && (val->val=="&&" || val->val=="||")){ int l=val->_p->val && val->_p->val!="0"; int r=val->_n->val && val->_n->val!="0"; val->val= (val->val=="&&" ? l && r : l || r) ? "1" : "0"; }else{ continue; } val->key="t"; //val->val= val->val==itos("+" ? val->_p->val.toi()+val->_n->val.toi() : val->_p->val.toi()-val->_n->val.toi() ); line.Del(val->_n); line.Del(val->_p); val=line._a; sz-=2; } break; } } } if(sz>1 || sz && line._a->key!="t"){ SetError("One value. Bad code"); return ; } if(sz && line._a){ outval.Move(*line._a); //outval.val=line._a->val; } return ; } msl_value* DoCodeValue(unsigned char*&line, unsigned char *to, msl_value *&pnval, msl_value *&nval, msl_value *&pval){ unsigned char *pline=line; int isnew=0; nval=0; while(line<to && *line>='a' && *line<='z' || *line>='A' && *line<='Z' || *line>='0' && *line<='9' || *line=='_') line++; if(line>=to){ SetError(LString()+"EOF."); return 0; } // Get existing or create new msl_value *val, *lval=0; if(do_opt_active){ val=local_value->SGet(VString(pline, line-pline), isnew); pval=local_value; if(isnew){ pnval=local_value; nval=val; } } else val=&null_value; lval=val; while(1){ // skip space _skipspace(line, to); //while(line<to && (*line==' ' || *line=='\t' || *line=='\r' || *line=='\n')) line++; if(line<to && *line=='['){ msl_value dval; DoCode(++line, to, dval, ']'); // next [] if(do_opt_active){ pval=val; val=val->SGet(dval.val, isnew); if(isnew && !nval){ pnval=lval; nval=val; } lval=val; }else val=&null_value; line++; } else return val; } return 0; } void DoCodeFunction(unsigned char*&line, unsigned char *to, msl_value &val, int &df){ VString name; unsigned char *pline=line; msl_fl_fargs args; unsigned char *code, *ecode; while(line<to){ // normal name if(*line>='a' && *line<='z' || *line>='A' && *line<='Z' || *line >= '0' && *line <= '9' || *line=='_'){} else{ name.setu(pline, line-pline); if(name=="function"){ DoCodeFunctionFunction(line, to); df=1; return ; } _skipspace(line, to); if(*line==';'){ if(name=="continue"){ if(do_opt_active) do_opt_cbr=MSLCBR_CONT; do_opt_active=0; return ; } if(name=="break"){ if(do_opt_active) do_opt_cbr=MSLCBR_BREAK; do_opt_active=0; return ; } if(name=="return"){ if(do_opt_active) do_opt_cbr=MSLCBR_RET; do_opt_active=0; return ; } if(name=="die"){ if(do_opt_active) do_opt_cbr=MSLCBR_DIE; do_opt_active=0; return ; } } //while(line<to){ //if(*line=='('){ unsigned char simple; if(*line == '('){ line ++; simple = 0; } else simple = 1; code = line; if(name == "for"){ DoCodeFunctionFor(line, to); df = 1; return ; } else if(name == "while"){ DoCodeFunctionWhile(line, to); df = 1; return ; } // save state int old_ifw = do_opt_ifw, old_active = do_opt_active; if(name == "while"){ //do_opt_active = 0; //do_opt_ifw = 0; } // get args if(!DoCodeFunctionArgs(line, to, args, simple)) return ; ecode = line; if(!simple) line++; // Exec function if(!DoCodeFunctionExec(name, args, val)) return ; //line++; // restore state if(name == "while"){ //do_opt_active = old_active; //do_opt_ifw = old_ifw; } // if, while, for functions if(do_opt_ifw){ if(name=="if") DoCodeFunctionIf(line, to, val); //else if(name=="for") //DoCodeFunctionFor(line, to); df=1; } return ; //} /*else if(!(*line==' ' || *line=='\t' || *line=='\r' || *line=='\n')){ if(*line==';'){ if(name=="continue"){ if(do_opt_active) do_opt_cbr=MSLCBR_CONT; do_opt_active=0; return ; } if(name=="break"){ if(do_opt_active) do_opt_cbr=MSLCBR_BREAK; do_opt_active=0; return ; } if(name=="return"){ if(do_opt_active) do_opt_cbr=MSLCBR_RET; do_opt_active=0; return ; } if(name=="die"){ if(do_opt_active) do_opt_cbr=MSLCBR_DIE; do_opt_active=0; return ; } } SetError(HLString()+"function '"+name+"' open '(' not found."); return ; }*/ //line++; //} } line++; } // line='functionname'EOF SetError(LString()+"end of function name: '"+VString(pline, line-pline)+"'"); return ; } int DoCodeFunctionArgs(unsigned char *&line, unsigned char *to, msl_fl_fargs &args, int simple = 0){ while(!do_opt_stopit){ // skip space _skipspace(line, to); // no data if(line<to && *line==')') break; msl_value val; if(!simple) DoCode(line, to, val, ',', ')'); else DoCode(line, to, val, ';'); //if(!DoCodeFunctionArgs(line, to, args)) return ; args.Add(val, cursor_value, cursor_value_p); if(line>=to){ SetError("not found ')'. EOF"); return 0; } if(*line!=',') break; line++; } return 1; } void DoCodeFunctionIf(unsigned char*&line, unsigned char *to, msl_value &val){ unsigned char endcode; unsigned char *pline; // save values int old_ifw=do_opt_ifw, old_active=do_opt_active; do_opt_ifw=0; // skip space _skipspace(line, to); //while(line<to && (*line==' ' || *line=='\t' || *line=='\r' || *line=='\n')) line++; // single or {multi} if(line>=to){ SetError("if(...) EOF"); return ; } // set active do_opt_active=old_active && old_ifw==2; // do if(){ code } if(*(line)=='{'){ endcode='}'; line++; } else endcode=';'; DoCodeMulti(line, to, val, endcode); pline=line++; // if(line<to && *line!=';') line++; // skip space _skipspace(line, to); //while(line<to && (*line==' ' || *line=='\t' || *line=='\r' || *line=='\n')) line++; // test on 'else' if(line+4<to && *line=='e' && *(line+1)=='l' && *(line+2)=='s' && *(line+3)=='e'){ // skip 'else' line+=4; // skip space _skipspace(line, to); //while(line<to && (*line==' ' || *line=='\t' || *line=='\r' || *line=='\n')) line++; // set active do_opt_active=old_active && old_ifw==1; // do else{ code } if(*(line)=='{'){ endcode='}'; line++; } else endcode=';'; if(line + 3 < to && *line =='i' && *(line + 1) == 'f' && ( *(line + 2) == '(' || !(*(line + 2) >= 'a' && *(line + 2) <= 'z' || *(line + 2) >= 'A' && *(line + 2) <= 'Z' || *(line + 2) >= '0' && *(line + 2) <= '9' || *(line + 2) == '_') )){ int df; DoCodeFunction(line, to, val, df); } else{ DoCodeMulti(line, to, val, endcode); if(endcode!=';') line++; } } else if(endcode==';') line=pline; // load old value do_opt_active=old_active; do_opt_ifw=0; // if cbr if(do_opt_cbr){ do_opt_active=0; } return ; } void DoCodeFunctionWhile(unsigned char *&line, unsigned char *to){ //, unsigned char *code, unsigned char *ecode){ // values unsigned char *lline, *elline, *tline; unsigned char endcode; msl_value val; // save values int old_active = do_opt_active, old_ifw = 2; //do_opt_ifw; do_opt_active = 0; //do_opt_ifw = 0; // while(this) unsigned char *fcode = line, *fecode; DoCode(line, to, val, ')'); fecode = line; if(line >= to || *line != ')'){ SetError("not found ')'. EOF"); return ; } line ++; // skip space _skipspace(line, to); // do while(){ this } if(*(line) == '{'){ endcode = '}'; line ++; } else endcode = ';'; lline = line; DoCodeMulti(line, to, val, endcode); elline = ++line; // set active do_opt_active = old_active && old_ifw == 2; /* // save values int old_ifw=do_opt_ifw, old_active=do_opt_active; do_opt_ifw=0; // skip space _skipspace(line, to); //while(line<to && (*line==' ' || *line=='\t' || *line=='\r' || *line=='\n')) line++; if(line>=to){ SetError("if(...) EOF"); return ; } // Not active code do_opt_active = 0; lline = line; // do while(){ code } if(*(line)=='{'){ endcode='}'; line++; } else endcode=';'; DoCodeMulti(line, to, val, endcode); line++; elline=line; // set active do_opt_active=old_active && old_ifw==2; */ // while while(!do_opt_stopit && old_active && old_ifw==2){ msl_value val; // do while( it code ) tline = fcode; DoCode(tline, fecode + 1, val, ')'); // cbr if(do_opt_cbr){ if(do_opt_cbr==MSLCBR_CONT){ do_opt_cbr=MSLCBR_NULL; } if(do_opt_cbr==MSLCBR_BREAK){ do_opt_cbr=MSLCBR_NULL; break; } if(do_opt_cbr==MSLCBR_RET){ break; } if(do_opt_cbr==MSLCBR_DIE){ break; } } // result if((!val.val || val.val == "0") && !val.a()) break; // do while(1){ it code } tline = lline; //if(*(tline)=='{'){ endcode='}'; tline++; } else endcode=';'; DoCodeMulti(tline, elline, val, endcode); // set active do_opt_active=old_active && old_ifw==2; } // load old value do_opt_active = old_active; do_opt_ifw = 0; return ; } int DoCodeFunctionFor(unsigned char *&line, unsigned char *to){ // save values int old_active=do_opt_active; do_opt_active=0; // for args VString a[4]; int as=0; while(!do_opt_stopit && as<4){ msl_value val; a[as].data=line; DoCode(line, to, val, ';', ')'); a[as].sz=line-a[as].data; as++; if(line>=to){ SetError("not found ')'. EOF"); return 0; } if(*line==')') break; line++; } line++; if(as!=3){ SetError("for(args!=3)."); return 0; } // Do {} msl_value val; unsigned char *lline, *elline, *tline, *eline; unsigned char endcode; lline=line; if(*(line)=='{'){ endcode='}'; line++; } else endcode=';'; DoCodeMulti(line, to, val, endcode); line++; elline=line; // load old value do_opt_active=old_active; // Go or Nooo... if(old_active){ // do for(1) tline=a[0].data; eline=a[0].endu()+1; DoCode(tline, eline, val, ';'); while(!do_opt_stopit){ // do for(2), test tline=a[1].data; eline=a[1].endu()+1; DoCode(tline, eline, val, ';'); if(!val.val || val.val=="0") break; // do {} tline=lline; eline=elline; if(*(tline)=='{'){ endcode='}'; tline++; } else endcode=';'; DoCodeMulti(tline, eline, val, endcode); // cbr if(do_opt_cbr){ if(do_opt_cbr==MSLCBR_CONT){ do_opt_cbr=MSLCBR_NULL; } if(do_opt_cbr==MSLCBR_BREAK){ do_opt_cbr=MSLCBR_NULL; break; } if(do_opt_cbr==MSLCBR_RET){ break; } if(do_opt_cbr==MSLCBR_DIE){ break; } } // set value do_opt_active=old_active; // do for(3) tline=a[2].data; eline=a[2].endu()+1; DoCode(tline, eline, val, ')'); } } // load old value do_opt_active=old_active; do_opt_ifw=0; return 1; } int DoCodeFunctionFunction(unsigned char *&line, unsigned char *to){ unsigned char *lline; VString name, key, val; msl_value value; int def_value=0; // skip space _skipspace(line, to); // find name lline=line; while(line<to && (*line>='a' && *line<='z' || *line>='A' && *line<='Z' || *line >= '0' && *line <= '9' || *line=='_')) line++; // add functions msl_function_d *func=functions.New(); //func->name.setu(lline, line-lline); func->name = temp_data.addnf(VString(lline, line-lline)); // '(' if(line>=to || *line!='('){ SetError("function '(' not found"); return 0; } line++; while(1){ _skipspace(line, to); if(line<to && *line=='$'){ lline=++line; while(line<to && (*line>='a' && *line<='z' || *line>='A' && *line<='Z' || *line=='_')) line++; if(lline==line){ SetError("$(no_name)"); return 0; } key.setu(lline, line-lline); _skipspace(line, to); if(line<to && *line=='='){ def_value=1; line++; val.Clean(); _skipspace(line, to); if(_skipnum(line, to, val)){ } else if(_skipquote(line, to, val)){ line++; } else{ SetError("$key= unknow"); return 0; } }else if(def_value){ SetError("$key=default value, $key= no default value"); return 0; } key = temp_data.addnf(key); val = temp_data.addnf(val); func->args.AddF(key, val); // , _skipspace(line, to); if(line<to){ if(*line==','){ line++; continue; } if(*line==')') break; } SetError("bad value"); return 0; }else if(line<to && *line==')'){ break; } else { SetError("bad parameter"); return 0; } } if(line>=to || *line!=')'){ SetError("Fubction ')' not found"); return 0; } line++; _skipspace(line, to); if(line>=to || *line!='{'){ SetError("Fubction '{' not found"); return 0; } // skip { ++line; // global values _skipspace(line, to); if(VString(line, to - line).incompare("global")){ SString it; line += 6; while(line < to){ _skipspace(line, to); if(*line == '$'){ lline = ++line; while(line < to && (*line >= 'a' && *line <= 'z' || *line >= 'A' && *line <= 'Z' || *line == '_')) line++; if(lline == line){ SetError("$(no_name)"); return 0; } key.setu(lline, line-lline); it.Add(it, it ? "." : "", key); continue; } else if(*line == ','){ if(key){ func->globals.AddF(temp_data.addnf(it), ""); it.Clean(); } else SetError("Bad global in symbol ','"); } else if(*line == ';'){ line ++; func->globals.AddF(temp_data.addnf(it), ""); break; } else{ SetError("Bad global line"); break; } line ++; } } lline = line; // save values int old_active=do_opt_active; do_opt_active=0; // Get Function Code DoCodeMulti(line, to, value, '}'); if(line>=to || *line!='}'){ SetError("function '}' not found"); return 0; } line++; func->code.setu(lline, line-lline); // activate function func->UseIt(); // load old value do_opt_active=old_active; do_opt_ifw=0; return 1; } void _skipspace(unsigned char *&line, unsigned char *to){ //while(line<to && (*line==' ' || *line=='\t' || *line=='\r' && (line+1>=to || *(line+1)=='\n' || line++ && ++do_line_count && (do_line=line+1)) // || (*line=='\n' && ++do_line_count && (do_line=line+1) ))) line++; while(line<to){ if(*line==' ' || *line=='\t') line++; else if(*line=='\r'){ if(line+1<to || *(line+1)=='\n'){ if(!do_line_count_ignore) ++do_line_count; do_line=line+2; } line += 2; } else if(*line=='\n'){ line++; if(!do_line_count_ignore) ++do_line_count; do_line=line; } else break; } return ; } int _skipnum(unsigned char *&line, unsigned char *to, VString &val){ if(line<to && *line>='0' && *line<='9'){ val.data=line; while(line<to && *line>='0' && *line<='9') line++; val.sz=line-val.data; return 1; } return 0; } int _skipquote(unsigned char *&line, unsigned char *to, VString &val){ if(line>=to) return 0; if(*line=='\'' || *line=='"'){ unsigned char q=*line; val.data=++line; while(line<to && *line!=q) line++; val.sz=line-val.data; return 1; } return 0; } void msv_func_print_r(msl_value *v, LString &ls){ int f=1; ls+"{"; while(v){ if(!f) ls+", "; else f=0; ls+"'"+v->key+"' => '"+v->val+"'"; if(v->_a) msv_func_print_r(v->_a, ls); v=v->_n; } ls+"}"; return ; } int DoCodeFunctionExec(VString name, msl_fl_fargs &args, msl_value &val){ // all sections if((name=="if" || name=="while") && args.Sz()==1){ do_opt_ifw=args[0].val.val && args[0].val.val!="0" || args[0].val.a(); do_opt_ifw++; return 1; } // if active if(!do_opt_active) return 1; if(extfunc){ int r=extfunc->DoCodeFunctionExec(name, args, val); if(r) return 1; } int r=DoCodeFunctionExecDefault(name, args, val); if(r) return 1; // msl_function_d *func=functions.Find(name, args.Sz()); if(func){ // save and new msl_value *_local_value=local_value, func_value; local_value=&func_value; // save values int old_active =do_opt_active; int old_do_line_count_ignore = do_line_count_ignore; // output value msl_value outval; do_line_count_ignore = 1; for(int i=0; i<func->args.Sz(); i++){ local_value->Set(func->args[i].fkey, &args[i].val); //(args.Sz()>=i+1) ? args[i].val.val : func->args[i].fval); } msl_value *global_uf[256]; // max function globals for(int i = 0; i < func->globals.Sz(); i++){ msl_value *gv, *lv; VString name = func->globals[i].fkey; gv = global_value.SGet(name); lv = local_value->Set(name, ""); if(lv->a()){ SetError("global $(value) allready defined."); } if(gv->_a == &functions_uf){ global_uf[i] = gv->_e; lv->_a = gv->_e->_a; lv->_e = gv->_e->_e; lv->val -= gv->_e->val; }else{ lv->_a = gv->_a; lv->_e = gv->_e; lv->val -= gv->val; global_uf[i] = gv; gv->_a = &functions_uf; gv->_e = lv; } } unsigned char *fline=func->code, *eline=func->code.endu(); DoCodeMulti(fline, eline, outval, '}'); for(int i = 0; i < func->globals.Sz(); i++){ msl_value *gv, *lv; VString name = func->globals[i].fkey; gv = global_value.GetV(name); lv = local_value->GetV(name); if(!lv && gv){ global_uf[i]->_a = 0; global_uf[i]->_e = 0; //gv->_a = 0; //gv->_e = 0; } else if(lv && gv){ global_uf[i]->_a = lv->_a; global_uf[i]->_e = lv->_e; global_uf[i]->val -= lv->val; //gv->_a = lv->_a; //gv->_e = lv->_e; //gv->val -= lv->val; lv->_a = 0; lv->_e = 0; } } // test continue, break, return DoTestCBR(); // load old value do_opt_active=old_active; do_opt_ifw=0; do_line_count_ignore = old_do_line_count_ignore; // load local_value=_local_value; // return output value val.Move(outval); return 1; } // SetError(LString()+"Function: '"+name+"' not found"); return 0; } int DoCodeFunctionExecDefault(VString name, msl_fl_fargs &args, msl_value &val){ SString it; // exec if(name=="print" || name=="echo"){ for(int i=0; i<args.Sz(); i++){ SetOutput(args[i].val.val); //print(args[i].val.val); } } else if(name=="print_r" && args.Sz()==1){ SetOutput(args[0].val.val); msl_value *v=args[0].val._a; LString ls; msv_func_print_r(v, ls); SetOutput(ls); } else if(name=="array"){ SString it; int n=0; for(int i=0; i<args.Sz(); i++){ val.Set(args[i].val.key ? args[i].val.key : it.itos(n++), args[i].val.val); } } else if(name=="include" && args.Sz()==1){ DoCodeInclude(args[0].val.val); } // text else if(name=="substr" && args.Sz()==2){ val.val=args[0].val.val.str(args[1].val.val.toi()); } else if(name=="substr" && args.Sz()==3){ val.val=args[0].val.val.str(args[1].val.val.toi(), args[2].val.val.toi()); } // time & data else if(name=="clock" && args.Sz()==0){ val.val=itos(clock()); } else if(name=="time" && args.Sz()==0){ val.val=itos(time()); } else if(name=="date" && args.Sz()==1){ MTime mt; val.val=mt.date(args[0].val.val); } else if(name=="date" && args.Sz()==2){ MTime mt; val.val=mt.date(args[0].val.val, args[1].val.val.toi()); } else if(name == "microtime" && args.Sz() == 0){ timeb tb; ftime(&tb); val.val = it.Format("%d 0.%3d", (int)tb.time, tb.millitm); } // size else if(name=="sizeof" && args.Sz()==1){ if(args[0].pval){ val.val=itos(args[0].pval->Size()); }else SetWarning("sizeof(need $value);"); } // cursor else if(name=="reset" && args.Sz()==1){ if(args[0].pval){ cursor.reset(args[0].pval); }else SetWarning("reset(need $value);"); } else if(name=="prev" && args.Sz()==1){ if(args[0].pval){ msl_value *v=cursor.prev(args[0].pval); if(v) val.val=v->val; } else SetWarning("prev(need $value);"); } else if(name=="current" && args.Sz()==1){ if(args[0].pval){ msl_value *v=cursor.current(args[0].pval); if(v) val.val=v->val; } else SetWarning("current(need $value);"); } else if(name=="next" && args.Sz()==1){ if(args[0].pval){ msl_value *v=cursor.next(args[0].pval); if(v) val.val=v->val; } else SetWarning("next(need $value);"); } else if(name=="end" && args.Sz()==1){ if(args[0].val._a && args[0].pval){ msl_value *v=cursor.end(args[0].pval); if(v) val.val=v->val; } else SetWarning("end(need $value);"); } // value else if(name=="kprev" && args.Sz()==1){ if(args[0].pval){ msl_value *v=cursor.prev(args[0].pval); if(v) val.val=v->key; } else SetWarning("prev(need $value);"); } else if(name=="kcurrent" && args.Sz()==1){ if(args[0].pval){ msl_value *v=cursor.current(args[0].pval); if(v) val.val=v->key; } else SetWarning("current(need $value);"); } else if(name=="knext" && args.Sz()==1){ if(args[0].pval){ msl_value *v=cursor.next(args[0].pval); if(v) val.val=v->key; } else SetWarning("next(need $value);"); } else if(name=="kend" && args.Sz()==1){ if(args[0].val._a && args[0].pval){ msl_value *v=cursor.end(args[0].pval); if(v) val.val=v->key; } else SetWarning("end(need $value);"); } // isset else if(name=="isset" && args.Sz()==1){ val.val = args[0].pval ? "1" : "0"; } // unset else if(name=="unset" && args.Sz()==1){ if(args[0].pval){ args[0].ppval->Del(args[0].pval); } else SetWarning("unset(need $value);"); } // explode else if(name=="explode" && args.Sz()==2){ VString line = args[1].val.val, sep = args[0].val.val; int cnt = 0; while(line){ VString o = PartLine(line, line, sep); val.Add(it.itos(cnt++), o); } } // json_decode else if(name == "json_decode" && args.Sz() == 1){ XDataCont ct(args[0].val.val); JsonToMsl(ct, val); } // replace else if(name=="str_replace" && args.Sz()==3){ val.val = Replace(args[2].val.val, args[0].val.val, args[1].val.val); } // return else if(name == "return" && args.Sz() <= 1){ if(do_opt_active) do_opt_cbr = MSLCBR_RET; do_opt_active = 0; if(args.Sz() == 1) val.Move(args[0].val); } // die else if(name == "die" && args.Sz() == 0){ do_opt_cbr = MSLCBR_DIE; do_opt_active = 0; } // info else if(name == "msl_info"){ val.val = it.Format("MSL: My Server Lanruage %s(%s).", msl_fl_version[0].ver, msl_fl_version[0].date); } #ifdef USEMSV_MYSQL // mysql else if(extension_mysql.DoCodeFunctionExec(name, args, val)){} #endif // dir else if(extension_dir.DoCodeFunctionExec(name, args, val)){} //else if(name == else return 0; return 1; } void SetExtFunc(msl_fl_extfunc *f){ extfunc=f; } // HTTP input void SetHttpGet(VString line){ msl_value *data = SetValue("_GET", ""); while(line){ VString key = PartLine(line, line, "&"), val; key = PartLine(key, val, "="); data->Set(key, HttpToVal(val)); } } void SetHttpPost(VString line){ msl_value *data = SetValue("_POST", ""); while(line){ VString key = PartLine(line, line, "&"), val; key = PartLine(key, val, "="); data->Set(key, HttpToVal(val)); } } void SetHttpCookie(VString line){ msl_value *data = SetValue("_COOKIE", ""); while(line){ VString key = PartLine(line, line, ";"), val; if(key[0] == ' '){ key.data++; key.sz--; } key = PartLine(key, val, "="); data->Set(key, val); } return ; } // global value msl_value* SetValue(VString key, VString val){ return local_value->Set(key, val); } VString GetValue(VString key){ return local_value->Get(key); } msl_value* GetVValue(VString key){ return local_value->GetV(key); } // get output MString GetOutput(){ // return result; return MString(output.oneline(), output.size()); } int _getlinecount(){ return do_line_count; } int _getlinesz(){ if(do_line>do_line_t) return 0; return do_line_t-do_line; } protected: // set output void SetOutput(VString line){ // add line to result if(opt_outcon) print(line); else output + line; return ; } void SetWarning(VString line){ // add error line to result output + "MSL-FL Warning: '" + line + "' in '" + file_path + "' on " + itos(_getlinecount() + 1) + " line " + itos(_getlinesz()) + " row\r\n"; if(opt_outcon){ print(output); output.Clean(); } return ; } void SetError(VString line){ // add error line to result output + "MSL-FL Error: '" + line + "' in '" + file_path + "' on " + itos(_getlinecount() + 1) + " line " + itos(_getlinesz()) + " row\r\n"; // stop do_opt_stopit = 1; if(opt_outcon){ print(output); output.Clean(); } return ; } void SetEpic(VString line){ // add error line to result output + "MSL-FL Epic Fail: '" + line + "' in '" + file_path + "' on " + itos(_getlinecount() + 1) + " line " + itos(_getlinesz()) + " row\r\n"; // stop do_opt_stopit = 1; if(opt_outcon){ print(output); output.Clean(); } return ; } }; #ifdef USEMSV_XDATACONT void JsonToMsl(XDataEl *el, msl_value &val, int clear){ if(clear) val.Clear(); el=el->a(); int i=0; while(el){ if(!el->a()) val.Set(el->key ? el->key : itos(i++), el->val); else{ JsonToMsl(el, *val.Set(el->key ? el->key : itos(i++), ""), clear); } el=el->n(); } return ; } void JsonToMslMulti(XDataEl *el, msl_value &val, int clear=1){ if(clear) val.Clear(); //el=el->a(); int i=0; while(el){ if(!el->a()) val.Set(el->key ? el->key : itos(i++), el->val); else{ JsonToMsl(el, *val.Set(el->key ? el->key : itos(i++), ""), clear); } el=el->n(); } return ; } //void MslToJson(msl_value &val, HLString &ls){ // msl_value *el=val._a; int f=1; // ls+"{"; // // while(el){ // if(!f) ls+","; else f=0; // if(!el->_a) // ls+"\""+el->key+"\":\""+el->val+"\""; // else{ // ls+"\""+el->key+"\":"; // MslToJson(*el, ls); // } // el=el->_n; // } // ls+"}"; // return ; //} /* void GetLine(msl_value &val, HLString &ls); MString GetLine(msl_value &val){ if(!val._a) return MString(); HLString ls; GetLine(val, ls); return ls; } void GetLine(msl_value &val, HLString &ls){ int a=val.a()!=0 && val.a()->key, f=1; if(a) ls+"{"; else ls+"["; msl_value *v=val._a; while(v){ if(!f) ls+","; else f=0; if(v->_a){ if(a) ls+"\""+v->key+"\":"; GetLine(*v, ls); } else{ if(v->key) ls+"\""+v->key+"\":"; if(!v->val) ls+"null"; else ls+"\""+v->val+"\""; } //ls+v->key+":"+v->val; v=v->_n; } if(a) ls+"}"; else ls+"]"; return ; } */ // msl_value_template template<class B> void JsonToMsl(XDataEl *el, msl_value_template<B> &val, int clear = 1){ if(clear) val.Clear(); int i = 0; SString it; el = el->a(); while(el){ if(!el->a()) val.Set(el->key ? el->key : it.itos(i++), el->val); else{ JsonToMsl(el, *val.Set(el->key ? el->key : it.itos(i++), ""), clear); } el = el->n(); } return ; } template<class B> unsigned int GetLineCount(msl_value_template<B> &val){ int a = val.a() != 0 && val.a()->k(), f = 1; int sz = 0; msl_value_template<B> *v = val._a; while(v){ if(!f) sz ++; else f = 0; if(v->_a){ if(a) sz += 3 + v->k().sz; sz += GetLineCount(*v); } else{ if(v->k()) sz += 3 + v->k().sz; #ifdef MSLTOJSON_USE_NULL if(!v->v()) sz += 4; else #endif sz += 2 + v->v().sz; } v = v->_n; } sz += 2; return sz; } template<class B> unsigned char* GetLine(msl_value_template<B> &val, unsigned char *to){ int a = val.a() != 0 && val.a()->k(), f = 1; if(a) *to ++ = '{'; else *to ++ = '['; msl_value_template<B> *v = val._a; while(v){ if(!f) *to ++ = ','; else f = 0; if(v->_a){ if(a){ *to ++ = '"'; memcpy(to, v->k(), v->k()); to += v->k(); *to ++ = '"'; *to ++ = ':'; } to = GetLine(*v, to); } else{ if(v->k()){ //ls + "\"" + v->k() + "\":"; *to ++ = '"'; memcpy(to, v->k(), v->k()); to += v->k(); *to ++ = '"'; *to ++ = ':'; } #ifdef MSLTOJSON_USE_NULL if(!v->v()){ memcpy(to, "null", 4); to += 4; //ls + "null"; } else #endif { //ls + "\"" + v->v() + "\""; *to ++ = '"'; memcpy(to, v->v(), v->v()); to += v->v(); *to ++ = '"'; } } //ls+v->key+":"+v->val; v = v->_n; } if(a) *to ++ = '}'; else *to ++ = ']'; return to; } template<class B> TString GetLine(msl_value_template<B> &val){ if(!val._a) return TString(); TString ret; ret.Reserve(GetLineCount(val)); GetLine(val, ret); //HLString ls; //GetLine(val, ls); return ret; } template<class B> void GetLineL(msl_value_template<B> &val, LString &ls){ int a = val.a() != 0 && val.a()->k(), f = 1; if(a) ls + "{"; else ls + "["; msl_value_template<B> *v = val._a; while(v){ if(!f) ls + ","; else f = 0; if(v->_a){ if(a) ls + "\"" + v->k() + "\":"; GetLine(*v, ls); } else{ if(v->k()) ls + "\"" + v->k() + "\":"; if(!v->v()) ls + "null"; else ls + "\"" + v->v() + "\""; } //ls+v->key+":"+v->val; v = v->_n; } if(a) ls + "}"; else ls + "]"; return ; } template<class B> TString GetLinePost(msl_value_template<B> &val){ if(!val._a) return TString(); LString ls; msl_value_template<B> *p = val._a; while(p){ if(ls) ls + "&"; ls + p->k() + "=" + p->v(); p = p->_n; } return TString(ls); } #endif #ifdef USEMSV_CJX template<class B> unsigned int CjxGetLineCount(msl_value_template<B> &val){ int a = val.a() != 0 && val.a()->k(); int sz = 0; CjxProtoData d; msl_value_template<B> *v = val._a; while(v){ if(v->_a){ sz += d.CountUp(v->k()); sz += CjxGetLineCount(*v); } else sz += d.Count(v->k(), v->v()); v = v->_n; } sz += d.CountDown(); return sz; } template<class B> unsigned char* CjxGetLine(msl_value_template<B> &val, unsigned char *to){ int a = val.a() != 0 && val.a()->k(), f = 1; msl_value_template<B> *v = val._a; while(v){ CjxProtoData &d = *(CjxProtoData*)to; if(v->_a){ to += d.SetLineUp(v->k()); to = CjxGetLine(*v, to); } else to += d.SetLine(v->k(), v->v()); v = v->_n; } CjxProtoData &d = *(CjxProtoData*)to; to += d.SetLineDown(); return to; } template<class B> TString CjxGetLine(msl_value_template<B> &val){ if(!val._a) return TString(); TString ret; unsigned int rsz = CjxGetLineCount(val); ret.Reserv(sizeof(CjxProtoHead) + rsz); CjxProtoHead &head = *(CjxProtoHead*) ret.data; unsigned char *line = ret.data + sizeof(CjxProtoHead); CjxGetLine(val, line); head.Init(rsz); return ret; } #ifdef IAM_YOU_CODE___NOOOOOOO void GetCJXLineD(int &els, msl_value &val, HLString &ls); MString GetCJXLine(msl_value &val){ HLString ls; MString ret; int els=0; if(!val._a){ ret.Reserv(sizeof(CJXParseH)); CJXParseH *h=(CJXParseH*)ret.data; if(!h) return MString(); // h->ver=1; return ret; } CJXParseH *h=(CJXParseH*)ls.addnfv(sizeof(CJXParseH)); if(!h) return MString(); GetCJXLineD(els, val, ls); // h->els=els; h->size=ls.size()-sizeof(CJXParseH); return ls; } void GetCJXLineD(int &els, msl_value &val, HLString &ls){ // count int sz=val.Size(), t; if(sz>127){ t=bsize(sz)|128; ls.add((char*)&t, 1); ls.add((char*)&sz, t&127); }else{ ls.add((char*)&sz, 1); } msl_value *v=val._a; while(v){ CJXParseL l; l.up=v->_a!=0; l.keysz = v->key.sz>15 ? 15 : v->key.sz; if(v->val.sz>511){ l.valsz=bsize(v->val.sz)|512; ls.add((char*)&l, sizeof(l)); ls.add((char*)&v->val.sz, bsize(v->val.sz)); }else{ l.valsz=v->val.sz; ls.add((char*)&l, sizeof(l)); } ls.add(v->key, l.keysz); ls.add(v->val, v->val); els++; v=v->_n; } return ; } #endif #endif
[ "mikelsv@msn.com" ]
mikelsv@msn.com
df32b534f46c3f4abe84043257b73f4ff35893b7
d8d4b0f9120385fdd78c142b291bce3994a5008d
/SDK/MagicLeapPrivileges_functions.cpp
33d52ea64c1bf272a1a7e41a6c7ea87d33bb8308
[]
no_license
xnf4o/DBD_SDK_460
e0dc30ee6fc250478be10171c99776a1172f66ab
efd4049148a88a6ea67643c89f5820b7096e23f8
refs/heads/main
2023-03-30T21:02:20.509098
2021-04-03T01:55:57
2021-04-03T01:55:57
354,176,407
2
0
null
null
null
null
UTF-8
C++
false
false
3,879
cpp
// Name: DBD, Version: 4.6.0 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function MagicLeapPrivileges.MagicLeapPrivilegesFunctionLibrary.RequestPrivilegeAsync // (Final, Native, Static, Public, HasOutParms, BlueprintCallable) // Parameters: // MagicLeapPrivileges_EMagicLeapPrivilege Privilege (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // struct FScriptDelegate ResultDelegate (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, NoDestructor, NativeAccessSpecifierPublic) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) bool UMagicLeapPrivilegesFunctionLibrary::STATIC_RequestPrivilegeAsync(MagicLeapPrivileges_EMagicLeapPrivilege Privilege, const struct FScriptDelegate& ResultDelegate) { static auto fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapPrivileges.MagicLeapPrivilegesFunctionLibrary.RequestPrivilegeAsync"); UMagicLeapPrivilegesFunctionLibrary_RequestPrivilegeAsync_Params params; params.Privilege = Privilege; params.ResultDelegate = ResultDelegate; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MagicLeapPrivileges.MagicLeapPrivilegesFunctionLibrary.RequestPrivilege // (Final, Native, Static, Public, BlueprintCallable) // Parameters: // MagicLeapPrivileges_EMagicLeapPrivilege Privilege (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) bool UMagicLeapPrivilegesFunctionLibrary::STATIC_RequestPrivilege(MagicLeapPrivileges_EMagicLeapPrivilege Privilege) { static auto fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapPrivileges.MagicLeapPrivilegesFunctionLibrary.RequestPrivilege"); UMagicLeapPrivilegesFunctionLibrary_RequestPrivilege_Params params; params.Privilege = Privilege; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MagicLeapPrivileges.MagicLeapPrivilegesFunctionLibrary.CheckPrivilege // (Final, Native, Static, Public, BlueprintCallable) // Parameters: // MagicLeapPrivileges_EMagicLeapPrivilege Privilege (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) bool UMagicLeapPrivilegesFunctionLibrary::STATIC_CheckPrivilege(MagicLeapPrivileges_EMagicLeapPrivilege Privilege) { static auto fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapPrivileges.MagicLeapPrivilegesFunctionLibrary.CheckPrivilege"); UMagicLeapPrivilegesFunctionLibrary_CheckPrivilege_Params params; params.Privilege = Privilege; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "xnf4o@inbox.ru" ]
xnf4o@inbox.ru
a6abee5d76f7b70da3a1fed3fed5e17cd53d53c6
806606a70819955046d2dfe3718c243b2f0d6008
/Cpp files/Phase4Controller.cpp
165ec257747a6cf8396e123d9d16ef35fdbd9727
[]
no_license
meskandari/Power-Grid
b8916bf4eed1b74d354f0fe1ab5f345aa215d157
e23ec8d7eb6c48a8ac4ef8a505c34e733ff20c6a
refs/heads/master
2020-12-09T23:09:01.424363
2020-01-12T19:56:17
2020-01-12T19:56:17
233,442,742
0
0
null
null
null
null
UTF-8
C++
false
false
1,586
cpp
#include "Phase4Controller.h" #include <iostream> #include "Model.h" Phase4Controller::Phase4Controller() :Controller() { phase4view = new Phase4View(); phase4view->hide(); curCity = ""; endOfPhase = false; } Phase4Controller::~Phase4Controller() {} void Phase4Controller::onClick(int _x, int _y) { if (phase4view->buyButtonClicked(_x, _y)) { std::cout<<Model::get_map()->buyCity(curCity, Model::get_currentPlayer()->get_color())<<"\n"; Model::get_currentPlayer()->addHouses(1); if (Model::get_step() == 1 && Model::get_currentPlayer()->getHousesOwned() >= 7) { Model::set_step(2); } } else if (phase4view->endTurnButtonClicked(_x, _y)) { if (!Model::previous_player()) { endOfPhase = true; } else { phase4view->set_playerName(Model::get_currentPlayer()->get_name()); std::cout << Model::get_currentPlayer()->executeStrategy(4, Model::get_factoryMarket()->getBuyableFactories(), Model::get_currentPlayer()->getFactories()) << "\n"; } } else { std::string city = phase4view->cityClicked(_x, _y); if (city != "") { curCity = city; phase4view->set_city(curCity, 10); } } } void Phase4Controller::onLoad() { phase4view->show(); phase4view->findAndAttach(); Model::set_currentPlayer(Model::get_playerCount() - 1); phase4view->set_playerName(Model::get_currentPlayer()->get_name()); endOfPhase = false; } void Phase4Controller::onUnload() { phase4view->hide(); endOfPhase = false; Model::set_phase(5); } bool Phase4Controller::phasedEnded() { return endOfPhase; }
[ "noreply@github.com" ]
noreply@github.com
54d605b9f3fe18f568abed465f891ac8c876b9dd
ffd583a7ae88ba510e02f8f5141506ec6d2071fd
/src/qt/clr/settings/settingsfaqwidget.h
aee8af94b5fbf25f1c1d2b1dce0c36540cb7142c
[ "MIT" ]
permissive
Coleganet/Clearcore-Project
37f90a797c8098c76f538f30125ce797fba9ebba
e1878cdff32ad14509c0950edf4cd428883e966b
refs/heads/master
2023-03-31T15:11:33.061970
2021-04-06T00:16:21
2021-04-06T00:16:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
873
h
// Copyright (c) 2019 The PIVX developers // Copyright (c) 2020 The CLEARCOIN developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef SETTINGSFAQWIDGET_H #define SETTINGSFAQWIDGET_H #include <QDialog> class ClearCoinGUI; namespace Ui { class SettingsFaqWidget; } class SettingsFaqWidget : public QDialog { Q_OBJECT public: explicit SettingsFaqWidget(ClearCoinGUI *parent = nullptr); ~SettingsFaqWidget(); void showEvent(QShowEvent *event) override; public Q_SLOTS: void windowResizeEvent(QResizeEvent* event); void setSection(int num); private Q_SLOTS: void onFaqClicked(const QWidget* const widget); private: Ui::SettingsFaqWidget *ui; int pos = 0; std::vector<QPushButton*> getButtons(); }; #endif // SETTINGSFAQWIDGET_H
[ "noreply@github.com" ]
noreply@github.com
7f9ee9d30aa81f2b453ba5c2c39d1e4afe83f2ec
1be638aa2a38615a19c45b06579429bc2ab206dd
/Source/Snowboarding/SnowboardingWheelRear.cpp
566618c0857541219e34a643444c121bb3207d46
[]
no_license
Lordmatics/UE4-SnowboardingGame
fffe5f99d7741b11c62d20d46fb6d739873cf8d7
38a12e101c9caec4cecbd82dd1fc65e9b149c658
refs/heads/master
2020-12-02T22:19:41.748941
2017-07-03T14:39:39
2017-07-03T14:39:39
96,114,400
0
0
null
null
null
null
UTF-8
C++
false
false
268
cpp
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "Snowboarding.h" #include "SnowboardingWheelRear.h" USnowboardingWheelRear::USnowboardingWheelRear() { ShapeRadius = 35.f; ShapeWidth = 10.0f; bAffectedByHandbrake = true; SteerAngle = 0.f; }
[ "niallmaple@yahoo.co.uk" ]
niallmaple@yahoo.co.uk
3b11b5965d3ca709f9f897bfb612150c1f6481df
edeaff68dbcf37f648263bf6ebde3dd5340ed189
/string testing using string function.cpp
0bd04f03efa2a1c5f051ada2c6d5c1a88d9f1b30
[]
no_license
arvindmeena003/C-and-C-
548a306cfe7f429d391f674e59e2858f2ec5a8d6
a25f476438f8223031af78b34ad94539a07d66ec
refs/heads/master
2020-07-26T13:55:06.869395
2019-09-15T22:57:53
2019-09-15T22:57:53
208,667,149
0
0
null
null
null
null
UTF-8
C++
false
false
259
cpp
#include<stdio.h> #include<string.h> #include<conio.h> int main() { char s1[100],s2[100]; gets(s1); strcpy(s2,s1); strrev(s2); if(strcmp(s1,s2)==0) printf("string is palindrom"); else printf("not palindrome"); getch(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
1ee8737b0697a20b90602c3c2244980683cb5e40
9e86403d464023e3f6826f131090fe94e819d6d9
/bisearchtree.cpp
8126fb7282a14455b4f63a5ddc0ef1e47d062ca9
[]
no_license
KriAB/binarySearchTree
7b682d019216dd8dceb14c3f0e39e1b3bdd320ee
64b5d94756c987de52db4dc0eb2b88140ad7cd8c
refs/heads/master
2020-03-29T19:46:27.350222
2018-09-25T14:43:57
2018-09-25T14:43:57
150,280,314
0
0
null
null
null
null
UTF-8
C++
false
false
8,682
cpp
#include "bisearchtree.h" #include <iostream> BiSearchTree::BiSearchTree() { root = nullptr; } BiSearchTree::node *BiSearchTree::CreateLeaf(int m_key) { node* newNode = new node; newNode->key = m_key; newNode->left = nullptr; newNode->right = nullptr; return newNode; } void BiSearchTree::AddLeaf(int m_key) { AddLeafPrivate(m_key, root); } void BiSearchTree::AddLeafPrivate(int m_key, node *Ptr) { //sjekker om root peker på noe if(root == nullptr) { root = CreateLeaf(m_key); } //hvis m_key er mindre en key else if (m_key < Ptr->key) { if(Ptr->left != nullptr) { // hvis den peker på noe til venstre og vi må mer til venstre brukes en rekursiv funksjon. AddLeafPrivate(m_key, Ptr->left); } else { Ptr->left = CreateLeaf(m_key); } } // hvis m_key er større en key else if (m_key > Ptr->key) { if(Ptr->right != nullptr) { // hvis den peker på noe til høyre og vi må mer til høyre brukes en rekursiv funksjon. AddLeafPrivate(m_key, Ptr->right); } else { Ptr->right = CreateLeaf(m_key); } } else { // hvis key er lik som en key i treet std::cout << "The key " << m_key << "has already been added to the tree\n"; } } void BiSearchTree::PrintInOrder() { PrintInOrderPrivate(root); } void BiSearchTree::PrintInOrderPrivate(node *Ptr) { if(root != nullptr) { if(Ptr->left != nullptr) { PrintInOrderPrivate(Ptr->left); } std::cout << Ptr->key << " "; if(Ptr->right != nullptr) { PrintInOrderPrivate(Ptr->right); } } else { std::cout << "The tree is empty\n"; } } BiSearchTree::node *BiSearchTree::ReturnNode(int m_key) { return ReturnNodePrivate(m_key, root); } BiSearchTree::node *BiSearchTree::ReturnNodePrivate(int m_key, node *Ptr) { if(Ptr != nullptr) { if(Ptr->key == m_key) { return Ptr; } else { if( m_key < Ptr->key) { return ReturnNodePrivate(m_key, Ptr->left); } else { return ReturnNodePrivate(m_key, Ptr->right); } } } else { return nullptr; } } int BiSearchTree::ReturnRootKey() { if(root != nullptr) { return root->key; } else { return -1000; } } void BiSearchTree::PrintChildren(int m_key) { //returnerer en pointer som peker på den noden node* Ptr = ReturnNode(m_key); if( Ptr != nullptr) { std::cout << "Parent Node = " << Ptr->key << std::endl; Ptr->left == nullptr ? std::cout << "Left Child = nullptr\n": std::cout << "Left Child = " << Ptr->left->key << std::endl; Ptr->right == nullptr ? std::cout << "Right Child = nullptr\n": std::cout << "Right Child = " << Ptr->right->key << std::endl; } else { std::cout << "Key " << m_key << " is not in the tree\n"; } } int BiSearchTree::FindSmallest() { return FindSmallestPrivate(root); } int BiSearchTree::FindSmallestPrivate(node *Ptr) { if(root == nullptr) { std::cout << "The treei s empty\n"; return -1000; //må sette negativ int value fordi, det ikke er en del av key values i treet } else { if(Ptr->left != nullptr) { return FindSmallestPrivate(Ptr->left); } else { return Ptr->key; } } } void BiSearchTree::RemoveNode(int m_key) { //starter ved root RemoveNodePrivate(m_key, root); } void BiSearchTree::RemoveNodePrivate(int m_key, node *parent) { if(root != nullptr) { if(root->key == m_key) { RemoveRootMatch(); } else { if(m_key < parent->key && parent->left != nullptr) { parent->left->key == m_key ? //boolean check - turnery conditional RemoveMatch(parent, parent->left, true): RemoveNodePrivate(m_key, parent->left); } else if(m_key > parent->key && parent->right != nullptr) { parent->right->key == m_key ? //boolean check - turnery conditional RemoveMatch(parent, parent->right, false): RemoveNodePrivate(m_key, parent->right); } else { std::cout << "The key " << m_key << "was not found in the tree\n"; } } } else { std::cout << "The tree i sempty\n"; } } void BiSearchTree::RemoveRootMatch() { //tree not empty if(root != nullptr) { node* delPtr = root; int rootKey = root->key; int smallestInRightSubtree; //case 0 - 0 children if( root->left == nullptr && root->right == nullptr) { root = nullptr; delete delPtr; } //case 1 - 1 child // one right child else if(root->left == nullptr && root->right != nullptr) { root = root->right; //disconecting the old root from the tree, the child becomes the root delPtr->right = nullptr; delete delPtr; std:: cout << "The root node with key " << rootKey << " was deleted. " << "The new root contains key " << root->key << std::endl; } // one left child else if(root->left != nullptr && root->right == nullptr) { root = root->left; //disconecting the old root from the tree, the child becomes the root delPtr->left = nullptr; delete delPtr; std:: cout << "The root node with key " << rootKey << " was deleted. " << "The new root contains key " << root->key << std::endl; } //case 2 - 2 children else { smallestInRightSubtree = FindSmallestPrivate(root->right); //fjernet den minste, RemoveNodePrivate(smallestInRightSubtree, root); //puttet den minste inn i root root->key = smallestInRightSubtree; std::cout << "The root key containing key " << rootKey << " was overwritten with key " << root->key << std::endl; } } //tree empty else { std::cout << "Can not remove root, tree empty\n"; } } //remove not root node void BiSearchTree::RemoveMatch(BiSearchTree::node *parent, BiSearchTree::node *match, bool left) { if(root != nullptr) { node* delPtr; int matchKey = match->key; int smallestInRightSubtree; //case 0 - 0 children if(match->left == nullptr && match->right == nullptr) { delPtr = match; left == true ? parent->left = nullptr: //true parent->right = nullptr; //false delete delPtr; std::cout << "The node containing key " << matchKey << " was removed\n"; } //case 1- 1 child else if (match->left == nullptr && match->right != nullptr) { left == true ? parent->left = match->right: parent->right = match->right; match->right = nullptr; delPtr = match; delete delPtr; std::cout << "The node containing key " << matchKey << " was removed\n"; } else if (match->left != nullptr && match->right == nullptr) { left == true ? parent->left = match->left: parent->right= match->left; match->left = nullptr; delPtr = match; delete delPtr; std::cout << "The node containing key " << matchKey << " was removed\n"; } // Case 2 - 2 children else { smallestInRightSubtree = FindSmallestPrivate(match->right); RemoveNodePrivate(smallestInRightSubtree, match); match->key = smallestInRightSubtree; } } else { std::cout << "Can not remove match. The tree is empty.\n"; } }
[ "misskristin12@hotmail.com" ]
misskristin12@hotmail.com
2ee81f0191ae16055eb2935511ae74c78f780a4b
01c6d49dfe409bbb93e7a6b475893c85b4182346
/MS06/Car.h
14f3bbdcb90f7a58a048524cdd68300cff97f0c6
[]
no_license
rafialarabi/OOP244
9ad8742c5144c5a8e87b19fa475b06ecc55f1a52
8775f28b0102acf4f3af22c124b76fbdecb07f22
refs/heads/main
2023-07-16T08:18:37.592922
2021-08-27T07:04:59
2021-08-27T07:04:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
712
h
// Name: Md Rafi Al Arabi Bhuiyan // Student Number: 147307193 // Email: mraabhuiyan@myseneca.ca // Section: NBB // Milestone 6 // Date: 10/08/2020 /* I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. */ #ifndef SDDS_CAR_H #define SDDS_CAR_H #include <iostream> #include "Vehicle.h" namespace sdds { class Car : public Vehicle { private: bool Carwash; public: Car(); Car(const char* licensePlate, const char* makeModel); std::istream& read(std::istream& is); std::ostream& write(std::ostream& os) const; }; } #endif //SDDS_CAR_H
[ "noreply@github.com" ]
noreply@github.com
ed4d34388fe96778c1b0169bedad701a3ba5e834
965e0b38a363885de057098d69c42dd53731e3b7
/src/qt/aboutdialog.cpp
4486a72cc29b8e42e27d19c1cdec919394d90db7
[ "MIT" ]
permissive
EXAGLOBAL/BurnCoinWallet
f3e3edffab473f570b973b8d2fe0030822642ab3
3a013c7236c2a226977039f42f75e16ed135a5cd
refs/heads/master
2021-07-01T11:20:13.431001
2019-06-11T17:24:32
2019-06-11T17:24:32
147,622,173
0
0
null
null
null
null
UTF-8
C++
false
false
804
cpp
// Copyright (c) 2018. BurnCoin developers #include "aboutdialog.h" #include "ui_aboutdialog.h" #include "dialogwindowflags.h" #include "clientmodel.h" #include "version.h" #include <QKeyEvent> AboutDialog::AboutDialog(QWidget *parent) : QWidget(parent, DIALOGWINDOWHINTS), ui(new Ui::AboutDialog) { ui->setupUi(this); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); } void AboutDialog::keyPressEvent(QKeyEvent *event) { #ifdef ANDROID if(event->key() == Qt::Key_Back) { close(); } #else if(event->key() == Qt::Key_Escape) { close(); } #endif }
[ "exa@exaglobal.kr" ]
exa@exaglobal.kr
80c66ddeeaa585661ee4c470a62ff9fab7bfc1d2
82617c68897b543ad0d7e0e24640f5e6141476b6
/CSES/Introductory Problems/TrailingZeros.cpp
3c755ca3d6534a20668c53d9e06222a44883c922
[]
no_license
storyofhis/solve-problem
cd1173ef00e52c5ce1cad1141974f8d6ce3088b9
b5e2b69185a530936d2e4050dcdf543969390ac7
refs/heads/main
2023-08-13T15:09:06.856191
2021-08-25T22:02:11
2021-08-25T22:02:11
399,966,869
0
0
null
null
null
null
UTF-8
C++
false
false
711
cpp
#include <iostream> #include <algorithm> #include <set> #include <map> #include <vector> #include <array> #include <cmath> #include <list> #define pi 3.14159265 #define pb push_back #define mod 1000000007 #define mp make_pair #define ff first #define ss second #define rep(i,a,b) for(ll i=a;i<b;i++) typedef long long int ll; using namespace std; int factorial (int n){ if (n <= 1){ return 1; }else { return n*factorial(n-1); } } int main(int argc, char const *argv[]) { ll t = 1; while (t--){ ll n; cin >> n; ll ans = 0; for (ll i = 5; n/i >= 1; i *= 5){ ans += (n/i); } cout << ans << endl; } return 0; }
[ "azizi.maula@gmail.com" ]
azizi.maula@gmail.com
50cdb2ecbe7648b77a0112a7a62131534fd91f9f
fbf49ac1585c87725a0f5edcb80f1fe7a6c2041f
/SDK/BP_Cpl004StatusC03_classes.h
4c32013a4c562837c6e011413b44df9e87075ca5
[]
no_license
zanzo420/DBZ-Kakarot-SDK
d5a69cd4b147d23538b496b7fa7ba4802fccf7ac
73c2a97080c7ebedc7d538f72ee21b50627f2e74
refs/heads/master
2021-02-12T21:14:07.098275
2020-03-16T10:07:00
2020-03-16T10:07:00
244,631,123
0
1
null
null
null
null
UTF-8
C++
false
false
659
h
#pragma once // Name: DBZKakarot, Version: 1.0.3 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_Cpl004StatusC03.BP_Cpl004StatusC03_C // 0x0000 (0x00F0 - 0x00F0) class UBP_Cpl004StatusC03_C : public UATCharacterStatusParam { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_Cpl004StatusC03.BP_Cpl004StatusC03_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
0472c967ab35c8eda84fc1d1899cec7621b97806
b59cceebacb423b54f38775bd88a99f5a15d013b
/atcoder/abc/abc170/a.cpp
5922bca76dc76b7795bfe4ee8b41c474a07c61dd
[ "MIT" ]
permissive
yu3mars/proconVSCodeGcc
5e434133d4e9edf80d02a8ca4b95ee77833fbee7
fcf36165bb14fb6f555664355e05dd08d12e426b
refs/heads/master
2021-06-06T08:32:06.122671
2020-09-13T05:49:32
2020-09-13T05:49:32
151,394,627
0
0
null
null
null
null
UTF-8
C++
false
false
528
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using pll = pair<ll, ll>; #define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i) #define all(x) (x).begin(),(x).end() #define m0(x) memset(x,0,sizeof(x)) int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1}; int main() { int ans=0; int n; for (int i = 0; i < 5; i++) { cin>>n; if(n==0) { ans=i+1; } } cout<<ans<<endl; return 0; }
[ "yu3mars@users.noreply.github.com" ]
yu3mars@users.noreply.github.com
560fac441e432f6f5c05f1a15f7570c5996cfac2
dc768f15e62f0ede164ee38787375ce36a075b8e
/GameObject/Item.cpp
3994a849db257c57f7377ed794345ec596409eb1
[]
no_license
haragonn/Do_Game_AI_Dream_of_Cyber_Girl
ec8461b231b48ea1026a522103679d05cad1e9a0
4685bfb0a844b2a175d886e1c1a32353638e032a
refs/heads/master
2023-04-05T13:44:25.801438
2021-04-13T07:28:17
2021-04-13T07:28:17
357,458,840
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,336
cpp
#include "Item.h" #include "Renderer.h" using namespace idea; class Item::Impl{ public: // セル座標 Cell cell_; // 移動ベクトル Vector3D moveVector_; // 球の当たり判定 Sphere sphereCollision_; // 表示用ビルボード Billboard billboardItem_; // アイテムのテクスチャ Texture textureItem_; // 寿命 int life_ = 0; // デバッグ情報 Debug debugLog_; }; Item::Item() : pImpl_(new Item::Impl) { Assert(pImpl_); } Item::~Item() { SafeDelete(pImpl_); } void Item::Init() { // 実装 auto& impl = (*pImpl_); // シーン auto& scene = (*pScene_); // レンダラー auto& renderer = (*scene.GetGameObject<Renderer>(RENDERER_LAYER)); position_ = Vector3D(0.0f, -10.0f, 0.0f); impl.textureItem_.LoadImageFromStorage("asset/TEXTURE/item.png"); impl.sphereCollision_.Init(position_); impl.sphereCollision_.SetScale(4.0f, 4.0f, 4.0f); renderer.AddObject(impl.sphereCollision_); impl.billboardItem_.Init(position_); impl.billboardItem_.SetScale(3.0f, 3.0f, 3.0f); impl.billboardItem_.SetYBillboardFlag(true); impl.billboardItem_.SetColor(ideaColor::CLEAR); impl.billboardItem_.SetTexture(impl.textureItem_); renderer.AddObject(impl.billboardItem_); impl.life_ = 900; } void Item::Update() { // 実装 auto& impl = (*pImpl_); // 時間経過で消滅 if(impl.life_){ --impl.life_; } else{ SetDestroy(); return; } impl.billboardItem_.SetColor(ideaColor::WHITE.ReplaceAlpha(impl.life_ / 120.0f)); impl.moveVector_.y = impl.moveVector_.y - 0.15f; position_ += impl.moveVector_; position_.y = Max(2.0f, position_.y); impl.sphereCollision_.SetPosition(position_); impl.billboardItem_.SetPosition(position_); if(impl.debugLog_.GetDebugSwitch(0)){ impl.sphereCollision_.SetColor(ideaColor::TRANSLUCENT); } else{ impl.sphereCollision_.SetColor(ideaColor::CLEAR); } } void Item::HitObstacle(const Vector3D& axis) { // 実装 auto& impl = (*pImpl_); //重力初期化 impl.moveVector_.y = 0.0f; position_ += axis; impl.sphereCollision_.SetPosition(position_); impl.billboardItem_.SetPosition(position_); } void Item::SetCell(int x, int y) { pImpl_->cell_.x = x; pImpl_->cell_.y = y; } Cell& Item::GetCell() { return pImpl_->cell_; } SphereCollider Item::GetCollider() { return pImpl_->sphereCollision_.GetCollider(); }
[ "keigo.haragonn@gmail.com" ]
keigo.haragonn@gmail.com
c44b6c9f3de87d1e22acf554677d28d9b383741e
eb3736423d134739044e03b39902a06ca938deb9
/Src/base/WindowManagerBase.cpp
f2ad4286605cd78b37385ad8faab76fc725a73bb
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
penk/luna-sysmgr
663d46c3c3817908420e3b9c78e67329a523aa91
60c7056a734cdb55a718507f3a739839c9d74edf
refs/heads/master
2021-01-23T21:11:21.070609
2012-09-20T23:43:09
2012-10-09T21:22:43
6,360,119
3
0
null
null
null
null
UTF-8
C++
false
false
2,484
cpp
/* @@@LICENSE * * Copyright (c) 2008-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include "Common.h" #include "WindowManagerBase.h" #include "Window.h" #include <QGraphicsScene> WindowManagerBase::WindowManagerBase(int maxWidth, int maxHeight) { m_boundingRect = QRectF(-maxWidth/2, -maxHeight/2, maxWidth, maxHeight); // This is an obsolete API, but needed to make sure child events don't // get handled at this layer. See: http://bugreports.qt.nokia.com/browse/QTBUG-6861 setHandlesChildEvents(false); setFlag(QGraphicsItem::ItemHasNoContents, true); } WindowManagerBase::~WindowManagerBase() { } void WindowManagerBase::setScreenBounds(int x, int y, int w, int h) { prepareGeometryChange(); m_boundingRect = QRectF(-w/2, -h/2, w, h); } void WindowManagerBase::resize(int width, int height) { setScreenBounds(-width/2, -height/2, width, height); } QRectF WindowManagerBase::boundingRect() const { return m_boundingRect; } bool WindowManagerBase::handleNavigationEvent(QKeyEvent* keyEvent, bool& propogate) { propogate = true; return false; } void WindowManagerBase::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { } void WindowManagerBase::addWindow(Window* win) { if (win) win->setParentItem(this); } void WindowManagerBase::prepareAddWindow(Window* win) { } void WindowManagerBase::addWindowTimedOut(Window* win) { } void WindowManagerBase::removeWindow(Window* win) { if (win) { win->setParentItem(0); delete win; } } void WindowManagerBase::focusWindow(Window* win) { } void WindowManagerBase::unfocusWindow(Window* win) { } void WindowManagerBase::raiseChild(QGraphicsItem* child) { // need a better system for promoting a sibling instead of // remove/add to the scene bool restoreFocus = child->hasFocus(); scene()->removeItem(child); child->setParentItem(this); if (restoreFocus) child->setFocus(); }
[ "roger.stringer@palm.com" ]
roger.stringer@palm.com
e95d79f87eb2b0e10e05785d30c77c3f7226b6db
1f1b0b02bc6523d37537d179bbdac929c968a171
/Chap05App/TimeAdd.cpp
bd33afcb2880c4cc179414b9fb85bea210e0b8ec
[]
no_license
andrewbyun112/StudyCpp
72e1cc30302241e2ffc46366405bc12b015d6123
c0d0548e6f2d0ccb4fd3f6f133652525bb72430d
refs/heads/master
2022-06-16T15:34:45.335087
2020-05-13T01:32:50
2020-05-13T01:32:50
257,439,325
0
0
null
null
null
null
UTF-8
C++
false
false
581
cpp
#include <stdio.h> class Time { private: int hour, min, sec; public: Time() {} Time(int h, int m, int s) { hour = h; min = m; sec = s; } void OutTime() { printf("%d:%d:%d\n", hour, min, sec); } const Time AddTime(const Time& other) const { Time t; t.sec = sec + other.sec; t.min = min + other.min; t.hour = hour + other.hour; t.min += t.sec / 60; t.sec %= 60; t.hour += t.min / 60; t.min %= 60; return t; } }; int main() { Time t1(1, 10, 30); Time t2(2, 20, 40); Time t3; t3 = t1.AddTime(t2); t1.OutTime(); t2.OutTime(); t3.OutTime(); }
[ "andrewbyun112@gmail.com" ]
andrewbyun112@gmail.com
6b4ae795985986c707e777a27af7f94a73b4e03c
86b6582721787108968eaa1172bfb80f339304fe
/Core/GPU/Definitions.h
64877fd9ba2535c9c7178bf5a43c625dab753653
[]
no_license
NoamRodrik/RodrikGameboyEmulator
243c23dfa6b2b8714d2ecb928ce2a6cc673d1d95
07986ad69b70236bcfc0c4aa573255ee5810483c
refs/heads/master
2023-08-28T09:37:34.711849
2021-11-06T09:55:12
2021-11-06T09:55:12
217,574,592
2
0
null
2021-11-06T09:55:12
2019-10-25T16:33:27
C++
UTF-8
C++
false
false
2,206
h
/** * @file Definitions.h * @author Noam Rodrik * @description LR35902 GPU definitions */ #ifndef __LR35902_GPU_DEFINITIONS_H__ #define __LR35902_GPU_DEFINITIONS_H__ #include <API/Definitions.h> #include <Tools/Tools.h> namespace Core { [[nodiscard]] static constexpr API::address_t GetWrappedAroundDistance(const std::size_t from, const std::size_t to) { return (from + 0x100 - to) % 0x100; } /** * The original colors to choose from. */ enum class [[nodiscard]] PixelColor : API::data_t { WHITE = 0x00, DARK_GREY = 0x01, LIGHT_GREY = 0x02, BLACK = 0x03 }; /** * The chosen colors as the palette. */ enum class [[nodiscard]] PaletteColor : API::data_t { FIRST_PALETTE = 0x00, SECOND_PALETTE = 0x01, THIRD_PALETTE = 0x02, FOURTH_PALETTE = 0x03 }; /** * The state of the PPU. */ enum class [[nodiscard]] PPUState : API::data_t { H_BLANK = 0x00, V_BLANK = 0x01, OAM_SEARCH = 0x02, PIXEL_RENDER = 0x03 }; static constexpr const char ENGINE_WINDOW_NAME[]{"RodrikGameBoyEmulator"}; static constexpr size_t BACKGROUND_MAP_SIZE{Tools::SlotsToBytes(10)}; static constexpr size_t SCREEN_WIDTH_PIXELS{160}; static constexpr size_t SCREEN_HEIGHT_PIXELS{144}; static constexpr size_t AMOUNT_OF_SPRITES{40}; static constexpr size_t AMOUNT_OF_SPRITES_PER_LINE{10}; static constexpr int32_t BGP_PIXEL{-1}; static constexpr int32_t WIN_PIXEL{-2}; #ifdef GREEN_DISPLAY static constexpr uint8_t WHITE_PIXEL[]{143, 144, 85}; static constexpr uint8_t BLACK_PIXEL[]{32, 55, 50}; static constexpr uint8_t LIGHT_GREY_PIXEL[]{81, 113, 88}; static constexpr uint8_t DARK_GREY_PIXEL[]{55, 85, 76}; #elif defined(BEAUTIFUL_DISPLAY) static constexpr uint8_t WHITE_PIXEL[]{255, 255, 255}; static constexpr uint8_t BLACK_PIXEL[]{0, 0, 0}; static constexpr uint8_t LIGHT_GREY_PIXEL[]{221, 180, 180}; static constexpr uint8_t DARK_GREY_PIXEL[]{97, 79, 76}; #else static constexpr uint8_t WHITE_PIXEL[]{255, 255, 255}; static constexpr uint8_t BLACK_PIXEL[]{0, 0, 0}; static constexpr uint8_t LIGHT_GREY_PIXEL[]{203, 203, 203}; static constexpr uint8_t DARK_GREY_PIXEL[]{149, 149, 149}; #endif } // Core #endif // __LR35902_GPU_DEFINITIONS_H__
[ "rodriknoam@gmail.com" ]
rodriknoam@gmail.com
76f67a517cc2615e9245dfaa18517844be4d97e1
de7e771699065ec21a340ada1060a3cf0bec3091
/core/src/java/org/apache/lucene/index/TermVectorsConsumer.cpp
3b28b55cb2767d51410972fbeb0eaed1ee6f7343
[]
no_license
sraihan73/Lucene-
0d7290bacba05c33b8d5762e0a2a30c1ec8cf110
1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3
refs/heads/master
2020-03-31T07:23:46.505891
2018-12-08T14:57:54
2018-12-08T14:57:54
152,020,180
7
0
null
null
null
null
UTF-8
C++
false
false
4,043
cpp
using namespace std; #include "TermVectorsConsumer.h" namespace org::apache::lucene::index { using TermVectorsWriter = org::apache::lucene::codecs::TermVectorsWriter; using FlushInfo = org::apache::lucene::store::FlushInfo; using IOContext = org::apache::lucene::store::IOContext; using ArrayUtil = org::apache::lucene::util::ArrayUtil; using BytesRef = org::apache::lucene::util::BytesRef; using IOUtils = org::apache::lucene::util::IOUtils; using RamUsageEstimator = org::apache::lucene::util::RamUsageEstimator; TermVectorsConsumer::TermVectorsConsumer( shared_ptr<DocumentsWriterPerThread> docWriter) : TermsHash(docWriter, false, nullptr), docWriter(docWriter) { } void TermVectorsConsumer::flush( unordered_map<wstring, std::shared_ptr<TermsHashPerField>> &fieldsToFlush, shared_ptr<SegmentWriteState> state, shared_ptr<Sorter::DocMap> sortMap) { if (writer != nullptr) { int numDocs = state->segmentInfo->maxDoc(); assert(numDocs > 0); // At least one doc in this run had term vectors enabled try { fill(numDocs); assert(state->segmentInfo != nullptr); writer->finish(state->fieldInfos, numDocs); } // C++ TODO: There is no native C++ equivalent to the exception 'finally' // clause: finally { IOUtils::close({writer}); writer.reset(); lastDocID = 0; hasVectors = false; } } } void TermVectorsConsumer::fill(int docID) { while (lastDocID < docID) { writer->startDocument(0); writer->finishDocument(); lastDocID++; } } void TermVectorsConsumer::initTermVectorsWriter() { if (writer == nullptr) { shared_ptr<IOContext> context = make_shared<IOContext>(make_shared<FlushInfo>( docWriter->getNumDocsInRAM(), docWriter->bytesUsed())); writer = docWriter->codec->termVectorsFormat()->vectorsWriter( docWriter->directory, docWriter->getSegmentInfo(), context); lastDocID = 0; } } void TermVectorsConsumer::finishDocument() { if (!hasVectors) { return; } // Fields in term vectors are UTF16 sorted: ArrayUtil::introSort(perFields, 0, numVectorFields); initTermVectorsWriter(); fill(docState->docID); // Append term vectors to the real outputs: writer->startDocument(numVectorFields); for (int i = 0; i < numVectorFields; i++) { perFields[i]->finishDocument(); } writer->finishDocument(); assert((lastDocID == docState->docID, L"lastDocID=" + to_wstring(lastDocID) + L" docState.docID=" + to_wstring(docState->docID))); lastDocID++; TermsHash::reset(); resetFields(); } void TermVectorsConsumer::abort() { hasVectors = false; try { TermsHash::abort(); } // C++ TODO: There is no native C++ equivalent to the exception 'finally' // clause: finally { IOUtils::closeWhileHandlingException({writer}); writer.reset(); lastDocID = 0; reset(); } } void TermVectorsConsumer::resetFields() { Arrays::fill(perFields, nullptr); // don't hang onto stuff from previous doc numVectorFields = 0; } shared_ptr<TermsHashPerField> TermVectorsConsumer::addField(shared_ptr<FieldInvertState> invertState, shared_ptr<FieldInfo> fieldInfo) { return make_shared<TermVectorsConsumerPerField>( invertState, shared_from_this(), fieldInfo); } void TermVectorsConsumer::addFieldToFlush( shared_ptr<TermVectorsConsumerPerField> fieldToFlush) { if (numVectorFields == perFields.size()) { int newSize = ArrayUtil::oversize(numVectorFields + 1, RamUsageEstimator::NUM_BYTES_OBJECT_REF); std::deque<std::shared_ptr<TermVectorsConsumerPerField>> newArray(newSize); System::arraycopy(perFields, 0, newArray, 0, numVectorFields); perFields = newArray; } perFields[numVectorFields++] = fieldToFlush; } void TermVectorsConsumer::startDocument() { resetFields(); numVectorFields = 0; } } // namespace org::apache::lucene::index
[ "smamunr@fedora.localdomain" ]
smamunr@fedora.localdomain
9d126962ab4f96992dd3285728c11772f6b09f25
39ab815dfdbab9628ede8ec3b4aedb5da3fd456a
/aql/benchmark/lib_19/class_0.cpp
d60a4fea820ad84794663d8fac7fded5933f328c
[ "MIT" ]
permissive
menify/sandbox
c03b1bf24c1527b47eb473f1acc433f17bfb1d4f
32166c71044f0d5b414335b2b6559adc571f568c
refs/heads/master
2016-09-05T21:46:53.369065
2015-04-20T06:35:27
2015-04-20T06:35:27
25,891,580
0
0
null
null
null
null
UTF-8
C++
false
false
308
cpp
#include "class_0.h" #include "class_8.h" #include "class_4.h" #include "class_0.h" #include "class_7.h" #include "class_5.h" #include <lib_17/class_0.h> #include <lib_8/class_5.h> #include <lib_8/class_1.h> #include <lib_5/class_4.h> #include <lib_8/class_8.h> class_0::class_0() {} class_0::~class_0() {}
[ "menify@a28edc5c-ec3e-0410-a3da-1b30b3a8704b" ]
menify@a28edc5c-ec3e-0410-a3da-1b30b3a8704b
0c7fc96adc417a5da196706bf0269989696dbe37
bff9ee7f0b96ac71e609a50c4b81375768541aab
/deps/src/boost_1_65_1/boost/fusion/container/deque/detail/cpp03/as_deque.hpp
b8161cbc32d009e7fa5c3fb7b3dd5dded74c2704
[ "BSL-1.0", "BSD-3-Clause" ]
permissive
rohitativy/turicreate
d7850f848b7ccac80e57e8042dafefc8b949b12b
1c31ee2d008a1e9eba029bafef6036151510f1ec
refs/heads/master
2020-03-10T02:38:23.052555
2018-04-11T02:20:16
2018-04-11T02:20:16
129,141,488
1
0
BSD-3-Clause
2018-04-11T19:06:32
2018-04-11T19:06:31
null
UTF-8
C++
false
false
4,684
hpp
/*============================================================================= Copyright (c) 2005-2012 Joel de Guzman Copyright (c) 2006 Dan Marsden Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef BOOST_PP_IS_ITERATING #if !defined(FUSION_AS_DEQUE_20061213_2210) #define FUSION_AS_DEQUE_20061213_2210 #include <boost/preprocessor/iterate.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_binary_params.hpp> #include <boost/preprocessor/repetition/repeat.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/inc.hpp> #include <boost/preprocessor/dec.hpp> #include <boost/fusion/container/deque/deque.hpp> #include <boost/fusion/iterator/value_of.hpp> #include <boost/fusion/iterator/deref.hpp> #include <boost/fusion/iterator/next.hpp> namespace boost { namespace fusion { namespace detail { BOOST_FUSION_BARRIER_BEGIN template <int size> struct as_deque; template <> struct as_deque<0> { template <typename Iterator> struct apply { typedef deque<> type; }; template <typename Iterator> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static typename apply<Iterator>::type call(Iterator) { return deque<>(); } }; BOOST_FUSION_BARRIER_END }}} #if !defined(BOOST_FUSION_DONT_USE_PREPROCESSED_FILES) #include <boost/fusion/container/deque/detail/cpp03/preprocessed/as_deque.hpp> #else #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 2, line: 0, output: "preprocessed/as_deque" FUSION_MAX_DEQUE_SIZE_STR ".hpp") #endif /*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) This is an auto-generated file. Do not edit! ==============================================================================*/ #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 1) #endif namespace boost { namespace fusion { namespace detail { BOOST_FUSION_BARRIER_BEGIN #define BOOST_FUSION_NEXT_ITERATOR(z, n, data) \ typedef typename fusion::result_of::next<BOOST_PP_CAT(I, n)>::type \ BOOST_PP_CAT(I, BOOST_PP_INC(n)); #define BOOST_FUSION_NEXT_CALL_ITERATOR(z, n, data) \ typename gen::BOOST_PP_CAT(I, BOOST_PP_INC(n)) \ BOOST_PP_CAT(i, BOOST_PP_INC(n)) = fusion::next(BOOST_PP_CAT(i, n)); #define BOOST_FUSION_VALUE_OF_ITERATOR(z, n, data) \ typedef typename fusion::result_of::value_of<BOOST_PP_CAT(I, n)>::type \ BOOST_PP_CAT(T, n); #define BOOST_PP_FILENAME_1 <boost/fusion/container/deque/detail/cpp03/as_deque.hpp> #define BOOST_PP_ITERATION_LIMITS (1, FUSION_MAX_DEQUE_SIZE) #include BOOST_PP_ITERATE() #undef BOOST_FUSION_NEXT_ITERATOR #undef BOOST_FUSION_NEXT_CALL_ITERATOR #undef BOOST_FUSION_VALUE_OF_ITERATOR BOOST_FUSION_BARRIER_END }}} #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(output: null) #endif #endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES #endif #else // defined(BOOST_PP_IS_ITERATING) /////////////////////////////////////////////////////////////////////////////// // // Preprocessor vertical repetition code // /////////////////////////////////////////////////////////////////////////////// #define N BOOST_PP_ITERATION() template <> struct as_deque<N> { template <typename I0> struct apply { BOOST_PP_REPEAT(N, BOOST_FUSION_NEXT_ITERATOR, _) BOOST_PP_REPEAT(N, BOOST_FUSION_VALUE_OF_ITERATOR, _) typedef deque<BOOST_PP_ENUM_PARAMS(N, T)> type; }; template <typename Iterator> BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED static typename apply<Iterator>::type call(Iterator const& i0) { typedef apply<Iterator> gen; typedef typename gen::type result; BOOST_PP_REPEAT(BOOST_PP_DEC(N), BOOST_FUSION_NEXT_CALL_ITERATOR, _) return result(BOOST_PP_ENUM_PARAMS(N, *i)); } }; #undef N #endif // defined(BOOST_PP_IS_ITERATING)
[ "znation@apple.com" ]
znation@apple.com
c0d155f4ebdf260d7f51589b5605bbce75d5225b
29c5aff0dd4a3f8d6d3aa6efb744e821f3333ee8
/C++/treeGcmd/main.cpp
0ee2f12d13444662048d159347da5e3c3cdf7c23
[]
no_license
raresdolga/Problems_Algh-Data_Structures
63fd51ae2b330c7c0f92f55445cb813a02022542
aff04a597c2f60cb08e644be7cdcf33a0d7e739f
refs/heads/master
2021-01-01T06:14:00.967879
2018-05-26T21:57:09
2018-05-26T21:57:09
97,386,485
0
0
null
null
null
null
UTF-8
C++
false
false
1,563
cpp
#include <bits/stdc++.h> using namespace std; int mini = 0; int euclid(int a, int b) { int c; while (b) { c = a % b; a = b; b = c; } return a; } void BFS(vector<int> children[],int gcmd_parent[], int parent[], int key[], int nr_nodes){ queue<int> visit; visit.push(0); int now; bool visited[nr_nodes]; for(int i = 0; i < nr_nodes; i++) visited[i] = false; visited[0] = true; while(!visit.empty()){ now = visit.front(); visit.pop(); gcmd_parent[now] = euclid(gcmd_parent[parent[now]], key[now]); for(int i = 0; i < children[now].size(); i++){ if(!visited[(children[now]).at(i)]) visit.push((children[now]).at(i)); } } } int main() { int nr_nodes, i,a,b; cin >> nr_nodes; int gcmd_parent[nr_nodes]; int key[nr_nodes]; vector<int> children[nr_nodes]; for(i = 0; i < nr_nodes; i++){ cin >>key[i]; if(key[i] < key[mini] ) mini = i; children[i] = (vector<int> ()); } int parent[nr_nodes]; gcmd_parent[0] = key[0]; // change just one key to 0 (i.e the minimum one) if(nr_nodes > 1) key[mini] = 0; parent[0] = 0; for(i = 0; i < nr_nodes - 1; i++){ cin >>a>>b; // start from 0 children[a - 1].push_back(b - 1); parent[b - 1] = a - 1; } BFS(children, gcmd_parent, parent, key,nr_nodes); cout<<"\n"; for(i = 0; i < nr_nodes; i++){ cout<<gcmd_parent[i]<< " "; } return 0; }
[ "rares.dolga.16@ucl.ac.uk" ]
rares.dolga.16@ucl.ac.uk
13c38bc740ac00c9d56fc198f11c7edf3dcda979
80ee6883432d059defee6508c6c24be155ff6d9f
/95_UniqueBSTII/solution1.cpp
ffe4ec9fa7cdd0c14e16ea669c2ab9dbc024239c
[]
no_license
evelyn-plee/leetcode
2398dd6dbdb5702ea2f31ebfe45c4ad7ce3790f0
5544082d680da4c4177ca8d6da3cbed8389eadb9
refs/heads/master
2021-06-03T06:38:14.603934
2020-02-20T08:45:24
2020-02-20T08:45:24
130,520,459
1
0
null
null
null
null
UTF-8
C++
false
false
884
cpp
// O(3^n) & O(3^n) /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution{ public: vector<TreeNode*> generateTrees(int n){ if(n==0) return {}; const auto& ans = generateTrees(1, n); return ans; } private: vector<TreeNode*> generateTrees(int l, int r){ if(l > r) return {nullptr}; vector<TreeNode*> ans; for(int i = l; i <= r; ++i){ for(TreeNode* left : generateTrees(l, i-1)){ for(TreeNode* right : generateTrees(i+1, r)){ ans.push_back(new TreeNode(i)); ans.back()->left = left; ans.back()->right = right; } } } return ans; } };
[ "noreply@github.com" ]
noreply@github.com
90d0b737eaf101ad7440390b38c2134006b487e2
d9b2e87c378f84e4451c601404e5061e44a0a935
/PhysicsForGamesvs2015_Start/PhysicsForGames/MyControllerHitReport.h
7c09eb3bc3d7a1edb4dfa385672828fadf5ab33d
[]
no_license
nicholasByrne/PhysicsEngine
5520e65d974f663582e0c2bffe9ed26602a9f3d4
302406afc780900afa205e9d6032e258dcb64610
refs/heads/master
2021-01-17T12:50:01.553190
2016-06-15T05:17:03
2016-06-15T05:17:03
58,355,761
0
0
null
null
null
null
UTF-8
C++
false
false
969
h
#pragma once #include <PxPhysicsAPI.h> #include "glm\glm.hpp" using namespace physx; class MyControllerHitReport : public PxUserControllerHitReport { public: //MyControllerHitReport(); //~MyControllerHitReport(); //overload the onShapeHit function virtual void onShapeHit(const PxControllerShapeHit &hit); //other collision functions which we must overlaod //these handle collision with other controller and hitting obstacles virtual void onControllerHit(const PxControllersHit &hit) {}; //called when current controller hits another controller. More.. virtual void onObstacleHit(const PxControllerObstacleHit &hit) {}; //called when current controller hits a user-defined obstacle MyControllerHitReport() : PxUserControllerHitReport() {}; PxVec3 getPlayerContactNormal() { return _playerContactNormal; }; void ClearPlayerContactNormal() { _playerContactNormal = PxVec3(0, 0, 0); }; PxVec3 _playerContactNormal; //static glm::vec4 RenderColour; };
[ "nicholas.byrne@ad.aie.edu" ]
nicholas.byrne@ad.aie.edu
cf88e805bf9ffa01a48a8351301477055af1406e
36a5354d381c72d5bb5ec8c66da5c37aa1749ae9
/Milestone1_Grafisches_UI/build-Milestone1_Grafisches_UI-Desktop_Qt_5_13_1_MinGW_32_bit-Debug/ui_visuellecriptographytab.h
96813ad5ac7fbabb689bf569e650344fbfcac9e3
[]
no_license
janlycka/propra_goethe_uni_2019_20
52d79b7c1b1ed2acd76df0ec5a3d4d8d166287e6
35a34b9aac91eb54b70b2e2aa622effd3ca2a67c
refs/heads/master
2020-08-23T04:11:50.241314
2019-11-11T12:55:11
2019-11-11T12:55:11
216,540,913
0
0
null
null
null
null
UTF-8
C++
false
false
2,614
h
/******************************************************************************** ** Form generated from reading UI file 'visuellecriptographytab.ui' ** ** Created by: Qt User Interface Compiler version 5.13.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_VISUELLECRIPTOGRAPHYTAB_H #define UI_VISUELLECRIPTOGRAPHYTAB_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QDialog> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_visuellecriptographytab { public: QWidget *verticalLayoutWidget; QVBoxLayout *verticalLayout; QPushButton *pushButton_2; QPushButton *pushButton; void setupUi(QDialog *visuellecriptographytab) { if (visuellecriptographytab->objectName().isEmpty()) visuellecriptographytab->setObjectName(QString::fromUtf8("visuellecriptographytab")); visuellecriptographytab->resize(1259, 614); verticalLayoutWidget = new QWidget(visuellecriptographytab); verticalLayoutWidget->setObjectName(QString::fromUtf8("verticalLayoutWidget")); verticalLayoutWidget->setGeometry(QRect(890, 320, 311, 251)); verticalLayout = new QVBoxLayout(verticalLayoutWidget); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); pushButton_2 = new QPushButton(verticalLayoutWidget); pushButton_2->setObjectName(QString::fromUtf8("pushButton_2")); verticalLayout->addWidget(pushButton_2); pushButton = new QPushButton(verticalLayoutWidget); pushButton->setObjectName(QString::fromUtf8("pushButton")); verticalLayout->addWidget(pushButton); retranslateUi(visuellecriptographytab); QMetaObject::connectSlotsByName(visuellecriptographytab); } // setupUi void retranslateUi(QDialog *visuellecriptographytab) { visuellecriptographytab->setWindowTitle(QCoreApplication::translate("visuellecriptographytab", "Dialog", nullptr)); pushButton_2->setText(QCoreApplication::translate("visuellecriptographytab", "PushButton", nullptr)); pushButton->setText(QCoreApplication::translate("visuellecriptographytab", "PushButton", nullptr)); } // retranslateUi }; namespace Ui { class visuellecriptographytab: public Ui_visuellecriptographytab {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_VISUELLECRIPTOGRAPHYTAB_H
[ "valenarias98@hotmail.com" ]
valenarias98@hotmail.com
6407ec80b484ae3cf83f055dba37951aba7422ef
04addda94f56f35110d49bbd4dad8e2f95478b5a
/math_37.cpp
b0c95cc70ba2e93daf0beb9f506e746a53f0f8e1
[]
no_license
catidiana/math_tasks
64cc5e486b0d983e142eaffd536a1e3127e32a1a
899feeb5eaca8d7a1ed53ca5ae1607ecd0cdd1d3
refs/heads/master
2020-05-25T18:14:43.846555
2019-08-23T20:31:15
2019-08-23T20:31:15
187,924,579
0
0
null
null
null
null
UTF-8
C++
false
false
1,250
cpp
#include <iostream> #include <cmath> using namespace std; //this function test if number is prime. It returns 1 if it's prime int isprime (int num) { if (num == 1) return 0; if (num == 2) return 1; for (int i = 2; i <= sqrt(num); i++) { if (num % i == 0) return 0; } } //this function return the length of number int num_len(int a) { int len=0; while (a!=0) { a=a/10; len++; } return len; } //this function test interesting property int isinteresting (int a) { int N=num_len(a); int prime_test; if (isprime(a)) prime_test=1; else return 0; int test1=a/10; while (test1>0) { if(isprime(test1)==0) return 0; test1=test1/10; } int test2=a; for (int i=N-1;i>0;i--) { int k=pow(10, i); test2=test2%k; if (isprime(test2)==0) return 0; } return prime_test; } int main() { int i=0; int k=11; int sum=0; while (i<11) { if (isinteresting(k)) { cout << "Interesting " << k << endl; sum=sum+k; i++; } k=k+2; } cout << "Sum is " << sum << endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
a20bddb0bc69ee706fc4247f8311dd49d2fcf837
8483752549e2bf8cfa624862325f4f8e9d2d5727
/samples/06_mediaplayer/06_mediaplayer.cpp
ed5ae72ab789a152a48deb84d53d013611b2ae16
[ "MIT" ]
permissive
asdlei99/aoce
cefe0d749d8c05ab502827a63e82b17248942540
303e9b0519671b96875dbd60fc5a115ac61781ce
refs/heads/master
2023-02-27T16:30:27.672584
2021-02-05T10:40:19
2021-02-05T10:40:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,479
cpp
#include <AoceManager.hpp> #include <Media/MediaPlayer.hpp> #include <Module/ModuleManager.hpp> #include <iostream> #include <memory> #include <string> #include <thread> #include <vulkan/VulkanContext.hpp> #include <vulkan/VulkanWindow.hpp> #ifdef __ANDROID__ #include <android/native_activity.h> #include <android/native_window_jni.h> #include <android_native_app_glue.h> #include "../../code/aoce/Aoce.h" #include "errno.h" #endif using namespace aoce; using namespace aoce::vulkan; static std::unique_ptr<VulkanWindow> window = nullptr; static PipeGraph *vkGraph; static InputLayer *inputLayer; static OutputLayer *outputLayer; static YUV2RGBALayer *yuv2rgbLayer; static VideoFormat format = {}; static GpuType gpuType = GpuType::vulkan; static MediaPlayer *player = nullptr; // test rtmp // static std::string uri = "rtmp://202.69.69.180:443/webcast/bshdlive-pc"; static std::string uri = "rtmp://58.200.131.2:1935/livetv/hunantv"; // rtmp://58.200.131.2:1935/livetv/hunantv // static std::string uri = "D://备份/tnmil3.flv"; class TestMediaPlay : public IMediaPlayerObserver { public: TestMediaPlay() {} virtual ~TestMediaPlay() override{}; public: virtual void onPrepared() override { logMessage(LogLevel::info, "start"); player->start(); } virtual void onError(PlayStatus staus, int32_t code, std::string msg) override { std::string mssg; string_format(mssg, "status: ", (int32_t)staus, " msg: ", msg); logMessage(LogLevel::info, mssg); }; virtual void onVideoFrame(const VideoFrame &frame) override { std::string msg; string_format(msg, "time stamp: ", frame.timeStamp); logMessage(LogLevel::info, msg); if (format.width != frame.width || format.height != frame.height) { format.width = frame.width; format.height = frame.height; format.videoType = frame.videoType; inputLayer->setImage(format); yuv2rgbLayer->updateParamet({format.videoType}); } inputLayer->inputCpuData(frame, 0); vkGraph->run(); #if __ANDROID__ if (window) { window->tick(); } #endif }; virtual void onStop() override{}; virtual void onComplate() override{}; }; void onPreCommand(uint32_t index) { VkImage winImage = window->images[index]; VkCommandBuffer cmd = window->cmdBuffers[index]; // 我们要把cs生成的图复制到正在渲染的图上,先改变渲染图的layout changeLayout(cmd, winImage, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); VkOutGpuTex outTex = {}; outTex.commandbuffer = cmd; outTex.image = winImage; outTex.width = window->width; outTex.height = window->height; outputLayer->outVkGpuTex(outTex); // 复制完成后,改变渲染图的layout准备呈现 changeLayout(cmd, winImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); } static TestMediaPlay *testPlay = nullptr; #if _WIN32 int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int) { loadAoce(); // 生成一张执行图 vkGraph = AoceManager::Get().getPipeGraphFactory(gpuType)->createGraph(); auto *layerFactory = AoceManager::Get().getLayerFactory(gpuType); inputLayer = layerFactory->crateInput(); outputLayer = layerFactory->createOutput(); // 输出GPU数据 outputLayer->updateParamet({false, true}); yuv2rgbLayer = layerFactory->createYUV2RGBA(); // 生成图 vkGraph->addNode(inputLayer)->addNode(yuv2rgbLayer)->addNode(outputLayer); player = AoceManager::Get().getMediaPlayerFactory(MediaPlayType::ffmpeg)->createPlay(); // 因执行图里随时重启,会导致相应资源重启,故运行时确定commandbuffer window = std::make_unique<VulkanWindow>(onPreCommand, false); window->initWindow(hInstance, 1280, 720, "vulkan test"); std::this_thread::sleep_for(std::chrono::milliseconds(100)); testPlay = new TestMediaPlay(); player->setDataSource(uri.c_str()); player->setObserver(testPlay); player->prepare(true); window->run(); unloadAoce(); } #elif __ANDROID__ extern "C" { JNIEXPORT void JNICALL Java_aoce_samples_mediaplayer_MainActivity_initEngine( JNIEnv *env, jobject thiz) { loadAoce(); AndroidEnv andEnv = {}; andEnv.env = env; andEnv.activity = thiz; AoceManager::Get().initAndroid(andEnv); // 生成一张执行图 vkGraph = AoceManager::Get().getPipeGraphFactory(gpuType)->createGraph(); auto *layerFactory = AoceManager::Get().getLayerFactory(gpuType); inputLayer = layerFactory->crateInput(); outputLayer = layerFactory->createOutput(); // 输出GPU数据 outputLayer->updateParamet({false, true}); yuv2rgbLayer = layerFactory->createYUV2RGBA(); // 生成图 vkGraph->addNode(inputLayer)->addNode(yuv2rgbLayer)->addNode(outputLayer); player = AoceManager::Get().getMediaPlayerFactory(MediaPlayType::ffmpeg)->createPlay(); testPlay = new TestMediaPlay(); player->setObserver(testPlay); } JNIEXPORT void JNICALL Java_aoce_samples_mediaplayer_MainActivity_vkInitSurface( JNIEnv *env, jobject thiz, jobject surface, jint width, jint height) { ANativeWindow *winSurf = surface ? ANativeWindow_fromSurface(env, surface) : nullptr; window = std::make_unique<VulkanWindow>(onPreCommand, false); window->initSurface(winSurf); } JNIEXPORT void JNICALL Java_aoce_samples_mediaplayer_MainActivity_glCopyTex( JNIEnv *env, jobject thiz, jint textureId, jint width, jint height) { VkOutGpuTex outGpuTex = {}; outGpuTex.image = textureId; outGpuTex.width = width; outGpuTex.height = height; outputLayer->outGLGpuTex(outGpuTex); } JNIEXPORT void JNICALL Java_aoce_samples_mediaplayer_MainActivity_openUri( JNIEnv *env, jobject thiz, jstring uri) { const char *str = nullptr; jboolean bCopy = false; str = env->GetStringUTFChars(uri, &bCopy); if (str == NULL) { return; } // copy std::string ruri = str; env->ReleaseStringUTFChars(uri, str); player->setDataSource(ruri.c_str()); player->prepare(true); } } #endif
[ "mfjt55@163.com" ]
mfjt55@163.com
5104857f1d5dbbd4f280cc3dfca30e4b1a1150da
88d4b94ae710bf6dde982fa911221d8bac016655
/FlowerShop/FlowerShopTest/stdafx.cpp
5580e9e0cd6a5d7d08973568a35cc95b13f514f3
[]
no_license
Anatoliy90/Shop
8bdb105e3e22a764e46ac6fa0d01013e7d88549f
44571ebb79c99eb1ef4966ab2e1afc496fbfd159
refs/heads/master
2020-06-05T18:51:57.687445
2015-04-14T20:44:34
2015-04-14T20:44:34
33,952,738
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
578
cpp
// stdafx.cpp: исходный файл, содержащий только стандартные включаемые модули // FlowerShopTest.pch будет предкомпилированным заголовком // stdafx.obj будет содержать предварительно откомпилированные сведения о типе #include "stdafx.h" // TODO: Установите ссылки на любые требующиеся дополнительные заголовки в файле STDAFX.H // , а не в данном файле
[ "601762847@mail.ru" ]
601762847@mail.ru
071d8547039b9de853252552b19f48cf928ab420
544f19af502328a6b614b9bb9515702f58466528
/apps/src/polygonization.cpp
908fe1c10314cb9b67a2f9334d7c89f79e912a60
[]
no_license
YuePanEdward/TAMS-Planar-Surface-Based-Perception
a47f99c2fdb9d412d65fa0e1c5d601070d21b641
6f6b3eb6326dcdf5039da1dbc9e7ba86800f7042
refs/heads/master
2020-04-18T13:40:04.365896
2013-03-13T16:48:33
2013-03-13T16:48:33
167,567,483
0
1
null
2019-01-25T15:20:02
2019-01-25T15:20:02
null
UTF-8
C++
false
false
116
cpp
#include "polygonization/polygonization.h" int main(int argc, char **argv) { tamrot::Polygonization polygizer; }
[ "junhao.xiao@hotmail.com" ]
junhao.xiao@hotmail.com
262e443408d1e81d26f7fc09dba4295268ae8273
8e242d624781b66c3dece9826c9e6bd0b358b59c
/PacsLite/pacslite/InternalSetupDLL/NSInternalSetup/StdAfx.cpp
b3423769e23381903fb8c5fb442877ed9d1e8af9
[]
no_license
asianhawk/Legacy
3b46d89dc0391e7bdb47d17af5142e63b9cd56a4
ac0e7cbdfade4fa7360e61597a9af49520ba8867
refs/heads/master
2020-07-23T09:22:15.206570
2015-01-20T17:32:51
2015-01-20T17:32:51
207,512,160
1
0
null
2019-09-10T09:01:39
2019-09-10T09:01:38
null
UTF-8
C++
false
false
209
cpp
// stdafx.cpp : source file that includes just the standard includes // NSInternalSetup.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "tpm777@gmail.com" ]
tpm777@gmail.com
1ba6feca25d7b484397ee3ba3f4bda375fa4b0b0
640dd07e9b1e1af23d633179aadb0fe5b65a0fb2
/day_11_5/day_11_5/day_11_6.cpp
9608da990468510bae11bec70418bcf4bfa76f60
[]
no_license
dragon-web/review_cpp
247e419d9e64179cef5aaaed3b963f9f6e1068f2
41b7a5c7e703b6da22423d491e39a51f2d14c803
refs/heads/master
2023-01-08T11:18:06.637692
2020-11-13T13:41:39
2020-11-13T13:41:39
283,394,878
0
0
null
null
null
null
UTF-8
C++
false
false
1,369
cpp
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<map> #include<unordered_map> #include<unordered_set> #include<vector> #include<string> #include<stack> using namespace std; /* class Solution { public: bool buddyStrings(string A, string B) { if (A.size() != B.size()) return false; if (A == B) { unordered_map<char, int> hash; for (char c : A) hash[c] += 1; for (char c : A) { if (hash[c] > 1) return true; } return false; } else { int first = -1, second = -1; for (int i = 0; i < A.size(); i++) { if (A[i] != B[i]) { if (first == -1) first = i; else if (second == -1) second = i; else return false; } } return (second != -1 && A[first] == B[second] && A[second] == B[first]); } } }; */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: bool isPalindrome(ListNode* head) { vector<int> dp; vector<int> dp1; stack<ListNode*> temp; ListNode* p = head; ListNode* tail = head; while (p != NULL) { dp.push_back(p->val); temp.push(p); p = p->next; } while (temp.size()) { int num = temp.top()->val; dp1.push_back(num); temp.pop(); } if (dp1 == dp) { return true; } else { return false; } } }; int main() { system("pause"); return 0; }
[ "1582943265@qq.com" ]
1582943265@qq.com
82808b96935191a9a5381a2edeb6331f7ab1dc39
281420e81eeedc441927980fd3145f02d623fef6
/swig_cmake_example/src/student.h
aa08826a3b4196f4d4dc62c49d29df8959ea4b6a
[ "Apache-2.0" ]
permissive
gzzyj/code_examples
8add585776e9681f27a170f97b589726c6868526
d5500a4e68078fbe051e3dc845b7c2be0c3d4ab1
refs/heads/master
2022-09-07T00:44:50.458570
2020-06-02T10:29:43
2020-06-02T10:29:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
282
h
#ifndef STUDENT_H_ #define STUDENT_H_ #include <string> #include <iostream> using namespace std; class Student { private: string name; int age; public: Student(); Student(string name, int age); ~Student(); void show(); }; #endif // end of STUDENT_H_
[ "tobeg3oogle@gmail.com" ]
tobeg3oogle@gmail.com
c05c33b416d195df2fae76045e82653632953d7b
1af8ccada10ba81ddf8def3eae3c5defdd91287c
/include/VTKPlotView.h
b3bff309dee143fda397f13fe02d0f6c2e319382
[]
no_license
barug/Scriptbots-NEAT
4ae62696e9d5bbd74541c727c5c15d79d9f60452
06bf5973ead2bd5d705d97b8e1efd816c4acc51c
refs/heads/NEAT
2020-03-26T13:38:53.062936
2019-10-11T13:01:20
2019-10-11T13:01:20
144,949,641
3
0
null
2018-12-04T07:49:18
2018-08-16T06:58:37
C++
UTF-8
C++
false
false
880
h
// // Created by barth on 9/3/18. // #ifndef SCRIPTBOTS_VTKPLOTVIEW_H #define SCRIPTBOTS_VTKPLOTVIEW_H #include <vtkNew.h> #include <vtkSmartPointer.h> #include "vtkChartXY.h" #include "vtkStatisticsAlgorithm.h" #include "vtkComputeQuartiles.h" #include "vtkContextScene.h" #include "vtkContextView.h" #include "vtkIntArray.h" #include "vtkLookupTable.h" #include "vtkPlotBox.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkStringArray.h" #include "vtkTable.h" #include "vtkAxis.h" #include "vtkTextProperty.h" #include <vtkPlotLine.h> class VTKPlotView; extern VTKPlotView *VTKPLOTVIEW; class VTKPlotView { vtkNew<vtkContextView> _view; vtkNew<vtkTable> _data; public: VTKPlotView(); void addDataRow(int numHerb, int numCarn); void startInteraction(); }; #endif //SCRIPTBOTS_VTKPLOTVIEW_H
[ "barthelemy.gouby@gmail.com" ]
barthelemy.gouby@gmail.com
b378577d9b2edf5ce8ff4488696b80cb60905aab
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5708921029263360_0/C++/aidarbek98/C1.cpp
8012e41c0e5c8c4df74af1c0486e4f6c11bf8635
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,946
cpp
/// izizi #include <cstring> #include <vector> #include <map> #include <set> #include <bitset> #include <algorithm> #include <iostream> #include <cstdio> #include <cmath> #include <cassert> #include <cstdlib> #include <ctime> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; const double EPS = 1e-9; const double PI = acos(-1); const int oo = 1e9, bpr = 1e9 + 7, N = 5; #define mp make_pair #define eb emplace_back #define pb push_back #define fe first #define se second int a[N][N]; int cnt1[N][N], cnt2[N][N], cnt4[N][N], cnt3[N][N][N]; vector <int> b[3], best[3]; int J, P, S, k; inline void rec (int x, int k1, int k2) { if (x > S) { if (best[0].size () < b[0].size ()) for (int i = 0; i < 3; ++i) best[i] = b[i]; return; } for (int i = k1; i <= J; ++i) { for (int j = ((i == k1) ? (k2 + 1) : (1)); j <= P; ++j) { if (cnt1[x][i] < k && cnt2[i][j] < k && cnt4[x][j] < k && !cnt3[x][i][j]) { ++cnt1[x][i]; ++cnt2[i][j]; ++cnt4[x][j]; ++cnt3[x][i][j]; b[2].pb (x); b[0].pb (i); b[1].pb (j); rec (x, i, j); --cnt1[x][i]; --cnt2[i][j]; --cnt4[x][j]; --cnt3[x][i][j]; b[0].pop_back (); b[1].pop_back (); b[2].pop_back (); } } } rec (x + 1, 1, 0); } int main() { freopen ("in", "r", stdin); freopen ("out", "w", stdout); ios_base :: sync_with_stdio (0); cin.tie (0); int test_num; cin >> test_num; for (int test = 1; test <= test_num; ++test) { cout << "Case #" << test << ": "; cin >> J >> P >> S >> k; cerr << test << "\n"; for (int i = 0; i < 3; ++i) best[i].clear (); rec (1, 1, 0); cout << best[0].size () << "\n"; for (int i = 0; i < (int)best[0].size (); ++i) { for (int j = 0; j < 3; ++j) cout << best[j][i] << " "; cout << "\n"; } } return 0; }
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
8ebeb4ca626d04ed05fcf0417e36f641f9a5f70f
bdd1d996d5aa26e6f6628e97d7df013ab43de710
/src/tile_atlas.cpp
5bcd59d4fb5c83adf7f7d3c95279d95546257c8a
[]
no_license
MarkOates/beary2d
aa55da891a3fb10c5678e7eca58619fb39c71b62
c6e9a7d4819ea23b83331c30cb23b5318afa8905
refs/heads/master
2021-05-16T03:12:30.383710
2019-10-29T18:15:25
2019-10-29T18:15:25
39,583,081
2
0
null
null
null
null
UTF-8
C++
false
false
3,493
cpp
#include <allegro_flare/color.h> #include <beary2d/tile_atlas.h> #include <iostream> #include <beary2d/tile.h> TileAtlas::TileAtlas() : tile_atlas(NULL) , tiles() , tile_width(16) , tile_height(16) {} void TileAtlas::load_from_atlas(ALLEGRO_BITMAP *tile_atlas, int tile_width, int tile_height, int margin_x, int margin_y, int tile_padding_x, int tile_padding_y) { tiles.clear(); this->tile_atlas = tile_atlas; this->tile_width = tile_width; this->tile_height = tile_height; int num_rows = (al_get_bitmap_width(tile_atlas) - margin_x*2) / (tile_width + tile_padding_x); int num_cols = (al_get_bitmap_height(tile_atlas) - margin_y*2) / (tile_height + tile_padding_y); if (tile_padding_x > 0) num_rows++; if (tile_padding_y > 0) num_cols++; std::cout << "loading tileset " << num_cols << "x" << num_rows << std::endl; for (int row=0; row<num_rows; row++) for (int col=0; col<num_cols; col++) tiles.push_back(al_create_sub_bitmap(tile_atlas, margin_x + col*(tile_width) + col*(tile_padding_x*2) + tile_padding_x, margin_y + row*(tile_height) + row*(tile_padding_y*2) + tile_padding_y, tile_width, tile_height)); std::cout << "num tiles: " << tiles.size() << std::endl; } bool TileAtlas::export_atlas(std::string image_filename) // exports with no padding and no margins { int num_cols = 8; int num_rows = (tiles.size() / num_cols); if (num_rows % num_cols > 0) num_rows++; int atlas_width = num_cols * tile_width; int atlas_height = num_rows * tile_height; ALLEGRO_STATE previous_state; al_store_state(&previous_state, ALLEGRO_STATE_TARGET_BITMAP | ALLEGRO_STATE_BLENDER); ALLEGRO_BITMAP *atlas_for_export = al_create_bitmap(atlas_width, atlas_height); al_set_target_bitmap(atlas_for_export); al_clear_to_color(color::transparent); for (int i=0; i<(int)tiles.size(); i++) { int row = i / num_cols; int col = i % num_cols; Tile *t = get_tile(i); if (t && t->bitmap) al_draw_bitmap(t->bitmap, col*tile_width, row*tile_height, 0); } al_save_bitmap(image_filename.c_str(), atlas_for_export); al_restore_state(&previous_state); al_destroy_bitmap(atlas_for_export); return true; } Tile *TileAtlas::set(int index, ALLEGRO_BITMAP *bitmap) { if ((int)tiles.size() <= index) tiles.resize((index+1), NULL); else { // clear the existing tile bitmap data if (tiles[index].bitmap) al_destroy_bitmap(tiles[index].bitmap); } tiles[index].bitmap = bitmap; return &tiles[index]; //return NULL; } Tile *TileAtlas::set(int index, ALLEGRO_BITMAP *bitmap, int64_t flags) { if ((int)tiles.size() >= index) tiles.resize(index, NULL); else { // clear the existing tile bitmap data if (tiles[index].bitmap) al_destroy_bitmap(tiles[index].bitmap); } tiles[index].bitmap = bitmap; tiles[index].flags = flags; return &tiles[index]; } Tile *TileAtlas::get_tile(int index) { //if (index < 0 || tiles.empty() || index >= (int)tiles.size()) return NULL; // want to avoid this at all costs return &tiles[index]; } void TileAtlas::clear() { tiles.clear(); } int TileAtlas::get_tile_width() { return tile_width; } int TileAtlas::get_tile_height() { return tile_height; } void TileAtlas::set_tile_height(int height) { tile_height = height; } void TileAtlas::set_tile_width(int width) { tile_width = width; } void TileAtlas::lock_bitmap() { al_lock_bitmap(this->tile_atlas, ALLEGRO_PIXEL_FORMAT_ANY, ALLEGRO_LOCK_READONLY); } void TileAtlas::unlock_bitmap() { al_unlock_bitmap(this->tile_atlas); }
[ "euph_boy@hotmail.com" ]
euph_boy@hotmail.com
233a1be6a2a9ac01d2dcae431d90da21fe424078
567b6ec9778d8bda5dfb43ee7139ed06e5d72af7
/trunk/private/net/snmp/subagent/snmpevnt/evntcmd/registry.cpp
20f82a46e1e38987ab01f43c7edb04370da920e2
[]
no_license
mfkiwl/win2k
5542bce486d5b827d47a9fb4770fae7cd0a77718
074be7e4bf30a5f67672382fa5c9e34765949da1
refs/heads/master
2023-01-11T08:52:03.896046
2020-11-10T06:22:50
2020-11-10T06:22:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,180
cpp
#include <stdafx.h> #include "Errors.h" #include "EventCmd.h" #include "Registry.h" #include "Operation.h" CRegistry gRegistry; DWORD CRegistry::ConfigureRegSource(HKEY hRegSource, char* szEventSource) { DWORD retCode; char* szSourceOID; char* szEventDup; int nIndex; DWORD dwAppend; szSourceOID = new char[4 * strlen(szEventSource) + 9]; if (szSourceOID == NULL) return _E(ERROR_OUTOFMEMORY, IDS_ERR01); nIndex = sprintf(szSourceOID, "%u.", strlen(szEventSource)); for (szEventDup = szEventSource; *szEventDup != '\0'; szEventDup++) nIndex += sprintf(szSourceOID + nIndex, "%d.", *szEventDup); if (nIndex == 0) { retCode = _E(ERROR_FUNCTION_FAILED, IDS_ERR05, szEventSource); goto done; } szSourceOID[--nIndex] = '\0'; retCode = RegSetValueEx(hRegSource, REG_SRC_ENTOID, 0, REG_SZ, (const BYTE*)szSourceOID, nIndex); if (retCode != ERROR_SUCCESS) { retCode = _E(retCode, IDS_ERR11, REG_SRC_ENTOID, szEventSource); goto done; } dwAppend = 1; retCode = RegSetValueEx(hRegSource, REG_SRC_APPEND, 0, REG_DWORD, (const BYTE*)&dwAppend, sizeof(DWORD)); if (retCode != ERROR_SUCCESS) { retCode = _E(retCode, IDS_ERR11, REG_SRC_APPEND, szEventSource); goto done; } _W(WARN_TRACK, IDS_TRCK_WRN33, szEventSource); done: delete szSourceOID; return retCode; } DWORD CRegistry::ConfigureRegEvent(HKEY hRegEvent, DWORD dwEventID, DWORD dwCount, DWORD dwTime) { DWORD retCode = ERROR_SUCCESS; retCode = RegSetValueEx(hRegEvent, REG_EVNT_ID, 0, REG_DWORD, (const BYTE*)&dwEventID, sizeof(DWORD)); if (retCode != ERROR_SUCCESS) return _E(retCode, IDS_ERR13, REG_EVNT_ID, dwEventID); retCode = RegSetValueEx(hRegEvent, REG_EVNT_COUNT, 0, REG_DWORD, (const BYTE*)&dwCount, sizeof(DWORD)); if (retCode != ERROR_SUCCESS) return _E(retCode, IDS_ERR13, REG_EVNT_COUNT, dwEventID); retCode = RegSetValueEx(hRegEvent, REG_EVNT_TIME, 0, REG_DWORD, (const BYTE*)&dwTime, sizeof(DWORD)); if (retCode != ERROR_SUCCESS) return _E(retCode, IDS_ERR13, REG_EVNT_TIME, dwEventID); return retCode; } DWORD CRegistry::ScanForTrap(HKEY hRegCommunity, char* szAddress, char* szName, DWORD& nNameLen) { DWORD retCode; DWORD nMaxName = 1; char szDataBuffer[64]; for (DWORD i = 0, iNameLen = nNameLen, iDataLen = 64; (retCode = RegEnumValue(hRegCommunity, i, szName, &iNameLen, 0, NULL, (BYTE*)szDataBuffer, &iDataLen)) == ERROR_SUCCESS; i++, iNameLen = nNameLen, iDataLen = 64) { DWORD nNameNum; if (strcmp(szDataBuffer, szAddress) == 0) return ERROR_ALREADY_EXISTS; nNameNum = atoi(szName); if (nMaxName <= nNameNum) nMaxName = nNameNum + 1; } if (retCode != ERROR_NO_MORE_ITEMS) return _E(retCode, IDS_ERR12); nNameLen = sprintf(szName, "%u", nMaxName); retCode = ERROR_SUCCESS; return retCode; } CRegistry::CRegistry() { m_hRegRoot = HKEY_LOCAL_MACHINE; m_hRegSnmpTraps = NULL; m_hRegEvntSources = NULL; m_dwFlags = 0; } CRegistry::~CRegistry() { if (m_hRegRoot != HKEY_LOCAL_MACHINE) RegCloseKey(m_hRegRoot); if (m_hRegSnmpTraps != NULL) RegCloseKey(m_hRegSnmpTraps); if (m_hRegEvntSources != NULL) RegCloseKey(m_hRegEvntSources); } DWORD CRegistry::Connect() { DWORD retCode = ERROR_SUCCESS; if (gCommandLine.m_szSystem != NULL) { _W(WARN_ATTENTION, IDS_ATTN_WRN34, gCommandLine.m_szSystem); retCode = RegConnectRegistry(gCommandLine.m_szSystem, HKEY_LOCAL_MACHINE, &m_hRegRoot); } if (retCode != ERROR_SUCCESS) return _E(retCode, IDS_ERR14, gCommandLine.m_szSystem); return retCode; } DWORD CRegistry::AddEvent(char* szEventSource, DWORD dwEventID, DWORD dwCount, DWORD dwTime) { DWORD retCode; DWORD dwDisposition; HKEY hRegSource; HKEY hRegEvent; char szEventID[64]; if (m_hRegEvntSources == NULL) { retCode = RegOpenKeyEx(m_hRegRoot, REGPATH_EVNTAGENT, 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_WRITE, &m_hRegEvntSources); if (retCode != ERROR_SUCCESS) return _E(retCode, IDS_ERR15); } retCode = RegCreateKeyEx(m_hRegEvntSources, szEventSource, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hRegSource, &dwDisposition); if (retCode != ERROR_SUCCESS) return _E(retCode, IDS_ERR16, szEventSource); if (dwDisposition == REG_CREATED_NEW_KEY) { retCode = ConfigureRegSource(hRegSource, szEventSource); if (retCode != ERROR_SUCCESS) { RegCloseKey(hRegSource); return retCode; } } sprintf(szEventID, "%u", dwEventID); retCode = RegCreateKeyEx(hRegSource, szEventID, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hRegEvent, &dwDisposition); if (retCode != ERROR_SUCCESS) { RegCloseKey(hRegSource); return _E(retCode, IDS_ERR17, szEventSource); } retCode = ConfigureRegEvent(hRegEvent, dwEventID, dwCount, dwTime); _W(WARN_ATTENTION, IDS_ATTN_WRN35, dwDisposition == REG_CREATED_NEW_KEY ? "new" : "existing", dwEventID); RegCloseKey(hRegSource); RegCloseKey(hRegEvent); return retCode; } DWORD CRegistry::DelEvent(char* szEventSource, DWORD dwEventID) { DWORD retCode; char szEventID[64]; DWORD nSzEventID = 64; HKEY hRegSource; FILETIME ft; if (m_hRegEvntSources == NULL) { retCode = RegOpenKeyEx(m_hRegRoot, REGPATH_EVNTAGENT, 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_WRITE, &m_hRegEvntSources); if (retCode != ERROR_SUCCESS) return _E(retCode, IDS_ERR18); } retCode = RegOpenKeyEx(m_hRegEvntSources, szEventSource, 0, KEY_ENUMERATE_SUB_KEYS | KEY_WRITE, &hRegSource); if (retCode != ERROR_SUCCESS) { _W(WARN_ATTENTION, IDS_ATTN_WRN36, szEventSource); return ERROR_SUCCESS; } sprintf(szEventID, "%u", dwEventID); retCode = RegDeleteKey(hRegSource, szEventID); if (retCode != ERROR_SUCCESS) { _W(WARN_ATTENTION, IDS_ATTN_WRN37, szEventID); RegCloseKey(hRegSource); return ERROR_SUCCESS; } _W(WARN_ATTENTION, IDS_ATTN_WRN38, dwEventID); retCode = RegEnumKeyEx(hRegSource, 0, szEventID, &nSzEventID, 0, NULL, NULL, &ft); RegCloseKey(hRegSource); if (retCode == ERROR_NO_MORE_ITEMS) { retCode = RegDeleteKey(m_hRegEvntSources, szEventSource); if (retCode != ERROR_SUCCESS) return _E(retCode, IDS_ERR19, szEventSource); _W(WARN_TRACK, IDS_TRCK_WRN39, szEventSource); retCode = ERROR_SUCCESS; } else if (retCode != ERROR_SUCCESS) { _W(WARN_TRACK, IDS_TRCK_WRN40, retCode, szEventSource); retCode = ERROR_SUCCESS; } return retCode; } DWORD CRegistry::AddTrap(char* szCommunity, char* szAddress) { DWORD retCode; DWORD dwDisposition; char szTrapName[64]; DWORD nLenTrapName = 64; HKEY hRegCommunity; if (m_hRegSnmpTraps == NULL) { retCode = RegOpenKeyEx(m_hRegRoot, REGPATH_SNMPTRAPS, 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_WRITE, &m_hRegSnmpTraps); if (retCode != ERROR_SUCCESS) return _E(retCode, IDS_ERR20); } retCode = RegCreateKeyEx(m_hRegSnmpTraps, szCommunity, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hRegCommunity, &dwDisposition); if (retCode != ERROR_SUCCESS) return _E(retCode, IDS_ERR21, szCommunity); if (dwDisposition == REG_CREATED_NEW_KEY) _W(WARN_TRACK, IDS_TRCK_WRN41, szCommunity); retCode = ScanForTrap(hRegCommunity, szAddress, szTrapName, nLenTrapName); if (retCode != ERROR_SUCCESS) { RegCloseKey(hRegCommunity); if (retCode == ERROR_ALREADY_EXISTS) { _W(WARN_ATTENTION, IDS_ATTN_WRN42, szAddress, szTrapName); retCode = ERROR_SUCCESS; } return retCode; } retCode = RegSetValueEx(hRegCommunity, szTrapName, 0, REG_SZ, (const BYTE*)szAddress, strlen(szAddress)); if (retCode != ERROR_SUCCESS) _E(retCode, IDS_ERR22, szAddress); else { m_dwFlags |= REG_FLG_NEEDRESTART; _W(WARN_ATTENTION, IDS_ATTN_WRN43, szAddress); } RegCloseKey(hRegCommunity); return retCode; } DWORD CRegistry::DelTrap(char* szCommunity, char* szAddress) { DWORD retCode; char szTrapName[64]; DWORD nLenTrapName = 64; HKEY hRegCommunity; if (m_hRegSnmpTraps == NULL) { retCode = RegOpenKeyEx(m_hRegRoot, REGPATH_SNMPTRAPS, 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_WRITE, &m_hRegSnmpTraps); if (retCode != ERROR_SUCCESS) return _E(retCode, IDS_ERR23); } if ((retCode = RegOpenKeyEx(m_hRegSnmpTraps, szCommunity, 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_WRITE, &hRegCommunity)) == ERROR_SUCCESS && (retCode = ScanForTrap(hRegCommunity, szAddress, szTrapName, nLenTrapName)) == ERROR_ALREADY_EXISTS) { retCode = RegDeleteValue(hRegCommunity, szTrapName); if (retCode != ERROR_SUCCESS) { RegCloseKey(hRegCommunity); return _E(retCode, IDS_ERR24, szAddress); } else { m_dwFlags |= REG_FLG_NEEDRESTART; _W(WARN_ATTENTION, IDS_ATTN_WRN44, szAddress); } } else { _W(WARN_ATTENTION, IDS_ATTN_WRN45, szAddress, szCommunity); retCode = ERROR_SUCCESS; } retCode = RegEnumValue(hRegCommunity, 0, szTrapName, &nLenTrapName, 0, NULL, NULL, NULL); RegCloseKey(hRegCommunity); if (retCode == ERROR_NO_MORE_ITEMS) { retCode = RegDeleteKey(m_hRegSnmpTraps, szCommunity); if (retCode != ERROR_SUCCESS) _W(WARN_ERROR, IDS_ERRO_WRN46, retCode, szCommunity); else _W(WARN_TRACK, IDS_TRCK_WRN47, szCommunity); retCode = ERROR_SUCCESS; } else if (retCode != ERROR_SUCCESS) { _W(WARN_TRACK, IDS_TRCK_WRN48, retCode, szCommunity); retCode = ERROR_SUCCESS; } return retCode; }
[ "112426112@qq.com" ]
112426112@qq.com
8e7f6459cadcb62fc5a703a4a6ace958ca2ecd7f
ca47ac4151a291f8615b5d190d5eb8efa4e54495
/library/tune/tune_ddot.cpp
6471c3452923b194667f0bf32bec3c1ab52958de
[]
no_license
pc2/liftracc
ce91dc785516b0a15960d8e9cbdc64b955102131
1cdfca41a11fd5fa5a661767e6a0aea176aa379d
refs/heads/master
2021-01-19T22:33:00.816193
2011-01-25T03:21:27
2011-01-25T03:21:27
650,211
2
1
null
null
null
null
UTF-8
C++
false
false
2,862
cpp
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <time.h> #include <math.h> #ifndef __USE_GNU #define __USE_GNU #endif #include <dlfcn.h> #include <sched.h> #include <math.h> #include <signal.h> #include "liftracc.h" #include "liftracc_logging.h" #include "liftracc_profiling.h" extern "C" { #include "cblas.h" } unsigned int error_count = 0; const int max_runs = 30; const int max_exp = 14; const int max_dim = (int)pow(2, max_exp); const int max_entries = max_dim; #ifdef _LIFTRACC_PROFILING_ profiling_data_t data[max_exp+1] = { }; #endif /* _LIFTRACC_PROFILING_ */ void INThandler(int); int main(int argc, char** argv) { signal(SIGINT, INThandler); /* pid_t pid = getpid(); struct sched_param sparam; if (sched_getparam(pid, &sparam) > -1) { sparam.sched_priority = sched_get_priority_max(SCHED_FIFO); if (sched_setscheduler(pid, SCHED_FIFO, &sparam) == 0) MSG("Scheduler set to FIFO!\n"); else MSG("Scheduler not set!\n"); } else MSG("Scheduler not set!\n"); */ #ifdef _LIFTRACC_PROFILING_ for (int i=0; i<1000; i++) { liftracc_function_timing_start(&(liftracc_profiling_data[MEASURING_ERROR])); liftracc_function_timing_stop(&(liftracc_profiling_data[MEASURING_ERROR])); } #endif /* _LIFTRACC_PROFILING_ */ double *dA = (double*) malloc( sizeof(double) * max_entries ); double *dB = (double*) malloc( sizeof(double) * max_entries ); srand(time(0)); MSG("Starting ddot tuning.\n"); int i, j, c; for (i=1; i<=max_exp; i++) { int p = (int)pow(2, i); for (j=0; j<max_runs; j++) { MSG("Generate Random Array."); for (c=0; c<p; c++) dA[c] = (double)(rand()%500/100.0); for (c=0; c<p; c++) dB[c] = (double)(rand()%500/100.0); MSG("Done."); #ifdef _LIFTRACC_PROFILING_ liftracc_function_timing_start(&(data[i])); #endif /* _LIFTRACC_PROFILING_ */ double ret = liftracc_ddot(p, dA, 1, dB, 1); #ifdef _LIFTRACC_PROFILING_ liftracc_function_timing_stop(&(data[i])); #endif /* _LIFTRACC_PROFILING_ */ MSG("RET: %f", ret); MSG("tune_%d_%d.run", p, j); } } #ifdef _LIFTRACC_PROFILING_ print_profiling_data("tune_ddot_result", &(liftracc_profiling_data[0]), prof_id_names, ID_COUNT); print_profiling_data("tune_ddot_result", &(data[0]), 0, max_exp+1); #endif /* _LIFTRACC_PROFILING_ */ return error_count; } void INThandler(int sig) { signal(sig, SIG_IGN); #ifdef _LIFTRACC_PROFILING_ MSG("Saving partly collected data.\n"); print_profiling_data("tune_ddot_result", &(liftracc_profiling_data[0]), prof_id_names, ID_COUNT); print_profiling_data("tune_ddot_result", &(data[0]), 0, max_exp+1); #endif /* _LIFTRACC_PROFILING_ */ exit(error_count); }
[ "niekma@upb.de" ]
niekma@upb.de
272aa9186eddee6ecbbdc94ee1b94956c7f0cb8f
d17fb97ea13179b8b94c28ef8b56cadd04f32e03
/tensorflow/compiler/mlir/tensorflow/transforms/tpu_sharding_identification_pass.cc
eb47b8c1740496b7b955def43f752e3afff645b0
[ "Apache-2.0" ]
permissive
LogX2/tensorflow
e313c801dbac101b046144d4d518da81762ae994
3e773cfae4238001e19dd23524d79d08205a04fc
refs/heads/master
2020-06-03T11:47:36.102366
2020-04-18T09:04:09
2020-04-18T09:04:09
191,549,362
2
0
Apache-2.0
2020-04-18T09:04:10
2019-06-12T10:26:35
C++
UTF-8
C++
false
false
13,233
cc
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include <string> #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/Block.h" // from @llvm-project #include "mlir/IR/Builders.h" // from @llvm-project #include "mlir/IR/Function.h" // from @llvm-project #include "mlir/IR/Module.h" // from @llvm-project #include "mlir/IR/Operation.h" // from @llvm-project #include "mlir/IR/Value.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Pass/PassRegistry.h" // from @llvm-project #include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/utils/xla_sharding_util.h" #include "tensorflow/compiler/xla/client/sharding_builder.h" namespace mlir { namespace TFTPU { namespace { constexpr char kShardingAttr[] = "xla_hlo.sharding"; struct TPUShardingIdentificationPass : public PassWrapper<TPUShardingIdentificationPass, OperationPass<ModuleOp>> { void runOnOperation() override; }; // Sets `sharding_op` if `op` is XlaShardingOp or if XlaSharding op is // adjacent to `op`. XlaSharding op may be direct user of inputs but it // may also be followed by an Identity op and, in the case where bfloat16 // type is used, Cast op may be added right after the input. As so, // parse the users of the operation to access connected XlaSharding op. // // TODO(hongjunchoi): Consider explicitly checking op patterns to detect // sharded inputs. void GetAdjacentXlaShardingOp(Operation* op, llvm::Optional<TF::XlaShardingOp>* sharding_op) { // TODO(hongjunchoi): Detect the case when sharding configuration is // ambiguous for a single input (i.e. multiple different XlaSharding ops // with different configuration policies are connected). if (sharding_op->hasValue()) return; if (auto sharding = llvm::dyn_cast<TF::XlaShardingOp>(op)) { sharding_op->emplace(sharding); return; } if (llvm::isa<TF::IdentityOp>(op) || llvm::isa<TF::CastOp>(op)) { for (auto user : op->getUsers()) GetAdjacentXlaShardingOp(user, sharding_op); } } // Parses XlaSharding op connected to input args. If Input to // tf_device.LaunchFunc op is of resource type, then XlaSharding op // will be connected to following ReadVariable op. // // TODO(hongjunchoi): Add logic to parse XlaSharding op inside a // Call op or if/while op. llvm::Optional<llvm::StringRef> ParseInputSharding(const Value& arg) { llvm::Optional<TF::XlaShardingOp> parsed_sharding_op; for (auto user : arg.getUsers()) { if (parsed_sharding_op) continue; GetAdjacentXlaShardingOp(user, &parsed_sharding_op); if (parsed_sharding_op) continue; if (llvm::isa<TF::ReadVariableOp>(user)) for (auto read_variable_user : user->getUsers()) GetAdjacentXlaShardingOp(read_variable_user, &parsed_sharding_op); } if (!parsed_sharding_op) return llvm::Optional<llvm::StringRef>(); return tensorflow::ParseShardingAttribute(parsed_sharding_op->getOperation()); } // Returns the provided sharding configuration if operand of return value // of tf_device.LaunchFunc op is directly from XlaSharding op, llvm::Optional<StringRef> ParseReturnValueSharding(FuncOp func, const int output_index, const OpOperand& operand) { if (auto sharding_op = llvm::dyn_cast_or_null<TF::XlaShardingOp>( operand.get().getDefiningOp())) { return tensorflow::ParseShardingAttribute(sharding_op.getOperation()); } return llvm::Optional<StringRef>(); } // Includes information on Func op and argument index of the input value. // This is used to trace Value that is fed into function call ops. struct FunctionAndArgumentInfo { FuncOp func; int argument_index; }; // Adds tf.PartitionedCall op or tf.StatefulPartitionedCall op to `list`. // If `op` is a function call op, then find the func op from provided `module` // and add the func op with `arg_index` to `list`. `list` will later be used to // trace mlir::Value that is fed into (potentially nested) function call ops. void AddFunctionalOpsToList( const int arg_index, ModuleOp module, Operation* op, llvm::SmallVectorImpl<FunctionAndArgumentInfo>* list) { if (auto pcall_op = llvm::dyn_cast<TF::PartitionedCallOp>(op)) { if (!pcall_op.f().isa<FlatSymbolRefAttr>()) return; auto pcall_func = llvm::cast<FuncOp>( module.lookupSymbol(pcall_op.f().getRootReference())); assert(pcall_func); list->emplace_back(FunctionAndArgumentInfo{pcall_func, arg_index}); } else if (auto spcall_op = llvm::dyn_cast<TF::StatefulPartitionedCallOp>(op)) { auto sp_call_func = llvm::cast<FuncOp>(module.lookupSymbol(spcall_op.f())); assert(sp_call_func); list->emplace_back(FunctionAndArgumentInfo{sp_call_func, arg_index}); } } // Walks the MLIR graph from `arg` and return a list of all function // call ops to which the `arg` op is directly connected. // // For example: // argument0 -> PartitionedCallOp -> StatefulPartitionedCallOp -> AddOp // // For above case, PartitionedCall op and StatefulPartitionedCallOp will be // returned. llvm::SmallVector<FunctionAndArgumentInfo, 4> ExtractFunctionsConnectedToArg( BlockArgument arg, ModuleOp module) { llvm::SmallVector<FunctionAndArgumentInfo, 4> functions_connected_to_arg; for (auto& arg_use : arg.getUses()) AddFunctionalOpsToList(arg_use.getOperandNumber(), module, arg_use.getOwner(), &functions_connected_to_arg); llvm::SmallVector<FunctionAndArgumentInfo, 4> functions_to_parse{ functions_connected_to_arg.begin(), functions_connected_to_arg.end()}; while (!functions_to_parse.empty()) { llvm::SmallVector<FunctionAndArgumentInfo, 4> newly_discovered_functions; for (auto function_info : functions_to_parse) { Block& func_entry_block = function_info.func.getBody().getBlocks().front(); auto argument = func_entry_block.getArgument(function_info.argument_index); for (auto& arg_use : argument.getUses()) AddFunctionalOpsToList(arg_use.getOperandNumber(), module, arg_use.getOwner(), &newly_discovered_functions); } functions_connected_to_arg.append(newly_discovered_functions.begin(), newly_discovered_functions.end()); std::swap(functions_to_parse, newly_discovered_functions); } return functions_connected_to_arg; } // Walks the graph from the arguments of the `launch_func_op` and extracts // sharding configurations for all inputs by parsing XlaSharding op connected // to the arguments. If argument to the `launch_func_op` directly feeds into // another function call op, then recursively walk the function definition to // find the connected XlaSharding op. void IdentifyXlaShardingForComputationInputs( StringRef logical_core_0_sharding, tf_device::LaunchFuncOp launch_func_op, FuncOp launch_function, Builder* builder) { // Look up function definition from module. Block& launch_function_block = launch_function.getBody().getBlocks().front(); ModuleOp module = launch_func_op.getParentOfType<ModuleOp>(); llvm::SmallVector<llvm::StringRef, 8> sharding_for_args( launch_function_block.getNumArguments(), logical_core_0_sharding); // Iterate through input arguments to the entry block of tf_device.LaunchFunc. // For input ops, look for following XlaSharding ops. XlaSharding ops can: // 1) Directly follow the input argument if input argument has non-resource // types. // 2) Follow ReadVariableOp if the input type is of resource type. // 3) Follow IdentityOp or CastOp after above cases (1), (2). // // Sharding configurations are added to the tf_device.LaunchFunc as an // attribute and the function as an argument attribute. for (auto& arg : launch_function_block.getArguments()) { auto arg_sharding = ParseInputSharding(arg); const int arg_index_to_tpu_computation = arg.getArgNumber(); if (!arg_sharding.hasValue()) { auto connected_functions_to_arg = ExtractFunctionsConnectedToArg(arg, module); for (auto& function_arg_info : connected_functions_to_arg) { if (arg_sharding.hasValue()) break; const int function_argument_index = function_arg_info.argument_index; auto& parsed_function = function_arg_info.func; Block& parsed_function_block = parsed_function.getBody().getBlocks().front(); arg_sharding = ParseInputSharding( parsed_function_block.getArgument(function_argument_index)); } } if (arg_sharding) { sharding_for_args[arg_index_to_tpu_computation] = arg_sharding.getValue(); launch_function.setArgAttr( arg_index_to_tpu_computation, kShardingAttr, builder->getStringAttr(arg_sharding.getValue())); } else { launch_function.setArgAttr( arg_index_to_tpu_computation, kShardingAttr, builder->getStringAttr(logical_core_0_sharding)); } } launch_func_op.setAttr(tensorflow::kInputShardingAttr, builder->getStrArrayAttr(sharding_for_args)); } // Parses XlaSharding op directly connected from the outputs of the // `launch_func` and extract sharding configurations for outputs. void IdentifyXlaShardingForComputationOutputs( StringRef logical_core_0_sharding, FuncOp func, tf_device::LaunchFuncOp launch_func, Builder* builder) { // By default return values from logical core 0 is used if no sharding // configuration is defined. Block& function_block = func.getBody().getBlocks().front(); Operation* terminator = function_block.getTerminator(); llvm::SmallVector<llvm::StringRef, 8> sharding_for_rets( terminator->getNumOperands(), logical_core_0_sharding); // Iterate through operands of the terminator. If the preceding op is // XlaShardingOp, then the provided sharding configuration is added to the // tf_device.LaunchFunc as an attribute and the function as a result // attribute. for (auto& ret : terminator->getOpOperands()) { const int index = ret.getOperandNumber(); auto ret_sharding = ParseReturnValueSharding(func, index, ret); if (ret_sharding) { sharding_for_rets[index] = ret_sharding.getValue(); func.setResultAttr(index, kShardingAttr, builder->getStringAttr(ret_sharding.getValue())); } else { func.setResultAttr(index, kShardingAttr, builder->getStringAttr(logical_core_0_sharding)); } } launch_func.setAttr(tensorflow::kOutputShardingAttr, builder->getStrArrayAttr(sharding_for_rets)); } // Extracts input/output sharding configuration of `launch_func` by parsing // XlaSharding ops inside the `launch_func`. void IdentifyXlaShardingForTPUComputation(Builder* builder, tf_device::LaunchFuncOp launch_func) { // Look up function definition from module. FuncOp func = launch_func.getParentOfType<ModuleOp>().lookupSymbol<FuncOp>( launch_func.func()); // By default inputs/outputs have maximal sharding and are assigned to // logical core 0 if no sharding is defined. const std::string logical_core_0_sharding = xla::sharding_builder::AssignDevice(0).SerializeAsString(); IdentifyXlaShardingForComputationInputs(logical_core_0_sharding, launch_func, func, builder); IdentifyXlaShardingForComputationOutputs(logical_core_0_sharding, func, launch_func, builder); } void TPUShardingIdentificationPass::runOnOperation() { Builder builder(getOperation().getContext()); getOperation().walk([&](tf_device::LaunchFuncOp launch_func) { IdentifyXlaShardingForTPUComputation(&builder, launch_func); }); } } // anonymous namespace std::unique_ptr<OperationPass<ModuleOp>> CreateTPUShardingIdentificationPass() { return std::make_unique<TPUShardingIdentificationPass>(); } static PassRegistration<TPUShardingIdentificationPass> pass( "tf-tpu-sharding-identification", "Identifies and handles inputs/outputs of TPU computation that is " "sharded across logical cores."); } // namespace TFTPU } // namespace mlir
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
0ef310134cc2eca90b33c071923f5512cb3921df
f27e97eb7682f90823c52fe5b1dbc1eef9700fcd
/cocos-tz/Classes/cocos-tz/json/JsonFileManagement.h
23d5b67e0a31b9c1923c815c07fb2a1bac4fc45a
[]
no_license
darling0825/cocos2dx_tz_lib
16791e2f295e5033426188786be4043bf162f6c4
9eefceb5f7a95c8496de59b38a9023994195eef4
refs/heads/master
2020-05-18T04:42:06.809529
2014-01-20T10:12:23
2014-01-20T10:16:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
931
h
#pragma once #include "cocos2d.h" #include "external/json/document.h" #include "external/json/prettywriter.h" #include "external/json/filestream.h" #include "external/json/stringbuffer.h" #include "../config.h" NS_TZ_BEGIN class JsonFileManagement { typedef std::shared_ptr<rapidjson::Document> PtrDoc; typedef std::unordered_map<std::string,PtrDoc> MapDocument; typedef int Id; typedef std::map<Id,rapidjson::SizeType> MapId; typedef std::unordered_map<std::string,MapId> FileMapId; public: static JsonFileManagement* getInstance(); static void destroyInstance(); void erease(const std::string& fileName); void clear(); const rapidjson::Document& getDocument(const std::string& fileName); const MapId& getMapId(const std::string& fileName); protected: private: JsonFileManagement(){} ~JsonFileManagement(){} static JsonFileManagement* _this; MapDocument _mapDocument; FileMapId _fileMapId; }; NS_TZ_END
[ "491633197@qq.com" ]
491633197@qq.com
175c5961b00da89825b4307b2415ef0de5555a93
6146e33102797407ede06ce2daa56c28fdfa2812
/src/GafferImageModule/TransformBinding.cpp
9ea701ca2599877fe27f92d73a1c2eba7e906e27
[ "BSD-3-Clause" ]
permissive
GafferHQ/gaffer
e1eb78ba8682bfbb7b17586d6e7b47988c3b7d64
59cab96598c59b90bee6d3fc1806492a5c03b4f1
refs/heads/main
2023-09-01T17:36:45.227956
2023-08-30T09:10:56
2023-08-30T09:10:56
9,043,124
707
144
BSD-3-Clause
2023-09-14T09:05:37
2013-03-27T00:04:53
Python
UTF-8
C++
false
false
3,241
cpp
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software 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 OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "TransformBinding.h" #include "GafferImage/Crop.h" #include "GafferImage/ImageTransform.h" #include "GafferImage/Mirror.h" #include "GafferImage/Offset.h" #include "GafferImage/Resample.h" #include "GafferImage/Resize.h" #include "GafferBindings/DependencyNodeBinding.h" using namespace boost::python; using namespace GafferImage; using namespace GafferBindings; void GafferImageModule::bindTransforms() { GafferBindings::DependencyNodeClass<ImageTransform>(); GafferBindings::DependencyNodeClass<Mirror>(); GafferBindings::DependencyNodeClass<Offset>(); { scope s = GafferBindings::DependencyNodeClass<Resize>(); enum_<Resize::FitMode>( "FitMode" ) .value( "Horizontal", Resize::Horizontal ) .value( "Vertical", Resize::Vertical ) .value( "Fit", Resize::Fit ) .value( "Fill", Resize::Fill ) .value( "Distort", Resize::Distort ) ; } { scope s = GafferBindings::DependencyNodeClass<Resample>(); enum_<Resample::Debug>( "Debug") .value( "Off", Resample::Off ) .value( "HorizontalPass", Resample::HorizontalPass ) .value( "SinglePass", Resample::SinglePass ) ; } { scope s = GafferBindings::DependencyNodeClass<Crop>(); enum_<Crop::AreaSource>( "AreaSource" ) .value( "Area", Crop::Area ) .value( "Format", Crop::Format ) .value( "DataWindow", Crop::DataWindow ) .value( "DisplayWindow", Crop::DisplayWindow ) ; } }
[ "thehaddonyoof@gmail.com" ]
thehaddonyoof@gmail.com
b852dc5383bc455f0f49ee88ccd59021c26fa04b
b3bff44ad5c3d6cbebde8500d09dec4642de56b5
/third-party/proxygen/src/proxygen/lib/http/sink/HTTPSink.h
cd462a249ccea7fa5d74ff7c389136cd3a14bcdc
[ "PHP-3.01", "Zend-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
sbuzonas/hhvm
0180fe9e416f4b570e19c75e3d991a69354e5069
3f02bce658ef94002e30279264649ff44f2c936a
refs/heads/master
2023-09-01T11:54:00.370084
2022-10-22T01:23:33
2022-10-22T01:23:33
16,925,766
0
0
NOASSERTION
2023-04-03T22:57:29
2014-02-17T20:34:17
C++
UTF-8
C++
false
false
3,055
h
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <folly/CppAttributes.h> #include <proxygen/lib/http/HTTPMessage.h> #include <proxygen/lib/http/session/HTTPTransaction.h> namespace proxygen { /** * A HTTPSink wraps a http transaction (ClientTxnSink), or an AsyncRequest * (AsyncRequestSink). * * Its purpose is to receive http txn events from HTTPRevProxyHandler. * This abstraction allows HTTPRevProxyHandler to continue the normal flow * in a similar way as it had http txn. * * Life-cycle * ========== * A HTTPSink is owned by a unique_ptr in HTTPRevProxyHandler. It's created * when a http txn (/AyncRequest) is set, and destructed when the http txn * /AsyncRequest finishes. */ class HTTPSink { public: virtual ~HTTPSink() = default; [[nodiscard]] virtual HTTPTransaction* FOLLY_NULLABLE getHTTPTxn() const = 0; virtual void detachHandler() = 0; // Sending data virtual void sendHeaders(const HTTPMessage& headers) = 0; virtual bool sendHeadersWithDelegate( const HTTPMessage& headers, std::unique_ptr<DSRRequestSender> sender) = 0; virtual void sendHeadersWithEOM(const HTTPMessage& headers) = 0; virtual void sendHeadersWithOptionalEOM(const HTTPMessage& headers, bool eom) = 0; virtual void sendBody(std::unique_ptr<folly::IOBuf> body) = 0; virtual void sendChunkHeader(size_t length) = 0; virtual void sendChunkTerminator() = 0; virtual void sendTrailers(const HTTPHeaders& trailers) = 0; virtual void sendEOM() = 0; virtual void sendAbort() = 0; virtual void sendAbortIfIncomplete() = 0; virtual HTTPTransaction* newPushedTransaction( HTTPPushTransactionHandler* handler, ProxygenError* error = nullptr) = 0; virtual HTTPTransaction* newExTransaction(HTTPTransaction::Handler* handler, bool unidirectional) = 0; // Check state [[nodiscard]] virtual bool canSendHeaders() const = 0; [[nodiscard]] virtual bool extraResponseExpected() const = 0; virtual const wangle::TransportInfo& getSetupTransportInfo() const noexcept = 0; virtual void getCurrentTransportInfo(wangle::TransportInfo* tinfo) const = 0; // Flow control virtual void pauseIngress() = 0; virtual void pauseEgress() = 0; virtual void resumeIngress() = 0; virtual void resumeEgress() = 0; [[nodiscard]] virtual bool isIngressPaused() const = 0; [[nodiscard]] virtual bool isEgressPaused() const = 0; virtual void setEgressRateLimit(uint64_t bitsPerSecond) = 0; // Client timeout virtual void timeoutExpired() = 0; virtual void setIdleTimeout(std::chrono::milliseconds timeout) = 0; // Capabilities virtual bool safeToUpgrade(HTTPMessage* req) const = 0; [[nodiscard]] virtual bool supportsPush() const = 0; // Logging virtual void describe(std::ostream& os) = 0; }; } // namespace proxygen
[ "atry@fb.com" ]
atry@fb.com
f1d00669ed5ecedfb9c75f15c008abda077c8f50
efd2d45dfb564bba736c8722dcf8dbf35eed212d
/tags/CRYPTOPP_5_2/c5/whrlpool.h
fbec1b6476c48d675f1565a581013d12d40279b8
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-cryptopp" ]
permissive
zooko/cryptopp
c8ff712dfbff397b4865bbd7106ec3f51196566a
c00dffd441be1392152794d9e1d6b9abb91c3da9
refs/heads/master
2021-01-01T05:40:44.382744
2012-05-23T17:56:48
2012-05-23T17:56:48
5,386,236
1
1
null
null
null
null
UTF-8
C++
false
false
625
h
#ifndef CRYPTOPP_WHIRLPOOL_H #define CRYPTOPP_WHIRLPOOL_H #include "config.h" #ifdef WORD64_AVAILABLE #include "iterhash.h" NAMESPACE_BEGIN(CryptoPP) //! <a href="http://www.eskimo.com/~weidai/scan-mirror/md.html#Whirlpool">Whirlpool</a> /*! 512 Bit Hash */ class Whirlpool : public IteratedHashWithStaticTransform<word64, BigEndian, 64, 64, Whirlpool> { public: static void InitState(HashWordType *state); static void Transform(word64 *digest, const word64 *data); void TruncatedFinal(byte *hash, unsigned int size); static const char * StaticAlgorithmName() {return "Whirlpool";} }; NAMESPACE_END #endif #endif
[ "(no author)@57ff6487-cd31-0410-9ec3-f628ee90f5f0" ]
(no author)@57ff6487-cd31-0410-9ec3-f628ee90f5f0
1ec352e6792785b80282c9896ed5d03547eeaf10
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
/third_party/WebKit/Source/platform/graphics/ImageFrameGeneratorTest.cpp
9fd43e12a5a2b11f45938a6d3cb8aed0922e52d6
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
massnetwork/mass-browser
7de0dfc541cbac00ffa7308541394bac1e945b76
67526da9358734698c067b7775be491423884339
refs/heads/master
2022-12-07T09:01:31.027715
2017-01-19T14:29:18
2017-01-19T14:29:18
73,799,690
4
4
BSD-3-Clause
2022-11-26T11:53:23
2016-11-15T09:49:29
null
UTF-8
C++
false
false
9,205
cpp
/* * Copyright (C) 2012 Google 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: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS 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 "platform/graphics/ImageFrameGenerator.h" #include "platform/CrossThreadFunctional.h" #include "platform/SharedBuffer.h" #include "platform/WebTaskRunner.h" #include "platform/graphics/ImageDecodingStore.h" #include "platform/graphics/test/MockImageDecoder.h" #include "platform/image-decoders/SegmentReader.h" #include "public/platform/Platform.h" #include "public/platform/WebThread.h" #include "public/platform/WebTraceLocation.h" #include "testing/gtest/include/gtest/gtest.h" #include "wtf/PtrUtil.h" #include <memory> namespace blink { namespace { // Helper methods to generate standard sizes. SkISize fullSize() { return SkISize::Make(100, 100); } SkImageInfo imageInfo() { return SkImageInfo::Make(100, 100, kBGRA_8888_SkColorType, kOpaque_SkAlphaType); } } // namespace class ImageFrameGeneratorTest : public ::testing::Test, public MockImageDecoderClient { public: void SetUp() override { ImageDecodingStore::instance().setCacheLimitInBytes(1024 * 1024); m_generator = ImageFrameGenerator::create(fullSize(), nullptr, false); m_data = SharedBuffer::create(); m_segmentReader = SegmentReader::createFromSharedBuffer(m_data); useMockImageDecoderFactory(); m_decodersDestroyed = 0; m_decodeRequestCount = 0; m_status = ImageFrame::FrameEmpty; m_frameCount = 1; m_requestedClearExceptFrame = kNotFound; } void TearDown() override { ImageDecodingStore::instance().clear(); } void decoderBeingDestroyed() override { ++m_decodersDestroyed; } void decodeRequested() override { ++m_decodeRequestCount; } ImageFrame::Status status() override { ImageFrame::Status currentStatus = m_status; m_status = m_nextFrameStatus; return currentStatus; } void clearCacheExceptFrameRequested(size_t clearExceptFrame) override { m_requestedClearExceptFrame = clearExceptFrame; }; size_t frameCount() override { return m_frameCount; } int repetitionCount() const override { return m_frameCount == 1 ? cAnimationNone : cAnimationLoopOnce; } float frameDuration() const override { return 0; } protected: void useMockImageDecoderFactory() { m_generator->setImageDecoderFactory( MockImageDecoderFactory::create(this, fullSize())); } void addNewData() { m_data->append("g", 1u); } void setFrameStatus(ImageFrame::Status status) { m_status = m_nextFrameStatus = status; } void setNextFrameStatus(ImageFrame::Status status) { m_nextFrameStatus = status; } void setFrameCount(size_t count) { m_frameCount = count; if (count > 1) { m_generator.clear(); m_generator = ImageFrameGenerator::create(fullSize(), nullptr, true); useMockImageDecoderFactory(); } } RefPtr<SharedBuffer> m_data; RefPtr<SegmentReader> m_segmentReader; RefPtr<ImageFrameGenerator> m_generator; int m_decodersDestroyed; int m_decodeRequestCount; ImageFrame::Status m_status; ImageFrame::Status m_nextFrameStatus; size_t m_frameCount; size_t m_requestedClearExceptFrame; }; TEST_F(ImageFrameGeneratorTest, incompleteDecode) { setFrameStatus(ImageFrame::FramePartial); char buffer[100 * 100 * 4]; m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(1, m_decodeRequestCount); addNewData(); m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(2, m_decodeRequestCount); EXPECT_EQ(0, m_decodersDestroyed); } TEST_F(ImageFrameGeneratorTest, incompleteDecodeBecomesComplete) { setFrameStatus(ImageFrame::FramePartial); char buffer[100 * 100 * 4]; m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(1, m_decodeRequestCount); EXPECT_EQ(0, m_decodersDestroyed); setFrameStatus(ImageFrame::FrameComplete); addNewData(); m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(2, m_decodeRequestCount); EXPECT_EQ(1, m_decodersDestroyed); // Decoder created again. m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(3, m_decodeRequestCount); } static void decodeThreadMain(ImageFrameGenerator* generator, SegmentReader* segmentReader) { char buffer[100 * 100 * 4]; generator->decodeAndScale(segmentReader, false, 0, imageInfo(), buffer, 100 * 4); } TEST_F(ImageFrameGeneratorTest, incompleteDecodeBecomesCompleteMultiThreaded) { setFrameStatus(ImageFrame::FramePartial); char buffer[100 * 100 * 4]; m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(1, m_decodeRequestCount); EXPECT_EQ(0, m_decodersDestroyed); // LocalFrame can now be decoded completely. setFrameStatus(ImageFrame::FrameComplete); addNewData(); std::unique_ptr<WebThread> thread = wrapUnique(Platform::current()->createThread("DecodeThread")); thread->getWebTaskRunner()->postTask( BLINK_FROM_HERE, crossThreadBind(&decodeThreadMain, m_generator, m_segmentReader)); thread.reset(); EXPECT_EQ(2, m_decodeRequestCount); EXPECT_EQ(1, m_decodersDestroyed); // Decoder created again. m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(3, m_decodeRequestCount); addNewData(); // Delete generator. m_generator = nullptr; } TEST_F(ImageFrameGeneratorTest, frameHasAlpha) { setFrameStatus(ImageFrame::FramePartial); char buffer[100 * 100 * 4]; m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_TRUE(m_generator->hasAlpha(0)); EXPECT_EQ(1, m_decodeRequestCount); ImageDecoder* tempDecoder = 0; EXPECT_TRUE(ImageDecodingStore::instance().lockDecoder( m_generator.get(), fullSize(), &tempDecoder)); ASSERT_TRUE(tempDecoder); tempDecoder->frameBufferAtIndex(0)->setHasAlpha(false); ImageDecodingStore::instance().unlockDecoder(m_generator.get(), tempDecoder); EXPECT_EQ(2, m_decodeRequestCount); setFrameStatus(ImageFrame::FrameComplete); m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(3, m_decodeRequestCount); EXPECT_FALSE(m_generator->hasAlpha(0)); } TEST_F(ImageFrameGeneratorTest, clearMultiFrameDecoder) { setFrameCount(3); setFrameStatus(ImageFrame::FrameComplete); char buffer[100 * 100 * 4]; m_generator->decodeAndScale(m_segmentReader.get(), true, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(1, m_decodeRequestCount); EXPECT_EQ(0, m_decodersDestroyed); EXPECT_EQ(0U, m_requestedClearExceptFrame); setFrameStatus(ImageFrame::FrameComplete); m_generator->decodeAndScale(m_segmentReader.get(), true, 1, imageInfo(), buffer, 100 * 4); EXPECT_EQ(2, m_decodeRequestCount); EXPECT_EQ(0, m_decodersDestroyed); EXPECT_EQ(1U, m_requestedClearExceptFrame); setFrameStatus(ImageFrame::FrameComplete); // Decoding the last frame of a multi-frame images should trigger clearing // all the frame data, but not destroying the decoder. See comments in // ImageFrameGenerator::tryToResumeDecode(). m_generator->decodeAndScale(m_segmentReader.get(), true, 2, imageInfo(), buffer, 100 * 4); EXPECT_EQ(3, m_decodeRequestCount); EXPECT_EQ(0, m_decodersDestroyed); EXPECT_EQ(kNotFound, m_requestedClearExceptFrame); } } // namespace blink
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
fd8e362efe1e573efb8f31cc83a3e8e28a3db563
e1184f0954f6de41a57a9405fe4b95cf9035b2fc
/5TabuadaInvertidaII.cpp.cpp
defd8bed8c374eb164e8d512c195072ae3199721
[]
no_license
adilsonLuz/Linguagem_C
c82c74b6e8dd00d0de16247cbe5471622f11e01e
2e57e20f47c6b3264f0338352209c7d3a32f2614
refs/heads/main
2023-06-23T18:18:04.803170
2021-07-21T20:51:58
2021-07-21T20:51:58
388,242,138
0
0
null
null
null
null
ISO-8859-1
C++
false
false
455
cpp
/* Name: Tabuada invertida II Author: Chacal Date: 01/11/19 10:28 Description: programa que faz a imoressão da tabuada invertida II */ #include<stdio.h> #include<conio.h> #include<locale.h> main() { int num, i; num = 0; i = 10; setlocale(LC_ALL,"Portuguese"); printf("Você quer tabuada de qual número? \n"); scanf("%d", &num); while (i>0) { printf("%d X %5.2d = %.2d\n", num, i, i*num); (i--); } printf("CONCLUÍDO... Parabéns"); }
[ "adilson.luz@fatec.sp.gov.br" ]
adilson.luz@fatec.sp.gov.br
8d91232276890abee1a8ed89c62350abb8ff6d5a
e96b33c182701f4841acf589dcee49ebb4e8dada
/2-HTDD-5-FnForInterval.cpp
900aaac66e8636315c01637bbc93635bb0062273
[]
no_license
pn94958/Systematic-Program-Design-CPP
074e950244e5ff400f69641fb665dbbc3c95f2c7
3c7a1842060c445ea5e05bb0b0c7e041364ab42d
refs/heads/main
2023-03-24T01:55:37.634810
2021-03-16T22:57:24
2021-03-16T22:57:24
342,291,251
0
0
null
null
null
null
UTF-8
C++
false
false
1,099
cpp
#include<iostream> using namespace std; bool CheckExpect(bool a, bool b) { bool check; if(a == b) { cout << "Test passed successfully.\n"; check = true; } else { cout << "The result is expected to be " << b << " but is " << a << ".\n"; check = true; } return check; } // ParkField is Integer[1, 16] // interp. number of parking field in a row, 1 and 16 are borders int PF1 = 1; // border int PF2 = 9; // middle int PF3 = 16; // border /* void fnForParkField(int pf) { ... pf; } */ // Template rules used: // - atomic non-distinct: Integer[1, 16] // ParkField -> Boolean // Returns true if consumed ParkField is border, that is 1 or 16 // bool BorderQ(int pf) { return false; } //stub //<take template from ParkField> bool BorderQ(int pf) { bool borderpf; if(pf == 1 || pf==16) { borderpf = true; } else { borderpf = false; } return borderpf; } int main() { CheckExpect(BorderQ(PF1), true); CheckExpect(BorderQ(PF2), false); CheckExpect(BorderQ(PF3), true); return 0; }
[ "noreply@github.com" ]
noreply@github.com
99e165349e253b622aa3df732d6a7259fc136371
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/tar/new_hunk_218.cpp
ced27edcd1d1ae6ad73e69b1d223ef52857c72f9
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
366
cpp
|| current_header->header.typeflag == BLKTYPE) && current_stat_info.stat.st_rdev != stat_data.st_rdev) { report_difference (&current_stat_info, _("Device number differs")); break; } if ((current_stat_info.stat.st_mode & MODE_ALL) != (stat_data.st_mode & MODE_ALL)) { report_difference (&current_stat_info, _("Mode differs")); break; }
[ "993273596@qq.com" ]
993273596@qq.com
4f4221f345cdca3afa7a4b6fd51347ad68621133
8af23530c7a2d76cba058d8d7f29b5a43dd43511
/exam5.cpp
60ea2437f03eb1030aee88c804b4cce123b70ccd
[]
no_license
ABCorabc/C-Programming
310caf4960e7ce07749e9890be16bab7737248cc
ede6bdf520eb97d8af4c451861bcfb32d826ece7
refs/heads/master
2021-07-05T20:19:09.219111
2017-09-28T23:54:07
2017-09-28T23:54:07
105,117,571
0
0
null
null
null
null
UTF-8
C++
false
false
345
cpp
#include <stdio.h> typedef struct{ char name[10]; int score; }student; int main() { student sary[5]= { "",0 }; int total = 0; for (int i = 0; i < 5; i++) { scanf("%s %d", &sary[i].name, &sary[i].score); total += sary[i].score; } for (int i = 0; i < 5; i++) { if (sary[i].score <= total / 5.0) printf("%s\n", sary[i].name); } }
[ "kangkang1104@naver.com" ]
kangkang1104@naver.com
0572a20cd0c9d6ff01f0173b67b3ccb9b6f35dea
77a091c62781f6aefeebdfd6efd4bab9caa51465
/Done/aula/E.cpp
951b3ec4e02bfaaa7bc5de8a637bb5d42a97c120
[]
no_license
breno-helf/Maratona
55ab11264f115592e1bcfd6056779a3cf27e44dc
c6970bc554621746cdb9ce53815b8276a4571bb3
refs/heads/master
2021-01-23T21:31:05.267974
2020-05-05T23:25:23
2020-05-05T23:25:23
57,412,343
1
2
null
2017-01-25T14:58:46
2016-04-29T20:54:08
C++
UTF-8
C++
false
false
984
cpp
//This code was made by Breno Moura, Codeforces Handle: Brelf //From University of São Paulo - USP //If you are trying to hack me I wish you can get it, Good Luck :D #include<bits/stdc++.h> using namespace std; #define debug(args...) fprintf(stderr,args) #define pb push_back #define mp make_pair typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; const int MAXN=11234; const int INF=0x3f3f3f3f; const ll MOD=1000000007; int crivo[MAXN], resp; map<int,int> d; int main () { for (int i = 2; i*i <= 10000; i++) if (crivo[i] == 0) for (int j = i*i; j <= 10000; j += i) crivo[j] = i; for (int i = 0; i < 10; i++) { int a; scanf("%d", &a); if (a == 1) continue; while (crivo[a] != 0) { // debug("Travei? %d\n", a); d[crivo[a]]++; a /= crivo[a]; } d[a]++; } resp = 1; for (auto p : d){ resp *= (p.second + 1); // resp %= 1000000; } resp %= 10; printf("%d\n", resp); return 0; }
[ "breno.moura@hotmail.com" ]
breno.moura@hotmail.com
727ac70921c4cbc5a768c4fef3378432bfd5386c
2e38b79c9774800496072e533caa8e839a620d8b
/first-cpp/Lab 01/lab1.cpp
88e9b4822c00d7efefbb64245b749c7dd0f7bec4
[]
no_license
y0dev/cpp-collection
04bac2c3688d5db5a7a68aac543c2d7ae731ef47
83696b2b32d13de377bc19c527e384130dc865b4
refs/heads/master
2021-08-20T08:51:09.165731
2017-11-28T17:00:23
2017-11-28T17:00:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,303
cpp
// Devontae Reid // CIS 180 Lab1 #include <iostream> #include <iomanip> using namespace std; int main() { // Set up numbers of calories per food item double hamburger = 400; double frenchFries = 275; double softDrink = 150; // Ask question for user cout << "How many been hamburger, french fries, and soft drink you consume? "; // Number of Items user inputed double numOfHamburgers; double numOfFrenchFries; double numOfSoftDrinks; // User Input cin >> numOfHamburgers >> numOfFrenchFries >> numOfSoftDrinks; // Total calories that the user has ingested calculator double totalCalories = (hamburger * numOfHamburgers) + (frenchFries * numOfFrenchFries) + (softDrink * numOfSoftDrinks); // Show User number of total calories cout << endl << "You ingested " << totalCalories << " calories."<< endl << endl; // Number of calories burned perMile const double caloriesPerMile = 375; // Number of miles needed to burn the calories off double neededMiles = totalCalories/caloriesPerMile; // Show user how many calories that was burned cout << "You will have to run " << setprecision(2) << neededMiles << " miles to expand that much energy."<< endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
a844e1727931848866740fd9a99933908ba6a336
be084131635850062abd17cdb037e1161725f56c
/QtGUI/vtkQtWordleView.cxx
64fe669a09c5cfc11f8e97022a62de84ec321a3a
[]
no_license
emonson/vtkVTG
177a80820e27aad7fc9fb1d7b14cee4155166d00
767f35ae18142133f7ffd1a9ea6c22dfd59acac7
refs/heads/master
2016-09-10T00:53:25.613217
2012-06-05T14:45:12
2012-06-05T14:45:12
699,786
0
0
null
null
null
null
UTF-8
C++
false
false
41,141
cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkQtWordleView.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkQtWordleView.h" #include <QCoreApplication> #include <QFont> #include <QFontDatabase> #include <QGraphicsView> #include <QImage> #include <QList> #include <QPolygonF> #include <QPrinter> #include <QRectF> #include <QString> #include <QStringList> #include <QtSvg/QSvgGenerator> #include <QTime> #include <QTransform> #include "vtkAbstractArray.h" #include "vtkAlgorithm.h" #include "vtkAlgorithmOutput.h" #include "vtkApplyColors.h" #include "vtkDataObjectToTable.h" #include "vtkDataRepresentation.h" #include "vtkDataSetAttributes.h" #include "vtkDoubleArray.h" #include "vtkImageData.h" #include "vtkImageGaussianSmooth.h" #include "vtkInformation.h" #include "vtkObjectFactory.h" #include "vtkQImageToImageSource.h" #include "vtkSmartPointer.h" #include "vtkStringArray.h" #include "vtkTable.h" #include "vtkUnsignedCharArray.h" #include "vtkViewTheme.h" #include <string> #include <time.h> //------------------------ // Need to translate rect_item into proper QRectF before passing to this routine void vtkQtWordleQuadCIF::AddRectItemMin(QGraphicsRectItem *rect_item, int index) { QRectF rA = rect_item->rect(); rA.translate(rect_item->pos()); double ax1 = rA.x(); double ax2 = ax1 + rA.width(); double ay1 = rA.y(); double ay2 = ay1 + rA.height(); // Intersects xline if ((xmiddle >= ax1 && xmiddle <= ax2) || (ymiddle >= ay1 && ymiddle <= ay2)) { ItemsList.append(vtkQtWordleIndexedRectItem(index, rect_item)); } else { // TODO: Eventually test here to see whether this node is too small // to subdivide, and if so, I guess add items directly to xline->ItemsList? // UL if (ay1 > ymiddle && ax2 < xmiddle) { if (!UL) { UL = new vtkQtWordleQuadCIF(QRectF(frame.x(), ymiddle, frame.width()/2.0, frame.height()/2.0)); } UL->AddRectItemMin(rect_item, index); } // LL if (ay2 < ymiddle && ax2 < xmiddle) { if (!LL) { LL = new vtkQtWordleQuadCIF(QRectF(frame.x(), frame.y(), frame.width()/2.0, frame.height()/2.0)); } LL->AddRectItemMin(rect_item, index); } // UR if (ay1 > ymiddle && ax1 > xmiddle) { if (!UR) { UR = new vtkQtWordleQuadCIF(QRectF(xmiddle, ymiddle, frame.width()/2.0, frame.height()/2.0)); } UR->AddRectItemMin(rect_item, index); } // LR if (ay2 < ymiddle && ax1 > xmiddle) { if (!LR) { LR = new vtkQtWordleQuadCIF(QRectF(xmiddle, frame.y(), frame.width()/2.0, frame.height()/2.0)); } LR->AddRectItemMin(rect_item, index); } } } //============================================================================ //---------------------------------------------------------------------------- vtkStandardNewMacro(vtkQtWordleView); //---------------------------------------------------------------------------- vtkQtWordleView::vtkQtWordleView() { // Scene which will actually be viewed with text this->scene = new QGraphicsScene(); this->scene->setSceneRect(-300, -400, 900, 800); this->scene->setItemIndexMethod(QGraphicsScene::NoIndex); this->View = new QGraphicsView(); this->View->setScene(this->scene); this->View->setRenderHint(QPainter::Antialiasing); this->View->setCacheMode(QGraphicsView::CacheBackground); this->View->setAlignment(Qt::AlignCenter); // this->View->setViewportUpdateMode(QGraphicsView::NoViewportUpdate); this->View->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); this->View->setDragMode(QGraphicsView::ScrollHandDrag); this->ApplyColors = vtkSmartPointer<vtkApplyColors>::New(); double defCol[3] = {0.827,0.827,0.827}; this->ApplyColors->SetDefaultPointColor(defCol); this->ApplyColors->SetUseCurrentAnnotationColor(true); this->ColorArrayNameInternal = 0; this->TermsArrayNameInternal = 0; this->SizeArrayNameInternal = 0; this->DataObjectToTable = vtkSmartPointer<vtkDataObjectToTable>::New(); this->ApplyColors->SetInputConnection(0, this->DataObjectToTable->GetOutputPort(0)); this->DataObjectToTable->SetFieldType(vtkDataObjectToTable::VERTEX_DATA); OutputImageDataDimensions[0] = 256; OutputImageDataDimensions[1] = 256; this->QImageToImage = vtkSmartPointer<vtkQImageToImageSource>::New(); this->ImageGaussSmooth = vtkSmartPointer<vtkImageGaussianSmooth>::New(); this->ImageGaussSmooth->SetInputConnection(this->QImageToImage->GetOutputPort(0)); this->ImageGaussSmooth->SetDimensionality(2); this->ImageGaussSmooth->SetStandardDeviations(1.0, 1.0, 1.0); this->bigFontSize = 100; this->MaxNumberOfWords = 150; this->orientation = vtkQtWordleView::HORIZONTAL; this->LayoutPathShape = vtkQtWordleView::CIRCULAR_PATH; this->WordSizePower = 1.0; this->xbuffer = 1.5; this->ybuffer = 1.5; this->randSpread = 0.1; // Archimedean spiral this->thetaMult = 0.75; this->thetaPow = 0.66667; this->rMult = 2.0; this->rPow = 0.5; // Square spiral this->dMult = 2.5; this->dPow = 0.80; this->boundingRect = new QRectF(0.0, 0.0, 0.0, 0.0); this->font = new QFont("Adobe Caslon Pro", 12); this->font->setStyle(QFont::StyleNormal); this->font->setWeight(QFont::Bold); this->FontDatabase = new QFontDatabase(); // if (this->FontDatabase->supportsThreadedFontRendering()) // printf("Threaded font rendering supported!!!\n"); // else // printf("Font rendering can't be done outside GUI thread! :(\n"); this->FieldType = vtkQtWordleView::ROW_DATA; this->LastInputMTime = 0; this->LastColorMTime = 0; this->LastMTime = 0; srand( time(NULL) ); } //---------------------------------------------------------------------------- vtkQtWordleView::~vtkQtWordleView() { if(this->View) { delete this->View; } } //---------------------------------------------------------------------------- QWidget* vtkQtWordleView::GetWidget() { return this->View; } //---------------------------------------------------------------------------- void vtkQtWordleView::SetRandomSeed(unsigned int seed) { srand(seed); } //---------------------------------------------------------------------------- void vtkQtWordleView::SetFieldType(int type) { this->DataObjectToTable->SetFieldType(type); if(this->FieldType != type) { this->FieldType = type; this->Modified(); } } //---------------------------------------------------------------------------- void vtkQtWordleView::AddRepresentationInternal(vtkDataRepresentation* rep) { vtkAlgorithmOutput *annConn, *conn; conn = rep->GetInputConnection(); annConn = rep->GetInternalAnnotationOutputPort(); this->DataObjectToTable->SetInputConnection(0, conn); if(annConn) { this->ApplyColors->SetInputConnection(1, annConn); } } void vtkQtWordleView::RemoveRepresentationInternal(vtkDataRepresentation* rep) { vtkAlgorithmOutput *annConn, *conn; conn = rep->GetInputConnection(); annConn = rep->GetInternalAnnotationOutputPort(); this->DataObjectToTable->RemoveInputConnection(0, conn); this->ApplyColors->RemoveInputConnection(1, annConn); } //---------------------------------------------------------------------------- void vtkQtWordleView::SetFontFamily(const char* name) { if (strcmp(this->font->family().toStdString().c_str(), name) != 0) { QStringList families = this->FontDatabase->families(); if (families.contains(QString(name))) { this->font->setFamily(QString(name)); this->GetRepresentation()->GetInputConnection()->GetProducer()->GetOutputDataObject(0)->Modified(); } else { vtkDebugMacro(<< "Font family does not match a known entry in Qt database."); } } } //---------------------------------------------------------------------------- const char* vtkQtWordleView::GetFontFamily() { return this->font->family().toStdString().c_str(); } //---------------------------------------------------------------------------- void vtkQtWordleView::GetAllFontFamilies(vtkStringArray* famlies) { famlies->SetName("FontFamilies"); famlies->SetNumberOfComponents(1); famlies->SetNumberOfValues(this->FontDatabase->families().size()); vtkIdType ii = 0; foreach (QString family, this->FontDatabase->families()) { famlies->SetValue(ii, family.toStdString()); ii++; // foreach (QString style, this->FontDatabase->styles(family)) { // cout << "\t" << style.toStdString() << endl; // } // cout << endl; } } //---------------------------------------------------------------------------- bool vtkQtWordleView::FontFamilyExists(const char* name) { QStringList families = this->FontDatabase->families(); if (families.contains(QString(name))) { return true; } else { return false; } } //---------------------------------------------------------------------------- void vtkQtWordleView::SetFontStyle(int style) { if (this->font->style() != style) { // Convert from int to QFont::Style QFont::Style val; switch (style) { case 0: val = QFont::StyleNormal; break; case 1: val = QFont::StyleItalic; break; case 2: val = QFont::StyleOblique; break; default: vtkDebugMacro(<< "Font style not in correct range."); } if (style <= 2 && style >= 0) { this->font->setStyle(val); this->GetRepresentation()->GetInputConnection()->GetProducer()->GetOutputDataObject(0)->Modified(); } } } //---------------------------------------------------------------------------- int vtkQtWordleView::GetFontStyle() { return this->font->style(); } //---------------------------------------------------------------------------- void vtkQtWordleView::SetFontWeight(int weight) { if (this->font->weight() != weight) { if (weight <= 99 && weight >= 0) { this->font->setWeight(weight); this->GetRepresentation()->GetInputConnection()->GetProducer()->GetOutputDataObject(0)->Modified(); } else { vtkDebugMacro(<< "Font weight not in correct range."); } } } //---------------------------------------------------------------------------- int vtkQtWordleView::GetFontWeight() { return this->font->weight(); } //---------------------------------------------------------------------------- void vtkQtWordleView::SetOrientation(int orientation) { if (this->orientation != orientation) { if (orientation <= 4 && orientation >= 0) { this->orientation = orientation; this->GetRepresentation()->GetInputConnection()->GetProducer()->GetOutputDataObject(0)->Modified(); } else { vtkDebugMacro(<< "Orientation not in correct range."); } } } //---------------------------------------------------------------------------- int vtkQtWordleView::GetOrientation() { return this->orientation; } //---------------------------------------------------------------------------- void vtkQtWordleView::SetColorByArray(bool b) { this->ApplyColors->SetUsePointLookupTable(b); } //---------------------------------------------------------------------------- bool vtkQtWordleView::GetColorByArray() { return this->ApplyColors->GetUsePointLookupTable(); } //---------------------------------------------------------------------------- void vtkQtWordleView::SetColorArrayName(const char* name) { this->SetColorArrayNameInternal(name); this->ApplyColors->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_ROWS, name); } //---------------------------------------------------------------------------- const char* vtkQtWordleView::GetColorArrayName() { return this->GetColorArrayNameInternal(); } //---------------------------------------------------------------------------- void vtkQtWordleView::ApplyViewTheme(vtkViewTheme* theme) { this->Superclass::ApplyViewTheme(theme); this->ApplyColors->SetPointLookupTable(theme->GetPointLookupTable()); this->ApplyColors->SetDefaultPointColor(theme->GetPointColor()); this->ApplyColors->SetDefaultPointOpacity(theme->GetPointOpacity()); this->ApplyColors->SetDefaultCellColor(theme->GetCellColor()); this->ApplyColors->SetDefaultCellOpacity(theme->GetCellOpacity()); this->ApplyColors->SetSelectedPointColor(theme->GetSelectedPointColor()); this->ApplyColors->SetSelectedPointOpacity(theme->GetSelectedPointOpacity()); this->ApplyColors->SetSelectedCellColor(theme->GetSelectedCellColor()); this->ApplyColors->SetSelectedCellOpacity(theme->GetSelectedCellOpacity()); double bg[3]; theme->GetBackgroundColor(bg); QColor bgColor; bgColor.setRgbF(bg[0],bg[1],bg[2]); this->scene->setBackgroundBrush(QBrush(bgColor)); } //---------------------------------------------------------------------------- void vtkQtWordleView::SetTermsArrayName(const char* name) { if (QString(name) != QString(this->TermsArrayNameInternal)) { this->SetTermsArrayNameInternal(name); this->GetRepresentation()->GetInputConnection()->GetProducer()->GetOutputDataObject(0)->Modified(); } } //---------------------------------------------------------------------------- const char* vtkQtWordleView::GetTermsArrayName() { return this->GetTermsArrayNameInternal(); } //---------------------------------------------------------------------------- void vtkQtWordleView::SetSizeArrayName(const char* name) { if (QString(name) != QString(this->SizeArrayNameInternal)) { this->SetSizeArrayNameInternal(name); this->GetRepresentation()->GetInputConnection()->GetProducer()->GetOutputDataObject(0)->Modified(); } } //---------------------------------------------------------------------------- const char* vtkQtWordleView::GetSizeArrayName() { return this->GetSizeArrayNameInternal(); } //---------------------------------------------------------------------------- void vtkQtWordleView::ClearGraphicsView() { QList<QGraphicsItem*> sceneItems = this->scene->items(); for (int ii=0; ii < sceneItems.length(); ++ii) { this->scene->removeItem(sceneItems[ii]); } this->scene->clear(); } //---------------------------------------------------------------------------- void vtkQtWordleView::ZoomToBounds() { this->View->fitInView(this->scene->sceneRect(), Qt::KeepAspectRatio); } //---------------------------------------------------------------------------- QGraphicsScene* vtkQtWordleView::GetScene() { return this->scene; } //---------------------------------------------------------------------------- vtkVector2f vtkQtWordleView::CartesianToPolar(vtkVector2f posArr) { double r = sqrt(posArr.X()*posArr.X() + posArr.Y()*posArr.Y()); double phi = atan2(posArr.Y(), posArr.X()); vtkVector2f r_phi(r, phi); return r_phi; } //---------------------------------------------------------------------------- vtkVector2f vtkQtWordleView::PolarToCartesian(vtkVector2f posArr) { float x = posArr.X()*cos(posArr.Y()); float y = posArr.X()*sin(posArr.Y()); vtkVector2f result(x, y); return result; } //---------------------------------------------------------------------------- vtkVector2f vtkQtWordleView::MakeInitialPosition() { double x = (double)(this->scene->sceneRect().width())*this->randSpread*((double)rand()/(double)RAND_MAX); double y = (double)(this->scene->sceneRect().height())*this->randSpread*((double)rand()/(double)RAND_MAX); vtkVector2f result((float)x, (float)y); return result; } //---------------------------------------------------------------------------- void vtkQtWordleView::UpdateArchPositionSpirals(vtkQtWordleWordObject* word) { // Updating in place double const Pi = 4.0 * atan(1); double ri = word->R0 + (word->rdelta * word->theta); word->theta += (word->delta * Pi) / ri; double r = word->R0 + word->rdelta * word->theta; vtkVector2f dPos = this->PolarToCartesian(vtkVector2f(r, word->theta)); word->pos.SetX(dPos.X() + word->initial_pos.X()); word->pos.SetY(dPos.Y() + word->initial_pos.Y()); } //---------------------------------------------------------------------------- void vtkQtWordleView::UpdateSquarePositionSpirals(vtkQtWordleWordObject* word) { // Updating in place if (word->flag) { float x = word->pos.GetX(); x += word->sign * word->dist; word->pos.SetX(x); word->count += 1; if (word->count == word->target_count) { word->flag = false; word->count = 0; } } else { float y = word->pos.GetY(); y += word->sign * word->dist; word->pos.SetY(y); word->count += 1; if (word->count == word->target_count) { word->count = 0; word->sign *= -1; word->target_count += 1; word->flag = true; } } } namespace { // Compare the two word objects for vector sort // Want to sort in DESCENDING order, so return "greater than" rather than < bool compvtkQtWordleWordObject(const vtkQtWordleWordObject& v1, const vtkQtWordleWordObject& v2) { if (v1.getsize() > v2.getsize()) { return true; } else { return false; } } } //---------------------------------------------------------------------------- vtkImageData* vtkQtWordleView::GetImageData(bool antialias = false) { this->Update(); // Create a new QImage and fill it with the background color QImage* qimage = new QImage(OutputImageDataDimensions[0], OutputImageDataDimensions[1], QImage::Format_ARGB32); qimage->fill(this->scene->backgroundBrush().color().rgba()); QPainter* painter = new QPainter(qimage); painter->setRenderHint(QPainter::Antialiasing); QRectF r_source(this->scene->sceneRect()); QRectF r_target(qimage->rect()); double ws = r_source.width(); double hs = r_source.height(); double wt = r_target.width(); double ht = r_target.height(); double d; // Make sure the wordle ends up in the center of the image // rather than the top (default if source & target rect aspects don't match) if (wt/ht < ws/hs) { // hs adjust d = (ht*(ws/wt) - hs)/2.0; r_source.adjust(0, -d, 0, d); } else { // ws adjust d = (wt*(hs/ht) - ws)/2.0; r_source.adjust(-d, 0, d, 0); } this->scene->render(painter, r_target, r_source, Qt::KeepAspectRatio); painter->end(); this->QImageToImage->SetQImage(qimage); this->QImageToImage->Update(); this->ImageGaussSmooth->Update(); if (antialias) { return vtkImageData::SafeDownCast(this->ImageGaussSmooth->GetOutputDataObject(0)); } else { return vtkImageData::SafeDownCast(this->QImageToImage->GetOutputDataObject(0)); } } //---------------------------------------------------------------------------- // void vtkQtWordleView::SaveSVG(char* filename) // { // this->Update(); // // QSvgGenerator* svggen = new QSvgGenerator(); // svggen->setFileName(filename); // svggen->setSize(QSize(600, 600)); // svggen->setViewBox(QRect(0, 0, 600, 600)); // svggen->setTitle("SVG Wordle"); // svggen->setDescription("An SVG drawing created by the vtkQtWordleView"); // QPainter* svgPainter = new QPainter(svggen); // this->scene->render(svgPainter); // svgPainter->end(); // } //---------------------------------------------------------------------------- void vtkQtWordleView::SavePDF(char* filename) { this->Update(); // Output size with same aspect ratio as scene rect // limited to 7" wide or 9.5" high. QRectF sr = this->scene->sceneRect(); double ph, pw; if (sr.width()/sr.height() >= (7.0/9.5)) { pw = 7.0; ph = pw * (sr.height()/sr.width()); } else { ph = 9.5; pw = ph * (sr.width()/sr.height()); } QSizeF paper_size(pw, ph); QPrinter* printer = new QPrinter(); printer->setOutputFormat(QPrinter::PdfFormat); printer->setOutputFileName(filename); printer->setPaperSize(paper_size, QPrinter::Inch); QPainter* pdfPainter = new QPainter(printer); this->scene->render(pdfPainter); pdfPainter->end(); } //---------------------------------------------------------------------------- void vtkQtWordleView::SaveImage(char* filename, const char* format) { this->Update(); // Create a new QImage and fill it with the background color QImage* qimage = new QImage(OutputImageDataDimensions[0], OutputImageDataDimensions[1], QImage::Format_ARGB32); qimage->fill(this->scene->backgroundBrush().color().rgba()); QPainter* painter = new QPainter(qimage); painter->setRenderHint(QPainter::Antialiasing); QRectF r_source(this->scene->sceneRect()); QRectF r_target(qimage->rect()); double ws = r_source.width(); double hs = r_source.height(); double wt = r_target.width(); double ht = r_target.height(); double d; // Make sure the wordle ends up in the center of the image // rather than the top (default if source & target rect aspects don't match) if (wt/ht < ws/hs) { // hs adjust d = (ht*(ws/wt) - hs)/2.0; r_source.adjust(0, -d, 0, d); } else { // ws adjust d = (wt*(hs/ht) - ws)/2.0; r_source.adjust(-d, 0, d, 0); } this->scene->render(painter, r_target, r_source, Qt::KeepAspectRatio); painter->end(); qimage->save(filename, format); } //---------------------------------------------------------------------------- void vtkQtWordleView::BuildvtkQtWordleWordObjectsList() { vtkDataRepresentation* rep = this->GetRepresentation(); if (!rep) { return; } this->ApplyColors->Update(); vtkTable* table = vtkTable::SafeDownCast(this->ApplyColors->GetOutput()); if (!table) { return; } vtkStringArray* terms = vtkStringArray::SafeDownCast(table->GetColumnByName(this->TermsArrayNameInternal)); if (!terms) { vtkDebugMacro(<< "Terms array not vtkStringArray"); return; } vtkUnsignedCharArray* colors = vtkUnsignedCharArray::SafeDownCast(table->GetColumnByName("vtkApplyColors color")); if (!colors) { vtkDebugMacro(<< "Colors array not vtkUnsignedCharArray"); return; } vtkDoubleArray* sizes = vtkDoubleArray::SafeDownCast(table->GetColumnByName(this->SizeArrayNameInternal)); if (!sizes) { vtkDebugMacro(<< "Size array not vtkDoubleArray"); return; } this->sortedvtkQtWordleWordObjectList.clear(); double sizeRange[2]; sizes->GetRange(sizeRange); double maxSize = std::max(fabs(sizeRange[0]), fabs(sizeRange[1])); unsigned char cc[4]; // Doing a two-stage load for the data so that the more expensive // Qt path related work is only done for the needed number of words // but for sorting it's necessary to load all of the external data first for (vtkIdType ii=0; ii < terms->GetNumberOfValues(); ++ii) { vtkQtWordleWordObject word; word.text = terms->GetValue(ii); word.original_index = ii; word.size = fabs(sizes->GetValue(ii)); colors->GetTupleValue(ii, cc); word.color = new QColor(cc[0],cc[1],cc[2],cc[3]); word.font_size = (int)((float)this->bigFontSize*pow((float)word.size/(float)maxSize,this->WordSizePower)); if (word.font_size < 1) { word.font_size = 1; } (this->sortedvtkQtWordleWordObjectList).push_back(word); } // Sort words according to size std::sort((this->sortedvtkQtWordleWordObjectList).begin(), (this->sortedvtkQtWordleWordObjectList).end(), compvtkQtWordleWordObject); // Second stage for more expensive operations int word_count = std::min((int)this->sortedvtkQtWordleWordObjectList.size(), this->MaxNumberOfWords); for (int ii=0; ii < word_count; ++ii) { this->sortedvtkQtWordleWordObjectList[ii].pos = this->MakeInitialPosition(); this->sortedvtkQtWordleWordObjectList[ii].initial_pos = this->sortedvtkQtWordleWordObjectList[ii].pos; // Archimedean spiral this->sortedvtkQtWordleWordObjectList[ii].delta = this->thetaMult*pow((float)this->sortedvtkQtWordleWordObjectList[ii].font_size, this->thetaPow); this->sortedvtkQtWordleWordObjectList[ii].rdelta = this->rMult*pow((float)this->sortedvtkQtWordleWordObjectList[ii].font_size, this->rPow); // Square spiral this->sortedvtkQtWordleWordObjectList[ii].dist = this->dMult*pow((float)this->sortedvtkQtWordleWordObjectList[ii].font_size, this->dPow); this->font->setPointSize(this->sortedvtkQtWordleWordObjectList[ii].font_size); QPainterPath pathOrig; pathOrig.addText(0.0f, 0.0f, *this->font, QString(this->sortedvtkQtWordleWordObjectList[ii].text.c_str())); QTransform trans; // Orientation values can take on [0,4] inclusive int flip = rand() % 4; if (flip <= (this->orientation-1)) { trans.rotate(90); } this->sortedvtkQtWordleWordObjectList[ii].painter_path = trans.map(pathOrig); QGraphicsPathItem* pathItem = new QGraphicsPathItem(this->sortedvtkQtWordleWordObjectList[ii].painter_path); pathItem->setPen(QPen(Qt::NoPen)); pathItem->setBrush(*this->sortedvtkQtWordleWordObjectList[ii].color); this->sortedvtkQtWordleWordObjectList[ii].path_item = pathItem; // Manually build two-deep tree right here for now... QGraphicsRectItem* rect = new QGraphicsRectItem(pathItem->boundingRect().adjusted(-this->xbuffer, -this->ybuffer, this->xbuffer, this->ybuffer)); rect->setPen(QPen(Qt::NoPen)); QList<QPolygonF> shapes = this->sortedvtkQtWordleWordObjectList[ii].painter_path.toSubpathPolygons(); for (int jj=0; jj < shapes.size(); ++jj) { QGraphicsRectItem* subRect = new QGraphicsRectItem(shapes.at(jj).boundingRect().adjusted(-this->xbuffer,-this->ybuffer,this->xbuffer,this->ybuffer)); subRect->setParentItem(rect); subRect->setPen(QPen(Qt::NoPen)); } this->sortedvtkQtWordleWordObjectList[ii].rect_item = rect; this->sortedvtkQtWordleWordObjectList[ii].rect_item->setPos(this->sortedvtkQtWordleWordObjectList[ii].pos.X(),this->sortedvtkQtWordleWordObjectList[ii].pos.Y()); this->sortedvtkQtWordleWordObjectList[ii].path_item->setPos(this->sortedvtkQtWordleWordObjectList[ii].pos.X(),this->sortedvtkQtWordleWordObjectList[ii].pos.Y()); } } //---------------------------------------------------------------------------- void vtkQtWordleView::ResetOnlyvtkQtWordleWordObjectsPositions() { if (this->sortedvtkQtWordleWordObjectList.size() == 0) { vtkDebugMacro(<< "Tried to reset word objects list but EMPTY."); return; } int word_count = std::min((int)this->sortedvtkQtWordleWordObjectList.size(), this->MaxNumberOfWords); for (int ii=0; ii < word_count; ++ii) { this->sortedvtkQtWordleWordObjectList[ii].pos = this->MakeInitialPosition(); this->sortedvtkQtWordleWordObjectList[ii].initial_pos = this->sortedvtkQtWordleWordObjectList[ii].pos; // Archimedean spiral this->sortedvtkQtWordleWordObjectList[ii].theta = 0.0; // Square spiral this->sortedvtkQtWordleWordObjectList[ii].flag = true; this->sortedvtkQtWordleWordObjectList[ii].sign = 1; this->sortedvtkQtWordleWordObjectList[ii].count = 0; this->sortedvtkQtWordleWordObjectList[ii].target_count = 1; // Resetting only positions this->sortedvtkQtWordleWordObjectList[ii].rect_item->setPos(this->sortedvtkQtWordleWordObjectList[ii].pos.X(),this->sortedvtkQtWordleWordObjectList[ii].pos.Y()); this->sortedvtkQtWordleWordObjectList[ii].path_item->setPos(this->sortedvtkQtWordleWordObjectList[ii].pos.X(),this->sortedvtkQtWordleWordObjectList[ii].pos.Y()); } } //---------------------------------------------------------------------------- void vtkQtWordleView::ResetOnlyvtkQtWordleWordObjectsColors() { if (this->sortedvtkQtWordleWordObjectList.size() == 0) { vtkDebugMacro(<< "Tried to reset word objects list but EMPTY."); return; } vtkDataRepresentation* rep = this->GetRepresentation(); if (!rep) { return; } this->ApplyColors->Update(); vtkTable* table = vtkTable::SafeDownCast(this->ApplyColors->GetOutput()); if (!table) { return; } vtkUnsignedCharArray* colors = vtkUnsignedCharArray::SafeDownCast(table->GetColumnByName("vtkApplyColors color")); if (!colors) { vtkDebugMacro(<< "Colors array not vtkUnsignedCharArray"); return; } unsigned char cc[4]; int orig_idx; int word_count = std::min((int)this->sortedvtkQtWordleWordObjectList.size(), this->MaxNumberOfWords); for (int ii=0; ii < word_count; ++ii) { orig_idx = this->sortedvtkQtWordleWordObjectList[ii].original_index; colors->GetTupleValue(orig_idx, cc); delete this->sortedvtkQtWordleWordObjectList[ii].color; this->sortedvtkQtWordleWordObjectList[ii].color = new QColor(cc[0],cc[1],cc[2],cc[3]); this->sortedvtkQtWordleWordObjectList[ii].path_item->setBrush(*this->sortedvtkQtWordleWordObjectList[ii].color); } } //---------------------------------------------------------------------------- bool vtkQtWordleView::HierarchicalRectCollision_B(QGraphicsRectItem* rectA, QGraphicsRectItem* rectB) { QRectF rA = rectA->rect(); QRectF rB = rectB->rect(); rA.translate(rectA->pos()); rB.translate(rectB->pos()); double ax1 = rA.x(); double ay1 = rA.y(); double ax2 = ax1 + rA.width(); double ay2 = ay1 + rA.height(); double bx1 = rB.x(); double by1 = rB.y(); double bx2 = bx1 + rB.width(); double by2 = by1 + rB.height(); // This sequence only true for non-overlap if ((ax2<bx1) || (ax1>bx2) || (ay2<by1) || (ay1>by2)) { // short-circuit if not overlapping with outer rect return false; } else { // but if overlap with outer rect, check to make sure overlap with a sub-rect QList<QGraphicsItem *> rBchildren = rectB->childItems(); const QGraphicsRectItem* gitem; foreach (const QGraphicsItem* item, rBchildren) { gitem = static_cast<const QGraphicsRectItem*>(item); rB = gitem->rect(); rB.translate(rectB->pos()); bx1 = rB.x(); by1 = rB.y(); bx2 = bx1 + rB.width(); by2 = by1 + rB.height(); if (!((ax2<bx1) or (ax1>bx2) or (ay2<by1) or (ay1>by2))) { // short-circuit if find overlap with any sub-rect return true; } } // return no overlaps if didn't hit any sub-rects return false; } } //---------------------------------------------------------------------------- /* A procedure for finding all the items that intersect a given current_rect Need to supply this code with already translated outer rectangle for the current word rect_item so don't have to translate the position every time QRectF current_rect = current_rect_item->rect(); current_rect.translate(current_rect_item->pos()); */ int vtkQtWordleView::AllIntersectionsMin(vtkQtWordleQuadCIF* Tree, QGraphicsRectItem *rect_item, QRectF current_rect, int last_index) { bool itemCollided; int idxCollided = -1; for (int ii=0; ii < Tree->ItemsList.length(); ++ii) { if (Tree->ItemsList[ii].index == last_index) { continue; } itemCollided = this->HierarchicalRectCollision_B(rect_item, Tree->ItemsList[ii].rect_item); if (itemCollided) { // Short circuit on collision return Tree->ItemsList[ii].index; } } /* traverse the four children */ if (Tree->UL && IsBoundsIntersecting(Tree->UL->frame, current_rect)) { idxCollided = this->AllIntersectionsMin(Tree->UL, rect_item, current_rect, last_index); if (idxCollided >= 0) { // Short circuit on collision return idxCollided; } } if (Tree->LL && IsBoundsIntersecting(Tree->LL->frame, current_rect)) { idxCollided = this->AllIntersectionsMin(Tree->LL, rect_item, current_rect, last_index); if (idxCollided >= 0) { // Short circuit on collision return idxCollided; } } if (Tree->UR && IsBoundsIntersecting(Tree->UR->frame, current_rect)) { idxCollided = this->AllIntersectionsMin(Tree->UR, rect_item, current_rect, last_index); if (idxCollided >= 0) { // Short circuit on collision return idxCollided; } } if (Tree->LR && IsBoundsIntersecting(Tree->LR->frame, current_rect)) { idxCollided = this->AllIntersectionsMin(Tree->LR, rect_item, current_rect, last_index); if (idxCollided >= 0) { // Short circuit on collision return idxCollided; } } return -1; } //---------------------------------------------------------------------------- /* Only test outer bounds, no children */ bool vtkQtWordleView::IsBoundsIntersecting(QRectF frame, QRectF current_rect) { double ax1 = current_rect.x(); double ay1 = current_rect.y(); double ax2 = ax1 + current_rect.width(); double ay2 = ay1 + current_rect.height(); double bx1 = frame.x(); double by1 = frame.y(); double bx2 = bx1 + frame.width(); double by2 = by1 + frame.height(); // This sequence only true for non-overlap if ((ax2<bx1) || (ax1>bx2) || (ay2<by1) || (ay1>by2)) { return false; } else { return true; } } //---------------------------------------------------------------------------- void vtkQtWordleView::DoHybridLayout() { int TEST_ALL = 0; int TEST_QUAD = 1; int mode = TEST_ALL; int quad_fsize_cutoff = 50; int quad_minnum_cutoff = 8; int quad_maxnum_cutoff = (int)((float)this->MaxNumberOfWords * 0.5); bool quadtree_loaded = false; double quad_inc_factor = 0.25; this->scene->setSceneRect(-300, -400, 900, 800); vtkQtWordleQuadCIF *root_node; QRectF tmpRect = this->sortedvtkQtWordleWordObjectList[0].path_item->boundingRect(); int word_count = std::min((int)this->sortedvtkQtWordleWordObjectList.size(), this->MaxNumberOfWords); bool overlap, itemCollided; int idxCollided; int lastRectIndex = 0; // MAIN LOOP for (int ii=0; ii < word_count; ++ii) { // Check whether font size (normalized to 100) has dropped below threshold // or sufficient number of words have been positioned, // and if so, initialize and load up QuadCIF based on layout so far // and switch over to Quad mode collision detection if (quadtree_loaded == false && ((this->sortedvtkQtWordleWordObjectList[ii].font_size < quad_fsize_cutoff && ii > quad_minnum_cutoff) || ii > quad_maxnum_cutoff)) { double xAd = tmpRect.width() * quad_inc_factor; double yAd = tmpRect.height() * quad_inc_factor; QRectF quad_bounds = tmpRect.adjusted(-xAd, -yAd, xAd, yAd); root_node = new vtkQtWordleQuadCIF(quad_bounds); for (int jj=0; jj < ii; ++jj) { root_node->AddRectItemMin(this->sortedvtkQtWordleWordObjectList[jj].rect_item, jj); } mode = TEST_QUAD; quadtree_loaded = true; } if (ii == 0) overlap = false; else overlap = true; while (overlap) { // Assume no overlap and collision detection turns to true if there is overlap overlap = false; // First test for overlap with last one intersected itemCollided = this->HierarchicalRectCollision_B(this->sortedvtkQtWordleWordObjectList[ii].rect_item, this->sortedvtkQtWordleWordObjectList[lastRectIndex].rect_item); if (itemCollided) { overlap = true; } else { if (mode == TEST_QUAD) { // Using QuadCIF tree for intersection tests QRectF current_rect = this->sortedvtkQtWordleWordObjectList[ii].rect_item->rect(); current_rect.translate(this->sortedvtkQtWordleWordObjectList[ii].rect_item->pos()); idxCollided = this->AllIntersectionsMin(root_node, this->sortedvtkQtWordleWordObjectList[ii].rect_item, current_rect, lastRectIndex); if (idxCollided >= 0) { overlap = true; lastRectIndex = idxCollided; } } if (mode == TEST_ALL) { // Checking all words that have already been placed for (int jj=0; jj < ii; ++jj) { if (jj == lastRectIndex) continue; itemCollided = this->HierarchicalRectCollision_B(this->sortedvtkQtWordleWordObjectList[ii].rect_item, this->sortedvtkQtWordleWordObjectList[jj].rect_item); if (itemCollided) { overlap = true; lastRectIndex = jj; break; } } } } if (overlap) { // Update word position in place if (this->LayoutPathShape == vtkQtWordleView::CIRCULAR_PATH) { this->UpdateArchPositionSpirals(&this->sortedvtkQtWordleWordObjectList[ii]); } else { this->UpdateSquarePositionSpirals(&this->sortedvtkQtWordleWordObjectList[ii]); } this->sortedvtkQtWordleWordObjectList[ii].rect_item->setPos(this->sortedvtkQtWordleWordObjectList[ii].pos.X(),this->sortedvtkQtWordleWordObjectList[ii].pos.Y()); } } this->sortedvtkQtWordleWordObjectList[ii].rect_item->setPos(this->sortedvtkQtWordleWordObjectList[ii].pos.X(),this->sortedvtkQtWordleWordObjectList[ii].pos.Y()); this->sortedvtkQtWordleWordObjectList[ii].path_item->setPos(this->sortedvtkQtWordleWordObjectList[ii].pos.X(),this->sortedvtkQtWordleWordObjectList[ii].pos.Y()); this->scene->addItem(this->sortedvtkQtWordleWordObjectList[ii].path_item); if (mode == TEST_QUAD) { // Increase vtkQtWordleQuadCIF size if placement will take new word out of bounds if (tmpRect.x() < root_node->frame.x() || tmpRect.y() < root_node->frame.y() || tmpRect.x() + tmpRect.width() > root_node->frame.x() + root_node->frame.width() || tmpRect.y() + tmpRect.height() > root_node->frame.y() + root_node->frame.height()) { double xAd = tmpRect.width() * quad_inc_factor; double yAd = tmpRect.height() * quad_inc_factor; QRectF quad_bounds = tmpRect.adjusted(-xAd, -yAd, xAd, yAd); root_node = new vtkQtWordleQuadCIF(quad_bounds); for (int jj=0; jj < ii; ++jj) { root_node->AddRectItemMin(this->sortedvtkQtWordleWordObjectList[jj].rect_item, jj); } } // Add current item to the vtkQtWordleQuadCIF tree root_node->AddRectItemMin(this->sortedvtkQtWordleWordObjectList[ii].rect_item, ii); } tmpRect = tmpRect.united(this->sortedvtkQtWordleWordObjectList[ii].path_item->mapRectToScene(this->sortedvtkQtWordleWordObjectList[ii].path_item->boundingRect())); } // Rescale to fit in view double adjX = (tmpRect.width()*0.05)/2.0; double adjY = (tmpRect.height()*0.05)/2.0; QRectF boundingRect = tmpRect.adjusted(-adjX, -adjY, adjX, adjY); this->scene->setSceneRect(boundingRect); this->View->fitInView(boundingRect, Qt::KeepAspectRatio); } //---------------------------------------------------------------------------- void vtkQtWordleView::RedrawWithSameLayout() { this->scene->setSceneRect(-300, -400, 900, 800); QRectF tmpRect = this->sortedvtkQtWordleWordObjectList[0].path_item->boundingRect(); int word_count = std::min((int)this->sortedvtkQtWordleWordObjectList.size(), this->MaxNumberOfWords); // MAIN LOOP for (int ii=0; ii < word_count; ++ii) { this->scene->addItem(this->sortedvtkQtWordleWordObjectList[ii].path_item); tmpRect = tmpRect.united(this->sortedvtkQtWordleWordObjectList[ii].path_item->mapRectToScene(this->sortedvtkQtWordleWordObjectList[ii].path_item->boundingRect())); } // Rescale to fit in view double adjX = (tmpRect.width()*0.05)/2.0; double adjY = (tmpRect.height()*0.05)/2.0; QRectF boundingRect = tmpRect.adjusted(-adjX, -adjY, adjX, adjY); this->scene->setSceneRect(boundingRect); this->View->fitInView(boundingRect, Qt::KeepAspectRatio); } //---------------------------------------------------------------------------- void vtkQtWordleView::Update() { vtkDataRepresentation* rep = this->GetRepresentation(); if (!rep) { this->View->update(); return; } // Make the data current vtkAlgorithmOutput *conn; conn = rep->GetInputConnection(); conn->GetProducer()->Update(); vtkDataObject *d = conn->GetProducer()->GetOutputDataObject(0); // If input has changed, rebuild word objects list if (d->GetMTime() > this->LastInputMTime) { this->DataObjectToTable->Update(); this->ApplyColors->Update(); this->ClearGraphicsView(); this->BuildvtkQtWordleWordObjectsList(); this->DoHybridLayout(); this->LastInputMTime = d->GetMTime(); this->LastColorMTime = this->ApplyColors->GetMTime(); this->LastMTime = this->GetMTime(); } // If only Colors Modified, don't even reset positions if (this->ApplyColors->GetMTime() > this->LastColorMTime) { this->ClearGraphicsView(); this->ResetOnlyvtkQtWordleWordObjectsColors(); this->RedrawWithSameLayout(); this->LastColorMTime = this->ApplyColors->GetMTime(); this->LastMTime = this->GetMTime(); } // If only this->Modified, only reset positions (not orientation or color) if (this->GetMTime() > this->LastMTime) { this->ClearGraphicsView(); this->ResetOnlyvtkQtWordleWordObjectsPositions(); this->DoHybridLayout(); this->LastMTime = this->GetMTime(); } this->View->update(); } //---------------------------------------------------------------------------- void vtkQtWordleView::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }
[ "emonson@cs.duke.edu" ]
emonson@cs.duke.edu
506ecee7a30bea49b1ab95871b90bec09e29b519
a590fbaf14f8e623cdbad4751df1a4e17569051c
/Headers/Platform/Thread.h
682d91177f816184ab151d6594ecbf9ed5be7ab5
[]
no_license
ninoles/snake-3d
e47326d26f37622b907bf980f8c05c9cc84a1dea
11b9c1b5054c85814872d6ecf628de6a38c743a8
refs/heads/master
2016-09-05T21:53:57.403056
2010-02-05T02:23:32
2010-02-05T02:23:32
41,636,616
0
0
null
null
null
null
UTF-8
C++
false
false
1,126
h
/* * Thread.h * * Created on: 04/01/2010 * Author: Henrique Jonas */ #ifndef THREAD_H_ #define THREAD_H_ #ifdef WIN32 #include <windows.h> #define sleepms(x) Sleep(x) #elif defined(__linux__) || defined(MAC_OS) #include <unistd.h> #define sleepms(x) usleep(x * 1000) #else #warning "Could not find an implementation for sleep for current OS. Game won't sleep" #define sleepms(x) #endif #include <pthread.h> #include <iostream> #include <time.h> #include "Snake.h" void* runSnake(void* __snake); void* checkCollisionMap(void* __gamePlay); void* checkCollisionNode(void* __gamePlay); void* checkCollisionPoint(void* __gamePlay); namespace platform{ enum typeThread{ THREAD_COLLISION_MAP, THREAD_COLLISION_POINT, THREAD_COLLISION_NODE, THREAD_MOVIMENT_NODE }; class Thread{ private: pthread_t _thread; int _idThread; public: Thread(); void createThread(platform::Snake *__arg); void stopThread(); int getID(); pthread_t getThread(); }; } #endif /* THREAD_H_ */
[ "henriquesesi@yahoo.com.br" ]
henriquesesi@yahoo.com.br
c2986ba74988dba9a6593c71cc0fa997b07d50e5
b9031e843ff2639d590f5294ff7f598999096da3
/HardLight/include/Controls/Controller.h
4f1369d6dd4407e778262652712a0441d6a19137
[]
no_license
albchu/hardlight
d62fa67b5b1afdaa2e5a25a0eb7fe6fd042f882f
02d52288303e31ff51cb46de667a996a76bb9949
refs/heads/master
2021-01-01T03:37:31.952071
2015-04-17T23:21:26
2015-04-17T23:21:26
57,224,002
0
0
null
null
null
null
UTF-8
C++
false
false
921
h
#ifndef _CONTROLLER_H #define _CONTROLLER_H #include "Vehicle/Chassis.h" // This class is in charge of moving the bike class Controller { public: typedef void (Controller::*Callback)(Chassis*, PxReal); Controller(); Controller(Chassis* new_bike); void forward(Chassis * abike, PxReal acceleration); void backwards(); void steer(Chassis * abike, PxReal steer); Chassis* get_chassis(); void execute_steering(); void execute_motion(); void set_motion(Callback); void set_steering(Callback); void set_direction(PxReal); PxReal get_direction(); void set_acceleration(PxReal); PxReal get_acceleration(); PxReal get_max_acceleration(); PxReal get_min_acceleration(); bool callbacks_set(); //void set_bike(Chassis* new_bike); protected: Chassis* chassis; PxReal direction; PxReal max_acceleration; PxReal min_acceleration; PxReal acceleration; Callback steeringMethod; Callback motionMethod; }; #endif
[ "achu@coverity.com" ]
achu@coverity.com
105341ee85b9c9d22deec2ed1c909c67d5a8d528
0d6d4f12709b26607cff500c1c01f8201b4cfa3a
/include/echo/linear_algebra/submatrix.h
8563f73c2aed36417ac271e104114a9332ae9877
[]
no_license
echo-ml/linear_algebra
6ac16449fde56b23114657d55ae8dd72d8ea7cdd
c0580abb2db5a9bbb7d961cc0c81057b7d55d639
refs/heads/master
2021-01-10T12:25:55.377894
2015-09-14T03:44:33
2015-09-14T03:44:33
36,343,710
0
0
null
null
null
null
UTF-8
C++
false
false
805
h
#pragma once #include <echo/linear_algebra/concept.h> #include <echo/linear_algebra/matrix.h> #include <echo/contract.h> namespace echo { namespace linear_algebra { //------------------------------------------------------------------------------ // make_submatrix //------------------------------------------------------------------------------ template <class RowSlice, class ColumnSlice, class A, CONCEPT_REQUIRES(concept::general_matrix<uncvref_t<A>>() && numeric_array::concept::numeric_subarray< uncvref_t<A>, RowSlice, ColumnSlice>())> auto make_submatrix(A&& a, const RowSlice& row_slice, const ColumnSlice& column_slice) { return make_numeric_subarray(std::forward<A>(a), row_slice, column_slice); } } }
[ "ribulous.barnulous@gmail.com" ]
ribulous.barnulous@gmail.com
2d248403f143dc1c1e89f5da25251181eefea932
82372173e768c0a056c676217f8f68d2a8347978
/Source/PluginEditor.cpp
136a432a3b6fae0eed0dd29a3e35bb6c448ce937
[]
no_license
kiranrkumar/VariableDelay
96610a0301fda94b947c3746087b55e3f5488d17
79c4b69a7945ce9e5ad71fe5cb491e8d9b0e3a53
refs/heads/master
2021-01-20T03:59:19.277759
2017-04-27T15:39:08
2017-04-27T15:39:08
89,613,736
0
0
null
null
null
null
UTF-8
C++
false
false
4,269
cpp
/* ============================================================================== This file was auto-generated! It contains the basic framework code for a JUCE plugin editor. ============================================================================== */ #include "PluginProcessor.h" #include "PluginEditor.h" //============================================================================== VariableDelayAudioProcessorEditor::VariableDelayAudioProcessorEditor (VariableDelayAudioProcessor& p) : AudioProcessorEditor (&p), processor (p) { // Make sure that before the constructor has finished, you've set the // editor's size to whatever you need it to be. setSize (500, 300); //create sliders //carrier Frequency initSlider(&carFreq, Slider::RotaryHorizontalVerticalDrag, "Carrier Freq", Slider::TextBoxRight, false, " Hz", 0.0, 2000.0, 1.0, initCarFreq); //delay LFO frequency initSlider(&delLfoFreq, Slider::RotaryHorizontalVerticalDrag, "LFO Freq", Slider::TextBoxRight, false, " Hz", 0.0, 50.0, 0.2, 0.0); //output volume in dB initSlider(&outGain, Slider::LinearHorizontal, "Out Gain", Slider::TextBoxBelow, false, " dB", -60.0, 0.0, 0.1, 0.0); //delay LFO depth initSlider(&delLfoDepth, Slider::LinearHorizontal, "LFO Depth", Slider::TextBoxBelow, false, "", 0.0, 5000.0, 1.0, 1500.0); } VariableDelayAudioProcessorEditor::~VariableDelayAudioProcessorEditor() { } void VariableDelayAudioProcessorEditor::initSlider( Slider* slider, Slider::SliderStyle newStyle, juce::String newName, Slider::TextEntryBoxPosition newTxtBoxPos, bool txtIsReadOnly, juce::String newSuffix, double newMin, double newMax, double newInc, double newValue, bool addListener) { slider->setSliderStyle(newStyle); slider->setName(newName); slider->setTextBoxStyle(newTxtBoxPos, txtIsReadOnly, slider->getTextBoxWidth(), slider->getTextBoxHeight()); slider->setTextValueSuffix(newSuffix); slider->setRange(newMin, newMax, newInc); slider->setValue(newValue); if (addListener) { slider->addListener(this); } addAndMakeVisible(slider); } //============================================================================== void VariableDelayAudioProcessorEditor::paint (Graphics& g) { g.fillAll (Colours::white); g.setColour (Colours::black); g.setFont (15.0f); // g.drawFittedText ("Hello World!", getLocalBounds(), Justification::centred, 1); g.drawFittedText("Carrier Frequency", 50, 30, 100, 25, Justification::left, 1); g.drawFittedText("LFO Frequency", 250, 30, 100, 25, Justification::left, 1); g.drawFittedText("Gain", 10, 185, 100, 25, Justification::centred, 1); g.drawFittedText("Delay LFO Depth", 230, 185, 100, 25, Justification::centred, 1); } void VariableDelayAudioProcessorEditor::resized() { // This is generally where you'll want to lay out the positions of any // subcomponents in your editor.. carFreq.setBounds(50, 30, 150, 150); delLfoFreq.setBounds(245, 30, 200, 200); outGain.setBounds(25, 210, 200, 50); delLfoDepth.setBounds(225, 210, 200, 50); } void VariableDelayAudioProcessorEditor::sliderValueChanged(Slider* slider) { //convert dB gain to linear gain if (slider->getName() == "Out Gain") { processor.mPrevOutputGain = processor.mOutputGain; processor.mOutputGain = Decibels::decibelsToGain(slider->getValue()); } else if (slider->getName() == "Carrier Freq") { processor.mCarrierFreq = slider->getValue(); } else if (slider->getName() == "LFO Freq") { //because of how the modulator gets treated (zero-min), we want to half this frequency so that there's basically one movement away from 0 per period rather than 2 processor.mLfoDelFreq = slider->getValue() / 2; } else if (slider->getName() == "LFO Depth") { processor.mPrevLfoDepth = processor.mLfoDepth; processor.mLfoDepth = slider->getValue(); } } void VariableDelayAudioProcessorEditor::buttonClicked(Button* button) { }
[ "krkumar11@gmail.com" ]
krkumar11@gmail.com
34f3ec0147befe5ed7b851160e9e4cca20e6eeae
d301049a0398ee2ff71a85d5e0ff3ef51afcd26f
/src/decompiler/Optimization/Graph/DecGraphDebugProcessing.h
abea9165c7d6788098acc4fd45869007f736c332
[ "Apache-2.0" ]
permissive
Fleynaro/SDA
08a53ae434e31d46e97fab5de4f4a3325cdc80bb
d4b977e9522f09da38847a8e95b7f471e3a30f14
refs/heads/master
2023-08-30T14:34:38.655997
2022-10-06T16:22:58
2022-10-06T16:22:58
233,063,028
114
11
null
null
null
null
UTF-8
C++
false
false
461
h
#pragma once #include "DecGraphModification.h" namespace CE::Decompiler::Optimization { // process the graph for debugging class GraphDebugProcessing : public GraphModification { bool m_seqLines; public: GraphDebugProcessing(DecompiledCodeGraph* decGraph, bool seqLines); void start() override; private: static void ProcessLines(std::list<DecBlock::AssignmentLine*>& lines); static uint64_t GetOrder(DecBlock::AssignmentLine* seqLine); }; };
[ "dariusjohnson555@gmail.com" ]
dariusjohnson555@gmail.com
baf82375165b15fd8de0657c301aefc99757b3a2
1a6a10e9432b70385e6e06c21c9cac71b9c93152
/src/main.cpp
b6ca84f92d075a4301b0998771ceddcef8d778af
[]
no_license
Scoobadood/FaceOff
ff9fe67c849e0013dcce6cb9caeaff2304e888c6
41838cb52dcedbf4f8124fb396635b0288e87dea
refs/heads/master
2021-01-18T19:36:44.181034
2017-04-09T07:49:27
2017-04-09T07:49:27
86,903,725
14
2
null
null
null
null
UTF-8
C++
false
false
7,360
cpp
#include <iostream> #include <OpenNI.h> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/objdetect.hpp> #include "FaceOffConfig.h" const int SAMPLE_READ_WAIT_TIMEOUT = 2000; // ms const float FACE_SIZE_RATIO = 0.25f; const float EYE_SIZE_RATIO = 0.25f; const float EYE_REGION_HEIGHT_PROPORTION = 0.6f; const cv::Scalar BLUE( 255, 0, 0 ); const cv::Scalar GREEN( 0, 255, 0 ); /** * Setup and initialise openNI * or fail */ int initializeDepthCamera( openni::Device& device, openni::VideoStream& depth, openni::VideoStream& colour ) { using namespace openni; Status rc = OpenNI::initialize(); if (rc != STATUS_OK) { std::cout << "Initialize failed: " << OpenNI::getExtendedError() << std::endl; return 1; } rc = device.open(ANY_DEVICE); if (rc != STATUS_OK) { std::cout << "Couldn't open device: " << OpenNI::getExtendedError() << std::endl; return 2; } if (device.getSensorInfo(SENSOR_DEPTH) != NULL) { rc = depth.create(device, SENSOR_DEPTH); if (rc == STATUS_OK) { rc = depth.start(); if (rc != STATUS_OK) { std::cout << "Couldn't start the depth stream: " << OpenNI::getExtendedError() << std::endl; } } else { std::cout << "Couldn't create depth stream: " << OpenNI::getExtendedError() << std::endl; } } if (device.getSensorInfo(SENSOR_COLOR) != NULL) { rc = colour.create(device, SENSOR_COLOR); if (rc == STATUS_OK) { rc = colour.start(); if (rc != STATUS_OK) { std::cout << "Couldn't start the colour stream: " << OpenNI::getExtendedError() << std::endl; } } else { std::cout << "Couldn't create colour stream: " << OpenNI::getExtendedError() << std::endl; } } return 0; } /** * Finish with the device, close down stream etc */ void finalizeDevice( openni::Device& device, openni::VideoStream& depth, openni::VideoStream& colour ) { depth.stop(); colour.stop(); depth.destroy(); colour.destroy(); device.close(); openni::OpenNI::shutdown(); } /** * Get a pair of frames; depth and RGB which are close together in time * @return -1 If no frame returned, 0 for depth and 1 for colour */ int getFrame( openni::VideoStream& depth, openni::VideoStream& colour, openni::VideoFrameRef& frame) { using namespace openni; int readyStream = -1; VideoStream * streams[] = { &depth, &colour }; Status rc = OpenNI::waitForAnyStream(streams, 2, &readyStream, SAMPLE_READ_WAIT_TIMEOUT); if (rc != STATUS_OK) { std::cout << "Wait failed! (timeout is " << SAMPLE_READ_WAIT_TIMEOUT << " ms): " << OpenNI::getExtendedError() << std::endl; } // Status was OK, we got a frame else { switch (readyStream) { case 0: // Depth depth.readFrame(&frame); break; case 1: // Colour colour.readFrame(&frame); break; default: std::cerr << "Unxpected stream: " << readyStream << std::endl; } } return readyStream; } /** * @return the path to the directory containing this executable file */ int getPathToExe( char * buffer, int buffer_length ) { char szTmp[32]; sprintf(szTmp, "/proc/%d/exe", getpid()); int bytes = MIN(readlink(szTmp, buffer, buffer_length), buffer_length - 1); if(bytes >= 0) buffer[bytes] = '\0'; // Now search from the end of the string to find the last file separator while( (--bytes > 0 ) && buffer[bytes] != '/'); if( buffer[bytes] == '/') { buffer[bytes] = '\0'; } else { bytes = strlen( buffer ); } return bytes; } /* * Load Haar classifiers for face and eyes */ bool loadHaarClassifiers( cv::CascadeClassifier& face_classifier, cv::CascadeClassifier& left_eye_classifier, cv::CascadeClassifier& right_eye_classifier ) { // Work out where this code is running from char exe_dir[1024]; getPathToExe( exe_dir, 1024 ); std::string base( exe_dir ); base += "/data"; // Classifiers should be in a data subdirectory std::cout << "Loading haar cascades from " << base << std::endl; bool loaded_ok = true; loaded_ok &= face_classifier.load( base + "/haarcascade_frontalface_default.xml" ); loaded_ok &= left_eye_classifier.load( base + "/haarcascade_lefteye_2splits.xml" ); loaded_ok &= right_eye_classifier.load( base + "/haarcascade_righteye_2splits.xml" ); return loaded_ok; } int main( int argc, char *argv[] ) { using namespace openni; std::cout << "FaceOff v" << VERSION_MAJOR << "." << VERSION_MINOR << std::endl; std::cout << "hit a key to quit" << std::endl; // Set up the capture device Device device; VideoStream colour, depth; if( initializeDepthCamera( device, depth, colour ) != 0 ) { return 1; } VideoFrameRef frame; // Load classifiers cv::CascadeClassifier faceClassifier, leftEyeClassifier, rightEyeClassifier; if( !loadHaarClassifiers( faceClassifier, leftEyeClassifier, rightEyeClassifier ) ) { std::cout << "Failed to load classfiers" << std::endl; return -1; } // Create a window to display RGB feed cv::namedWindow( "RGB" ); int numDepthFrames = 0; int numColourFrames= 0; while ( cv::waitKey(10) == -1 ) { int frameType = getFrame( depth, colour, frame ); // Depth frame if( frameType == 0 ) { // Register this to colour // Process frame numDepthFrames++; } else if ( frameType == 1 ) { // Grab pointer to data in appropriate format const RGB888Pixel* imageBuffer = (const openni::RGB888Pixel*)frame.getData(); // Create a Mat cv::Mat rgbImage; rgbImage.create( frame.getHeight(), frame.getWidth(), CV_8UC3 ); memcpy( rgbImage.data, imageBuffer, 3 * frame.getHeight()*frame.getWidth()*sizeof(uint8_t) ); // Manage BGR to RGB conversion cv::cvtColor( rgbImage, rgbImage, CV_BGR2RGB); // Make a grey version for face detection cv::Mat greyImage( frame.getHeight(), frame.getWidth(), CV_8UC1 ); cv::cvtColor( rgbImage, greyImage, CV_RGB2GRAY); // Find the face std::vector<cv::Rect> faces; cv::Size desiredSize( frame.getWidth() * FACE_SIZE_RATIO, frame.getHeight() * FACE_SIZE_RATIO ); faceClassifier.detectMultiScale( greyImage, faces, 1.1, 3, 0, desiredSize ); // Render if there is one if( faces.size() > 0 ) { // Render face box into image cv::rectangle( rgbImage, faces[0], BLUE, 3 ); // And find eyes cv::Rect eyeRegion( faces[0].x, faces[0].y, faces[0].width, faces[0].height * EYE_REGION_HEIGHT_PROPORTION ); cv::Mat eyeROI = greyImage( eyeRegion ); cv::Size desiredSize( eyeRegion.width * EYE_SIZE_RATIO, eyeRegion.width * EYE_SIZE_RATIO ); std::vector<cv::Rect> leftEyes; leftEyeClassifier.detectMultiScale( eyeROI, leftEyes, 1.1, 2, 0, desiredSize ); if( leftEyes.size() > 0 ) { leftEyes[0].x += faces[0].x; leftEyes[0].y += faces[0].y; cv::rectangle( rgbImage, leftEyes[0], GREEN, 2 ); } std::vector<cv::Rect> rightEyes; rightEyeClassifier.detectMultiScale( eyeROI, rightEyes, 1.1, 2, 0, desiredSize ); if( rightEyes.size() > 0 ) { rightEyes[0].x += faces[0].x; rightEyes[0].y += faces[0].y; cv::rectangle( rgbImage, rightEyes[0], GREEN, 2 ); } } // Render cv::imshow( "RGB", rgbImage ); numColourFrames++; } std::cout << "\rDepth frames : " << numDepthFrames << " Colour frames : " << numColourFrames << std::flush; } std::cout << std::endl; cv::destroyWindow( "RGB" ); // Shutdown the device finalizeDevice( device, depth, colour ); return 0; }
[ "scoobadood@me.com" ]
scoobadood@me.com
79dbdd416a4d7b2123a9974d7f2d0aee3c63eb81
78bb30969ff3ee13546565685cb87a7be1652aa9
/projects/libwebp/fuzz_webp_animencoder.cc
f5cb2d13f88bdb3637b0c09d5a6836ff8c12b403
[ "Apache-2.0" ]
permissive
DeepInThought/oss-fuzz
d8cebc6a0133dad2ef0d1fa8b9de17679a030ebf
8e2d57684bd49355b80572592c3af5cefc19a69c
refs/heads/master
2020-12-19T15:18:19.169907
2020-01-23T02:24:10
2020-01-23T02:24:10
235,771,632
2
0
Apache-2.0
2020-01-23T10:27:10
2020-01-23T10:26:18
null
UTF-8
C++
false
false
5,306
cc
// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <stdlib.h> #include "fuzz.h" #include "webp/encode.h" #include "webp/mux.h" namespace { const VP8CPUInfo default_VP8GetCPUInfo = VP8GetCPUInfo; int AddFrame(WebPAnimEncoder** const enc, const WebPAnimEncoderOptions& anim_config, int* const width, int* const height, int timestamp_ms, const uint8_t data[], size_t size, uint32_t* const bit_pos) { if (enc == nullptr || width == nullptr || height == nullptr) { fprintf(stderr, "NULL parameters.\n"); if (enc != nullptr) WebPAnimEncoderDelete(*enc); abort(); } // Init the source picture. WebPPicture pic; if (!WebPPictureInit(&pic)) { fprintf(stderr, "WebPPictureInit failed.\n"); WebPAnimEncoderDelete(*enc); abort(); } pic.use_argb = Extract(1, data, size, bit_pos); // Read the source picture. if (!ExtractSourcePicture(&pic, data, size, bit_pos)) { fprintf(stderr, "Can't read input image.\n"); WebPPictureFree(&pic); abort(); } // Crop and scale. if (*enc == nullptr) { // First frame will set canvas width and height. if (!ExtractAndCropOrScale(&pic, data, size, bit_pos)) { fprintf(stderr, "ExtractAndCropOrScale failed."); WebPPictureFree(&pic); abort(); } } else { // Other frames will be resized to the first frame's dimensions. if (!WebPPictureRescale(&pic, *width, *height)) { fprintf(stderr, "WebPPictureRescale failed. Size: %d,%d\n", *width, *height); WebPAnimEncoderDelete(*enc); WebPPictureFree(&pic); abort(); } } // Create encoder if it doesn't exist. if (*enc == nullptr) { *width = pic.width; *height = pic.height; *enc = WebPAnimEncoderNew(*width, *height, &anim_config); if (*enc == nullptr) { fprintf(stderr, "WebPAnimEncoderNew failed.\n"); WebPPictureFree(&pic); abort(); } } // Create frame encoding config. WebPConfig config; if (!ExtractWebPConfig(&config, data, size, bit_pos)) { fprintf(stderr, "ExtractWebPConfig failed.\n"); WebPAnimEncoderDelete(*enc); WebPPictureFree(&pic); abort(); } // Skip slow settings on big images, it's likely to timeout. if (pic.width * pic.height > 32 * 32) { config.method = (config.method > 4) ? 4 : config.method; config.quality = (config.quality > 99.0f) ? 99.0f : config.quality; config.alpha_quality = (config.alpha_quality > 99) ? 99 : config.alpha_quality; } // Encode. if (!WebPAnimEncoderAdd(*enc, &pic, timestamp_ms, &config)) { fprintf(stderr, "WebPEncode failed. Error code: %d\n", pic.error_code); WebPAnimEncoderDelete(*enc); WebPPictureFree(&pic); abort(); } WebPPictureFree(&pic); return 1; } } // namespace extern "C" int LLVMFuzzerTestOneInput(const uint8_t* const data, size_t size) { WebPAnimEncoder* enc = nullptr; int width = 0, height = 0, timestamp_ms = 0; uint32_t bit_pos = 0; ExtractAndDisableOptimizations(default_VP8GetCPUInfo, data, size, &bit_pos); // Extract a configuration from the packed bits. WebPAnimEncoderOptions anim_config; if (!WebPAnimEncoderOptionsInit(&anim_config)) { fprintf(stderr, "WebPAnimEncoderOptionsInit failed.\n"); abort(); } anim_config.minimize_size = Extract(1, data, size, &bit_pos); anim_config.kmax = Extract(15, data, size, &bit_pos); const int min_kmin = (anim_config.kmax > 1) ? (anim_config.kmax / 2) : 0; const int max_kmin = (anim_config.kmax > 1) ? (anim_config.kmax - 1) : 0; anim_config.kmin = min_kmin + Extract((uint32_t)(max_kmin - min_kmin), data, size, &bit_pos); anim_config.allow_mixed = Extract(1, data, size, &bit_pos); anim_config.verbose = 0; const int nb_frames = 1 + Extract(15, data, size, &bit_pos); // For each frame. for (int i = 0; i < nb_frames; ++i) { if (!AddFrame(&enc, anim_config, &width, &height, timestamp_ms, data, size, &bit_pos)) { return 0; } timestamp_ms += (1 << (2 + Extract(15, data, size, &bit_pos))) + Extract(1, data, size, &bit_pos); // [1..131073], arbitrary } // Assemble. if (!WebPAnimEncoderAdd(enc, nullptr, timestamp_ms, nullptr)) { fprintf(stderr, "Last WebPAnimEncoderAdd failed."); WebPAnimEncoderDelete(enc); abort(); } WebPData webp_data; WebPDataInit(&webp_data); if (!WebPAnimEncoderAssemble(enc, &webp_data)) { fprintf(stderr, "WebPAnimEncoderAssemble failed."); WebPAnimEncoderDelete(enc); WebPDataClear(&webp_data); abort(); } WebPAnimEncoderDelete(enc); WebPDataClear(&webp_data); return 0; }
[ "41697236+mbarbella-chromium@users.noreply.github.com" ]
41697236+mbarbella-chromium@users.noreply.github.com
589ce542de83782938ffdaeaaad23d22fa231c0d
fdd07a7ef27a60a2be92a0787f5b40e220558d07
/Ship.h
486de897a5bec7be30948018f52ab869a459bd06
[]
no_license
xain999/naval-war
8793ad783c1aabe1d770c02b0b37966928c0a1c6
0fa22c1b42e0c4cade21d1de7e441c628d9cd35f
refs/heads/master
2021-04-28T15:52:08.981816
2012-02-18T23:44:05
2018-02-18T23:44:05
122,001,345
0
0
null
null
null
null
UTF-8
C++
false
false
1,961
h
#pragma once #include "point.h" #include "glut.h" #include "Bomb.h" class Ship : //class ship inheriting class point public point { protected: float DeltaMove ; //can ship moves towards right int power ; //power of the bomb int angle ; //angle of the bomb int score ; //score of the player point pos ; //adjusting the ship point turret ; //turret start position point CurrentPosition; //current position of the ship Bomb bombs ; //Array of bombs string fileName ; //name to the file public: //Taking points to keep track of the coordinates of Ship point TopLeft ; point TopRight ; point BottomLeft ; point BottomRight ; Ship(void); virtual ~Ship(void); float getMove() ; //checking moves left to move Left void ChangePosition() ; //changing ships coordinates void Fire(); //fire bomb bool CheckBomb(int, int); //Check the bomb void DEC2STR(int ,char *); //changing a decimal to string void SaveToFile(); //Save HighScore to File point getPosition(); //geet the position of the ship void calculateScore(point); //calculate the score of the player int getScore(); //return score point getBombPosition(); //get bombs position virtual void intialize() = 0; //intialize the ships virtual void DisplayHighScore() = 0 ; //Display High Score virtual void display_Atr() = 0 ; //display score angle and power virtual bool checkLeft() = 0 ; //checking whether to move left or not virtual bool checkRight() = 0 ; //checking whether to move right or not virtual void draw(void) = 0 ; //virtual drawing fuction virtual void move(char) = 0 ; //virtual move fuction virtual void changePower(char) = 0 ; //increasing or decreasing power virtual void changeAngle(char) = 0 ; //increasing or decreasing angle };
[ "zain.ul.abideen@tum.de" ]
zain.ul.abideen@tum.de
570963fdb812f83b572b6cd22a6235a5d472b69a
cc7ea7d3af5afdfab52c4ade486f2b733147415b
/folly/stats/TDigest.cpp
c363c0d41abded51e01455c8a44753bede9ebb25
[ "MIT", "Apache-2.0" ]
permissive
couchbasedeps/folly
f2d70e1b2c629761e40e15248ea17335e651fc40
99a218de8a87c48f8164afb614401717c58cce8a
refs/heads/master
2022-09-09T08:32:46.196956
2021-02-26T21:43:46
2021-02-26T21:45:23
152,815,030
1
3
Apache-2.0
2022-08-22T12:19:33
2018-10-12T22:48:10
C++
UTF-8
C++
false
false
11,141
cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/stats/TDigest.h> #include <algorithm> #include <limits> #include <glog/logging.h> #include <folly/stats/detail/DoubleRadixSort.h> namespace folly { /* * A good biased scaling function has the following properties: * - The value of the function k(0, delta) = 0, and k(1, delta) = delta. * This is a requirement for any t-digest function. * - The limit of the derivative of the function dk/dq at 0 is inf, and at * 1 is inf. This provides bias to improve accuracy at the tails. * - For any q <= 0.5, dk/dq(q) = dk/dq(1-q). This ensures that the accuracy * of upper and lower quantiles are equivalent. * * The scaling function used here is... * k(q, d) = (IF q >= 0.5, d - d * sqrt(2 - 2q) / 2, d * sqrt(2q) / 2) * * k(0, d) = 0 * k(1, d) = d * * dk/dq = (IF q >= 0.5, d / sqrt(2-2q), d / sqrt(2q)) * limit q->1 dk/dq = inf * limit q->0 dk/dq = inf * * When plotted, the derivative function is symmetric, centered at q=0.5. * * Note that FMA has been tested here, but benchmarks have not shown it to be a * performance improvement. */ /* * q_to_k is unused but left here as a comment for completeness. * double q_to_k(double q, double d) { * if (q >= 0.5) { * return d - d * std::sqrt(0.5 - 0.5 * q); * } * return d * std::sqrt(0.5 * q); * } */ static double k_to_q(double k, double d) { double k_div_d = k / d; if (k_div_d >= 0.5) { double base = 1 - k_div_d; return 1 - 2 * base * base; } else { return 2 * k_div_d * k_div_d; } } static double clamp(double v, double lo, double hi) { if (v > hi) { return hi; } else if (v < lo) { return lo; } return v; } TDigest::TDigest( std::vector<Centroid> centroids, double sum, double count, double max_val, double min_val, size_t maxSize) : maxSize_(maxSize), sum_(sum), count_(count), max_(max_val), min_(min_val) { if (centroids.size() <= maxSize_) { centroids_ = std::move(centroids); } else { // Number of centroids is greater than maxSize, we need to compress them // When merging, resulting digest takes the maxSize of the first digest auto sz = centroids.size(); std::array<TDigest, 2> digests{{ TDigest(maxSize_), TDigest(std::move(centroids), sum_, count_, max_, min_, sz), }}; *this = this->merge(digests); } } // Merge unsorted values by first sorting them. Use radix sort if // possible. This implementation puts all additional memory in the // heap, so that if called from fiber context we do not smash the // stack. Otherwise it is very similar to boost::spreadsort. TDigest TDigest::merge(Range<const double*> unsortedValues) const { auto n = unsortedValues.size(); // We require 256 buckets per byte level, plus one count array we can reuse. std::unique_ptr<uint64_t[]> buckets{new uint64_t[256 * 9]}; // Allocate input and tmp array std::unique_ptr<double[]> tmp{new double[n * 2]}; auto out = tmp.get() + n; auto in = tmp.get(); std::copy(unsortedValues.begin(), unsortedValues.end(), in); detail::double_radix_sort(n, buckets.get(), in, out); DCHECK(std::is_sorted(in, in + n)); return merge(sorted_equivalent, Range<const double*>(in, in + n)); } TDigest TDigest::merge( sorted_equivalent_t, Range<const double*> sortedValues) const { if (sortedValues.empty()) { return *this; } TDigest result(maxSize_); result.count_ = count_ + sortedValues.size(); double maybeMin = *sortedValues.begin(); double maybeMax = *(sortedValues.end() - 1); if (count_ > 0) { // We know that min_ and max_ are numbers result.min_ = std::min(min_, maybeMin); result.max_ = std::max(max_, maybeMax); } else { // We know that min_ and max_ are NaN. result.min_ = maybeMin; result.max_ = maybeMax; } std::vector<Centroid> compressed; compressed.reserve(maxSize_); double k_limit = 1; double q_limit_times_count = k_to_q(k_limit++, maxSize_) * result.count_; auto it_centroids = centroids_.begin(); auto it_sortedValues = sortedValues.begin(); Centroid cur; if (it_centroids != centroids_.end() && it_centroids->mean() < *it_sortedValues) { cur = *it_centroids++; } else { cur = Centroid(*it_sortedValues++, 1.0); } double weightSoFar = cur.weight(); // Keep track of sums along the way to reduce expensive floating points double sumsToMerge = 0; double weightsToMerge = 0; while (it_centroids != centroids_.end() || it_sortedValues != sortedValues.end()) { Centroid next; if (it_centroids != centroids_.end() && (it_sortedValues == sortedValues.end() || it_centroids->mean() < *it_sortedValues)) { next = *it_centroids++; } else { next = Centroid(*it_sortedValues++, 1.0); } double nextSum = next.mean() * next.weight(); weightSoFar += next.weight(); if (weightSoFar <= q_limit_times_count) { sumsToMerge += nextSum; weightsToMerge += next.weight(); } else { result.sum_ += cur.add(sumsToMerge, weightsToMerge); sumsToMerge = 0; weightsToMerge = 0; compressed.push_back(cur); q_limit_times_count = k_to_q(k_limit++, maxSize_) * result.count_; cur = next; } } result.sum_ += cur.add(sumsToMerge, weightsToMerge); compressed.push_back(cur); compressed.shrink_to_fit(); // Deal with floating point precision std::sort(compressed.begin(), compressed.end()); result.centroids_ = std::move(compressed); return result; } TDigest TDigest::merge(Range<const TDigest*> digests) { size_t nCentroids = 0; for (const auto& digest : digests) { nCentroids += digest.centroids_.size(); } if (nCentroids == 0) { return TDigest(); } std::vector<Centroid> centroids; centroids.reserve(nCentroids); std::vector<std::vector<Centroid>::iterator> starts; starts.reserve(digests.size()); double count = 0; // We can safely use these limits to avoid isnan checks below because we know // nCentroids > 0, so at least one TDigest has a min and max. double min = std::numeric_limits<double>::infinity(); double max = -std::numeric_limits<double>::infinity(); for (const auto& digest : digests) { starts.push_back(centroids.end()); double curCount = digest.count(); if (curCount > 0) { DCHECK(!std::isnan(digest.min_)); DCHECK(!std::isnan(digest.max_)); min = std::min(min, digest.min_); max = std::max(max, digest.max_); count += curCount; for (const auto& centroid : digest.centroids_) { centroids.push_back(centroid); } } } for (size_t digestsPerBlock = 1; digestsPerBlock < starts.size(); digestsPerBlock *= 2) { // Each sorted block is digestPerBlock digests big. For each step, try to // merge two blocks together. for (size_t i = 0; i < starts.size(); i += (digestsPerBlock * 2)) { // It is possible that this block is incomplete (less than digestsPerBlock // big). In that case, the rest of the block is sorted and leave it alone if (i + digestsPerBlock < starts.size()) { auto first = starts[i]; auto middle = starts[i + digestsPerBlock]; // It is possible that the next block is incomplete (less than // digestsPerBlock big). In that case, merge to end. Otherwise, merge to // the end of that block. auto last = (i + (digestsPerBlock * 2) < starts.size()) ? *(starts.begin() + i + 2 * digestsPerBlock) : centroids.end(); std::inplace_merge(first, middle, last); } } } DCHECK(std::is_sorted(centroids.begin(), centroids.end())); size_t maxSize = digests.begin()->maxSize_; TDigest result(maxSize); std::vector<Centroid> compressed; compressed.reserve(maxSize); double k_limit = 1; double q_limit_times_count = k_to_q(k_limit, maxSize) * count; Centroid cur = centroids.front(); double weightSoFar = cur.weight(); double sumsToMerge = 0; double weightsToMerge = 0; for (auto it = centroids.begin() + 1; it != centroids.end(); ++it) { weightSoFar += it->weight(); if (weightSoFar <= q_limit_times_count) { sumsToMerge += it->mean() * it->weight(); weightsToMerge += it->weight(); } else { result.sum_ += cur.add(sumsToMerge, weightsToMerge); sumsToMerge = 0; weightsToMerge = 0; compressed.push_back(cur); q_limit_times_count = k_to_q(k_limit++, maxSize) * count; cur = *it; } } result.sum_ += cur.add(sumsToMerge, weightsToMerge); compressed.push_back(cur); compressed.shrink_to_fit(); // Deal with floating point precision std::sort(compressed.begin(), compressed.end()); result.count_ = count; result.min_ = min; result.max_ = max; result.centroids_ = std::move(compressed); return result; } double TDigest::estimateQuantile(double q) const { if (centroids_.empty()) { return 0.0; } double rank = q * count_; size_t pos; double t; if (q > 0.5) { if (q >= 1.0) { return max_; } pos = 0; t = count_; for (auto rit = centroids_.rbegin(); rit != centroids_.rend(); ++rit) { t -= rit->weight(); if (rank >= t) { pos = std::distance(rit, centroids_.rend()) - 1; break; } } } else { if (q <= 0.0) { return min_; } pos = centroids_.size() - 1; t = 0; for (auto it = centroids_.begin(); it != centroids_.end(); ++it) { if (rank < t + it->weight()) { pos = std::distance(centroids_.begin(), it); break; } t += it->weight(); } } double delta = 0; double min = min_; double max = max_; if (centroids_.size() > 1) { if (pos == 0) { delta = centroids_[pos + 1].mean() - centroids_[pos].mean(); max = centroids_[pos + 1].mean(); } else if (pos == centroids_.size() - 1) { delta = centroids_[pos].mean() - centroids_[pos - 1].mean(); min = centroids_[pos - 1].mean(); } else { delta = (centroids_[pos + 1].mean() - centroids_[pos - 1].mean()) / 2; min = centroids_[pos - 1].mean(); max = centroids_[pos + 1].mean(); } } auto value = centroids_[pos].mean() + ((rank - t) / centroids_[pos].weight() - 0.5) * delta; return clamp(value, min, max); } double TDigest::Centroid::add(double sum, double weight) { sum += (mean_ * weight_); weight_ += weight; mean_ = sum / weight_; return sum; } } // namespace folly
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
713b0b55e776d4a53507244dcf4d5dae9fb322dc
21e5d4f7478965d6b59297edad403715afa07b08
/Classes/FileReader.cpp
637acb436921453f2960ba6aaa5c9bec4da422a5
[]
no_license
khacchinh/SaveTheForest
2892574dd69b6efcb4a26aaa0990c3e6c4e66b9e
6ea49a68a9288ef26147c8190722b81a13daf22e
refs/heads/master
2021-01-10T08:20:13.857371
2015-05-26T08:20:16
2015-05-26T08:20:16
36,281,901
0
0
null
null
null
null
UTF-8
C++
false
false
1,203
cpp
#include "FileReader.h" #include <fstream> #include "cocos2d.h" #include <stdio.h> using namespace cocos2d; using namespace std; FileReader::FileReader(){ } void FileReader::readFile(){ string line; ifstream myfile("HightScore.txt"); if (myfile.is_open()){ while (getline(myfile, line)) { mFileContents.push_back(line); } myfile.close(); } for (int i = 0; i < mFileContents.size(); i++) { log("%s",mFileContents.at(i).c_str()); } } void FileReader::writeFile(string data){ ofstream myfile("HightScore.txt"); if (myfile.is_open()) { myfile << data; myfile.close(); } readFile(); /*CCFileUtils *sharedFileUtils = CCFileUtils::sharedFileUtils(); string line; string path = sharedFileUtils->fullPathForFilename("encoderTest.csv"); ifstream myfile(path.c_str()); ofstream outfile("filedamahoa.csv"); if (myfile.is_open()) { while (getline(myfile, line)) { CCLog("Read: %s", line.c_str()); string temp = convertBinaryToASCII(line); outfile << temp << "\n"; } myfile.close(); outfile.close(); } */ /*FILE *outfile; outfile = fopen("HightScore.txt", "w"); for (int i = 0; i<10; i++) { fprintf(outfile, "%d\n", i + 1); } fclose(outfile);*/ }
[ "13520079@gm.uit.edu.vn" ]
13520079@gm.uit.edu.vn
704d838648b05a8cb3452820a66b711b6a7f8db6
0a4541e219bbfe9296cc659618dd4a91c81e0d56
/K2D/stdcommon.h
79db62bcbe9ee8992c66289fab6ae09a8a292b39
[]
no_license
karikera/ken
e07b8858f63d839ac1cc9b69c648897644d5bfe2
c41bee5f2da2b8e99d0b9284a53404218c4a6869
refs/heads/master
2023-04-27T17:48:03.681745
2023-04-17T09:20:50
2023-04-17T09:20:50
182,513,850
4
0
null
null
null
null
UTF-8
C++
false
false
627
h
#pragma once #include <KR3/main.h> namespace kr { inline bool kr_fopen_read(FILE ** file, pcstr16 filename) noexcept { #ifdef WIN32 if (_wfopen_s(file, (const wchar_t*)filename, L"rb") != 0) return false; #else *file = fopen(TSZ() << toUtf8((Text16)filename), "rb"); if (*file == nullptr) return false; #endif return true; } inline bool kr_fopen_write(FILE ** file, pcstr16 filename) noexcept { #ifdef WIN32 if (_wfopen_s(file, (const wchar_t*)filename, L"wb") != 0) return false; #else *file = fopen(TSZ() << toUtf8((Text16)filename), "wb"); if (*file == nullptr) return false; #endif return true; } }
[ "karikera3@hotmail.com" ]
karikera3@hotmail.com
40df1ff2661ec03f1d935d64f2caaf85aa837401
f42f97a97a0b446dd793ed33430a4db048643a80
/test/test_gui.cpp
ad87726e24edb104bd5e75f46be9133043e5a45e
[]
no_license
Dwillnio/ConBox
b729066415cca6eeec1d5500ee5d57ae90c83974
a361359cbebfcbe274ec07381e44c83c3acad745
refs/heads/master
2022-11-13T23:06:13.270975
2020-07-12T14:06:04
2020-07-12T14:06:04
268,073,456
0
0
null
null
null
null
UTF-8
C++
false
false
49
cpp
#include "test_gui.h" test_gui::test_gui() { }
[ "dwillnio@gmx.de" ]
dwillnio@gmx.de
34ebce1ebd02e43ca54fcc193fd3dad2434f5a08
da640365b9dffadf4088f4960ebb4768d2fb5ca5
/hashchain.h
12ba6c01113cfdd7315f97bda7cb9a90ad294852
[]
no_license
thienhoang23/CS170-Proj1
eebb8693018f21279f5f835a0135cfc8bebdb8f4
11c93794f42a2ad9493564b7ed51835c2df4929d
refs/heads/master
2021-01-20T00:22:20.686300
2017-04-27T09:12:39
2017-04-27T09:12:39
89,123,547
0
0
null
null
null
null
UTF-8
C++
false
false
600
h
/** * Code is based on *http://www.algolist.net/Data_structures/Hash_table/Chaining * **/ class LinkedHashEntry { private: int key; int value; LinkedHashEntry *next; public: LinkedHashEntry(int key, int value); int getKey(); int getValue(); void setValue(int value); LinkedHashEntry *getNext(); void setNext(LinkedHashEntry *next); }; class HashMap { private: LinkedHashEntry **table; public: HashMap(); int get(int key); void put(int key, int value); bool remove(int key); ~HashMap(); };
[ "tonyhoang2308@gmail.com" ]
tonyhoang2308@gmail.com
0850f73c93571eaa108e42b5390397fa821f0baf
7180e1ed2d9b60f3d3b42fbf04416439b91f2520
/main/main.cpp
c99051a2c90d4ab80278bc5b08e2edce2ef67157
[]
no_license
hippeus/cpp_skeleton
0ff38bc98a2c6619622fa90b618e15c60cd726b5
8eeace56aa337ade32b8052db400f50b80708927
refs/heads/master
2021-06-17T03:59:51.615939
2017-05-30T02:34:39
2017-05-30T02:34:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
145
cpp
#include <iostream> #include <cassert> #include "liba/a.hpp" int main() { std::cout << "skel: Hello world\n"; SkelA a{}; a.f(); return 0; }
[ "plachta.maciej@gmail.com" ]
plachta.maciej@gmail.com
74bcb0b7420f22114a4084d2e3a028a196adac22
556f5f9648be5f847d68b2e8513229f899e09bfc
/service/common/common_func.cpp
bc02fe5f204a48502113e965b38ffeed22c4d785
[]
no_license
hermixy/C
40d704ba38878e7785e95470108fc9e3dd13a987
4d1063106ebc19d9cde4f18ef5f6b6c7b9502332
refs/heads/master
2020-04-27T13:03:36.409527
2019-03-06T12:41:55
2019-03-06T12:41:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,295
cpp
#include <cstdlib> #include <cstring> #include "common_func.h" uint64_t time_from_uuid(uint64_t uuid) { uint64_t EPOCH = 1420864633000; uint64_t truncation = uuid & 0x7FFFFFFFFFC00000 ; uint64_t shifted_timestamp_in_ms = truncation >> 22 ; uint64_t unix_timestamp = ( shifted_timestamp_in_ms + EPOCH ) / 1000 ; return unix_timestamp; } /* * 多路归并算法. 这是一个古典算法, 但也包含了部分青驿业务逻辑. * * 每一路链表元素内部有序, 依次扫描每一路的元素. 扫描过程中保留该路下一个可能 * 选出元素的索引, 一旦被选中, 索引向后更新一位. * * 假如来自于不同路的元素值相等, 古典算法中并未给出排序的唯一答案. 本算法中结 * 合青驿实际使用场景, 采用了排除重复的方式, 放弃后出现的同值元素. * * 例如, 青驿用户在首页 Timeline 中可拉取到好友和旅行地的推送文章. 假设来自于 * 某旅行地的文章恰好同是他关注的好友所发布的, 那么该用户将拉取到2篇完全一样的 * 文章在相邻的位置上, 而这是违背了产品初衷的. * * 另外, 在比较2个元素的先后顺序时, 青驿的基准是元素ID对应的文章的发布时间. 由 * 于本算法没有额外引入这类参数, 所以使用的是基于元素值反向推算出该时间. * */ int multi_merge(uint64_t in_list[][MAX_ELEMENT_NUM_IN_A_LINE], int in_list_num, uint64_t *out_list, int out_list_size, int *in_list_x, int *in_list_y, int start_idx, int req_len) { if (in_list == NULL || out_list == NULL || out_list_size < req_len) return -1; int saved_len = 0, merged_len = 0; int curr_idx_in_list = 0; int idxs[MAX_LINE_NUM]; memset(idxs, 0, sizeof(idxs[0]) * in_list_num); uint64_t max_id = 0; uint64_t max_time = 0; int max_idx = -1; uint64_t last_merged_id = 0 ; while (saved_len < req_len) { max_time = 0; max_idx = -1; for (int i = 0; i < in_list_num; i++) { // 第 i 路链表待扫描元素的索引. curr_idx_in_list = idxs[i]; // 每路链表的末尾以0元素值代表结束. if (in_list[i][curr_idx_in_list] == 0) { continue; } uint64_t time = time_from_uuid(in_list[i][curr_idx_in_list]); if (time > max_time) { max_time = time; max_id = in_list[i][curr_idx_in_list]; max_idx = i; } } if (max_idx == -1) break; // 将当前选出元素所在链表的待扫描索引下移一位. idxs[max_idx]++; // 本归并排序算法不支持出现2个值相同的元素. 跳过. if ( max_id == last_merged_id ) continue ; last_merged_id = max_id ; // 查看当前候选元素的索引是否满足要求. if (merged_len++ < start_idx) continue; // 选出符合条件的元素. in_list_x[saved_len] = max_idx ; in_list_y[saved_len] = idxs[max_idx] - 1 ; out_list[saved_len] = max_id; saved_len ++ ; } // 结尾标志 out_list[saved_len] = 0; return saved_len; }
[ "cky951010@163.com" ]
cky951010@163.com
60b2e270a8b6f86eb130998a2c9e497a09d588a7
dfb0517789d0b083297ca85d81b15a16a9c06c9e
/source/text_utils/shader.hpp
facaef8bc632600120a376574048de78e17b321e
[]
no_license
tobwik/DGIProject
dff86c0e6904e0f5481cc9df01474718bab6779e
a6bf1650ac1eac2b06fdb9808e48c991c0cfc224
refs/heads/master
2020-12-28T22:53:12.869447
2014-06-12T15:02:26
2014-06-12T15:02:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
137
hpp
#ifndef SHADER_HPP #define SHADER_HPP GLuint LoadShaders2(const char * vertex_file_path,const char * fragment_file_path); #endif
[ "tob.wikstrom@gmail.com" ]
tob.wikstrom@gmail.com
107461175c798bb92daefb6d9c1f5480438abae5
28dba754ddf8211d754dd4a6b0704bbedb2bd373
/Topcoder/ExtendedDominoes.cpp
f92eef75212978efe09e607fe775cbd575cf6192
[]
no_license
zjsxzy/algo
599354679bd72ef20c724bb50b42fce65ceab76f
a84494969952f981bfdc38003f7269e5c80a142e
refs/heads/master
2023-08-31T17:00:53.393421
2023-08-19T14:20:31
2023-08-19T14:20:31
10,140,040
0
1
null
null
null
null
UTF-8
C++
false
false
2,232
cpp
#line 2 "ExtendedDominoes.cpp" #include <map> #include <set> #include <list> #include <cmath> #include <queue> #include <stack> #include <bitset> #include <vector> #include <cstdio> #include <string> #include <sstream> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; class ExtendedDominoes { public: long long countCycles(vector <string> pieces) { } // 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 long long &Expected, const long long &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 Arr0[] = {"12","25","45","24","28","18"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 3LL; verify_case(0, Arg1, countCycles(Arg0)); } void test_case_1() { string Arr0[] = {"01","12","23","34","45"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 0LL; verify_case(1, Arg1, countCycles(Arg0)); } void test_case_2() { string Arr0[] = {"09","12","24","14","57","79","05"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 1LL; verify_case(2, Arg1, countCycles(Arg0)); } void test_case_3() { string Arr0[] = {"34","35","36","37","45","46","47","56","57","67"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 243LL; verify_case(3, Arg1, countCycles(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { ExtendedDominoes ___test; for (int i = 0; i <= 5; i++) ___test.run_test(i); return 0; } // END CUT HERE
[ "zjsxzy@gmail.com" ]
zjsxzy@gmail.com
04b0db9fa16c2919e7d257d3f865186d9ea1908e
6c376312457b8af43e372d10bbe6ba29f58cf99d
/DirectX11_BaseSystem/Include/Havok_SDK/Common/Base/Math/Vector/hkPackedVector3.h
c48c28e1a675e16903d564d37aaacb94cabd4a56
[]
no_license
kururu-zzz/DirectWrite
f3599ae83c0edefb574ccd9c0026a151a68fbfbf
19fe366832ec04cbcdb79db799eb8088ced376ad
refs/heads/master
2021-01-10T08:00:53.148408
2015-12-17T04:51:31
2015-12-17T04:51:31
48,152,937
1
0
null
null
null
null
UTF-8
C++
false
false
10,977
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2014 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKMATH_MATH_PACKED_VECTOR3_H #define HKMATH_MATH_PACKED_VECTOR3_H #include <Common/Base/Math/Vector/hkIntVector.h> /// Compressed 8 byte sized float vector3 with 1 sign bit, 15 bit mantissa and a shared 8 bit exponent. /// /// This class is great to store positions or normals using an accuracy of 1.0f/32000 /// (e.g., a position which is 100meters off the origin has a precision of +-3mm. /// pack() takes a little time (~100-200 cycles), unpack is pretty fast on SIMD platforms (6 assembly instructions). /// See also hkPackedUnitVector and hkVectorPackUtil. struct HK_EXPORT_COMMON hkPackedVector3 { public: HK_DECLARE_REFLECTION(); /// pack a vector4 into this void pack( hkVector4fParameter v ); /// pack a vector4 into this void pack( hkVector4dParameter v ); /// inline version of pack, you need to include #include <Common/Base/Math/Vector/hkPackedVector3.inl> to use this HK_FORCE_INLINE void _pack( hkVector4fParameter v ); HK_FORCE_INLINE void _pack( hkVector4dParameter v ); typedef union { hkInt16 i16[4]; hkUint32 u32[2]; } s2u; /// unpack HK_FORCE_INLINE void unpack( hkVector4f& vOut ) const { // bring m_values into the high bits hkIntVector iv; { const s2u* values = (const s2u*)m_values; iv.loadNotAligned<2>( values->u32 ); // loads 2*uint32 = 4*uint16 hkIntVector zero; zero.setZero(); iv.setCombineHead16To32( iv, zero ); } // convert to integer hkVector4f v; iv.convertS32ToF32( v ); // calculate the exp correction hkIntVector iexp; iexp.setBroadcast<3>(iv); hkVector4f vexp; iexp.storeAsFloat32BitRepresentation( vexp ); v.mul( vexp ); vOut = v; } /// unpack HK_FORCE_INLINE void unpack( hkVector4d& vOut ) const { hkVector4f v; unpack(v); hkVector4fUtil::convertVector(v,vOut); } /// unpack assuming this is aligned to a 16 byte boundary HK_FORCE_INLINE void unpackAligned16( hkVector4f& vOut ) const { // bring m_values into the high bits hkIntVector iv; { const s2u* values = (const s2u*)m_values; iv.load<2>( values->u32 ); // loads 2*uint32 = 4*uint16 hkIntVector zero; zero.setZero(); iv.setCombineHead16To32( iv, zero ); } // convert to integer hkVector4f v; iv.convertS32ToF32( v ); // calculate the exp correction hkIntVector iexp; iexp.setBroadcast<3>(iv); hkVector4f vexp; iexp.storeAsFloat32BitRepresentation( vexp ); v.mul( vexp ); vOut = v; } /// unpack assuming this is aligned to a 16 byte boundary HK_FORCE_INLINE void unpackAligned16( hkVector4d& vOut ) const { hkVector4f v; unpackAligned16(v); hkVector4fUtil::convertVector(v,vOut); } public: HK_ALIGN( hkInt16 m_values[4], 8 ); }; /// Compressed 4 byte sized float vector3 with 1 sign bit, 7 bit mantissa and a shared 8 bit exponent. /// /// This class is great to store velocities in a network environment. /// pack() takes a little time (~20 cycles), unpack is pretty fast on SIMD platforms (7 assembly instructions). /// See also hkPackedUnitVector and hkVectorPackUtil. struct HK_EXPORT_COMMON hkPackedVector8_3 { HK_DECLARE_REFLECTION(); HK_DECLARE_POD_TYPE(); // ------------------------------------------------------------------------------------------------------------- // Functions // ------------------------------------------------------------------------------------------------------------- /// pack a vector4 into this void pack( hkVector4fParameter v ); void pack( hkVector4dParameter v ); /// inline version of pack, you need to include #include <Common/Base/Math/Vector/hkPackedVector3.inl> to use this HK_FORCE_INLINE void _pack( hkVector4fParameter v ); HK_FORCE_INLINE void _pack( hkVector4dParameter v ); typedef union { hkInt8 i8[4]; hkUint32 u32; } s2u; /// unpack HK_FORCE_INLINE void unpack( hkVector4f& vOut ) const { // bring m_values into the high bits hkIntVector iv; { iv.load<1>( &m_values.m_u32 ); // loads 1*uint32 = 4*uint8 hkIntVector zero; zero.setZero(); iv.setCombineHead8To16( iv, zero ); iv.setCombineHead16To32( iv, zero ); } // convert to float hkVector4f v; iv.convertS32ToF32( v ); // calculate the exp correction hkIntVector iexp; iexp.setBroadcast<3>(iv); iexp.setShiftRight32<1>(iexp); // shift the exponent to the right place hkVector4f vexp; iexp.storeAsFloat32BitRepresentation( vexp ); vOut.setMul( v, vexp ); } HK_FORCE_INLINE void unpack( hkVector4d& vOut ) const { hkVector4f v; unpack(v); hkVector4fUtil::convertVector(v,vOut); } HK_FORCE_INLINE void setZero() { m_values.m_u32 = 0; } // ------------------------------------------------------------------------------------------------------------- // Fields // ------------------------------------------------------------------------------------------------------------- union { hkInt8 m_u8[4]; hkUint32 m_u32; } m_values; //+overridetype(hkInt8[4]) }; extern HK_EXPORT_COMMON const hkUint32 hkPackedUnitVector_m_offset[4]; #ifdef HK_ARCH_ARM # define HK_VECTOR4f_ALIGN_CHECK 0x7 #else # define HK_VECTOR4f_ALIGN_CHECK (HK_FLOAT_ALIGNMENT-1) #endif /// Store a set of unit values (normals/quaternions (1-4 floats)) using 15 bit accuracy template<int NUM_ELEMS> class hkPackedUnitVector { public: HK_FORCE_INLINE void set(int x, int y, int z, int w = int(0)) { set(hkFloat32(x), hkFloat32(y), hkFloat32(z), hkFloat32(w)); } HK_FORCE_INLINE void set(hkFloat32 x, hkFloat32 y, hkFloat32 z, hkFloat32 w = hkFloat32(0)) { HK_COMPILE_TIME_ASSERT( NUM_ELEMS >= 3 ); hkVector4f v; v.set(x,y,z,w); pack(v); } HK_FORCE_INLINE void set(hkDouble64 x, hkDouble64 y, hkDouble64 z, hkDouble64 w = hkDouble64(0)) { HK_COMPILE_TIME_ASSERT( NUM_ELEMS >= 3 ); hkVector4d v; v.set(x,y,z,w); pack(v); } HK_FORCE_INLINE void set(hkSimdFloat32Parameter x, hkSimdFloat32Parameter y, hkSimdFloat32Parameter z, hkSimdFloat32Parameter w) { HK_COMPILE_TIME_ASSERT( NUM_ELEMS >= 4 ); hkVector4f v; v.set(x,y,z,w); pack(v); } HK_FORCE_INLINE void set(hkSimdDouble64Parameter x, hkSimdDouble64Parameter y, hkSimdDouble64Parameter z, hkSimdDouble64Parameter w) { HK_COMPILE_TIME_ASSERT( NUM_ELEMS >= 4 ); hkVector4d v; v.set(x,y,z,w); pack(v); } HK_FORCE_INLINE void setZero() { m_vec[0] = 0x8000; if ( NUM_ELEMS >=2 ) m_vec[1%NUM_ELEMS] = 0x8000; if ( NUM_ELEMS >=3 ) m_vec[2%NUM_ELEMS] = 0x8000; if ( NUM_ELEMS >=4 ) m_vec[3%NUM_ELEMS] = 0x8000; } /// pack the vector HK_FORCE_INLINE void pack( hkVector4fParameter vIn ) { hkVector4f v; v.setMul( hkVector4f::getConstant<HK_QUADREAL_PACK16_UNIT_VEC>(), vIn ); hkIntVector iv32; iv32.setConvertF32toS32( v ); hkIntVector packedOffset; packedOffset.load<4>(hkPackedUnitVector_m_offset); iv32.setAddU32(iv32, packedOffset); #if (HK_ENDIAN_BIG) const int hoffset = 0; // extract the high word #else const int hoffset = 1; #endif m_vec[0] = iv32.getU16<hoffset>(); if ( NUM_ELEMS >=2 ) m_vec[1%NUM_ELEMS] = iv32.getU16<2+hoffset>(); if ( NUM_ELEMS >=3 ) m_vec[2%NUM_ELEMS] = iv32.getU16<4+hoffset>(); if ( NUM_ELEMS >=4 ) m_vec[3%NUM_ELEMS] = iv32.getU16<6+hoffset>(); } /// pack the vector HK_FORCE_INLINE void pack( hkVector4dParameter vIn ) { hkVector4d v; v.setMul( hkVector4d::getConstant<HK_QUADREAL_PACK16_UNIT_VEC>(), vIn ); hkIntVector iv32; iv32.setConvertF32toS32( v ); hkIntVector packedOffset; packedOffset.load<4>(hkPackedUnitVector_m_offset); iv32.setAddU32(iv32, packedOffset); #if (HK_ENDIAN_BIG) const int hoffset = 0; // extract the high word #else const int hoffset = 1; #endif m_vec[0] = iv32.getU16<hoffset>(); if ( NUM_ELEMS >=2 ) m_vec[1%NUM_ELEMS] = iv32.getU16<2+hoffset>(); if ( NUM_ELEMS >=3 ) m_vec[2%NUM_ELEMS] = iv32.getU16<4+hoffset>(); if ( NUM_ELEMS >=4 ) m_vec[3%NUM_ELEMS] = iv32.getU16<6+hoffset>(); } // unpack HK_FORCE_INLINE void unpack( hkVector4f* HK_RESTRICT vecOut ) const { HK_ASSERT( 0xf04523ef, (hkUlong(vecOut) & HK_VECTOR4f_ALIGN_CHECK) == 0 ); hkIntVector zero; zero.setZero(); hkIntVector iv16; iv16.loadNotAligned<(NUM_ELEMS+1)/2>((const hkUint32*)m_vec); hkIntVector iv32; iv32.setCombineHead16To32( iv16, zero ); hkIntVector packedOffset; packedOffset.load<4>(hkPackedUnitVector_m_offset); iv32.setAddU32( iv32, packedOffset); hkVector4f v; iv32.convertS32ToF32( v ); vecOut->setMul( hkVector4f::getConstant<HK_QUADREAL_UNPACK16_UNIT_VEC>(), v ); } // unpack HK_FORCE_INLINE void unpack( hkVector4d* HK_RESTRICT vecOut ) const { hkVector4f v; unpack(&v); hkVector4fUtil::convertVector(v,*vecOut); } /// Gets the vector assuming that this instance is aligned on a 16 byte boundary HK_FORCE_INLINE void unpackAligned16( hkVector4f* HK_RESTRICT vecOut ) const { HK_COMPILE_TIME_ASSERT( NUM_ELEMS <= 4 ); HK_ASSERT( 0xf04523ed, (hkUlong(this) & 0xf) == 0 ); HK_ASSERT( 0xf04523ef, (hkUlong(vecOut) & HK_VECTOR4f_ALIGN_CHECK) == 0 ); hkIntVector iv16; iv16.loadNotAligned<(NUM_ELEMS+1)/2>((const hkUint32*)m_vec); hkIntVector zero; zero.setZero(); hkIntVector iv32; iv32.setCombineHead16To32( iv16, zero ); hkIntVector packedOffset; packedOffset.load<4>(hkPackedUnitVector_m_offset); iv32.setAddU32( iv32, packedOffset); hkVector4f v; iv32.convertS32ToF32( v ); vecOut->setMul( hkVector4f::getConstant<HK_QUADREAL_UNPACK16_UNIT_VEC>(), v ); } /// Gets the vector assuming that this instance is aligned on a 16 byte boundary HK_FORCE_INLINE void unpackAligned16( hkVector4d* HK_RESTRICT vecOut ) const { hkVector4f v; unpack(&v); hkVector4fUtil::convertVector(v,*vecOut); } protected: hkUint16 m_vec[NUM_ELEMS]; }; #undef HK_VECTOR4f_ALIGN_CHECK #endif //HKMATH_MATH_PACKED_VECTOR3_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907) * * Confidential Information of Havok. (C) Copyright 1999-2014 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ "kurukuru.0844808@gmail.com" ]
kurukuru.0844808@gmail.com
2e8a1d739a78f5e5e44b49c299ff19e2231a34bb
40b99b8ddf58ec864cd5d15459e2ec19999b8b2d
/Blaze/io.hpp
c7986a7d8047e34b0d7f8822112648b025dd52c8
[ "MIT" ]
permissive
Stryxus/Blaze
c8fd07b6a276f51bd08152af1a7ea4d39f4d346f
73f26316e4146596aeb82f77d054cf4e472a2d3d
refs/heads/master
2023-07-15T02:05:49.943983
2021-08-15T14:03:30
2021-08-15T14:03:30
256,217,195
1
0
null
null
null
null
UTF-8
C++
false
false
1,337
hpp
#pragma once bool file_exists(const string& file_path); void create_file(const string& file_path); // enum class BYTE_MAGNITUDE { BYTE, KILO_BYTE, MEGA_BYTE, GIGA_BYTE, TERRA_BYTE, PETTA_BYTE, EXA_BYTE, ZETTA_BYTE, YOTTA_BYTE }; enum class BIT_MAGNITUDE { BIT, KILO_BIT, MEGA_BIT, GIGA_BIT, TERRA_BIT, PETTA_BIT, EXA_BIT, ZETTA_BIT, YOTTA_BIT }; // void convert_data_magnitude_to_bits(unsigned long long value, BYTE_MAGNITUDE from_magnitude, BIT_MAGNITUDE to_magnitude); void convert_data_magnitude_to_bytes(unsigned long long value, BIT_MAGNITUDE from_magnitude, BYTE_MAGNITUDE to_magnitude); void convert_data_magnitude_in_bits(unsigned long long value, BIT_MAGNITUDE from_magnitude, BIT_MAGNITUDE to_magnitude); void convert_data_magnitude_in_bytes(unsigned long long value, BYTE_MAGNITUDE from_magnitude, BYTE_MAGNITUDE to_magnitude); double convert_data_magnitude_to_bits_copy(double value, BYTE_MAGNITUDE from_magnitude, BIT_MAGNITUDE to_magnitude); double convert_data_magnitude_to_bytes_copy(double value, BIT_MAGNITUDE from_magnitude, BYTE_MAGNITUDE to_magnitude); double convert_data_magnitude_in_bits_copy(double value, BIT_MAGNITUDE from_magnitude, BIT_MAGNITUDE to_magnitude); double convert_data_magnitude_in_bytes_copy(double value, BYTE_MAGNITUDE from_magnitude, BYTE_MAGNITUDE to_magnitude); //
[ "connor_shearer@outlook.com" ]
connor_shearer@outlook.com
5d84e2b422fd5e9c1ef5173beb2c1cb39f84262a
e470af618dd0811f6a7056ef39b9e6d670b5d6c7
/src/2439. Minimize Maximum of Array.cpp
d2759109153c18340c4c140925f7cb3a4ae77f21
[]
no_license
Lilybon/leetcode
48a9388f740ee366e257a05e6751d1e3e76e3e70
21aafd7d7d30d4b49b5f3d7c8fcf16df42300088
refs/heads/master
2023-08-25T01:51:57.392834
2023-08-21T03:34:45
2023-08-21T03:34:45
159,440,633
1
0
null
2023-08-11T12:07:13
2018-11-28T03:54:02
JavaScript
UTF-8
C++
false
false
267
cpp
class Solution { public: int minimizeArrayValue(vector<int>& nums) { long sum = 0, ans = 0; for (int i = 0; i < nums.size(); ++i) { sum += nums[i]; ans = max(ans, (sum + i) / (i + 1)); } return ans; } };
[ "zebra10029@gmail.com" ]
zebra10029@gmail.com
923255d8984f4a2be16b4175beaa426089e74358
23b8b57057b3b758f01dcdfde33cc03becb4caf6
/llvm/projects/compiler-rt/test/meds/TestCases/ASan/contiguous_container.cc
a5c64d24096daffb4aa3e33b4011cf1073cf3fa6
[ "NCSA", "MIT" ]
permissive
purdue-secomp-lab/MEDS
0ab642a86dabe0af36f236043e9ea82dfac54174
f05ef7da40fa6214000e51c908ab26e16a21c512
refs/heads/master
2022-06-09T19:01:48.875018
2022-06-01T14:18:15
2022-06-01T14:18:15
117,601,008
38
14
null
2022-06-01T14:18:17
2018-01-15T22:13:57
C++
UTF-8
C++
false
false
2,665
cc
// RUN: %clangxx_meds -fexceptions -O %s -o %t && %run %t // // Test __sanitizer_annotate_contiguous_container. #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <sanitizer/asan_interface.h> void TestContainer(size_t capacity) { char *beg = new char[capacity]; char *end = beg + capacity; char *mid = beg + capacity; char *old_mid = 0; for (int i = 0; i < 10000; i++) { size_t size = rand() % (capacity + 1); assert(size <= capacity); old_mid = mid; mid = beg + size; __sanitizer_annotate_contiguous_container(beg, end, old_mid, mid); for (size_t idx = 0; idx < size; idx++) assert(!__asan_address_is_poisoned(beg + idx)); for (size_t idx = size; idx < capacity; idx++) assert(__asan_address_is_poisoned(beg + idx)); assert(__sanitizer_verify_contiguous_container(beg, mid, end)); assert(NULL == __sanitizer_contiguous_container_find_bad_address(beg, mid, end)); if (mid != beg) { assert(!__sanitizer_verify_contiguous_container(beg, mid - 1, end)); assert(mid - 1 == __sanitizer_contiguous_container_find_bad_address( beg, mid - 1, end)); } if (mid != end) { assert(!__sanitizer_verify_contiguous_container(beg, mid + 1, end)); assert(mid == __sanitizer_contiguous_container_find_bad_address( beg, mid + 1, end)); } } // Don't forget to unpoison the whole thing before destroing/reallocating. __sanitizer_annotate_contiguous_container(beg, end, mid, end); for (size_t idx = 0; idx < capacity; idx++) assert(!__asan_address_is_poisoned(beg + idx)); delete[] beg; } __attribute__((noinline)) void Throw() { throw 1; } __attribute__((noinline)) void ThrowAndCatch() { try { Throw(); } catch(...) { } } void TestThrow() { char x[32]; __sanitizer_annotate_contiguous_container(x, x + 32, x + 32, x + 14); assert(!__asan_address_is_poisoned(x + 13)); assert(__asan_address_is_poisoned(x + 14)); ThrowAndCatch(); assert(!__asan_address_is_poisoned(x + 13)); // FIXME: invert the assertion below once we fix // https://code.google.com/p/address-sanitizer/issues/detail?id=258 // This assertion works only w/o UAR. if (!__asan_get_current_fake_stack()) assert(!__asan_address_is_poisoned(x + 14)); __sanitizer_annotate_contiguous_container(x, x + 32, x + 14, x + 32); assert(!__asan_address_is_poisoned(x + 13)); assert(!__asan_address_is_poisoned(x + 14)); } int main(int argc, char **argv) { int n = argc == 1 ? 128 : atoi(argv[1]); for (int i = 0; i <= n; i++) TestContainer(i); TestThrow(); }
[ "wookhyunhan@gmail.com" ]
wookhyunhan@gmail.com
68396db7aa893df1461f769ee4a70194ccdc625f
900eeb54ac340c17f5921a1035248463046efe48
/SDK/PWND_MediaAssets_functions.cpp
7ae4ff25693f4a70ec462d41be854306f8024c59
[]
no_license
hinnie123/PWND_SDK
f94c5f8ebc99fd68aac02928550cf9401a7ac18d
b7cf225765a8083ba0a358ecb0067eb9ce1964d6
refs/heads/master
2020-04-02T04:44:07.654425
2018-10-21T17:01:00
2018-10-21T17:01:00
154,031,939
2
4
null
null
null
null
UTF-8
C++
false
false
39,586
cpp
// PWND (4.17.2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function MediaAssets.FileMediaSource.SetFilePath // (Final, Native, Public, BlueprintCallable) // Parameters: // struct FString Path (Parm, ZeroConstructor) void UFileMediaSource::SetFilePath(const struct FString& Path) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.FileMediaSource.SetFilePath"); UFileMediaSource_SetFilePath_Params params; params.Path = Path; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MediaAssets.MediaOverlays.GetTexts // (Final, Native, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintPure, Const) // Parameters: // TArray<struct FMediaPlayerOverlay> OutTexts (Parm, OutParm, ZeroConstructor) // struct FTimespan Time (Parm) void UMediaOverlays::GetTexts(const struct FTimespan& Time, TArray<struct FMediaPlayerOverlay>* OutTexts) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaOverlays.GetTexts"); UMediaOverlays_GetTexts_Params params; params.Time = Time; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (OutTexts != nullptr) *OutTexts = params.OutTexts; } // Function MediaAssets.MediaOverlays.GetSubtitles // (Final, Native, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintPure, Const) // Parameters: // TArray<struct FMediaPlayerOverlay> OutSubtitles (Parm, OutParm, ZeroConstructor) // struct FTimespan Time (Parm) void UMediaOverlays::GetSubtitles(const struct FTimespan& Time, TArray<struct FMediaPlayerOverlay>* OutSubtitles) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaOverlays.GetSubtitles"); UMediaOverlays_GetSubtitles_Params params; params.Time = Time; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (OutSubtitles != nullptr) *OutSubtitles = params.OutSubtitles; } // Function MediaAssets.MediaOverlays.GetCaptions // (Final, Native, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintPure, Const) // Parameters: // TArray<struct FMediaPlayerOverlay> OutCaptions (Parm, OutParm, ZeroConstructor) // struct FTimespan Time (Parm) void UMediaOverlays::GetCaptions(const struct FTimespan& Time, TArray<struct FMediaPlayerOverlay>* OutCaptions) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaOverlays.GetCaptions"); UMediaOverlays_GetCaptions_Params params; params.Time = Time; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (OutCaptions != nullptr) *OutCaptions = params.OutCaptions; } // Function MediaAssets.MediaPlayer.SupportsSeeking // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::SupportsSeeking() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.SupportsSeeking"); UMediaPlayer_SupportsSeeking_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.SupportsScrubbing // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::SupportsScrubbing() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.SupportsScrubbing"); UMediaPlayer_SupportsScrubbing_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.SupportsRate // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // float Rate (Parm, ZeroConstructor, IsPlainOldData) // bool Unthinned (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::SupportsRate(float Rate, bool Unthinned) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.SupportsRate"); UMediaPlayer_SupportsRate_Params params; params.Rate = Rate; params.Unthinned = Unthinned; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.SetVideoTexture // (Final, Native, Public, BlueprintCallable) // Parameters: // class UMediaTexture* NewTexture (Parm, ZeroConstructor, IsPlainOldData) void UMediaPlayer::SetVideoTexture(class UMediaTexture* NewTexture) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.SetVideoTexture"); UMediaPlayer_SetVideoTexture_Params params; params.NewTexture = NewTexture; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MediaAssets.MediaPlayer.SetSoundWave // (Final, Native, Public, BlueprintCallable) // Parameters: // class UMediaSoundWave* NewSoundWave (Parm, ZeroConstructor, IsPlainOldData) void UMediaPlayer::SetSoundWave(class UMediaSoundWave* NewSoundWave) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.SetSoundWave"); UMediaPlayer_SetSoundWave_Params params; params.NewSoundWave = NewSoundWave; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MediaAssets.MediaPlayer.SetRate // (Final, Native, Public, BlueprintCallable) // Parameters: // float Rate (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::SetRate(float Rate) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.SetRate"); UMediaPlayer_SetRate_Params params; params.Rate = Rate; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.SetOverlays // (Final, Native, Public, BlueprintCallable) // Parameters: // class UMediaOverlays* NewOverlays (Parm, ZeroConstructor, IsPlainOldData) void UMediaPlayer::SetOverlays(class UMediaOverlays* NewOverlays) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.SetOverlays"); UMediaPlayer_SetOverlays_Params params; params.NewOverlays = NewOverlays; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MediaAssets.MediaPlayer.SetLooping // (Final, Native, Public, BlueprintCallable) // Parameters: // bool Looping (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::SetLooping(bool Looping) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.SetLooping"); UMediaPlayer_SetLooping_Params params; params.Looping = Looping; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.SetDesiredPlayerName // (Final, Native, Public, BlueprintCallable) // Parameters: // struct FName PlayerName (Parm, ZeroConstructor, IsPlainOldData) void UMediaPlayer::SetDesiredPlayerName(const struct FName& PlayerName) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.SetDesiredPlayerName"); UMediaPlayer_SetDesiredPlayerName_Params params; params.PlayerName = PlayerName; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MediaAssets.MediaPlayer.SelectTrack // (Final, Native, Public, BlueprintCallable) // Parameters: // EMediaPlayerTrack TrackType (Parm, ZeroConstructor, IsPlainOldData) // int TrackIndex (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::SelectTrack(EMediaPlayerTrack TrackType, int TrackIndex) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.SelectTrack"); UMediaPlayer_SelectTrack_Params params; params.TrackType = TrackType; params.TrackIndex = TrackIndex; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.Seek // (Final, Native, Public, HasOutParms, HasDefaults, BlueprintCallable) // Parameters: // struct FTimespan Time (ConstParm, Parm, OutParm, ReferenceParm) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::Seek(const struct FTimespan& Time) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.Seek"); UMediaPlayer_Seek_Params params; params.Time = Time; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.Rewind // (Final, Native, Public, BlueprintCallable) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::Rewind() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.Rewind"); UMediaPlayer_Rewind_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.Reopen // (Final, Native, Public, BlueprintCallable) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::Reopen() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.Reopen"); UMediaPlayer_Reopen_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.Previous // (Final, Native, Public, BlueprintCallable) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::Previous() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.Previous"); UMediaPlayer_Previous_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.Play // (Final, Native, Public, BlueprintCallable) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::Play() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.Play"); UMediaPlayer_Play_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.Pause // (Final, Native, Public, BlueprintCallable) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::Pause() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.Pause"); UMediaPlayer_Pause_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.OpenUrl // (Final, Native, Public, BlueprintCallable) // Parameters: // struct FString URL (Parm, ZeroConstructor) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::OpenUrl(const struct FString& URL) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.OpenUrl"); UMediaPlayer_OpenUrl_Params params; params.URL = URL; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.OpenSource // (Final, Native, Public, BlueprintCallable) // Parameters: // class UMediaSource* MediaSource (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::OpenSource(class UMediaSource* MediaSource) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.OpenSource"); UMediaPlayer_OpenSource_Params params; params.MediaSource = MediaSource; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.OpenPlaylistIndex // (Final, Native, Public, BlueprintCallable) // Parameters: // class UMediaPlaylist* InPlaylist (Parm, ZeroConstructor, IsPlainOldData) // int Index (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::OpenPlaylistIndex(class UMediaPlaylist* InPlaylist, int Index) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.OpenPlaylistIndex"); UMediaPlayer_OpenPlaylistIndex_Params params; params.InPlaylist = InPlaylist; params.Index = Index; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.OpenPlaylist // (Final, Native, Public, BlueprintCallable) // Parameters: // class UMediaPlaylist* InPlaylist (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::OpenPlaylist(class UMediaPlaylist* InPlaylist) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.OpenPlaylist"); UMediaPlayer_OpenPlaylist_Params params; params.InPlaylist = InPlaylist; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.OpenFile // (Final, Native, Public, BlueprintCallable) // Parameters: // struct FString FilePath (Parm, ZeroConstructor) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::OpenFile(const struct FString& FilePath) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.OpenFile"); UMediaPlayer_OpenFile_Params params; params.FilePath = FilePath; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.Next // (Final, Native, Public, BlueprintCallable) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::Next() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.Next"); UMediaPlayer_Next_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.IsReady // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::IsReady() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.IsReady"); UMediaPlayer_IsReady_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.IsPreparing // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::IsPreparing() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.IsPreparing"); UMediaPlayer_IsPreparing_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.IsPlaying // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::IsPlaying() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.IsPlaying"); UMediaPlayer_IsPlaying_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.IsPaused // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::IsPaused() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.IsPaused"); UMediaPlayer_IsPaused_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.IsLooping // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::IsLooping() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.IsLooping"); UMediaPlayer_IsLooping_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.GetUrl // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // struct FString ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm) struct FString UMediaPlayer::GetUrl() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.GetUrl"); UMediaPlayer_GetUrl_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.GetTrackLanguage // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // EMediaPlayerTrack TrackType (Parm, ZeroConstructor, IsPlainOldData) // int TrackIndex (Parm, ZeroConstructor, IsPlainOldData) // struct FString ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm) struct FString UMediaPlayer::GetTrackLanguage(EMediaPlayerTrack TrackType, int TrackIndex) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.GetTrackLanguage"); UMediaPlayer_GetTrackLanguage_Params params; params.TrackType = TrackType; params.TrackIndex = TrackIndex; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.GetTrackDisplayName // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // EMediaPlayerTrack TrackType (Parm, ZeroConstructor, IsPlainOldData) // int TrackIndex (Parm, ZeroConstructor, IsPlainOldData) // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UMediaPlayer::GetTrackDisplayName(EMediaPlayerTrack TrackType, int TrackIndex) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.GetTrackDisplayName"); UMediaPlayer_GetTrackDisplayName_Params params; params.TrackType = TrackType; params.TrackIndex = TrackIndex; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.GetTime // (Final, Native, Public, HasDefaults, BlueprintCallable, BlueprintPure, Const) // Parameters: // struct FTimespan ReturnValue (Parm, OutParm, ReturnParm) struct FTimespan UMediaPlayer::GetTime() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.GetTime"); UMediaPlayer_GetTime_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.GetSelectedTrack // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // EMediaPlayerTrack TrackType (Parm, ZeroConstructor, IsPlainOldData) // int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) int UMediaPlayer::GetSelectedTrack(EMediaPlayerTrack TrackType) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.GetSelectedTrack"); UMediaPlayer_GetSelectedTrack_Params params; params.TrackType = TrackType; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.GetReverseRates // (Final, Native, Public, BlueprintCallable) // Parameters: // bool Unthinned (Parm, ZeroConstructor, IsPlainOldData) // struct FFloatRange ReturnValue (Parm, OutParm, ReturnParm) struct FFloatRange UMediaPlayer::GetReverseRates(bool Unthinned) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.GetReverseRates"); UMediaPlayer_GetReverseRates_Params params; params.Unthinned = Unthinned; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.GetRate // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) float UMediaPlayer::GetRate() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.GetRate"); UMediaPlayer_GetRate_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.GetPlayerName // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // struct FName ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FName UMediaPlayer::GetPlayerName() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.GetPlayerName"); UMediaPlayer_GetPlayerName_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.GetNumTracks // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // EMediaPlayerTrack TrackType (Parm, ZeroConstructor, IsPlainOldData) // int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) int UMediaPlayer::GetNumTracks(EMediaPlayerTrack TrackType) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.GetNumTracks"); UMediaPlayer_GetNumTracks_Params params; params.TrackType = TrackType; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.GetForwardRates // (Final, Native, Public, BlueprintCallable) // Parameters: // bool Unthinned (Parm, ZeroConstructor, IsPlainOldData) // struct FFloatRange ReturnValue (Parm, OutParm, ReturnParm) struct FFloatRange UMediaPlayer::GetForwardRates(bool Unthinned) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.GetForwardRates"); UMediaPlayer_GetForwardRates_Params params; params.Unthinned = Unthinned; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.GetDuration // (Final, Native, Public, HasDefaults, BlueprintCallable, BlueprintPure, Const) // Parameters: // struct FTimespan ReturnValue (Parm, OutParm, ReturnParm) struct FTimespan UMediaPlayer::GetDuration() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.GetDuration"); UMediaPlayer_GetDuration_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.GetDesiredPlayerName // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // struct FName ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FName UMediaPlayer::GetDesiredPlayerName() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.GetDesiredPlayerName"); UMediaPlayer_GetDesiredPlayerName_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.Close // (Final, Native, Public, BlueprintCallable) void UMediaPlayer::Close() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.Close"); UMediaPlayer_Close_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MediaAssets.MediaPlayer.CanPlayUrl // (Final, Native, Public, BlueprintCallable) // Parameters: // struct FString URL (Parm, ZeroConstructor) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::CanPlayUrl(const struct FString& URL) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.CanPlayUrl"); UMediaPlayer_CanPlayUrl_Params params; params.URL = URL; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.CanPlaySource // (Final, Native, Public, BlueprintCallable) // Parameters: // class UMediaSource* MediaSource (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::CanPlaySource(class UMediaSource* MediaSource) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.CanPlaySource"); UMediaPlayer_CanPlaySource_Params params; params.MediaSource = MediaSource; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlayer.CanPause // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UMediaPlayer::CanPause() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlayer.CanPause"); UMediaPlayer_CanPause_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlaylist.RemoveAt // (Final, Native, Public, BlueprintCallable) // Parameters: // int Index (Parm, ZeroConstructor, IsPlainOldData) void UMediaPlaylist::RemoveAt(int Index) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlaylist.RemoveAt"); UMediaPlaylist_RemoveAt_Params params; params.Index = Index; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MediaAssets.MediaPlaylist.Remove // (Final, Native, Public, BlueprintCallable) // Parameters: // class UMediaSource* MediaSource (Parm, ZeroConstructor, IsPlainOldData) void UMediaPlaylist::Remove(class UMediaSource* MediaSource) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlaylist.Remove"); UMediaPlaylist_Remove_Params params; params.MediaSource = MediaSource; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MediaAssets.MediaPlaylist.Num // (Final, Native, Public, BlueprintCallable) // Parameters: // int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) int UMediaPlaylist::Num() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlaylist.Num"); UMediaPlaylist_Num_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlaylist.Insert // (Final, Native, Public, BlueprintCallable) // Parameters: // class UMediaSource* MediaSource (Parm, ZeroConstructor, IsPlainOldData) // int Index (Parm, ZeroConstructor, IsPlainOldData) void UMediaPlaylist::Insert(class UMediaSource* MediaSource, int Index) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlaylist.Insert"); UMediaPlaylist_Insert_Params params; params.MediaSource = MediaSource; params.Index = Index; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MediaAssets.MediaPlaylist.GetRandom // (Final, Native, Public, HasOutParms, BlueprintCallable) // Parameters: // int InOutIndex (Parm, OutParm, ZeroConstructor, IsPlainOldData) // class UMediaSource* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) class UMediaSource* UMediaPlaylist::GetRandom(int* InOutIndex) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlaylist.GetRandom"); UMediaPlaylist_GetRandom_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (InOutIndex != nullptr) *InOutIndex = params.InOutIndex; return params.ReturnValue; } // Function MediaAssets.MediaPlaylist.GetPrevious // (Final, Native, Public, HasOutParms, BlueprintCallable) // Parameters: // int InOutIndex (Parm, OutParm, ZeroConstructor, IsPlainOldData) // class UMediaSource* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) class UMediaSource* UMediaPlaylist::GetPrevious(int* InOutIndex) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlaylist.GetPrevious"); UMediaPlaylist_GetPrevious_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (InOutIndex != nullptr) *InOutIndex = params.InOutIndex; return params.ReturnValue; } // Function MediaAssets.MediaPlaylist.GetNext // (Final, Native, Public, HasOutParms, BlueprintCallable) // Parameters: // int InOutIndex (Parm, OutParm, ZeroConstructor, IsPlainOldData) // class UMediaSource* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) class UMediaSource* UMediaPlaylist::GetNext(int* InOutIndex) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlaylist.GetNext"); UMediaPlaylist_GetNext_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (InOutIndex != nullptr) *InOutIndex = params.InOutIndex; return params.ReturnValue; } // Function MediaAssets.MediaPlaylist.Get // (Final, Native, Public, BlueprintCallable) // Parameters: // int Index (Parm, ZeroConstructor, IsPlainOldData) // class UMediaSource* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) class UMediaSource* UMediaPlaylist::Get(int Index) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlaylist.Get"); UMediaPlaylist_Get_Params params; params.Index = Index; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaPlaylist.Add // (Final, Native, Public, BlueprintCallable) // Parameters: // class UMediaSource* MediaSource (Parm, ZeroConstructor, IsPlainOldData) void UMediaPlaylist::Add(class UMediaSource* MediaSource) { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaPlaylist.Add"); UMediaPlaylist_Add_Params params; params.MediaSource = MediaSource; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MediaAssets.MediaTexture.GetWidth // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) int UMediaTexture::GetWidth() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaTexture.GetWidth"); UMediaTexture_GetWidth_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaTexture.GetHeight // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) int UMediaTexture::GetHeight() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaTexture.GetHeight"); UMediaTexture_GetHeight_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MediaAssets.MediaTexture.GetAspectRatio // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) float UMediaTexture::GetAspectRatio() { static auto fn = UObject::FindObject<UFunction>("Function MediaAssets.MediaTexture.GetAspectRatio"); UMediaTexture_GetAspectRatio_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "hindrik-sibma@hotmail.nl" ]
hindrik-sibma@hotmail.nl
0f165a8d1340f283ef50ec64a544fd6abf62f9a5
64d3552cad51573b83bcc32e5b2a9c4fcbaf901c
/models/sinuca.h
afe5130afd59427e14762629574ea178e90d99b0
[]
no_license
leeoalmd/cg-transf-cam
d351663b837a358c756ab0c2ee18a2872a05784a
de94bffe6d44a373a6db1dc6afce54701e15d3e8
refs/heads/master
2023-04-03T19:07:47.371320
2021-04-10T22:53:22
2021-04-10T22:53:22
345,532,203
0
0
null
null
null
null
UTF-8
C++
false
false
175
h
#ifndef SINUCA_H #define SINUCA_H #include <objeto.h> class Sinuca : public Objeto { public: Sinuca(); Model3DS* model; void desenhar(); }; #endif // SINUCA_H
[ "leeo97@alu.ufc.br" ]
leeo97@alu.ufc.br
e011925784c5b1cdec2672bd6c6a8d5ab3dd6b68
1ed64dca330bc2865b914129c84aa09ee48c8d81
/dmg_emu/dmg_emu/CPU.h
1485bcef7d293f006a55dc67bff3c0894c2e0f37
[]
no_license
EV71/Gameboy-1
7976e4037c14b6959dd1b4bdbec9b98186fd382e
ece1d15ba1f45d7b86d56e919101964b4827ced0
refs/heads/master
2020-03-24T05:58:59.513496
2013-12-11T02:18:20
2013-12-11T02:18:20
142,511,651
1
0
null
2018-07-27T01:18:58
2018-07-27T01:18:58
null
UTF-8
C++
false
false
2,381
h
/* This file is part of DMGBoy. DMGBoy is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DMGBoy 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 DMGBoy. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __CPU_H__ #define __CPU_H__ #include "Registers.h" #include "Memory.h" class QueueLog; class Video; class Instructions; class Cartridge; class CPU: public Registers, public Memory { private: unsigned long numInstructions; unsigned long actualCycles; BYTE lastCycles; int cyclesLCD; WORD cyclesTimer; WORD cyclesDIV; WORD cyclesSerial; int bitSerial; int lcdMode0; int lcdMode1; int lcdMode2; int lcdMode3; int cyclesFrame; Video *v; #ifdef MAKEGBLOG QueueLog *log; #endif bool frameCompleted; bool VBlankIntPending; bool newInterrupt; public: CPU(Video *v, Sound * s); CPU(Video *v, Cartridge *c, Sound * s); ~CPU(); void ExecuteOneFrame(); void UpdatePad(); void OnWriteLCDC(BYTE value); BYTE TACChanged(BYTE newValue); BYTE DIVChanged(BYTE newValue); BYTE P1Changed(BYTE newValue); void AddCycles(int cycles); void Reset(); #ifdef MAKEGBLOG void SaveLog(); #endif void SaveState(std::string saveDirectory, int numSlot); void LoadState(std::string loadDirectory, int numSlot); ////////////////// ADDED FOR CPU SIMULATION void ExecuteUntilHalt(unsigned int maxInstructions); void ExecuteInstructions(int n); void ResetDebug(); private: void Init(Video *v); void ResetGlobalVariables(); void OpCodeCB(Instructions * inst); void UpdateStateLCD(int cycles); void UpdateStateLCDOn(); void UpdateTimer(int cycles); void UpdateSerial(int cycles); void SetIntFlag(int bit); void Interrupts(Instructions * inst); void CheckLYC(); void OnEndFrame(); void ChangeSpeed(); ////////////////// ADDED FOR CPU SIMULATION void ExecuteOneInstruction(Instructions* inst, BYTE* OpCode, BYTE* NextOpcode, BYTE* lastOpCode); }; #endif
[ "jdcarlos1@gmail.com" ]
jdcarlos1@gmail.com