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
9f59f07a5aed925ab2615af4ebb3b05ef83cc675
efdc794bc1152d9e702ea03e32142cf4ff1031cd
/third_party/pdfium/xfa/fxfa/app/xfa_ffbarcode.cpp
b136b8da5a570f81b39ac8afb7b8b607f68bb832
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
taggun/node-pdfium
c3c7c85fd4a280993aa0ce99dcb2f41ce8d592dc
1990bc55e39f700434841e35078cecaa347b1e36
refs/heads/master
2020-12-02T12:44:31.341993
2020-02-26T20:52:34
2020-02-26T20:52:34
96,583,707
3
3
BSD-2-Clause
2020-02-26T20:48:59
2017-07-07T23:34:05
C++
UTF-8
C++
false
false
10,067
cpp
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "xfa/fxfa/app/xfa_ffbarcode.h" #include "core/fxcrt/fx_ext.h" #include "xfa/fwl/cfwl_app.h" #include "xfa/fwl/cfwl_barcode.h" #include "xfa/fwl/cfwl_notedriver.h" #include "xfa/fxfa/app/xfa_fffield.h" #include "xfa/fxfa/app/xfa_fftextedit.h" #include "xfa/fxfa/app/xfa_fwladapter.h" #include "xfa/fxfa/xfa_ffpageview.h" #include "xfa/fxfa/xfa_ffwidget.h" namespace { const XFA_BARCODETYPEENUMINFO g_XFABarCodeTypeEnumData[] = { {0x7fb4a18, L"ean13", XFA_BARCODETYPE_ean13, BC_EAN13}, {0x8d13a3d, L"code11", XFA_BARCODETYPE_code11, BC_UNKNOWN}, {0x8d149a8, L"code49", XFA_BARCODETYPE_code49, BC_UNKNOWN}, {0x8d16347, L"code93", XFA_BARCODETYPE_code93, BC_UNKNOWN}, {0x91a92e2, L"upsMaxicode", XFA_BARCODETYPE_upsMaxicode, BC_UNKNOWN}, {0xa7d48dc, L"fim", XFA_BARCODETYPE_fim, BC_UNKNOWN}, {0xb359fe9, L"msi", XFA_BARCODETYPE_msi, BC_UNKNOWN}, {0x121f738c, L"code2Of5Matrix", XFA_BARCODETYPE_code2Of5Matrix, BC_UNKNOWN}, {0x15358616, L"ucc128", XFA_BARCODETYPE_ucc128, BC_UNKNOWN}, {0x1f4bfa05, L"rfid", XFA_BARCODETYPE_rfid, BC_UNKNOWN}, {0x1fda71bc, L"rss14Stacked", XFA_BARCODETYPE_rss14Stacked, BC_UNKNOWN}, {0x22065087, L"ean8add2", XFA_BARCODETYPE_ean8add2, BC_UNKNOWN}, {0x2206508a, L"ean8add5", XFA_BARCODETYPE_ean8add5, BC_UNKNOWN}, {0x2278366c, L"codabar", XFA_BARCODETYPE_codabar, BC_CODABAR}, {0x2a039a8d, L"telepen", XFA_BARCODETYPE_telepen, BC_UNKNOWN}, {0x323ed337, L"upcApwcd", XFA_BARCODETYPE_upcApwcd, BC_UNKNOWN}, {0x347a1846, L"postUSIMB", XFA_BARCODETYPE_postUSIMB, BC_UNKNOWN}, {0x391bb836, L"code128", XFA_BARCODETYPE_code128, BC_CODE128}, {0x398eddaf, L"dataMatrix", XFA_BARCODETYPE_dataMatrix, BC_DATAMATRIX}, {0x3cff60a8, L"upcEadd2", XFA_BARCODETYPE_upcEadd2, BC_UNKNOWN}, {0x3cff60ab, L"upcEadd5", XFA_BARCODETYPE_upcEadd5, BC_UNKNOWN}, {0x402cb188, L"code2Of5Standard", XFA_BARCODETYPE_code2Of5Standard, BC_UNKNOWN}, {0x411764f7, L"aztec", XFA_BARCODETYPE_aztec, BC_UNKNOWN}, {0x44d4e84c, L"ean8", XFA_BARCODETYPE_ean8, BC_EAN8}, {0x48468902, L"ucc128sscc", XFA_BARCODETYPE_ucc128sscc, BC_UNKNOWN}, {0x4880aea4, L"upcAadd2", XFA_BARCODETYPE_upcAadd2, BC_UNKNOWN}, {0x4880aea7, L"upcAadd5", XFA_BARCODETYPE_upcAadd5, BC_UNKNOWN}, {0x54f18256, L"code2Of5Industrial", XFA_BARCODETYPE_code2Of5Industrial, BC_UNKNOWN}, {0x58e15f25, L"rss14Limited", XFA_BARCODETYPE_rss14Limited, BC_UNKNOWN}, {0x5c08d1b9, L"postAUSReplyPaid", XFA_BARCODETYPE_postAUSReplyPaid, BC_UNKNOWN}, {0x5fa700bd, L"rss14", XFA_BARCODETYPE_rss14, BC_UNKNOWN}, {0x631a7e35, L"logmars", XFA_BARCODETYPE_logmars, BC_UNKNOWN}, {0x6a236236, L"pdf417", XFA_BARCODETYPE_pdf417, BC_PDF417}, {0x6d098ece, L"upcean2", XFA_BARCODETYPE_upcean2, BC_UNKNOWN}, {0x6d098ed1, L"upcean5", XFA_BARCODETYPE_upcean5, BC_UNKNOWN}, {0x76b04eed, L"code3Of9extended", XFA_BARCODETYPE_code3Of9extended, BC_UNKNOWN}, {0x7c7db84a, L"maxicode", XFA_BARCODETYPE_maxicode, BC_UNKNOWN}, {0x8266f7f7, L"ucc128random", XFA_BARCODETYPE_ucc128random, BC_UNKNOWN}, {0x83eca147, L"postUSDPBC", XFA_BARCODETYPE_postUSDPBC, BC_UNKNOWN}, {0x8dd71de0, L"postAUSStandard", XFA_BARCODETYPE_postAUSStandard, BC_UNKNOWN}, {0x98adad85, L"plessey", XFA_BARCODETYPE_plessey, BC_UNKNOWN}, {0x9f84cce6, L"ean13pwcd", XFA_BARCODETYPE_ean13pwcd, BC_UNKNOWN}, {0xb514fbe9, L"upcA", XFA_BARCODETYPE_upcA, BC_UPCA}, {0xb514fbed, L"upcE", XFA_BARCODETYPE_upcE, BC_UNKNOWN}, {0xb5c6a853, L"ean13add2", XFA_BARCODETYPE_ean13add2, BC_UNKNOWN}, {0xb5c6a856, L"ean13add5", XFA_BARCODETYPE_ean13add5, BC_UNKNOWN}, {0xb81fc512, L"postUKRM4SCC", XFA_BARCODETYPE_postUKRM4SCC, BC_UNKNOWN}, {0xbad34b22, L"code128SSCC", XFA_BARCODETYPE_code128SSCC, BC_UNKNOWN}, {0xbfbe0cf6, L"postUS5Zip", XFA_BARCODETYPE_postUS5Zip, BC_UNKNOWN}, {0xc56618e8, L"pdf417macro", XFA_BARCODETYPE_pdf417macro, BC_UNKNOWN}, {0xca730f8a, L"code2Of5Interleaved", XFA_BARCODETYPE_code2Of5Interleaved, BC_UNKNOWN}, {0xd0097ac6, L"rss14Expanded", XFA_BARCODETYPE_rss14Expanded, BC_UNKNOWN}, {0xd25a0240, L"postAUSCust2", XFA_BARCODETYPE_postAUSCust2, BC_UNKNOWN}, {0xd25a0241, L"postAUSCust3", XFA_BARCODETYPE_postAUSCust3, BC_UNKNOWN}, {0xd53ed3e7, L"rss14Truncated", XFA_BARCODETYPE_rss14Truncated, BC_UNKNOWN}, {0xe72bcd57, L"code128A", XFA_BARCODETYPE_code128A, BC_UNKNOWN}, {0xe72bcd58, L"code128B", XFA_BARCODETYPE_code128B, BC_CODE128_B}, {0xe72bcd59, L"code128C", XFA_BARCODETYPE_code128C, BC_CODE128_C}, {0xee83c50f, L"rss14StackedOmni", XFA_BARCODETYPE_rss14StackedOmni, BC_UNKNOWN}, {0xf2a18f7e, L"QRCode", XFA_BARCODETYPE_QRCode, BC_QR_CODE}, {0xfaeaf37f, L"postUSStandard", XFA_BARCODETYPE_postUSStandard, BC_UNKNOWN}, {0xfb48155c, L"code3Of9", XFA_BARCODETYPE_code3Of9, BC_CODE39}, }; const int32_t g_iXFABarcodeTypeCount = sizeof(g_XFABarCodeTypeEnumData) / sizeof(XFA_BARCODETYPEENUMINFO); const XFA_BARCODETYPEENUMINFO* XFA_GetBarcodeTypeByName( const CFX_WideStringC& wsName) { if (wsName.IsEmpty()) return nullptr; uint32_t uHash = FX_HashCode_GetW(wsName, true); int32_t iStart = 0; int32_t iEnd = g_iXFABarcodeTypeCount - 1; do { int32_t iMid = (iStart + iEnd) / 2; const XFA_BARCODETYPEENUMINFO* pInfo = g_XFABarCodeTypeEnumData + iMid; if (uHash == pInfo->uHash) { return pInfo; } else if (uHash < pInfo->uHash) { iEnd = iMid - 1; } else { iStart = iMid + 1; } } while (iStart <= iEnd); return nullptr; } } // namespace. CXFA_FFBarcode::CXFA_FFBarcode(CXFA_WidgetAcc* pDataAcc) : CXFA_FFTextEdit(pDataAcc) {} CXFA_FFBarcode::~CXFA_FFBarcode() {} bool CXFA_FFBarcode::LoadWidget() { CFWL_Barcode* pFWLBarcode = new CFWL_Barcode(GetFWLApp()); m_pNormalWidget = pFWLBarcode; m_pNormalWidget->SetLayoutItem(this); CFWL_NoteDriver* pNoteDriver = m_pNormalWidget->GetOwnerApp()->GetNoteDriver(); pNoteDriver->RegisterEventTarget(m_pNormalWidget, m_pNormalWidget); m_pOldDelegate = m_pNormalWidget->GetDelegate(); m_pNormalWidget->SetDelegate(this); m_pNormalWidget->LockUpdate(); CFX_WideString wsText; m_pDataAcc->GetValue(wsText, XFA_VALUEPICTURE_Display); pFWLBarcode->SetText(wsText); UpdateWidgetProperty(); m_pNormalWidget->UnlockUpdate(); return CXFA_FFField::LoadWidget(); } void CXFA_FFBarcode::RenderWidget(CFX_Graphics* pGS, CFX_Matrix* pMatrix, uint32_t dwStatus) { if (!IsMatchVisibleStatus(dwStatus)) return; CFX_Matrix mtRotate = GetRotateMatrix(); if (pMatrix) mtRotate.Concat(*pMatrix); CXFA_FFWidget::RenderWidget(pGS, &mtRotate, dwStatus); CXFA_Border borderUI = m_pDataAcc->GetUIBorder(); DrawBorder(pGS, borderUI, m_rtUI, &mtRotate); RenderCaption(pGS, &mtRotate); CFX_RectF rtWidget = m_pNormalWidget->GetWidgetRect(); CFX_Matrix mt(1, 0, 0, 1, rtWidget.left, rtWidget.top); mt.Concat(mtRotate); m_pNormalWidget->DrawWidget(pGS, &mt); } void CXFA_FFBarcode::UpdateWidgetProperty() { CXFA_FFTextEdit::UpdateWidgetProperty(); CFWL_Barcode* pBarCodeWidget = (CFWL_Barcode*)m_pNormalWidget; CFX_WideString wsType = GetDataAcc()->GetBarcodeType(); const XFA_BARCODETYPEENUMINFO* pBarcodeTypeInfo = XFA_GetBarcodeTypeByName(wsType.AsStringC()); if (!pBarcodeTypeInfo) return; pBarCodeWidget->SetType(pBarcodeTypeInfo->eBCType); CXFA_WidgetAcc* pAcc = GetDataAcc(); int32_t intVal; FX_CHAR charVal; bool boolVal; FX_FLOAT floatVal; if (pAcc->GetBarcodeAttribute_CharEncoding(intVal)) { pBarCodeWidget->SetCharEncoding((BC_CHAR_ENCODING)intVal); } if (pAcc->GetBarcodeAttribute_Checksum(boolVal)) { pBarCodeWidget->SetCalChecksum(boolVal); } if (pAcc->GetBarcodeAttribute_DataLength(intVal)) { pBarCodeWidget->SetDataLength(intVal); } if (pAcc->GetBarcodeAttribute_StartChar(charVal)) { pBarCodeWidget->SetStartChar(charVal); } if (pAcc->GetBarcodeAttribute_EndChar(charVal)) { pBarCodeWidget->SetEndChar(charVal); } if (pAcc->GetBarcodeAttribute_ECLevel(intVal)) { pBarCodeWidget->SetErrorCorrectionLevel(intVal); } if (pAcc->GetBarcodeAttribute_ModuleWidth(intVal)) { pBarCodeWidget->SetModuleWidth(intVal); } if (pAcc->GetBarcodeAttribute_ModuleHeight(intVal)) { pBarCodeWidget->SetModuleHeight(intVal); } if (pAcc->GetBarcodeAttribute_PrintChecksum(boolVal)) { pBarCodeWidget->SetPrintChecksum(boolVal); } if (pAcc->GetBarcodeAttribute_TextLocation(intVal)) { pBarCodeWidget->SetTextLocation((BC_TEXT_LOC)intVal); } if (pAcc->GetBarcodeAttribute_Truncate(boolVal)) { pBarCodeWidget->SetTruncated(boolVal); } if (pAcc->GetBarcodeAttribute_WideNarrowRatio(floatVal)) { pBarCodeWidget->SetWideNarrowRatio((int32_t)floatVal); } if (pBarcodeTypeInfo->eName == XFA_BARCODETYPE_code3Of9 || pBarcodeTypeInfo->eName == XFA_BARCODETYPE_ean8 || pBarcodeTypeInfo->eName == XFA_BARCODETYPE_ean13 || pBarcodeTypeInfo->eName == XFA_BARCODETYPE_upcA) { pBarCodeWidget->SetPrintChecksum(true); } } bool CXFA_FFBarcode::OnLButtonDown(uint32_t dwFlags, const CFX_PointF& point) { CFWL_Barcode* pBarCodeWidget = (CFWL_Barcode*)m_pNormalWidget; if (!pBarCodeWidget || pBarCodeWidget->IsProtectedType()) return false; if (m_pDataAcc->GetAccess() != XFA_ATTRIBUTEENUM_Open) return false; return CXFA_FFTextEdit::OnLButtonDown(dwFlags, point); } bool CXFA_FFBarcode::OnRButtonDown(uint32_t dwFlags, const CFX_PointF& point) { CFWL_Barcode* pBarCodeWidget = (CFWL_Barcode*)m_pNormalWidget; if (!pBarCodeWidget || pBarCodeWidget->IsProtectedType()) return false; return CXFA_FFTextEdit::OnRButtonDown(dwFlags, point); }
[ "michael.arthur@ikegps.com" ]
michael.arthur@ikegps.com
4ed12d801f53240621bff19d5c9583c2d6ea7a7c
5793887005d7507a0a08dc82f389d8b8849bc4ed
/vendor/mediatek/proprietary/hardware/mtkcam/feature/core/featurePipe/streaming/QParamsBase_t.h
f1187286d8ddd5a7de96e18f2e7ada9382437de7
[]
no_license
wangbichao/dual_camera_x
34b0e70bf2dc294c7fa077c637309498654430fa
fa4bf7e6d874adb7cf4c658235a8d24399f29f30
refs/heads/master
2020-04-05T13:40:56.119933
2017-07-10T13:57:33
2017-07-10T13:57:33
94,966,927
3
0
null
null
null
null
UTF-8
C++
false
false
5,321
h
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ #ifndef _MTK_CAMERA_STREAMING_FEATURE_PIPE_QPARAMS_BASE_T_H_ #define _MTK_CAMERA_STREAMING_FEATURE_PIPE_QPARAMS_BASE_T_H_ #include "MtkHeader.h" //#include <mtkcam/iopipe/PostProc/IHalPostProcPipe.h> #include <utils/RefBase.h> #include <utils/Mutex.h> namespace NSCam { namespace NSCamFeature { namespace NSFeaturePipe { template <typename T> class QParamsBase : public virtual android::RefBase { public: enum MAGIC { MAGIC_VALID = 0xabcd, MAGIC_USED = 0xdddd, MAGIC_FREED = 0xfaaf, }; class BACKUP_DATA_TYPE { public: BACKUP_DATA_TYPE() : mMagic(MAGIC_VALID) { } BACKUP_DATA_TYPE(QParamsBase *parent, NSCam::NSIoPipe::NSPostProc::QParams qparams, const T &data) : mParent(parent) , mQParamsCookie(qparams.mpCookie) , mQParamsCB(qparams.mpfnEnQFailCallback) , mQParamsFailCB(qparams.mpfnEnQFailCallback) , mQParamsBlockCB(qparams.mpfnEnQBlockCallback) , mData(data) , mMagic(MAGIC_VALID) { } ~BACKUP_DATA_TYPE() { mMagic = MAGIC_FREED; } void restore(NSCam::NSIoPipe::NSPostProc::QParams &qparams) { qparams.mpCookie = mQParamsCookie; qparams.mpfnCallback = mQParamsCB; qparams.mpfnEnQFailCallback = mQParamsFailCB; qparams.mpfnEnQBlockCallback = mQParamsBlockCB; } QParamsBase *mParent; void *mQParamsCookie; NSCam::NSIoPipe::NSPostProc::QParams::PFN_CALLBACK_T mQParamsCB; NSCam::NSIoPipe::NSPostProc::QParams::PFN_CALLBACK_T mQParamsFailCB; NSCam::NSIoPipe::NSPostProc::QParams::PFN_CALLBACK_T mQParamsBlockCB; T mData; MAGIC mMagic; }; QParamsBase(); virtual ~QParamsBase(); protected: virtual MBOOL onQParamsCB(const NSCam::NSIoPipe::NSPostProc::QParams &param, const T &data) = 0; virtual MBOOL onQParamsFailCB(const NSCam::NSIoPipe::NSPostProc::QParams &param, const T &data); virtual MBOOL onQParamsBlockCB(const NSCam::NSIoPipe::NSPostProc::QParams &param, const T &data); enum CB_TYPE { CB_DONE, CB_FAIL, CB_BLOCK }; static void processCB(NSCam::NSIoPipe::NSPostProc::QParams param, CB_TYPE type); public: static void staticQParamsCB(NSCam::NSIoPipe::NSPostProc::QParams &param); static void staticQParamsFailCB(NSCam::NSIoPipe::NSPostProc::QParams &param); static void staticQParamsBlockCB(NSCam::NSIoPipe::NSPostProc::QParams &param); protected: MBOOL enqueQParams(NSCam::NSIoPipe::NSPostProc::INormalStream *stream, NSCam::NSIoPipe::NSPostProc::QParams param, const T &data); MVOID waitEnqueQParamsDone(); private: MVOID signalDone(); MVOID signalEnque(); static BACKUP_DATA_TYPE* checkOutBackup(void* handle); private: android::Mutex mMutex; android::Condition mCondition; unsigned mCount; }; } // namespace NSFeaturePipe } // namespace NSCamFeature } // namespace NSCam #endif // _MTK_CAMERA_STREAMING_FEATURE_PIPE_QPARAMS_BASE_T_H_
[ "wangbichao@live.com" ]
wangbichao@live.com
d53fa9a44d277a5bc5a13314b626260eeeec6c26
a05f3e3bcc9f1161f5890f98eaf1a4a7129846ce
/c++/MMD/ReadPMD.cpp
ab88ec84a6cf32d5c31dd4ba16ffa9d3ba17fa95
[]
no_license
sosflyyi/laboratory
17d3d0e13a62674c244a3bcd7bdca8803fe89f32
9a3f47c99279e328d2719d21dfd13cd212fab5b6
refs/heads/master
2023-04-09T23:20:02.592346
2016-05-09T13:27:16
2016-05-09T13:27:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
444
cpp
/** * @file * @brief * * @author Takuya Shishido * @date 2012.07.09 22:54:19 * * @version 0.01, Shishido Takuya, 2012.07.09 22:54:19 * (c) 2012 Konami Digital Entertainment Co., Ltd. All Rights Reserved. */ //----------------------------------------------------- // include //----------------------------------------------------- namespace mmd { void readPMD(const std::string& fileName) { } } // namespace mmd
[ "joke0201@gmail.com" ]
joke0201@gmail.com
26183ff6a74efa52fe4323a8ad1700fe8ef2a951
9eb4e3d423bc1410674cdf3d27678a59a5a2a8e5
/cpp/classes/sunblind/cornice.cc
8e9c3aec2ac614518490559f17536349ed17ffcb
[]
no_license
alexdreamwalker/web-constructor
41fe86ed80e7b66aaf2559445b7afd4bd31b854e
a9764069d1de4c00cfc328e55ec950e2cdc94e32
refs/heads/master
2021-01-18T21:08:47.624302
2014-02-12T14:59:32
2014-02-12T14:59:32
36,761,245
0
0
null
null
null
null
UTF-8
C++
false
false
207
cc
#ifndef CORNICE_HPP #define CORNICE_HPP #include "../complectation.cc" class Cornice: public Complectation { public: Cornice() {} virtual float calculate() { return 3; } }; #endif
[ "dreamer@dreamer-ThinkPad-X121e.(none)" ]
dreamer@dreamer-ThinkPad-X121e.(none)
30dd5e3f983217ef8af13147373822138d8880c8
e9e7fba53f740c33258b4024035d06a9458a7809
/src/Utilities/telemetry_logging.h
66994d0873d0bd480abb5b260571ceb87c113791
[]
no_license
kirencaldwell/StateEstimation
b6baedab7fa412bdc98865082631164b3a5e8abc
b4da1fc7bdd3265857fe4bb71c1e758396ddfd7a
refs/heads/main
2023-08-16T04:44:42.850228
2021-09-24T21:51:21
2021-09-24T21:51:21
343,886,861
0
0
null
null
null
null
UTF-8
C++
false
false
1,310
h
#ifndef TELEMETRY_LOGGING_H_ #define TELEMETRY_LOGGING_H_ #include "../../Eigen/Dense" #include <iostream> #include <vector> #include "utilities.h" #include <fstream> using Eigen::MatrixXd; using Eigen::VectorXd; class Signal { public: Signal(std::string signal_name); std::string GetSignalString(); std::string GetSignalName(); std::string GetSignalHeader(); void SetSignalName(std::string signal_name); void SetSignal(MatrixXd *x); void SetSignal(VectorXd *x); void SetSignal(double *x); private: std::string _signal_name; MatrixXd *_mx; VectorXd *_vx; double *_dx; std::string _datatype; }; class TelemetryLogging { public: TelemetryLogging(std::string filename); void AddSignal(Signal signal); void LogSignals(); void CreateLogHeader(); void EndLogging(); private: std::vector<Signal> _signals; std::ofstream _logfile; }; // class MatrixSignal: public Signal { // public: // void CreateLink(MatrixXd *x); // private: // MatrixXd *_x; // }; // class VectorSignal: public Signal { // public: // void CreateLink(VectorXd *x); // private: // VectorXd *_x; // }; #endif
[ "kirencaldwell@gmail.com" ]
kirencaldwell@gmail.com
d83cc1ab1d173f5978415836b2ab8a156376ca72
5a46c5434d622ca0e035526c094614a1f6eddb44
/project/include/Audio.h
eac5f944d51f445a6844e2ddd090513fbc3206fa
[ "MIT" ]
permissive
TiVo/NME
b60833a99dbfebb27c93e0c50df4a14510cad728
37577ad54430e5cde9aa0b2477083098698b2f74
refs/heads/master
2021-01-18T07:51:54.714397
2013-09-09T18:10:31
2013-09-09T18:10:31
12,600,565
1
0
null
null
null
null
UTF-8
C++
false
false
1,283
h
#ifndef AUDIO_H #define AUDIO_H #include <QuickVec.h> #include <Utils.h> namespace nme { class AudioSample { }; class AudioStream { }; enum AudioFormat { eAF_unknown, eAF_auto, eAF_ogg, eAF_wav, eAF_mp3, eAF_count }; //The main audio interface namespace Audio { AudioFormat determineAudioTypeFromMagic( const QuickVec<unsigned char> &bytes ); AudioFormat determineAudioTypeFromFilename( const std::string &filename ); //Loading formats bool loadOggData(const char *inFileURL, QuickVec<unsigned char> &outBuffer, int *channels, int *bitsPerSample, int* outSampleRate); bool loadWavData(const char *inFileURL, QuickVec<unsigned char> &outBuffer, int *channels, int *bitsPerSample, int* outSampleRate); } //namespace Audio //Wav format info struct RIFF_Header { char chunkID[4]; long chunkSize;//size not including chunkSize or chunkID char format[4]; }; struct WAVE_Format { char subChunkID[4]; long subChunkSize; short audioFormat; short numChannels; long sampleRate; long byteRate; short blockAlign; short bitsPerSample; }; struct WAVE_Data { char subChunkID[4]; //should contain the word data long subChunk2Size; //Stores the size of the data block }; } //namespace nme #endif //AUDIO_H
[ "fuzzyspoon@gmail.com" ]
fuzzyspoon@gmail.com
4c7959800dfaba0fab39a5c5c05f28fb12845ed7
6c15077cdd6ec01215332c58428d2d9bda3217b1
/spank3d/inc/ui/parsers/IWindowParser.h
bd69bfb33ccb9ff960b0c87bbe27015304d1ed50
[]
no_license
zjhlogo/spank3d
6efb88a59ef281707bafaeab74736482a7c13bd8
540b197d1a66bb72cc2fc30f1476b22c6ce1c3b3
refs/heads/master
2016-09-10T19:19:27.739776
2013-04-18T01:12:46
2013-04-18T01:12:46
32,371,451
0
0
null
null
null
null
UTF-8
C++
false
false
811
h
/*! * \file IWindowParser.h * \date 10-23-2012 15:46:20 * * * \author zjhlogo (zjhlogo@gmail.com) */ #ifndef __IWINDOWPARSER_H__ #define __IWINDOWPARSER_H__ #include "../../core/IObject.h" #include "../controls/IWindow.h" #include <tinyxml-2.6.2/tinyxml.h> class IWindowParser : public IObject { public: RTTI_DEF(IWindowParser, IObject); IWindowParser(const tstring& strClassName = _("IWindow")); virtual ~IWindowParser(); const tstring& GetClassName() const; bool CanParse(const tstring& strClassName); IWindow* Parse(TiXmlElement* pXmlWindow, IWindow* pParent); virtual bool ParseWindow(TiXmlElement* pXmlWindow, IWindow* pWindow); virtual IWindow* CreateWindow(IWindow* pParent) = 0; private: tstring m_strClassName; }; #endif // __IWINDOWPARSER_H__
[ "zjhlogo@146e4613-b970-0576-f1ea-3e13f537ed8b" ]
zjhlogo@146e4613-b970-0576-f1ea-3e13f537ed8b
f890dcb4a2fd32bb8d30fd7c3227b51810da0a33
934b88d9a7c06b1e389c98adfa6e4b491f073604
/Simulation/Simulation/1057.cpp
0f51cebd4318ed7a00cdea14b7012c835937e670
[]
no_license
flash1117/Algorithm
cf7ac89588bd3c9fb03b7964559b6b16130e83d7
1331972e573aa6e6661cb37ff291c258a8ed456a
refs/heads/master
2023-02-10T21:32:47.088851
2021-01-05T14:02:31
2021-01-05T14:02:31
152,283,309
0
0
null
null
null
null
UTF-8
C++
false
false
374
cpp
#include <iostream> using namespace std; int N, a, b; int solve() { int round = 1; while (N) { if (b > a && b - a == 1 && b % 2 == 0) return round; else if (a > b && a - b == 1 && a % 2 == 0) return round; else round++; a = a / 2 + a % 2; b = b / 2 + b % 2; N /= 2; } return -1; } int main() { cin >> N >> a >> b; cout << solve(); return 0; }
[ "flash1117@naver.com" ]
flash1117@naver.com
e2759b121cd293aa18e7729f587756bdbff31471
c30d20ffd5522d4fe3e9fca3fb30e19931ab9e97
/Versionen/stand_semesterende_01_07_2021/RMF/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/priority__rosidl_typesupport_introspection_cpp.hpp
1cb656fe81b0decfe5e01ee352f82d0abf44ccc5
[ "MIT" ]
permissive
flitzmo-hso/flitzmo_agv_control_system
557f1200c0f060264e4d6ea688e104cabd9d0568
99e8006920c03afbd93e4c7d38b4efff514c7069
refs/heads/main
2023-06-19T08:18:30.282776
2021-07-09T18:05:09
2021-07-09T18:05:09
358,238,668
0
2
null
null
null
null
UTF-8
C++
false
false
1,017
hpp
// generated from rosidl_typesupport_introspection_cpp/resource/idl__rosidl_typesupport_introspection_cpp.h.em // with input from rmf_task_msgs:msg/Priority.idl // generated code does not contain a copyright notice #ifndef RMF_TASK_MSGS__MSG__DETAIL__PRIORITY__ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_HPP_ #define RMF_TASK_MSGS__MSG__DETAIL__PRIORITY__ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_HPP_ #include "rosidl_runtime_c/message_type_support_struct.h" #include "rosidl_typesupport_interface/macros.h" #include "rosidl_typesupport_introspection_cpp/visibility_control.h" #ifdef __cplusplus extern "C" { #endif // TODO(dirk-thomas) these visibility macros should be message package specific ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC const rosidl_message_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_cpp, rmf_task_msgs, msg, Priority)(); #ifdef __cplusplus } #endif #endif // RMF_TASK_MSGS__MSG__DETAIL__PRIORITY__ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_HPP_
[ "aline.schaub@web.de" ]
aline.schaub@web.de
01527c285a49f11df9289e90b76b3e82e26b407e
81ded04643728a64ee021250fc5ad8381bdd77e1
/SportsWorldCup/Classes/URLDelegator.h
b6c00afabc022b70601cdce10ac66b1b2b50ca6e
[]
no_license
LitQoo/SportsWorldCupForKaKao
d5b16e9fe43c264853fe701a133e4f4fe27fbb1b
90fe941bf0dad5a31d128c4ad6a80a1aaf90d5b7
refs/heads/master
2021-03-22T02:58:32.441110
2013-05-30T09:05:56
2013-05-30T09:05:56
10,356,316
0
0
null
null
null
null
UTF-8
C++
false
false
1,549
h
#pragma once #include "cocos2d.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID #include "android/jni/JniHelper.h" #include "jni.h" #endif using namespace cocos2d; using namespace std; typedef void (CCObject::*RecvSelType)(string); #define recv_selector(_SELECTOR) (RecvSelType)(&_SELECTOR) class URLDelegator { public: struct DeleSel { CCObject* target; RecvSelType selector; }; public: void removeTarget(CCObject* _obj) { // DeleTable<int, DeleSel> for(auto iter = DeleSelTable.begin(); iter != DeleSelTable.end();) { if(iter->second.target == _obj) { DeleSelTable.erase(iter++); } else ++iter; } } int addDeleSel(CCObject* target, RecvSelType selector) { key++; DeleSel temp; temp.target = target; temp.selector = selector; DeleSelTable[key] = temp; return key; } void removeDeleSel(int _key) { if(DeleSelTable.find(_key) != DeleSelTable.end()) DeleSelTable.erase(_key); } DeleSel getDeleSel(int _key) { // find if(DeleSelTable.find(_key) != DeleSelTable.end()) { return DeleSelTable[_key]; } else { //CCLog("not found!!!"); DeleSel _t; _t.target = 0; _t.selector = 0; return _t; } } public: static URLDelegator* getInstance() { static URLDelegator* _ins = 0; if(_ins == 0) _ins = new URLDelegator(); return _ins; } private: URLDelegator() { key = 0; } ~URLDelegator(){} private: map<int, DeleSel> DeleSelTable; int key; };
[ "hsnks100@gmail.com" ]
hsnks100@gmail.com
a8d4547c5f24cd5191bbbb26a63df1d00de4c6a9
79882e9193621a73808c50aa7c2948f9ff7485e5
/tests/unit/seq.cpp
46968ffa5c50b4583d053ed07c8b8b811008cde2
[ "MIT" ]
permissive
cudarrays/cudarrays
2e28c717c74e56d280fa30910260824c99a809dd
cc4fb82da381b548e1fd3501b8fc6d1c07c8be37
refs/heads/master
2020-05-09T16:15:34.716528
2016-11-27T07:26:44
2016-11-27T07:26:44
33,399,232
29
1
null
null
null
null
UTF-8
C++
false
false
2,021
cpp
/* * CUDArrays is a library for easy multi-GPU program development. * * The MIT License (MIT) * * Copyright (c) 2013-2015 Barcelona Supercomputing Center and * University of Illinois * * Developed by: Javier Cabezas <javier.cabezas@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <iostream> #include <type_traits> #include "cudarrays/utils.hpp" #include "gtest/gtest.h" class seq_test : public testing::Test { protected: static void SetUpTestCase() {} static void TearDownTestCase() {} }; template <unsigned...> struct var; TEST_F(seq_test, create) { ASSERT_EQ(SEQ_SIZE(SEQ_WITH_TYPE(unsigned)), 0u); ASSERT_EQ(SEQ_SIZE(SEQ(1)), 1u); ASSERT_EQ(SEQ_SIZE(SEQ(1, 2, 3)), 3u); using t = var<1, 2, 3>; ASSERT_EQ(SEQ_SIZE(SEQ_WRAP(unsigned, t)), 3u); bool result = std::is_same<t, SEQ_UNWRAP(SEQ_WRAP(unsigned, t), var<>)>::value; ASSERT_EQ(result, true); }
[ "javier.cabezas@gmail.com" ]
javier.cabezas@gmail.com
af9c28d5e0ac0d5523bc7d3ce5f8b4dca3f22e5b
a3f3aaa07f84b0926f09f77ae2d7bb1bed83e262
/common-files/image_processing_function.h
4d0b61237cdfe15d9d1a7053bac8db4d0957b88f
[]
no_license
MSECode/Master-Thesis-Ladimo-Project
bda4aae54983dbb15327460270cc5f1adfc6e349
fc8c529bed6f165a911c57fd8080a6d157aea20d
refs/heads/main
2023-02-20T11:39:10.136450
2021-01-25T10:14:39
2021-01-25T10:14:39
332,691,610
0
0
null
null
null
null
UTF-8
C++
false
false
2,083
h
#pragma once #include <iostream> #include <opencv2/imgproc.hpp> class ImageProcessingStandard { public: enum class FilteringTechnique { mean_filter, gaussian_filter, median_filter, bilateral_filter }; // Set general kernel dimension and define kernel box for all the methods void setKernelSize(const int& kernel_size_) { kernel_size = kernel_size_; kernel_box = cv::Size(kernel_size_, kernel_size_); } /** * Set overneeded Gaussian blur parameters: * sigma_X * sigma_Y */ void setGaussianBlurParams(const double& gaussian_sigma_X_, const double& gaussian_sigma_Y_) { gaussian_sigma_X = gaussian_sigma_X_; gaussian_sigma_Y = gaussian_sigma_Y_; } /** * Set overneeded Bilateral blur parameters: * diameter * sigma */ void setBilateralParams(const int& diameter_bilateral_, const double& sigma_bilateral_) { diameter_bilateral = diameter_bilateral_; sigma_bilateral = sigma_bilateral_; } /** * Set image pre-processing operations * Mean blur * Gaussian blur * Median blur * Bilateral blur */ void setProcessedImageStandard(const cv::Mat& input_image, int filter_technique); cv::Mat getProcessedImageStandard(int filter_technique); private: // Parameters int kernel_size = 0; cv::Size kernel_box; double gaussian_sigma_X = 0.0; double gaussian_sigma_Y = 0.0; int diameter_bilateral = 0; double sigma_bilateral = 0.0; // Filtered images cv::Mat mean_blurred; cv::Mat gaussian_blurred; cv::Mat median_blurred; cv::Mat bilateral_blurred; }; class ImageProcessingMorphology { public: enum class MorphologicalFilters { morph_open, morph_close, morph_dilation, morph_erosion, morph_mixed }; // Setter void setProcessedParametersMorph(const int& morph_size, int kernel_shape); void setProcessedImageMorph(const cv::Mat& inputImage, int morph_technique); // Getter cv::Mat getProcessedImageMorph(int morph_technique); private: cv::Mat morphElement; // (size --> 2 * morph_size + 1) cv::Mat openingMat; cv::Mat closingMat; cv::Mat dilateMat; cv::Mat erodeMat; cv::Mat mixedMat; };
[ "noreply@github.com" ]
noreply@github.com
95405926d080c9244c0bc765685b3a06abce72fa
5e6910a3e9a20b15717a88fd38d200d962faedb6
/Codeforces/Contests/CF1430/F.cpp
6a536d45305c628132baca52f4e617d37ec61415
[]
no_license
khaledsliti/CompetitiveProgramming
f1ae55556d744784365bcedf7a9aaef7024c5e75
635ef40fb76db5337d62dc140f38105595ccd714
refs/heads/master
2023-08-29T15:12:04.935894
2023-08-15T13:27:12
2023-08-15T13:27:12
171,742,989
3
0
null
null
null
null
UTF-8
C++
false
false
1,259
cpp
#include <bits/stdc++.h> using namespace std; #define pb push_back #define mp make_pair #define endl '\n' #define D(x) cerr << #x << " = " << (x) << '\n' #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() typedef long long ll; const int N = 2008; const ll INF = 1e18; int n, k; ll a[N], L[N], R[N]; ll dp[N][N]; ll solve(int cur, int last, ll have) { if(cur >= n) { return 0; } ll& r = dp[cur][last]; if(r != -1) return r; r = INF; if(have >= a[cur]) { r = min(r, a[cur] + solve(cur + 1, last, have - a[cur])); if(R[cur] > L[cur] || L[cur + 1] > R[cur]) { r = min(r, have + solve(cur + 1, cur + 1, k)); } } else { ll rem = a[cur] - have; ll x = (rem + k - 1) / k; ll w = R[cur] - L[cur]; if(x <= w) { // possible r = min(r, a[cur] + solve(cur + 1, last, x * k - rem)); if(x < w || L[cur + 1] > R[cur]) { r = min(r, have + x * k + solve(cur + 1, cur + 1, k)); } } } return r; } int main() { cin >> n >> k; for(int i = 0; i < n; i++) { cin >> L[i] >> R[i] >> a[i]; } memset(dp, -1, sizeof dp); L[n] = INF; ll ans = solve(0, 0, k); if(ans >= INF) ans = -1; cout << ans << endl; return 0; }
[ "khaled.sliti1@gmail.com" ]
khaled.sliti1@gmail.com
294e7734e880a36edaa5cdacf6e06cc9aaf22ea0
51f700992583bbf855f1ed5cad1c2ee67f1bb10b
/client/webtoon.h
96c96b7f88a226f7ad8b0afed2ef51127851f2a7
[]
no_license
zych1751/webtoon_alarm
972340171f17d63e343fc8e6acf08d2671f91b3d
8519700ef675eb18ac8deab4cfa934b76508376c
refs/heads/master
2021-01-15T18:41:10.856386
2017-09-09T04:23:58
2017-09-09T04:23:58
99,799,092
0
0
null
null
null
null
UTF-8
C++
false
false
602
h
#ifndef WEBTOON_H #define WEBTOON_H #include<QString> #include<QUrl> class Webtoon { public: Webtoon(); Webtoon(int company, int day, QString name, QUrl url); bool same(int _company, int _day, QString _name); int getCompany(); int getDay(); QString getName(); QUrl getListUrl(); QUrl getRecentUrl(); QUrl getImageUrl(); void setImageUrl(QUrl url); protected: int company; // 0 : naver, (maybe 1 : daum, 2 : lezhin) int day; // 0 : mon, 1 : tue .... QString name; QUrl list_url; QUrl recent_url; QUrl image_url; }; #endif // WEBTOON_H
[ "zych1751@naver.com" ]
zych1751@naver.com
8d301202d0dea6f43a0e4d1472b6cc2185c577e8
407f49b0296d11ddd00469a545e7d5c0ccfddd4e
/EsperClient_UI/EsperClient/stdafx.cpp
e81787bc5eaad5cba59cababcbb798e144aa202e
[]
no_license
PIGMANIA/EsperClient
69a78f4ef47cc27dadee517e74076d898313c708
e66ddaa1dd6f5747d39cf032d06267a516c4fd2b
refs/heads/master
2020-12-29T02:31:24.899955
2016-12-23T04:30:02
2016-12-23T04:30:02
54,934,218
0
0
null
null
null
null
UHC
C++
false
false
247
cpp
// stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다. // EsperClient.pch는 미리 컴파일된 헤더가 됩니다. // stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다. #include "stdafx.h"
[ "tkddn017@gmail.com" ]
tkddn017@gmail.com
03b2eaae30b15af250d9c2344e8f9da5fda3118f
9f21315b2191e02a33abde637844d9b98c0f5318
/Vektor.h
cc4980ff934a1cbd9291808197765f8cd5f30597
[]
no_license
DrGilion/math3solver
6c1ecf9ae293a1fc60476b9a227bf1cae1b8c022
5b10dd80db3290985eaa72aaac51481dd68f535c
refs/heads/master
2021-09-10T03:40:44.954535
2018-03-20T22:00:28
2018-03-20T22:00:28
126,086,251
0
0
null
null
null
null
UTF-8
C++
false
false
962
h
#include <iostream> #ifndef VEKTOR_H #define VEKTOR_H using namespace std; class Vektor{ friend ostream& operator << (ostream& out, const Vektor& v); friend istream& operator >> (istream& in, Vektor& v); friend bool operator == (const double d[], const Vektor& c); public: Vektor(int a); Vektor(const double values[]); Vektor(const Vektor& v); double size(void); double Summennorm(void)const; double Euklidnorm(void)const; double Maximumnorm(void)const; Vektor& operator = (const Vektor& v); Vektor& operator += (const Vektor& v); Vektor& operator += (const double d[]); bool operator == (const Vektor& v) const; bool operator == (const double d[]) const; Vektor operator + (const Vektor& v) const; double& operator [] (int index) const; ~Vektor(); private: double* elems; int sz; }; #endif // VEKTOR_H
[ "michael.m.weissmann@gmail.com" ]
michael.m.weissmann@gmail.com
0a960767f1cdef8a9fad1bfecdd734aa26290396
12b2f272df30be186408f22eda85dce0a11e3e43
/ntest.cpp
e33210b73a4461c619c2fe46501ae093818d52d1
[]
no_license
joeld42/neuralnet_test
8ac909cbef85bfccc19ff52ea335b66e70d8da68
86585dad5d37313d609dd6e5ece0c6e400b7f1a0
refs/heads/master
2023-02-04T02:01:59.272392
2020-12-26T07:18:10
2020-12-26T07:18:10
260,109,645
0
0
null
null
null
null
UTF-8
C++
false
false
12,248
cpp
// clang -Wno-nullability-completeness ntest.cpp -o ntest -lc++ #include <stdio.h> #include <assert.h> #include <math.h> #include <stdlib.h> #include <string.h> typedef float real_t; #define ALLOC(T,num) \ (T*)malloc(sizeof(T)*(num)) struct Matrix { int rows, cols; real_t *data; Matrix() : rows(0), cols(0), data(NULL) {} Matrix( int _rows, int _cols) { _setup( _rows, _cols ); } Matrix( const Matrix &other ) { _setup( other.rows, other.cols ); _copyDataFrom( other ); } Matrix &operator=( const Matrix &other) { if (data) { rows = 0; cols = 0; free(data); data = NULL; } _setup( other.rows, other.cols ); _copyDataFrom(other ); return *this; } ~Matrix() { free(data); } void _setup( int _rows, int _cols ) { rows = _rows; cols = _cols; data = ALLOC(real_t, rows*cols ); } void _copyDataFrom( const Matrix & other ) { assert( rows*cols == other.rows*other.cols ); for (int i=0; i < rows*cols; i++) { data[i] = other.data[i]; } } void Reshape( int _newRows, int _newCols ) { assert( rows*cols == _newCols*_newRows ); rows = _newRows; cols = _newCols; } void Flip() { int t = rows; rows = cols; cols = t; } real_t get( int i, int j ) { int ndx = i*cols+j; return data[ndx]; } void set( int i, int j, real_t v ) { int ndx = i*cols+j; data[ndx] = v; } void accum( int i, int j, real_t v ) { int ndx = i*cols+j; data[ndx] += v; } void print( const char *title ) { char tcopy[32]; strcpy( tcopy, title ); for (int j=0; j < rows; j++) { printf( "%s |", tcopy ); for (int i=0; i < cols; i++) { printf("%5.4f ", get( j, i )); } printf( "|\n"); if (j==0) { for (char *ch=tcopy; *ch; ch++) { *ch = ' '; } } } printf("\n"); } }; void mat_zero( Matrix &m ) { memset( m.data, 0, m.cols * m.rows*sizeof(real_t)); } void mat_random( Matrix &m ) { for (int i=0; i < m.cols*m.rows; i++) { m.data[i] = (2.0f * ((real_t)rand() / (real_t)RAND_MAX)) - 1.0f; } } void mat_scale( Matrix &m, real_t scalar ) { for (int i=0; i < m.cols*m.rows; i++) { m.data[i] *= scalar; } } void mat_add( Matrix &dest, Matrix &vals ) { assert( dest.rows == vals.rows ); assert( dest.cols == vals.cols ); for (int i=0; i < dest.rows*dest.cols; i++) { dest.data[i] += vals.data[i]; } } void mat_sub( Matrix &dest, Matrix &vals ) { assert( dest.rows == vals.rows ); assert( dest.cols == vals.cols ); for (int i=0; i < dest.rows*dest.cols; i++) { dest.data[i] -= vals.data[i]; } } void mat_mult( Matrix &dest, Matrix &a, Matrix &b ) { // printf("mult %dx%d by %dx%d mat, expect %dx%d result, got %dx%d\n", // a.rows, a.cols, // b.rows, b.cols, // a.rows, b.cols, // dest.rows, dest.cols ); printf("A cols %d, b rows %d\n", a.cols, b.rows ); assert( b.rows==a.cols ); // printf("Expect dest to be %dx%d\n", b.cols, a.rows ); assert( dest.rows==b.cols ); assert( dest.cols==a.rows ); mat_zero( dest ); for (int di=0; di < a.rows; di++) { for (int dj=0; dj < b.cols; dj++) { // row a.i dot col b.j for (int n=0; n < a.cols; n++) { dest.accum( dj, di, a.get( dj, n ) * b.get( n, di ) ); } } } } // --------------------------- struct NetLayer { char layerName[10]; int num_inputs; int num_outputs; real_t *inputs; real_t *outputs; Matrix weights; real_t *biases; NetLayer( int _numInputs, int _numOutputs, const char *_name=NULL ) : weights( _numInputs, _numOutputs ) { num_inputs = _numInputs; num_outputs = _numOutputs; if (_name) { strcpy( layerName, _name ); } else { strcpy( layerName, "Unnamed" ); } inputs = ALLOC(real_t, num_inputs ); outputs = ALLOC(real_t, num_outputs ); biases = ALLOC( real_t, num_outputs ); } void Describe( ) { printf( "Layer %s\n", layerName ); printf("Inputs (%d): ", num_inputs ); for (int i=0; i < num_inputs; i++) { printf( "%3.3f ", inputs[i]); } printf("\n"); weights.print("Weights"); printf("Biases (%d): ", num_outputs ); for (int i=0; i < num_outputs; i++) { printf( "%3.3f ", biases[i]); } printf("\n"); printf("Outputs (%d): ", num_outputs ); for (int i=0; i < num_outputs; i++) { printf( "%3.3f ", outputs[i]); } printf("\n"); } void Evaluate() { for (int i=0; i < num_outputs; i++) { //real_t sum = biases[i]; real_t sum = 0.0; for (int j=0; j < num_inputs; j++) { sum += inputs[j] * weights.get( i, j ); } outputs[i] = sum; printf("Eval: sum %d %3.2f\n", i, outputs[i] ); } ApplyActivation(); } void ApplyActivation() { for (int i=0; i < num_outputs; i++) { outputs[i] = 1.0 / ( 1.0 + exp(outputs[i]) ); } } }; // --------------------------- #if 0 #define MAX_LAYERS (10) struct NeuralNet { void AddLayer( int layerSize, const char *name ) { lsz[numLayers++] = layerSize; if (numLayers > 1) { int n = numLayers - 2; int a = lsz[numLayers-2]; int b = lsz[numLayers-1]; matWeights[n] = Matrix( b, a ); mat_random( matWeights[n] ); matBias[n] = Matrix( b, 1 ); mat_random( matBias[n] ); strcpy( layerName[n], name ); } } void SetWeight( int layer, int row, int col, float weight ) { assert( layer < numLayers); assert( row < lsz[layer] ); matWeights[layer].set( row, col, weight ); } void SetBias( int layer, int row, float bias ) { assert( layer < numLayers ); assert( row < lsz[layer] ); matBias[layer].set( row, 0, bias ); } Matrix Predict( Matrix input ) { Matrix dest; assert( input.rows == lsz[0] ); assert( input.cols == 1 ); for (int i=0; i < numLayers-1; i++) { // This is stupid because I can't keep track of what the hell is a column // vector and what is a row vector if (input.cols != matWeights[i].rows) { input.Flip(); } printf("Input is %d x %d\n", input.rows, input.cols ); printf("Layer (%s) is %d x %d\n", layerName[i], matWeights[i].rows, matWeights[i].cols ); dest = Matrix( matWeights[i].cols, 1 ); mat_mult( dest, input, matWeights[i] ); printf("Layer %d before bias:\n", i); dest.print("Layer"); // dest.print("dest (flip)"); // matBias[i].print("bias"); mat_sub( dest, matBias[i] ); printf("Layer %d (%s) after bias:\n", i, layerName[i]); dest.print("Layer"); // apply the activation func printf("Layer %d before activation:\n", i); dest.print("Layer"); Activation( dest ); printf("Layer %d after activation:\n", i); dest.print("Layer"); // printf("Size after layer %d -- %dx%d\n", i, dest.rows, dest.cols ); input = dest; } // dest.print( "Predict" ); return dest; } void Activation( Matrix &m) { for (int i=0; i < m.rows*m.cols; i++) { m.data[i] = 1.0 / ( 1.0 + exp(-m.data[i]) ); } } void Randomize() { for (int i=0; i < numLayers; i++) { mat_random( matWeights[i] ); float d = 1.0 / sqrt( (float)matWeights[i].cols ); mat_scale( matWeights[i], d ); mat_random( matBias[i] ); //mat_zero( matBias[i]); } } void Zero() { for (int i=0; i < numLayers; i++) { mat_zero( matWeights[i] ); //mat_random( matBias[i] ); mat_zero( matBias[i]); } } void Describe() { int totalWeights = 0; for (int i=0; i < numLayers; i++) { printf("Layer %d (size %d)\n", i, lsz[i] ); if ( i > 0) { int i2 = i-1; printf(" Weights %dx%d biases %d\n", matWeights[i2].rows, matWeights[i2].cols, matBias[i2].rows ); char buff[20]; int layerWeights = matWeights[i2].rows * matWeights[i2].cols; sprintf( buff, "Weights %d", i2); matWeights[i2].print( buff ); sprintf( buff, "Bias %d", i2 ); matBias[i2].print( buff ); totalWeights += layerWeights; } } printf("Total Weights %d\n", totalWeights ); } }; #endif // ------ void test_net_layer() { NetLayer layer(2, 3, "Layer0"); layer.inputs[0] = 0.0; layer.inputs[1] = 1.0; layer.weights.set( 0, 0, -6.029f ); layer.weights.set( 0, 1, -3.261f ); layer.weights.set( 1, 0, -5.734f ); layer.weights.set( 1, 1, -3.172f ); layer.weights.set( 2, 0, 10.f ); layer.weights.set( 2, 1, 20.f ); layer.biases[0] = -1.777; layer.biases[1] = -4.460; layer.Evaluate(); layer.Describe(); printf("---------\n"); NetLayer outlayer( 2, 1, "OutLayer" ); outlayer.inputs[0] = layer.outputs[0]; outlayer.inputs[1] = layer.outputs[1]; outlayer.weights.set( 0, 0, -6.581f ); outlayer.weights.set( 0, 1, 5.826f ); outlayer.biases[0] = 2.444f; outlayer.Evaluate(); outlayer.Describe(); printf("Output >> %1.0f (%3.2f)\n", outlayer.outputs[0], outlayer.outputs[1] ); } #if 0 // ------ void test_basic_mat() { Matrix mA(2, 3); mA.set( 0, 0, 1); mA.set( 0, 1, 2); mA.set( 0, 2, 3); mA.set( 1, 0, 4); mA.set( 1, 1, 5); mA.set( 1, 2, 6); mA.print( "Matrix A"); Matrix mB(3, 2); mB.set( 0, 0, 7); mB.set( 0, 1, 8); mB.set( 1, 0, 9); mB.set( 1, 1, 10); mB.set( 2, 0, 11); mB.set( 2, 1, 12); mB.print( "Matrix B"); Matrix mResult1( 2, 2 ); mat_mult( mResult1, mA, mB ); mResult1.print("A*B"); Matrix mResult2( 3, 3 ); mat_mult( mResult2, mB, mA ); mResult2.print("B*A"); } void test_basic_net() { NeuralNet net; // MNIST setup // net.AddLayer( 784 ); // Input layer // net.AddLayer( 15 ); // Hidden Layer // net.AddLayer( 10 ); // Output Layer net.AddLayer( 2, "INPUT" ); net.AddLayer( 3, "HIDDEN" ); net.AddLayer( 2, "OUTPUT" ); net.Describe(); Matrix mInp; //mInp.Setup( 784, 1 ); mat_random( mInp ); net.Predict( mInp ); } void test_xor_random_net() { printf("----- xor random test ------\n"); NeuralNet net; NeuralNet bestNet; float bestErr = 0; net.AddLayer( 2, "INPUT" ); net.AddLayer( 3, "HIDDEN" ); net.AddLayer( 1, "OUTPUT" ); //net.Describe(); Matrix mInp( 2, 1 ); float input[4][2] = {{0, 0}, {0, 1}, {1, 0}, {1, 1}}; float output[4] = {0, 1, 1, 0}; for (int j=0; j < 20; j++) { net.Randomize(); float err = 0.0f; //net.Describe(); for (int i=0; i < 4; i++) { mInp.set( 0, 0, input[i][0] ); mInp.set( 1, 0, input[i][1] ); Matrix result = net.Predict( mInp ); float n = result.get(0,0); float e = output[i] - n; err += (e*e); printf("TEST %.f %1.f --> %3.2f (exp: %1.f, %3.2f)\n", input[i][0], input[i][1], n, output[i], fabs( output[i] - n) ); } if ((err < bestErr) || (j==0)) { bestNet = net; bestErr = err; } printf("iter %d) err: %f, best %f\n", j, err,bestErr ); } for (int i=0; i < 4; i++) { mInp.set( 0, 0, input[i][0] ); mInp.set( 1, 0, input[i][1] ); Matrix result = net.Predict( mInp ); float n = result.get(0,0); printf("%.f %1.f --> %1.f, %3.2f (exp: %1f)\n", input[i][0], input[i][1], round(n), n, output[i] ); } } void test_xor_saved_net() { printf("----- xor saved net test ------\n"); NeuralNet net; // Test data borrowed from genann library // 2 1 2 1 // B -1.777 W1 -5.734 -6.029 // B -4.460 W2 -3.261 -3.172 // // 2.444 // -6.581 5.826 net.AddLayer( 2, "INPUTS" ); // Inputs net.AddLayer( 2, "HIDDEN" ); // Hidden layer net.AddLayer( 1, "OUTPUTS" ); // Outputs net.SetBias( 0, 0, -1.777 ); net.SetBias( 0, 1, -4.460 ); net.SetWeight( 0, 0, 0, -6.029 ); net.SetWeight( 0, 0, 1, -3.261 ); net.SetWeight( 0, 1, 0, -5.734 ); net.SetWeight( 0, 1, 1, -3.172 ); net.SetBias( 1, 0, 2.444 ); net.SetWeight( 1, 0, 0, -6.581 ); net.SetWeight( 1, 0, 1, 5.826 ); net.Describe(); Matrix mInp( 2, 1 ); float input[4][2] = {{0, 0}, {0, 1}, {1, 0}, {1, 1}}; float output[4] = {0, 1, 1, 0}; float match_output[4] = { 0.090012, 0.883921, 0.870898, 0.150186 }; // output from genann for (int i=0; i < 4; i++) { printf( "---------[ %d ] ------------------------\n", i ); mInp.set( 0, 0, input[i][0] ); mInp.set( 1, 0, input[i][1] ); Matrix result = net.Predict( mInp ); float n = result.get(0,0); printf("%.f %1.f --> %1.f, %3.5f (exp: %1f, match %f)\n", input[i][0], input[i][1], round(n), n, output[i], match_output[i] ); } } #endif int main(int argc, char *argv[] ) { //test_basic_mat(); //test_basic_net(); //test_xor_random_net(); //test_xor_saved_net(); test_net_layer(); }
[ "joeld42@gmail.com" ]
joeld42@gmail.com
300980c0816f6590d78ad1ff1b20be88bb028c46
0f53b1eb772db8351b46edf772ea8bd86ad1a0d2
/src/main/include/subsystems/VisionSubsystem.h
7a4abe543f5dfe47f50e14c68ec2724ff5506381
[]
no_license
ParadigmShift1259/Swerve2021
c69ff21e31405aa8bee834d55c935ab8e4aa5883
6158dd606a97a541d65bec1be26193717794cc64
refs/heads/main
2023-07-13T06:50:20.351724
2021-08-20T01:19:26
2021-08-20T01:19:26
391,460,826
0
0
null
null
null
null
UTF-8
C++
false
false
1,418
h
#pragma once #include <frc2/command/SubsystemBase.h> #include <frc/smartdashboard/SmartDashboard.h> #include <networktables/NetworkTable.h> #include <networktables/NetworkTableInstance.h> #include <wpi/math> #include "Constants.h" #include "common/Util.h" using namespace std; using namespace frc; using namespace VisionConstants; class VisionSubsystem : public frc2::SubsystemBase { public: VisionSubsystem(); /// Will be called periodically whenever the CommandScheduler runs. void Periodic() override; /// Determine valid vision based on returned distance values /// \return Whether or not the Vision Subsystem is giving accurate values bool GetValidTarget(); /// Retrieves the distance calculation from the target via the limelight double GetDistance(); /// \return The angle calculation from the target via the limelight double GetAngle(); /// Turns the limelight LED on or off /// \param on Boolean where true = LED on void SetLED(bool on); protected: /// Converts degrees to radians /// \param degrees Degrees to convert double DegreesToRadians(double degrees); private: shared_ptr<NetworkTable> m_dashboard; shared_ptr<NetworkTable> m_networktable; bool m_led; double m_tx; double m_ty; bool m_validTarget; vector<double> m_averageDistance; vector<double> m_averageAngle; };
[ "xuegeo21@pewaukeeschools.org" ]
xuegeo21@pewaukeeschools.org
308823b6a4f26576a959309fc84de5d82cefda8b
8d782214cc09f43db64c49d5d646509de3e86b64
/Pc/convert/ExprConvert.h
25c8a64dfc87831fea7678ba5826e6c8f288ad4f
[]
no_license
Aardvajk/OPx
f8c39a9b3d2a3c7edae8d48d29480cee01aaf9f6
1f450602a5f0e69c1956e48e915c0a893a31aa29
refs/heads/master
2022-03-26T08:28:14.561146
2019-12-14T08:31:43
2019-12-14T08:31:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,298
h
#ifndef EXPRCONVERT_H #define EXPRCONVERT_H #include "nodes/Node.h" #include "visitors/Visitor.h" class Context; class Type; class ExprConvert : public Visitor { public: ExprConvert(Context &c, NodePtr &cn, Type *expectedType); NodePtr result(){ return rn; } virtual void visit(IdNode &node) override; virtual void visit(CallNode &node) override; virtual void visit(ProxyCallNode &node) override; virtual void visit(ConstructNode &node) override; virtual void visit(AddrOfNode &node) override; virtual void visit(DerefNode &node) override; virtual void visit(AssignNode &node) override; virtual void visit(UnaryNode &node) override; virtual void visit(BinaryNode &node) override; virtual void visit(LogicalNode &node) override; virtual void visit(PreIncDecNode &node) override; virtual void visit(PostIncDecNode &node) override; virtual void visit(CommaNode &node) override; virtual void visit(InlineVarNode &node) override; virtual void visit(TernaryNode &node) override; virtual void visit(TypeCastNode &node) override; static NodePtr convert(Context &c, NodePtr &node, Type *expectedType = nullptr); private: Context &c; NodePtr &cn; Type *expectedType; NodePtr rn; }; #endif // EXPRCONVERT_H
[ "aardvajk@live.co.uk" ]
aardvajk@live.co.uk
d224ce4c29ccf58352d05b260d2d5b889492e51c
7c71410d765d366a388d940c7859538c3b916198
/SSAM219G.cpp
c8346ef5a5c99beb63fc3fd8d2b3ed67518f155a
[]
no_license
dinhtai1104/SPOJ_PTIT
790f8474682e7c8d1a90f01bdd55aa697000897d
e7aef29eda3b0dea6ae5a833810f0a70d4ea4423
refs/heads/master
2022-12-03T22:27:23.397741
2020-08-26T16:00:07
2020-08-26T16:00:07
290,542,452
1
0
null
null
null
null
UTF-8
C++
false
false
595
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; void Solve() { ll n; cin >> n; ll a[n], res = 0; for (ll i = 0; i < n; i++) cin >> a[i]; for (ll i = 0; i < n; i++) { ll d = 1; for (ll j = i - 1; j >= 0; j--) { if (a[j] < a[i]) break; else { d++; } } for (ll j = i + 1; j < n; j++) { if (a[j] < a[i]) break; else { d++; } } res = max(res, a[i]*d); } cout << res << '\n'; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int test; cin >> test; while(test--) { Solve(); } return 0; }  
[ "51129122+dinhtai1104@users.noreply.github.com" ]
51129122+dinhtai1104@users.noreply.github.com
e7094b5f550529686034145ab2f9f6418b4c341f
4475b39e88036606eee23754ce5e5edead0b4f98
/codeforces/712/C.cpp
615960cabd63ac73b3bd0a861efb1a5d7c43943c
[]
no_license
abhayishere/Codes
a39ca15c451d8418df0fcf284d97daa16857bce0
88b88e19fa8607a538dc9ce9c89dc7d65f201ff0
refs/heads/master
2023-02-15T18:37:54.792783
2020-07-02T01:29:00
2021-01-15T09:34:37
329,863,777
0
0
null
null
null
null
UTF-8
C++
false
false
1,101
cpp
#include <bits/stdc++.h> #define int long long int #define mod 1000000007 #define endl '\n' using namespace std; #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #define decimal(x) cout<<fixed<<setprecision(x); #define form(i, n) for(int i = 0; i <n ;i++) #define mp make_pair #define pb push_back #define sortvec(v) sort(v.begin(),v.end()); #define sortarr(a,n) sort(a,a+n); typedef pair<int, int> pt; void solve() { int a,b; cin>>a>>b; int x=b,y=b,z=b; int ans=0; int k=100; while((x!=a || y!=a || z!=a) && k--) { x=min(a,y+z-1); ans++; if(x==a && y==a && z==a) break; y=min(a,z+x-1); ans++; if(x==a && y==a && z==a) break; z=min(a,x+y-1); ans++; if(x==a && y==a && z==a) break; } cout<<ans<<endl; } signed main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); int t=1; //cin>>t; while(t--) { solve(); } }
[ "62054505+abhayishere@users.noreply.github.com" ]
62054505+abhayishere@users.noreply.github.com
0158ad124f1508a64f3f9f91fb28d6df6e942df7
8c2b9a6baad4a19e8ffdbb02447dfd530ce954d8
/lib/Basics/Exceptions.h
0040d2a4b5ef70c8bcb323f15b49b7758a3b953b
[ "Apache-2.0" ]
permissive
alepharchives/ArangoDB
4c5bafc55aef96099360be3290dc386180e4690c
cf0dc533f7559c44dc837001f9da5438a325ea84
refs/heads/master
2021-01-18T16:40:44.316583
2012-11-13T16:23:24
2012-11-13T16:23:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,391
h
//////////////////////////////////////////////////////////////////////////////// /// @brief basic exceptions /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2012 triagens GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Copyright 2009-2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #ifndef TRIAGENS_BASICS_EXCEPTIONS_H #define TRIAGENS_BASICS_EXCEPTIONS_H 1 #include "Basics/Common.h" #include <errno.h> #if BOOST_VERSION < 103600 #undef USE_BOOST_EXCEPTIONS #else #define USE_BOOST_EXCEPTIONS 1 #endif #ifdef USE_BOOST_EXCEPTIONS #if BOOST_VERSION < 104000 #include <boost/exception.hpp> #else #include <boost/exception/all.hpp> #endif #include <boost/exception/info.hpp> #else #include "Basics/StringUtils.h" #endif // ----------------------------------------------------------------------------- // --SECTION-- boost // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup Utilities /// @{ //////////////////////////////////////////////////////////////////////////////// #if defined(USE_BOOST_EXCEPTIONS) && (BOOST_VERSION < 104000) namespace boost { typedef error_info<struct errinfo_api_function_,char const *> errinfo_api_function; typedef error_info<struct errinfo_at_line_,int> errinfo_at_line; typedef error_info<struct errinfo_errno_,int> errinfo_errno; typedef error_info<struct errinfo_file_name_,std::string> errinfo_file_name; typedef error_info<struct errinfo_file_open_mode_,std::string> errinfo_file_open_mode; } #endif //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- public macros // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup Utilities /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief diagnostic output //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define DIAGNOSTIC_INFORMATION(e) \ boost::diagnostic_information(e) #else #define DIAGNOSTIC_INFORMATION(e) \ e.diagnostic_information() #endif //////////////////////////////////////////////////////////////////////////////// /// @brief throws an unqualified exception /// /// Some compilers do not know that BOOST_THROW_EXCEPTION never returns. //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define THROW_TRIAGENS_ERROR(mesg, details) \ do { \ BOOST_THROW_EXCEPTION(triagens::basics::TriagensError() \ << triagens::ErrorMessage(mesg) \ << triagens::ErrorDetails(details)); \ throw "this cannot happen"; \ } \ while (0) #else #define THROW_TRIAGENS_ERROR(mesg, details) \ throw triagens::basics::TriagensError(mesg, details) #endif //////////////////////////////////////////////////////////////////////////////// /// @brief throws an exception for internal errors /// /// Some compilers do not know that BOOST_THROW_EXCEPTION never returns. //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define THROW_INTERNAL_ERROR(a) \ do { \ BOOST_THROW_EXCEPTION(triagens::basics::InternalError() \ << triagens::ErrorMessage(a) \ << boost::errinfo_at_line(__LINE__) \ << boost::errinfo_file_name(__FILE__)); \ throw "this cannot happen"; \ } \ while (0) #else #define THROW_INTERNAL_ERROR(a) \ throw triagens::basics::InternalError(a) #endif //////////////////////////////////////////////////////////////////////////////// /// @brief throws an exception for internal errors with line info /// /// Some compilers do not know that BOOST_THROW_EXCEPTION never returns. //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define THROW_INTERNAL_ERROR_L(a, file, line) \ do { \ BOOST_THROW_EXCEPTION(triagens::basics::InternalError() \ << triagens::ErrorMessage(a) \ << boost::errinfo_at_line(line) \ << boost::errinfo_file_name(file)); \ throw "this cannot happen"; \ } \ while (0) #else #define THROW_INTERNAL_ERROR_L(a, file, line) \ throw triagens::basics::InternalError(a) #endif //////////////////////////////////////////////////////////////////////////////// /// @brief throws an exception for out-of-memory errors /// /// Some compilers do not know that BOOST_THROW_EXCEPTION never returns. //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define THROW_OUT_OF_MEMORY_ERROR() \ do { \ BOOST_THROW_EXCEPTION(triagens::basics::OutOfMemoryError()); \ throw "this cannot happen"; \ } \ while (0) #else #define THROW_OUT_OF_MEMORY_ERROR() \ throw triagens::basics::OutOfMemoryError() #endif //////////////////////////////////////////////////////////////////////////////// /// @brief throws an exception for file open errors /// /// Some compilers do not know that BOOST_THROW_EXCEPTION never returns. //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define THROW_FILE_OPEN_ERROR(func, file, mode) \ do { \ BOOST_THROW_EXCEPTION(triagens::basics::FileError() \ << triagens::ErrorMessage("file open error") \ << boost::errinfo_api_function(func) \ << boost::errinfo_errno(errno) \ << boost::errinfo_file_name(file) \ << boost::errinfo_file_open_mode(mode)); \ throw "this cannot happen"; \ } \ while (0) #else #define THROW_FILE_OPEN_ERROR(func, file, mode) \ throw triagens::basics::FileError("file open error", file) #endif //////////////////////////////////////////////////////////////////////////////// /// @brief throws an exception for file errors /// /// Some compilers do not know that BOOST_THROW_EXCEPTION never returns. //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define THROW_FILE_FUNC_ERROR(func, mesg) \ do { \ BOOST_THROW_EXCEPTION(triagens::basics::FileError() \ << triagens::ErrorMessage(mesg) \ << boost::errinfo_api_function(func) \ << boost::errinfo_errno(errno)); \ throw "this cannot happen"; \ } \ while (0) #else #define THROW_FILE_FUNC_ERROR(func, mesg) \ throw triagens::basics::FileError(func, mesg) #endif //////////////////////////////////////////////////////////////////////////////// /// @brief throws an exception for file errors /// /// Some compilers do not know that BOOST_THROW_EXCEPTION never returns. //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define THROW_FILE_FUNC_ERROR_E(func, mesg, error) \ do { \ BOOST_THROW_EXCEPTION(triagens::basics::FileError() \ << triagens::ErrorMessage(mesg) \ << boost::errinfo_api_function(func) \ << boost::errinfo_errno(error)); \ throw "this cannot happen"; \ } \ while (0) #else #define THROW_FILE_FUNC_ERROR_E(func, mesg, error) \ throw triagens::basics::FileError(func, mesg + (" " + triagens::basics::StringUtils::itoa(error))) #endif //////////////////////////////////////////////////////////////////////////////// /// @brief throws an exception for file errors /// /// Some compilers do not know that BOOST_THROW_EXCEPTION never returns. //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define THROW_FILE_ERROR(mesg) \ do { \ BOOST_THROW_EXCEPTION(triagens::basics::FileError() \ << triagens::ErrorMessage(mesg)); \ throw "this cannot happen"; \ } \ while (0) #else #define THROW_FILE_ERROR(mesg) \ throw triagens::basics::FileError(mesg) #endif //////////////////////////////////////////////////////////////////////////////// /// @brief rethrows an exception with filename //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define RETHROW_FILE_NAME(ex, file) \ do { \ ex << boost::errinfo_file_name(file); \ throw ex; \ } while (0) #else #define RETHROW_FILE_NAME(ex, file) \ throw ex #endif //////////////////////////////////////////////////////////////////////////////// /// @brief throws an exception for parse errors /// /// Some compilers do not know that BOOST_THROW_EXCEPTION never returns. //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define THROW_PARSE_ERROR(mesg) \ do { \ BOOST_THROW_EXCEPTION(triagens::basics::ParseError() \ << triagens::ErrorMessage(mesg)); \ throw "this cannot happen"; \ } \ while (0) #else #define THROW_PARSE_ERROR(mesg) \ throw triagens::basics::ParseError(mesg) #endif //////////////////////////////////////////////////////////////////////////////// /// @brief throws an exception for parse errors /// /// Some compilers do not know that BOOST_THROW_EXCEPTION never returns. //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define THROW_PARSE_ERROR_L(line, mesg) \ do { \ BOOST_THROW_EXCEPTION(triagens::basics::ParseError() \ << triagens::ErrorMessage(mesg) \ << boost::errinfo_at_line(line)); \ throw "this cannot happen"; \ } \ while (0) #else #define THROW_PARSE_ERROR_L(line, mesg) \ throw triagens::basics::ParseError(mesg, "line " + triagens::basics::StringUtils::itoa(line)) #endif //////////////////////////////////////////////////////////////////////////////// /// @brief throws an exception for parse errors /// /// Some compilers do not know that BOOST_THROW_EXCEPTION never returns. //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define THROW_PARSE_ERROR_D(mesg, details) \ do { \ BOOST_THROW_EXCEPTION(triagens::basics::ParseError() \ << triagens::ErrorMessage(mesg) \ << triagens::ErrorDetails(details)); \ throw "this cannot happen"; \ } \ while (0) #else #define THROW_PARSE_ERROR_D(mesg, details) \ throw triagens::basics::ParseError(mesg, details) #endif //////////////////////////////////////////////////////////////////////////////// /// @brief rethrows an exception with line //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define RETHROW_LINE(ex, line) \ do { \ ex << boost::errinfo_at_line(line); \ throw ex; \ } while (0) #else #define RETHROW_LINE(ex, line) \ throw ex #endif //////////////////////////////////////////////////////////////////////////////// /// @brief throws an exception for parameter errors /// /// Some compilers do not know that BOOST_THROW_EXCEPTION never returns. //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS #define THROW_PARAMETER_ERROR(param, func, mesg) \ do { \ BOOST_THROW_EXCEPTION(triagens::basics::ParameterError() \ << triagens::ErrorMessage(mesg) \ << ErrorParameterName(param) \ << boost::errinfo_api_function(func)); \ throw "this cannot happen"; \ } \ while (0) #else #define THROW_PARAMETER_ERROR(param, func, mesg) \ throw triagens::basics::ParameterError(mesg, param + string(" in ") + func) #endif //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- public types // ----------------------------------------------------------------------------- namespace triagens { //////////////////////////////////////////////////////////////////////////////// /// @addtogroup Utilities /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief message info //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS typedef boost::error_info<struct TagMessage, std::string> ErrorMessage; #endif //////////////////////////////////////////////////////////////////////////////// /// @brief message details //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS typedef boost::error_info<struct TagDetails, std::string> ErrorDetails; #endif //////////////////////////////////////////////////////////////////////////////// /// @brief parameter name //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS typedef boost::error_info<struct TagParameterName, string> ErrorParameterName; #endif namespace basics { //////////////////////////////////////////////////////////////////////////////// /// @brief base class for all errors //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS class TriagensError : public virtual std::exception, public virtual boost::exception { public: ~TriagensError () throw() { } public: char const * what () const throw() { return "triagens error"; } string description () const { return boost::diagnostic_information(*this); } }; #else class TriagensError : public virtual std::exception { public: TriagensError () : message("unknown") { } TriagensError (string mesg) : message(mesg) { } TriagensError (string mesg, string details) : message(mesg + " (" + details + ")") { } ~TriagensError () throw() { } public: string diagnostic_information () const { return string(what()) + ": " + message; } string description () const { return diagnostic_information(); } char const * what () const throw() { return "triagens error"; } string const& details () const throw() { return message; } private: string const message; }; #endif //////////////////////////////////////////////////////////////////////////////// /// @brief exception for internal errors //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS struct InternalError : public TriagensError { public: InternalError () { } InternalError (string const& what) { *this << ErrorMessage(what); } InternalError (std::exception const& ex) { *this << ErrorMessage(ex.what()); } public: char const * what () const throw() { return "internal error"; } }; #else struct InternalError : public TriagensError { public: InternalError () : TriagensError("internal error") { } InternalError (string mesg) : TriagensError(mesg) { } InternalError (std::exception const& ex) : TriagensError(ex.what()) { } public: char const * what () const throw() { return "internal error"; } }; #endif //////////////////////////////////////////////////////////////////////////////// /// @brief exception for out-of-memory errors //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS struct OutOfMemoryError : public TriagensError { public: char const * what () const throw() { return "out-of-memory error"; } }; #else struct OutOfMemoryError : public TriagensError { public: OutOfMemoryError () : TriagensError("out-of-memory") { } public: char const * what () const throw() { return "out-of-memory error"; } }; #endif //////////////////////////////////////////////////////////////////////////////// /// @brief exception for file errors //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS struct FileError : public TriagensError { public: char const * what () const throw() { return "file error"; } }; #else struct FileError : public TriagensError { public: FileError () : TriagensError("file error") { } FileError (string mesg) : TriagensError(mesg) { } FileError (string mesg, string details) : TriagensError(mesg, details) { } public: char const * what () const throw() { return "file error"; } }; #endif //////////////////////////////////////////////////////////////////////////////// /// @brief exception for parse errors //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS struct ParseError : public TriagensError { public: char const * what () const throw() { return "parse error"; } }; #else struct ParseError : public TriagensError { public: ParseError () : TriagensError("parse error") { } ParseError (string mesg) : TriagensError(mesg) { } ParseError (string mesg, string details) : TriagensError(mesg, details) { } public: char const * what () const throw() { return "parse error"; } }; #endif //////////////////////////////////////////////////////////////////////////////// /// @brief exception for parameter errors //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS struct ParameterError : public TriagensError { public: char const * what () const throw() { return "parameter error"; } }; #else struct ParameterError : public TriagensError { public: ParameterError () : TriagensError("parameter error") { } ParameterError (string mesg) : TriagensError(mesg) { } ParameterError (string mesg, string details) : TriagensError(mesg, details) { } public: char const * what () const throw() { return "parameter error"; } }; #endif } } // ----------------------------------------------------------------------------- // --SECTION-- boost // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup Utilities /// @{ //////////////////////////////////////////////////////////////////////////////// #ifdef USE_BOOST_EXCEPTIONS /// @cond IGNORE namespace boost { #if BOOST_VERSION < 104300 #define TRIAGENS_TAG_TYPEID_NAME_RETURN_TYPE char const * #else #define TRIAGENS_TAG_TYPEID_NAME_RETURN_TYPE std::string #endif template<> inline TRIAGENS_TAG_TYPEID_NAME_RETURN_TYPE boost::error_info<struct triagens::TagMessage, std::string>::tag_typeid_name () const { return "message"; } template<> inline TRIAGENS_TAG_TYPEID_NAME_RETURN_TYPE boost::error_info<struct TagDetails, std::string>::tag_typeid_name () const { return "details"; } template<> inline TRIAGENS_TAG_TYPEID_NAME_RETURN_TYPE boost::errinfo_errno::tag_typeid_name () const { return "errno"; } template<> inline TRIAGENS_TAG_TYPEID_NAME_RETURN_TYPE boost::errinfo_file_name::tag_typeid_name () const { return "file name"; } template<> inline TRIAGENS_TAG_TYPEID_NAME_RETURN_TYPE boost::errinfo_file_open_mode::tag_typeid_name () const { return "file open mode"; } template<> inline TRIAGENS_TAG_TYPEID_NAME_RETURN_TYPE boost::errinfo_api_function::tag_typeid_name () const { return "api function"; } template<> inline TRIAGENS_TAG_TYPEID_NAME_RETURN_TYPE boost::errinfo_at_line::tag_typeid_name () const { return "at line"; } #undef TRIAGENS_TAG_TYPEID_NAME_RETURN_TYPE } /// @endcond #endif //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// #endif // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)" // End:
[ "f.celler@triagens.de" ]
f.celler@triagens.de
5737eb731d2dcadf05af0428153b6e7bbda918c4
85e514e6b9d8b16d08890977a2695bb6070675ac
/osvr/Display/Display.cpp
029ab20a92b0010a64febb03ec86d9477db0d4b9
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
digideskio/OSVR-Display
faf3df612f702624070f7b0a3cbd71a9a37e3fa6
05c26d0a49ffae4304d8e070085db09fa9b5c582
refs/heads/master
2020-12-25T22:07:02.292036
2016-08-20T22:15:00
2016-08-20T22:15:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,672
cpp
/** @file @brief Display struct and related types. @date 2016 @author Sensics, Inc. <http://sensics.com> */ // Copyright 2016 Sensics, 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. // Internal Includes #include <osvr/Display/Display.h> // Library/third-party includes // - none // Standard includes #include <cmath> #include <cstdint> #include <string> namespace osvr { namespace display { bool DisplaySize::operator==(const DisplaySize& other) const { if (width != other.width) return false; if (height != other.height) return false; return true; } bool DisplaySize::operator!=(const DisplaySize& other) const { return !(*this == other); } bool DisplayPosition::operator==(const DisplayPosition& other) const { if (x != other.x) return false; if (y != other.y) return false; return true; } bool DisplayPosition::operator!=(const DisplayPosition& other) const { return !(*this == other); } bool DisplayAdapter::operator==(const DisplayAdapter& other) const { if (description != other.description) return false; return true; } bool DisplayAdapter::operator!=(const DisplayAdapter& other) const { return !(*this == other); } Rotation operator-(const DesktopOrientation lhs, const DesktopOrientation rhs) { const auto difference = (4 + static_cast<int>(lhs) - static_cast<int>(rhs)) % 4; switch (difference) { case 0: return Rotation::Zero; case 1: return Rotation::Ninety; case 2: return Rotation::OneEighty; case 3: return Rotation::TwoSeventy; default: // ERROR! Shouldn't get here. Check to see if the Rotation or // DesktopOrientation enums have changed. return Rotation::Zero; } } DesktopOrientation operator+(DesktopOrientation orientation, Rotation rotation) { return static_cast<DesktopOrientation>((static_cast<int>(orientation) + static_cast<int>(rotation)) % 4); } DesktopOrientation operator+(Rotation rotation, DesktopOrientation orientation) { return orientation + rotation; } DesktopOrientation operator-(DesktopOrientation orientation, Rotation rotation) { return static_cast<DesktopOrientation>((static_cast<int>(orientation) - static_cast<int>(rotation) + 4) % 4); } DesktopOrientation operator+(ScanOutOrigin origin, Rotation rotation) { int shift = 0; if (ScanOutOrigin::UpperLeft == origin) { shift = 0; } else if (ScanOutOrigin::LowerLeft == origin) { shift = 1; } else if (ScanOutOrigin::LowerRight == origin) { shift = 2; } else if (ScanOutOrigin::UpperRight == origin) { shift = 3; } if (Rotation::Zero == rotation) { shift += 0; } else if (Rotation::Ninety == rotation) { shift += 1; } else if (Rotation::OneEighty == rotation) { shift += 2; } else if (Rotation::TwoSeventy == rotation) { shift += 3; } const auto orientation = static_cast<DesktopOrientation>((static_cast<int>(DesktopOrientation::Landscape) + shift) % 4); return orientation; } DesktopOrientation operator+(Rotation rotation, ScanOutOrigin origin) { return origin + rotation; } DesktopOrientation operator-(ScanOutOrigin origin, Rotation rotation) { // FIXME int shift = 0; if (ScanOutOrigin::UpperLeft == origin) { shift = 0; } else if (ScanOutOrigin::LowerLeft == origin) { shift = 1; } else if (ScanOutOrigin::LowerRight == origin) { shift = 2; } else if (ScanOutOrigin::UpperRight == origin) { shift = 3; } if (Rotation::Zero == rotation) { shift += 0; } else if (Rotation::Ninety == rotation) { shift += 1; } else if (Rotation::OneEighty == rotation) { shift += 2; } else if (Rotation::TwoSeventy == rotation) { shift += 3; } const auto orientation = static_cast<DesktopOrientation>((static_cast<int>(DesktopOrientation::Landscape) + shift) % 4); return orientation; } Rotation operator-(const Rotation rotation) { return static_cast<Rotation>((4 - static_cast<int>(rotation)) % 4); } bool Display::operator==(const Display& other) const { if (adapter != other.adapter) return false; if (name != other.name) return false; if (size != other.size) return false; if (position != other.position) return false; if (rotation != other.rotation) return false; if (verticalRefreshRate != other.verticalRefreshRate) return false; if (attachedToDesktop != other.attachedToDesktop) return false; if (edidProductId != other.edidProductId) return false; if (edidVendorId != other.edidVendorId) return false; return true; } bool Display::operator!=(const Display& other) const { return !(*this == other); } OSVR_DISPLAY_EXPORT std::string to_string(const Rotation rotation) { switch (rotation) { case osvr::display::Rotation::Zero: return "0 degrees counter-clockwise"; case osvr::display::Rotation::Ninety: return "90 degrees counter-clockwise"; case osvr::display::Rotation::OneEighty: return "180 degrees counter-clockwise"; case osvr::display::Rotation::TwoSeventy: return "270 degrees counter-clockwise"; default: return "Unknown rotation: " + std::to_string(static_cast<int>(rotation)); } } OSVR_DISPLAY_EXPORT std::string to_string(const DesktopOrientation orientation) { switch (orientation) { case osvr::display::DesktopOrientation::Landscape: return "Landscape"; case osvr::display::DesktopOrientation::Portrait: return "Portrait"; case osvr::display::DesktopOrientation::LandscapeFlipped: return "Landscape (flipped)"; case osvr::display::DesktopOrientation::PortraitFlipped: return "Portrait (flipped)"; default: return "Unknown orientation: " + std::to_string(static_cast<int>(orientation)); } } OSVR_DISPLAY_EXPORT std::string to_string(const ScanOutOrigin origin) { switch (origin) { case ScanOutOrigin::UpperLeft: return "Upper-left"; case ScanOutOrigin::UpperRight: return "Upper-right"; case ScanOutOrigin::LowerRight: return "Lower-right"; case ScanOutOrigin::LowerLeft: return "Lower-left"; default: return "Unknown scan-out origin: " + std::to_string(static_cast<int>(origin)); } } OSVR_DISPLAY_EXPORT std::string decodeEdidVendorId(uint32_t vid) { // The vid is two bytes wsde. The most-significant bit is always 0. The // remaining 15 bits are split into five-bit segments. Each segment // represents a letter (0b00001 = A, 0b00010 = B, etc.). // // We'll just mask out each letter's bits and convert it to a character. // Then append each character to a string to get the three-letter vendor ID. // But first, we need to swap the bytes. vid = ((vid & 0xff00) >> 8) | ((vid & 0x00ff) << 8); std::string str = " "; str[2] = 'A' + ((vid >> 0) & 0x1f) - 1; str[1] = 'A' + ((vid >> 5) & 0x1f) - 1; str[0] = 'A' + ((vid >> 10) & 0x1f) - 1; return str; } } // end namespace display } // end namespace osvr
[ "kevin@godby.org" ]
kevin@godby.org
a3dca989aff690da585c0b78506771626ef3bd0b
77f7b9c32665fe795c8d6c77412dce8c8013a3c1
/BaseCommon/BaseCommon/Md5Tool.cpp
dc30aa8e8bdd6ff0a8308c7c917a41c80f76efa8
[]
no_license
wenge8126/MemoryDB
7d9fb7e8aaf2393941f90089f80cf6bd6a9b1419
b5e133a23db94039990270a198f29bb4b0275cdc
refs/heads/master
2021-09-10T16:21:00.935843
2018-03-29T05:47:45
2018-03-29T05:47:45
113,527,948
0
1
null
null
null
null
UTF-8
C++
false
false
9,086
cpp
#include "md5tool.h" using namespace std; /* Constants for MD5Transform routine. */ #define S11 7 #define S12 12 #define S13 17 #define S14 22 #define S21 5 #define S22 9 #define S23 14 #define S24 20 #define S31 4 #define S32 11 #define S33 16 #define S34 23 #define S41 6 #define S42 10 #define S43 15 #define S44 21 /* F, G, H and I are basic MD5 functions. */ #define F(x, y, z) (((x) & (y)) | ((~x) & (z))) #define G(x, y, z) (((x) & (z)) | ((y) & (~z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) #define I(x, y, z) ((y) ^ ((x) | (~z))) /* ROTATE_LEFT rotates x left n bits. */ #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) /* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent recomputation. */ #define FF(a, b, c, d, x, s, ac) { \ (a) += F ((b), (c), (d)) + (x) + ac; \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define GG(a, b, c, d, x, s, ac) { \ (a) += G ((b), (c), (d)) + (x) + ac; \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define HH(a, b, c, d, x, s, ac) { \ (a) += H ((b), (c), (d)) + (x) + ac; \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define II(a, b, c, d, x, s, ac) { \ (a) += I ((b), (c), (d)) + (x) + ac; \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } const byte MD5::PADDING[64] = { 0x80 }; const char MD5::HEX[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /* Default construct. */ MD5::MD5() { reset(); } /* Construct a MD5 object with a input buffer. */ MD5::MD5(const void *input, size_t length) { reset(); update(input, length); } /* Construct a MD5 object with a string. */ MD5::MD5(const string &str) { reset(); update(str); } /* Construct a MD5 object with a file. */ MD5::MD5(ifstream &in) { reset(); update(in); } /* Return the message-digest */ const byte* MD5::digest() { if (!_finished) { _finished = true; final(); } return _digest; } /* Reset the calculate state */ void MD5::reset() { _finished = false; /* reset number of bits. */ _count[0] = _count[1] = 0; /* Load magic initialization constants. */ _state[0] = 0x67452301; _state[1] = 0xefcdab89; _state[2] = 0x98badcfe; _state[3] = 0x10325476; } /* Updating the context with a input buffer. */ void MD5::update(const void *input, size_t length) { update((const byte*)input, length); } /* Updating the context with a string. */ void MD5::update(const string &str) { update((const byte*)str.c_str(), str.length()); } /* Updating the context with a file. */ void MD5::update(ifstream &in) { if (!in) return; std::streamsize length; char buffer[BUFFER_SIZE]; while (!in.eof()) { in.read(buffer, BUFFER_SIZE); length = in.gcount(); if (length > 0) update(buffer, (size_t)length); } in.close(); } /* MD5 block update operation. Continues an MD5 message-digest operation, processing another message block, and updating the context. */ void MD5::update(const byte *input, size_t length) { ulong i, index, partLen; _finished = false; /* Compute number of bytes mod 64 */ index = (ulong)((_count[0] >> 3) & 0x3f); /* update number of bits */ if((_count[0] += ((ulong)length << 3)) < ((ulong)length << 3)) _count[1]++; _count[1] += ((ulong)length >> 29); partLen = 64 - index; /* transform as many times as possible. */ if(length >= partLen) { memcpy(&_buffer[index], input, partLen); transform(_buffer); for (i = partLen; i + 63 < length; i += 64) transform(&input[i]); index = 0; } else { i = 0; } /* Buffer remaining input */ memcpy(&_buffer[index], &input[i], length-i); } /* MD5 finalization. Ends an MD5 message-_digest operation, writing the the message _digest and zeroizing the context. */ void MD5::final() { byte bits[8]; ulong oldState[4]; ulong oldCount[2]; ulong index, padLen; /* Save current state and count. */ memcpy(oldState, _state, 16); memcpy(oldCount, _count, 8); /* Save number of bits */ encode(_count, bits, 8); /* Pad out to 56 mod 64. */ index = (ulong)((_count[0] >> 3) & 0x3f); padLen = (index < 56) ? (56 - index) : (120 - index); update(PADDING, padLen); /* Append length (before padding) */ update(bits, 8); /* Store state in digest */ encode(_state, _digest, 16); /* Restore current state and count. */ memcpy(_state, oldState, 16); memcpy(_count, oldCount, 8); } /* MD5 basic transformation. Transforms _state based on block. */ void MD5::transform(const byte block[64]) { ulong a = _state[0], b = _state[1], c = _state[2], d = _state[3], x[16]; decode(block, x, 64); /* Round 1 */ FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ _state[0] += a; _state[1] += b; _state[2] += c; _state[3] += d; } /* Encodes input (ulong) into output (byte). Assumes length is a multiple of 4. */ void MD5::encode(const ulong *input, byte *output, size_t length) { for(size_t i=0, j=0; j<length; i++, j+=4) { output[j]= (byte)(input[i] & 0xff); output[j+1] = (byte)((input[i] >> 8) & 0xff); output[j+2] = (byte)((input[i] >> 16) & 0xff); output[j+3] = (byte)((input[i] >> 24) & 0xff); } } /* Decodes input (byte) into output (ulong). Assumes length is a multiple of 4. */ void MD5::decode(const byte *input, ulong *output, size_t length) { for(size_t i=0, j=0; j<length; i++, j+=4) { output[i] = ((ulong)input[j]) | (((ulong)input[j+1]) << 8) | (((ulong)input[j+2]) << 16) | (((ulong)input[j+3]) << 24); } } /* Convert byte array to hex string. */ string MD5::bytesToHexString(const byte *input, size_t length) { string str; str.reserve(length << 1); for(size_t i = 0; i < length; i++) { int t = input[i]; int a = t / 16; int b = t % 16; str.append(1, HEX[a]); str.append(1, HEX[b]); } return str; } /* Convert digest to string value */ string MD5::toString() { return bytesToHexString(digest(), 16); }
[ "34360740+wenge8126@users.noreply.github.com" ]
34360740+wenge8126@users.noreply.github.com
7072a3b9e4e52ecce62e2ec04bdb699635016d13
525dc6ab33a8e5bc90d8009e06bd86ec6561854c
/Snake.h
a2a0313830ddf10771662362600b973bcb503150
[]
no_license
lethanhnam305/lameSnake
a645cb2fe6cfa51e50f6b5b9f35616057513d886
277fffcfabca9ef0c828a02efd3cefc883117327
refs/heads/master
2020-07-15T22:48:11.314237
2019-09-01T11:15:01
2019-09-01T11:15:01
205,665,260
0
0
null
null
null
null
UTF-8
C++
false
false
585
h
#pragma once #include <iostream> #include <Windows.h> #include <stdlib.h> #include <time.h> #include <vector> #include "console.h" #include<conio.h> using namespace std; enum Status { UP, DOWN, LEFT, RIGHT, STOP, }; struct Coordinate { int x, y; }; class Snake { private: int length; Status Status; static Snake* m_Instance; ~Snake(); Snake(); Coordinate * head; public: int getX(); int getY(); int getLength(); void snakeGrowth(); static Snake* createSnake(); void move(); void print(); bool touchWall(); bool biteItself(); };
[ "noreply@github.com" ]
noreply@github.com
52f47ea37ad5c324b955c722cde6daee6f928dab
ca0b8d79fbce09ecbab4b9279fb230c2a7ad370a
/Esercizi Libro/Capitolo 11/11.4/11.4.3/11.4.3.cpp
322a31bfa2ec228e299298ccd40eb0e3910b38f2
[]
no_license
FIUP/Programmazione-1
6523e4d7a5c64370eef5b7ac8e6c5687b620ffd8
a897af997a5ded0d6e167f9f03d846d54a161add
refs/heads/master
2021-06-03T16:22:01.190618
2020-09-30T20:57:12
2020-09-30T20:57:12
80,129,830
23
39
null
2020-09-30T20:57:13
2017-01-26T16:01:07
C++
UTF-8
C++
false
false
2,851
cpp
/* Scrivere una funzione ricorsiva nodo* alt_mix(nodo* P, nodo* Q) che riceva per valore due liste (possibilmente vuote) P e Q e restituisca col return una lista composta da un nodo di P, seguita da un nodo di Q, poi di nuovo un nodo di P e cosi' via. Se una delle due liste finisce prima dell'altra */ #include<iostream> using namespace std; struct nodo {char info; nodo * next; nodo(char a='\0', nodo * b=0) {info=a; next=b;}}; /* Notazione: mix(P,Q) - se P e' vuota mix(P,Q)=Q - se Q e' vuota mix(P,Q)=P - altrimenti mix(P,Q)=p@q@mix(P',Q') (con P=p@P' e Q=q@Q') */ nodo* alt_mix(nodo* P, nodo* Q) { // PRE = (P e Q sono due liste corrette, eventualmente vuote (vP=P e vQ=Q)) if (!P) return Q; if (!Q) return P; nodo* t=P->next; nodo* s=Q->next; P->next=Q; Q->next=alt_mix(t,s); return P; // POST = (alt_mix restituisce mix(P,Q)) } /* CASO BASE Supponiamo di essere nel primo dei casi base. Supponiamo cioe' che P sia una lista vuota. Viene restituito Q. E' giusto? O meglio, rispetta POST questa cosa? Si. Infatti POST afferma che deve essere restituito mix(P,Q). Ma mix(P,Q)=Q nel caso in cui P sia vuota. Quindi POST e' verificata. Supponiamo ora di essere nel secondo caso base. Supponiamo cioe' che Q sia una lista vuota. In questo caso la funzione restituisce P. E' corretta questa cosa rispetto a POST? Si. Infatti POST afferma che deve essere restituito mix(P,Q). Ma mix(P,Q)=P nel caso in cui Q sia vuota. Quindi POST e' verificata. PASSO INDUTTIVO Supponiamo ora di non essere in nessuno dei casi base (e ovviamente sappiamo che vale PRE). Quindi, di conseguenza, siamo sicuri che P e Q hanno almeno un nodo. Cosa viene fatto in questo caso? Viene concatenato il primo nodo di P (p) con il primo nodo di Q (q). Poi viene concatenato a q il risultato della chiamata ricorsiva. Per la chiamata ricorsiva abbiamo la seguente PRE_RIC: PRE_RIC = (P' e Q' sono due liste corrette, eventualmente vuote (vP'=P' e vQ=Q')) Essa e' verificata al momento della chiamata ricorsiva? Ricordiamo che P=p@restoP e che Q=q@restoQ. Alla funzione vengono passati proprio restoP e restoQ. Sono due liste corrette? Sicuramente. Infatti esse sono parte di P e Q che, per ipotesi, erano liste corrette (non vuote). Quindi PRE_RIC e' verificata. Possiamo dunque supporre che valga POST_RIC. Essa afferma che viene restituito mix(P',Q') che, in questo caso, equivale a mix(restoP,restoQ). Questo risultato viene concatenato a q (che era stato a sua volta concatenato a p). Quindi abbiamo p@q@mix(restoP,restoQ)=mix(P,Q). Questa e' esattamente POST, quindi la funzione ricorsiva e' corretta. */ void stampa(nodo* P) { if (!P) return; cout << P->info << ' '; stampa(P->next); } main() { nodo* P=new nodo('a', new nodo('b', new nodo('c', 0))); nodo* Q=new nodo('d', new nodo('e', new nodo('f', 0))); P=alt_mix(P,Q); stampa(P); }
[ "fedsib@hotmail.it" ]
fedsib@hotmail.it
26a7534de9277b253d40c75229df1c4ff0538a7b
3cbdcff94aa15e9459e19004fefc495243495466
/pa03/sqtree.cpp
a3b1767f544cd7f14a2e4150c2cdbd15e3673e2c
[]
no_license
anggelazhou/cpsc-221
329fc83cc3e13105e24cad8d2ffe44fb5ffbb169
ee7b1641e35d86611d3282b04a2122b1552ae47a
refs/heads/master
2023-04-05T10:10:57.954549
2021-03-31T02:42:03
2021-03-31T02:42:03
336,433,705
0
0
null
null
null
null
UTF-8
C++
false
false
6,434
cpp
/** * * shifty quadtree (pa3) * sqtree.cpp * This file will be used for grading. * */ #include "sqtree.h" // First Node constructor, given. SQtree::Node::Node(pair<int,int> ul, int w, int h, RGBAPixel a, double v) :upLeft(ul),width(w),height(h),avg(a),var(v),NW(NULL),NE(NULL),SE(NULL),SW(NULL) {} // Second Node constructor, given SQtree::Node::Node(stats & s, pair<int,int> ul, int w, int h) :upLeft(ul),width(w),height(h),NW(NULL),NE(NULL),SE(NULL),SW(NULL) { avg = s.getAvg(ul,w,h); var = s.getVar(ul,w,h); } // SQtree destructor, given. SQtree::~SQtree() { clear(); } // SQtree copy constructor, given. SQtree::SQtree(const SQtree & other) { copy(other); } // SQtree assignment operator, given. SQtree & SQtree::operator=(const SQtree & rhs) { if (this != &rhs) { clear(); copy(rhs); } return *this; } /** * SQtree constructor given tolerance for variance. */ SQtree::SQtree(PNG & imIn, double tol) { // Your code here. stats s(imIn); pair<int,int> origin(0, 0); root = buildTree(s, origin, imIn.width(), imIn.height(), tol); } /** * Helper for the SQtree constructor. */ SQtree::Node * SQtree::buildTree(stats & s, pair<int,int> & ul, int w, int h, double tol) { // Your code here. Node * node = new Node(s, ul, w, h); double minMaxVar = -1; int minX; int minY; bool withinTol = false; for (int x = 0; x < w && !withinTol; x++) { for (int y = 0; y < h && !withinTol; y++) { if (x == 0 && y == 0) { // itself so don't do anything continue; } double neVar = -1; double nwVar = -1; double seVar = -1; double swVar = -1; if (x == 0) { // horizontal cuts nwVar = s.getVar(ul, w, y); pair<int,int> newUl(ul.first, ul.second + y); swVar = s.getVar(newUl, w, h - y); } else if (y == 0) { // vertical cuts nwVar = s.getVar(ul, x, h); pair<int,int> newUl(ul.first + x, ul.second); neVar = s.getVar(newUl, w - x, h); } else { // horizontal and vertical cuts nwVar = s.getVar(ul, x, y); pair<int,int> newUl(ul.first + x, ul.second); neVar = s.getVar(newUl, w - x, y); pair<int,int> newUl1(ul.first, ul.second + y); swVar = s.getVar(newUl1, x, h - y); pair<int,int> newUl2(ul.first + x, ul.second + y); seVar = s.getVar(newUl2, w - x, h - y); } // save biggest variance from the two/four double currMax = max(max(neVar, nwVar), max(seVar, swVar)); // find the minimum variance from the maximums if (currMax >= tol) { if (minMaxVar == -1 || minMaxVar > currMax) { minMaxVar = currMax; minX = x; minY = y; } else if (minMaxVar == currMax) { if ( (minX == 0 || minY == 0) && x != 0 && y != 0 ) { minX = x; minY = y; } } } else { withinTol = true; } } } if (!withinTol && minMaxVar != -1) { // either within tolerance or is 1X1 // split if (minX == 0) { node->NW = buildTree(s, ul, w, minY, tol); pair<int,int> newUl(ul.first, ul.second + minY); node->SW = buildTree(s, newUl, w, h - minY, tol); } else if (minY == 0) { node->NW = buildTree(s, ul, minX, h, tol); pair<int,int> newUl(ul.first + minX, ul.second); node->NE = buildTree(s, newUl, w - minX, h, tol); } else { node->NW = buildTree(s, ul,minX, minY, tol); pair<int,int> newUl(ul.first + minX, ul.second); node->NE = buildTree(s, newUl, w - minX, minY, tol); pair<int,int> newUl1(ul.first, ul.second + minY); node->SW = buildTree(s, newUl1, minX, h - minY, tol); pair<int,int> newUl2(ul.first + minX, ul.second + minY); node->SE = buildTree(s, newUl2, w - minX, h - minY, tol); } } return node; } /** * Render SQtree and return the resulting image. */ PNG SQtree::render() { // Your code here. PNG ret(root->width, root->height); renderNode(root, ret); return ret; } /** * Delete allocated memory. */ void SQtree::clear() { // Your code here. deleteNode(root); } void SQtree::copy(const SQtree & other) { // Your code here. root = copyNode(other.root); } int SQtree::size() { // Your code here. return nodeCount(root); } int SQtree::nodeCount(Node * node) { int count = 1; if (node->NE != NULL) { count += nodeCount(node->NE); } if (node->NW != NULL) { count += nodeCount(node->NW); } if (node->SE != NULL) { count += nodeCount(node->SE); } if (node->SW != NULL) { count += nodeCount(node->SW); } return count; } void SQtree::deleteNode(Node * node) { if (node->NE != NULL) { deleteNode(node->NE); } if (node->NW != NULL) { deleteNode(node->NW); } if (node->SE != NULL) { deleteNode(node->SE); } if (node->SW != NULL) { deleteNode(node->SW); } delete node; } SQtree::Node * SQtree::copyNode(Node * node) { Node * ret = new Node(node->upLeft, node->width, node->height, node->avg, node->var); if (node->NE != NULL) { ret->NE = copyNode(node->NE); } if (node->NW != NULL) { ret->NW = copyNode(node->NW); } if (node->SE != NULL) { ret->SE = copyNode(node->SE); } if (node->SW != NULL) { ret->SW = copyNode(node->SW); } return ret; } void SQtree::renderNode(Node * node, PNG & im) { bool leaf = true; if (node->NE != NULL) { renderNode(node->NE, im); leaf = false; } if (node->NW != NULL) { renderNode(node->NW, im); leaf = false; } if (node->SE != NULL) { renderNode(node->SE, im); leaf = false; } if (node->SW != NULL) { renderNode(node->SW, im); leaf = false; } if (leaf) { for (int x = node->upLeft.first; x < node->width + node->upLeft.first; x++) { for(int y = node->upLeft.second; y < node->height + node->upLeft.second; y++) { RGBAPixel * pixel = im.getPixel(x, y); pixel->r = node->avg.r; pixel->g = node->avg.g; pixel->b = node->avg.b; } } } }
[ "angelazhouqi@gmail.com" ]
angelazhouqi@gmail.com
73d817bcd143b72e8ba2de553deb17692178930b
e22eea26f2654436cab0600585b1e82b4dcfa235
/kdtree.hpp
02c162ef18da7db30661644e3c3e2eb9eff91910
[]
no_license
pranavladkat/KdTree
1196a63e02a8d27575583ce55a1ad957fa843ff9
402d3e4c3e31c087ec115d6ab24dc56acf7d4adb
refs/heads/master
2021-01-10T04:38:47.649385
2016-01-05T22:05:58
2016-01-05T22:05:58
49,095,350
0
0
null
null
null
null
UTF-8
C++
false
false
5,370
hpp
#ifndef KDTREE_HPP #define KDTREE_HPP #include <iostream> #include <memory> #include <vector> #include <algorithm> #include <memory> #include <limits> #include <cassert> template<typename Point> class KdTree{ public: KdTree():root(nullptr){} ~KdTree(){} void build_kdtree(std::vector<std::shared_ptr<Point>>& points){ root = build_subtree(points); } size_t nearest_neighbour(const Point& qpoint) const { // pair of (id, distance) representing nearest node std::pair<size_t, double> best_node(0,std::numeric_limits<double>::max()); //start with root size_t id = nearest(qpoint, root, best_node); return id; } private: struct KdNode{ std::shared_ptr<Point> point; // point data std::pair<size_t, typename Point::value_type> split; // split(dimension,value) bool leaf; // is it a leaf node? std::shared_ptr<KdNode> kd_left; // left child std::shared_ptr<KdNode> kd_right; // right child KdNode(): leaf(false), kd_left(nullptr), kd_right(nullptr) {} }; std::shared_ptr<KdNode> root; // root node std::shared_ptr<KdNode> build_subtree(std::vector<std::shared_ptr<Point>>& points){ // return null if empty input vector if(points.size() == 0){ return nullptr; } std::shared_ptr<KdNode> node = std::make_shared<KdNode>(); // leaf node if only 1 element in input vector if(points.size() == 1){ node->point = points[0]; node->leaf = true; return node; } // get split dimension and value (also partitions input vector about median) // i.e. all elements less than split value are at < median position // and elements greater than split value are at > median position node->split = get_split(points); size_t median = points.size() / 2; // assign point at median to current node node->point = points[median]; // create vector of points which are less/greater than key value std::vector<std::shared_ptr<Point>> left_vec(points.begin(), points.begin()+median); std::vector<std::shared_ptr<Point>> right_vec(points.begin()+median+1, points.end()); // build left/right subtree node->kd_left = build_subtree(left_vec); node->kd_right = build_subtree(right_vec); return node; } std::pair<size_t, typename Point::value_type> get_split(std::vector<std::shared_ptr<Point>>& points){ std::pair<size_t, typename Point::value_type> split(-1,-1); size_t total_points = points.size(); size_t dim = points[0]->data.size(); double max_var = -1; // get dimension with maximum variance for(size_t i = 0; i < dim; ++i){ double mean = 0, var = 0, x; // calculate mean for(size_t j = 0; j < total_points; ++j){ mean += points[j]->data[i]; } mean /= (double)total_points; // calculate variance for(size_t j = 0; j < total_points; ++j){ x = points[j]->data[i] - mean; var += x * x; } var /= ((double)total_points-1); // get dimension with max variance if(max_var < var){ split.first = i; max_var = var; } } size_t median = total_points / 2; // find median in the dimension having max variance std::nth_element(points.begin(), points.begin()+median, points.end(), [&split](std::shared_ptr<Point> a, std::shared_ptr<Point> b){ return a->data[split.first] < b->data[split.first]; }); // get split value split.second = points[median]->data[split.first]; return split; } // find nearest node size_t nearest(const Point& qpoint, const std::shared_ptr<KdNode> node, std::pair<size_t,double>& best) const { //std::cout << "best = " << best.first << " - " << best.second << std::endl; size_t id = node->point->id; double distance = this->distance(qpoint,node->point); if(distance < best.second){ best.first = id; best.second = distance; } if(!node->leaf){ std::shared_ptr<KdNode> near, far; if(qpoint.data[node->split.first] <= node->split.second){ near = node->kd_left; far = node->kd_right; }else{ near = node->kd_right; far = node->kd_left; } id = nearest(qpoint,near,best); if(distance >= best.second) return best.first; id = nearest(qpoint,far,best); } return best.first; } // computes euclidian distance double distance(const Point& pt1, const std::shared_ptr<Point> pt2) const { size_t dim = pt1.data.size(); double distance = 0; for(size_t i = 0; i < dim; i++){ double x = pt1.data[i] - pt2->data[i]; distance += x*x; } return distance; } }; // end class def #endif // KDTREE_HPP
[ "pranavladkat@gmail.com" ]
pranavladkat@gmail.com
7a4ccf3f855b9b001427ed37fa1825fccb05b4ea
05f7573db159e870fb26c847991c4cb8c407ed4c
/VBF/Source/VBF_App/ModelingTool/VBF_GlobalGIS_Plot.h
180d4c7e9b1f817070d6e98dda006d78e0a39f2e
[]
no_license
riyue625/OneGIS.ModelingTool
e126ef43429ce58d22c65832d96dbd113eacbf85
daf3dc91584df7ecfed6a51130ecdf6671614ac4
refs/heads/master
2020-05-28T12:12:43.543730
2018-09-06T07:42:00
2018-09-06T07:42:00
null
0
0
null
null
null
null
GB18030
C++
false
false
3,443
h
//******************************************************************* // FileName:VBF_GlobalGIS_Plot.h // Function:测试标图模型需要的共享头文件,提供共用的变量和内联函数 // Author: 杜莹 // Date: 2014-09-04 //******************************************************************* #ifndef __VBF_GLOBALGIS_PLOT_H__ #define __VBF_GLOBALGIS_PLOT_H__ #include <string> #include <vector> #include <VBF_MainCtrl/IVBF_MainCtrl.h> #include <VBF_MainCtrl/IVBF_3DMainCtrl.h> #include <VBF_Plot/IVBF_3DPlot.h> #include <VBF_Plot/IVBF_3DPlotDoc.h> #include <VBF_Plot/IVBF_3DPlotLayer.h> #include <VBF_Display/IVBF_3DDisplay.h> extern string g_sDataPath; extern IVBF_3DPlot* g_pI3DPlot; // 3D标图接口 extern std::string g_strDocName; // 各类模型共用的标图文档 extern float s_fMeshScale; // Mesh模型的放大倍数 extern osg::Vec3d g_vGeo; // 模型的定位点(地理坐标) //----------------------------------------------------------------------------- // 内联函数:VBF_Get3DPlot() // 函数描述:获取3D标图接口 //----------------------------------------------------------------------------- inline IVBF_3DPlot* VBF_Get3DPlot(IVBF_MainCtrl* pIMainCtrl) { if(g_pI3DPlot!=NULL) return g_pI3DPlot; if(NULL==pIMainCtrl) return NULL; g_pI3DPlot = (IVBF_3DPlot*)pIMainCtrl->QueryInterface(VBF_INTERFACE_3DPLOT); return g_pI3DPlot; } //----------------------------------------------------------------------------- // 内联函数:VBF_CreateDocLayer() // 函数描述:创建标图文档与图层 //----------------------------------------------------------------------------- inline bool VBF_CreateDocLayer(IVBF_MainCtrl* pIMainCtrl, const std::string& strDocName, const std::string& strLayerName, IVBF_3DPlotDoc*& pIDoc, IVBF_3DPlotLayer*& pILayer,EVBF_SRS srs = ECEF) { if(NULL==pIMainCtrl) return false; IVBF_3DPlot* pI3DPlot = (IVBF_3DPlot*)pIMainCtrl->QueryInterface(VBF_INTERFACE_3DPLOT); if(NULL==pI3DPlot) return false; pIDoc = pI3DPlot->AddDoc(strDocName); if(NULL==pIDoc) return false; pI3DPlot->ActivateDoc(strDocName); pILayer = pIDoc->AddLayer(strLayerName,srs); if(NULL==pILayer) return false; return true; } //----------------------------------------------------------------------------- // 内联函数:VBF_DeleteDoc() // 函数描述:删除指定的标图文档 //----------------------------------------------------------------------------- inline void VBF_DeleteDoc(IVBF_MainCtrl* pIMainCtrl, const std::string& strDocName) { IVBF_3DPlot* pI3DPlot = (IVBF_3DPlot*)pIMainCtrl->QueryInterface(VBF_INTERFACE_3DPLOT); if(pI3DPlot) pI3DPlot->DeleteDoc(strDocName); } //----------------------------------------------------------------------------- // 内联函数:VBF_Locate() // 函数描述:定位到指定位置 //----------------------------------------------------------------------------- inline void VBF_Locate(IVBF_MainCtrl* pIMainCtrl, const osg::Vec3d& ptGeo, double dViewDist, double dAngleH, double dAngleV=-90.0, double dDurationSec=3.0) { IVBF_3DDisplay* pI3DDisplay = (IVBF_3DDisplay*)pIMainCtrl->QueryInterface(VBF_INTERFACE_3DDISPLAY, NULL); if(NULL==pI3DDisplay) return; CVBF_Viewpoint point(ptGeo, dAngleH, dAngleV, dViewDist); pI3DDisplay->SetViewpoint(point, dDurationSec, false); } #endif
[ "robertsam@126.com" ]
robertsam@126.com
5451fd813cf8ae45adb406536b0d46969a9a5048
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_frame.h
45ee51111c3481495c54185b3d4f551c1eb9d929
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
2,306
h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_ENCODED_AUDIO_FRAME_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_ENCODED_AUDIO_FRAME_H_ #include <stdint.h> #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace webrtc { class TransformableAudioFrameInterface; class TransformableFrameInterface; } // namespace webrtc namespace blink { class DOMArrayBuffer; class RTCEncodedAudioFrameDelegate; class RTCEncodedAudioFrameMetadata; class MODULES_EXPORT RTCEncodedAudioFrame final : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: explicit RTCEncodedAudioFrame( std::unique_ptr<webrtc::TransformableFrameInterface> webrtc_frame); explicit RTCEncodedAudioFrame( std::unique_ptr<webrtc::TransformableAudioFrameInterface> webrtc_frame); explicit RTCEncodedAudioFrame( scoped_refptr<RTCEncodedAudioFrameDelegate> delegate); // rtc_encoded_audio_frame.idl implementation. uint64_t timestamp() const; DOMArrayBuffer* data() const; RTCEncodedAudioFrameMetadata* getMetadata() const; DOMArrayBuffer* additionalData() const; void setData(DOMArrayBuffer*); uint32_t synchronizationSource() const; Vector<uint32_t> contributingSources() const; String toString() const; scoped_refptr<RTCEncodedAudioFrameDelegate> Delegate() const; void SyncDelegate() const; // Returns and transfers ownership of the internal WebRTC frame // backing this RTCEncodedAudioFrame, neutering all RTCEncodedAudioFrames // backed by that internal WebRTC frame. std::unique_ptr<webrtc::TransformableFrameInterface> PassWebRtcFrame(); void Trace(Visitor*) const override; private: scoped_refptr<RTCEncodedAudioFrameDelegate> delegate_; Vector<uint32_t> contributing_sources_; mutable Member<DOMArrayBuffer> frame_data_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_ENCODED_AUDIO_FRAME_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
45e898f5befc30ed692e2203de689691be7444d3
79cfb3573442870deb4f019b1c98bee5549c9a5e
/lab7/lab_07/src/my_vector.cpp
6ea3cbc40cbfbf8d8860e4044af41184aad73494
[]
no_license
123a6bcw/c-
6ea366a418f75355b9bd051afcb5688212d7be9d
3be75620bf35b8a30c3e8b0fc4debb0f58ba714d
refs/heads/master
2021-01-24T08:32:16.637724
2016-12-03T11:05:46
2016-12-03T11:05:46
69,559,942
0
0
null
null
null
null
UTF-8
C++
false
false
2,650
cpp
#include "my_vector.h" MyVector::MyVector() { this -> _data = new int[2]; *(_data) = 0; *(_data + 1) = 0; this -> _sz = 0; this -> _cp = 2; } MyVector::MyVector(std::size_t init_capacity) { (this -> _data) = new int[init_capacity]; for (std::size_t i = 0; i < init_capacity; i++) { *((this -> _data) + i) = 0; } (this -> _cp) = init_capacity; (this -> _sz) = 0; } MyVector::~MyVector() { delete [] (this -> _data); } void MyVector::set(std::size_t index, int value) { *((this -> _data) + index) = value; } int MyVector::get(std::size_t index) { return *((this -> _data) + index); } std::size_t MyVector::size() { return (this -> _sz); } std::size_t MyVector::capacity() { return (this -> _cp); } void MyVector::reserve(std::size_t new_capacity) { if (new_capacity <= (this -> _cp)) { return; } int *_data_new = new int[new_capacity]; for (std::size_t i = 0; i < (this -> _sz); i++) { *(_data_new + i) = *((this -> _data) + i); } for (std::size_t i = (this -> _sz); i < new_capacity; i++) { *(_data_new + i) = 0; } delete [] (this -> _data); (this -> _data) = _data_new; if (new_capacity > (this -> _cp)) { (this -> _cp) = new_capacity; } } void MyVector::resize(std::size_t new_size) { if (new_size < (this -> _sz)) { (this -> _sz) = new_size; return; } if (new_size > (this -> _cp)) { std::size_t _new_capacity = (this -> _cp); while (_new_capacity < new_size) { _new_capacity *= 2; } this -> reserve(_new_capacity); } (this -> _sz) = new_size; } void MyVector::push_back(int value) { if ((this -> _sz) + 1 > this -> _cp) { this -> reserve(2 * (this -> _cp)); } *((this -> _data) + (this -> _sz)) = value; (this -> _sz)++; } void MyVector::insert(std::size_t index, int value) { if ((this -> _sz) == 0) { this -> push_back(value); return; } if ((this -> _sz) + 1 > (this -> _cp)) { this -> reserve(2 * (this -> _cp)); } for (std::size_t i = (this -> _sz); i > index; i--) { *((this -> _data) + i) = *((this -> _data) + i - 1); } *((this -> _data) + index) = value; (this -> _sz)++; } void MyVector::erase(std::size_t index) { for (std::size_t i = index + 1; i <= (this -> _sz) - 1; i++) { *((this -> _data) + i - 1) = *((this -> _data) + i); } (this -> _sz)--; }
[ "ga.karandash@yandex.ru" ]
ga.karandash@yandex.ru
bedf23c43f203869fedcdb82c358138cf3bf6104
928328409405a6392771608d501f9c79afc81e0a
/prj/MarketData/MarketDataApiFactory.cpp
608b25694cb6507fb7f0337cd2242bc7eea3c781
[]
no_license
kknet/cpp_prj
19ce6b73a495af2c5dd719cb5512720cb9a432c1
0904b6f8b8e8f8fcb9295bd587aa4eb6689badd0
refs/heads/master
2021-05-10T16:43:27.253758
2018-01-04T08:25:57
2018-01-04T08:25:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
966
cpp
#include "marketapi/MarketDataApiFactory.h" #include "marketapi/CtpFutureMarketDataApi.h" //#ifdef WIN32 //#include "marketapi/GtaStockMarketDataApi.h" //#endif namespace itstation { namespace marketapi { const std::string MarketDataApiFactory::kCtpFutureDataType = "CTP_FUTURE"; const std::string MarketDataApiFactory::kCtpStockDataType = "CTP_STOCK"; const std::string MarketDataApiFactory::kCtpOptionDataType = "CTP_OPTION"; const std::string MarketDataApiFactory::kGtaStockDataType = "GTA_STOCK"; MarketDataApiFactory::MarketDataApiFactory(void) { } MarketDataApiFactory::~MarketDataApiFactory(void) { } MarketDataApi* MarketDataApiFactory::CreateMarketDataApi(std::string type) { if (kCtpFutureDataType == type) { MarketDataApi* api = new CtpFutureMarketDataApi(); return api; } //#ifdef WIN32 #if 0 else if (kGtaStockDataType == type) { MarketDataApi* api = new GtaStockMarketDataApi; return api; } #endif else { return NULL; } } } }
[ "84020702@qq.com" ]
84020702@qq.com
de11c293d83df1eff23614d2ad8e5c002c28cb94
02508aa773dcbd9939eb879952ee2cb3dd90bcad
/torch/csrc/jit/codegen/cuda/type.cpp
802ccc43d94770ac2e07cb7c9d8878ee78fc44c3
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
dhivyadharshin/pytorch
d8a3b7f3c03e21e776ea34788d13743467b738c8
6a170011876bb8bd1909e8f60fba1270ac7a5577
refs/heads/master
2023-07-18T07:31:52.918955
2021-08-17T18:12:01
2021-08-17T18:12:01
397,330,616
5
0
NOASSERTION
2021-08-17T18:12:02
2021-08-17T16:57:16
null
UTF-8
C++
false
false
13,888
cpp
#include <torch/csrc/jit/codegen/cuda/type.h> #include <stdexcept> #include <unordered_map> namespace torch { namespace jit { namespace fuser { namespace cuda { // Return highest on list (smallest enum val) DataType promote_type(const DataType& t1, const DataType& t2) { TORCH_CHECK( DataType::Null != t1 && DataType::Null != t2, "Expected promotable DataTypes but got: ", t1, " and ", t2); return t1 < t2 ? t1 : t2; } // Return highest on list (smallest enum val) ValType promote_type(const ValType& t1, const ValType& t2) { TORCH_CHECK( t1 >= ValType::TensorView && t2 >= ValType::TensorView, "Expected promotable ValTypes but got: ", t1, " and ", t2); // Check that it's a promotable type (with dtype) // static_assert?? return t1 < t2 ? t1 : t2; } static const char* data_type2string(DataType t) { switch (t) { case DataType::Bool: return "bool"; case DataType::Float: return "float"; case DataType::Half: return "__half"; case DataType::Int: return "int64_t"; case DataType::Null: return "nullptr"; default: break; } TORCH_INTERNAL_ASSERT(false, "No string found for data type."); return nullptr; } static const char* val_type2string(ValType t) { switch (t) { case ValType::TensorIndex: return "TensorIndex"; case ValType::TensorView: return "TensorView"; case ValType::TensorDomain: return "TensorDomain"; case ValType::IterDomain: return "IterDomain"; case ValType::Scalar: return "Scalar"; case ValType::NamedScalar: return "NamedScalar"; case ValType::KirIterDomain: return "KirIterDomain"; case ValType::KirNamedScalar: return "KirNamedScalar"; case ValType::KirScalar: return "KirScalar"; case ValType::KirTensorDomain: return "KirTensorDomain"; case ValType::KirTensorView: return "KirTensorView"; default: break; } TORCH_INTERNAL_ASSERT(false, "No string found for val type."); return nullptr; } static const char* expr_type2string(ExprType t) { switch (t) { case ExprType::UnaryOp: return "UnaryOp"; case ExprType::BinaryOp: return "BinaryOp"; case ExprType::TernaryOp: return "TernaryOp"; case ExprType::ReductionOp: return "ReductionOp"; case ExprType::GridReduction: return "GridReduction"; case ExprType::BroadcastOp: return "BroadcastOp"; case ExprType::ForLoop: return "ForLoop"; case ExprType::IfThenElse: return "IfThenElse"; case ExprType::Allocate: return "Allocate"; case ExprType::Sync: return "SyncThreads"; case ExprType::Split: return "Split"; case ExprType::Merge: return "Merge"; case ExprType::KirUnaryOp: return "KirUnaryOp"; case ExprType::KirBinaryOp: return "KirBinaryOp"; case ExprType::KirTernaryOp: return "KirTernaryOp"; case ExprType::KirReductionOp: return "KirReductionOp"; case ExprType::KirBroadcastOp: return "KirBroadcastOp"; default: break; } TORCH_INTERNAL_ASSERT(false, "No string found for expr type."); return nullptr; } static const char* unary_op_type2string(UnaryOpType t) { switch (t) { case UnaryOpType::Abs: return "fabs"; case UnaryOpType::Acos: return "acosf"; case UnaryOpType::Asin: return "asinf"; case UnaryOpType::Atan: return "atanf"; case UnaryOpType::Atanh: return "atanhf"; case UnaryOpType::Cast: return "cast"; case UnaryOpType::Ceil: return "ceilf"; case UnaryOpType::Cos: return "cosf"; case UnaryOpType::Cosh: return "coshf"; case UnaryOpType::Exp: return "expf"; case UnaryOpType::Expm1: return "expm1f"; case UnaryOpType::Erf: return "erff"; case UnaryOpType::Erfc: return "erfcf"; case UnaryOpType::Floor: return "floorf"; case UnaryOpType::Frac: return "frac"; case UnaryOpType::Gelu: return "gelu"; case UnaryOpType::Lgamma: return "lgammaf"; case UnaryOpType::Log: return "logf"; case UnaryOpType::Log10: return "log10f"; case UnaryOpType::Log1p: return "log1pf"; case UnaryOpType::Log2: return "log2f"; case UnaryOpType::Neg: return "neg"; case UnaryOpType::RandLike: return "randLike"; case UnaryOpType::Reciprocal: return "reciprocal"; case UnaryOpType::Relu: return "relu"; case UnaryOpType::Rsqrt: return "rsqrtf"; case UnaryOpType::Round: return "roundf"; case UnaryOpType::Set: return "set"; case UnaryOpType::Sigmoid: return "sigmoid"; case UnaryOpType::Sin: return "sinf"; case UnaryOpType::Sinh: return "sinhf"; case UnaryOpType::Sqrt: return "sqrtf"; case UnaryOpType::Tan: return "tanf"; case UnaryOpType::Tanh: return "tanhf"; case UnaryOpType::Trunc: return "truncf"; default: break; } TORCH_INTERNAL_ASSERT(false, "No string found for unary op type."); return nullptr; } static const char* unary_op_type_inline_op2string(UnaryOpType t) { switch (t) { case UnaryOpType::Neg: return "-"; case UnaryOpType::Set: return ""; default: break; } return nullptr; } static const char* binary_op_type2string(BinaryOpType t) { switch (t) { case BinaryOpType::Add: return "add"; case BinaryOpType::Atan2: return "atan2f"; case BinaryOpType::Div: return "div"; case BinaryOpType::Fmod: return "fmodf"; case BinaryOpType::Max: return "fmaxf"; case BinaryOpType::Min: return "fminf"; case BinaryOpType::Mul: return "mul"; case BinaryOpType::Pow: return "powf"; case BinaryOpType::Remainder: return "remainder"; case BinaryOpType::Sub: return "sub"; // Logical Ops case BinaryOpType::Mod: return "mod"; case BinaryOpType::CeilDiv: return "ceilDiv"; case BinaryOpType::And: return "and"; case BinaryOpType::Eq: return "equal"; case BinaryOpType::GE: return "greaterThanOrEqual"; case BinaryOpType::GT: return "greaterThan"; case BinaryOpType::LE: return "lessThanOrEqual"; case BinaryOpType::LT: return "lessThan"; case BinaryOpType::NE: return "notEqual"; default: break; } TORCH_INTERNAL_ASSERT(false, "No string found for binary op type."); return nullptr; } static const char* binary_op_type_inline_op2string(BinaryOpType t) { switch (t) { case BinaryOpType::Add: return "+"; case BinaryOpType::Div: return "/"; case BinaryOpType::Mod: return "%"; case BinaryOpType::Mul: return "*"; case BinaryOpType::Sub: return "-"; // Logical Ops case BinaryOpType::And: return "&&"; case BinaryOpType::Eq: return "=="; case BinaryOpType::GE: return ">="; case BinaryOpType::GT: return ">"; case BinaryOpType::LE: return "<="; case BinaryOpType::LT: return "<"; case BinaryOpType::NE: return "!="; default: break; } return nullptr; } static const char* ternary_op_type2string(TernaryOpType t) { switch (t) { case TernaryOpType::Clamp: return "clamp"; case TernaryOpType::Threshold: return "threshold"; case TernaryOpType::Where: return "where"; default: break; } TORCH_INTERNAL_ASSERT(false, "No string found for ternary op type."); return nullptr; } static const char* parallel_type2string(ParallelType t) { switch (t) { case ParallelType::BIDz: return "blockIdx.z"; case ParallelType::BIDy: return "blockIdx.y"; case ParallelType::BIDx: return "blockIdx.x"; case ParallelType::TIDz: return "threadIdx.z"; case ParallelType::TIDy: return "threadIdx.y"; case ParallelType::TIDx: return "threadIdx.x"; case ParallelType::Vectorize: return "V"; case ParallelType::Unroll: return "U"; case ParallelType::Serial: return "S"; default: break; } TORCH_INTERNAL_ASSERT(false, "No string found for parallel type."); return nullptr; } static const char* memory_type2string(MemoryType t) { switch (t) { case MemoryType::Local: return "register"; case MemoryType::Shared: return "shared"; case MemoryType::Global: return "global"; default: break; } TORCH_INTERNAL_ASSERT(false, "No string found for memory type."); return nullptr; } static const char* iter_type2string(IterType t) { switch (t) { case IterType::Iteration: return "i"; case IterType::Reduction: return "r"; case IterType::BroadcastWithStride: return "sb"; case IterType::BroadcastWithoutStride: return "b"; default: TORCH_INTERNAL_ASSERT(false, "No string found for IterDomain type."); return nullptr; } } static const char* thread_size2string(ParallelType t) { switch (t) { case ParallelType::BIDz: return "gridDim.z"; case ParallelType::BIDy: return "gridDim.y"; case ParallelType::BIDx: return "gridDim.x"; case ParallelType::TIDz: return "blockDim.z"; case ParallelType::TIDy: return "blockDim.y"; case ParallelType::TIDx: return "blockDim.x"; default: break; } TORCH_INTERNAL_ASSERT(false, "Could not find size of the thread type ", t); return nullptr; } const unsigned int _WORD_SHIFT = 16; constexpr unsigned int supported_switch_pair(DataType t1, DataType t2) { return ((unsigned int)t1 << _WORD_SHIFT) + (unsigned int)t2; } static const char* supported_casts2string( const std::pair<DataType, DataType>& t) { switch (supported_switch_pair(std::get<0>(t), std::get<1>(t))) { case supported_switch_pair(DataType::Float, DataType::Half): return "__float2half"; case supported_switch_pair(DataType::Half, DataType::Float): return "__half2float"; default: break; } return nullptr; } bool is_logical_op(const BinaryOpType& bot) { switch (bot) { case BinaryOpType::And: case BinaryOpType::Eq: case BinaryOpType::GE: case BinaryOpType::GT: case BinaryOpType::LE: case BinaryOpType::LT: case BinaryOpType::NE: return true; default: return false; } } DataType aten_to_data_type(const at::ScalarType& scalar_type) { switch (scalar_type) { case at::ScalarType::Bool: return DataType::Bool; case at::ScalarType::Float: return DataType::Float; case at::ScalarType::Half: return DataType::Half; case at::ScalarType::Long: return DataType::Int; default: TORCH_INTERNAL_ASSERT(false, "No data type found for scalar type."); return DataType::Null; } } at::ScalarType data_type_to_aten(const DataType& data_type) { switch (data_type) { case DataType::Bool: return at::ScalarType::Bool; case DataType::Float: return at::ScalarType::Float; case DataType::Half: return at::ScalarType::Half; case DataType::Int: return at::ScalarType::Long; default: TORCH_INTERNAL_ASSERT(false, "No data type found for scalar type."); return at::ScalarType::Undefined; } } std::ostream& operator<<(std::ostream& out, const ValType vtype) { return out << val_type2string(vtype); } std::ostream& operator<<(std::ostream& out, const DataType dtype) { return out << data_type2string(dtype); } std::ostream& operator<<(std::ostream& out, const ExprType etype) { return out << expr_type2string(etype); } std::ostream& operator<<(std::ostream& out, const UnaryOpType uotype) { return out << unary_op_type2string(uotype); } std::ostream& operator<<(std::ostream& out, const BinaryOpType botype) { return out << binary_op_type2string(botype); } std::ostream& operator<<(std::ostream& out, const TernaryOpType totype) { return out << ternary_op_type2string(totype); } std::ostream& operator<<(std::ostream& out, const ParallelType ptype) { return out << stringifyThread(ptype); } std::ostream& operator<<(std::ostream& out, const MemoryType mtype) { return out << memory_type2string(mtype); } TORCH_CUDA_CU_API std::ostream& operator<<( std::ostream& out, const IterType bt) { return out << iter_type2string(bt); } TORCH_CUDA_CU_API c10::optional<std::string> inline_op_str( const UnaryOpType uotype) { const char* str = unary_op_type_inline_op2string(uotype); return str != nullptr ? c10::optional<std::string>(std::string(str)) : c10::nullopt; } c10::optional<std::string> inline_op_str(const BinaryOpType botype) { const char* str = binary_op_type_inline_op2string(botype); return str != nullptr ? c10::optional<std::string>(std::string(str)) : c10::nullopt; } std::string stringifyThreadSize(const ParallelType ptype) { return thread_size2string(ptype); } std::string stringifyThread(const ParallelType ptype) { return parallel_type2string(ptype); } c10::optional<std::string> cast_func_str( const std::pair<DataType, DataType>& cast) { const char* str = supported_casts2string(cast); return str != nullptr ? c10::optional<std::string>(std::string(str)) : c10::nullopt; } size_t dataTypeSize(DataType type) { switch (type) { case DataType::Bool: return sizeof(bool); case DataType::Float: return 4; case DataType::Half: return 2; case DataType::Int: return 4; default: TORCH_INTERNAL_ASSERT(false, "Size undefined for data type, ", type); } } } // namespace cuda } // namespace fuser } // namespace jit } // namespace torch
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
2b831638121d5ddd71fa0066b18af5cc459693cc
945269911c780e59c549d80cc091fab4beeaed52
/libs/compress/cpps_zipfile.cpp
10cb875054e9034d1cd23c4546f327b8521f7878
[ "MIT" ]
permissive
liuhao0620/cpps
2a05295ae8c6348083cdcbda262ecf7623dafe4c
bda58f629c3c7083550f29abad4c14550bdec14b
refs/heads/master
2023-02-08T15:25:01.143503
2021-01-02T05:55:27
2021-01-02T05:55:27
324,134,288
0
0
MIT
2021-01-02T05:55:28
2020-12-24T10:53:45
null
GB18030
C++
false
false
9,391
cpp
#include "stdafx.h" #include "cpps_zipfile.h" #include "cpps_zipfile_info.h" #include <fstream> namespace cpps { std::string cpps_io_getfilename(std::string str); std::string cpps_io_getfilepath(std::string str); cpps_integer cpps_io_mkdirs(std::string szdir); bool cpps_io_file_exists(std::string path); cpps_zipfile::cpps_zipfile() { filecomment_length = 0; } cpps_zipfile::~cpps_zipfile() { } bool cpps_zipfile::open(std::string file, cpps_value pwd, cpps_value mode, cpps_value level) { nlevel = level.tt == CPPS_TINTEGER ? level.value.integer : Z_BEST_COMPRESSION; smode = mode.tt == CPPS_TSTRING ? cpps_to_string(mode) : "r"; password = mode.tt == CPPS_TSTRING ? cpps_to_string(pwd) : ""; file_path = file; bool b = cpps_io_file_exists(file_path); int t = APPEND_STATUS_CREATE; /*解压缩 a为追加 也要先解压缩.*/ if (smode == "r" ) { if (!b) return false; unzFile unzipfile = unzOpen64(file.c_str()); if (unzipfile == NULL) { return false; } if (unzGetGlobalInfo64(unzipfile, &global_info) != UNZ_OK) { unzClose(unzipfile); return false; } unzGetGlobalComment(unzipfile, file_comment, READ_SIZE); filecomment_length = strlen(file_comment); ZPOS64_T i = 0; for (;i < global_info.number_entry; ++i) { cpps_zipfile_info* zipfile_info = new cpps_zipfile_info(); //unzGetFilePos64 if (unzGetCurrentFileInfo64( unzipfile, &zipfile_info->file_info, zipfile_info->file_name, MAX_FILENAME, zipfile_info->file_extra, READ_SIZE, zipfile_info->file_comment, READ_SIZE) != UNZ_OK) { unzClose(unzipfile); return false; } unzGetFilePos64(unzipfile, &zipfile_info->file_pos); zipfile_info->filename_length = strlen(zipfile_info->file_name); zipfile_info->fileextra_length = strlen(zipfile_info->file_extra); zipfile_info->filecomment_length = strlen(zipfile_info->file_comment); file_list.insert(phmap::flat_hash_map<std::string, cpps_zipfile_info*>::value_type(zipfile_info->file_name, zipfile_info)); // Go the the next entry listed in the zip file. if ((i + 1) < global_info.number_entry) { if (unzGoToNextFile(unzipfile) != UNZ_OK) { unzClose(unzipfile); return false; } } } unzClose(unzipfile); return true; } else if(smode == "w" ){ //写入文件 } else if (smode == "x") { if (b) return false; } else if (smode == "a"){ if (!b) return false; t = APPEND_STATUS_ADDINZIP; } /*这里都是打开文件*/ zipfile = zipOpen64(file_path.c_str(), t); if (zipfile == NULL) { return false; } return true; } void cpps_zipfile::close() { if(zipfile) zipClose(zipfile, NULL); zipfile = NULL; } cpps_zipfile_info* cpps_zipfile::getinfo(std::string name) { if (smode != "r") return NULL; cpps_zipfile_info* ret = NULL; auto it = file_list.find(name); if (it != file_list.end()) { ret = it->second; } return ret; } cpps_value cpps_zipfile::infolist(C *c) { if (smode != "r") return nil; cpps_vector* vec = NULL; cpps_value ret = newclass<cpps_vector>(c, &vec); vec->realvector().reserve(file_list.size()); for (auto it : file_list) { vec->realvector().push_back(cpps_cpp_to_cpps_converter<cpps_zipfile_info*>::apply(c, it.second)); } return ret; } cpps_value cpps_zipfile::namelist(C*c) { if (smode != "r") return nil; cpps_vector* vec = NULL; cpps_value ret = newclass<cpps_vector>(c, &vec); vec->realvector().reserve(file_list.size()); for (auto it : file_list) { vec->realvector().push_back(cpps_value(c, it.second->file_name)); } return ret; } bool cpps_zipfile::real_extract(unzFile zipfile,cpps_zipfile_info* member, std::string path) { // Check if this entry is a directory or file. if (!member->is_dir()){ if (unzGoToFilePos64(zipfile, &member->file_pos) != UNZ_OK){ return false; } if (password.empty() && unzOpenCurrentFile(zipfile) != UNZ_OK) { return false; } else if (!password.empty() && unzOpenCurrentFilePassword(zipfile, password.c_str()) != UNZ_OK) { return false; } std::string realpath = path + member->file_name; cpps_io_mkdirs(cpps_io_getfilepath(realpath)); // Open a file to write out the data. FILE* out = fopen(realpath.c_str(), "wb"); if (out == NULL){ unzCloseCurrentFile(zipfile); unzClose(zipfile); return false; } char read_buffer[READ_SIZE]; int error = UNZ_OK; do { error = unzReadCurrentFile(zipfile, read_buffer, READ_SIZE); if (error < 0) { unzCloseCurrentFile(zipfile); unzClose(zipfile); return false; } // Write data to file. if (error > 0) { fwrite(read_buffer, error, 1, out); // You should check return of fwrite... } } while (error > 0); fclose(out); unzCloseCurrentFile(zipfile); return true; } else { std::string realpath = path + member->file_name; cpps_io_mkdirs(realpath); return true; } return false; } bool cpps_zipfile::extract(cpps_value member, cpps_value path) { if (smode != "r") return false; cpps_zipfile_info* info = NULL; if (member.tt == CPPS_TNIL) { return false; } else if (member.tt == CPPS_TSTRING) { std::string* s = cpps_get_string(member); info = getinfo(*s); } else if (member.isdomain() && member.value.domain->domainname == "zipfile_info") { info = cpps_converter< cpps_zipfile_info*>::apply(member); } if (info == NULL) return false; unzFile zipfile = unzOpen64(file_path.c_str()); if (zipfile == NULL) { return false; } std::string spath = path.tt == CPPS_TSTRING ? cpps_to_string(path) : ""; real_extract(zipfile, info, spath); unzClose(zipfile); return true; } bool cpps_zipfile::extractall(cpps_value path, cpps_value members) { if (smode != "r") return false; unzFile zipfile = unzOpen64(file_path.c_str()); if (zipfile == NULL) { return false; } std::string spath = path.tt == CPPS_TSTRING ? cpps_to_string(path) : ""; cpps_vector* vec = NULL; if (members.isdomain() && members.value.domain->domainname == "vector") { vec = cpps_to_cpps_vector(members); } if (vec) { for (auto it : vec->realvector()) { cpps_zipfile_info* info = cpps_converter<cpps_zipfile_info*>::apply(it); real_extract(zipfile,info, spath); } } else { for (auto it : file_list) { cpps_zipfile_info* info = it.second; real_extract(zipfile, info, spath); } } unzClose(zipfile); return true; } void cpps_zipfile::setpassword(std::string pwd) { password = pwd; } void cpps_zipfile::real_read(cpps_zipfile_info* info,char *buf) { unzFile zipfile = unzOpen64(file_path.c_str()); if (zipfile == NULL) { return ; } if (!info->is_dir()) { if (unzGoToFilePos64(zipfile, &info->file_pos) != UNZ_OK) { return ; } if (password.empty() && unzOpenCurrentFile(zipfile) != UNZ_OK) { return ; } else if (!password.empty() && unzOpenCurrentFilePassword(zipfile, password.c_str()) != UNZ_OK) { return ; } int err = unzReadCurrentFile(zipfile, buf, (usint32)info->file_info.uncompressed_size); if (err != (int)info->file_info.uncompressed_size) { printf("info->file_info.uncompressed_size:%d err:%d", (int)info->file_info.uncompressed_size, err); } unzCloseCurrentFile(zipfile); } unzClose(zipfile); } cpps_value cpps_zipfile::read(C *c,cpps_value member) { cpps_zipfile_info* info = NULL; if (member.tt == CPPS_TNIL) { return false; } else if (member.tt == CPPS_TSTRING) { std::string* s = cpps_get_string(member); info = getinfo(*s); } else if (member.isdomain() && member.value.domain->domainname == "zipfile_info") { info = cpps_converter< cpps_zipfile_info*>::apply(member); } if (info == NULL) return false; Buffer* buffer = NULL; cpps_value ret = newclass<Buffer>(c, &buffer); buffer->realloc(info->file_info.uncompressed_size); real_read(info, buffer->getbuffer()); buffer->seek(info->file_info.uncompressed_size); return ret; } bool cpps_zipfile::testzip() { return true; } int writeInZipFile(zipFile zFile, const std::string& file) { std::fstream f(file.c_str(), std::ios::binary | std::ios::in); f.seekg(0, std::ios::end); size_t size = f.tellg(); f.seekg(0, std::ios::beg); if (size <= 0) { return zipWriteInFileInZip(zFile, NULL, 0); } char* buf = new char[size]; f.read(buf, size); int ret = zipWriteInFileInZip(zFile, buf,(usint32) size); delete[] buf; return ret; } bool cpps_zipfile::write(std::string filepath, cpps_value arcname) { //只有这三种情况下会写文件. if (smode == "w" || smode == "x" || smode == "a") { std::string sarcname = arcname.tt == CPPS_TSTRING ? cpps_to_string(arcname) : ""; zip_fileinfo zi; memset(&zi,0, sizeof(zip_fileinfo)); int err = zipOpenNewFileInZip3_64(zipfile, sarcname.empty() ? cpps_io_getfilename(filepath).c_str() : sarcname.c_str(), &zi, NULL, 0, NULL, 0, NULL, nlevel != 0 ? Z_DEFLATED : 0, (int)nlevel, 0,-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password.empty()? NULL : password.c_str(), 0, 1); if (err != ZIP_OK) { return false; } err = writeInZipFile(zipfile, filepath); if (err != ZIP_OK) { return false; } return true; } return false; } }
[ "88481106@qq.com" ]
88481106@qq.com
9dae47b4ea95ec4d8c4f6dbe36e993f02d684ba1
8abfa44c27ff41a663251574bb4240616ee03fe3
/caffe2/operators/experimental/c10/schemas/filler.cc
8fe87072c70060f018ba3418076631a119f3bb62
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
rlorigro/pytorch
9365a933f73feb6f3cf133ee40e39c94b23fbfac
9a05ad46c8ff9946f8945325985c19ec19129ff2
refs/heads/master
2020-05-01T13:09:40.265608
2019-03-29T22:42:57
2019-03-29T22:42:57
177,483,393
0
0
NOASSERTION
2019-03-24T23:47:28
2019-03-24T23:47:28
null
UTF-8
C++
false
false
3,850
cc
#include "caffe2/operators/experimental/c10/schemas/filler.h" #include <ATen/core/dispatch/OpSchemaRegistration.h> #include "caffe2/core/operator_c10wrapper.h" #include "caffe2/utils/cast.h" using caffe2::CPUContext; using c10::C10Tensor; using c10::ivalue::IntList; using c10::intrusive_ptr; namespace caffe2 { namespace ops { // TODO Parse schema strings instead of creating FunctionSchema manually C10_DEFINE_OP_SCHEMA( ConstantFill, FunctionSchema( "_c10_experimental::ConstantFill", "", (std::vector<c10::Argument>{ c10::Argument("inputs", ListType::ofTensors()), c10::Argument("output"), c10::Argument("shape", ListType::ofInts()), c10::Argument("extra_shape", ListType::ofInts()), c10::Argument("input_as_shape", BoolType::get()), c10::Argument("dtype", IntType::get()), c10::Argument("value", NumberType::get())}), (std::vector<c10::Argument>{}))); C10_DEFINE_OP_SCHEMA( UniformFill, FunctionSchema( "_c10_experimental::UniformFill", "", (std::vector<c10::Argument>{ c10::Argument("inputs", ListType::ofTensors()), c10::Argument("output"), c10::Argument("shape", ListType::ofInts()), c10::Argument("extra_shape", ListType::ofInts()), c10::Argument("input_as_shape", BoolType::get()), c10::Argument("min", FloatType::get()), c10::Argument("max", FloatType::get())}), (std::vector<c10::Argument>{}))); C10_DEFINE_OP_SCHEMA( GivenTensorFill, FunctionSchema( "_c10_experimental::GivenTensorFill", "", (std::vector<c10::Argument>{ c10::Argument("inputs", ListType::ofTensors()), c10::Argument("output"), c10::Argument("shape", ListType::ofInts()), c10::Argument("extra_shape", ListType::ofInts()), c10::Argument("input_as_shape", BoolType::get()), c10::Argument("values"), }), (std::vector<c10::Argument>{}))); C10_DEFINE_OP_SCHEMA( GivenTensorIntFill, FunctionSchema( "_c10_experimental::GivenTensorIntFill", "", (std::vector<c10::Argument>{ c10::Argument("inputs", ListType::ofTensors()), c10::Argument("output"), c10::Argument("shape", ListType::ofInts()), c10::Argument("extra_shape", ListType::ofInts()), c10::Argument("input_as_shape", BoolType::get()), c10::Argument("values"), }), (std::vector<c10::Argument>{}))); C10_DEFINE_OP_SCHEMA( GivenTensorInt64Fill, FunctionSchema( "_c10_experimental::GivenTensorInt64Fill", "", (std::vector<c10::Argument>{ c10::Argument("inputs", ListType::ofTensors()), c10::Argument("output"), c10::Argument("shape", ListType::ofInts()), c10::Argument("extra_shape", ListType::ofInts()), c10::Argument("input_as_shape", BoolType::get()), c10::Argument("values"), }), (std::vector<c10::Argument>{}))); } } namespace caffe2 { REGISTER_C10_OPERATOR_FOR_CAFFE2_DISPATCH_CPU( "_c10_experimental::ConstantFill", C10ConstantFill_DontUseThisOpYet) REGISTER_C10_OPERATOR_FOR_CAFFE2_DISPATCH_CPU( "_c10_experimental::UniformFill", C10UniformFill_DontUseThisOpYet) REGISTER_C10_OPERATOR_FOR_CAFFE2_DISPATCH_CPU( "_c10_experimental::GivenTensorFill", C10GivenTensorFill_DontUseThisOpYet) REGISTER_C10_OPERATOR_FOR_CAFFE2_DISPATCH_CPU( "_c10_experimental::GivenTensorIntFill", C10GivenTensorIntFill_DontUseThisOpYet) REGISTER_C10_OPERATOR_FOR_CAFFE2_DISPATCH_CPU( "_c10_experimental::GivenTensorInt64Fill", C10GivenTensorInt64Fill_DontUseThisOpYet) } // namespace caffe2
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
3e9cca1f8e539d567f892e318fb045e6dc447d24
3e3c5b9022ae6cc8b06053f96809800f07aca4f8
/Src/EvolvedPlus/Samples/Messages/SetPosition.cpp
c840c288b284f80c59c1245a52afac2534c3ef57
[]
no_license
MetanoKid/toy-game-architecture
1b4bc44f1d4628ce66f80aeeef279d609a95be8f
a388c7b44e49d26678bc80bbef96bb29e4d26ce2
refs/heads/master
2021-01-18T18:25:24.335524
2015-09-30T15:32:53
2015-09-30T15:32:53
22,257,487
6
0
null
null
null
null
UTF-8
C++
false
false
516
cpp
#include "SetPosition.h" namespace EvolvedPlus { namespace Samples { namespace Messages { IMPLEMENT_MESSAGE(CSetPosition); CSetPosition::CSetPosition() : CMessage() { } CSetPosition::~CSetPosition() { } const Vector3 &CSetPosition::getPosition() const { return _position; } void CSetPosition::reset() { _position = Vector3(0.0f, 0.0f, 0.0f); } CSetPosition *CSetPosition::init(const Vector3 &position) { _position = position; return this; } } } }
[ "carloscdcskate@gmail.com" ]
carloscdcskate@gmail.com
2176d7cbbde67684f0b5d149028dbe7916ce87b0
80bce6bd02c40727efd602a5f36da28273cb1c0f
/ChessGame/src/GameLogic.h
c2ec005f55f8cc6bdc190fde2475629c9060eedd
[]
no_license
MarcisTU/ChessGame
76af356dcf7a970fce23abb5ac7a49808ca1e347
efb7c7f0a556277ab0a808c27712910a49034c3e
refs/heads/master
2023-06-07T03:55:11.089849
2021-07-05T11:00:10
2021-07-05T11:00:10
349,728,293
0
0
null
null
null
null
UTF-8
C++
false
false
1,550
h
#pragma once #include "pch.h" #include "ChessPiece.h" class GameLogic { public: GameLogic() = default; bool checkIfCapturingEnemy(int curX, int curY, int color, const std::vector<ChessPiece>& chessPieces); bool checkIfSquareHasPiece(int curX, int curY, const std::vector<ChessPiece>& chessPieces); void generateRookMoves(int curX, int curY, std::vector<std::pair<int, int>>& freeMoves, std::vector<std::pair<int, int>>& captureMoves, const std::vector<ChessPiece>& chessPieces, int color); void generateKnightMoves(int curX, int curY, std::vector<std::pair<int, int>>& freeMoves, std::vector<std::pair<int, int>>& captureMoves, const std::vector<ChessPiece>& chessPieces, int color); void generateBishopMoves(int curX, int curY, std::vector<std::pair<int, int>>& freeMoves, std::vector<std::pair<int, int>>& captureMoves, const std::vector<ChessPiece>& chessPieces, int color, bool isQueen = false); void generateKingMoves(int curX, int curY, std::vector<std::pair<int, int>>& freeMoves, std::vector<std::pair<int, int>>& captureMoves, const std::vector<ChessPiece>& chessPieces, int color); void generateBlackPawnMoves(int curX, int curY, std::vector<std::pair<int, int>>& freeMoves, std::vector<std::pair<int, int>>& captureMoves, const std::vector<ChessPiece>& chessPieces, bool isFirstMove, int color); void generateWhitePawnMoves(int curX, int curY, std::vector<std::pair<int, int>>& freeMoves, std::vector<std::pair<int, int>>& captureMoves, const std::vector<ChessPiece>& chessPiece, bool isFirstMove, int color); };
[ "marcisreb@gmail.com" ]
marcisreb@gmail.com
0543b76ea03c810926659ed34b5bf26301633a2e
cab4242b19eadb90ea94ab6c4cf8b1dc5075da83
/EngineOfEvil/source/RenderImage.h
bd830e145f9054d5f2e8cf2d45fe5b231a78e7b9
[]
no_license
tmf7/Engine-of-Evil
6ec2db19eb224416effd26c080b0686fa7af264b
81e846ef79ab714e06c4908ad990f2c1e5b1fe89
refs/heads/master
2023-03-03T08:59:35.636877
2023-02-28T15:31:20
2023-02-28T15:31:20
65,588,272
10
1
null
null
null
null
UTF-8
C++
false
false
7,171
h
/* =========================================================================== Engine of Evil GPL Source Code Copyright (C) 2016-2017 Thomas Matthew Freehill This file is part of the Engine of Evil GPL game engine source code. The Engine of Evil (EOE) Source Code 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. EOE Source Code 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 EOE Source Code. If not, see <http://www.gnu.org/licenses/>. If you have questions concerning this license, you may contact Thomas Freehill at tom.freehill26@gmail.com =========================================================================== */ #ifndef EVIL_RENDERIMAGE_H #define EVIL_RENDERIMAGE_H #include "Definitions.h" #include "Bounds.h" #include "Bounds3D.h" #include "Sort.h" #include "Image.h" #include "Component.h" class eRenderTarget; class eGridCell; //************************************************** // eRenderImage // data used by eRenderer for draw-order sorting // and drawing to the render target //************************************************** class eRenderImage : public eComponent { private: friend class eRenderer; // directly sets dstRect, priority, lastDrawnTime, allBehind, visited (no other accessors outside *this) public: eRenderImage(eGameObject * owner); virtual ~eRenderImage() override; std::shared_ptr<eImage> & Image(); const std::shared_ptr<eImage> & GetImage() const; void SetImage(int imageManagerIndex); void SetImageFrame(int subframeIndex); const SDL_Rect * GetImageFrame() const; SDL_Rect GetOverlapImageFrame(const eBounds & otherWorldClip) const; void SetOrigin(const eVec2 & newOrigin); const eVec2 & Origin() const; const eVec2 & Offset() const; void SetOffset(const eVec2 & newOffset); void SetRenderBlockSize(const eVec3 & newSize); const eBounds3D & GetRenderBlock() const; const eBounds & GetWorldClip() const; const std::vector<eGridCell *> & Areas() const; void SetIsSelectable(bool isSelectable); bool IsSelectable() const; virtual void Update() override; virtual std::unique_ptr<eComponent> GetCopy() const override { return std::make_unique<eRenderImage>(*this); } virtual int GetClassType() const override { return CLASS_RENDERIMAGE; } virtual bool IsClassType(int classType) const override { if(classType == CLASS_RENDERIMAGE) return true; return eComponent::IsClassType(classType); } private: void UpdateWorldClip(); void UpdateRenderBlock(); void ClearAreas(); void UpdateAreasWorldClipCorners(); void UpdateAreasWorldClipArea(); private: std::vector<eRenderTarget *> drawnTo; // prevent attempts to draw this more than once per renderTarget per frame std::vector<eRenderImage *> allBehind; // topological sort std::vector<eGridCell *> areas; // the gridcells responsible for drawing *this std::shared_ptr<eImage> image = nullptr; // source image (ie texture wrapper) eBounds3D renderBlock; // determines draw order of visible images eBounds worldClip; // dstRect in world space (ie: not adjusted with camera position yet) used for occlusion tests const SDL_Rect * srcRect = nullptr; // what part of the source image to draw (nullptr for all of it) SDL_Rect dstRect; // SDL consumable cliprect, where on the screen (adjusted with camera position) eVec2 origin; // top-left corner of image using world coordinates (not adjusted with camera position) eVec2 oldOrigin; // minimizes number of UpdateAreas calls for non-static eGameObjects that aren't moving eVec2 orthoOriginOffset; // offset from (eGameObject)owner::orthoOrigin (default: (0,0)) float priority; // determined during topological sort, lower priority draws first Uint32 lastDrawnTime = 0; // allows the drawnTo vector to be cleared before *this is drawn the first time during a frame bool isSelectable = false; // if this should added to all eGridCells its worldClip overlaps, or just its corners bool visited = false; // topological sort }; //************* // eRenderImage::eRenderImage //************* inline eRenderImage::eRenderImage(eGameObject * owner) { this->owner = owner; } //************* // eRenderImage::Image //************* inline std::shared_ptr<eImage> & eRenderImage::Image() { return image; } //************* // eRenderImage::GetImage //************* inline const std::shared_ptr<eImage> & eRenderImage::GetImage() const { return image; } //************* // eRenderImage::ImageFrame // DEBUG: assumes image has been initialized // DEBUG: no range checking for faster assignment //************* inline void eRenderImage::SetImageFrame(int subframeIndex) { srcRect = &image->GetSubframe(subframeIndex); } //************* // eRenderImage::ImageFrame //************* inline const SDL_Rect * eRenderImage::GetImageFrame() const { return srcRect; } //************* // eRenderImage::Origin //************* inline const eVec2 & eRenderImage::Origin() const { return origin; } //************* // eRenderImage::Offset // x and y distance from owner::orthoOrigin //************* inline const eVec2 & eRenderImage::Offset() const { return orthoOriginOffset; } //************* // eRenderImage::SetOffset // sets the x and y distance from owner::orthoOrigin //************* inline void eRenderImage::SetOffset(const eVec2 & newOffset) { orthoOriginOffset = newOffset; } //************* // eRenderImage::GetRenderBlock //************* inline const eBounds3D & eRenderImage::GetRenderBlock() const { return renderBlock; } //************* // eRenderImage::UpdateWorldClip // DEBUG: only call this after ImageFrame has been assigned //************* inline void eRenderImage::UpdateWorldClip() { worldClip = eBounds(origin, origin + eVec2((float)srcRect->w, (float)srcRect->h)); } //************* // eRenderImage::GetWorldClip //************* inline const eBounds & eRenderImage::GetWorldClip() const { return worldClip; } //************* // eRenderImage::Areas //************* inline const std::vector<eGridCell *> & eRenderImage::Areas() const { return areas; } //************* // eRenderImage::SetIsSelectable //************* inline void eRenderImage::SetIsSelectable(bool isSelectable) { this->isSelectable = isSelectable; } //************* // eRenderImage::IsSelectable //************* inline bool eRenderImage::IsSelectable() const { return isSelectable; } #endif /* EVIL_RENDERIMAGE_H */
[ "tmf7@njit.edu" ]
tmf7@njit.edu
63fca1b2f8bac8c8ba089589c00c96e31604a052
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/skia/src/core/SkImageFilter.cpp
a7c419b4353d7b57a301bb737d30d90bce4b47df
[ "BSD-3-Clause", "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
31,906
cpp
/* * Copyright 2012 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkImageFilter.h" #include "include/core/SkCanvas.h" #include "include/core/SkRect.h" #include "include/private/base/SkSafe32.h" #include "src/core/SkFuzzLogging.h" #include "src/core/SkImageFilterCache.h" #include "src/core/SkImageFilter_Base.h" #include "src/core/SkLocalMatrixImageFilter.h" #include "src/core/SkReadBuffer.h" #include "src/core/SkRectPriv.h" #include "src/core/SkSpecialImage.h" #include "src/core/SkSpecialSurface.h" #include "src/core/SkValidationUtils.h" #include "src/core/SkWriteBuffer.h" #if defined(SK_GANESH) #include "include/gpu/GrRecordingContext.h" #include "src/gpu/SkBackingFit.h" #include "src/gpu/ganesh/GrColorSpaceXform.h" #include "src/gpu/ganesh/GrDirectContextPriv.h" #include "src/gpu/ganesh/GrRecordingContextPriv.h" #include "src/gpu/ganesh/GrTextureProxy.h" #include "src/gpu/ganesh/SkGr.h" #include "src/gpu/ganesh/SurfaceFillContext.h" #endif #include <atomic> /////////////////////////////////////////////////////////////////////////////////////////////////// // SkImageFilter - A number of the public APIs on SkImageFilter downcast to SkImageFilter_Base // in order to perform their actual work. /////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns the number of inputs this filter will accept (some inputs can * be NULL). */ int SkImageFilter::countInputs() const { return as_IFB(this)->fInputs.count(); } /** * Returns the input filter at a given index, or NULL if no input is * connected. The indices used are filter-specific. */ const SkImageFilter* SkImageFilter::getInput(int i) const { SkASSERT(i < this->countInputs()); return as_IFB(this)->fInputs[i].get(); } bool SkImageFilter::isColorFilterNode(SkColorFilter** filterPtr) const { return as_IFB(this)->onIsColorFilterNode(filterPtr); } SkIRect SkImageFilter::filterBounds(const SkIRect& src, const SkMatrix& ctm, MapDirection direction, const SkIRect* inputRect) const { // The old filterBounds() function uses SkIRects that are defined in layer space so, while // we still are supporting it, bypass SkIF_B's new public filter bounds functions and go right // to the internal layer-space calculations. skif::Mapping mapping{ctm}; if (kReverse_MapDirection == direction) { skif::LayerSpace<SkIRect> targetOutput(src); if (as_IFB(this)->cropRectIsSet()) { skif::LayerSpace<SkIRect> outputCrop = mapping.paramToLayer( skif::ParameterSpace<SkRect>(as_IFB(this)->getCropRect().rect())).roundOut(); // Just intersect directly; unlike the forward-mapping case, since we start with the // external target output, there's no need to embiggen due to affecting trans. black if (!targetOutput.intersect(outputCrop)) { // Nothing would be output by the filter, so return empty rect return SkIRect::MakeEmpty(); } } skif::LayerSpace<SkIRect> content(inputRect ? *inputRect : src); return SkIRect(as_IFB(this)->onGetInputLayerBounds(mapping, targetOutput, content)); } else { SkASSERT(!inputRect); skif::LayerSpace<SkIRect> content(src); return SkIRect(as_IFB(this)->onGetOutputLayerBounds(mapping, content)); } } SkRect SkImageFilter::computeFastBounds(const SkRect& src) const { if (0 == this->countInputs()) { return src; } SkRect combinedBounds = this->getInput(0) ? this->getInput(0)->computeFastBounds(src) : src; for (int i = 1; i < this->countInputs(); i++) { const SkImageFilter* input = this->getInput(i); if (input) { combinedBounds.join(input->computeFastBounds(src)); } else { combinedBounds.join(src); } } return combinedBounds; } bool SkImageFilter::canComputeFastBounds() const { return !as_IFB(this)->affectsTransparentBlack(); } bool SkImageFilter_Base::affectsTransparentBlack() const { if (this->onAffectsTransparentBlack()) { return true; } for (int i = 0; i < this->countInputs(); i++) { const SkImageFilter* input = this->getInput(i); if (input && as_IFB(input)->affectsTransparentBlack()) { return true; } } return false; } bool SkImageFilter::asAColorFilter(SkColorFilter** filterPtr) const { SkASSERT(nullptr != filterPtr); if (!this->isColorFilterNode(filterPtr)) { return false; } if (nullptr != this->getInput(0) || as_CFB(*filterPtr)->affectsTransparentBlack()) { (*filterPtr)->unref(); return false; } return true; } sk_sp<SkImageFilter> SkImageFilter::makeWithLocalMatrix(const SkMatrix& matrix) const { return SkLocalMatrixImageFilter::Make(matrix, this->refMe()); } /////////////////////////////////////////////////////////////////////////////////////////////////// // SkImageFilter_Base /////////////////////////////////////////////////////////////////////////////////////////////////// static int32_t next_image_filter_unique_id() { static std::atomic<int32_t> nextID{1}; int32_t id; do { id = nextID.fetch_add(1, std::memory_order_relaxed); } while (id == 0); return id; } SkImageFilter_Base::SkImageFilter_Base(sk_sp<SkImageFilter> const* inputs, int inputCount, const SkRect* cropRect, std::optional<bool> usesSrc) : fUsesSrcInput(usesSrc.has_value() ? *usesSrc : false) , fCropRect(cropRect) , fUniqueID(next_image_filter_unique_id()) { fInputs.reset(inputCount); for (int i = 0; i < inputCount; ++i) { if (!usesSrc.has_value() && (!inputs[i] || as_IFB(inputs[i])->usesSource())) { fUsesSrcInput = true; } fInputs[i] = inputs[i]; } } SkImageFilter_Base::~SkImageFilter_Base() { SkImageFilterCache::Get()->purgeByImageFilter(this); } bool SkImageFilter_Base::Common::unflatten(SkReadBuffer& buffer, int expectedCount) { const int count = buffer.readInt(); if (!buffer.validate(count >= 0)) { return false; } if (!buffer.validate(expectedCount < 0 || count == expectedCount)) { return false; } #if defined(SK_BUILD_FOR_FUZZER) if (count > 4) { return false; } #endif SkASSERT(fInputs.empty()); for (int i = 0; i < count; i++) { fInputs.push_back(buffer.readBool() ? buffer.readImageFilter() : nullptr); if (!buffer.isValid()) { return false; } } SkRect rect; buffer.readRect(&rect); if (!buffer.isValid() || !buffer.validate(SkIsValidRect(rect))) { return false; } uint32_t flags = buffer.readUInt(); if (!buffer.isValid() || !buffer.validate(flags == 0x0 || flags == CropRect::kHasAll_CropEdge)) { return false; } fCropRect = CropRect(flags ? &rect : nullptr); return buffer.isValid(); } void SkImageFilter_Base::flatten(SkWriteBuffer& buffer) const { buffer.writeInt(fInputs.count()); for (int i = 0; i < fInputs.count(); i++) { const SkImageFilter* input = this->getInput(i); buffer.writeBool(input != nullptr); if (input != nullptr) { buffer.writeFlattenable(input); } } buffer.writeRect(fCropRect.rect()); buffer.writeUInt(fCropRect.flags()); } skif::FilterResult SkImageFilter_Base::filterImage(const skif::Context& context) const { // TODO (michaelludwig) - Old filters have an implicit assumption that the source image // (originally passed separately) has an origin of (0, 0). SkComposeImageFilter makes an effort // to ensure that remains the case. Once everyone uses the new type systems for bounds, non // (0, 0) source origins will be easy to support. SkASSERT((!context.source().image() && context.source().layerBounds().isEmpty()) || (context.source().image() && context.source().layerBounds().left() == 0 && context.source().layerBounds().top() == 0 && context.source().layerBounds().right() == context.source().image()->width() && context.source().layerBounds().bottom() == context.source().image()->height())); // TODO: Once all image filters operate on FilterResult, we should allow null source images. // Some filters that use a source input will produce non-transparent black values even if the // input is fully transparent (null). For now, at least allow filters that do not use the source // at all to still produce an output image. skif::FilterResult result; if (context.desiredOutput().isEmpty() || (fUsesSrcInput && !context.source()) || !context.mapping().layerMatrix().isFinite()) { return result; } uint32_t srcGenID = fUsesSrcInput ? context.sourceImage()->uniqueID() : 0; const SkIRect srcSubset = fUsesSrcInput ? context.sourceImage()->subset() : SkIRect::MakeWH(0, 0); SkImageFilterCacheKey key(fUniqueID, context.mapping().layerMatrix(), context.clipBounds(), srcGenID, srcSubset); if (context.cache() && context.cache()->get(key, &result)) { return result; } result = this->onFilterImage(context); if (context.gpuBacked()) { SkASSERT(!result.image() || result.image()->isTextureBacked()); } if (context.cache()) { context.cache()->set(key, this, result); } return result; } skif::LayerSpace<SkIRect> SkImageFilter_Base::getInputBounds( const skif::Mapping& mapping, const skif::DeviceSpace<SkIRect>& desiredOutput, const skif::ParameterSpace<SkRect>* knownContentBounds) const { // Map both the device-space desired coverage area and the known content bounds to layer space skif::LayerSpace<SkIRect> desiredBounds = mapping.deviceToLayer(desiredOutput); // TODO (michaelludwig) - To be removed once cropping is its own filter, since then an output // crop would automatically adjust the required input of its child filter in this same way. if (this->cropRectIsSet()) { skif::LayerSpace<SkIRect> outputCrop = mapping.paramToLayer(skif::ParameterSpace<SkRect>(fCropRect.rect())).roundOut(); if (!desiredBounds.intersect(outputCrop)) { // Nothing would be output by the filter, so return empty rect return skif::LayerSpace<SkIRect>(SkIRect::MakeEmpty()); } } // If we have no known content bounds use the desired coverage area, because that is the most // conservative possibility. skif::LayerSpace<SkIRect> contentBounds = knownContentBounds ? mapping.paramToLayer(*knownContentBounds).roundOut() : desiredBounds; // Process the layer-space desired output with the filter DAG to determine required input skif::LayerSpace<SkIRect> requiredInput = this->onGetInputLayerBounds( mapping, desiredBounds, contentBounds); // If we know what's actually going to be drawn into the layer, and we don't change transparent // black, then we can further restrict the layer to what the known content is // TODO (michaelludwig) - This logic could be moved into visitInputLayerBounds() when an input // filter is null. Additionally, once all filters are robust to FilterResults with tile modes, // we can always restrict the required input by content bounds since any additional transparent // black is handled when producing the output result and sampling outside the input image with // a decal tile mode. if (knownContentBounds && !this->affectsTransparentBlack()) { if (!requiredInput.intersect(contentBounds)) { // Nothing would be output by the filter, so return empty rect return skif::LayerSpace<SkIRect>(SkIRect::MakeEmpty()); } } return requiredInput; } skif::DeviceSpace<SkIRect> SkImageFilter_Base::getOutputBounds( const skif::Mapping& mapping, const skif::ParameterSpace<SkRect>& contentBounds) const { // Map the input content into the layer space where filtering will occur skif::LayerSpace<SkRect> layerContent = mapping.paramToLayer(contentBounds); // Determine the filter DAGs output bounds in layer space skif::LayerSpace<SkIRect> filterOutput = this->onGetOutputLayerBounds( mapping, layerContent.roundOut()); // Map all the way to device space return mapping.layerToDevice(filterOutput); } // TODO (michaelludwig) - Default to using the old onFilterImage, as filters are updated one by one. // Once the old function is gone, this onFilterImage() will be made a pure virtual. skif::FilterResult SkImageFilter_Base::onFilterImage(const skif::Context& context) const { SkIPoint origin = {0, 0}; auto image = this->onFilterImage(context, &origin); return skif::FilterResult(std::move(image), skif::LayerSpace<SkIPoint>(origin)); } SkImageFilter_Base::MatrixCapability SkImageFilter_Base::getCTMCapability() const { MatrixCapability result = this->onGetCTMCapability(); // CropRects need to apply in the source coordinate system, but are not aware of complex CTMs // when performing clipping. For a simple fix, any filter with a crop rect set cannot support // more than scale+translate CTMs until that's updated. if (this->cropRectIsSet()) { result = std::min(result, MatrixCapability::kScaleTranslate); } const int count = this->countInputs(); for (int i = 0; i < count; ++i) { if (const SkImageFilter_Base* input = as_IFB(this->getInput(i))) { result = std::min(result, input->getCTMCapability()); } } return result; } void SkImageFilter_Base::CropRect::applyTo(const SkIRect& imageBounds, const SkMatrix& ctm, bool embiggen, SkIRect* cropped) const { *cropped = imageBounds; if (fFlags) { SkRect devCropR; ctm.mapRect(&devCropR, fRect); SkIRect devICropR = devCropR.roundOut(); // Compute the left/top first, in case we need to modify the right/bottom for a missing edge if (fFlags & kHasLeft_CropEdge) { if (embiggen || devICropR.fLeft > cropped->fLeft) { cropped->fLeft = devICropR.fLeft; } } else { devICropR.fRight = Sk32_sat_add(cropped->fLeft, devICropR.width()); } if (fFlags & kHasTop_CropEdge) { if (embiggen || devICropR.fTop > cropped->fTop) { cropped->fTop = devICropR.fTop; } } else { devICropR.fBottom = Sk32_sat_add(cropped->fTop, devICropR.height()); } if (fFlags & kHasWidth_CropEdge) { if (embiggen || devICropR.fRight < cropped->fRight) { cropped->fRight = devICropR.fRight; } } if (fFlags & kHasHeight_CropEdge) { if (embiggen || devICropR.fBottom < cropped->fBottom) { cropped->fBottom = devICropR.fBottom; } } } } bool SkImageFilter_Base::applyCropRect(const Context& ctx, const SkIRect& srcBounds, SkIRect* dstBounds) const { SkIRect tmpDst = this->onFilterNodeBounds(srcBounds, ctx.ctm(), kForward_MapDirection, nullptr); fCropRect.applyTo(tmpDst, ctx.ctm(), this->onAffectsTransparentBlack(), dstBounds); // Intersect against the clip bounds, in case the crop rect has // grown the bounds beyond the original clip. This can happen for // example in tiling, where the clip is much smaller than the filtered // primitive. If we didn't do this, we would be processing the filter // at the full crop rect size in every tile. return dstBounds->intersect(ctx.clipBounds()); } // Return a larger (newWidth x newHeight) copy of 'src' with black padding // around it. static sk_sp<SkSpecialImage> pad_image(SkSpecialImage* src, const SkImageFilter_Base::Context& ctx, int newWidth, int newHeight, int offX, int offY) { // We would like to operate in the source's color space (so that we return an "identical" // image, other than the padding. To achieve that, we'd create a new context using // src->getColorSpace() to replace ctx.colorSpace(). // That fails in at least two ways. For formats that are texturable but not renderable (like // F16 on some ES implementations), we can't create a surface to do the work. For sRGB, images // may be tagged with an sRGB color space (which leads to an sRGB config in makeSurface). But // the actual config of that sRGB image on a device with no sRGB support is non-sRGB. // // Rather than try to special case these situations, we execute the image padding in the // destination color space. This should not affect the output of the DAG in (almost) any case, // because the result of this call is going to be used as an input, where it would have been // switched to the destination space anyway. The one exception would be a filter that expected // to consume unclamped F16 data, but the padded version of the image is pre-clamped to 8888. // We can revisit this logic if that ever becomes an actual problem. sk_sp<SkSpecialSurface> surf(ctx.makeSurface(SkISize::Make(newWidth, newHeight))); if (!surf) { return nullptr; } SkCanvas* canvas = surf->getCanvas(); SkASSERT(canvas); canvas->clear(0x0); src->draw(canvas, offX, offY); return surf->makeImageSnapshot(); } sk_sp<SkSpecialImage> SkImageFilter_Base::applyCropRectAndPad(const Context& ctx, SkSpecialImage* src, SkIPoint* srcOffset, SkIRect* bounds) const { const SkIRect srcBounds = SkIRect::MakeXYWH(srcOffset->x(), srcOffset->y(), src->width(), src->height()); if (!this->applyCropRect(ctx, srcBounds, bounds)) { return nullptr; } if (srcBounds.contains(*bounds)) { return sk_sp<SkSpecialImage>(SkRef(src)); } else { sk_sp<SkSpecialImage> img(pad_image(src, ctx, bounds->width(), bounds->height(), Sk32_sat_sub(srcOffset->x(), bounds->x()), Sk32_sat_sub(srcOffset->y(), bounds->y()))); *srcOffset = SkIPoint::Make(bounds->x(), bounds->y()); return img; } } // NOTE: The new onGetOutputLayerBounds() and onGetInputLayerBounds() default to calling into the // deprecated onFilterBounds and onFilterNodeBounds. While these functions are not tagged, they do // match the documented default behavior for the new bounds functions. SkIRect SkImageFilter_Base::onFilterBounds(const SkIRect& src, const SkMatrix& ctm, MapDirection dir, const SkIRect* inputRect) const { if (this->countInputs() < 1) { return src; } SkIRect totalBounds; for (int i = 0; i < this->countInputs(); ++i) { const SkImageFilter* filter = this->getInput(i); SkIRect rect = filter ? filter->filterBounds(src, ctm, dir, inputRect) : src; if (0 == i) { totalBounds = rect; } else { totalBounds.join(rect); } } return totalBounds; } SkIRect SkImageFilter_Base::onFilterNodeBounds(const SkIRect& src, const SkMatrix&, MapDirection, const SkIRect*) const { return src; } skif::LayerSpace<SkIRect> SkImageFilter_Base::visitInputLayerBounds( const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& desiredOutput, const skif::LayerSpace<SkIRect>& contentBounds) const { if (this->countInputs() < 1) { // TODO (michaelludwig) - if a filter doesn't have any inputs, it doesn't need any // implicit source image, so arguably we could return an empty rect here. 'desiredOutput' is // consistent with original behavior, so empty bounds may have unintended side effects // but should be explored later. Of note is that right now an empty layer bounds assumes // that there's no need to filter on restore, which is not the case for these filters. return desiredOutput; } skif::LayerSpace<SkIRect> netInput; for (int i = 0; i < this->countInputs(); ++i) { const SkImageFilter* filter = this->getInput(i); // The required input for this input filter, or 'targetOutput' if the filter is null and // the source image is used (so must be sized to cover 'targetOutput'). // TODO (michaelludwig) - Right now contentBounds is applied conditionally at the end of // the root getInputLayerBounds() based on affecting transparent black. Once that bit only // changes output behavior, we can have the required bounds for a null input filter be the // intersection of the desired output and the content bounds. skif::LayerSpace<SkIRect> requiredInput = filter ? as_IFB(filter)->onGetInputLayerBounds(mapping, desiredOutput, contentBounds) : desiredOutput; // Accumulate with all other filters if (i == 0) { netInput = requiredInput; } else { netInput.join(requiredInput); } } return netInput; } skif::LayerSpace<SkIRect> SkImageFilter_Base::visitOutputLayerBounds( const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& contentBounds) const { if (this->countInputs() < 1) { // TODO (michaelludwig) - if a filter doesn't have any inputs, it presumably is determining // its output size from something other than the implicit source contentBounds, in which // case it shouldn't be calling this helper function, so explore adding an unreachable test return contentBounds; } skif::LayerSpace<SkIRect> netOutput; for (int i = 0; i < this->countInputs(); ++i) { const SkImageFilter* filter = this->getInput(i); // The output for just this input filter, or 'contentBounds' if the filter is null and // the source image is used (i.e. the identity filter applied to the source). skif::LayerSpace<SkIRect> output = filter ? as_IFB(filter)->onGetOutputLayerBounds(mapping, contentBounds) : contentBounds; // Accumulate with all other filters if (i == 0) { netOutput = output; } else { netOutput.join(output); } } return netOutput; } skif::LayerSpace<SkIRect> SkImageFilter_Base::onGetInputLayerBounds( const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& desiredOutput, const skif::LayerSpace<SkIRect>& contentBounds, VisitChildren recurse) const { // Call old functions for now since they may have been overridden by a subclass that's not been // updated yet; eventually this will be a pure virtual and impls control visiting children SkIRect content = SkIRect(contentBounds); SkIRect input = this->onFilterNodeBounds(SkIRect(desiredOutput), mapping.layerMatrix(), kReverse_MapDirection, &content); if (recurse == VisitChildren::kYes) { SkIRect aggregate = this->onFilterBounds(input, mapping.layerMatrix(), kReverse_MapDirection, &input); return skif::LayerSpace<SkIRect>(aggregate); } else { return skif::LayerSpace<SkIRect>(input); } } skif::LayerSpace<SkIRect> SkImageFilter_Base::onGetOutputLayerBounds( const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& contentBounds) const { // Call old functions for now; eventually this will be a pure virtual. The old functions for // filters that affected transparent black were often not overridden, in which case they would // just return 'contentBounds' instead of being infinite. They also assumed the base class // handled all cropping. New filter implementations rely on SkCropImageFilter and do not use // the built-in CropRect so their isCropRectSet() always returns false. SkIRect output; if (this->onAffectsTransparentBlack()) { output = SkRectPriv::MakeILarge(); } else { SkIRect aggregate = this->onFilterBounds(SkIRect(contentBounds), mapping.layerMatrix(), kForward_MapDirection, nullptr); output = this->onFilterNodeBounds(aggregate, mapping.layerMatrix(), kForward_MapDirection, nullptr); } SkIRect dst; as_IFB(this)->getCropRect().applyTo( output, mapping.layerMatrix(), this->onAffectsTransparentBlack(), &dst); return skif::LayerSpace<SkIRect>(dst); } // TODO (michaelludwig): Remove filterInput() use as cleanup continues. IMO it's automatic calls // to mapContext() and onGetInputLayerBounds() obfuscates how the bounds request flows through // the DAG. Particularly once dry-runs are possible, the only place that needs to calculate the // required input / new context's desired output is in each filter's onFilterImage() impl. skif::FilterResult SkImageFilter_Base::filterInput(int index, const skif::Context& ctx) const { const SkImageFilter* input = this->getInput(index); if (!input) { // Null image filters late bind to the source image return ctx.source(); } skif::FilterResult result = as_IFB(input)->filterImage(this->mapContext(ctx)); SkASSERT(!result.image() || ctx.gpuBacked() == result.image()->isTextureBacked()); return result; } sk_sp<SkSpecialImage> SkImageFilter_Base::filterInput(int index, const skif::Context& ctx, SkIPoint* offset) const { // The deprecated version needs to use the mapped context for the call to imageAndOffset(). skif::Context inputCtx = this->mapContext(ctx); const SkImageFilter* input = this->getInput(index); if (!input) { // Null image filters late bind to the source image return ctx.source().imageAndOffset(inputCtx, offset); } skif::FilterResult result = as_IFB(input)->filterImage(inputCtx); SkASSERT(!result.image() || ctx.gpuBacked() == result.image()->isTextureBacked()); return result.imageAndOffset(inputCtx, offset); } SkImageFilter_Base::Context SkImageFilter_Base::mapContext(const Context& ctx) const { // We don't recurse through the child input filters because that happens automatically // as part of the filterImage() evaluation. In this case, we want the bounds for the // edge from this node to its children, without the effects of the child filters. skif::LayerSpace<SkIRect> childOutput = this->onGetInputLayerBounds( ctx.mapping(), ctx.desiredOutput(), ctx.desiredOutput(), VisitChildren::kNo); return ctx.withNewDesiredOutput(childOutput); } #if defined(SK_GANESH) sk_sp<SkSpecialImage> SkImageFilter_Base::DrawWithFP(GrRecordingContext* rContext, std::unique_ptr<GrFragmentProcessor> fp, const SkIRect& bounds, SkColorType colorType, const SkColorSpace* colorSpace, const SkSurfaceProps& surfaceProps, GrSurfaceOrigin surfaceOrigin, GrProtected isProtected) { GrImageInfo info(SkColorTypeToGrColorType(colorType), kPremul_SkAlphaType, sk_ref_sp(colorSpace), bounds.size()); auto sfc = rContext->priv().makeSFC(info, "ImageFilterBase_DrawWithFP", SkBackingFit::kApprox, 1, GrMipmapped::kNo, isProtected, surfaceOrigin); if (!sfc) { return nullptr; } SkIRect dstIRect = SkIRect::MakeWH(bounds.width(), bounds.height()); SkRect srcRect = SkRect::Make(bounds); sfc->fillRectToRectWithFP(srcRect, dstIRect, std::move(fp)); return SkSpecialImage::MakeDeferredFromGpu(rContext, dstIRect, kNeedNewImageUniqueID_SpecialImage, sfc->readSurfaceView(), sfc->colorInfo(), surfaceProps); } sk_sp<SkSpecialImage> SkImageFilter_Base::ImageToColorSpace(const skif::Context& ctx, SkSpecialImage* src) { // There are several conditions that determine if we actually need to convert the source to the // destination's color space. Rather than duplicate that logic here, just try to make an xform // object. If that produces something, then both are tagged, and the source is in a different // gamut than the dest. There is some overhead to making the xform, but those are cached, and // if we get one back, that means we're about to use it during the conversion anyway. auto colorSpaceXform = GrColorSpaceXform::Make(src->getColorSpace(), src->alphaType(), ctx.colorSpace(), kPremul_SkAlphaType); if (!colorSpaceXform) { // No xform needed, just return the original image return sk_ref_sp(src); } sk_sp<SkSpecialSurface> surf = ctx.makeSurface(src->dimensions()); if (!surf) { return sk_ref_sp(src); } SkCanvas* canvas = surf->getCanvas(); SkASSERT(canvas); SkPaint p; p.setBlendMode(SkBlendMode::kSrc); src->draw(canvas, 0, 0, SkSamplingOptions(), &p); return surf->makeImageSnapshot(); } #endif // In repeat mode, when we are going to sample off one edge of the srcBounds we require the // opposite side be preserved. SkIRect SkImageFilter_Base::DetermineRepeatedSrcBound(const SkIRect& srcBounds, const SkIVector& filterOffset, const SkISize& filterSize, const SkIRect& originalSrcBounds) { SkIRect tmp = srcBounds; tmp.adjust(-filterOffset.fX, -filterOffset.fY, filterSize.fWidth - filterOffset.fX, filterSize.fHeight - filterOffset.fY); if (tmp.fLeft < originalSrcBounds.fLeft || tmp.fRight > originalSrcBounds.fRight) { tmp.fLeft = originalSrcBounds.fLeft; tmp.fRight = originalSrcBounds.fRight; } if (tmp.fTop < originalSrcBounds.fTop || tmp.fBottom > originalSrcBounds.fBottom) { tmp.fTop = originalSrcBounds.fTop; tmp.fBottom = originalSrcBounds.fBottom; } return tmp; } void SkImageFilter_Base::PurgeCache() { SkImageFilterCache::Get()->purge(); }
[ "jengelh@inai.de" ]
jengelh@inai.de
4fcb14d380c1d347c97453e93b5474c55bf5be36
87464fd51294f061472244148aebce14e454f2a6
/Practice/Codechef/JulyLong20/DRGNDEN.cpp
f9e2ce2e0c2e3c346d227794657abdf6a1f8d601
[]
no_license
msk4862/DS-Algo
6fb348e4ae0f685f58b89f619ce4edc6690c3817
10e41a8ce1879fceee6f064c81192aa3e981d8d4
refs/heads/master
2021-08-02T23:31:44.813569
2021-07-24T11:18:51
2021-07-24T11:18:51
199,693,163
4
3
null
2020-10-07T19:28:55
2019-07-30T16:56:48
C++
UTF-8
C++
false
false
1,677
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long int #define FASTIO \ ios_base::sync_with_stdio(false); \ cin.tie(nullptr); \ cout.tie(nullptr); ll travel(vector<ll> h, vector<ll> a, ll b, ll k) { if(b == k) { return a[b]; } if(h[b] <= h[k]) { return -1; } bool possible = true; ll taste, i; ll step = (b-k)/abs(b-k); taste = a[b] + a[k]; i = k+step; ll cur = k; while(i != b) { if(h[i] >= h[b]) { possible =false; break; } if(h[i] > h[cur]) { taste += a[i]; cur = i; } i += step; } if(possible) return taste; return -1; } void solve() { ll n, q; cin>>n>>q; vector<ll> h(n); for (ll i = 0; i < n; i++) { cin>>h[i]; } vector<ll> a(n); for (ll i = 0; i < n; i++) { cin>>a[i]; } ll taste_s[n][n]; // precalculating tastiness for (ll i = 0; i < n; i++) { for (ll j = 0; j < n; j++) { taste_s[i][j] = travel(h, a, i, j); } } while(q--) { ll t; cin>>t; if(t==1) { ll b, c; cin>>b>>c; a[b-1] = c; continue; } // travel else { ll b, k; cin>>b>>k; b -=1; k -=1; cout<<taste_s[b][k]<<"\n"; } } } int main() { FASTIO; solve(); return 0; }
[ "shoaib.mca19.du@gmail.com" ]
shoaib.mca19.du@gmail.com
fe797e4d0b4c0b1789f54fc7ce26d70e20cc78af
e5aa1c3c356541b499de3bcbc5db940ae12818d6
/maxmin.cpp
8302b67334224745bee86d27f419a0a1b806ee99
[]
no_license
BiswayanPaul/new_github-tutorials
50a1bf9780e2f4600aa08592abeae849e0b79729
5c4ed8c08b3c4cf0ff5ee3377b4c2195da08bfd4
refs/heads/master
2023-01-08T16:32:17.726361
2020-10-30T10:18:28
2020-10-30T10:18:28
308,213,468
1
0
null
null
null
null
UTF-8
C++
false
false
577
cpp
#include<iostream> using namespace std; int main(){ int n1,n2,n3; cout<<"Enter three numbers"<<endl; cin>>n1>>n2>>n3; if (n1>n2) { if (n1>n3) { cout<<"The maximum number is "<<n1<<endl; } else { cout<<"The maximum number is "<<n3<<endl; } } else { if (n2>n3) { cout<<"The maximum number is "<<n2<<endl; } else { cout<<"The maximum number is "<<n3<<endl; } } return 0; }
[ "biswayanpaul2015@gmail.com" ]
biswayanpaul2015@gmail.com
18152832df4494c1ace0d17d8bf6e67616b7a3b3
a2111a80faf35749d74a533e123d9da9da108214
/raw/workshop12/workshop2012-data-20120906/trunk/.svn/pristine/18/18152832df4494c1ace0d17d8bf6e67616b7a3b3.svn-base
e6dc76a92e5706c69d2af13eb30c130a21a745d1
[ "BSD-3-Clause", "MIT" ]
permissive
bkahlert/seqan-research
f2c550d539f511825842a60f6b994c1f0a3934c2
21945be863855077eec7cbdb51c3450afcf560a3
refs/heads/master
2022-12-24T13:05:48.828734
2015-07-01T01:56:22
2015-07-01T01:56:22
21,610,669
1
0
null
null
null
null
UTF-8
C++
false
false
81,923
/*========================================================================== This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your options) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ==========================================================================*/ //#define RAZERS_DUMP_SNPS //#define COVBASED_INDELCALLING //#define SNP_STORE_RTTEST //#define CORRECTED_HET #define TRACE_PIPELINE //#define READS_454 //#define SNPSTORE_DEBUG //#define SNPSTORE_DEBUG_CANDPOS //#ifdef SNPSTORE_DEBUG //#define SNPSTORE_DEBUG_CANDPOS //#endif #include <seqan/platform.h> #include <seqan/sequence.h> #include <seqan/file.h> #include <seqan/align.h> #include <seqan/store.h> #include <seqan/consensus.h> #include <seqan/stream.h> #include <seqan/bam_io.h> //#include "snp_store_underconstruction.h" #ifdef PLATFORM_WINDOWS #define SEQAN_DEFAULT_TMPDIR "C:\\TEMP\\" #else #define SEQAN_DEFAULT_TMPDIR "./" #endif //#include "/home/takifugu2/emde/seqan/seqan-trunk/projects/library/apps/razers/outputFormat.h" //#include "../../../extras/apps/rep_sep/utils.h" //#include "../../../extras/apps/rep_sep/assembly_parser.h" //#include "../../../extras/apps/rep_sep/column_scanner.h" //#include "../../../extras/apps/rep_sep/rgraph.h" //#include "/home/takifugu2/emde/seqanRestructured/seqan-trunk/extras/apps/rep_sep/rep_sep.h" #include "snp_store.h" #include <iostream> #include <fstream> #include <sstream> #include <map> using namespace std; using namespace seqan; // load entire genome into memory template <typename TGenomeSet, typename TGenomeNames> bool loadGenomes(TGenomeSet &genomes, StringSet<CharString> &fileNameList, ::std::map<CharString,unsigned> &gIdStringToIdNumMap, TGenomeNames & genomeNames) { unsigned gSeqNo = 0; unsigned filecount = 0; CharString temp; clear(genomeNames); while(filecount < length(fileNameList)) { clear(temp); MultiFasta multiFasta; if (!open(multiFasta.concat, toCString(fileNameList[filecount]), OPEN_RDONLY)) return false; split(multiFasta, Fasta()); unsigned seqCount = length(multiFasta); if(length(genomes) < gSeqNo+seqCount) resize(genomes,gSeqNo+seqCount); for(unsigned i = 0; i < seqCount; ++i) { assignSeq(genomes[gSeqNo+i], multiFasta[i], Fasta()); // read Genome sequence assignSeqId(temp, multiFasta[i], Fasta()); for (unsigned pos = 0; pos < length(temp); ++pos) { if(temp[pos]=='\t' || temp[pos]=='\b' || temp[pos]==' ') { resize(temp,pos); break; } } gIdStringToIdNumMap.insert(::std::make_pair<CharString,unsigned>(temp,gSeqNo+i)); //TODO shortID appendValue(genomeNames,temp); } gSeqNo += seqCount; ++filecount; } resize(genomes,gSeqNo); return (gSeqNo > 0); } // transform global cooridnates to coordinates relative to chromosomal segment template<typename TFragmentStore, typename TContigPos, typename TOptions> void transformCoordinates(TFragmentStore &fragmentStore, TContigPos startCoord, TOptions&) { typedef typename TFragmentStore::TAlignedReadStore TMatches; typedef typename Value<TMatches>::Type TMatch; typedef typename Iterator<TMatches,Standard>::Type TMatchIt; TMatchIt mIt = begin(fragmentStore.alignedReadStore,Standard()); TMatchIt mItEnd = end(fragmentStore.alignedReadStore,Standard()); while(mIt != mItEnd) { (*mIt).endPos -= startCoord; (*mIt).beginPos -= startCoord; ++mIt; } } // copy matches relevant for next window template<typename TFragmentStore, typename TReadCigars, typename TReadCounts, typename TReadClips, typename TSize, typename TContigPos, typename TOptions> void copyNextWindowMatchesAndReads(TFragmentStore &fragmentStore, TReadCounts &readCounts, TReadCigars &readCigars, TReadClips &readClips, TReadCounts &tmpReadCounts, typename TFragmentStore::TReadSeqStore &tmpReads, typename TFragmentStore::TReadStore &tmpRs, typename TFragmentStore::TAlignedReadStore &tmpMatches, typename TFragmentStore::TAlignQualityStore &tmpQualities, TReadClips &tmpReadClips, TReadCigars &tmpReadCigars, TSize , TContigPos currentWindowEnd, TOptions &options) { typedef typename TFragmentStore::TAlignedReadStore TMatches; typedef typename Value<TMatches>::Type TMatch; typedef typename Iterator<TMatches,Standard>::Type TMatchIt; typedef typename Id<TFragmentStore>::Type TId; typedef typename Value<TReadClips>::Type TPair; SEQAN_ASSERT_EQ(length(fragmentStore.readSeqStore),length(fragmentStore.alignQualityStore)); ::std::sort(begin(fragmentStore.alignedReadStore, Standard()), end(fragmentStore.alignedReadStore, Standard()), LessGPos<TMatch>()); if(options._debugLevel > 1 )::std::cout << "Copying matches overlapping more than one window ... \n"; TMatchIt mIt = end(fragmentStore.alignedReadStore,Standard()); TMatchIt mItBegin = begin(fragmentStore.alignedReadStore,Standard()); --mIt; options.minCoord = MaxValue<unsigned>::VALUE; options.maxCoord = 0; //CharString str = "discBef"; //_dumpMatches(fragmentStore, str); //std::cout << " max hit length = " << options.maxHitLength << std::endl; // look for matches that are inside our window of interest, copy corresponding matches,reads,qualities while(mIt >= mItBegin && _min((*mIt).beginPos,(*mIt).endPos) + (TContigPos)options.maxHitLength + (TContigPos)options.windowBuff >= currentWindowEnd ) { if( _max((*mIt).beginPos,(*mIt).endPos) + (TContigPos)options.windowBuff > currentWindowEnd ) { TId id = length(tmpMatches); appendValue(tmpMatches,*mIt); tmpMatches[id].id = id; tmpMatches[id].readId = id; appendValue(tmpReads,fragmentStore.readSeqStore[(*mIt).readId]); appendValue(tmpRs,fragmentStore.readStore[(*mIt).readId]); if(!empty(readCounts))appendValue(tmpReadCounts,readCounts[(*mIt).readId]); appendValue(tmpQualities,fragmentStore.alignQualityStore[(*mIt).readId]); appendValue(tmpReadCigars,readCigars[(*mIt).readId]); // appendValue(tmpReadClips,TPair(0,0)); appendValue(tmpReadClips,readClips[(*mIt).readId]); if(_max((*mIt).beginPos,(*mIt).endPos) > (TContigPos)options.maxCoord) options.maxCoord = (unsigned) _max((*mIt).beginPos,(*mIt).endPos); if(_min((*mIt).beginPos,(*mIt).endPos) < (TContigPos)options.minCoord) options.minCoord = (unsigned) _min((*mIt).beginPos,(*mIt).endPos); } --mIt; } if(options._debugLevel > 1) std::cout << length(tmpMatches)<<" matches left over from previous window.\n"; } // little helper template<typename TMatch> char orientation(TMatch & match) { if(match.endPos > match.beginPos) return 'F'; else return 'R'; } // discard reads stacking up, give preference to high quality reads template<typename TFragmentStore, typename TSize, typename TOptions> void applyPileupCorrection(TFragmentStore &fragmentStore, TSize arrayBeginPos, TSize arrayEndPos, TOptions &options) { typedef StringSet<String<Dna5Q>, Owner<ConcatDirect<> > > TFalseType; typedef typename TFragmentStore::TAlignedReadStore TMatches; typedef typename Value<TMatches>::Type TMatch; typedef typename TFragmentStore::TAlignQualityStore TMatchQualities; typedef typename Value<TMatchQualities>::Type TMatchQuality; typedef typename TFragmentStore::TReadSeqStore TReads; typedef typename Value<TReads>::Type TRead; typedef typename TFragmentStore::TContigStore TGenomeSet; typedef typename Value<TGenomeSet>::Type TGenome; typedef typename TFragmentStore::TContigPos TContigPos; typedef typename Iterator<TMatches,Standard>::Type TMatchIterator; if(IsSameType<TReads, TFalseType >::VALUE) std::cout << "Hier stimmt was nciht. strinsetspec concat direct\n"; if(options._debugLevel > 0) std::cout << arrayEndPos - arrayBeginPos << " matches subject to pile up correction." << std::endl; //CharString str = "pileBef"; //_dumpMatches(fragmentStore, str); if(options.orientationAware) ::std::sort(iter(fragmentStore.alignedReadStore, arrayBeginPos, Standard()), iter(fragmentStore.alignedReadStore, arrayEndPos, Standard()), LessGStackOaMQ<TMatches,TMatchQualities>(fragmentStore.alignQualityStore)); else ::std::sort(iter(fragmentStore.alignedReadStore, arrayBeginPos, Standard()), iter(fragmentStore.alignedReadStore, arrayEndPos, Standard()), LessGStackMQ<TMatches,TMatchQualities>(fragmentStore.alignQualityStore)); TMatchIterator matchIt = iter(fragmentStore.alignedReadStore, arrayBeginPos, Standard()); TMatchIterator matchRangeEnd = iter(fragmentStore.alignedReadStore, arrayEndPos, Standard()); TMatchIterator matchItKeep = matchIt; while(matchIt != matchRangeEnd) { TContigPos currentBegin = _min((*matchIt).beginPos,(*matchIt).endPos); TContigPos currentEnd = _max((*matchIt).beginPos,(*matchIt).endPos); unsigned currentSeqno = (*matchIt).contigId; char currentOrientation = orientation(*matchIt); unsigned currPile = 0; while(matchIt != matchRangeEnd && (*matchIt).contigId == currentSeqno && _min((*matchIt).beginPos,(*matchIt).endPos) == currentBegin && _max((*matchIt).beginPos,(*matchIt).endPos) == currentEnd && (!options.orientationAware || orientation(*matchIt) == currentOrientation) && currPile < options.maxPile) { *matchItKeep = *matchIt; ++currPile; ++matchIt; ++matchItKeep; } //if(matchRangeEnd > matchItEnd) ::std::cerr <<"neeeeeeee\n"; while(matchIt != matchRangeEnd && (*matchIt).contigId == currentSeqno && _min((*matchIt).beginPos,(*matchIt).endPos) == currentBegin && _max((*matchIt).beginPos,(*matchIt).endPos) == currentEnd && (!options.orientationAware || orientation(*matchIt) == currentOrientation)) ++matchIt; } if(options._debugLevel > 0) std::cout << matchIt - matchItKeep << " matches discarded." << std::endl; resize(fragmentStore.alignedReadStore,matchItKeep - begin(fragmentStore.alignedReadStore,Standard())); // ::std::cout << "numMatches = " << length(fragmentStore.alignedReadStore) << ::std::endl; SEQAN_ASSERT_LEQ(length(fragmentStore.alignedReadStore), length(fragmentStore.alignQualityStore)); SEQAN_ASSERT_EQ(length(fragmentStore.readSeqStore), length(fragmentStore.alignQualityStore)); // str="pileAft"; // _dumpMatches(fragmentStore,str); } // average quality of read is kept as extra info for each match // used for prioritization in pile up correction template<typename TFragmentStore, typename TSize, typename TOptions> void addReadQualityToMatches(TFragmentStore &fragmentStore, TSize arrayBeginPos, TSize arrayEndPos, TOptions &) { typedef typename TFragmentStore::TAlignedReadStore TMatches; typedef typename Value<TMatches>::Type TMatch; typedef typename TFragmentStore::TReadSeqStore TReads; typedef typename Value<TReads>::Type TRead; typedef typename Iterator<TMatches, Standard>::Type TIterator; TIterator it = iter(fragmentStore.alignedReadStore, arrayBeginPos, Standard()); TIterator itEnd = iter(fragmentStore.alignedReadStore, arrayEndPos, Standard()); int avgRQ; for (; it != itEnd; ++it) { TRead const &read = fragmentStore.readSeqStore[(*it).readId]; avgRQ = 0; for(unsigned i = 0; i < length(read); ++i) avgRQ += (int) getQualityValue(read[i]); // watch out, this is new: use mapping quality if given if((fragmentStore.alignQualityStore[(*it).id]).score == 0 || (char)(avgRQ/length(read))<(fragmentStore.alignQualityStore[(*it).id]).score) (fragmentStore.alignQualityStore[(*it).id]).score = (char)(avgRQ/length(read)); } } // checks whether an alignment has indels template<typename TValue, typename TSpec> bool alignmentHasIndel(Align<TValue,TSpec> &align) { typedef Align<TValue,TSpec> TAlign; typedef typename Row<TAlign>::Type TAlignRow; typedef typename Iterator<TAlignRow>::Type TAlignIterator; bool hasIndel = false; for(unsigned i = 0; !hasIndel && i < length(rows(align)); ++i) { TAlignIterator it = begin(row(align,i)); TAlignIterator itEnd = end(row(align,i)); while (it != itEnd) { if(isGap(it)) { hasIndel = true; break; } ++it; } } return hasIndel; } // perform read clipping template<typename TFragmentStore, typename TReadClips, typename TSize, typename TOptions> void clipReads(TFragmentStore &fragmentStore, TReadClips &readClips, TSize arrayBeginPos, TSize arrayEndPos, TOptions &options) { typedef typename TFragmentStore::TAlignedReadStore TMatches; typedef typename Value<TMatches>::Type TMatch; typedef typename TFragmentStore::TAlignQualityStore TAlignQualityStore; // TMatchQualities typedef typename Value<TAlignQualityStore>::Type TAlignQuality; typedef typename TFragmentStore::TReadSeqStore TReads; typedef typename Value<TReads>::Type TRead; typedef typename Iterator<TMatches, Standard>::Type TIterator; typedef typename TFragmentStore::TContigSeq TContigSeq; // TGenome typedef typename Position<TContigSeq>::Type TContigPos; TIterator it = iter(fragmentStore.alignedReadStore, arrayBeginPos, Standard()); TIterator itEnd = iter(fragmentStore.alignedReadStore, arrayEndPos, Standard()); Align<TRead, ArrayGaps> align; resize(rows(align), 2); #ifdef SNPSTORE_DEBUG bool extraV = true; #endif Score<int> scoreType = Score<int>(0, -999, -1001, -1000); if(length(readClips) < (arrayEndPos-arrayBeginPos)) ::std::cout << length(readClips) << " readclips but " << (arrayEndPos-arrayBeginPos) << " many reads.\n"; TContigSeq &currGenome = fragmentStore.contigStore[0].seq; int kickout = 0; for (; it != itEnd; ++it) { TMatch &m = *it; TRead &read = fragmentStore.readSeqStore[m.readId]; int clipLeft = readClips[m.readId].i1; int clipRight = readClips[m.readId].i2; TContigPos beginPos = (m.beginPos < m.endPos ) ? m.beginPos : m.endPos; TContigPos endPos = (m.beginPos > m.endPos ) ? m.beginPos : m.endPos; TAlignQuality &aliQ = fragmentStore.alignQualityStore[m.id]; #ifdef SNPSTORE_DEBUG TContigPos beginBefore = beginPos; #endif if(m.id != m.readId) ::std::cout << "match id != readId \n"; if(clipLeft+clipRight > (int)length(read) || clipLeft > (int)length(read) || clipRight > (int)length(read)) { if(options._debugLevel > 0)::std::cout << "WARNING: clipLeft+clipRight > readLen!!\n"; #ifdef SNPSTORE_DEBUG ::std::cout << "readlength = "<<length(read)<< " \n"; ::std::cout << "readId = "<<m.readId << "id=" << m.id << " \n"; ::std::cout << "clipLeft = " << clipLeft << " clipRight = "<<clipRight << "\n"; ::std::cout << "read=" << read << std::endl; ::std::cout << "beginPos=" << beginPos << std::endl; ::std::cout << "endPos=" << endPos << std::endl; #endif clipLeft = length(read); clipRight = 0; } #ifdef SNPSTORE_DEBUG ::std::cout << "readlength = "<<length(read)<< " \n"; ::std::cout << "readId = "<<m.readId << "id=" << m.id << " \n"; ::std::cout << "clipLeft = " << clipLeft << " clipRight = "<<clipRight << "\n"; ::std::cout << "read=" << read << std::endl; ::std::cout << "beginPos=" << beginPos << std::endl; ::std::cout << "endPos=" << endPos << std::endl; #endif if(clipLeft > 0 || clipRight > 0) { // if(extraV) ::std::cout << "clipLeft = " << clipLeft << " clipRight = "<<clipRight << std::endl; if((int)length(read)-clipLeft-clipRight < options.minClippedLength) { if(options._debugLevel > 1 ) ::std::cout << "Discarded: "<<read<<" at position "<< beginPos <<"\n"; m.endPos = m.beginPos = 0; // "mask" read read = ""; ++kickout; continue; } // adjust read sequence read = infix(read,clipLeft,length(read)-clipRight); // upate avg read quality int avgRQ = 0; for(unsigned i = 0; i < length(read); ++i) avgRQ += (int) getQualityValue(read[i]); aliQ.score = (char)(avgRQ/length(read)); // if(extraV) ::std::cout << "aliQ.score = " << (int)aliQ.score << ::std::endl; //do semi-global alignment assignSource(row(align, 0), read); assignSource(row(align, 1), infix(currGenome, beginPos, endPos)); if ((*it).endPos < (*it).beginPos) reverseComplement(source(row(align, 1))); int score = globalAlignment(align, scoreType, AlignConfig<false,true,true,false>(), Gotoh()); aliQ.errors = (unsigned) round((float)-score/1000); #ifdef SNPSTORE_DEBUG if(extraV) ::std::cout << align << std::endl; if(extraV) ::std::cout << "aliQ.errors = " << (int) aliQ.errors << std::endl; #endif // transform first and last read character to genomic positions if(aliQ.pairScore == 1) { unsigned viewPosReadFirst = toViewPosition(row(align, 0), 0); unsigned viewPosReadLast = toViewPosition(row(align, 0), length(read) - 1); unsigned genomePosReadFirst = toSourcePosition(row(align, 1), viewPosReadFirst); unsigned genomePosReadLast = toSourcePosition(row(align, 1), viewPosReadLast); // if(isGap(row(align,1),viewPosReadFirst)) // { // std::cout << "bgein gap --> do nothing " << std::endl; // // } if(isGap(row(align,1),viewPosReadLast)) { genomePosReadLast--; } #ifdef SNPSTORE_DEBUG if(extraV) { ::std::cout << "viewPosReadFirst = " << viewPosReadFirst << ::std::endl; ::std::cout << "viewPosReadLast = " << viewPosReadLast << ::std::endl; ::std::cout << "genomePosReadFirst = " << genomePosReadFirst << ::std::endl; } #endif if(m.beginPos < m.endPos) // forward { endPos = beginPos + (genomePosReadLast + 1); beginPos += genomePosReadFirst; } else { beginPos = endPos - genomePosReadLast - 1; endPos = endPos - genomePosReadFirst; } if(!alignmentHasIndel(align)) aliQ.pairScore = 0; } else { if(m.beginPos < m.endPos) // forward { endPos -= clipRight; beginPos += clipLeft; } else { endPos -= clipLeft; beginPos += clipRight; } } // set genomic positions if(m.beginPos < m.endPos) // forward { m.endPos = endPos; m.beginPos = beginPos; } else { m.endPos = beginPos; m.beginPos = endPos; } if(beginPos > 300000000 || endPos > 300000000) { ::std::cout << "bgein groesser 300mio neu beginPos = "<< beginPos << " endpos=" << endPos << ::std::endl; #ifdef SNPSTORE_DEBUG ::std::cout << "WARNING: clipLeft+clipRight > readLen!!??\n"; ::std::cout << "readId = "<<m.readId << "id=" << m.id << " \n"; ::std::cout << "clipLeft = " << clipLeft << " clipRight = "<<clipRight << "\n"; ::std::cout << "read=" << read << std::endl; ::std::cout << "beginPos before=" << beginBefore << std::endl; ::std::cout << "beginPos=" << beginPos << std::endl; ::std::cout << "endPos=" << endPos << std::endl; #endif } } } if(options._debugLevel > 0) ::std::cout << kickout <<" reads too short after clipping, discarding!\n"; } template<typename TTable> void printHetTable(TTable & hetTable) { cout << "Printing het table:" << std::endl; for (int n1=0; n1<256; ++n1) { for (int n2=0; n2<256; ++n2) { cout << hetTable[n1<<8|n2] << "\t"; } cout << std::endl; } cout << std::endl; } template<typename TTmpReads, typename TTmpMatches, typename TTmpQualities, typename TStr> void _dumpMatches(TTmpReads & reads, TTmpMatches & matches, TTmpQualities & qualities, TStr str) { std::cout << "Length of matches = " << length(matches) << "\n"; std::cout << "Length of reads = " << length(reads) << "\n"; std::cout << "Length of matchqs = " << length(qualities) << "\n"; for(unsigned i = 0 ; i < length(matches); ++i) { char ori = (matches[i].beginPos < matches[i].endPos) ? 'F' : 'R'; std::cout << "--"<<str<<"Match number " << i << ":\n"; std::cout << "--"<<str<<"MatchId = " << matches[i].id << "\n"; std::cout << "--"<<str<<"ReadId = " << matches[i].readId << "\n"; std::cout << "--"<<str<<"ContigId = " << matches[i].contigId << std::flush << "\n"; std::cout << "--"<<str<<"gBegin = " << _min(matches[i].beginPos, matches[i].endPos) << "\n"; std::cout << "--"<<str<<"gEnd = " << _max(matches[i].beginPos, matches[i].endPos) << "\n"; std::cout << "--"<<str<<"orient = " << ori << std::flush << std::endl; if(length(qualities) > matches[i].id) { std::cout << "--"<<str<<"EditDist = " << (int) qualities[matches[i].id].errors << "\n"; std::cout << "--"<<str<<"AvgQ = " << (int) qualities[matches[i].id].score << "\n"; } std::cout << "--"<<str<<"Readseq = " << reads[matches[i].readId] << std::flush << "\n"; } } ////////////////////////////////////////////////////////////////////////////// // Main read mapper function template <typename TSpec> int detectSNPs( const char *genomeFileName, String<CharString> & readFNames, String<CharString> &, SNPCallingOptions<TSpec> &options) { typedef FragmentStore<SnpStoreSpec_> TFragmentStore; typedef typename TFragmentStore::TReadSeq TReadSeq; // TRead typedef typename TFragmentStore::TContigSeq TContigSeq; // TGenome //typedef typename Position<TReadSeq>::Type TReadPos; // TPos typedef typename TFragmentStore::TReadPos TReadPos; // TPos //typedef typename Position<TContigSeq>::Type TContigPos; // TContigPos typedef typename TFragmentStore::TContigPos TContigPos; typedef typename TFragmentStore::TAlignedReadStore TAlignedReadStore; // TMatches typedef typename TFragmentStore::TAlignQualityStore TAlignQualityStore; // TMatchQualities typedef typename TFragmentStore::TReadStore TReadStore; // TReadSet typedef typename TFragmentStore::TReadSeqStore TReadSeqStore; // TReadSet typedef typename TFragmentStore::TContigStore TContigStore; // TGenomeSet typedef typename Value<TContigStore>::Type TContig; typedef TContigSeq TGenome; typedef StringSet<TGenome> TGenomeSet; typedef String<String<TContigPos > > TPositions; typedef typename Iterator<String<TContigPos > >::Type TPosIterator; typedef ::std::map<CharString,unsigned> TGenomeMap; typedef typename TGenomeMap::iterator TMapIter; typedef String<unsigned> TReadCounts; typedef String<Pair<int,int> > TReadClips; typedef StringSet<String<Pair<char,int> > > TReadCigars; TGenomeSet genomes; StringSet<CharString> genomeFileNameList; // filenamen StringSet<CharString> genomeNames; // todo: raus TGenomeMap gIdStringToIdNumMap; // name to id TPositions positions; // list of positions to inspect // dump configuration in verbose mode if (options._debugLevel >= 1) { ::std::cerr << "___SETTINGS____________" << ::std::endl; ::std::cerr << "Genome file: \t" << genomeFileName << ::std::endl; ::std::cerr << "Read files: \t" << readFNames[0] << ::std::endl; for(unsigned i = 1; i < length(readFNames); ++i) ::std::cerr << " \t" << readFNames[i] << ::std::endl; /* if(options.inputFormat == 1) { ::std::cerr << "Quality files: \t" << qualityFNames[0] << ::std::endl; for(unsigned i = 1; i < length(qualityFNames); ++i) ::std::cerr << " \t" << qualityFNames[i] << ::std::endl; }*/::std::cerr << "MaxPile: \t" << options.maxPile << ::std::endl; if(options.laneSpecificMaxPile)::std::cerr << "Lane specific: \tYES" << ::std::endl; else ::std::cerr << "Lane specific: \tNO" << ::std::endl; ::std::cerr << "MinCoverage: \t" << options.minCoverage << ::std::endl; if(options.method == 0) { ::std::cerr << "MinMutThreshold: \t" << options.minMutT << ::std::endl; ::std::cerr << "MinPercentageThreshold: \t" << options.percentageT << ::std::endl; ::std::cerr << "MinQualityThreshold: \t" << options.avgQualT << ::std::endl; } else { ::std::cerr << "MinMappingQuality: \t" << options.minMapQual << ::std::endl; } if(options.doIndelCalling && *options.outputIndel != 0) { ::std::cerr << "IndelCountThreshold: \t" << options.indelCountThreshold << ::std::endl; ::std::cerr << "IndelPercentageThreshold: \t" << options.indelPercentageT << ::std::endl; ::std::cerr << "IndelWindow: \t" << options.indelWindow << ::std::endl; } ::std::cerr << ::std::endl; } ////////////////////////////////////////////////////////////////////////////// // Step 1: Determine genome file type and load genomes SEQAN_PROTIMESTART(load_time); int result = getGenomeFileNameList(genomeFileName, genomeFileNameList, options); if(result == CALLSNPS_GENOME_FAILED || !loadGenomes(genomes, genomeFileNameList,gIdStringToIdNumMap,genomeNames)) { ::std::cerr << "Failed to open genome file " << genomeFileName << ::std::endl; return result; } ////////////////////////////////////////////////////////////////////////////// // Step 2: Load fragmentStore.readSeqStore and fragmentStore.alignedReadStore // open read files and store open file pointers String<int> highestChrId; resize(highestChrId,length(readFNames),0); vector< ::std::fstream* > readFileStreams; readFileStreams.resize(length(readFNames)); for(unsigned i = 0; options.inputFormat != 2 && i < length(readFNames); ++i) { readFileStreams[i] = new fstream(toCString(readFNames[i]), ios_base::in | ios::binary); if(!(*(readFileStreams[i])).is_open()) { ::std::cerr << "Failed to open read file " << readFNames[i] << ::std::endl; return CALLSNPS_GFF_FAILED; } } String<RecordReader<std::fstream, SinglePass< > >* > recordReaders; String<Stream<Bgzf>* > bgzfStreams; if(options.inputFormat == 2) { resize(bgzfStreams,length(readFNames)); for(unsigned i = 0; i < length(readFNames); ++i) { bgzfStreams[i] = new Stream<Bgzf>(); std::cout <<"Opening bam file" << std::endl; if (!open(*bgzfStreams[i], toCString(readFNames[i]), "r")) { std::cerr << "[ERROR] Could not open BAM file" << readFNames[i] << std::endl; return 1; } } } typedef StringSet<CharString> TNameStore; typedef NameStoreCache<TNameStore> TNameStoreCache; TNameStoreCache refNameStoreCache(genomeNames); String<BamIOContext<TNameStore> > contexts; String<BamAlignmentRecord> records; if(options.inputFormat > 0) { if(options.inputFormat == 1) resize(recordReaders, length(readFNames)); resize(records, length(readFNames)); //resize(contexts, length(readFNames)); for (unsigned i = 0; i < length(readFNames); ++i) { clear(records[i].qName); if(options.inputFormat == 1) recordReaders[i] = new RecordReader<std::fstream,SinglePass< > >(*readFileStreams[i]); //appendValue(contexts,BamIOContext<TNameStore>(refNameStore, refNameStoreCache)); appendValue(contexts,BamIOContext<TNameStore>(genomeNames, refNameStoreCache)); } } ///////////////////////////////////////////////////////////////////// // open out file streams and store open file pointers ::std::ofstream snpFileStream; if (*options.outputSNP != 0) { // prepare lookup tables for maq statistics if (options.method == 1 ) { computeCnks(options.cnks,options.fks,options); #ifdef CORRECTED_HET if(options.correctedHetTable) options.priorHetQ = computeHetTable(options.hetTable,options); // corrected het table computed with normal distribution else #endif options.priorHetQ = computeHetTable(options.hetTable,options,MaqMethod()); // original Maq method //printHetTable(options.hetTable); //printHetTable(options.hetTable2); } snpFileStream.open(options.outputSNP,::std::ios_base::out); if(!snpFileStream.is_open()) return CALLSNPS_OUT_FAILED; snpFileStream << "#" << (options.programCall).str() << "\n"; if(options.outputFormat < 2) { if(options.orientationAware) snpFileStream << "#chr\tpos\tref\t[A+]\t[C+]\t[G+]\t[T+]\t[A-]\t[C-]\t[G-]\t[T-]\tcov\tcall"; else snpFileStream << "#chr\tpos\tref\tA\tC\tG\tT\tcov\tcall"; //if(options.method==1) snpFileStream << "\tquality\tsnpQ\n"; //else // file <<"\n"; } } ::std::ofstream indelFileStream; if (*options.outputIndel != 0) { indelFileStream.open(options.outputIndel,::std::ios_base::out); if(!indelFileStream.is_open()) return CALLSNPS_OUT_FAILED; } // ::std::ofstream cnvFileStream; // if (*options.outputCNV != 0) // { // cnvFileStream.open(options.outputCNV,::std::ios_base::out); // if(!cnvFileStream.is_open()) // return CALLSNPS_OUT_FAILED; // } ::std::ofstream posFileStream; if(*options.inputPositionFile != 0) { resize(positions,length(genomeNames)); result = loadPositions(positions,gIdStringToIdNumMap,options.inputPositionFile,options); if(result != 0) { ::std::cerr << "Failed to read position file " << options.inputPositionFile << ::std::endl; return result; } posFileStream.open(options.outputPosition,::std::ios_base::out); if(!posFileStream.is_open()) return CALLSNPS_OUT_FAILED; if(options.orientationAware) posFileStream << "#chr\tpos\t[A+]\t[C+]\t[G+]\t[T+]\t[gap+]\t[A-]\t[C-]\t[G-]\t[T-]\t[gap-]\n"; else posFileStream << "#chr\tpos\tA\tC\tG\tT\tgap\n"; } ///////////////////////////////////////////////////////////////////////////// // helper variables Pair<int,int> zeroPair(0,0); int sumreads = 0; int sumwindows = 0; bool positionStatsOnly = (*options.outputSNP == 0 && *options.outputPosition != 0); TPosIterator inspectPosIt, inspectPosItEnd; bool firstCall = true; ///////////////////////////////////////////////////////////////////////////// // Start scanning for SNPs/indels // for each chromosome for(unsigned i=0; i < length(genomes); ++i) { //std::cout << genomeNames[i] << "\n"; if(!empty(positions)) { inspectPosIt = begin(positions[i],Standard()); inspectPosItEnd = end(positions[i],Standard()); if(inspectPosIt == inspectPosItEnd ) if(positionStatsOnly) continue; } // parse matches batch by batch TContigPos currentWindowBegin = 0; if(options._debugLevel > 0) ::std::cout << "Scanning genome #" << i << " ..." << ::std::endl; // containers for those matches that overlap two windows TAlignedReadStore tmpMatches; TAlignQualityStore tmpQualities; TReadStore tmpRs; TReadSeqStore tmpReads; TReadCounts tmpReadCounts; TReadClips tmpReadClips; TReadCigars tmpReadCigars; options.minCoord = MaxValue<unsigned>::VALUE; options.maxCoord = 0; // snp calling is done for all positions between windowBegin and windowEnd while(currentWindowBegin < (TContigPos)length(genomes[i])) { TContigPos currentWindowEnd = currentWindowBegin + options.windowSize; if(currentWindowEnd > (TContigPos)length(genomes[i])) currentWindowEnd = (TContigPos)length(genomes[i]); if(positionStatsOnly && !(currentWindowBegin <= *inspectPosIt && *inspectPosIt< currentWindowEnd)) { SEQAN_ASSERT_LEQ(currentWindowBegin,*inspectPosIt); clear(tmpReads); clear(tmpRs); clear(tmpMatches); clear(tmpQualities); clear(tmpReadClips); clear(tmpReadCounts); clear(tmpReadCigars); currentWindowBegin = currentWindowEnd; ++sumwindows; continue; } if(options._debugLevel > 0) ::std::cout << "Sequence number " << i << " window " << currentWindowBegin << ".." << currentWindowEnd << "\n"; TFragmentStore fragmentStore; TReadCounts readCounts; TReadClips readClips; TReadCigars readCigars; // currently only stored for split-mapped reads // add the matches that were overlapping with this and the last window (copied in order to avoid 2 x makeGlobal) if(!empty(tmpMatches)) { sumreads -= length(tmpReads); // count these reads only once resize(fragmentStore.alignQualityStore,length(tmpMatches)); resize(fragmentStore.alignedReadStore,length(tmpMatches)); resize(fragmentStore.readSeqStore,length(tmpMatches)); resize(fragmentStore.readStore,length(tmpMatches)); if(!empty(tmpReadClips))resize(readClips,length(tmpMatches)); if(!empty(tmpReadCounts)) resize(readCounts,length(tmpMatches)); if(!empty(tmpReadCigars))resize(readCigars,length(tmpMatches)); arrayMoveForward(begin(tmpQualities,Standard()), end(tmpQualities,Standard()), begin(fragmentStore.alignQualityStore,Standard())); arrayMoveForward(begin(tmpMatches,Standard()), end(tmpMatches,Standard()), begin(fragmentStore.alignedReadStore,Standard())); arrayMoveForward(begin(tmpReads,Standard()), end(tmpReads,Standard()), begin(fragmentStore.readSeqStore,Standard())); arrayMoveForward(begin(tmpRs,Standard()), end(tmpRs,Standard()), begin(fragmentStore.readStore,Standard())); if(!empty(tmpReadCounts)) arrayMoveForward(begin(tmpReadCounts,Standard()), end(tmpReadCounts,Standard()), begin(readCounts,Standard())); if(!empty(tmpReadCigars)) arrayMoveForward(begin(tmpReadCigars,Standard()), end(tmpReadCigars,Standard()), begin(readCigars,Standard())); if(!empty(tmpReadClips)) arrayMoveForward(begin(tmpReadClips,Standard()), end(tmpReadClips,Standard()), begin(readClips,Standard())); #ifdef SNPSTORE_DEBUG CharString strstr = "afterCopyInFrag"; _dumpMatches(fragmentStore,strstr); #endif } // parse matches for current window if(options._debugLevel > 0) ::std::cout << "Parsing reads up to position " << currentWindowEnd << "...\n"; for(unsigned j = 0; j < length(readFNames); ++j) { unsigned sizeBefore = length(fragmentStore.alignedReadStore); // currently only gff supported if(options.inputFormat == 0) // GFF result = readMatchesFromGFF_Batch(readFileStreams[j], fragmentStore, readCounts, readClips, readCigars, genomes[i], gIdStringToIdNumMap, i, currentWindowBegin, currentWindowEnd, highestChrId[j], options); if(options.inputFormat == 1) // SAM result = readMatchesFromSamBam_Batch(*recordReaders[j], contexts[j], records[j], fragmentStore, readCounts, readClips, readCigars, genomes[i], gIdStringToIdNumMap, i, currentWindowBegin, currentWindowEnd, highestChrId[j], options, Sam(),firstCall); if(options.inputFormat == 2) // BAM result = readMatchesFromSamBam_Batch(*bgzfStreams[j], contexts[j], records[j], fragmentStore, readCounts, readClips, // result = readMatchesFromSamBam_Batch(*recordReaders[j], contexts[j], records[j], fragmentStore, readCounts, readClips, readCigars, genomes[i], gIdStringToIdNumMap, i, currentWindowBegin, currentWindowEnd, highestChrId[j], options, Bam(),firstCall); firstCall = false; if(result == CALLSNPS_GFF_FAILED) { ::std::cerr << "Failed to open read file " << readFNames[j] << ::std::endl; ::std::cerr << "or reads are not sorted correctly. " << ::std::endl; return result; } if(result > 0) return result; if(options._debugLevel > 0) ::std::cout << "parsed reads of file " << j << "\n"; // store average quality of each read addReadQualityToMatches(fragmentStore,sizeBefore,(unsigned)length(fragmentStore.alignedReadStore),options); // do pile up correction if lane-based if(options.maxPile != 0 && options.laneSpecificMaxPile) applyPileupCorrection(fragmentStore,sizeBefore,(unsigned)length(fragmentStore.alignedReadStore),options); } if (options._debugLevel > 1) // number of reads currently in memory ::std::cerr << lengthSum(fragmentStore.readSeqStore) << " bps of " << length(fragmentStore.readSeqStore) << " reads in memory." << ::std::endl; sumreads += length(fragmentStore.readSeqStore); // total count of reads // do merged pile up correction if(options.maxPile != 0 && !options.laneSpecificMaxPile) applyPileupCorrection(fragmentStore,(unsigned)0,(unsigned)length(fragmentStore.alignedReadStore),options); // these were set while parsing matches, first and last position of parsed matches // TContigPos startCoord = options.minCoord;// can be < currentWindowBegin // TContigPos endCoord = options.maxCoord; // can be > currentWindoEnd // check TContigPos startCoord = _max((int)options.minCoord-options.realignAddBorder,0);// can be < currentWindowBegin TContigPos endCoord = _min(options.maxCoord+options.realignAddBorder,length(genomes[i])); // can be > currentWindoEnd if(!empty(fragmentStore.alignedReadStore)) { //initial values of min and max coords for next round are set here if(currentWindowEnd != (TContigPos)length(genomes[i])) { clear(tmpMatches); clear(tmpQualities); clear(tmpRs); clear(tmpReads); clear(tmpReadCounts); clear(tmpReadClips); clear(tmpReadCigars); copyNextWindowMatchesAndReads(fragmentStore,readCounts,readCigars,readClips,tmpReadCounts,tmpReads,tmpRs,tmpMatches,tmpQualities,tmpReadClips,tmpReadCigars,i,currentWindowEnd,options); #ifdef SNPSTORE_DEBUG CharString strstr = "afterCopyInTmp"; _dumpMatches(tmpReads,tmpMatches,tmpQualities,strstr); #endif } // ::std::cout << "Min = " << options.minCoord << " Max = " << options.maxCoord << std::endl; // ::std::cout << "Min = " << startCoord << " Max = " << endCoord << std::endl; // coordinates are relative to current chromosomal window (segment) transformCoordinates(fragmentStore,startCoord,options); // set the current chromosomal segment as contig sequence TContig conti; conti.seq = infix(genomes[i],startCoord,endCoord); appendValue(fragmentStore.contigStore, conti, Generous() ); appendValue(fragmentStore.contigNameStore, genomeNames[i], Generous() );// internal id is always 0 // clip Reads if clipping is switched on and there were clip tags in the gff file if((!options.dontClip && options.clipTagsInFile) || options.softClipTagsInFile) { options.useBaseQuality = false; // activate "average read quality"-mode for snp calling, low quality bases should be clipped anyway clipReads(fragmentStore,readClips,(unsigned)0,(unsigned)length(fragmentStore.alignedReadStore),options); } // check for indels if (*options.outputIndel != 0) { if(options._debugLevel > 1) ::std::cout << "Check for indels..." << std::endl; if(!options.realign) dumpShortIndelPolymorphismsBatch(fragmentStore, readCigars, fragmentStore.contigStore[0].seq, genomeNames[i], startCoord, currentWindowBegin, currentWindowEnd, indelFileStream, options); } // // check for CNVs // if (*options.outputCNV != 0) // dumpCopyNumberPolymorphismsBatch(fragmentStore, genomeNames[i], startCoord, currentWindowBegin, currentWindowEnd, cnvFileStream, options); #ifdef SNPSTORE_DEBUG CharString strstr = "test"; // _dumpMatches(fragmentStore, strstr ); #endif if (*options.outputSNP != 0) { if(options._debugLevel > 1) ::std::cout << "Check for SNPs..." << std::endl; if(options.realign) dumpVariantsRealignBatchWrap(fragmentStore, readCigars, readCounts, genomeNames[i], startCoord, currentWindowBegin, currentWindowEnd, snpFileStream,indelFileStream,options); else dumpSNPsBatch(fragmentStore, readCigars, readCounts, genomeNames[i], startCoord, currentWindowBegin, currentWindowEnd, snpFileStream,options); } if(positionStatsOnly) { if(options._debugLevel > 1) ::std::cout << "Dumping info for query positions..." << std::endl; if(options.realign) dumpPositionsRealignBatchWrap(fragmentStore, inspectPosIt, inspectPosItEnd, readCigars, readCounts, genomeNames[i], startCoord, currentWindowBegin, currentWindowEnd, posFileStream, options); else dumpPosBatch(fragmentStore, inspectPosIt, inspectPosItEnd, readCigars, readCounts, genomeNames[i], startCoord, currentWindowBegin, currentWindowEnd, posFileStream, options); } } // else // { if(positionStatsOnly && !empty(positions)) { while(inspectPosIt != inspectPosItEnd && *inspectPosIt < currentWindowEnd) { if(options.orientationAware) posFileStream << genomeNames[i] << '\t' << *inspectPosIt + options.positionFormat << "\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0" << std::endl; else posFileStream << genomeNames[i] << '\t' << *inspectPosIt + options.positionFormat << "\t0\t0\t0\t0\t0\t0" << std::endl; ++inspectPosIt; } } // } currentWindowBegin = currentWindowEnd; ++sumwindows; } } if (*options.outputSNP != 0) snpFileStream.close(); if (*options.outputIndel != 0) indelFileStream.close(); if (*options.outputPosition != 0) posFileStream.close(); // if (*options.outputCNV != 0) // cnvFileStream.close(); return 0; } // log file to keep track of happenings template <typename TSpec> int writeLogFile( int argc, const char *argv[], const char *genomeFileName, String<CharString> & readFNames, String<CharString> & , SNPCallingOptions<TSpec> &options) { ::std::ofstream logfile; logfile.open(options.outputLog, ::std::ios_base::out | ::std::ios_base::trunc); if (!logfile.is_open()) { ::std::cerr << "Failed to open log file" << ::std::endl; return 1; } logfile << "#call" << std::endl; for (int i = 0; i < argc; ++i) logfile << argv[i] << " "; logfile << std::endl; logfile << "#files" << ::std::endl; logfile << "Genome=\"" << genomeFileName << "\""<<::std::endl; logfile << "Reads=\"" << readFNames[0]; for(unsigned i = 1; i < length(readFNames); ++i) logfile << " " << readFNames[i] << ::std::endl; logfile << "\"" << std::endl; if(*options.output != 0) { logfile << "OutputSnp=\"" << CharString(options.output) << "\"" << ::std::endl; } if(*options.outputIndel != 0) { logfile << "OutputIndel=\"" << CharString(options.outputIndel) << "\""<< ::std::endl; } logfile << "#settings" << ::std::endl; logfile << "MaxPile=" << options.maxPile << ::std::endl; logfile << "MinCov=" << options.minCoverage << ::std::endl; logfile << "Method=" << options.method << ::std::endl; if(options.method == 0) { logfile << "MinMutT=" << options.minMutT << ::std::endl; logfile << "MinPercT=" << options.percentageT << ::std::endl; logfile << "MinQualT=" << options.avgQualT << ::std::endl; } else { logfile << "MinMapQual=" << options.minMapQual << ::std::endl; } if(*options.outputIndel != 0) { logfile << "MinIndel=" << options.indelCountThreshold << ::std::endl; logfile << "MinPercIndelT=" << options.indelPercentageT << ::std::endl; } logfile.close(); return 0; } template <typename TOptions> void printHelp(int, const char *[], TOptions &options, bool longHelp = false) { cerr << "Usage: snpStore [OPTION]... <GENOME FILE> <MAPPED READ FILE>" << endl; if (longHelp) { cerr << endl << "Options:" << endl; cerr << " -o, --output FILE \t" << "change output filename (default <READ FILE>.snp)" << endl; cerr << " -if, --input-format NUM \t" << "input format:" << endl; cerr << " \t" << "0 = GFF sorted according to genome pos (default)" << endl; cerr << " \t" << "1 = SAM sorted according to genome pos" << endl; cerr << " -of, --output-format NUM \t" << "output format:" << endl; cerr << " \t" << "0 = output all candidate snps (default)" << endl; cerr << " \t" << "1 = output succesful candidate snps only" << endl; cerr << " -dc, --dont-clip \t" << "ignore clip tags in gff (off)" << endl; cerr << " -mu, --multi \t" << "keep non-unique fragmentStore.alignedReadStore (off)" << endl; cerr << " -hq, --hide-qualities \t" << "only show coverage (no qualities) in SNP output file (off)" << endl; cerr << " -sqo,--solexa-qual-offset \t" << "base qualities are encoded as Ascii value - 64 (instead of Ascii - 33)" << endl; cerr << " -id, --indel-file FILE \t" << "output file for called indels in gff format (off)" << endl; cerr << " -m, --method NUM \t" << "set method used for SNP calling" << endl; cerr << " \t" << "0 = threshold method" << endl; cerr << " \t" << "1 = maq (default)" << endl; // cerr << " \t" << "(default = "<<options.method << ")" << endl; cerr << " -mp, --max-pile NUM \t" << "maximal number of matches allowed to pile up at the same genome position ("<<options.maxPile<<")" << endl; cerr << " -mmp,--merged-max-pile \t" << "do pile up correction on merged lanes (off)" << endl; cerr << " -mc, --min-coverage NUM \t" << "minimal required number of reads covering a candidate position ("<< options.minCoverage<<")" << endl; cerr << " -fc, --force-call NUM \t" << "always call base if count is >= fc, ignore other parameters (off)" << endl; cerr << " -oa, --orientation-aware \t" << "distinguish between forward and reverse reads (off)" << endl; cerr << " -fl, --force-length NUM \t" << "read length to be used (ignores suffix of read) (off)" << endl; cerr << endl; cerr << "SNP calling options: " << endl; cerr << " Threshold method related: " << endl; cerr << " -mm, --min-mutations NUM \t" << "minimal number of observed mutations for mutation to be called ("<<options.minMutT<<")" << endl; cerr << " -pt, --perc-threshold NUM \t" << "minimal percentage of mutational base for mutation to be called (" << options.percentageT << ")" << endl; cerr << " -mq, --min-quality NUM \t" << "minimal average quality of mutational base for mutation to be called ("<<options.avgQualT <<")" << endl; cerr << " Maq method related: " << endl; cerr << " -th, --theta NUM \t" << "dependency coefficient ("<< options.theta <<")" << endl; cerr << " -hr, --hetero-rate NUM \t" << "heterozygote rate ("<< options.hetRate <<")" << endl; cerr << " -mmq,--min-map-quality NUM \t" << "minimum base call (mapping) quality for a match to be considered ("<< options.minMapQual <<")" << endl; cerr << " -ch, --corrected-het \t" << "use amplification bias corrected distribution for heterozygotes (off)" << endl; cerr << " -maf,--mean-alleleFreq NUM \t" << "mean ref allele frequency in heterozygotes (" << options.meanAlleleFrequency << ")" << endl; cerr << " -ac, --amp-cycles NUM \t" << "number of amplification cycles (" << options.amplificationCycles << ")" << endl; cerr << " -ae, --amp-efficiency NUM \t" << "polymerase efficiency, probability of amplification (" << options.amplificationEfficiency << ")" << endl; cerr << " -in, --initialN NUM \t" << "initial allele population size (" << options.initialN << ")" << endl; cerr << " -pht,--print-hetTable \t" << "print het table (off)" << endl; // cerr << " -cq, --corrected-quality NUM \t" << "do simple quality recalibration with x=NUM (" << options.newQualityCalibrationFactor << ")" << endl; cerr << " -mec,--min-explained-col \t" << "minimum fraction of alignment column reads explained by genotype call (" << options.minExplainedColumn << ")" << endl; cerr << "Indel calling options: " << endl; cerr << " -it, --indel-threshold NUM \t" << "minimal number of indel-supporting reads required for indel calling (" << options.indelCountThreshold<<")"<< endl; cerr << " -ipt,--indel-perc-threshold NUM \t" << "minimal ratio of indel-supporting/covering reads for indel to be called (" << options.indelPercentageT<<")" << endl; cerr << " -iqt,--indel-quality-thresh NUM \t" << "minimal average quality of inserted base/deletion-neighboring bases for indel to be called (" << options.indelQualityThreshold<<")" << endl; cerr << " -bsi,--both-strands-indel \t" << "both strands need to be observed for indel to be called (off)" << endl; // cerr << " -iw, --indel-window \t" << "overlap window used for indel calling (" << options.indelWindow<<")"<< endl; cerr << endl<< "Other options: " << endl; cerr << " -lf, --log-file FILE \t" << "write log file to FILE" << endl; cerr << " -v, --verbose \t" << "verbose mode" << endl; cerr << " -vv, --very-verbose \t" << "very verbose mode" << endl; cerr << " -h, --help \t" << "print this help" << endl << endl; } else { cerr << "Try 'snpStore --help' for more information." << endl <<endl; } } int main(int argc, const char *argv[]) { ////////////////////////////////////////////////////////////////////////////// // Parse command line SNPCallingOptions<> options; unsigned fnameCount = 0; const char *genomeFName = ""; String<CharString> readFNames; String<CharString> qualityFNames; for(int arg = 0; arg < argc; ++arg) { options.programCall << argv[arg] << " "; } /* std::cout << "lgamma(1) = " << lgamma(1) << std::endl; std::cout << "lgamma(2) = " << lgamma(2) << std::endl; std::cout << "lgamma(3) = " << lgamma(3) << std::endl; std::cout << "lgamma(4) = " << lgamma(4) << std::endl; std::cout << "lgamma(25) = " << lgamma(25) << std::endl; std::cout << "lgamma(105) = " << lgamma(105) << std::endl; std::cout << "lgamma(255) = " << lgamma(255) << std::endl;*/ for(int arg = 1; arg < argc; ++arg) { if (argv[arg][0] == '-') { // parse options if (strcmp(argv[arg], "-m") == 0 || strcmp(argv[arg], "--method") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.method; if (!istr.fail()) { if (options.method > 1) cerr << "Invalid method option." << endl << endl; else continue; } } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-mq") == 0 || strcmp(argv[arg], "--min-quality") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.avgQualT; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-mm") == 0 || strcmp(argv[arg], "--min-mutations") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.minMutT; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-fl") == 0 || strcmp(argv[arg], "--force-length") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.forceReadLength; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-fc") == 0 || strcmp(argv[arg], "--force-call") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.forceCallCount; if (!istr.fail()) { if(options.forceCallCount < 1) cerr << "--force-call expects a positive integer." << endl; else continue; } } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-mpr") == 0 || strcmp(argv[arg], "--max-polymer-run") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.maxPolymerRun; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-bsi") == 0 || strcmp(argv[arg], "--both-strands-indel") == 0) { options.bothIndelStrands = true; continue; } if (strcmp(argv[arg], "-iqt") == 0 || strcmp(argv[arg], "--indel-quality-thresh") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.indelQualityThreshold; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-mec") == 0 || strcmp(argv[arg], "--min-explained-column") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.minExplainedColumn; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-ipt") == 0 || strcmp(argv[arg], "--indel-perc-threshold") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.indelPercentageT; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-pt") == 0 || strcmp(argv[arg], "--perc-threshold") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.percentageT; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-mp") == 0 || strcmp(argv[arg], "--max-pile") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.maxPile; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-dp") == 0 || strcmp(argv[arg], "--diff-pos") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.minDifferentReadPos; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-eb") == 0 || strcmp(argv[arg], "--exclude-border") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.excludeBorderPos; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-ebi") == 0 || strcmp(argv[arg], "--exclude-border-indel") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.indelDepthMinOverlap; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-mc") == 0 || strcmp(argv[arg], "--min-coverage") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.minCoverage; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-dc") == 0 || strcmp(argv[arg], "--dont-clip") == 0) { options.dontClip = true; continue; } if (strcmp(argv[arg], "-su") == 0 || strcmp(argv[arg], "--suboptimal") == 0) { options.keepSuboptimalReads = true; continue; } if (strcmp(argv[arg], "-ch") == 0 || strcmp(argv[arg], "--corrected-het") == 0) { options.correctedHetTable = true; continue; } if (strcmp(argv[arg], "-mu") == 0 || strcmp(argv[arg], "--multi") == 0) { options.keepMultiReads = true; continue; } if (strcmp(argv[arg], "-re") == 0 || strcmp(argv[arg], "--realign") == 0) { options.realign = true; continue; } if (strcmp(argv[arg], "-hq") == 0 || strcmp(argv[arg], "--hide-qualities") == 0) { options.showQualityStrings = false; continue; } if (strcmp(argv[arg], "-mmp") == 0 || strcmp(argv[arg], "--merged-max-pile") == 0) { options.laneSpecificMaxPile = false; continue; } if (strcmp(argv[arg], "-oa") == 0 || strcmp(argv[arg], "--orientation-aware") == 0) { options.orientationAware = true; continue; } if (strcmp(argv[arg], "-pht") == 0 || strcmp(argv[arg], "--print-hetTable") == 0) { options.printHetTable = true; continue; } if (strcmp(argv[arg], "-ae") == 0 || strcmp(argv[arg], "--amp-efficiency") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.amplificationEfficiency; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-cq") == 0 || strcmp(argv[arg], "--corrected-quality") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.newQualityCalibrationFactor; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-maf") == 0 || strcmp(argv[arg], "--mean-alleleFreq") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.meanAlleleFrequency; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-ac") == 0 || strcmp(argv[arg], "--amp-cycles") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.amplificationCycles; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-in") == 0 || strcmp(argv[arg], "--initial-N") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.initialN; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-iw") == 0 || strcmp(argv[arg], "--indel-window") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.indelWindow; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-it") == 0 || strcmp(argv[arg], "--indel-threshold") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.indelCountThreshold; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-mmq") == 0 || strcmp(argv[arg], "--min-map-quality") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.minMapQual; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-th") == 0 || strcmp(argv[arg], "--theta") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.theta; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-pws") == 0 || strcmp(argv[arg], "--parse-window-size") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.windowSize; if (!istr.fail() && options.windowSize > 0) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-sqo") == 0 || strcmp(argv[arg], "--solexa-qual-offset") == 0) { options.asciiQualOffset = 64; continue; } if (strcmp(argv[arg], "-reb") == 0 || strcmp(argv[arg], "--realign-border") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.realignAddBorder; if (!istr.fail() && options.realignAddBorder >= 0 && options.realignAddBorder <= 100) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-cws") == 0 || strcmp(argv[arg], "--cnv-window-size") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.cnvWindowSize; if (!istr.fail() && options.cnvWindowSize > 0) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-hr") == 0 || strcmp(argv[arg], "--hetero-rate") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.hetRate; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-if") == 0 || strcmp(argv[arg], "--input-format") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.inputFormat; if (!istr.fail()) { if(options.inputFormat > 2 ) cerr << "--input-format expects 0 or 1." << endl; else continue; } } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-of") == 0 || strcmp(argv[arg], "--output-format") == 0) { if (arg + 1 < argc) { ++arg; istringstream istr(argv[arg]); istr >> options.outputFormat; if (!istr.fail()) continue; } printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-lf") == 0 || strcmp(argv[arg], "--log-file") == 0) { if (arg + 1 == argc) { printHelp(argc, argv, options, true); return 0; } ++arg; options.outputLog = argv[arg]; continue; } if (strcmp(argv[arg], "-o") == 0 || strcmp(argv[arg], "--output") == 0) { if (arg + 1 == argc) { printHelp(argc, argv, options, true); return 0; } ++arg; options.outputSNP = argv[arg]; continue; } if (strcmp(argv[arg], "-id") == 0 || strcmp(argv[arg], "--indel-file") == 0) { if (arg + 1 == argc) { printHelp(argc, argv, options, true); return 0; } ++arg; options.outputIndel = argv[arg]; continue; } if (strcmp(argv[arg], "-cnv") == 0 || strcmp(argv[arg], "--output-cnv") == 0) { if (arg + 1 == argc) { printHelp(argc, argv, options, true); return 0; } ++arg; options.outputCNV = argv[arg]; continue; } if (strcmp(argv[arg], "-op") == 0 || strcmp(argv[arg], "--output-positions") == 0) { if (arg + 1 == argc) { printHelp(argc, argv, options, true); return 0; } ++arg; options.outputPosition = argv[arg]; continue; } if (strcmp(argv[arg], "-ip") == 0 || strcmp(argv[arg], "--input-positions") == 0) { if (arg + 1 == argc) { printHelp(argc, argv, options, true); return 0; } ++arg; options.inputPositionFile = argv[arg]; continue; } if (strcmp(argv[arg], "-h") == 0 || strcmp(argv[arg], "--help") == 0) { // print help printHelp(argc, argv, options, true); return 0; } if (strcmp(argv[arg], "-v") == 0 || strcmp(argv[arg], "--verbose") == 0) { options._debugLevel = max(options._debugLevel, 1); continue; } if (strcmp(argv[arg], "-vv") == 0 || strcmp(argv[arg], "--very-verbose") == 0) { options._debugLevel = max(options._debugLevel, 2); continue; } cerr << "Unknown option: " << argv[arg] << endl << endl; printHelp(argc, argv, options); return 0; } else { // parse file name if (fnameCount == 0) genomeFName = argv[arg]; if (fnameCount == 1) { if(argv[arg][0]=='[') { String<char> tempStr = argv[arg]; appendValue(readFNames,suffix(tempStr,1),Generous()); ++arg; while(arg < argc && argv[arg][0] != '-') { tempStr = argv[arg]; appendValue(readFNames,tempStr,Generous()); ++arg; } if(readFNames[length(readFNames)-1][length(readFNames[length(readFNames)-1])-1] != ']' ) cerr << "Something wrong with read file list?" << endl; resize(readFNames[length(readFNames)-1],length(readFNames[length(readFNames)-1])-1); --arg; } else { //split by whitesapce and append each read file ::std::string tempStr(argv[arg]); size_t firstPos = 0; size_t lastPos = tempStr.find(' '); ::std::string tempFile = tempStr.substr(firstPos,lastPos); appendValue(readFNames,String<char>(tempFile),Generous()); while (lastPos != 0 && lastPos != tempStr.npos) { while(tempStr[lastPos]==' ') ++lastPos; firstPos = lastPos; lastPos = tempStr.find(' ',firstPos); if (lastPos != tempStr.npos) tempFile = tempStr.substr(firstPos,lastPos-firstPos); else tempFile = tempStr.substr(firstPos,length(tempStr)); appendValue(readFNames,String<char>(tempFile),Generous()); } } } if (fnameCount == 2) { cerr << "More than 2 input files specified." <<endl; cerr << "If more than 2 mapped read files are to be parsed, use quotation marks directly before first file name and directly after last file name (e.g. \"lane1.gff lane2.gff\")." << endl << endl; printHelp(argc, argv, options); return 0; } ++fnameCount; } } // some option checking if (fnameCount != 2) { if (argc > 1 && !options.printVersion) cerr << "Exactly 2 input files need to be specified." << endl << endl; printHelp(argc, argv, options); return 0; } //if(options.inputFormat == 1 && (!options.qualityFile || (length(qualityFNames)!=length(readFNames)))) //{ // cerr << "If mapped read file is in Eland format, a .qual or .fastq file containing read qualities needs to be specified." << endl << endl; // return 0; //} if(*options.inputPositionFile == 0 && *options.outputPosition != 0) { cerr << "Position analysis output specified, but no position file given." << endl << endl; return 0; } if((options.realign && options.windowSize > 50000) || options.windowSize > 1000000) options.windowSize = 10000; if (*options.outputLog != 0) writeLogFile(argc, argv, genomeFName, readFNames, qualityFNames, options); // TODO: is forceReadLength still needed? if(options.inputFormat == 0 ) options.forceReadLength = 0; // for now this is safer if(options.runID == "") { ::std::string tempStr = toCString(readFNames[0]); size_t lastPos = tempStr.find_last_of('/') + 1; if (lastPos == tempStr.npos) lastPos = tempStr.find_last_of('\\') + 1; if (lastPos == tempStr.npos) lastPos = 0; options.runID = tempStr.substr(lastPos); } ////////////////////////////////////////////////////////////////////////////// // check for variants int result = detectSNPs(genomeFName, readFNames, qualityFNames, options); if (result > 0) { printHelp(argc, argv, options); return 0; } return result; }
[ "mail@bkahlert.com" ]
mail@bkahlert.com
509b6016ec39d9fc9d84b15a1a6a29e08aef2a60
2814b4ed8ebe8bbeb2e4210ed083326dd6ce7252
/Medium/429. N-ary Tree Level Order Traversal/levelOrder.cpp
31f11263af7a6001142e5b94f17ab40e0cae8762
[]
no_license
teddy8997/LeetCode
31970b5efe1945204bf2f8fc4e5d6924f05636db
399edc5300fb1cb2cb0fe51b42ce3a913c830d25
refs/heads/master
2023-04-10T21:14:28.684276
2021-04-19T06:12:34
2021-04-19T06:12:34
303,752,589
0
0
null
null
null
null
UTF-8
C++
false
false
1,485
cpp
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ /* 法一: BFS */ class Solution { public: vector<vector<int>> levelOrder(Node* root) { if(!root){ return {}; } vector<vector<int>> ans; queue<Node*> q; q.push(root); int depth = 0; while(!q.empty()){ int size = q.size(); ans.push_back({}); while(size--){ Node *n = q.front(); q.pop(); ans[depth].push_back(n->val); for(auto child : n->children){ q.push(child); } } depth++; } return ans; } }; /* 法二: DFS Time complexity: O(n) Space complexity: O(n) */ class Solution { public: vector<vector<int>> levelOrder(Node* root) { vector<vector<int>> ans; preorder(root, 0, ans); return ans; } private: void preorder(Node* root, int d, vector<vector<int>> &ans){ if(!root){ return; } while(ans.size() <= d){ ans.push_back({}); } ans[d].push_back(root->val); for(auto child : root->children){ preorder(child, d+1, ans); } } };
[ "70366832+teddy@users.noreply.github.com" ]
70366832+teddy@users.noreply.github.com
e468b8adb9f371e8cf8f16aea308cae43e299ff2
9c451121eaa5e0131110ad0b969d75d9e6630adb
/Codeforces/Codeforces Round 725/1538G - Gift Set.cpp
cfd8327d99fa2614da316f51b4fba24d21689c96
[]
no_license
tokitsu-kaze/ACM-Solved-Problems
69e16c562a1c72f2a0d044edd79c0ab949cc76e3
77af0182401904f8d2f8570578e13d004576ba9e
refs/heads/master
2023-09-01T11:25:12.946806
2023-08-25T03:26:50
2023-08-25T03:26:50
138,472,754
5
1
null
null
null
null
UTF-8
C++
false
false
4,242
cpp
#include <bits/stdc++.h> using namespace std; namespace fastIO{ #define BUF_SIZE 100000 #define OUT_SIZE 100000 //fread->read bool IOerror=0; //inline char nc(){char ch=getchar();if(ch==-1)IOerror=1;return ch;} inline char nc(){ static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE; if(p1==pend){ p1=buf;pend=buf+fread(buf,1,BUF_SIZE,stdin); if(pend==p1){IOerror=1;return -1;} } return *p1++; } inline bool blank(char ch){return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';} template<class T> inline bool read(T &x){ bool sign=0;char ch=nc();x=0; for(;blank(ch);ch=nc()); if(IOerror)return false; if(ch=='-')sign=1,ch=nc(); for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0'; if(sign)x=-x; return true; } inline bool read(double &x){ bool sign=0;char ch=nc();x=0; for(;blank(ch);ch=nc()); if(IOerror)return false; if(ch=='-')sign=1,ch=nc(); for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0'; if(ch=='.'){ double tmp=1; ch=nc(); for(;ch>='0'&&ch<='9';ch=nc())tmp/=10.0,x+=tmp*(ch-'0'); } if(sign)x=-x; return true; } inline bool read(char *s){ char ch=nc(); for(;blank(ch);ch=nc()); if(IOerror)return false; for(;!blank(ch)&&!IOerror;ch=nc())*s++=ch; *s=0; return true; } inline bool read(char &c){ for(c=nc();blank(c);c=nc()); if(IOerror){c=-1;return false;} return true; } template<class T,class... U>bool read(T& h,U&... t){return read(h)&&read(t...);} #undef OUT_SIZE #undef BUF_SIZE }; using namespace fastIO; /************* debug begin *************/ string to_string(string s){return '"'+s+'"';} string to_string(const char* s){return to_string((string)s);} string to_string(const bool& b){return(b?"true":"false");} template<class T>string to_string(T x){ostringstream sout;sout<<x;return sout.str();} template<class A,class B>string to_string(pair<A,B> p){return "("+to_string(p.first)+", "+to_string(p.second)+")";} template<class A>string to_string(const vector<A> v){ int f=1;string res="{";for(const auto x:v){if(!f)res+= ", ";f=0;res+=to_string(x);}res+="}"; return res; } void debug_out(){puts("");} template<class T,class... U>void debug_out(const T& h,const U&... t){cout<<" "<<to_string(h);debug_out(t...);} #ifdef tokitsukaze #define debug(...) cout<<"["<<#__VA_ARGS__<<"]:",debug_out(__VA_ARGS__); #else #define debug(...) 233; #endif /************* debug end *************/ #define mem(a,b) memset((a),(b),sizeof(a)) #define MP make_pair #define pb push_back #define fi first #define se second #define sz(x) (int)x.size() #define all(x) x.begin(),x.end() #define sqr(x) (x)*(x) using namespace __gnu_cxx; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> PII; typedef pair<ll,ll> PLL; typedef pair<int,ll> PIL; typedef pair<ll,int> PLI; typedef vector<int> VI; typedef vector<ll> VL; typedef vector<PII > VPII; /************* define end *************/ void read(int *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);} void read(ll *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);} void read(double *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);} void println(VI x){for(int i=0;i<sz(x);i++) printf("%d%c",x[i]," \n"[i==sz(x)-1]);} void println(VL x){for(int i=0;i<sz(x);i++) printf("%lld%c",x[i]," \n"[i==sz(x)-1]);} void println(int *x,int l,int r){for(int i=l;i<=r;i++) printf("%d%c",x[i]," \n"[i==r]);} void println(ll *x,int l,int r){for(int i=l;i<=r;i++) printf("%lld%c",x[i]," \n"[i==r]);} /*************** IO end ***************/ void go(); int main(){ #ifdef tokitsukaze freopen("TEST.txt","r",stdin); #endif go();return 0; } const int INF=0x3f3f3f3f; const ll LLINF=0x3f3f3f3f3f3f3f3fLL; const double PI=acos(-1.0); const double eps=1e-6; const int MAX=2e5+10; const ll mod=998244353; /********************************* head *********************************/ ll x,y,a,b; int ck(ll ans) { return floorl(min(1.0*ans,1.0*(x-b*ans)/(a-b))) >= ceill(max(0.0,1.0*(y-a*ans)/(b-a))); } void go() { int t; ll l,r,mid; read(t); while(t--) { read(x,y,a,b); if(a==b) { printf("%lld\n",min(x/a,y/b)); continue; } if(a<b) { swap(a,b); swap(x,y); } l=0; r=1e9; while(l<r) { mid=(l+r)>>1; if(ck(mid+1)) l=mid+1; else r=mid; } printf("%lld\n",l); } }
[ "861794979@qq.com" ]
861794979@qq.com
186e44ed5fb1a2ea0582cdc18bdf31b9c0a052f7
511d7cd374cf8ecdc6a9d72223bed16a32d83c78
/msdk/mscom/mstask/Check.cpp
42ed942d4bda884ae34fe542a4b3e46d3e1d28ef
[]
no_license
mynick777/msdk
1818c718a181de772b9a3e2dd6d7b9a66296dc86
4ee669c60148ad72e1d8af9bea05e05019af79e6
refs/heads/master
2020-05-18T00:56:37.308774
2019-05-01T16:19:13
2019-05-01T16:19:13
184,075,465
0
0
null
2019-04-29T13:22:32
2019-04-29T13:22:32
null
UTF-8
C++
false
false
7,292
cpp
#include "StdAfx.h" #include ".\check.h" #include "WtsApi32.h" CCheck::CCheck(void) { m_hModPSAPI = NULL; m_pfnEnumProcesses = NULL; m_pfnEnumProcessModules = NULL; m_pfnGetModuleFileNameEx = NULL; m_hKernel = NULL; m_pCreateToolhelp32Snapshot = NULL; m_pProcess32First = NULL; m_pProcess32Next = NULL; m_bXpAbove = IsXPAbove(); ZeroMemory(m_szFileName,sizeof(m_szFileName)); GetWindowsDirectory(m_szFileName,MAX_PATH); lstrcat(m_szFileName,_T("\\explorer.exe")); _tcslwr(m_szFileName); RsGetCurentPath(m_szPath,MAX_PATH); lstrcat(m_szPath,_T("\\tray.exe")); _tcslwr(m_szPath); GetDllFunc(); //CheckExplorer(); } CCheck::~CCheck(void) { if(m_hModPSAPI) { FreeLibrary(m_hModPSAPI); m_hModPSAPI = NULL; } if(m_hKernel) { FreeLibrary(m_hKernel); m_hKernel = NULL; } } BOOL CCheck::GetDllFunc() { if( GetVersion() < 0x80000000) { return GetDllFuncNT(); } else { return GetDllFunc9x(); } return TRUE; } BOOL CCheck::GetDllFunc9x() { if (NULL == m_hKernel) m_hKernel = ::LoadLibrary(_T("kernel32.dll")); if(NULL == m_hKernel) return FALSE; m_pCreateToolhelp32Snapshot = (xCreateToolhelp32Snapshot) ::GetProcAddress(m_hKernel,"CreateToolhelp32Snapshot"); m_pProcess32First = (xProcess32First) ::GetProcAddress(m_hKernel, "Process32First"); m_pProcess32Next = (xProcess32Next) ::GetProcAddress(m_hKernel, "Process32Next"); return TRUE; } BOOL CCheck::GetDllFuncNT() { if (NULL == m_hModPSAPI) m_hModPSAPI = ::LoadLibrary(_T("PSAPI.DLL")); if(m_hModPSAPI == NULL) return FALSE; m_pfnEnumProcesses = (PFNENUMPROCESSES) ::GetProcAddress(m_hModPSAPI,"EnumProcesses"); m_pfnEnumProcessModules = (PFNENUMPROCESSMODULES) ::GetProcAddress(m_hModPSAPI, "EnumProcessModules"); #ifdef _UNICODE m_pfnGetModuleFileNameEx = (PFNGETMODULEFILENAMEEX) ::GetProcAddress(m_hModPSAPI, "GetModuleFileNameExW"); #else m_pfnGetModuleFileNameEx = (PFNGETMODULEFILENAMEEX) ::GetProcAddress(m_hModPSAPI, "GetModuleFileNameExA"); #endif return TRUE; } DWORD CCheck::GetCurrentSession(DWORD dwPid) { HMODULE hKernal32 = LoadLibrary(_T("kernel32.dll")); if(hKernal32 == NULL) { return -1; } typedef BOOL (WINAPI *FNPTS )(DWORD , DWORD*); DWORD dwSid = -1; FNPTS fnPts = NULL; fnPts = (FNPTS)GetProcAddress(hKernal32 , "ProcessIdToSessionId"); if(fnPts) { //dwPid = GetCurrentProcessId(); fnPts(dwPid , &dwSid); } FreeLibrary(hKernal32); return dwSid; } DWORD CCheck::CheckExplorerNT(DWORD dwSessionID) { RASSERTP(m_pfnEnumProcesses,0); RASSERTP(m_pfnEnumProcessModules,0); RASSERTP(m_pfnGetModuleFileNameEx,0); DWORD dwExplorerID = 0; BOOL b64 = FALSE; DWORD pidArray[1024]; DWORD cbNeeded; DWORD nProcesses; if ( ! m_pfnEnumProcesses(pidArray, sizeof(pidArray), &cbNeeded)) return 0; nProcesses = cbNeeded / sizeof(DWORD); for (DWORD i = 0; i < nProcesses; i++) { HMODULE hModuleArray[1024]; HANDLE hProcess; DWORD pid = pidArray[i]; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,FALSE, pid); if (!hProcess) continue; if (!m_pfnEnumProcessModules(hProcess, hModuleArray,sizeof(hModuleArray), &cbNeeded) ) { ::CloseHandle(hProcess); continue; } TCHAR szModuleName[MAX_PATH]={0}; m_pfnGetModuleFileNameEx(hProcess, hModuleArray[0],szModuleName, sizeof(szModuleName)); ::CloseHandle(hProcess); if(_tcscmp(_tcslwr(szModuleName),m_szFileName) == 0 || _tcscmp(_tcslwr(szModuleName),m_szPath) == 0 ) { dwExplorerID = pidArray[i]; if(dwSessionID != 0xFFFFFFFF && m_bXpAbove) { DWORD dwSid = GetCurrentSession(dwExplorerID); if(dwSid == dwSessionID) break; dwExplorerID = 0; } else break; } } // for return dwExplorerID; } DWORD CCheck::CheckExplorer9x(DWORD dwSessionID) { DWORD dwExplorerID = 0; BOOL b64 = FALSE; RASSERTP(m_pCreateToolhelp32Snapshot,0); RASSERTP(m_pProcess32First,0); RASSERTP(m_pProcess32Next,0); HANDLE hProcessSnap = NULL; PROCESSENTRY32 pe32 = {0}; hProcessSnap = m_pCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) { RSLOG(RSXML_DETAIL, _T("CreateToolhelp32Snapshot error =%d\n"),GetLastError()); return 0; } pe32.dwSize = sizeof(PROCESSENTRY32); if (! m_pProcess32First(hProcessSnap, &pe32)) { CloseHandle (hProcessSnap); return 0; } do { if(_tcscmp(_tcslwr(pe32.szExeFile),m_szFileName)==0 || _tcscmp(_tcslwr(pe32.szExeFile),m_szPath)==0) { dwExplorerID = pe32.th32ProcessID; break; } } while (m_pProcess32Next(hProcessSnap, &pe32)); CloseHandle (hProcessSnap); return dwExplorerID; } DWORD CCheck::CheckExplorer(DWORD dwSessionID) { if( GetVersion() < 0x80000000 ) { return CheckExplorerNT(dwSessionID); } return CheckExplorer9x(dwSessionID); } typedef BOOL (WINAPI * FnWTSEnumerateSessions)( HANDLE hServer, DWORD Reserved, DWORD Version, PWTS_SESSION_INFO* ppSessionInfo, DWORD* pCount ); typedef void (WINAPI *FnWTSFreeMemory)(PVOID pMemory); DWORD CCheck::GetActiveExplorer(DWORD& dwSessionID) { RASSERTP(m_pfnEnumProcesses,0); RASSERTP(m_pfnEnumProcessModules,0); RASSERTP(m_pfnGetModuleFileNameEx,0); DWORD dwExplorerID = 0; BOOL b64 = FALSE; WTS_SESSION_INFO* pSesionBuf = NULL; DWORD dwSessionNum =0; dwSessionID = 0; if( ! m_bXpAbove ) return 0; HMODULE hWtsapi32 = LoadLibrary(_T("Wtsapi32.dll")); RASSERTP(hWtsapi32,0); FnWTSEnumerateSessions pWTSEnumerateSessions = (FnWTSEnumerateSessions) GetProcAddress(hWtsapi32, "WTSEnumerateSessionsA"); FnWTSFreeMemory pWTSFreeMemory = (FnWTSFreeMemory) GetProcAddress(hWtsapi32, "WTSFreeMemory"); RASSERTP(pWTSEnumerateSessions,0); RASSERTP(pWTSFreeMemory,0); if(! pWTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE,0,1,&pSesionBuf,&dwSessionNum)) { FreeLibrary(hWtsapi32); return 0; } DWORD pidArray[1024]; DWORD cbNeeded; DWORD nProcesses; if ( ! m_pfnEnumProcesses(pidArray, sizeof(pidArray), &cbNeeded)) { if(pSesionBuf) { pWTSFreeMemory(pSesionBuf); } FreeLibrary(hWtsapi32); return 0; } nProcesses = cbNeeded / sizeof(DWORD); for (DWORD i = 0; i < nProcesses; i++) { HMODULE hModuleArray[1024]; HANDLE hProcess; DWORD pid = pidArray[i]; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,FALSE, pid); if (!hProcess) continue; if (!m_pfnEnumProcessModules(hProcess, hModuleArray, sizeof(hModuleArray), &cbNeeded) ) { ::CloseHandle(hProcess); continue; } TCHAR szModuleName[MAX_PATH]={0}; m_pfnGetModuleFileNameEx(hProcess, hModuleArray[0],szModuleName, sizeof(szModuleName)); ::CloseHandle(hProcess); if(_tcscmp(_tcslwr(szModuleName),m_szFileName) == 0 || _tcscmp(_tcslwr(szModuleName),m_szPath) == 0 ) { dwExplorerID = pidArray[i]; DWORD dwSid = GetCurrentSession(dwExplorerID); BOOL bFind = FALSE; for(DWORD j=0;j<dwSessionNum ;j++) { WTS_SESSION_INFO*ppBuf =(WTS_SESSION_INFO * ) ( pSesionBuf +j); if( ppBuf->SessionId == dwSid && ppBuf->State == WTSActive ) { dwSessionID = dwSid; bFind = TRUE; //break; } } if(bFind) break; dwExplorerID = 0; } } // for if(pSesionBuf) { pWTSFreeMemory(pSesionBuf); } FreeLibrary(hWtsapi32); return dwExplorerID; }
[ "maguojun123@126.com" ]
maguojun123@126.com
01ce05b8ff0d65baf6c5e6adaf123c9907adeee2
06e3479ec05be3e2a4edf0190768f08dbfbd4685
/lista4.9.cpp
e8748ecc08219cfa2bbbe3af29b46fe4aa46a9e2
[]
no_license
santripas/-Atividade-Avaliativa-04
329023299d6e41a3d1c995b77b6cc220fd23ed14
cf92cca1743ff8f895ae06f6f7be2b477c250697
refs/heads/main
2023-05-15T22:48:11.769371
2021-06-15T20:15:17
2021-06-15T20:15:17
377,283,019
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
657
cpp
#include<stdio.h> #include<locale> #include<ctype.h> void limpaTela(){ system("cls"); } int main(){ setlocale(LC_ALL, "Portuguese"); int numero, chutes, i=1; printf("Informe o numero imaginado: "); scanf("%d", &numero); fflush(stdin); limpaTela(); while(chutes != numero){ printf("%d° chute: ", i); scanf("%d", &chutes); fflush(stdin); if(chutes<numero) printf("\nMais\n\n"); else if(chutes>numero) printf("\nMenos\n\n"); else printf("\nAcertou!\n\n"); system("pause"); limpaTela(); i++; } printf("\nO numero imaginado foi: %d", numero); return 0; }
[ "noreply@github.com" ]
noreply@github.com
575de933cd2c336e2fe473da9a7b0f6866181e93
bc802f2f46557a0b5bfa9eb26821d0e82ec78aab
/H07/18127070/Cattle/Animal.h
8079025a87023b96cdc9e54cea55c8577f68fdbc
[ "MIT" ]
permissive
IceIce1ce/Lab-OOP-HCMUS
5fd145994cb352d1d65af1a292071dd554b3f018
974873f129dd4d39c0094fe8e0cc30236555cf50
refs/heads/master
2022-01-22T12:15:00.084514
2022-01-17T10:32:13
2022-01-17T10:32:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
838
h
#include<iostream> #include<string> #include<vector> #include<ctime> using namespace std; class Animal { public: Animal(); ~Animal(); virtual void talk() = 0; virtual int provideMilk() = 0; virtual vector <Animal*> birth() = 0; int type_of_animal(); virtual string name_of_animal() = 0; protected: int num_of_each_animal; }; class Cow: public Animal { public: Cow(); ~Cow(); void talk(); int provideMilk(); vector<Animal*> birth(); string name_of_animal(); }; class Sheep: public Animal { public: Sheep(); ~Sheep(); void talk(); int provideMilk(); vector<Animal*> birth(); string name_of_animal(); }; class Goat: public Animal { public: Goat(); ~Goat(); void talk(); int provideMilk(); vector<Animal*> birth(); string name_of_animal(); };
[ "ctran743@gmail.com" ]
ctran743@gmail.com
3a6f0f0ce04c43a7c3c205ff6696fbbb665414f4
f903fa24571f4c641b51b4e421158b60817cee7d
/Accepted_Tasks/J171_Acronym.cc
3c0f9cb2a8e5a5cd34d3e927e3e018b2ce3aafd2
[]
no_license
jerryliuhkg/my-c--codes
e2f413da7a2e3c92efa454e1e632e680bffd37c0
dc95912e685b2d00de54636527d88ef09351ccdb
refs/heads/master
2020-12-03T04:23:26.316376
2020-01-04T06:08:27
2020-01-04T06:08:27
231,199,189
1
0
null
null
null
null
UTF-8
C++
false
false
1,525
cc
#include <iostream> #include <string> using namespace std; int main() { string a; cin >> a; int lena = a.length(); int N; cin >> N; string test; int lentest; getline(cin, test); for(int i=0; i<N; i++) { getline(cin, test); lentest = test.length(); int counter = 0; bool boo = false; bool word = false; for(int j=0; j<lentest; j++) { if(test.at(j)==' ') { word = false; } else if(word==false && (test.at(j)==a.at(counter) || test.at(j)==a.at(counter)+32)) { counter++; word = true; } else if(word==false && !(test.at(j)==a.at(counter) || test.at(j)==a.at(counter)+32)) { word = true; } if(counter==lena) { boo = true; break; } } counter = 0; if(boo==true) { for(int j=0; j<lentest; j++) { if(counter>=lena) { if(test.at(j)==' ') { cout << ' '; } else if(test.at(j)<95) { cout << char(test.at(j) + 32); } else{ cout << test.at(j); } } else if((j==0 || test.at(j-1)==' ') && (test.at(j)==a.at(counter) || test.at(j)==a.at(counter)+32) && counter<lena) { if(test.at(j)<95) { cout << test.at(j); counter++; } else{ cout << char(test.at(j)-32); counter++; } } else{ if(test.at(j)==' ') { cout << ' '; } else if(test.at(j)<95) { cout << char(test.at(j) + 32); } else{ cout << test.at(j); } } } } else{ cout << "No :("; } cout << endl; } }
[ "noreply@github.com" ]
noreply@github.com
1f7b10d32968a8dc8fc3d821f1ee3004e037db4e
a93f5a41959faa793f4f22c439ad4c1ea92668b8
/AtCoder/abc_081/main_b.cpp
13fdb3fcc070b41a60ac8eb2eac0d1e603db6580
[]
no_license
admiswalker/i-am-learning-coding
08a473da773d0e2e67d44462c2d7dee83fa0adac
9c0d152d313aae06affdf0823fd59a188705d8f8
refs/heads/master
2021-07-07T05:21:09.871137
2020-12-21T23:55:42
2020-12-21T23:55:42
218,574,075
0
0
null
null
null
null
UTF-8
C++
false
false
827
cpp
#include <bits/stdc++.h> using namespace std; bool isEven(const int n){ if(n%2==0){ return true; }else{ return false; } } int min(const vector<int>& vec){ int min=vec[0]; for(int i=1; i<vec.size(); i++){ if(min>vec[i]){ min=vec[i]; } } return min; } int numOf2in(int x){ int n=0; while(isEven(x)){ x/=2; n++; } return n; } vector<int> numOf2in(const vector<int>& vec_in){ vector<int> vec_out(vec_in.size()); for(int i=0; i<vec_in.size(); i++){ vec_out[i] = numOf2in(vec_in[i]); } return vec_out; } int main(){ int N; cin >> N; vector<int> A(N); for(int i=0; i<A.size(); i++){ cin >> A[i]; } A = numOf2in(A); int a = min(A); cout << a; return 0; }
[ "admiswalker@gmail.com" ]
admiswalker@gmail.com
4b5e48842f442c38e5b8293ab28c5d9ad8f05096
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/hunk_5954.cpp
697cef4a9663c82ea78f83624bff10456c25d78e
[]
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
427
cpp
storeAppendPrintf(sentry, "Cache Clients:\n"); hash_first(client_table); while ((c = (ClientInfo *) hash_next(client_table))) { - storeAppendPrintf(sentry, "Address: %s\n", c->key); + storeAppendPrintf(sentry, "Address: %s\n", hashKeyStr(&c->hash)); storeAppendPrintf(sentry, "Name: %s\n", fqdnFromAddr(c->addr)); storeAppendPrintf(sentry, "Currently established connections: %d\n", c->n_established);
[ "993273596@qq.com" ]
993273596@qq.com
0e7c48c5682fb2de78d10608e3d44c945c5822c1
e32fb46aaa28a9fc753fc9128dd445aff00a1317
/borisovayu.h
c972db2aa106bc882c114a299d3718175c610583
[]
no_license
mrsu-ru/2020-203
125c48e99c47fccd88ecdb4dd5ac5eb4a63c4128
cbe0b970d2b65f1c466269d646ebe103a335cb58
refs/heads/master
2020-12-28T04:30:09.031001
2020-06-23T11:52:22
2020-06-23T11:52:22
238,181,295
4
40
null
2020-06-23T13:26:57
2020-02-04T10:38:01
C++
UTF-8
C++
false
false
735
h
#pragma once #include "lab.h" class borisovayu : public lab { /** * Метод Гаусса */ virtual void lab1(); /** * Метод Гаусса с выбором главного элемента */ virtual void lab2(); /** * Метод квадратного корня (метод Холецкого) */ virtual void lab3(); /** * Метод прогонки */ virtual void lab4(); /** * Метод Якоби */ virtual void lab5(); /** * Метод Зейделя */ virtual void lab6(); /** * Один из градиентных методов */ virtual void lab7(); virtual void lab8(); virtual void lab9(); virtual std::string get_name(); };
[ "borisovayu@lab227.local" ]
borisovayu@lab227.local
c31e2c1831f052c26f7b5c8215c56720b77dff8f
a34cd99c5ea4ba25290882bea2c0fc35998b8046
/Assignment2/ISailable.h
ba7896feddb25b3a50b495b11a420de415dd9527
[ "MIT" ]
permissive
OpticalSpring/ProjectPOCU
41c3cd2ff709d47a2e149f1f4c07e04ee841ed5e
58ac849f02fa68bc61d32f2c5a28e7ceaf157d13
refs/heads/master
2023-03-29T06:25:47.789248
2021-04-04T04:59:10
2021-04-04T04:59:10
205,868,520
3
0
null
null
null
null
UTF-8
C++
false
false
121
h
#pragma once namespace assignment2 { class ISailable { public: virtual unsigned int GetSailSpeed() const = 0; }; }
[ "cosmos5477@gmail.com" ]
cosmos5477@gmail.com
8f352bdc85b2239917715c6501405b9302cfc0b6
6326e21a65b923cbda7687d70168edde4161908c
/src/viewer/viewgraph.h
421a69ee5da45c2052718913c0afb9e070df0d56
[ "BSD-3-Clause" ]
permissive
n1ckfg/contours_viewer
c6165338a3262fea0ac595ccccb3f58222e28a77
16eb17c916272d34e73039f0969e46abc0ec30ca
refs/heads/master
2022-01-04T16:24:30.351966
2020-02-27T13:05:59
2020-02-27T13:05:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,141
h
#ifndef VIEWGRAPH_H #define VIEWGRAPH_H #include "common.h" #include <surface_mesh.h> using Edge = surface_mesh::Surface_mesh::Edge; using Face = surface_mesh::Surface_mesh::Face; using Vertex = surface_mesh::Surface_mesh::Vertex; struct FEdge; struct SVertex { SVertex(const Vector3f &pos3D, nature_t nature = VertexNature::S_VERTEX) : m_pos3D(pos3D), m_nature(nature) {} Vector3f m_pos3D, m_pos2D; nature_t m_nature; std::list<FEdge *> m_fedges; }; template <class Edge> class Segment; struct FEdge { FEdge(SVertex *vA, SVertex *vB, nature_t n) : m_vertexA(vA), m_vertexB(vB), m_nature(n), m_segment(nullptr) {} SVertex *m_vertexA, *m_vertexB; virtual ~FEdge() {} virtual bool isSmooth() const { return false; }; nature_t m_nature; Segment<FEdge *> *m_segment; }; struct FEdgeSharp : public FEdge { FEdgeSharp(SVertex *vA, SVertex *vB, Edge e, nature_t n) : FEdge(vA, vB, n), m_edge(e) {} virtual ~FEdgeSharp() {} virtual bool isSmooth() const { return false; } Edge m_edge; }; struct FEdgeSmooth : public FEdge { FEdgeSmooth(SVertex *vA, SVertex *vB, Edge eA, real_t tA, Edge eB, real_t tB, nature_t n) : FEdge(vA, vB, n), m_edgeA(eA), m_edgeB(eB), m_tA(tA), m_tB(tB) {} virtual ~FEdgeSmooth() {} virtual bool isSmooth() const { return true; } Edge m_edgeA, m_edgeB; real_t m_tA, m_tB; }; struct FEdgeIntersection : public FEdge { FEdgeIntersection(SVertex *vA, SVertex *vB, Face f1, Face f2) : FEdge(vA, vB, EdgeNature::SURFACE_INTERSECTION), m_f1(f1), m_f2(f2) {} virtual ~FEdgeIntersection() {} virtual bool isSmooth() const { return true; } Face m_f1, m_f2; }; class VertexCompare { public: VertexCompare(real_t eps) : m_epsilon(eps) {} bool operator()(SVertex *x, SVertex *y) const { const Vector3f &A = x->m_pos2D; const Vector3f &B = y->m_pos2D; for (unsigned int i = 0; i < 3; i++) { if ((fabs(A[i] - B[i])) < m_epsilon) continue; if (A[i] < B[i]) return true; if (A[i] > B[i]) return false; } return false; } private: real_t m_epsilon; }; #endif
[ "pierre.g.benard@inria.fr" ]
pierre.g.benard@inria.fr
72a6b753bb257294badc475c1d511c3ac2fd7413
64d401b998d689d9c937988c5ad8badaffeb29ed
/components/ntp_snippets/features.cc
89a6f085e71e9fb4ff3782859256bb9877ee1f52
[ "BSD-3-Clause" ]
permissive
Snger/chromium
77c1ae991b5d92d830d83e2bbd6890673d98c963
23c9664fcc2ffd6bdcffbca5355ba4cd083f7060
refs/heads/master
2023-02-26T16:06:16.690161
2017-03-30T03:45:22
2017-03-30T03:45:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,572
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/ntp_snippets/features.h" #include "base/feature_list.h" #include "base/memory/ptr_util.h" #include "base/time/clock.h" #include "components/ntp_snippets/category_rankers/click_based_category_ranker.h" #include "components/ntp_snippets/category_rankers/constant_category_ranker.h" #include "components/variations/variations_associated_data.h" namespace ntp_snippets { const base::Feature kArticleSuggestionsFeature{ "NTPArticleSuggestions", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kBookmarkSuggestionsFeature{ "NTPBookmarkSuggestions", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kRecentOfflineTabSuggestionsFeature{ "NTPOfflinePageSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kSaveToOfflineFeature{"NTPSaveToOffline", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kOfflineBadgeFeature{"NTPOfflineBadge", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kIncreasedVisibility{"NTPSnippetsIncreasedVisibility", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kPhysicalWebPageSuggestionsFeature{ "NTPPhysicalWebPageSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kForeignSessionsSuggestionsFeature{ "NTPForeignSessionsSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kPreferAmpUrlsFeature{"NTPPreferAmpUrls", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kCategoryRanker{"ContentSuggestionsCategoryRanker", base::FEATURE_ENABLED_BY_DEFAULT}; const char kCategoryRankerParameter[] = "category_ranker"; const char kCategoryRankerConstantRanker[] = "constant"; const char kCategoryRankerClickBasedRanker[] = "click_based"; CategoryRankerChoice GetSelectedCategoryRanker() { std::string category_ranker_value = variations::GetVariationParamValueByFeature(kCategoryRanker, kCategoryRankerParameter); if (category_ranker_value.empty()) { // Default, Enabled or Disabled. return CategoryRankerChoice::CONSTANT; } if (category_ranker_value == kCategoryRankerConstantRanker) { return CategoryRankerChoice::CONSTANT; } if (category_ranker_value == kCategoryRankerClickBasedRanker) { return CategoryRankerChoice::CLICK_BASED; } LOG(DFATAL) << "The " << kCategoryRankerParameter << " parameter value is '" << category_ranker_value << "'"; return CategoryRankerChoice::CONSTANT; } std::unique_ptr<CategoryRanker> BuildSelectedCategoryRanker( PrefService* pref_service, std::unique_ptr<base::Clock> clock) { CategoryRankerChoice choice = ntp_snippets::GetSelectedCategoryRanker(); switch (choice) { case CategoryRankerChoice::CONSTANT: return base::MakeUnique<ConstantCategoryRanker>(); case CategoryRankerChoice::CLICK_BASED: return base::MakeUnique<ClickBasedCategoryRanker>(pref_service, std::move(clock)); } return nullptr; } const base::Feature kCategoryOrder{"ContentSuggestionsCategoryOrder", base::FEATURE_DISABLED_BY_DEFAULT}; const char kCategoryOrderParameter[] = "category_order"; const char kCategoryOrderGeneral[] = "general"; const char kCategoryOrderEmergingMarketsOriented[] = "emerging_markets_oriented"; CategoryOrderChoice GetSelectedCategoryOrder() { if (!base::FeatureList::IsEnabled(kCategoryOrder)) { return CategoryOrderChoice::GENERAL; } std::string category_order_value = variations::GetVariationParamValueByFeature(kCategoryOrder, kCategoryOrderParameter); if (category_order_value.empty()) { // Enabled with no parameters. return CategoryOrderChoice::GENERAL; } if (category_order_value == kCategoryOrderGeneral) { return CategoryOrderChoice::GENERAL; } if (category_order_value == kCategoryOrderEmergingMarketsOriented) { return CategoryOrderChoice::EMERGING_MARKETS_ORIENTED; } LOG(DFATAL) << "The " << kCategoryOrderParameter << " parameter value is '" << category_order_value << "'"; return CategoryOrderChoice::GENERAL; } } // namespace ntp_snippets
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
8f172e5b4c2cbb30831ffbf3b237ede9b21deaa0
c51febc209233a9160f41913d895415704d2391f
/YorozuyaGSLib/source/_add_lend_item_result_zocl.cpp
3dd2f75c318501fc3aa74d206ebdb0e2ad260b45
[ "MIT" ]
permissive
roussukke/Yorozuya
81f81e5e759ecae02c793e65d6c3acc504091bc3
d9a44592b0714da1aebf492b64fdcb3fa072afe5
refs/heads/master
2023-07-08T03:23:00.584855
2023-06-29T08:20:25
2023-06-29T08:20:25
463,330,454
0
0
MIT
2022-02-24T23:15:01
2022-02-24T23:15:00
null
UTF-8
C++
false
false
260
cpp
#include <_add_lend_item_result_zocl.hpp> START_ATF_NAMESPACE int _add_lend_item_result_zocl::size() { using org_ptr = int (WINAPIV*)(struct _add_lend_item_result_zocl*); return (org_ptr(0x1403fea30L))(this); }; END_ATF_NAMESPACE
[ "b1ll.cipher@yandex.ru" ]
b1ll.cipher@yandex.ru
4dfe535ba3b58c78eb017a99f559e8bafad1cafb
eba9424166882ccfb23f0542e6e751ad586901b5
/src/MSWin.hpp
21e6d099d68be02c97b92e178fff0dce0fa9da60
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
inambioinfo/pview
00f3c2de04540417b26e5798865b958afc4fb629
13e28fd9e8179e9f35b10d48ea8853ad51246c9f
refs/heads/master
2021-01-13T07:48:12.178233
2016-01-18T23:14:54
2016-01-18T23:14:54
95,094,105
1
0
null
2017-06-22T08:43:39
2017-06-22T08:43:39
null
UTF-8
C++
false
false
12,632
hpp
#ifndef __MSWIN_HPP__ #define __MSWIN_HPP__ #include <QtGui> #include <QtWidgets> #include <list> #include <map> #include <vector> #include "ui_MSWin.h" #include "dialogs.hpp" #include "MSMSWin.hpp" #include "analysis.hpp" #include <iostream> using namespace std; // Code is organized to keep all GUI state in the view LCMSView. The // window MSWin only alters this state based on user input. // Enums used as state information in LCMSView. enum queryrect_t { NO_QRECT, FILTER_QRECT, NEIGHBOR_QRECT }; // Used to set selection mode. enum selectmode_t { NO_SELECT, ZOOM, MS2_SELECT, XIC_SELECT, XIC_MS2_SELECT }; // retention time range struct time_range { double min_time, max_time; }; // Datatype for m/z range struct mz_range { double min_mz, max_mz; }; // GraphicsView framework item for displaying LC-MS/MS data. // This class contains most of the GUI's state information. class LCMSView : public QObject, public QGraphicsItem { Q_OBJECT public: // Constructor creates QImage canvas, initializes LCMS view state. LCMSView(lcms::analysis *a, int w, int h, QLabel *mzLabel_ = NULL, QLabel *rtLabel_ = NULL) { analysis = a; width = w; height = h; mzLabel = mzLabel_; rtLabel = rtLabel_; condIndex = 0; // condition number, show 0th (first) condition repIndex = 0; // replicate number, show 0th (first) replicate irunIndex = 0; // current irun to display, show 0th irun // Set range to original range specified in config.xml. d.min_mz = analysis->min_mz; d.max_mz = analysis->max_mz; t.min_time = analysis->min_time; t.max_time = analysis->max_time; terrain_colors(colors, 256); // Initialize GUI color set. // Use a QImage canavs (faster to use setPixel). canvas = new QImage(width, height, QImage::Format_ARGB32_Premultiplied); // Initial GUI state parameters. selection = NULL; select_mode = NO_SELECT; display_raw = false; display_graph = false; display_qrect = NO_QRECT; display_corr = false; display_obs = false; display_XICs = false; display_isotopic = false; display_group = false; display_IDs = true; peak_size = 1; ms2win = NULL; xicwin = NULL; setAcceptHoverEvents(true); // Allows display of mouse coordinates in corner. redraw(); } ~LCMSView() { delete canvas; if(selection != NULL) delete selection; if(ms2win != NULL) delete ms2win; if(xicwin != NULL) delete xicwin; } void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { if(canvas != NULL) painter->drawImage(0,0, *canvas); } QRectF boundingRect() const { return QRectF(0, 0, width, height); } void setSize(int w, int h) { width = w; height = h; delete canvas; canvas = new QImage(w,h, QImage::Format_ARGB32_Premultiplied); redraw(); } // START Accessor functions for controlling the GUI state. QString getDescription() { QString a = analysis->conditions[condIndex]->description.c_str(); QString d = analysis->conditions[condIndex]->replicates[repIndex]->description.c_str(); return a + ":" + d; } void setZoomMode() { select_mode = ZOOM; } void setMS2Select() { select_mode = MS2_SELECT; } void setXICSelect() { select_mode = XIC_SELECT; } void setXICMS2Select() { select_mode = XIC_MS2_SELECT; } void zoomOut() { if(zoom_mz.size() == 0) return; else { d = zoom_mz.front(); t = zoom_time.front(); zoom_mz.pop_front(); zoom_time.pop_front(); redraw(); update(); } } void toggleRawData() { display_raw = !display_raw; redraw(); update(); } void toggleGraph() { display_graph = !display_graph; redraw(); update(); } void toggleGroup() { display_group = !display_group; redraw(); update(); } void incrementPeakSize() { peak_size++; redraw(); update(); } void decrementPeakSize() { if(peak_size > 1) { peak_size--; redraw(); update(); } } void cycleRect() { // Cycle through query rectangle display. switch(display_qrect) { case NO_QRECT: display_qrect = FILTER_QRECT; break; case FILTER_QRECT: display_qrect = NEIGHBOR_QRECT; break; case NEIGHBOR_QRECT: display_qrect = NO_QRECT; break; } redraw(); update(); } void cycleCorrRect() { display_corr = !display_corr; redraw(); update(); } void toggleXICs() { display_XICs = !display_XICs; redraw(); update(); } void toggleIDs() { display_IDs = !display_IDs; redraw(); update(); } void toggleIsotopic() { display_isotopic = !display_isotopic; redraw(); update(); } void toggleObs() { display_obs = !display_obs; redraw(); update(); } // Change or access the current condition, replicate set, or irun. void setCond(int newCondIndex) { condIndex = newCondIndex; } int getCond() { return condIndex; } void setRep(int newRepIndex) { repIndex = newRepIndex; } int getRep() { return repIndex; } void setIrun(int newIrunIndex) { irunIndex = newIrunIndex; } int getIrun() { return irunIndex; } // Change view position. void setmzrt(double mz1, double mz2, double rt1, double rt2) { zoom_mz.push_front(d); zoom_time.push_front(t); // Save the zoom value. d.min_mz = mz1; d.max_mz = mz2; t.min_time = rt1; t.max_time = rt2; redraw(); update(); } // END accesor functions for controlling GUI state. void redraw(); protected: QLabel *mzLabel, *rtLabel; // pointers to label objects in MSWin updated as mouse moves. int condIndex, repIndex, irunIndex; // current condition, replicate, or irun to display lcms::analysis *analysis; // condition/replicate/irun LC-MS/MS data set mz_range d; time_range t; // Current m/z and time range. int width, height; // Current width and height of canvas/drawing area. list<mz_range> zoom_mz; // Stack of ranges vales for different zoom settings for m/z dimension list<time_range> zoom_time; // and for the retention time dimension. vector<QColor> colors; // Coloring scheme for peak intensity. selectmode_t select_mode; // Switch to select mode. bool display_raw; // Toggles display of raw peak data. bool display_graph; // Toggles display of peak graph. bool display_XICs; // Flag turns on and off the display of XICs. bool display_isotopic; // Flag turns on and off display isotope/charge related boxes. bool display_obs; // Flag for display of grouped XICs. bool display_group; // Display time range used to group across iruns. bool display_IDs; // Display search IDs. queryrect_t display_qrect; // Controls display of query rectangles. bool display_corr; // Controls display of alignment/grouping rectangles. int peak_size; // Size of drawn peak. MSMSWin *ms2win; // non-modal dialog window for display MS/MS spectra. XICWin *xicwin; // non-modal dialog window for display XICs // Data drawing routines. QImage *canvas; void draw_XICs(lcms::irun *irun, QPainter *painter); void draw_isotope_groups(lcms::irun *irun, QPainter *painter); void draw_peaks(vector<lcms::peak *> &data, vector<lcms::ms2peak *> &data2, QPainter *painter); void draw_qrect(lcms::irun *irun, vector<lcms::peak *> &data, QPainter *painter); void draw_graph(lcms::irun *irun, QPainter *painter); void draw_grouped(QPainter *painter); void draw_grouped(QPainter *painter, vector<lcms::align_group *> &obs, QColor color); // Convert from image coordinates to a (m/z, retention time group). void from_canvas(double x, double y, double &rt, double &mz){ rt = x / double(width) * (t.max_time - t.min_time) + t.min_time; mz = y / double(height) * (d.max_mz - d.min_mz) + d.min_mz; } // Take an (m/z, time) group and convert to a canvas coordinate. void to_canvas(double retentionTime, double mz, int &x, int &y){ double scaletime = double(width) / (t.max_time - t.min_time); double scalemz = double(height) / (d.max_mz - d.min_mz); x = (int)((retentionTime - t.min_time) * scaletime); y = (int)((mz - d.min_mz) * scalemz ); } // Selection rectangle, used for zooming into the data. QGraphicsRectItem *selection; // Mouse events used for zooming. void mousePressEvent( QGraphicsSceneMouseEvent *event) { if(selection == NULL && select_mode != NO_SELECT) { selection = new QGraphicsRectItem(event->pos().x(), event->pos().y(), 1,1, this); selection->setPen(QPen(Qt::white)); } } void mouseMoveEvent( QGraphicsSceneMouseEvent *event) { if(selection != NULL) { QRectF r = selection->rect(); r.setRight(event->pos().x()); r.setBottom(event->pos().y()); selection->setRect(r); } } void mouseReleaseEvent( QGraphicsSceneMouseEvent *); void hoverMoveEvent(QGraphicsSceneHoverEvent *event) { // Capture mouse position, show corresponding (rt, m/z) position. double rt, mz; from_canvas(event->pos().x(), event->pos().y(), rt, mz); QString rtStr = QString::number(rt,'f',7); QString mzStr = QString::number(mz,'f',7); if(mzLabel != NULL) mzLabel->setText(mzStr); if(rtLabel != NULL) rtLabel->setText(rtStr); } }; // Main window that manages the current set of replicate LC-MS/MS // iruns. This is just a wrapper around LCMSView which has most of // the GUI state information. class MSWin : public QMainWindow, private Ui::MSWin { Q_OBJECT public: MSWin(QMainWindow *parent = 0); ~MSWin() { if(view != NULL) delete view; if(analysis != NULL) delete analysis; } protected: QGraphicsScene scene; // Scene that contains LCMSView // Selected replicate, irun memory information. vector<int> selectedRepIndex; // condIndex -> repIndex vector< vector<int> > selectedIrunIndex; // (condIndex, repIndex) -> irunIndex LCMSView *view; // Main LC-MS/MS view msconfig conf; // Global configuration information. lcms::analysis *analysis; // Current replicate set. // Mapping from tree widget (pointer) item to a specific isotope group. map<QTreeWidgetItem *, lcms::isotope_group*> item2group; // Mapping from atree widget to a specific XIC. map<QTreeWidgetItem *, lcms::xic*> item2xic; void resizeEvent(QResizeEvent *) { if(view != NULL) { // Keep view the same size as window. int fw = graphicsView->frameWidth(); view->setSize(graphicsView->width() - 2*fw-1, graphicsView->height() - 2*fw-1); graphicsView->setSceneRect(0,0,graphicsView->width() - 2*fw-1, graphicsView->height() - 2*fw-1); } } // Examines given directory. Collects subdirectories = conditions and mzXML files. // Keyboard capture. void keyReleaseEvent(QKeyEvent *); // Collect mzXML files in given directory. void collect_mzXML_files(QDir dir, vector<lcms::irun_file> &irunFiles); // Examines given directory for files with given suffix. void find_files(QString dir, vector<string> &base, vector<string> &files, QString suf); // Process iruns, divided among threads. void processIruns(); // Multi-threaded irun/irun alignment. void alignIruns(); // Loads fasta files in directory and builds fragment database, etc. void loadDBs(); // Utility function for displaying progress dialog. void progressDialog(QString message, QThread *thread) { vector<QThread *> threads; threads.push_back(thread); progressDialog(message, threads); } void progressDialog(QString message, vector<QThread *> threads); bool profileDialog(bool &ms1_profile, bool &ms2_profile); // Populates tree widgets. void populateIsotopeTree(); void populateIsotopeGroups(QTreeWidgetItem *frags, vector<lcms::isop_seqgroup> &seq_groups); void populateXICTreeAlign(); void populateXICTree(); // Generates subtrees used by above functions. QTreeWidgetItem *accessionSubtree(vector<int> &idxs); QTreeWidgetItem *xicSubtree(string seq, int charge, vector<lcms::xic *> &xics); void closeEvent(QCloseEvent *event) { if(view != NULL) { delete view; view = NULL; } if(analysis != NULL) { delete analysis; analysis = NULL; } QMainWindow::closeEvent(event); } private slots: void on_action_Open_triggered(); void on_action_Recalibrate_triggered(); void on_action_Quit_triggered() { if(view != NULL) delete view; if(analysis != NULL) delete analysis; exit(0); } void on_actionSave_TXT_triggered(); void on_actionSave_SILAC_TXT_triggered(); void on_actionSave_Align_XICs_TXT_triggered(); void on_isotopeTree_itemDoubleClicked(QTreeWidgetItem * item, int column); void on_xicTree_itemDoubleClicked(QTreeWidgetItem * item, int column); void on_listCond_currentRowChanged(int row); void on_listRep_currentRowChanged(int row); void on_listIrun_currentRowChanged(int row); }; #endif // __MSWIN_HPP__
[ "zia@Zias-MBP.home" ]
zia@Zias-MBP.home
101c7f2c6188edcfaa5fa3bfd4006aba446f2a5a
c207771a336ba21194343d295db8dd639e6f98fe
/webserver.cpp
f2d73aab1082f01d783922be4e2d77d65edcdc74
[]
no_license
dawangzeng/webserver-epoll
6ea8320048666883328e805c740369c3b18e013f
1f7e61cde4c03889140aa049e4bdca993e93bc23
refs/heads/master
2021-06-23T11:44:05.511111
2019-04-08T06:41:21
2019-04-08T06:41:21
177,569,956
0
0
null
null
null
null
UTF-8
C++
false
false
2,374
cpp
#include "webserver.h" #include<signal.h> //设置套接字为非阻塞状态 void setnoblocking(int fd){ int old_op = fcntl(fd,F_GETFL); int new_op = old_op | O_NONBLOCK; fcntl(fd,F_SETFL,new_op); } //添加到epoll中 void addepoll(int epollfd,int fd){ epoll_event event; event.data.fd = fd; event.events = EPOLLIN | EPOLLONESHOT | EPOLLET | EPOLLRDHUP; epoll_ctl(epollfd,EPOLL_CTL_ADD,fd,&event); setnoblocking(fd); } int WebServer::start() { signal(SIGPIPE, SIG_IGN); //初始化服务地址 server.sin_family = AF_INET; server.sin_port = htons(port); server.sin_addr.s_addr = htonl(INADDR_ANY); //创建套接字 listenfd = socket(AF_INET,SOCK_STREAM,0); if(listenfd < 0) { cerr<<"sock failed!"<<endl; exit(-1); } //绑定套接字 int ret = bind(listenfd,(struct sockaddr *)&server,sizeof(server)); if(ret < 0) { cerr<<"bind error!"<<endl; exit(-1); } //监听套接字 ret = listen(listenfd,200); if(ret<0) { cerr<<"listen error"<<endl; exit(-2); } cout<<"server listening...."<<endl; //创建线程池 ThreadPool<Task> pool(100); //创建epoll epollfd = epoll_create(3000); if( epollfd < 0 ) { cout << "epoll_create error, line: " << __LINE__ << endl; exit(-1); } epoll_event events[MAX_EVENT_COUNT]; //将监听套接字加入到epoll中 epoll_event event; event.data.fd = listenfd; event.events = EPOLLIN | EPOLLHUP; epoll_ctl(epollfd,EPOLL_CTL_ADD,listenfd,&event); //循环处理 for(;;) { //epoll等待事件 ret = epoll_wait(epollfd,events,MAX_EVENT_COUNT,-1); if(ret < 0) { cerr<<"wait error!"<<endl; exit(-1); } for(int i = 0; i < ret ;i++) { int fd = events[i].data.fd; if(listenfd == fd)//有新的连接 { struct sockaddr_in client; socklen_t client_size = sizeof(client); int conn = accept(fd,(struct sockaddr *)&client,&client_size); if(conn < 0) { cerr<<"accept error!"<<endl; continue; } cout<<"new connection.."<<endl; addepoll(epollfd,conn); }else if(events[i].events &(EPOLLHUP | EPOLLRDHUP |EPOLLERR)) { deletefd(epollfd,fd); }else if(events[i].events & EPOLLIN)//有数据可以读 { cout<<"epollin"<<endl; Task *task = new Task(epollfd,fd); cout<<"pool add.. "<<fd<<endl; pool.append(task); }else { cerr<<"Unknown"<<endl; } } } return 0; }
[ "1303272313@qq.com" ]
1303272313@qq.com
5d022849ae2b76107619b39812afd085d7e5d458
6dfad0b6469e6d30719795c9a1b7acb26416e977
/BIANJI.CPP
44a59f84e176ca0608c79d52b8232e35d3e5294b
[]
no_license
836711600/angrypig
0b49cf4c28c4eae95f5d782ad9ab5425d213a80b
69239f2944c0dccdaac91ed9bdcb678266e08c7d
refs/heads/master
2021-01-18T16:00:42.216135
2017-03-30T12:45:19
2017-03-30T12:45:19
86,701,571
0
0
null
null
null
null
UTF-8
C++
false
false
3,256
cpp
#include"angrypig.h" void yidongbird(int *mx,int *my,int *mbutt); void yidongbox(int *mx,int *my,int *mbutt); void bianjimouse(BOX *box,BIRD *bird); void bianji() { BOX box[6]={ {100,820,565,0,0}, {100,820,525,0,0}, {100,820,485,0,0}, {100,820,445,0,0}, {100,940,565,0,0}, {100,940,525,0,0} }; BIRD bird[2]={ {100,940,490,0,0}, {100,820,410,0,0} }; VesaSetWriteMode(VESA_COPY); ShowBmp24B(0,767,"tupian\\bianji.bmp"); ShowBmp24B(20,60,"tupian\\zanting.bmp"); ShowBmp24B(80,60,"tupian\\again.bmp"); VesaSetWriteMode(VESA_XOR); drawbird(bird,2); drawbox(box,6); bianjimouse(box,bird); } void bianjimouse(BOX *box,BIRD *bird) { FILE *fp; int xmin,xmax,ymin,ymax,x_max=1024,y_max=575; int buttons=0,xm,ym,x0,y0,i=0,j,k,x,y; BOX *box1; BIRD *bird1; box1=box; bird1=bird; xmin=1; xmax=x_max-1; ymin=1; ymax=y_max-2; if(init(xmin,xmax,ymin,ymax)==0) { printf("Mouse or Mouse Driver Absent,P1ease install!"); delay(5000); exit(1); } x=512; y=384; cursor(x,y); for(;;) { box1=box; bird1=bird; for(j=0;j<6;j++) { if(abs(x-box1->x)<20&&abs(y-box1->y)<20&&buttons) { if(i++==0) { cursor(x,y); x=box1->x; y=box1->y; } for(;;) { yidongbox(&x,&y,&buttons); if(buttons==0) { box1->x=x; box1->y=y; box1->life=100; box1->vx=0; box1->vy=0; cursor(box1->x,box1->y); i=0; break; } } } box1++; } for(k=0;k<2;k++) { if(abs(x-bird1->x)<15&&abs(y-bird1->y)<15&&buttons) { if(i++==0) { cursor(x,y); x=bird1->x; y=bird1->y; } for(;;) { yidongbird(&x,&y,&buttons); if(buttons==0) { bird1->x=x; bird1->y=y; bird1->life=100; bird1->vx=0; bird1->vy=0; cursor(bird1->x,bird1->y); i=0; break; } } } bird1++; } if(x>=20&&x<=60&&y>=20&&y<=60&&buttons) { box1=box; bird1=bird; delay(50); if((fp=fopen("file\\zdybox.txt","wb+"))==NULL) { printf("zdybox.txt unopen!!"); getch(); exit(0); } for(i=0;i<6;i++) { fwrite(box1,sizeof(BOX),1,fp); box1++; } fclose(fp); if((fp=fopen("file\\zdybird.txt","wb+"))==NULL) { printf("zdybird.txt unopen!!"); getch(); exit(0); } fwrite(bird1,sizeof(BIRD),2,fp); fclose(fp); selfset(); } if(x>=80&&x<=120&&y>=20&&y<=60&&buttons) { delay(100); bianji(); } newxy(&x,&y,&buttons); } } void yidongbird(int *mx,int *my,int *mbutt) { ICON birdbmp; int xx0=*mx,yy0=*my; int xm,ym; read(&xm,&ym,mbutt); ReadIconBmp24B(&birdbmp,"tupian\\bird.bmp"); ShowIcon24B(xx0-15,yy0+15,&birdbmp); ShowIcon24B(xm-15,ym+15,&birdbmp); CloseIcon(&birdbmp); *mx=xm; *my=ym; } void yidongbox(int *mx,int *my,int *mbutt) { ICON boxbmp; int xx0=*mx,yy0=*my; int xm,ym; read(&xm,&ym,mbutt); ReadIconBmp24B(&boxbmp,"tupian\\box.bmp"); ShowIcon24B(xx0-20,yy0+20,&boxbmp); ShowIcon24B(xm-20,ym+20,&boxbmp); CloseIcon(&boxbmp); *mx=xm; *my=ym; }
[ "836711600@qq.com" ]
836711600@qq.com
75a418ea5fb60dc2d022db19ee78b005c30d6dc5
3a7482501a5a944a1da139f043f9a44fd402885a
/plantilla3d/src/main.cpp
34230dadf16fe914a11e67cec9922c710e922eab
[]
no_license
flopezv95/Programacion3D
c0b9b433a6e2bc7d4fb67169eceb22bcd7b5b584
08820eedc196322ca4c4af6244224fa18c3ac451
refs/heads/master
2022-03-10T06:45:58.339400
2019-08-18T12:22:39
2019-08-18T12:22:39
188,873,794
1
0
null
null
null
null
UTF-8
C++
false
false
2,885
cpp
#ifdef _MSC_VER #pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") #endif #include "GL/glew.h" #include "../lib/glfw/glfw3.h" #include <iostream> #include <vector> #include "../project/Shaders.h" #include "../project/Buffer.h" #include <vector> #include "../glm/gtc/matrix_transform.hpp" // glm::translate, glm::rotate, glm::scale, glm::perspective #include "../glm/gtc/type_ptr.hpp" // glm::value_ptr #define SCREEN_WIDTH 800 #define SCREEN_HEIGHT 600 glm::mat4 calculateMatrix(float angle); //Soy Maluma baby int main() { // init glfw if ( !glfwInit() ) { std::cout << "could not initialize glfw" << std::endl; return -1; } // create window //glfwWindowHint(GLFW_RESIZABLE, false); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); glfwWindowHint(GLFW_SAMPLES, 8); GLFWwindow* win = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Practica1", nullptr, nullptr); if (!win) { std::cout << "could not create opengl window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(win); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cout << "could not initialize glew" << std::endl; return -1; } glm::vec3 color1(0.0f, 1.0f, 1.0f); std::vector<Vertex> myVertex; myVertex.push_back({ glm::vec3(-1.0f, -1.0f, 0.0f), color1 }); myVertex.push_back({ glm::vec3(1.0f, -1.0f, 0.0f), color1 }); myVertex.push_back({ glm::vec3(0.0f, 1.0f, 0.0f), color1 }); std::vector<GLuint> indices = { 0, 1, 2 }; Buffer *myBuffer = new Buffer(myVertex, indices); Shader *myShader = new Shader("data/vertex.glsl", "data/fragment.glsl"); // main loop float angle = 0; double lastTime = glfwGetTime(); while ( !glfwWindowShouldClose(win) && !glfwGetKey(win, GLFW_KEY_ESCAPE) ) { // get delta time float deltaTime = static_cast<float>(glfwGetTime() - lastTime); lastTime = glfwGetTime(); glClearColor(0.2, 0.2, 0.2, 1.0); glClear(GL_COLOR_BUFFER_BIT); myShader->use(); angle += (32*deltaTime); myShader->setMatrix(myShader->getLocation("mvp"), calculateMatrix(angle)); myBuffer->draw(myShader); glUseProgram(0); // refresh screen glfwSwapBuffers(win); glfwPollEvents(); } // shutdown glfwTerminate(); } glm::mat4 calculateMatrix(float angle) { glm::mat4 proj = glm::perspective<float>(glm::radians(45.0f), static_cast<float>(SCREEN_WIDTH) / SCREEN_HEIGHT, 0.1f, 100.0f); glm::mat4 view = glm::lookAt(glm::vec3(0.0f, 0.0f, 6.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 model = glm::translate(glm::mat4(), glm::vec3(2.0f, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(angle), glm::vec3(0.0f, 1.0f, 0.0f)); return proj * view * model; }
[ "felipe020112@gmail.com" ]
felipe020112@gmail.com
bb3af86c3b57fb27cd5a605c94f882aacc994076
9d7649ca193d5e62b6752ba4098c43eb5a16aa5f
/third_party/chromium_base/testing/gmock/include/gmock/gmock-generated-matchers.h
68af306b04078ceba0381f48b6ce5be4546a1928
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-3-Clause" ]
permissive
yiw2/ikran
6aafe7d2b6ede852bdcffd9fc3ac4613ee9976a8
cc8a3205cdbcb34f7807373db01c7f8b2558a639
refs/heads/master
2020-12-25T17:12:41.280090
2012-03-13T05:42:58
2012-03-13T05:42:58
3,196,837
4
1
null
null
null
null
UTF-8
C++
false
false
79,966
h
// This file was GENERATED by command: // pump.py gmock-generated-matchers.h.pump // DO NOT EDIT BY HAND!!! // Copyright 2008, 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: // // * 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 Google Inc. 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 // 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. // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used variadic matchers. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ #include <sstream> #include <string> #include <vector> #include "gmock/gmock-matchers.h" namespace testing { namespace internal { // The type of the i-th (0-based) field of Tuple. #define GMOCK_FIELD_TYPE_(Tuple, i) \ typename ::std::tr1::tuple_element<i, Tuple>::type // TupleFields<Tuple, k0, ..., kn> is for selecting fields from a // tuple of type Tuple. It has two members: // // type: a tuple type whose i-th field is the ki-th field of Tuple. // GetSelectedFields(t): returns fields k0, ..., and kn of t as a tuple. // // For example, in class TupleFields<tuple<bool, char, int>, 2, 0>, we have: // // type is tuple<int, bool>, and // GetSelectedFields(make_tuple(true, 'a', 42)) is (42, true). template <class Tuple, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1, int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1, int k9 = -1> class TupleFields; // This generic version is used when there are 10 selectors. template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, int k9> class TupleFields { public: typedef ::std::tr1::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6), GMOCK_FIELD_TYPE_(Tuple, k7), GMOCK_FIELD_TYPE_(Tuple, k8), GMOCK_FIELD_TYPE_(Tuple, k9)> type; static type GetSelectedFields(const Tuple& t) { using ::std::tr1::get; return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), get<k5>(t), get<k6>(t), get<k7>(t), get<k8>(t), get<k9>(t)); } }; // The following specialization is used for 0 ~ 9 selectors. template <class Tuple> class TupleFields<Tuple, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1> { public: typedef ::std::tr1::tuple<> type; static type GetSelectedFields(const Tuple& /* t */) { using ::std::tr1::get; return type(); } }; template <class Tuple, int k0> class TupleFields<Tuple, k0, -1, -1, -1, -1, -1, -1, -1, -1, -1> { public: typedef ::std::tr1::tuple<GMOCK_FIELD_TYPE_(Tuple, k0)> type; static type GetSelectedFields(const Tuple& t) { using ::std::tr1::get; return type(get<k0>(t)); } }; template <class Tuple, int k0, int k1> class TupleFields<Tuple, k0, k1, -1, -1, -1, -1, -1, -1, -1, -1> { public: typedef ::std::tr1::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1)> type; static type GetSelectedFields(const Tuple& t) { using ::std::tr1::get; return type(get<k0>(t), get<k1>(t)); } }; template <class Tuple, int k0, int k1, int k2> class TupleFields<Tuple, k0, k1, k2, -1, -1, -1, -1, -1, -1, -1> { public: typedef ::std::tr1::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2)> type; static type GetSelectedFields(const Tuple& t) { using ::std::tr1::get; return type(get<k0>(t), get<k1>(t), get<k2>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3> class TupleFields<Tuple, k0, k1, k2, k3, -1, -1, -1, -1, -1, -1> { public: typedef ::std::tr1::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3)> type; static type GetSelectedFields(const Tuple& t) { using ::std::tr1::get; return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4> class TupleFields<Tuple, k0, k1, k2, k3, k4, -1, -1, -1, -1, -1> { public: typedef ::std::tr1::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4)> type; static type GetSelectedFields(const Tuple& t) { using ::std::tr1::get; return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5> class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, -1, -1, -1, -1> { public: typedef ::std::tr1::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5)> type; static type GetSelectedFields(const Tuple& t) { using ::std::tr1::get; return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), get<k5>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6> class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, -1, -1, -1> { public: typedef ::std::tr1::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6)> type; static type GetSelectedFields(const Tuple& t) { using ::std::tr1::get; return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), get<k5>(t), get<k6>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6, int k7> class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, k7, -1, -1> { public: typedef ::std::tr1::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6), GMOCK_FIELD_TYPE_(Tuple, k7)> type; static type GetSelectedFields(const Tuple& t) { using ::std::tr1::get; return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), get<k5>(t), get<k6>(t), get<k7>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8> class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, -1> { public: typedef ::std::tr1::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6), GMOCK_FIELD_TYPE_(Tuple, k7), GMOCK_FIELD_TYPE_(Tuple, k8)> type; static type GetSelectedFields(const Tuple& t) { using ::std::tr1::get; return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), get<k5>(t), get<k6>(t), get<k7>(t), get<k8>(t)); } }; #undef GMOCK_FIELD_TYPE_ // Implements the Args() matcher. template <class ArgsTuple, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1, int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1, int k9 = -1> class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> { public: // ArgsTuple may have top-level const or reference modifiers. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(ArgsTuple) RawArgsTuple; typedef typename internal::TupleFields<RawArgsTuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, k9>::type SelectedArgs; typedef Matcher<const SelectedArgs&> MonomorphicInnerMatcher; template <typename InnerMatcher> explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher) : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {} virtual bool MatchAndExplain(ArgsTuple args, MatchResultListener* listener) const { const SelectedArgs& selected_args = GetSelectedArgs(args); if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args); PrintIndices(listener->stream()); *listener << "are " << PrintToString(selected_args); StringMatchResultListener inner_listener; const bool match = inner_matcher_.MatchAndExplain(selected_args, &inner_listener); PrintIfNotEmpty(inner_listener.str(), listener->stream()); return match; } virtual void DescribeTo(::std::ostream* os) const { *os << "are a tuple "; PrintIndices(os); inner_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "are a tuple "; PrintIndices(os); inner_matcher_.DescribeNegationTo(os); } private: static SelectedArgs GetSelectedArgs(ArgsTuple args) { return TupleFields<RawArgsTuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, k9>::GetSelectedFields(args); } // Prints the indices of the selected fields. static void PrintIndices(::std::ostream* os) { *os << "whose fields ("; const int indices[10] = { k0, k1, k2, k3, k4, k5, k6, k7, k8, k9 }; for (int i = 0; i < 10; i++) { if (indices[i] < 0) break; if (i >= 1) *os << ", "; *os << "#" << indices[i]; } *os << ") "; } const MonomorphicInnerMatcher inner_matcher_; GTEST_DISALLOW_ASSIGN_(ArgsMatcherImpl); }; template <class InnerMatcher, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1, int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1, int k9 = -1> class ArgsMatcher { public: explicit ArgsMatcher(const InnerMatcher& inner_matcher) : inner_matcher_(inner_matcher) {} template <typename ArgsTuple> operator Matcher<ArgsTuple>() const { return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, k9>(inner_matcher_)); } private: const InnerMatcher inner_matcher_; GTEST_DISALLOW_ASSIGN_(ArgsMatcher); }; // Implements ElementsAre() of 1-10 arguments. template <typename T1> class ElementsAreMatcher1 { public: explicit ElementsAreMatcher1(const T1& e1) : e1_(e1) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; // Nokia's Symbian Compiler has a nasty bug where the object put // in a one-element local array is not destructed when the array // goes out of scope. This leads to obvious badness as we've // added the linked_ptr in it to our other linked_ptrs list. // Hence we implement ElementsAreMatcher1 specially to avoid using // a local array. const Matcher<const Element&> matcher = MatcherCast<const Element&>(e1_); return MakeMatcher(new ElementsAreMatcherImpl<Container>(&matcher, 1)); } private: const T1& e1_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher1); }; template <typename T1, typename T2> class ElementsAreMatcher2 { public: ElementsAreMatcher2(const T1& e1, const T2& e2) : e1_(e1), e2_(e2) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; const Matcher<const Element&> matchers[] = { MatcherCast<const Element&>(e1_), MatcherCast<const Element&>(e2_), }; return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 2)); } private: const T1& e1_; const T2& e2_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher2); }; template <typename T1, typename T2, typename T3> class ElementsAreMatcher3 { public: ElementsAreMatcher3(const T1& e1, const T2& e2, const T3& e3) : e1_(e1), e2_(e2), e3_(e3) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; const Matcher<const Element&> matchers[] = { MatcherCast<const Element&>(e1_), MatcherCast<const Element&>(e2_), MatcherCast<const Element&>(e3_), }; return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 3)); } private: const T1& e1_; const T2& e2_; const T3& e3_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher3); }; template <typename T1, typename T2, typename T3, typename T4> class ElementsAreMatcher4 { public: ElementsAreMatcher4(const T1& e1, const T2& e2, const T3& e3, const T4& e4) : e1_(e1), e2_(e2), e3_(e3), e4_(e4) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; const Matcher<const Element&> matchers[] = { MatcherCast<const Element&>(e1_), MatcherCast<const Element&>(e2_), MatcherCast<const Element&>(e3_), MatcherCast<const Element&>(e4_), }; return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 4)); } private: const T1& e1_; const T2& e2_; const T3& e3_; const T4& e4_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher4); }; template <typename T1, typename T2, typename T3, typename T4, typename T5> class ElementsAreMatcher5 { public: ElementsAreMatcher5(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5) : e1_(e1), e2_(e2), e3_(e3), e4_(e4), e5_(e5) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; const Matcher<const Element&> matchers[] = { MatcherCast<const Element&>(e1_), MatcherCast<const Element&>(e2_), MatcherCast<const Element&>(e3_), MatcherCast<const Element&>(e4_), MatcherCast<const Element&>(e5_), }; return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 5)); } private: const T1& e1_; const T2& e2_; const T3& e3_; const T4& e4_; const T5& e5_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher5); }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> class ElementsAreMatcher6 { public: ElementsAreMatcher6(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6) : e1_(e1), e2_(e2), e3_(e3), e4_(e4), e5_(e5), e6_(e6) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; const Matcher<const Element&> matchers[] = { MatcherCast<const Element&>(e1_), MatcherCast<const Element&>(e2_), MatcherCast<const Element&>(e3_), MatcherCast<const Element&>(e4_), MatcherCast<const Element&>(e5_), MatcherCast<const Element&>(e6_), }; return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 6)); } private: const T1& e1_; const T2& e2_; const T3& e3_; const T4& e4_; const T5& e5_; const T6& e6_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher6); }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> class ElementsAreMatcher7 { public: ElementsAreMatcher7(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7) : e1_(e1), e2_(e2), e3_(e3), e4_(e4), e5_(e5), e6_(e6), e7_(e7) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; const Matcher<const Element&> matchers[] = { MatcherCast<const Element&>(e1_), MatcherCast<const Element&>(e2_), MatcherCast<const Element&>(e3_), MatcherCast<const Element&>(e4_), MatcherCast<const Element&>(e5_), MatcherCast<const Element&>(e6_), MatcherCast<const Element&>(e7_), }; return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 7)); } private: const T1& e1_; const T2& e2_; const T3& e3_; const T4& e4_; const T5& e5_; const T6& e6_; const T7& e7_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher7); }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> class ElementsAreMatcher8 { public: ElementsAreMatcher8(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, const T8& e8) : e1_(e1), e2_(e2), e3_(e3), e4_(e4), e5_(e5), e6_(e6), e7_(e7), e8_(e8) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; const Matcher<const Element&> matchers[] = { MatcherCast<const Element&>(e1_), MatcherCast<const Element&>(e2_), MatcherCast<const Element&>(e3_), MatcherCast<const Element&>(e4_), MatcherCast<const Element&>(e5_), MatcherCast<const Element&>(e6_), MatcherCast<const Element&>(e7_), MatcherCast<const Element&>(e8_), }; return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 8)); } private: const T1& e1_; const T2& e2_; const T3& e3_; const T4& e4_; const T5& e5_; const T6& e6_; const T7& e7_; const T8& e8_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher8); }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> class ElementsAreMatcher9 { public: ElementsAreMatcher9(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) : e1_(e1), e2_(e2), e3_(e3), e4_(e4), e5_(e5), e6_(e6), e7_(e7), e8_(e8), e9_(e9) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; const Matcher<const Element&> matchers[] = { MatcherCast<const Element&>(e1_), MatcherCast<const Element&>(e2_), MatcherCast<const Element&>(e3_), MatcherCast<const Element&>(e4_), MatcherCast<const Element&>(e5_), MatcherCast<const Element&>(e6_), MatcherCast<const Element&>(e7_), MatcherCast<const Element&>(e8_), MatcherCast<const Element&>(e9_), }; return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 9)); } private: const T1& e1_; const T2& e2_; const T3& e3_; const T4& e4_; const T5& e5_; const T6& e6_; const T7& e7_; const T8& e8_; const T9& e9_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher9); }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> class ElementsAreMatcher10 { public: ElementsAreMatcher10(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9, const T10& e10) : e1_(e1), e2_(e2), e3_(e3), e4_(e4), e5_(e5), e6_(e6), e7_(e7), e8_(e8), e9_(e9), e10_(e10) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; const Matcher<const Element&> matchers[] = { MatcherCast<const Element&>(e1_), MatcherCast<const Element&>(e2_), MatcherCast<const Element&>(e3_), MatcherCast<const Element&>(e4_), MatcherCast<const Element&>(e5_), MatcherCast<const Element&>(e6_), MatcherCast<const Element&>(e7_), MatcherCast<const Element&>(e8_), MatcherCast<const Element&>(e9_), MatcherCast<const Element&>(e10_), }; return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 10)); } private: const T1& e1_; const T2& e2_; const T3& e3_; const T4& e4_; const T5& e5_; const T6& e6_; const T7& e7_; const T8& e8_; const T9& e9_; const T10& e10_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher10); }; } // namespace internal // Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected // fields of it matches a_matcher. C++ doesn't support default // arguments for function templates, so we have to overload it. template <typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher>(matcher); } template <int k1, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1>(matcher); } template <int k1, int k2, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2>(matcher); } template <int k1, int k2, int k3, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3>(matcher); } template <int k1, int k2, int k3, int k4, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4>(matcher); } template <int k1, int k2, int k3, int k4, int k5, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5>(matcher); } template <int k1, int k2, int k3, int k4, int k5, int k6, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6>(matcher); } template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7>(matcher); } template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8>(matcher); } template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, int k9, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9>(matcher); } template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, int k9, int k10, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10>(matcher); } // ElementsAre(e0, e1, ..., e_n) matches an STL-style container with // (n + 1) elements, where the i-th element in the container must // match the i-th argument in the list. Each argument of // ElementsAre() can be either a value or a matcher. We support up to // 10 arguments. // // NOTE: Since ElementsAre() cares about the order of the elements, it // must not be used with containers whose elements's order is // undefined (e.g. hash_map). inline internal::ElementsAreMatcher0 ElementsAre() { return internal::ElementsAreMatcher0(); } template <typename T1> inline internal::ElementsAreMatcher1<T1> ElementsAre(const T1& e1) { return internal::ElementsAreMatcher1<T1>(e1); } template <typename T1, typename T2> inline internal::ElementsAreMatcher2<T1, T2> ElementsAre(const T1& e1, const T2& e2) { return internal::ElementsAreMatcher2<T1, T2>(e1, e2); } template <typename T1, typename T2, typename T3> inline internal::ElementsAreMatcher3<T1, T2, T3> ElementsAre(const T1& e1, const T2& e2, const T3& e3) { return internal::ElementsAreMatcher3<T1, T2, T3>(e1, e2, e3); } template <typename T1, typename T2, typename T3, typename T4> inline internal::ElementsAreMatcher4<T1, T2, T3, T4> ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) { return internal::ElementsAreMatcher4<T1, T2, T3, T4>(e1, e2, e3, e4); } template <typename T1, typename T2, typename T3, typename T4, typename T5> inline internal::ElementsAreMatcher5<T1, T2, T3, T4, T5> ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5) { return internal::ElementsAreMatcher5<T1, T2, T3, T4, T5>(e1, e2, e3, e4, e5); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> inline internal::ElementsAreMatcher6<T1, T2, T3, T4, T5, T6> ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6) { return internal::ElementsAreMatcher6<T1, T2, T3, T4, T5, T6>(e1, e2, e3, e4, e5, e6); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> inline internal::ElementsAreMatcher7<T1, T2, T3, T4, T5, T6, T7> ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7) { return internal::ElementsAreMatcher7<T1, T2, T3, T4, T5, T6, T7>(e1, e2, e3, e4, e5, e6, e7); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> inline internal::ElementsAreMatcher8<T1, T2, T3, T4, T5, T6, T7, T8> ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, const T8& e8) { return internal::ElementsAreMatcher8<T1, T2, T3, T4, T5, T6, T7, T8>(e1, e2, e3, e4, e5, e6, e7, e8); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> inline internal::ElementsAreMatcher9<T1, T2, T3, T4, T5, T6, T7, T8, T9> ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) { return internal::ElementsAreMatcher9<T1, T2, T3, T4, T5, T6, T7, T8, T9>(e1, e2, e3, e4, e5, e6, e7, e8, e9); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> inline internal::ElementsAreMatcher10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9, const T10& e10) { return internal::ElementsAreMatcher10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10); } // ElementsAreArray(array) and ElementAreArray(array, count) are like // ElementsAre(), except that they take an array of values or // matchers. The former form infers the size of 'array', which must // be a static C-style array. In the latter form, 'array' can either // be a static array or a pointer to a dynamically created array. template <typename T> inline internal::ElementsAreArrayMatcher<T> ElementsAreArray( const T* first, size_t count) { return internal::ElementsAreArrayMatcher<T>(first, count); } template <typename T, size_t N> inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(const T (&array)[N]) { return internal::ElementsAreArrayMatcher<T>(array, N); } // AllOf(m1, m2, ..., mk) matches any value that matches all of the given // sub-matchers. template <typename Matcher1, typename Matcher2> inline internal::BothOfMatcher<Matcher1, Matcher2> AllOf(Matcher1 m1, Matcher2 m2) { return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2); } template <typename Matcher1, typename Matcher2, typename Matcher3> inline internal::BothOfMatcher<Matcher1, internal::BothOfMatcher<Matcher2, Matcher3> > AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) { return AllOf(m1, AllOf(m2, m3)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4> inline internal::BothOfMatcher<Matcher1, internal::BothOfMatcher<Matcher2, internal::BothOfMatcher<Matcher3, Matcher4> > > AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) { return AllOf(m1, AllOf(m2, m3, m4)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4, typename Matcher5> inline internal::BothOfMatcher<Matcher1, internal::BothOfMatcher<Matcher2, internal::BothOfMatcher<Matcher3, internal::BothOfMatcher<Matcher4, Matcher5> > > > AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) { return AllOf(m1, AllOf(m2, m3, m4, m5)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4, typename Matcher5, typename Matcher6> inline internal::BothOfMatcher<Matcher1, internal::BothOfMatcher<Matcher2, internal::BothOfMatcher<Matcher3, internal::BothOfMatcher<Matcher4, internal::BothOfMatcher<Matcher5, Matcher6> > > > > AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5, Matcher6 m6) { return AllOf(m1, AllOf(m2, m3, m4, m5, m6)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4, typename Matcher5, typename Matcher6, typename Matcher7> inline internal::BothOfMatcher<Matcher1, internal::BothOfMatcher<Matcher2, internal::BothOfMatcher<Matcher3, internal::BothOfMatcher<Matcher4, internal::BothOfMatcher<Matcher5, internal::BothOfMatcher<Matcher6, Matcher7> > > > > > AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5, Matcher6 m6, Matcher7 m7) { return AllOf(m1, AllOf(m2, m3, m4, m5, m6, m7)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4, typename Matcher5, typename Matcher6, typename Matcher7, typename Matcher8> inline internal::BothOfMatcher<Matcher1, internal::BothOfMatcher<Matcher2, internal::BothOfMatcher<Matcher3, internal::BothOfMatcher<Matcher4, internal::BothOfMatcher<Matcher5, internal::BothOfMatcher<Matcher6, internal::BothOfMatcher<Matcher7, Matcher8> > > > > > > AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5, Matcher6 m6, Matcher7 m7, Matcher8 m8) { return AllOf(m1, AllOf(m2, m3, m4, m5, m6, m7, m8)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4, typename Matcher5, typename Matcher6, typename Matcher7, typename Matcher8, typename Matcher9> inline internal::BothOfMatcher<Matcher1, internal::BothOfMatcher<Matcher2, internal::BothOfMatcher<Matcher3, internal::BothOfMatcher<Matcher4, internal::BothOfMatcher<Matcher5, internal::BothOfMatcher<Matcher6, internal::BothOfMatcher<Matcher7, internal::BothOfMatcher<Matcher8, Matcher9> > > > > > > > AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5, Matcher6 m6, Matcher7 m7, Matcher8 m8, Matcher9 m9) { return AllOf(m1, AllOf(m2, m3, m4, m5, m6, m7, m8, m9)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4, typename Matcher5, typename Matcher6, typename Matcher7, typename Matcher8, typename Matcher9, typename Matcher10> inline internal::BothOfMatcher<Matcher1, internal::BothOfMatcher<Matcher2, internal::BothOfMatcher<Matcher3, internal::BothOfMatcher<Matcher4, internal::BothOfMatcher<Matcher5, internal::BothOfMatcher<Matcher6, internal::BothOfMatcher<Matcher7, internal::BothOfMatcher<Matcher8, internal::BothOfMatcher<Matcher9, Matcher10> > > > > > > > > AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5, Matcher6 m6, Matcher7 m7, Matcher8 m8, Matcher9 m9, Matcher10 m10) { return AllOf(m1, AllOf(m2, m3, m4, m5, m6, m7, m8, m9, m10)); } // AnyOf(m1, m2, ..., mk) matches any value that matches any of the given // sub-matchers. template <typename Matcher1, typename Matcher2> inline internal::EitherOfMatcher<Matcher1, Matcher2> AnyOf(Matcher1 m1, Matcher2 m2) { return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2); } template <typename Matcher1, typename Matcher2, typename Matcher3> inline internal::EitherOfMatcher<Matcher1, internal::EitherOfMatcher<Matcher2, Matcher3> > AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) { return AnyOf(m1, AnyOf(m2, m3)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4> inline internal::EitherOfMatcher<Matcher1, internal::EitherOfMatcher<Matcher2, internal::EitherOfMatcher<Matcher3, Matcher4> > > AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) { return AnyOf(m1, AnyOf(m2, m3, m4)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4, typename Matcher5> inline internal::EitherOfMatcher<Matcher1, internal::EitherOfMatcher<Matcher2, internal::EitherOfMatcher<Matcher3, internal::EitherOfMatcher<Matcher4, Matcher5> > > > AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) { return AnyOf(m1, AnyOf(m2, m3, m4, m5)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4, typename Matcher5, typename Matcher6> inline internal::EitherOfMatcher<Matcher1, internal::EitherOfMatcher<Matcher2, internal::EitherOfMatcher<Matcher3, internal::EitherOfMatcher<Matcher4, internal::EitherOfMatcher<Matcher5, Matcher6> > > > > AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5, Matcher6 m6) { return AnyOf(m1, AnyOf(m2, m3, m4, m5, m6)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4, typename Matcher5, typename Matcher6, typename Matcher7> inline internal::EitherOfMatcher<Matcher1, internal::EitherOfMatcher<Matcher2, internal::EitherOfMatcher<Matcher3, internal::EitherOfMatcher<Matcher4, internal::EitherOfMatcher<Matcher5, internal::EitherOfMatcher<Matcher6, Matcher7> > > > > > AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5, Matcher6 m6, Matcher7 m7) { return AnyOf(m1, AnyOf(m2, m3, m4, m5, m6, m7)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4, typename Matcher5, typename Matcher6, typename Matcher7, typename Matcher8> inline internal::EitherOfMatcher<Matcher1, internal::EitherOfMatcher<Matcher2, internal::EitherOfMatcher<Matcher3, internal::EitherOfMatcher<Matcher4, internal::EitherOfMatcher<Matcher5, internal::EitherOfMatcher<Matcher6, internal::EitherOfMatcher<Matcher7, Matcher8> > > > > > > AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5, Matcher6 m6, Matcher7 m7, Matcher8 m8) { return AnyOf(m1, AnyOf(m2, m3, m4, m5, m6, m7, m8)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4, typename Matcher5, typename Matcher6, typename Matcher7, typename Matcher8, typename Matcher9> inline internal::EitherOfMatcher<Matcher1, internal::EitherOfMatcher<Matcher2, internal::EitherOfMatcher<Matcher3, internal::EitherOfMatcher<Matcher4, internal::EitherOfMatcher<Matcher5, internal::EitherOfMatcher<Matcher6, internal::EitherOfMatcher<Matcher7, internal::EitherOfMatcher<Matcher8, Matcher9> > > > > > > > AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5, Matcher6 m6, Matcher7 m7, Matcher8 m8, Matcher9 m9) { return AnyOf(m1, AnyOf(m2, m3, m4, m5, m6, m7, m8, m9)); } template <typename Matcher1, typename Matcher2, typename Matcher3, typename Matcher4, typename Matcher5, typename Matcher6, typename Matcher7, typename Matcher8, typename Matcher9, typename Matcher10> inline internal::EitherOfMatcher<Matcher1, internal::EitherOfMatcher<Matcher2, internal::EitherOfMatcher<Matcher3, internal::EitherOfMatcher<Matcher4, internal::EitherOfMatcher<Matcher5, internal::EitherOfMatcher<Matcher6, internal::EitherOfMatcher<Matcher7, internal::EitherOfMatcher<Matcher8, internal::EitherOfMatcher<Matcher9, Matcher10> > > > > > > > > AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5, Matcher6 m6, Matcher7 m7, Matcher8 m8, Matcher9 m9, Matcher10 m10) { return AnyOf(m1, AnyOf(m2, m3, m4, m5, m6, m7, m8, m9, m10)); } } // namespace testing // The MATCHER* family of macros can be used in a namespace scope to // define custom matchers easily. // // Basic Usage // =========== // // The syntax // // MATCHER(name, description_string) { statements; } // // defines a matcher with the given name that executes the statements, // which must return a bool to indicate if the match succeeds. Inside // the statements, you can refer to the value being matched by 'arg', // and refer to its type by 'arg_type'. // // The description string documents what the matcher does, and is used // to generate the failure message when the match fails. Since a // MATCHER() is usually defined in a header file shared by multiple // C++ source files, we require the description to be a C-string // literal to avoid possible side effects. It can be empty, in which // case we'll use the sequence of words in the matcher name as the // description. // // For example: // // MATCHER(IsEven, "") { return (arg % 2) == 0; } // // allows you to write // // // Expects mock_foo.Bar(n) to be called where n is even. // EXPECT_CALL(mock_foo, Bar(IsEven())); // // or, // // // Verifies that the value of some_expression is even. // EXPECT_THAT(some_expression, IsEven()); // // If the above assertion fails, it will print something like: // // Value of: some_expression // Expected: is even // Actual: 7 // // where the description "is even" is automatically calculated from the // matcher name IsEven. // // Argument Type // ============= // // Note that the type of the value being matched (arg_type) is // determined by the context in which you use the matcher and is // supplied to you by the compiler, so you don't need to worry about // declaring it (nor can you). This allows the matcher to be // polymorphic. For example, IsEven() can be used to match any type // where the value of "(arg % 2) == 0" can be implicitly converted to // a bool. In the "Bar(IsEven())" example above, if method Bar() // takes an int, 'arg_type' will be int; if it takes an unsigned long, // 'arg_type' will be unsigned long; and so on. // // Parameterizing Matchers // ======================= // // Sometimes you'll want to parameterize the matcher. For that you // can use another macro: // // MATCHER_P(name, param_name, description_string) { statements; } // // For example: // // MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } // // will allow you to write: // // EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); // // which may lead to this message (assuming n is 10): // // Value of: Blah("a") // Expected: has absolute value 10 // Actual: -9 // // Note that both the matcher description and its parameter are // printed, making the message human-friendly. // // In the matcher definition body, you can write 'foo_type' to // reference the type of a parameter named 'foo'. For example, in the // body of MATCHER_P(HasAbsoluteValue, value) above, you can write // 'value_type' to refer to the type of 'value'. // // We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P10 to // support multi-parameter matchers. // // Describing Parameterized Matchers // ================================= // // The last argument to MATCHER*() is a string-typed expression. The // expression can reference all of the matcher's parameters and a // special bool-typed variable named 'negation'. When 'negation' is // false, the expression should evaluate to the matcher's description; // otherwise it should evaluate to the description of the negation of // the matcher. For example, // // using testing::PrintToString; // // MATCHER_P2(InClosedRange, low, hi, // string(negation ? "is not" : "is") + " in range [" + // PrintToString(low) + ", " + PrintToString(hi) + "]") { // return low <= arg && arg <= hi; // } // ... // EXPECT_THAT(3, InClosedRange(4, 6)); // EXPECT_THAT(3, Not(InClosedRange(2, 4))); // // would generate two failures that contain the text: // // Expected: is in range [4, 6] // ... // Expected: is not in range [2, 4] // // If you specify "" as the description, the failure message will // contain the sequence of words in the matcher name followed by the // parameter values printed as a tuple. For example, // // MATCHER_P2(InClosedRange, low, hi, "") { ... } // ... // EXPECT_THAT(3, InClosedRange(4, 6)); // EXPECT_THAT(3, Not(InClosedRange(2, 4))); // // would generate two failures that contain the text: // // Expected: in closed range (4, 6) // ... // Expected: not (in closed range (2, 4)) // // Types of Matcher Parameters // =========================== // // For the purpose of typing, you can view // // MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } // // as shorthand for // // template <typename p1_type, ..., typename pk_type> // FooMatcherPk<p1_type, ..., pk_type> // Foo(p1_type p1, ..., pk_type pk) { ... } // // When you write Foo(v1, ..., vk), the compiler infers the types of // the parameters v1, ..., and vk for you. If you are not happy with // the result of the type inference, you can specify the types by // explicitly instantiating the template, as in Foo<long, bool>(5, // false). As said earlier, you don't get to (or need to) specify // 'arg_type' as that's determined by the context in which the matcher // is used. You can assign the result of expression Foo(p1, ..., pk) // to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This // can be useful when composing matchers. // // While you can instantiate a matcher template with reference types, // passing the parameters by pointer usually makes your code more // readable. If, however, you still want to pass a parameter by // reference, be aware that in the failure message generated by the // matcher you will see the value of the referenced object but not its // address. // // Explaining Match Results // ======================== // // Sometimes the matcher description alone isn't enough to explain why // the match has failed or succeeded. For example, when expecting a // long string, it can be very helpful to also print the diff between // the expected string and the actual one. To achieve that, you can // optionally stream additional information to a special variable // named result_listener, whose type is a pointer to class // MatchResultListener: // // MATCHER_P(EqualsLongString, str, "") { // if (arg == str) return true; // // *result_listener << "the difference: " /// << DiffStrings(str, arg); // return false; // } // // Overloading Matchers // ==================== // // You can overload matchers with different numbers of parameters: // // MATCHER_P(Blah, a, description_string1) { ... } // MATCHER_P2(Blah, a, b, description_string2) { ... } // // Caveats // ======= // // When defining a new matcher, you should also consider implementing // MatcherInterface or using MakePolymorphicMatcher(). These // approaches require more work than the MATCHER* macros, but also // give you more control on the types of the value being matched and // the matcher parameters, which may leads to better compiler error // messages when the matcher is used wrong. They also allow // overloading matchers based on parameter types (as opposed to just // based on the number of parameters). // // MATCHER*() can only be used in a namespace scope. The reason is // that C++ doesn't yet allow function-local types to be used to // instantiate templates. The up-coming C++0x standard will fix this. // Once that's done, we'll consider supporting using MATCHER*() inside // a function. // // More Information // ================ // // To learn more about using these macros, please search for 'MATCHER' // on http://code.google.com/p/googlemock/wiki/CookBook. #define MATCHER(name, description)\ class name##Matcher {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl()\ {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name,\ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::std::tr1::tuple<>()));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>());\ }\ name##Matcher() {\ }\ private:\ GTEST_DISALLOW_ASSIGN_(name##Matcher);\ };\ inline name##Matcher name() {\ return name##Matcher();\ }\ template <typename arg_type>\ bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P(name, p0, description)\ template <typename p0##_type>\ class name##MatcherP {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ explicit gmock_Impl(p0##_type gmock_p0)\ : p0(gmock_p0) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name,\ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::std::tr1::tuple<p0##_type>(p0)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0));\ }\ name##MatcherP(p0##_type gmock_p0) : p0(gmock_p0) {\ }\ p0##_type p0;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP);\ };\ template <typename p0##_type>\ inline name##MatcherP<p0##_type> name(p0##_type p0) {\ return name##MatcherP<p0##_type>(p0);\ }\ template <typename p0##_type>\ template <typename arg_type>\ bool name##MatcherP<p0##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P2(name, p0, p1, description)\ template <typename p0##_type, typename p1##_type>\ class name##MatcherP2 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1)\ : p0(gmock_p0), p1(gmock_p1) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name,\ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::std::tr1::tuple<p0##_type, p1##_type>(p0, p1)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1));\ }\ name##MatcherP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ p1(gmock_p1) {\ }\ p0##_type p0;\ p1##_type p1;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP2);\ };\ template <typename p0##_type, typename p1##_type>\ inline name##MatcherP2<p0##_type, p1##_type> name(p0##_type p0, \ p1##_type p1) {\ return name##MatcherP2<p0##_type, p1##_type>(p0, p1);\ }\ template <typename p0##_type, typename p1##_type>\ template <typename arg_type>\ bool name##MatcherP2<p0##_type, \ p1##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P3(name, p0, p1, p2, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type>\ class name##MatcherP3 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name,\ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::std::tr1::tuple<p0##_type, p1##_type, p2##_type>(p0, p1, \ p2)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2));\ }\ name##MatcherP3(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP3);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type>\ inline name##MatcherP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \ p1##_type p1, p2##_type p2) {\ return name##MatcherP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type>\ template <typename arg_type>\ bool name##MatcherP3<p0##_type, p1##_type, \ p2##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P4(name, p0, p1, p2, p3, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type>\ class name##MatcherP4 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name,\ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::std::tr1::tuple<p0##_type, p1##_type, p2##_type, \ p3##_type>(p0, p1, p2, p3)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3));\ }\ name##MatcherP4(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \ p2(gmock_p2), p3(gmock_p3) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP4);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type>\ inline name##MatcherP4<p0##_type, p1##_type, p2##_type, \ p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \ p3##_type p3) {\ return name##MatcherP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, \ p1, p2, p3);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type>\ template <typename arg_type>\ bool name##MatcherP4<p0##_type, p1##_type, p2##_type, \ p3##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P5(name, p0, p1, p2, p3, p4, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type>\ class name##MatcherP5 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ p4(gmock_p4) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name,\ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::std::tr1::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type>(p0, p1, p2, p3, p4)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3, p4));\ }\ name##MatcherP5(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, \ p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP5);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type>\ inline name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ p4##_type p4) {\ return name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type>(p0, p1, p2, p3, p4);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type>\ template <typename arg_type>\ bool name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type>\ class name##MatcherP6 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ p4(gmock_p4), p5(gmock_p5) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name,\ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::std::tr1::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5));\ }\ name##MatcherP6(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP6);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type>\ inline name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \ p3##_type p3, p4##_type p4, p5##_type p5) {\ return name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type>\ template <typename arg_type>\ bool name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type>\ class name##MatcherP7 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name,\ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::std::tr1::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, \ p6)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6));\ }\ name##MatcherP7(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \ p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \ p6(gmock_p6) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP7);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type>\ inline name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \ p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ p6##_type p6) {\ return name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type>\ template <typename arg_type>\ bool name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type>\ class name##MatcherP8 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name,\ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::std::tr1::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, \ p3, p4, p5, p6, p7)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7));\ }\ name##MatcherP8(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, \ p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ p7(gmock_p7) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP8);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type>\ inline name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \ p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ p6##_type p6, p7##_type p7) {\ return name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \ p6, p7);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type>\ template <typename arg_type>\ bool name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type, \ p7##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type>\ class name##MatcherP9 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ p8(gmock_p8) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ p8##_type p8;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name,\ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::std::tr1::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, \ p8##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8));\ }\ name##MatcherP9(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ p8(gmock_p8) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ p8##_type p8;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP9);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type>\ inline name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, \ p8##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ p8##_type p8) {\ return name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \ p3, p4, p5, p6, p7, p8);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type>\ template <typename arg_type>\ bool name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type, p7##_type, \ p8##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type, \ typename p9##_type>\ class name##MatcherP10 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ p9##_type gmock_p9)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ p8(gmock_p8), p9(gmock_p9) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ p8##_type p8;\ p9##_type p9;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name,\ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::std::tr1::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ p9##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9));\ }\ name##MatcherP10(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \ p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ p8##_type p8;\ p9##_type p9;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP10);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type, \ typename p9##_type>\ inline name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ p9##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ p9##_type p9) {\ return name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \ p1, p2, p3, p4, p5, p6, p7, p8, p9);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type, \ typename p9##_type>\ template <typename arg_type>\ bool name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ p9##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
[ "ehugg@cisco.com" ]
ehugg@cisco.com
cd2783591dc948c4230fa0cfb216075b1e613ef1
2b6144aeefe48a5a9244c3560ffc91ed202f2fb6
/volna_init/config.hpp
8c25a114937f1607ea04417b431927c3327479e8
[ "BSD-2-Clause" ]
permissive
reguly/volna
b867a63c3bd09fa234264cb2d01b8d8dd353ae27
6656d994c75f93d0f29673a8fc0da10926fa8d4a
refs/heads/master
2023-08-19T07:19:35.315350
2022-11-05T19:46:49
2022-11-05T19:46:49
40,645,334
4
8
BSD-2-Clause
2021-11-15T13:16:52
2015-08-13T07:36:57
C++
UTF-8
C++
false
false
1,206
hpp
#ifndef CONFIG_H #define CONFIG_H #include <limits> #include <cassert> // #include <omp.h> // open MP header // #define NDEBUG // #define EIGEN_NO_DEBUG // #define BOOST_DISABLE_ASSERTS // #define EIGEN_VECTORIZE #define ORDER2 // Problem parameters unsigned int const neq = 3; // number of scalar equations unsigned int const ndim = 2; // ambient dimension // CURRENTLY NOT IN USE unsigned int const ncell = 3; // number of nodes in a mesh element unsigned int const nfacet = 2; // number of nodes in a facet #define RealType float // template defining a small value (used for testing for dry cells) // at compile time template<typename T> struct EPSILON { static T value() { return static_cast<T>(0); } }; // EPSILON specialization for floats template<> struct EPSILON<float> { static float value() { return 1e-6; } }; // EPSILON specialization for doubles template<> struct EPSILON<double> { static double value() { return 1e-11; } }; RealType const EPS = EPSILON<RealType>::value(); RealType const INFTY = std::numeric_limits<RealType>::max(); RealType const MINUS_INFTY = std::numeric_limits<RealType>::min(); int const MAXINT = std::numeric_limits<int>::max(); #endif // CONFIG_H
[ "regulyistvan@gmail.com" ]
regulyistvan@gmail.com
3c34948f3388dfeff7867ff28f4d71ed747a8228
fbbc524d836b62cde790284fbf50e5bb1d85c130
/private/TableHeaderProxyModel.h
785bf979ba42a724a61736abc03a4cc5dd3b6a38
[ "MIT" ]
permissive
Izowiuz/iz-sql-tableview
1626d9919020efb181e844ac64ab3dd1d8c03f46
5448b8e4e022f19804363b248822fcdef7001fe3
refs/heads/master
2020-04-16T20:48:56.454638
2019-07-25T19:28:46
2019-07-25T19:28:46
165,907,273
2
1
null
null
null
null
UTF-8
C++
false
false
2,093
h
#ifndef IZSQLTABLEVIEW_TABLEHEADERPROXYMODEL_H #define IZSQLTABLEVIEW_TABLEHEADERPROXYMODEL_H #include <QSortFilterProxyModel> namespace IzSQLTableView { class TableHeaderModel; class SQLTableViewImpl; class TableHeaderProxyModel : public QSortFilterProxyModel { Q_OBJECT Q_DISABLE_COPY(TableHeaderProxyModel) // source model for this proxy Q_PROPERTY(TableHeaderModel* source READ source CONSTANT FINAL) public: // ctor explicit TableHeaderProxyModel(SQLTableViewImpl* tableView, QObject* parent); // returns internal m_sourceModel Q_INVOKABLE TableHeaderModel* source() const; // QAbstractProxyModel interface start void setSourceModel(QAbstractItemModel* sourceModel) override; // QAbstractProxyModel interface end // returns source row for given proxy column or -1 if invalid index was requested Q_INVOKABLE int sourceRow(int proxyRow) const; // returns source column for given proxy column or -1 if invalid index was requested Q_INVOKABLE int sourceColumn(int proxyColumn) const; // returns proxy row for given source row or -1 if invalid index was requested Q_INVOKABLE int proxyRow(int sourceRow) const; // returns proxy column for given source column or -1 if invalid index was requested Q_INVOKABLE int proxyColumn(int sourceColumn) const; // used to sort given column Q_INVOKABLE bool sortColumn(int column); // used to apply filter to a given column Q_INVOKABLE bool setColumnFilter(int column, const QString& filterValue); // used to set width for a given column Q_INVOKABLE bool setColumnWidth(int column, qreal columnWidth); // used to set visibility for given column Q_INVOKABLE bool setColumnVisibility(int column, bool visibility); private: // handler to the internal model TableHeaderModel* m_headerModel; protected: // QSortFilterProxyModel interface start bool filterAcceptsColumn(int source_column, const QModelIndex& source_parent) const override; // QSortFilterProxyModel interface end }; } // namespace IzSQLTableView #endif // IZSQLTABLEVIEW_TABLEHEADERPROXYMODEL_H
[ "izowiuz@gmail.com" ]
izowiuz@gmail.com
a8b574f110b89146d4826c90e1fc6c4e8ae23b30
6a20b880263ae749da7c6fa5b73dbc83d90def91
/getTrie/Trie.cpp
06c0681a9405ef276d2f79c47794e7dfe7a8aa85
[]
no_license
yinizhizhu/NLP
3c097fe6de6b2076ddeac3ac9467afcb3c200b6c
fa7b8f7477315b561ae4b60bef9cd98b4cf5e4f6
refs/heads/master
2021-01-15T13:29:23.148962
2016-08-04T02:06:38
2016-08-04T02:06:38
62,943,652
2
0
null
null
null
null
UTF-8
C++
false
false
14,333
cpp
#include "../h/Trie.h" #define OUT //#define OUTSYMBOL #ifdef OUTSYMBOL ofstream outSymbol("RESULT/symbol.txt"); #endif #ifdef OUT ofstream out("RESULT/res.txt"); #endif TrieNode::TrieNode() //Initial { pre = NULL; next = new NextMap; if (next == NULL) { cout << "The room is not enough for TrieNode!" << endl; return; } dataValue.counter = 0; return; } TrieNode::~TrieNode() //free the room { delete next; return; } TrieNode* TrieNode::findNext(Unicode word) // get the next TrieNode { NextMap::const_iterator iter = next->find(word); if (iter == next->end()) return NULL; return iter->second; } Trie::Trie() //initial { root = new TrieNode; if (root == NULL) { cout << "The room is not enough for root!" << endl; return; } totalB = totalM = totalE = totalS = 0; totalWord = 0; totalWords = 0; return; } Trie::~Trie() // free the room { cout << "In delete Trie" << endl; TrieNode* tmp = NULL; queue<TrieNode*> container; container.push(root); unordered_map<Unicode, TrieNode*>::iterator moveIter, endIter; while (!container.empty()) { size_t i = 0, len = container.size(); for (; i < len; i++) { tmp = container.front(); if (tmp) { moveIter = tmp->next->begin(); endIter = tmp->next->end(); for (; moveIter != endIter; moveIter++) container.push(moveIter->second); tmp->next->clear(); } container.pop(); //pop the front element of the queue delete tmp; } } //out << "The total number of word is: " << totalWord << endl; //out << "The total number of words is: " << totalWords << endl; #ifdef OUTSYMBOL outSymbol.close(); #endif cout << "Out delete Trie" << endl; return; } void Trie::build() //build up the Trie Tree { cout << "In build" << endl; char tmp[3]; tmp[2] = 0; vector<Unicode> words; size_t len1 = 0, len2 = 0, len; ifstream in("trainingData.txt"); string container; while (!in.eof()) { getline(in, container); len = container.size(); for (size_t i = 0; i < len;) { tmp[0] = container[i]; if (getSerialOne(tmp[0]) == 0) { if (container[i + 1] == 'w' && container[i] == '/') { #ifdef OUTSYMBOL insertTrie(words); #endif words.clear(); len1 = len2 = 0; } else { if (!words.empty()) { totalWords++; //count the words #ifndef OUTSYMBOL insertTrie(words); len2 = insertWordContainer(words); #endif handleBS(len1, len2); len1 = len2; words.clear(); } } do { i++; } while (getSerialOne(container[i]) == 0 && i < len); } else { tmp[1] = container[i + 1]; words.push_back(charToUni(tmp)); i += 2; } } } in.close(); cout << "Out build" << endl; return; } void Trie::handleBS(size_t len1, size_t len2) { if (len1 == 0) { if (len2 == 1) totalSF++; else totalBF++; } else if (len1 == 1) //S { if (len2 == 1) //S->S totalSS++; else //S->B totalSB++; } else //E { if (len2 == 1) //E->S totalES++; else //E->B totalEB++; } return; } void Trie::addDict() { cout << "In addDict" << endl; char tmp[3]; tmp[2] = 0; vector<Unicode> words; ifstream in("dictTrain.txt"); string container; while (!in.eof()) { getline(in, container); for (size_t i = 0; i < container.size();) { tmp[0] = container[i]; tmp[1] = container[i + 1]; words.push_back(charToUni(tmp)); i += 2; if (0 == getSerialOne(container[i])) break; } insertTrie(words); words.clear(); } in.close(); cout << "out addDict" << endl; return; } size_t Trie::getDepth(vector<Unicode>& words, vector<size_t>& T, size_t start) { TrieNode *move = root; size_t i, counter, maxC, maxT = 1, len = words.size(); maxC = counter = 0; for (i = start; i < len; i++) { move = move->findNext(words[i]); if (move == NULL) { T[start] = maxT; return maxC; } counter++; if (move->dataValue.counter > 0) { maxC = counter; maxT = move->dataValue.counter; } } T[start] = maxT; return maxC; } bool Trie::checkI(size_t i, size_t lenI, vector<size_t>& posContainer) { size_t tmpI; size_t move = 0, len = posContainer.size(); for (; move < len; move++) { tmpI = posContainer[move]; if (i < tmpI && (i + lenI) > tmpI) return false; } return true; } void Trie::opWithMaxLen(vector<size_t>& maxLen, vector<size_t>& T) { set<size_t>::iterator iter; set<size_t> index; vector<size_t> posContainer; size_t maxP; size_t i, tmpI, len = maxLen.size(); for (i = 0; i < len; i++) index.insert(i); while (!index.empty()) { maxP = 10000; iter = index.begin(); for (; iter != index.end(); iter++) { tmpI = *iter; if (checkI(tmpI, maxLen[tmpI], posContainer)) { if (maxP == 10000) { maxP = tmpI; } else { if (maxLen[tmpI] > maxLen[maxP]) maxP = tmpI; else if (maxLen[tmpI] == maxLen[maxP] && maxLen[tmpI] == 2) { if (T[tmpI] > T[maxP]) { maxP = tmpI; } } } } } if (maxP == 10000 || maxLen[maxP] < 2) return; posContainer.push_back(maxP); for (i = 1; i < maxLen[maxP]; i++) { maxLen[maxP + i] = 0; index.erase(maxP + i); } index.erase(maxP); //delete the index from the ready set if (maxP > 0 && 2 == maxLen[maxP - 1]) maxLen[maxP - 1] = 1; } return; } void Trie::opWithDict(vector<Unicode>& words, vector<char>& state) { vector<size_t> T; vector<size_t> maxLen; size_t i, j, len = words.size(); T.resize(len); state.resize(len); for (i = 0; i < len; i++) { maxLen.push_back(getDepth(words, T, i)); } opWithMaxLen(maxLen, T); for (i = 0; i < len;) { if (maxLen[i] >= 2) { state[i] = 'B'; for (j = 1; j < (maxLen[i] - 1); j++) state[i + j] = 'M'; state[i + j] = 'E'; i += maxLen[i]; } else { state[i] = 'N'; i++; } } //for (i = 0; i < (len - 1); i++) //try to opitmise //{ // if (state[i] == 'B' && state[i + 1] == 'B') // state[i+1] = 'S'; // else if (state[i] == 'E' && state[i + 1] == 'E') // state[i+1] = 'S'; //} return; } TrieNode* Trie::findTrieNode(const vector<Unicode>& words) //get TrieNode of the words { TrieNode *move = root; size_t i = 0, len = words.size(); for (; i < len; i++) { move = move->findNext(words[i]); if (move == NULL) return NULL; } return move; } void Trie::insertTrie(const vector<Unicode>& words) //insert the words into the Trie { if (words.size() == 0) return; TrieNode *pre = NULL; TrieNode *cur = findTrieNode(words); size_t pos = 0, len = words.size(); totalWord += len;//count the word if (cur) { if (cur->dataValue.counter > 0) cur->dataValue.word = words.back(); cur->dataValue.counter++; return; } else { pre = cur = root; while (cur->next->size()) { cur = cur->findNext(words[pos]); if (cur) { pre = cur; pos++; } else break; } for (; pos < len - 1; pos++) //step by step { cur = new TrieNode; if (cur == NULL) { cout << "The room is not enough for cur!" << endl; return; } cur->pre = pre; cur->dataValue.word = words[pos]; pre->next->insert(unordered_map<Unicode, TrieNode*>::value_type(words[pos], cur)); pre = cur; } cur = new TrieNode; //finish the last step if (cur == NULL) { cout << "The room is not enough for cur!" << endl; return; } cur->pre = pre; cur->dataValue.word = words[pos]; cur->dataValue.counter++; pre->next->insert(unordered_map<Unicode, TrieNode*>::value_type(words[pos], cur)); } return; } size_t Trie::insertWordContainer(const vector<Unicode>& words) { size_t i = 0, len = words.size(); if (len == 1) { insertContainer(words[i], 3); //Single totalS++; } else if (len > 1) { insertContainer(words[i], 0); //Begin totalB++; if (len == 2) totalBE++; //BE else { totalBM++; //BM totalMM += len - 3; //MM totalME++; //ME } for (i = 1; i < (len - 1); i++) { insertContainer(words[i], 1); //Middle totalM++; } insertContainer(words[i], 2); //End totalE++; } return len; } void Trie::insertContainer(const Unicode& word, size_t tag) { unordered_map<Unicode, size_t>::iterator iter; iter = wordContainer.find(word); //wordContainer if (iter == wordContainer.end()) wordContainer.insert(unordered_map<Unicode, size_t>::value_type(word, 1)); else iter->second++; if (tag == 0) { iter = BContainer.find(word); //BContainer if (iter == BContainer.end()) BContainer.insert(unordered_map<Unicode, size_t>::value_type(word, 1)); else iter->second++; } else if (tag == 1) { iter = MContainer.find(word); //MContainer if (iter == MContainer.end()) MContainer.insert(unordered_map<Unicode, size_t>::value_type(word, 1)); else iter->second++; } else if (tag == 2) { iter = EContainer.find(word); //EContainer if (iter == EContainer.end()) EContainer.insert(unordered_map<Unicode, size_t>::value_type(word, 1)); else iter->second++; } else if (tag == 3) { iter = SContainer.find(word); //SContainer if (iter == SContainer.end()) SContainer.insert(unordered_map<Unicode, size_t>::value_type(word, 1)); else iter->second++; } return; } void Trie::deleteNode(TrieNode* node) //delete the all the nodes(Trie tree) { unordered_map<Unicode, TrieNode*>::iterator iter = node->next->begin(); for (; iter != node->next->end(); iter++) deleteNode(iter->second); delete node; return; } void Trie::showTrie(TrieNode *node, vector<TrieNode*>& words) //show each word of Trie { TrieNode *move; if (node) move = node; else move = root; if (move->next->size() == 0) { if (!words.empty()) { #ifdef OUTSYMBOL outSymbol << words.size() << " "; #endif for (size_t i = 0; i < words.size(); i++) showTrieNode(words[i]); //cout << endl; #ifdef OUTSYMBOL outSymbol<<endl; #endif #ifdef OUT out << endl; #endif } return; } unordered_map<Unicode, TrieNode*>::iterator iter = move->next->begin(); for (; iter != move->next->end(); iter++) { words.push_back(iter->second); showTrie(iter->second, words); words.pop_back(); } return; } void Trie::showTrieNode(TrieNode *node) //show the content of the TrieNode { char tmp[3]; UniToChar(node->dataValue.word, tmp); //cout << tmp << ": " << node->dataValue.counter << ", "; #ifdef OUTSYMBOL outSymbol << tmp; #endif #ifdef OUT out << tmp << ": " << node->dataValue.counter << ", "; #endif return; } void Trie::showContainer() { char tmp[3]; unordered_map<Unicode, size_t>::iterator iter; iter = wordContainer.begin(); #ifdef OUT out << wordContainer.size() << endl; #endif for (; iter != wordContainer.end(); iter++) { UniToChar(iter->first, tmp); //cout << tmp << ": " << iter->second << ","; #ifdef OUT out << tmp << endl; #endif } #ifdef OUT out << BContainer.size() << endl; #endif iter = BContainer.begin(); for (; iter != BContainer.end(); iter++) { UniToChar(iter->first, tmp); //cout << tmp << ": " << iter->second << ","; #ifdef OUT out << tmp << " " << setprecision(16) << log(double(iter->second*1.0 / totalWord)) << endl; #endif } //cout << endl; #ifdef OUT out << MContainer.size() << endl; #endif iter = MContainer.begin(); for (; iter != MContainer.end(); iter++) { UniToChar(iter->first, tmp); //cout << tmp << ": " << iter->second << ","; #ifdef OUT out << tmp << " " << setprecision(16) << log(double(iter->second*1.0 / totalWord)) << endl; #endif } //cout << endl; #ifdef OUT out << EContainer.size() << endl; #endif iter = EContainer.begin(); for (; iter != EContainer.end(); iter++) { UniToChar(iter->first, tmp); //cout << tmp << ": " << iter->second << ","; #ifdef OUT out << tmp << " " << setprecision(16) << log(double(iter->second*1.0 / totalWord)) << endl; #endif } //cout << endl; #ifdef OUT out << SContainer.size() << endl; #endif iter = SContainer.begin(); for (; iter != SContainer.end(); iter++) { UniToChar(iter->first, tmp); //cout << tmp << ": " << iter->second << ","; #ifdef OUT out << tmp << " " << setprecision(16) << log(double(iter->second*1.0 / totalWord)) << endl; #endif } #ifdef OUT out << "4"<< endl; out << "-3.14e+100 " << setprecision(16) << log(double(totalBM*1.0 / totalB)) << " " << setprecision(16) << log(double(totalBE*1.0 / totalB)) << " -3.14e+100 " << endl; out << "-3.14e+100 " << setprecision(16) << log(double(totalMM*1.0 / totalM)) << " " << setprecision(16) << log(double(totalME*1.0 / totalM)) << " -3.14e+100 " << endl; out << setprecision(16) << log(double(totalEB*1.0 / totalE)) << " -3.14e+100 -3.14e+100 " << setprecision(16) << log(double(totalES*1.0 / totalE)) << " " << endl; out << setprecision(16) << log(double(totalSB*1.0 / totalS)) << " -3.14e+100 -3.14e+100 " << setprecision(16) << log(double(totalSS*1.0 / totalS)) << " " << endl; out << "1" << endl; out << setprecision(16) << log(double(totalBF*1.0 / totalWord)) << " -3.14e+100 -3.14e+100 " << setprecision(16) << log(double(totalSF*1.0 / totalWord)) << " " << endl; #endif #ifdef OUT out.close(); #endif return; } void Trie::showWords(vector<Unicode>& words) { char tmp[3]; size_t i, len = words.size(); for (i = 0; i < len; i++) { UniToChar(words[i], tmp); cout << tmp; } return; } Unicode charToUni(char tmp[3]) //Unicode into two chars { return (((Unicode)tmp[0] << 8) | ((Unicode)tmp[1] & 0x00FF)); } void UniToChar(Unicode word, char tmp[3]) //two chars into Unicode { tmp[0] = (word >> 8); tmp[1] = (word & 0xFF); tmp[2] = '\0'; return; } int getSerialOne(char byte) //calculate the number of first continuous one { int counter = 0; unsigned int tag = 1 << 7; while (byte & tag) { counter++; tag = tag >> 1; } return counter; } void test() //for test the reading data from file { ifstream in("testData.txt"); string container; char tmp[3]; tmp[2] = 0; while (!in.eof()) { getline(in, container); for (unsigned int i = 0; i < container.size();) { tmp[0] = container[i]; if (getSerialOne(tmp[0]) == 0) cout << " " << dec << i++ << ": " << tmp[0] << endl; else { tmp[1] = container[i + 1]; Unicode res = charToUni(tmp); UniToChar(res, tmp); cout << tmp << ": " << getSerialOne(tmp[0]) << "-->>" << getSerialOne(container[i]) << endl; i += 2; } } cout << container << endl; } in.close(); return; }
[ "lijiahe19941013@sina.cn" ]
lijiahe19941013@sina.cn
4406692ad5ececd682354fd8f4ca7e355af6c802
88ae8695987ada722184307301e221e1ba3cc2fa
/chrome/browser/ui/views/location_bar/custom_tab_bar_view_browsertest.cc
13bca4de68aaa6d33ce38d9b5c114823b996164b
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
27,764
cc
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/memory/raw_ptr.h" #include "base/strings/string_util.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "chrome/browser/ui/web_applications/app_browser_controller.h" #include "chrome/browser/ui/web_applications/web_app_controller_browsertest.h" #include "chrome/browser/web_applications/web_app_install_info.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/security_interstitials/content/security_interstitial_controller_client.h" #include "components/security_interstitials/content/security_interstitial_page.h" #include "components/security_interstitials/content/security_interstitial_tab_helper.h" #include "components/security_interstitials/content/settings_page_helper.h" #include "components/security_interstitials/core/metrics_helper.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/notification_service.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_mock_cert_verifier.h" #include "content/public/test/test_navigation_observer.h" #include "net/dns/mock_host_resolver.h" #include "third_party/blink/public/common/features.h" #include "ui/base/clipboard/clipboard.h" #include "ui/views/controls/button/image_button.h" namespace { // Waits until the title of any tab in the browser for |contents| has the title // |target_title|. class TestTitleObserver : public TabStripModelObserver { public: // Create a new TitleObserver for the browser of |contents|, waiting for // |target_title|. TestTitleObserver(content::WebContents* contents, std::u16string target_title) : contents_(contents), target_title_(target_title) { browser_ = chrome::FindBrowserWithWebContents(contents_); browser_->tab_strip_model()->AddObserver(this); } // Run a loop, blocking until a tab has the title |target_title|. void Wait() { if (seen_target_title_) return; awaiter_.Run(); } // TabstripModelObserver: void TabChangedAt(content::WebContents* contents, int index, TabChangeType change_type) override { content::NavigationEntry* entry = contents->GetController().GetVisibleEntry(); std::u16string title = entry ? entry->GetTitle() : std::u16string(); if (title != target_title_) return; seen_target_title_ = true; awaiter_.Quit(); } private: bool seen_target_title_ = false; raw_ptr<content::WebContents, DanglingUntriaged> contents_; raw_ptr<Browser, DanglingUntriaged> browser_; std::u16string target_title_; base::RunLoop awaiter_; }; // Opens a new popup window from |web_contents| on |target_url| and returns // the Browser it opened in. Browser* OpenPopup(content::WebContents* web_contents, const GURL& target_url) { ui_test_utils::BrowserChangeObserver browser_change_observer( /*browser=*/nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kAdded); content::TestNavigationObserver nav_observer(target_url); nav_observer.StartWatchingNewWebContents(); std::string script = "window.open('" + target_url.spec() + "', 'popup', 'width=400 height=400');"; EXPECT_TRUE(content::ExecJs(web_contents, script)); nav_observer.Wait(); return browser_change_observer.Wait(); } // Navigates to |target_url| and waits for navigation to complete. void NavigateAndWait(content::WebContents* web_contents, const GURL& target_url) { content::TestNavigationObserver nav_observer(web_contents); std::string script = "window.location = '" + target_url.spec() + "';"; EXPECT_TRUE(content::ExecJs(web_contents, script)); nav_observer.Wait(); } // Navigates |web_contents| to |location|, waits for navigation to complete // and then sets document.title to be |title| and waits for the change // to propogate. void SetTitleAndLocation(content::WebContents* web_contents, const std::u16string title, const GURL& location) { NavigateAndWait(web_contents, location); TestTitleObserver title_observer(web_contents, title); std::string script = "document.title = '" + base::UTF16ToASCII(title) + "';"; EXPECT_TRUE(content::ExecJs(web_contents, script)); title_observer.Wait(); } // An interstitial page that requests URL hiding class UrlHidingInterstitialPage : public security_interstitials::SecurityInterstitialPage { public: UrlHidingInterstitialPage(content::WebContents* web_contents, const GURL& request_url) : security_interstitials::SecurityInterstitialPage( web_contents, request_url, std::make_unique< security_interstitials::SecurityInterstitialControllerClient>( web_contents, nullptr, nullptr, base::i18n::GetConfiguredLocale(), GURL(), nullptr /* settings_page_helper */)) {} void OnInterstitialClosing() override {} bool ShouldDisplayURL() const override { return false; } protected: void PopulateInterstitialStrings(base::Value::Dict& load_time_data) override { } }; // An observer that associates a URL-hiding interstitial when a page loads when // |install_interstitial| is true. class UrlHidingWebContentsObserver : public content::WebContentsObserver { public: explicit UrlHidingWebContentsObserver(content::WebContents* contents) : content::WebContentsObserver(contents), install_interstitial_(true) {} void DidFinishNavigation(content::NavigationHandle* handle) override { if (!install_interstitial_) return; security_interstitials::SecurityInterstitialTabHelper:: AssociateBlockingPage(handle, std::make_unique<UrlHidingInterstitialPage>( web_contents(), handle->GetURL())); } void StopBlocking() { install_interstitial_ = false; } private: bool install_interstitial_; }; } // namespace class CustomTabBarViewBrowserTest : public web_app::WebAppControllerBrowserTest { public: CustomTabBarViewBrowserTest() = default; CustomTabBarViewBrowserTest(const CustomTabBarViewBrowserTest&) = delete; CustomTabBarViewBrowserTest& operator=(const CustomTabBarViewBrowserTest&) = delete; ~CustomTabBarViewBrowserTest() override = default; protected: void SetUpCommandLine(base::CommandLine* command_line) override { web_app::WebAppControllerBrowserTest::SetUpCommandLine(command_line); // Browser will both run and display insecure content. command_line->AppendSwitch(switches::kAllowRunningInsecureContent); } void SetUp() override { feature_list_.InitAndDisableFeature( blink::features::kMixedContentAutoupgrade); web_app::WebAppControllerBrowserTest::SetUp(); } void SetUpOnMainThread() override { web_app::WebAppControllerBrowserTest::SetUpOnMainThread(); browser_view_ = BrowserView::GetBrowserViewForBrowser(browser()); location_bar_ = browser_view_->GetLocationBarView(); custom_tab_bar_ = browser_view_->toolbar()->custom_tab_bar(); } void InstallPWA(const GURL& start_url) { auto web_app_info = std::make_unique<WebAppInstallInfo>(); web_app_info->start_url = start_url; web_app_info->scope = start_url.GetWithoutFilename(); web_app_info->user_display_mode = web_app::mojom::UserDisplayMode::kStandalone; Install(std::move(web_app_info)); } void InstallBookmark(const GURL& start_url) { auto web_app_info = std::make_unique<WebAppInstallInfo>(); web_app_info->start_url = start_url; web_app_info->scope = start_url.DeprecatedGetOriginAsURL(); web_app_info->user_display_mode = web_app::mojom::UserDisplayMode::kStandalone; Install(std::move(web_app_info)); } raw_ptr<BrowserView, DanglingUntriaged> browser_view_; raw_ptr<LocationBarView, DanglingUntriaged> location_bar_; raw_ptr<CustomTabBarView, DanglingUntriaged> custom_tab_bar_; raw_ptr<Browser, DanglingUntriaged> app_browser_ = nullptr; raw_ptr<web_app::AppBrowserController, DanglingUntriaged> app_controller_ = nullptr; private: void Install(std::unique_ptr<WebAppInstallInfo> web_app_info) { const GURL start_url = web_app_info->start_url; web_app::AppId app_id = InstallWebApp(std::move(web_app_info)); ui_test_utils::UrlLoadObserver url_observer( start_url, content::NotificationService::AllSources()); app_browser_ = LaunchWebAppBrowser(app_id); url_observer.Wait(); DCHECK(app_browser_); DCHECK(app_browser_ != browser()); app_controller_ = app_browser_->app_controller(); DCHECK(app_controller_); } base::test::ScopedFeatureList feature_list_; }; // Check the custom tab bar is not instantiated for a tabbed browser window. IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, IsNotCreatedInTabbedBrowser) { EXPECT_TRUE(browser()->is_type_normal()); EXPECT_TRUE(browser_view_->GetIsNormalType()); EXPECT_FALSE(custom_tab_bar_); } IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, IsNotCreatedInPopup) { Browser* popup = OpenPopup(browser_view_->GetActiveWebContents(), GURL("http://example.com")); EXPECT_TRUE(popup); BrowserView* popup_view = BrowserView::GetBrowserViewForBrowser(popup); // The popup should be in a new window. EXPECT_NE(browser_view_, popup_view); // Popups are not the normal browser view. EXPECT_FALSE(popup_view->GetIsNormalType()); EXPECT_TRUE(popup->is_type_popup()); // Popups should not have a custom tab bar view. EXPECT_FALSE(popup_view->toolbar()->custom_tab_bar()); } IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, BackToAppButtonIsNotVisibleInOutOfScopePopups) { const GURL app_url = https_server()->GetURL("app.com", "/ssl/google.html"); const GURL out_of_scope_url = GURL("https://example.com"); InstallBookmark(app_url); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); Browser* popup_browser = OpenPopup(app_view->GetActiveWebContents(), out_of_scope_url); EXPECT_TRUE(popup_browser->is_type_app_popup()); // Out of scope, so custom tab bar should be shown. EXPECT_TRUE(popup_browser->app_controller()->ShouldShowCustomTabBar()); // As the popup was opened out of scope the close button should not be shown. EXPECT_FALSE(BrowserView::GetBrowserViewForBrowser(popup_browser) ->toolbar() ->custom_tab_bar() ->close_button_for_testing() ->GetVisible()); } // Check the custom tab will be used for a Desktop PWA. IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, IsUsedForDesktopPWA) { ASSERT_TRUE(embedded_test_server()->Start()); const GURL url = https_server()->GetURL("app.com", "/ssl/google.html"); InstallPWA(url); EXPECT_TRUE(app_browser_); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); EXPECT_NE(app_view, browser_view_); EXPECT_FALSE(app_view->GetIsNormalType()); EXPECT_TRUE(app_browser_->is_type_app()); // Custom tab bar should be created. EXPECT_TRUE(app_view->toolbar()->custom_tab_bar()); } // Check the CustomTabBarView appears when a PWA window attempts to load // insecure content. IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, ShowsWithMixedContent) { ASSERT_TRUE(embedded_test_server()->Start()); const GURL url = https_server()->GetURL("app.com", "/ssl/google.html"); InstallPWA(url); ASSERT_TRUE(app_browser_); EXPECT_TRUE(app_browser_->is_type_app()); CustomTabBarView* bar = BrowserView::GetBrowserViewForBrowser(app_browser_) ->toolbar() ->custom_tab_bar(); EXPECT_FALSE(bar->GetVisible()); EXPECT_TRUE(ExecJs(app_browser_->tab_strip_model()->GetActiveWebContents(), R"( let img = document.createElement('img'); img.src = 'http://not-secure.com'; document.body.appendChild(img); )")); EXPECT_TRUE(bar->GetVisible()); EXPECT_EQ(bar->title_for_testing(), u"Google"); EXPECT_EQ(bar->location_for_testing() + u"/", base::ASCIIToUTF16(https_server() ->GetURL("app.com", "/ssl") .DeprecatedGetOriginAsURL() .spec())); EXPECT_FALSE(bar->close_button_for_testing()->GetVisible()); } // The custom tab bar should update with the title and location of the current // page. IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, TitleAndLocationUpdate) { const GURL app_url = https_server()->GetURL("app.com", "/ssl/google.html"); // This url is out of scope, because the CustomTabBar is not updated when it // is not shown. const GURL navigate_to = https_server()->GetURL("app.com", "/simple.html"); InstallPWA(app_url); EXPECT_TRUE(app_browser_); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); EXPECT_NE(app_view, browser_view_); SetTitleAndLocation(app_view->GetActiveWebContents(), u"FooBar", navigate_to); std::string expected_origin = navigate_to.DeprecatedGetOriginAsURL().spec(); EXPECT_EQ( base::ASCIIToUTF16(expected_origin), app_view->toolbar()->custom_tab_bar()->location_for_testing() + u"/"); EXPECT_EQ(u"FooBar", app_view->toolbar()->custom_tab_bar()->title_for_testing()); } // If the page doesn't specify a title, we should use the origin. IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, UsesLocationInsteadOfEmptyTitles) { const GURL app_url = https_server()->GetURL("app.com", "/ssl/google.html"); InstallPWA(app_url); EXPECT_TRUE(app_browser_); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); EXPECT_NE(app_view, browser_view_); // Empty title should use location. SetTitleAndLocation(app_view->GetActiveWebContents(), std::u16string(), GURL("http://example.test/")); EXPECT_EQ(u"example.test", app_view->toolbar()->custom_tab_bar()->location_for_testing()); EXPECT_EQ(u"example.test", app_view->toolbar()->custom_tab_bar()->title_for_testing()); } // Closing the CCT should take you back to the last in scope url. IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, OutOfScopeUrlShouldBeClosable) { const GURL app_url = https_server()->GetURL("app.com", "/ssl/google.html"); InstallPWA(app_url); EXPECT_TRUE(app_browser_); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); auto* web_contents = app_view->GetActiveWebContents(); EXPECT_NE(app_view, browser_view_); // Perform an inscope navigation. const GURL other_app_url = https_server()->GetURL("app.com", "/ssl/blank_page.html"); NavigateAndWait(web_contents, other_app_url); EXPECT_FALSE(app_controller_->ShouldShowCustomTabBar()); // Navigate out of scope. NavigateAndWait(web_contents, GURL("http://example.test/")); EXPECT_TRUE(app_controller_->ShouldShowCustomTabBar()); // Simulate clicking the close button and wait for navigation to finish. content::TestNavigationObserver nav_observer(web_contents); app_view->toolbar()->custom_tab_bar()->GoBackToAppForTesting(); nav_observer.Wait(); // The app should be on the last in scope url we visited. EXPECT_EQ(other_app_url, web_contents->GetLastCommittedURL()); } // Right-click menu on CustomTabBar should have Copy URL option. // Disabled on Mac because Mac's native menu is synchronous. #if !BUILDFLAG(IS_MAC) IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, RightClickMenuShowsCopyUrl) { const GURL app_url = https_server()->GetURL("app.com", "/ssl/google.html"); InstallPWA(app_url); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); auto* web_contents = app_view->GetActiveWebContents(); // Navigate out of scope. NavigateAndWait(web_contents, GURL("http://example.test/")); EXPECT_TRUE(app_controller_->ShouldShowCustomTabBar()); // Show the right-click context menu. app_view->toolbar()->custom_tab_bar()->ShowContextMenu(gfx::Point(), ui::MENU_SOURCE_MOUSE); content::BrowserTestClipboardScope test_clipboard_scope; // Activate the first and only context menu item: IDC_COPY_URL. app_view->toolbar() ->custom_tab_bar() ->context_menu_for_testing() ->ActivatedAt(0); ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); std::u16string result; clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &result); EXPECT_EQ(result, u"http://example.test/"); } #endif // !BUILDFLAG(IS_MAC) // Paths above the launch url should be out of scope and should be closable from // the CustomTabBar. IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, ScopeAboveLaunchURLShouldBeOutOfScopeAndClosable) { const GURL app_url = https_server()->GetURL("app.com", "/ssl/google.html"); InstallPWA(app_url); EXPECT_TRUE(app_browser_); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); auto* web_contents = app_view->GetActiveWebContents(); EXPECT_NE(app_view, browser_view_); // Navigate to a different page in the app scope, so we have something to come // back to. const GURL other_app_url = https_server()->GetURL("app.com", "/ssl/blank_page.html"); NavigateAndWait(web_contents, other_app_url); EXPECT_FALSE(app_controller_->ShouldShowCustomTabBar()); // Navigate above the scope of the app, on the same origin. NavigateAndWait(web_contents, https_server()->GetURL( "app.com", "/accessibility_fail.html")); EXPECT_TRUE(app_controller_->ShouldShowCustomTabBar()); // Simulate clicking the close button and wait for navigation to finish. content::TestNavigationObserver nav_observer(web_contents); app_view->toolbar()->custom_tab_bar()->GoBackToAppForTesting(); nav_observer.Wait(); // The app should be on the last in scope url we visited. EXPECT_EQ(other_app_url, web_contents->GetLastCommittedURL()); } // When there are no in scope urls to navigate back to, closing the custom tab // bar should navigate to the app's launch url. IN_PROC_BROWSER_TEST_F( CustomTabBarViewBrowserTest, WhenNoHistoryIsInScopeCloseShouldNavigateToAppLaunchURL) { const GURL app_url = https_server()->GetURL("app.com", "/ssl/google.html"); InstallPWA(app_url); EXPECT_TRUE(app_browser_); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); auto* web_contents = app_view->GetActiveWebContents(); EXPECT_NE(app_view, browser_view_); { // Do a state replacing navigation, so we don't have any in scope urls in // history. content::TestNavigationObserver nav_observer(web_contents); EXPECT_TRUE(content::ExecJs( web_contents, "window.location.replace('http://example.com');")); nav_observer.Wait(); EXPECT_TRUE(app_controller_->ShouldShowCustomTabBar()); } { // Simulate clicking the close button and wait for navigation to finish. content::TestNavigationObserver nav_observer(web_contents); app_view->toolbar()->custom_tab_bar()->GoBackToAppForTesting(); nav_observer.Wait(); } // The app should be on the last in scope url we visited. EXPECT_EQ(app_url, web_contents->GetLastCommittedURL()); } IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, OriginsWithEmojiArePunyCoded) { const GURL app_url = https_server()->GetURL("app.com", "/ssl/google.html"); const GURL navigate_to = GURL("https://🔒.example/ssl/blank_page.html"); InstallPWA(app_url); EXPECT_TRUE(app_browser_); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); EXPECT_NE(app_view, browser_view_); SetTitleAndLocation(app_view->GetActiveWebContents(), u"FooBar", navigate_to); EXPECT_EQ(u"https://xn--lv8h.example", app_view->toolbar()->custom_tab_bar()->location_for_testing()); EXPECT_EQ(u"FooBar", app_view->toolbar()->custom_tab_bar()->title_for_testing()); } IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, OriginsWithNonASCIICharactersDisplayNormally) { const GURL app_url = https_server()->GetURL("app.com", "/ssl/google.html"); const GURL navigate_to = GURL("https://ΐ.example/ssl/blank_page.html"); InstallPWA(app_url); EXPECT_TRUE(app_browser_); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); EXPECT_NE(app_view, browser_view_); SetTitleAndLocation(app_view->GetActiveWebContents(), u"FooBar", navigate_to); EXPECT_EQ(u"https://ΐ.example", app_view->toolbar()->custom_tab_bar()->location_for_testing()); EXPECT_EQ(u"FooBar", app_view->toolbar()->custom_tab_bar()->title_for_testing()); } IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, BackToAppButtonIsNotVisibleInScope) { ASSERT_TRUE(embedded_test_server()->Start()); // We install over http because it's the easiest way to get a custom tab bar // in scope. A PWA won't be installed over http in the real world (it'd make a // shortcut app instead). const GURL app_url = embedded_test_server()->GetURL("app.com", "/ssl/google.html"); const GURL out_of_scope_url = GURL("https://example.com"); InstallPWA(app_url); EXPECT_TRUE(app_browser_); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); EXPECT_NE(app_view, browser_view_); content::WebContents* web_contents = app_view->GetActiveWebContents(); // Insecure site, so should show custom tab bar. EXPECT_TRUE(app_view->toolbar()->custom_tab_bar()->GetVisible()); // In scope, so don't show close button. EXPECT_FALSE(app_view->toolbar() ->custom_tab_bar() ->close_button_for_testing() ->GetVisible()); NavigateAndWait(web_contents, out_of_scope_url); // Out of scope, show the custom tab bar. EXPECT_TRUE(app_view->toolbar()->custom_tab_bar()->GetVisible()); // Out of scope, show the close button. EXPECT_TRUE(app_view->toolbar() ->custom_tab_bar() ->close_button_for_testing() ->GetVisible()); // Simulate clicking the close button and wait for navigation to finish. content::TestNavigationObserver nav_observer(web_contents); app_view->toolbar()->custom_tab_bar()->GoBackToAppForTesting(); nav_observer.Wait(); // Insecure site, show the custom tab bar. EXPECT_TRUE(app_view->toolbar()->custom_tab_bar()->GetVisible()); // In scope, hide the close button. EXPECT_FALSE(app_view->toolbar() ->custom_tab_bar() ->close_button_for_testing() ->GetVisible()); } IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, BackToAppButtonIsNotVisibleInBookmarkAppOnOrigin) { ASSERT_TRUE(embedded_test_server()->Start()); const GURL app_url = embedded_test_server()->GetURL("app.com", "/ssl/google.html"); const GURL out_of_scope_url = GURL("https://example.com"); InstallBookmark(app_url); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); EXPECT_NE(app_view, browser_view_); // Insecure site, so should show custom tab bar. EXPECT_TRUE(app_view->toolbar()->custom_tab_bar()->GetVisible()); // On origin, so don't show close button. EXPECT_FALSE(app_view->toolbar() ->custom_tab_bar() ->close_button_for_testing() ->GetVisible()); NavigateAndWait(app_view->GetActiveWebContents(), out_of_scope_url); // Off origin, show the custom tab bar. EXPECT_TRUE(app_view->toolbar()->custom_tab_bar()->GetVisible()); // Off origin, show the close button. EXPECT_TRUE(app_view->toolbar() ->custom_tab_bar() ->close_button_for_testing() ->GetVisible()); } // Verify that interstitials that hide origin have their preference respected. IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, InterstitialCanHideOrigin) { ASSERT_TRUE(embedded_test_server()->Start()); InstallPWA(https_server()->GetURL("app.com", "/ssl/google.html")); EXPECT_TRUE(app_browser_); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); EXPECT_NE(app_view, browser_view_); content::WebContents* contents = app_view->GetActiveWebContents(); // Verify origin is blanked on interstitial. UrlHidingWebContentsObserver blocker(contents); SetTitleAndLocation(contents, u"FooBar", https_server()->GetURL("/simple.html")); EXPECT_EQ(std::u16string(), app_view->toolbar()->custom_tab_bar()->location_for_testing()); EXPECT_FALSE( app_view->toolbar()->custom_tab_bar()->IsShowingOriginForTesting()); // Verify origin returns when interstitial is gone. blocker.StopBlocking(); SetTitleAndLocation(contents, u"FooBar2", https_server()->GetURL("/title1.html")); EXPECT_NE(std::u16string(), app_view->toolbar()->custom_tab_bar()->location_for_testing()); EXPECT_TRUE( app_view->toolbar()->custom_tab_bar()->IsShowingOriginForTesting()); } // Verify that blob URLs are displayed in the location text. IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, BlobUrlLocation) { InstallPWA(https_server()->GetURL("/simple.html")); EXPECT_TRUE(app_browser_); EXPECT_TRUE(app_browser_->is_type_app()); BrowserView* app_browser_view = BrowserView::GetBrowserViewForBrowser(app_browser_); EXPECT_NE(app_browser_view, browser_view_); content::WebContents* web_contents = app_browser_->tab_strip_model()->GetActiveWebContents(); content::TestNavigationObserver nav_observer(web_contents, /*number_of_navigations=*/1); std::string script = "window.open(" " URL.createObjectURL(" " new Blob([], {type: 'text/html'})" " )," " '_self');"; EXPECT_TRUE(content::ExecJs(web_contents, script)); nav_observer.Wait(); EXPECT_EQ( app_browser_view->toolbar()->custom_tab_bar()->location_for_testing() + u"/", base::ASCIIToUTF16(https_server()->GetURL("/").spec())); }
[ "jengelh@inai.de" ]
jengelh@inai.de
2a1123b6988c000c9ce9dd6fd8aa340f8b4d05b5
8b2c451850dea9df69e8c97d35d002de5e3a6500
/main.cpp
34df3a41d0d1f3770357b3909d76ac3db073aef6
[]
no_license
1003613248/Euclidean_Clustering
97f71a06d513109f1e99a569f307a2c22404c349
b400678d67abfe4ed5cc494794fc70086fc26d3b
refs/heads/master
2022-02-27T22:22:07.195332
2019-09-23T02:48:43
2019-10-15T13:45:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,311
cpp
#include <iostream> #include <eigen3/Eigen/Eigen> using std::cout; using std::endl; int main() { double thres = 2.0; std::vector<Eigen::Vector3d> vPts; for (int i = 0; i < 10; ++i) { vPts.emplace_back(i, i, 0); } for (int i = 20; i < 30; ++i) { vPts.emplace_back(i, i, 0); } for (int i = 50; i < 60; ++i) { vPts.emplace_back(i, i, 0); } int numPts = vPts.size(); std::random_shuffle(vPts.begin(), vPts.end()); for (int i = 0; i < numPts; ++i) { cout << i << ": [" << vPts[i].transpose() << "]" << endl; } std::vector<bool> vbProcessed(numPts, false); // 每个元素存储对应索引的点是否已经被处理过 std::vector<std::vector<int> > vClusters; for (int i = 0; i < numPts; ++i) { if (vbProcessed[i]) { // 这个点已经被加入到某个cluster中了,也就是前面的某个点长出来的cluster已经把它包进去了,它就不用再自立门户了 // 或者理解为他已经在某个门派里了,不能再反出门派自己成立新的门派 continue; } Eigen::Vector3d q = vPts[i]; // q本身不属于任何门派,所以可以自立山头 std::vector<int> Q; // 自立门户,创建一个cluster Q int slow_idx = 0; Q.push_back(i); vbProcessed[i] = true; // 每当一个点被push_back到cluster里面,它就被判定为已经处理过了 // 从头至尾遍历这个vector,有新元素加进来的话就往后push_back while (slow_idx < Q.size()) // 快慢指针,当慢指针追上快指针时,说明快指针已经停下了 { std::vector<int> P; // 该序列存储vPts中所有与点q的euclidean距离在thres以内的点 for (int j = 0; j < numPts; ++j) { if (i == j) { // // 自己还招自己啊,吃饱了撑的,也不用push_back进来,否则死循环了 continue; } // 这个点已经有了门派,不是江湖散人了,不能招揽入伙了,你能招揽的只有那些还在晃悠的,没被任何人招进门的 if (vbProcessed[j]) { // 如果这个点p已经被处理过了,也就是它已经被归到某个cluster里面了,那么有两种可能: // 1. p就是在以Q为种子点的cluster里,那么肯定就不能重复push_back了 // 2. p不在以Q为种子点的cluster里,那么p跟q的距离肯定大于thres,否则在构建p_cluster时肯定把q给包进来了 continue; } // 这个点还没被其他门派或本门看上,可以试试笼络下,条件合适的话就收入本门 if ((vPts[Q[slow_idx]] - vPts[j]).norm() < thres) { Q.push_back(j); vbProcessed[j] = true; // 条件合适,收入本门,同时对外宣称这个人我已经招了,不是闲云野鹤了 } } slow_idx++; } vClusters.push_back(Q); } for (const auto &cluster : vClusters) { for (int id : cluster) { cout << id << " "; } cout << endl; } return 0; }
[ "luxiao@sensetime.com" ]
luxiao@sensetime.com
f5c070fb616a9bc02ce5a163866279e9138edc71
d85b1f3ce9a3c24ba158ca4a51ea902d152ef7b9
/testcases/CWE762_Mismatched_Memory_Management_Routines/s03/CWE762_Mismatched_Memory_Management_Routines__delete_char_realloc_63a.cpp
2ab2aa78f0236319115f36b86e3b673e78c4e34a
[]
no_license
arichardson/juliet-test-suite-c
cb71a729716c6aa8f4b987752272b66b1916fdaa
e2e8cf80cd7d52f824e9a938bbb3aa658d23d6c9
refs/heads/master
2022-12-10T12:05:51.179384
2022-11-17T15:41:30
2022-12-01T15:25:16
179,281,349
34
34
null
2022-12-01T15:25:18
2019-04-03T12:03:21
null
UTF-8
C++
false
false
2,824
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_char_realloc_63a.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml Template File: sources-sinks-63a.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: realloc Allocate data using realloc() * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_char_realloc_63 { #ifndef OMITBAD /* bad function declaration */ void badSink(char * * dataPtr); void bad() { char * data; /* Initialize data*/ data = NULL; data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (char *)realloc(data, 100*sizeof(char)); if (data == NULL) {exit(-1);} badSink(&data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(char * * data); static void goodG2B() { char * data; /* Initialize data*/ data = NULL; /* FIX: Allocate memory from the heap using new */ data = new char; goodG2BSink(&data); } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(char * * data); static void goodB2G() { char * data; /* Initialize data*/ data = NULL; data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (char *)realloc(data, 100*sizeof(char)); if (data == NULL) {exit(-1);} goodB2GSink(&data); } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__delete_char_realloc_63; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "Alexander.Richardson@cl.cam.ac.uk" ]
Alexander.Richardson@cl.cam.ac.uk
a8aac325457bfdd7a9d04dd05d7e4d5d640f3584
478f8fdf9c00140c0cf975f6bdb07b6e5d771c72
/03 - WinAPI Threads Examples/09 - Readers-Writers Problem (Fair Solution)/RWProblem_4.cpp
79db4f89ebb19da0943ed721e452ebbe8b34bf33
[]
no_license
DtCh96/parallel-programming
9d6bcb8eb0824f662d35d3ac0bd3cbb0319f4100
73eae3304cea0e4eb3128aaaedf61e969e60fbcf
refs/heads/master
2021-01-22T10:50:58.753074
2017-05-17T06:29:00
2017-05-17T06:29:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,975
cpp
//////////////////////////////////////////////////////////////////////////////// /// Справедливое решение проблемы читателей-писателей /// (каждый поток должен получить доступ за конечное время) /// /// Процесс-читатель проверяет валидность данных при чтении (все элементы буфера /// содержат одинаковый символ), в случае ошибки - выводится сообщение (ошибок /// быть не должно). /// /// Процесс-писатель просто обновляет данные в буфере. /// /// По результатам работы программы подсчитывается количество произведенных /// операций чтения/записи за время TOTAL_TIME_MS //////////////////////////////////////////////////////////////////////////////// #include <windows.h> #include <stdio.h> #include <climits> const unsigned int N_READERS = 4; // Количество задач-читателей const unsigned int N_WRITERS = 4; // Количество задач-писателей const DWORD TOTAL_TIME_MS = 5000; // Общее время работы программы const DWORD READ_TIME_MS = 1; // Время чтения в мс (эмуляция долгих операций) const DWORD WRITE_TIME_MS = 1; // Время записи в мс (эмуляция долгих операций) const unsigned int BUFFER_SIZE = 20; // Размер буфера char buffer[BUFFER_SIZE] = "AAAAAAAAAAAAAAAAAAA"; // Буфер - играет роль общей области памяти bool abort_all_threads = false; // Признак завершения работы всех потоков LONG volatile read_count = 0; // Количество потоков-читателей имеющих доступ на чтение к ресурсу HANDLE hNoWaitingSemaphore; // Дескриптор семафора для синхронизации ожидающих потоков HANDLE hNoAccessingSemaphore; // Дескриптор семафора для разграничения доступа к буферу HANDLE hThreadArray[N_READERS + N_WRITERS]; // Дескрипторы потоков DWORD dwReadersThreadID[N_READERS]; // Идентификаторы потоков-читателей DWORD dwWritersThreadID[N_WRITERS]; // Идентификаторы потоков-писателей unsigned int N_Reads[N_READERS]; // Количество произведенных операций чтения unsigned int N_Writes[N_WRITERS]; // Количество произведенных операций записи // Функция потока-писателя DWORD WINAPI WriterThreadFunction(LPVOID lpParam) { unsigned int *Num_Writes = reinterpret_cast<unsigned int*>(lpParam); while (!abort_all_threads) { // ждем когда дойдет очередь DWORD dwWaitResult = WaitForSingleObject( hNoWaitingSemaphore, // дескриптор семафора INFINITE); // ждем в течении бесконечного времени // проверка на ошибку if (dwWaitResult != WAIT_OBJECT_0) return 1; // ждем когда дойдет ресурс будет свободен dwWaitResult = WaitForSingleObject( hNoAccessingSemaphore, // дескриптор семафора INFINITE); // ждем в течении бесконечного времени // проверка на ошибку if (dwWaitResult != WAIT_OBJECT_0) return 1; // освобождаем семафор ожидания ReleaseSemaphore(hNoWaitingSemaphore, 1, NULL); //////////////////////////////////////////////////////////////////////// /// ЗАПИСЬ ДАННЫХ //////////////////////////////////////////////////////////////////////// { // записываем данные в память char ch = buffer[0] == 'Z' ? 'A' : buffer[0] + 1; for (unsigned int i = 0; i < BUFFER_SIZE - 1; ++i) buffer[i] = ch; // увеличиваем счетчик операций записи ++(*Num_Writes); // Эмулируем продолжительность операции записи if (WRITE_TIME_MS > 0) Sleep(WRITE_TIME_MS); } //////////////////////////////////////////////////////////////////////// // освобождаем семафор для доступа к ресурсу ReleaseSemaphore(hNoAccessingSemaphore, 1, NULL); } return 0; } // Функция потока-читателя DWORD WINAPI ReaderThreadFunction(LPVOID lpParam) { unsigned int *Num_Reads = reinterpret_cast<unsigned int*>(lpParam); char local_buffer[BUFFER_SIZE]; while (!abort_all_threads) { // ждем когда дойдет очередь DWORD dwWaitResult = WaitForSingleObject( hNoWaitingSemaphore, // дескриптор семафора INFINITE); // ждем в течении бесконечного времени // проверка на ошибку if (dwWaitResult != WAIT_OBJECT_0) return 1; // увеличиваем счетчик потоков-читателей имеющих доступ на чтение к ресурсу LONG res = InterlockedIncrement(&read_count); // если это первый поток читатель, то блокируем доступ к ресурсу if (res == 1) { // ждем когда дойдет ресурс будет свободен DWORD dwWaitResult = WaitForSingleObject( hNoAccessingSemaphore, // дескриптор семафора INFINITE); // ждем в течении бесконечного времени // проверка на ошибку if (dwWaitResult != WAIT_OBJECT_0) { ReleaseSemaphore(hNoWaitingSemaphore, 1, NULL); return 1; } } // освобождаем семафор ожидания ReleaseSemaphore(hNoWaitingSemaphore, 1, NULL); ////////////////////////////////////////////////////////////////////////////// /// ЧТЕНИЕ ДАННЫХ ////////////////////////////////////////////////////////////////////////////// { // читаем данные из памяти bool error = false; for (unsigned int i = 0; i < BUFFER_SIZE; ++i) { local_buffer[i] = buffer[i]; error |= i > 0 && i < BUFFER_SIZE-1 && local_buffer[i] != local_buffer[i-1]; } // если была ошибка, выводим сообщение об ошибке if (error) printf_s("Reader thread %4d detect buffer corruption: %s\n", GetCurrentThreadId(), local_buffer); // увеличиваем счетчик операций чтения ++(*Num_Reads); // Эмулируем продолжительность операции чтения if (READ_TIME_MS > 0) Sleep(READ_TIME_MS); } ////////////////////////////////////////////////////////////////////////////// // уменьшаем счетчик потоков-читателей имеющих доступ на чтение к ресурсу res = InterlockedDecrement(&read_count); // Если это последний поток-читатель, то освобождаем ресурс для доступа if (res == 0) { // освобождаем семафор для доступа к ресурсу ReleaseSemaphore(hNoAccessingSemaphore, 1, NULL); } } return 0; } int main(int argc, char* argv[]) { // Создаем семафор для синхронизации ожидающих потоков hNoWaitingSemaphore = CreateSemaphore( NULL, // использовать настройки безопасности по умолчанию 1, // первоначальное значение семафора 1, // максимальное значение семафора NULL // создать объект без имени ); // Создать семафор не удалось - выводим сообщение об ошибке и завершаем программу if (hNoWaitingSemaphore == NULL) { printf_s("CreateSemaphore failed (%d)\n", GetLastError()); ExitProcess(1); } // Создаем семафор для разграничения доступа к буферу hNoAccessingSemaphore = CreateSemaphore( NULL, // использовать настройки безопасности по умолчанию 1, // первоначальное значение семафора 1, // максимальное значение семафора NULL // создать объект без имени ); // Создать семафор не удалось - выводим сообщение об ошибке и завершаем программу if (hNoAccessingSemaphore == NULL) { printf_s("CreateSemaphore failed (%d)\n", GetLastError()); ExitProcess(1); } // Создание потоков-читателей for (unsigned int i = 0; i < N_READERS; ++i) { // инициализируем нулем количество операций чтения, произведенных потоком N_Reads[i] = 0; hThreadArray[i] = CreateThread( NULL, // использовать настройки безопасности по умолчанию 0, // использовать ращмер стека по умолчанию ReaderThreadFunction, // имя функции потока &N_Reads[i], // аргумент - количество операций чтения, произведенных потоком 0, // создать поток с флагами по умолчанию &dwReadersThreadID[i]); // идентификатор потока // Если поток не был создан - завершаем работу с ошибкой if (hThreadArray[i] == NULL) ExitProcess(1); // Выводим сообщение об успешном создании потока printf_s("Reader thread %4d sucsessfully created\n", dwReadersThreadID[i]); } // Создание потоков-писатлей for (unsigned int i = 0; i < N_WRITERS; ++i) { // инициализируем нулем количество операций записи, произведенных потоком N_Reads[i] = 0; hThreadArray[N_READERS + i] = CreateThread( NULL, // использовать настройки безопасности по умолчанию 0, // использовать ращмер стека по умолчанию WriterThreadFunction, // имя функции потока &N_Writes[i], // аргумент - количество операций записи, произведенных потоком 0, // создать поток с флагами по умолчанию &dwWritersThreadID[i]); // идентификатор потока // Если поток не был создан - завершаем работу с ошибкой if (hThreadArray[N_READERS + i] == NULL) ExitProcess(1); // Выводим сообщение об успешном создании потока printf_s("Writer thread %4d sucsessfully created\n", dwWritersThreadID[i]); } // Ждем 5 секунд для получения результатов и выставляем флаг для завершения всех потоков Sleep(5000); abort_all_threads = true; // Ожидаем завершения всех потоков WaitForMultipleObjects( N_READERS + N_WRITERS, // общее количество потоков hThreadArray, // дескрипторы потоков TRUE, // ждем завершения всех потоков INFINITE); // ждем в течении бесконечного времени // Освобождаем дескрипторы CloseHandle(hNoWaitingSemaphore); CloseHandle(hNoAccessingSemaphore); for (unsigned int i = 0; i < N_READERS + N_WRITERS; ++i) CloseHandle(hThreadArray[i]); // Подсчитываем общее количество произведенных операций чтения unsigned int N_Reads_Total = 0; for (unsigned int i = 0; i < N_READERS; ++i) { printf_s("Number of reads by thread %4d: %d\n", dwReadersThreadID[i], N_Reads[i]); N_Reads_Total += N_Reads[i]; } printf_s("Total number of reads: %d\n", N_Reads_Total); // Подсчитываем общее количество произведенных операций чтения unsigned int N_Writes_Total = 0; for (unsigned int i = 0; i < N_WRITERS; ++i) { printf_s("Number of writes by thread %4d: %d\n", dwWritersThreadID[i], N_Writes[i]); N_Writes_Total += N_Writes[i]; } printf_s("Total number of writes: %d\n", N_Writes_Total); return 0; }
[ "huntercbx@gmail.com" ]
huntercbx@gmail.com
1886d5e931b046004c51e148b0b7f5e1159e7b16
682a4a804abeb48cbeb506120c96563b66340877
/lib/fakeposix/functions.cpp
8f3f13f105fbd4280e4739b0b33010beefe710f3
[]
no_license
jordansissel/radiodev
2b7818c1a138ad741415e892ec2f16063200c9fb
0c3b2c9ffb062916dbdd29447a75fcf0dfb69e3f
refs/heads/master
2023-08-14T13:40:10.505179
2016-12-20T07:57:29
2016-12-20T07:57:29
74,437,925
0
0
null
null
null
null
UTF-8
C++
false
false
600
cpp
#include <Arduino.h> extern "C" { #include "extra.h" int close(int fd) { return 0; } int open(const char *pathname, int flags, ...) { Serial.print("open("); Serial.print(pathname), Serial.println(")"); return 0; } int fstat(int fd, struct stat *buf) { Serial.print("fstat("); Serial.print(fd); Serial.println(")"); buf->st_mode = 0444; return 0; } ssize_t read(int fd, void *buf, size_t count) { Serial.print("read("); Serial.print(fd); Serial.print(", "); Serial.print(count); Serial.println(")"); return 0; } }
[ "jls@semicomplete.com" ]
jls@semicomplete.com
252e48dfa24c8e18df4571ba4251e4bc48704966
04e34004de3240fdd42427a7fe057c3b10a056d0
/Implementations/Algorithms/Search/CompleteSearch.cpp
319a622c9e045ce3888eff03c62b0efcc9c4b35e
[]
no_license
SathvikKuthuru/USACO
51a43b922861a6b22ff13fc5dee8ed54718a26d4
2ed32a1ff444a23e9bbf0688494d5aa90c053dba
refs/heads/master
2022-05-17T00:37:37.485374
2020-04-21T23:21:55
2020-04-21T23:21:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
460
cpp
#include <bits/stdc++.h> using namespace std; //level: bronze //objective: search for a value in an array in O(n) #define FOR(i,a,b) for(__typeof(b)i=(a)-((a)>(b));i!=(b)-((a)>(b));i+=((a)>(b))?-1:1) //go from i=lb to i=ub-1 #define F0R(i,b) FOR(i,0,b) const int SZ = 1e5; int n, val, ans, a[SZ]; int main(){ cin.tie(0)->sync_with_stdio(0); cin >> n >> val; F0R(i,n) cin >> a[i]; F0R(i,n) if(a[i]==val) ans=i; cout << ans << "\n"; return 0; }
[ "noreply@github.com" ]
noreply@github.com
2d64c06d04c8caafd74fb9ac4b3c99c8efcd6736
b0e72f95e6dda5221fc1a7a655c00d93ea950534
/Friend Request.cpp
cf2c8f9d2d92da02b256e820591f94e779831d8a
[]
no_license
tahsinsiad/Problemsolving
5a2d5d11739c9780d8af19a625d4f1eb8149be1e
930454ad4f485864694bdc65a7f3ff4c9c5bee3d
refs/heads/master
2020-03-28T01:04:22.883428
2018-09-05T07:30:43
2018-09-05T07:30:43
147,474,553
0
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include<bits/stdc++.h> using namespace std; int main() { int T,x,y; string s; vector<string> v; cin>>T; while(T) { cin>>s>>x>>y; if(x==1 || y>=30) { v.push_back(s); } T--; } vector<string>::iterator it=v.begin(); while(it!=v.end()) { cout<<*it<<endl; it++; } }
[ "tak.siad16@gmail.com" ]
tak.siad16@gmail.com
76140f145fa4ec533dc928d1b29c853207f0160d
c6d6098dec94e7b4d1285eb5fae2984eb311ca61
/Classes/Level.h
43aceb4a16c598976b0aadf18efe1e4cce1380fe
[]
no_license
James-Walsh121/Home-Run
ce7373faf7ca7618f2af7afe1a93367a968d55dc
c317fe2da0b306c54ccc40444fa3375eb7d152d1
refs/heads/master
2023-07-02T23:16:45.919664
2021-08-05T15:18:11
2021-08-05T15:18:11
393,088,704
0
0
null
null
null
null
UTF-8
C++
false
false
477
h
#pragma once #include "cocos2d.h" #include <vector> using namespace std; using namespace cocos2d; class Level : public Object { public: TMXTiledMap *map; void loadMap(const char* name); TMXTiledMap * getMap(); Point tileCoordinateToPosition(Point point); Point positionToTileCoordinate(Point point); vector<Rect> getCollisionTilesY(Point point, int direction); vector<Rect> getCollisionTilesX(Point point, int direction); Level(void); virtual ~Level(void); };
[ "jameswalsh121@gmail.com" ]
jameswalsh121@gmail.com
c9d75f3b53edffcdc1683506c7e6b5a7ab3690a4
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_repos_function_235_squid-3.5.27.cpp
eef0eae633ceda552113f64bd60208dcaf9afb94
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,491
cpp
static void InitLDAP(edui_ldap_t *l) { if (l == NULL) return; l->lp = NULL; if (l->lm != NULL) ldap_msgfree(l->lm); if (l->val != NULL) ldap_value_free_len(l->val); l->lm = NULL; l->val = NULL; *(l->basedn) = '\0'; *(l->host) = '\0'; *(l->dn) = '\0'; *(l->passwd) = '\0'; *(l->search_filter) = '\0'; *(l->userid) = '\0'; memset(l->search_ip, '\0', sizeof(l->search_ip)); l->status = 0; l->status |= LDAP_INIT_S; l->port = 0; l->scope = -1; l->type = 0; l->err = -1; /* Set error to LDAP_SUCCESS by default */ l->ver = 0; l->idle_time = 0; l->num_ent = 0; /* Number of entries in l->lm */ l->num_val = 0; /* Number of entries in l->val */ /* Set default settings from conf */ if (edui_conf.basedn[0] != '\0') xstrncpy(l->basedn, edui_conf.basedn, sizeof(l->basedn)); if (edui_conf.host[0] != '\0') xstrncpy(l->host, edui_conf.host, sizeof(l->host)); if (edui_conf.port != 0) l->port = edui_conf.port; if (edui_conf.dn[0] != '\0') xstrncpy(l->dn, edui_conf.dn, sizeof(l->dn)); if (edui_conf.passwd[0] != '\0') xstrncpy(l->passwd, edui_conf.passwd, sizeof(l->passwd)); if (edui_conf.search_filter[0] != '\0') xstrncpy(l->search_filter, edui_conf.search_filter, sizeof(l->search_filter)); if (!(edui_conf.scope < 0)) l->scope = edui_conf.scope; }
[ "993273596@qq.com" ]
993273596@qq.com
22be046474280428c023b07410ba20ad15ce350f
3a79dbfa4745da59ee29ecc880970dad4c4e412d
/shufflenetv2_final_solution/acceleartor_hls_final_solution/optimization_allfactor24_FIX8/syn/systemc/subconv_1x1_8_p_5.cpp
a5da75af4758c154225bb44c575c0e9af51d37db
[]
no_license
loujc/shufflenetv2_hls
90d70607e973a52fb846142fcf63ab3dcbc135d1
db1e0901cefa4bb1b5a2d3a9c717cbd633210aa4
refs/heads/master
2021-10-28T04:36:11.344041
2019-04-22T02:10:58
2019-04-22T02:10:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
37,565
cpp
#include "subconv_1x1_8_p.h" #include "AESL_pkg.h" using namespace std; namespace ap_rtl { void subconv_1x1_8_p::thread_tmp_973_fu_5400_p3() { tmp_973_fu_5400_p3 = p_Val2_89_17_fu_5373_p2.read().range(13, 13); } void subconv_1x1_8_p::thread_tmp_974_fu_5414_p3() { tmp_974_fu_5414_p3 = p_Val2_91_17_fu_5408_p2.read().range(7, 7); } void subconv_1x1_8_p::thread_tmp_975_fu_7536_p3() { tmp_975_fu_7536_p3 = p_Val2_89_17_reg_16454.read().range(14, 14); } void subconv_1x1_8_p::thread_tmp_978_fu_10848_p3() { tmp_978_fu_10848_p3 = p_Val2_94_17_fu_10821_p2.read().range(13, 13); } void subconv_1x1_8_p::thread_tmp_979_fu_10862_p3() { tmp_979_fu_10862_p3 = p_Val2_96_17_fu_10856_p2.read().range(7, 7); } void subconv_1x1_8_p::thread_tmp_980_fu_12984_p3() { tmp_980_fu_12984_p3 = p_Val2_94_17_reg_18182.read().range(14, 14); } void subconv_1x1_8_p::thread_tmp_983_fu_5514_p3() { tmp_983_fu_5514_p3 = p_Val2_89_18_fu_5487_p2.read().range(13, 13); } void subconv_1x1_8_p::thread_tmp_984_fu_5528_p3() { tmp_984_fu_5528_p3 = p_Val2_91_18_fu_5522_p2.read().range(7, 7); } void subconv_1x1_8_p::thread_tmp_985_fu_7619_p3() { tmp_985_fu_7619_p3 = p_Val2_89_18_reg_16501.read().range(14, 14); } void subconv_1x1_8_p::thread_tmp_988_fu_10962_p3() { tmp_988_fu_10962_p3 = p_Val2_94_18_fu_10935_p2.read().range(13, 13); } void subconv_1x1_8_p::thread_tmp_989_fu_10976_p3() { tmp_989_fu_10976_p3 = p_Val2_96_18_fu_10970_p2.read().range(7, 7); } void subconv_1x1_8_p::thread_tmp_990_fu_13067_p3() { tmp_990_fu_13067_p3 = p_Val2_94_18_reg_18229.read().range(14, 14); } void subconv_1x1_8_p::thread_tmp_993_fu_5628_p3() { tmp_993_fu_5628_p3 = p_Val2_89_19_fu_5601_p2.read().range(13, 13); } void subconv_1x1_8_p::thread_tmp_994_fu_5642_p3() { tmp_994_fu_5642_p3 = p_Val2_91_19_fu_5636_p2.read().range(7, 7); } void subconv_1x1_8_p::thread_tmp_995_fu_7702_p3() { tmp_995_fu_7702_p3 = p_Val2_89_19_reg_16548.read().range(14, 14); } void subconv_1x1_8_p::thread_tmp_998_fu_11076_p3() { tmp_998_fu_11076_p3 = p_Val2_94_19_fu_11049_p2.read().range(13, 13); } void subconv_1x1_8_p::thread_tmp_999_fu_11090_p3() { tmp_999_fu_11090_p3 = p_Val2_96_19_fu_11084_p2.read().range(7, 7); } void subconv_1x1_8_p::thread_tmp_s_fu_3306_p3() { tmp_s_fu_3306_p3 = esl_concat<8,6>(reg_2094.read(), ap_const_lv6_0); } void subconv_1x1_8_p::thread_underflow_10_fu_6944_p2() { underflow_10_fu_6944_p2 = (tmp_891_reg_16083.read() & tmp41_fu_6938_p2.read()); } void subconv_1x1_8_p::thread_underflow_11_fu_7027_p2() { underflow_11_fu_7027_p2 = (tmp_901_reg_16130.read() & tmp45_fu_7021_p2.read()); } void subconv_1x1_8_p::thread_underflow_12_fu_7110_p2() { underflow_12_fu_7110_p2 = (tmp_911_reg_16177.read() & tmp49_fu_7104_p2.read()); } void subconv_1x1_8_p::thread_underflow_13_fu_7193_p2() { underflow_13_fu_7193_p2 = (tmp_921_reg_16224.read() & tmp53_fu_7187_p2.read()); } void subconv_1x1_8_p::thread_underflow_14_fu_7276_p2() { underflow_14_fu_7276_p2 = (tmp_931_reg_16271.read() & tmp57_fu_7270_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_10_fu_12475_p2() { underflow_15_10_fu_12475_p2 = (tmp_906_reg_17858.read() & tmp47_fu_12469_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_11_fu_12558_p2() { underflow_15_11_fu_12558_p2 = (tmp_916_reg_17905.read() & tmp51_fu_12552_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_12_fu_12641_p2() { underflow_15_12_fu_12641_p2 = (tmp_926_reg_17952.read() & tmp55_fu_12635_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_13_fu_12724_p2() { underflow_15_13_fu_12724_p2 = (tmp_936_reg_17999.read() & tmp59_fu_12718_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_14_fu_12807_p2() { underflow_15_14_fu_12807_p2 = (tmp_946_reg_18046.read() & tmp63_fu_12801_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_15_fu_12890_p2() { underflow_15_15_fu_12890_p2 = (tmp_956_reg_18093.read() & tmp67_fu_12884_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_16_fu_12973_p2() { underflow_15_16_fu_12973_p2 = (tmp_966_reg_18140.read() & tmp71_fu_12967_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_17_fu_13056_p2() { underflow_15_17_fu_13056_p2 = (tmp_976_reg_18187.read() & tmp75_fu_13050_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_18_fu_13139_p2() { underflow_15_18_fu_13139_p2 = (tmp_986_reg_18234.read() & tmp79_fu_13133_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_19_fu_13222_p2() { underflow_15_19_fu_13222_p2 = (tmp_996_reg_18281.read() & tmp83_fu_13216_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_1_fu_11645_p2() { underflow_15_1_fu_11645_p2 = (tmp_806_reg_17388.read() & tmp7_fu_11639_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_20_fu_13305_p2() { underflow_15_20_fu_13305_p2 = (tmp_1006_reg_18328.read() & tmp87_fu_13299_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_21_fu_13388_p2() { underflow_15_21_fu_13388_p2 = (tmp_1016_reg_18375.read() & tmp91_fu_13382_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_22_fu_13471_p2() { underflow_15_22_fu_13471_p2 = (tmp_1026_reg_18422.read() & tmp95_fu_13465_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_2_fu_11728_p2() { underflow_15_2_fu_11728_p2 = (tmp_816_reg_17435.read() & tmp11_fu_11722_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_3_fu_11811_p2() { underflow_15_3_fu_11811_p2 = (tmp_826_reg_17482.read() & tmp15_fu_11805_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_4_fu_11894_p2() { underflow_15_4_fu_11894_p2 = (tmp_836_reg_17529.read() & tmp19_fu_11888_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_5_fu_11977_p2() { underflow_15_5_fu_11977_p2 = (tmp_846_reg_17576.read() & tmp23_fu_11971_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_6_fu_12060_p2() { underflow_15_6_fu_12060_p2 = (tmp_856_reg_17623.read() & tmp27_fu_12054_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_7_fu_12143_p2() { underflow_15_7_fu_12143_p2 = (tmp_866_reg_17670.read() & tmp31_fu_12137_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_8_fu_12226_p2() { underflow_15_8_fu_12226_p2 = (tmp_876_reg_17717.read() & tmp35_fu_12220_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_9_fu_12309_p2() { underflow_15_9_fu_12309_p2 = (tmp_886_reg_17764.read() & tmp39_fu_12303_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_fu_11562_p2() { underflow_15_fu_11562_p2 = (tmp_796_reg_17341.read() & tmp3_fu_11556_p2.read()); } void subconv_1x1_8_p::thread_underflow_15_not_10_fu_13816_p2() { underflow_15_not_10_fu_13816_p2 = (tmp48_fu_13812_p2.read() | p_38_i_i_s_reg_18739.read()); } void subconv_1x1_8_p::thread_underflow_15_not_11_fu_13846_p2() { underflow_15_not_11_fu_13846_p2 = (tmp52_fu_13842_p2.read() | p_38_i_i_11_reg_18764.read()); } void subconv_1x1_8_p::thread_underflow_15_not_12_fu_13876_p2() { underflow_15_not_12_fu_13876_p2 = (tmp56_fu_13872_p2.read() | p_38_i_i_12_reg_18789.read()); } void subconv_1x1_8_p::thread_underflow_15_not_13_fu_13906_p2() { underflow_15_not_13_fu_13906_p2 = (tmp60_fu_13902_p2.read() | p_38_i_i_13_reg_18814.read()); } void subconv_1x1_8_p::thread_underflow_15_not_14_fu_13936_p2() { underflow_15_not_14_fu_13936_p2 = (tmp64_fu_13932_p2.read() | p_38_i_i_14_reg_18839.read()); } void subconv_1x1_8_p::thread_underflow_15_not_15_fu_13966_p2() { underflow_15_not_15_fu_13966_p2 = (tmp68_fu_13962_p2.read() | p_38_i_i_15_reg_18864.read()); } void subconv_1x1_8_p::thread_underflow_15_not_16_fu_13996_p2() { underflow_15_not_16_fu_13996_p2 = (tmp72_fu_13992_p2.read() | p_38_i_i_16_reg_18889.read()); } void subconv_1x1_8_p::thread_underflow_15_not_17_fu_14026_p2() { underflow_15_not_17_fu_14026_p2 = (tmp76_fu_14022_p2.read() | p_38_i_i_17_reg_18914.read()); } void subconv_1x1_8_p::thread_underflow_15_not_18_fu_14056_p2() { underflow_15_not_18_fu_14056_p2 = (tmp80_fu_14052_p2.read() | p_38_i_i_18_reg_18939.read()); } void subconv_1x1_8_p::thread_underflow_15_not_19_fu_14086_p2() { underflow_15_not_19_fu_14086_p2 = (tmp84_fu_14082_p2.read() | p_38_i_i_19_reg_18964.read()); } void subconv_1x1_8_p::thread_underflow_15_not_1_fu_13516_p2() { underflow_15_not_1_fu_13516_p2 = (tmp8_fu_13512_p2.read() | p_38_i_i_1_reg_18489.read()); } void subconv_1x1_8_p::thread_underflow_15_not_20_fu_14116_p2() { underflow_15_not_20_fu_14116_p2 = (tmp88_fu_14112_p2.read() | p_38_i_i_20_reg_18989.read()); } void subconv_1x1_8_p::thread_underflow_15_not_21_fu_14146_p2() { underflow_15_not_21_fu_14146_p2 = (tmp92_fu_14142_p2.read() | p_38_i_i_21_reg_19014.read()); } void subconv_1x1_8_p::thread_underflow_15_not_22_fu_14176_p2() { underflow_15_not_22_fu_14176_p2 = (tmp96_fu_14172_p2.read() | p_38_i_i_22_reg_19039.read()); } void subconv_1x1_8_p::thread_underflow_15_not_2_fu_13546_p2() { underflow_15_not_2_fu_13546_p2 = (tmp12_fu_13542_p2.read() | p_38_i_i_2_reg_18514.read()); } void subconv_1x1_8_p::thread_underflow_15_not_3_fu_13576_p2() { underflow_15_not_3_fu_13576_p2 = (tmp16_fu_13572_p2.read() | p_38_i_i_3_reg_18539.read()); } void subconv_1x1_8_p::thread_underflow_15_not_4_fu_13606_p2() { underflow_15_not_4_fu_13606_p2 = (tmp20_fu_13602_p2.read() | p_38_i_i_4_reg_18564.read()); } void subconv_1x1_8_p::thread_underflow_15_not_5_fu_13636_p2() { underflow_15_not_5_fu_13636_p2 = (tmp24_fu_13632_p2.read() | p_38_i_i_5_reg_18589.read()); } void subconv_1x1_8_p::thread_underflow_15_not_6_fu_13666_p2() { underflow_15_not_6_fu_13666_p2 = (tmp28_fu_13662_p2.read() | p_38_i_i_6_reg_18614.read()); } void subconv_1x1_8_p::thread_underflow_15_not_7_fu_13696_p2() { underflow_15_not_7_fu_13696_p2 = (tmp32_fu_13692_p2.read() | p_38_i_i_7_reg_18639.read()); } void subconv_1x1_8_p::thread_underflow_15_not_8_fu_13726_p2() { underflow_15_not_8_fu_13726_p2 = (tmp36_fu_13722_p2.read() | p_38_i_i_8_reg_18664.read()); } void subconv_1x1_8_p::thread_underflow_15_not_9_fu_13756_p2() { underflow_15_not_9_fu_13756_p2 = (tmp40_fu_13752_p2.read() | p_38_i_i_9_reg_18689.read()); } void subconv_1x1_8_p::thread_underflow_15_not_fu_13486_p2() { underflow_15_not_fu_13486_p2 = (tmp4_fu_13482_p2.read() | p_38_i_i_reg_18464.read()); } void subconv_1x1_8_p::thread_underflow_15_not_s_fu_13786_p2() { underflow_15_not_s_fu_13786_p2 = (tmp44_fu_13782_p2.read() | p_38_i_i_10_reg_18714.read()); } void subconv_1x1_8_p::thread_underflow_15_s_fu_12392_p2() { underflow_15_s_fu_12392_p2 = (tmp_896_reg_17811.read() & tmp43_fu_12386_p2.read()); } void subconv_1x1_8_p::thread_underflow_16_fu_7442_p2() { underflow_16_fu_7442_p2 = (tmp_951_reg_16365.read() & tmp65_fu_7436_p2.read()); } void subconv_1x1_8_p::thread_underflow_17_fu_7525_p2() { underflow_17_fu_7525_p2 = (tmp_961_reg_16412.read() & tmp69_fu_7519_p2.read()); } void subconv_1x1_8_p::thread_underflow_18_fu_7608_p2() { underflow_18_fu_7608_p2 = (tmp_971_reg_16459.read() & tmp73_fu_7602_p2.read()); } void subconv_1x1_8_p::thread_underflow_19_fu_7691_p2() { underflow_19_fu_7691_p2 = (tmp_981_reg_16506.read() & tmp77_fu_7685_p2.read()); } void subconv_1x1_8_p::thread_underflow_1_fu_6197_p2() { underflow_1_fu_6197_p2 = (tmp_801_reg_15660.read() & tmp5_fu_6191_p2.read()); } void subconv_1x1_8_p::thread_underflow_20_fu_7774_p2() { underflow_20_fu_7774_p2 = (tmp_991_reg_16553.read() & tmp81_fu_7768_p2.read()); } void subconv_1x1_8_p::thread_underflow_21_fu_7857_p2() { underflow_21_fu_7857_p2 = (tmp_1001_reg_16600.read() & tmp85_fu_7851_p2.read()); } void subconv_1x1_8_p::thread_underflow_22_fu_7940_p2() { underflow_22_fu_7940_p2 = (tmp_1011_reg_16647.read() & tmp89_fu_7934_p2.read()); } void subconv_1x1_8_p::thread_underflow_23_fu_8023_p2() { underflow_23_fu_8023_p2 = (tmp_1021_reg_16694.read() & tmp93_fu_8017_p2.read()); } void subconv_1x1_8_p::thread_underflow_2_fu_6280_p2() { underflow_2_fu_6280_p2 = (tmp_811_reg_15707.read() & tmp9_fu_6274_p2.read()); } void subconv_1x1_8_p::thread_underflow_3_fu_6363_p2() { underflow_3_fu_6363_p2 = (tmp_821_reg_15754.read() & tmp13_fu_6357_p2.read()); } void subconv_1x1_8_p::thread_underflow_4_fu_6446_p2() { underflow_4_fu_6446_p2 = (tmp_831_reg_15801.read() & tmp17_fu_6440_p2.read()); } void subconv_1x1_8_p::thread_underflow_5_fu_6529_p2() { underflow_5_fu_6529_p2 = (tmp_841_reg_15848.read() & tmp21_fu_6523_p2.read()); } void subconv_1x1_8_p::thread_underflow_6_fu_6612_p2() { underflow_6_fu_6612_p2 = (tmp_851_reg_15895.read() & tmp25_fu_6606_p2.read()); } void subconv_1x1_8_p::thread_underflow_7_fu_6695_p2() { underflow_7_fu_6695_p2 = (tmp_861_reg_15942.read() & tmp29_fu_6689_p2.read()); } void subconv_1x1_8_p::thread_underflow_8_fu_6778_p2() { underflow_8_fu_6778_p2 = (tmp_871_reg_15989.read() & tmp33_fu_6772_p2.read()); } void subconv_1x1_8_p::thread_underflow_9_fu_6861_p2() { underflow_9_fu_6861_p2 = (tmp_881_reg_16036.read() & tmp37_fu_6855_p2.read()); } void subconv_1x1_8_p::thread_underflow_fu_6114_p2() { underflow_fu_6114_p2 = (tmp_791_reg_15613.read() & tmp1_fu_6108_p2.read()); } void subconv_1x1_8_p::thread_underflow_not_10_fu_8338_p2() { underflow_not_10_fu_8338_p2 = (tmp42_fu_8334_p2.read() | p_38_i_i8_s_reg_16986.read()); } void subconv_1x1_8_p::thread_underflow_not_11_fu_8398_p2() { underflow_not_11_fu_8398_p2 = (tmp50_fu_8394_p2.read() | p_38_i_i8_11_reg_17036.read()); } void subconv_1x1_8_p::thread_underflow_not_12_fu_8428_p2() { underflow_not_12_fu_8428_p2 = (tmp54_fu_8424_p2.read() | p_38_i_i8_12_reg_17061.read()); } void subconv_1x1_8_p::thread_underflow_not_13_fu_8458_p2() { underflow_not_13_fu_8458_p2 = (tmp58_fu_8454_p2.read() | p_38_i_i8_13_reg_17086.read()); } void subconv_1x1_8_p::thread_underflow_not_14_fu_8488_p2() { underflow_not_14_fu_8488_p2 = (tmp62_fu_8484_p2.read() | p_38_i_i8_14_reg_17111.read()); } void subconv_1x1_8_p::thread_underflow_not_15_fu_8518_p2() { underflow_not_15_fu_8518_p2 = (tmp66_fu_8514_p2.read() | p_38_i_i8_15_reg_17136.read()); } void subconv_1x1_8_p::thread_underflow_not_16_fu_8548_p2() { underflow_not_16_fu_8548_p2 = (tmp70_fu_8544_p2.read() | p_38_i_i8_16_reg_17161.read()); } void subconv_1x1_8_p::thread_underflow_not_17_fu_8578_p2() { underflow_not_17_fu_8578_p2 = (tmp74_fu_8574_p2.read() | p_38_i_i8_17_reg_17186.read()); } void subconv_1x1_8_p::thread_underflow_not_18_fu_8608_p2() { underflow_not_18_fu_8608_p2 = (tmp78_fu_8604_p2.read() | p_38_i_i8_18_reg_17211.read()); } void subconv_1x1_8_p::thread_underflow_not_19_fu_8638_p2() { underflow_not_19_fu_8638_p2 = (tmp82_fu_8634_p2.read() | p_38_i_i8_19_reg_17236.read()); } void subconv_1x1_8_p::thread_underflow_not_1_fu_8068_p2() { underflow_not_1_fu_8068_p2 = (tmp6_fu_8064_p2.read() | p_38_i_i8_1_reg_16761.read()); } void subconv_1x1_8_p::thread_underflow_not_20_fu_8668_p2() { underflow_not_20_fu_8668_p2 = (tmp86_fu_8664_p2.read() | p_38_i_i8_20_reg_17261.read()); } void subconv_1x1_8_p::thread_underflow_not_21_fu_8698_p2() { underflow_not_21_fu_8698_p2 = (tmp90_fu_8694_p2.read() | p_38_i_i8_21_reg_17286.read()); } void subconv_1x1_8_p::thread_underflow_not_22_fu_8728_p2() { underflow_not_22_fu_8728_p2 = (tmp94_fu_8724_p2.read() | p_38_i_i8_22_reg_17311.read()); } void subconv_1x1_8_p::thread_underflow_not_2_fu_8098_p2() { underflow_not_2_fu_8098_p2 = (tmp10_fu_8094_p2.read() | p_38_i_i8_2_reg_16786.read()); } void subconv_1x1_8_p::thread_underflow_not_3_fu_8128_p2() { underflow_not_3_fu_8128_p2 = (tmp14_fu_8124_p2.read() | p_38_i_i8_3_reg_16811.read()); } void subconv_1x1_8_p::thread_underflow_not_4_fu_8158_p2() { underflow_not_4_fu_8158_p2 = (tmp18_fu_8154_p2.read() | p_38_i_i8_4_reg_16836.read()); } void subconv_1x1_8_p::thread_underflow_not_5_fu_8188_p2() { underflow_not_5_fu_8188_p2 = (tmp22_fu_8184_p2.read() | p_38_i_i8_5_reg_16861.read()); } void subconv_1x1_8_p::thread_underflow_not_6_fu_8218_p2() { underflow_not_6_fu_8218_p2 = (tmp26_fu_8214_p2.read() | p_38_i_i8_6_reg_16886.read()); } void subconv_1x1_8_p::thread_underflow_not_7_fu_8248_p2() { underflow_not_7_fu_8248_p2 = (tmp30_fu_8244_p2.read() | p_38_i_i8_7_reg_16911.read()); } void subconv_1x1_8_p::thread_underflow_not_8_fu_8278_p2() { underflow_not_8_fu_8278_p2 = (tmp34_fu_8274_p2.read() | p_38_i_i8_8_reg_16936.read()); } void subconv_1x1_8_p::thread_underflow_not_9_fu_8308_p2() { underflow_not_9_fu_8308_p2 = (tmp38_fu_8304_p2.read() | p_38_i_i8_9_reg_16961.read()); } void subconv_1x1_8_p::thread_underflow_not_fu_8038_p2() { underflow_not_fu_8038_p2 = (tmp2_fu_8034_p2.read() | p_38_i_i8_reg_16736.read()); } void subconv_1x1_8_p::thread_underflow_not_s_fu_8368_p2() { underflow_not_s_fu_8368_p2 = (tmp46_fu_8364_p2.read() | p_38_i_i8_10_reg_17011.read()); } void subconv_1x1_8_p::thread_underflow_s_fu_7359_p2() { underflow_s_fu_7359_p2 = (tmp_941_reg_16318.read() & tmp61_fu_7353_p2.read()); } void subconv_1x1_8_p::thread_w2_cast_cast4_fu_2481_p1() { w2_cast_cast4_fu_2481_p1 = esl_zext<14,4>(w2_reg_1798.read()); } void subconv_1x1_8_p::thread_w2_cast_cast5_fu_2485_p1() { w2_cast_cast5_fu_2485_p1 = esl_zext<9,4>(w2_reg_1798.read()); } void subconv_1x1_8_p::thread_w2_cast_cast_fu_2489_p1() { w2_cast_cast_fu_2489_p1 = esl_zext<8,4>(w2_reg_1798.read()); } void subconv_1x1_8_p::thread_w6_cast_cast_fu_14398_p1() { w6_cast_cast_fu_14398_p1 = esl_zext<9,4>(w6_mid2_reg_19098.read()); } void subconv_1x1_8_p::thread_w6_mid2_fu_14307_p3() { w6_mid2_fu_14307_p3 = (!tmp_324_fu_14302_p2.read()[0].is_01())? sc_lv<4>(): ((tmp_324_fu_14302_p2.read()[0].to_bool())? ap_const_lv4_1: w6_phi_fu_1870_p4.read()); } void subconv_1x1_8_p::thread_w6_phi_fu_1870_p4() { if ((esl_seteq<1,1,1>(ap_const_lv1_0, ap_reg_pp1_iter1_exitcond_flatten6_reg_19064.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter2.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_flag00000000.read(), ap_const_boolean_0))) { w6_phi_fu_1870_p4 = w_17_fu_14407_p2.read(); } else { w6_phi_fu_1870_p4 = w6_reg_1866.read(); } } void subconv_1x1_8_p::thread_w_15_fu_2292_p2() { w_15_fu_2292_p2 = (!w_mid2_reg_14534.read().is_01() || !ap_const_lv4_1.is_01())? sc_lv<4>(): (sc_biguint<4>(w_mid2_reg_14534.read()) + sc_biguint<4>(ap_const_lv4_1)); } void subconv_1x1_8_p::thread_w_16_fu_2724_p2() { w_16_fu_2724_p2 = (!w2_reg_1798.read().is_01() || !ap_const_lv4_1.is_01())? sc_lv<4>(): (sc_biguint<4>(w2_reg_1798.read()) + sc_biguint<4>(ap_const_lv4_1)); } void subconv_1x1_8_p::thread_w_17_fu_14407_p2() { w_17_fu_14407_p2 = (!w6_mid2_reg_19098.read().is_01() || !ap_const_lv4_1.is_01())? sc_lv<4>(): (sc_biguint<4>(w6_mid2_reg_19098.read()) + sc_biguint<4>(ap_const_lv4_1)); } void subconv_1x1_8_p::thread_w_cast_cast_fu_2395_p1() { w_cast_cast_fu_2395_p1 = esl_zext<9,4>(ap_reg_pp0_iter8_w_mid2_reg_14534.read()); } void subconv_1x1_8_p::thread_w_mid2_fu_2276_p3() { w_mid2_fu_2276_p3 = (!tmp_311_fu_2271_p2.read()[0].is_01())? sc_lv<4>(): ((tmp_311_fu_2271_p2.read()[0].to_bool())? ap_const_lv4_1: w_phi_fu_1778_p4.read()); } void subconv_1x1_8_p::thread_w_phi_fu_1778_p4() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter2.read()) && esl_seteq<1,1,1>(ap_reg_pp0_iter1_exitcond_flatten4_reg_14505.read(), ap_const_lv1_0) && esl_seteq<1,1,1>(ap_block_pp0_stage0_flag00000000.read(), ap_const_boolean_0))) { w_phi_fu_1778_p4 = w_15_fu_2292_p2.read(); } else { w_phi_fu_1778_p4 = w_reg_1774.read(); } } void subconv_1x1_8_p::thread_weight_0_V_address0() { weight_0_V_address0 = weight_0_V_addr_reg_14847.read(); } void subconv_1x1_8_p::thread_weight_0_V_address1() { weight_0_V_address1 = weight_0_V_addr_4_reg_14852.read(); } void subconv_1x1_8_p::thread_weight_0_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_0_V_ce0 = ap_const_logic_1; } else { weight_0_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_0_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_0_V_ce1 = ap_const_logic_1; } else { weight_0_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_10_V_address0() { weight_10_V_address0 = weight_10_V_addr_reg_14947.read(); } void subconv_1x1_8_p::thread_weight_10_V_address1() { weight_10_V_address1 = weight_10_V_addr_4_reg_14952.read(); } void subconv_1x1_8_p::thread_weight_10_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_10_V_ce0 = ap_const_logic_1; } else { weight_10_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_10_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_10_V_ce1 = ap_const_logic_1; } else { weight_10_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_11_V_address0() { weight_11_V_address0 = weight_11_V_addr_reg_14957.read(); } void subconv_1x1_8_p::thread_weight_11_V_address1() { weight_11_V_address1 = weight_11_V_addr_4_reg_14962.read(); } void subconv_1x1_8_p::thread_weight_11_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_11_V_ce0 = ap_const_logic_1; } else { weight_11_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_11_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_11_V_ce1 = ap_const_logic_1; } else { weight_11_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_12_V_address0() { weight_12_V_address0 = weight_12_V_addr_reg_14967.read(); } void subconv_1x1_8_p::thread_weight_12_V_address1() { weight_12_V_address1 = weight_12_V_addr_4_reg_14972.read(); } void subconv_1x1_8_p::thread_weight_12_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_12_V_ce0 = ap_const_logic_1; } else { weight_12_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_12_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_12_V_ce1 = ap_const_logic_1; } else { weight_12_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_13_V_address0() { weight_13_V_address0 = weight_13_V_addr_reg_14977.read(); } void subconv_1x1_8_p::thread_weight_13_V_address1() { weight_13_V_address1 = weight_13_V_addr_4_reg_14982.read(); } void subconv_1x1_8_p::thread_weight_13_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_13_V_ce0 = ap_const_logic_1; } else { weight_13_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_13_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_13_V_ce1 = ap_const_logic_1; } else { weight_13_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_14_V_address0() { weight_14_V_address0 = weight_14_V_addr_reg_14987.read(); } void subconv_1x1_8_p::thread_weight_14_V_address1() { weight_14_V_address1 = weight_14_V_addr_4_reg_14992.read(); } void subconv_1x1_8_p::thread_weight_14_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_14_V_ce0 = ap_const_logic_1; } else { weight_14_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_14_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_14_V_ce1 = ap_const_logic_1; } else { weight_14_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_15_V_address0() { weight_15_V_address0 = weight_15_V_addr_reg_14997.read(); } void subconv_1x1_8_p::thread_weight_15_V_address1() { weight_15_V_address1 = weight_15_V_addr_4_reg_15002.read(); } void subconv_1x1_8_p::thread_weight_15_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_15_V_ce0 = ap_const_logic_1; } else { weight_15_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_15_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_15_V_ce1 = ap_const_logic_1; } else { weight_15_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_16_V_address0() { weight_16_V_address0 = weight_16_V_addr_reg_15007.read(); } void subconv_1x1_8_p::thread_weight_16_V_address1() { weight_16_V_address1 = weight_16_V_addr_4_reg_15012.read(); } void subconv_1x1_8_p::thread_weight_16_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_16_V_ce0 = ap_const_logic_1; } else { weight_16_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_16_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_16_V_ce1 = ap_const_logic_1; } else { weight_16_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_17_V_address0() { weight_17_V_address0 = weight_17_V_addr_reg_15017.read(); } void subconv_1x1_8_p::thread_weight_17_V_address1() { weight_17_V_address1 = weight_17_V_addr_4_reg_15022.read(); } void subconv_1x1_8_p::thread_weight_17_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_17_V_ce0 = ap_const_logic_1; } else { weight_17_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_17_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_17_V_ce1 = ap_const_logic_1; } else { weight_17_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_18_V_address0() { weight_18_V_address0 = weight_18_V_addr_reg_15027.read(); } void subconv_1x1_8_p::thread_weight_18_V_address1() { weight_18_V_address1 = weight_18_V_addr_4_reg_15032.read(); } void subconv_1x1_8_p::thread_weight_18_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_18_V_ce0 = ap_const_logic_1; } else { weight_18_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_18_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_18_V_ce1 = ap_const_logic_1; } else { weight_18_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_19_V_address0() { weight_19_V_address0 = weight_19_V_addr_reg_15037.read(); } void subconv_1x1_8_p::thread_weight_19_V_address1() { weight_19_V_address1 = weight_19_V_addr_4_reg_15042.read(); } void subconv_1x1_8_p::thread_weight_19_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_19_V_ce0 = ap_const_logic_1; } else { weight_19_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_19_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_19_V_ce1 = ap_const_logic_1; } else { weight_19_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_1_V_address0() { weight_1_V_address0 = weight_1_V_addr_reg_14857.read(); } void subconv_1x1_8_p::thread_weight_1_V_address1() { weight_1_V_address1 = weight_1_V_addr_4_reg_14862.read(); } void subconv_1x1_8_p::thread_weight_1_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_1_V_ce0 = ap_const_logic_1; } else { weight_1_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_1_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_1_V_ce1 = ap_const_logic_1; } else { weight_1_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_20_V_address0() { weight_20_V_address0 = weight_20_V_addr_reg_15047.read(); } void subconv_1x1_8_p::thread_weight_20_V_address1() { weight_20_V_address1 = weight_20_V_addr_4_reg_15052.read(); } void subconv_1x1_8_p::thread_weight_20_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_20_V_ce0 = ap_const_logic_1; } else { weight_20_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_20_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_20_V_ce1 = ap_const_logic_1; } else { weight_20_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_21_V_address0() { weight_21_V_address0 = weight_21_V_addr_reg_15057.read(); } void subconv_1x1_8_p::thread_weight_21_V_address1() { weight_21_V_address1 = weight_21_V_addr_4_reg_15062.read(); } void subconv_1x1_8_p::thread_weight_21_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_21_V_ce0 = ap_const_logic_1; } else { weight_21_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_21_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_21_V_ce1 = ap_const_logic_1; } else { weight_21_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_22_V_address0() { weight_22_V_address0 = weight_22_V_addr_reg_15067.read(); } void subconv_1x1_8_p::thread_weight_22_V_address1() { weight_22_V_address1 = weight_22_V_addr_4_reg_15072.read(); } void subconv_1x1_8_p::thread_weight_22_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_22_V_ce0 = ap_const_logic_1; } else { weight_22_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_22_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_22_V_ce1 = ap_const_logic_1; } else { weight_22_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_23_V_address0() { weight_23_V_address0 = weight_23_V_addr_reg_15077.read(); } void subconv_1x1_8_p::thread_weight_23_V_address1() { weight_23_V_address1 = weight_23_V_addr_4_reg_15082.read(); } void subconv_1x1_8_p::thread_weight_23_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_23_V_ce0 = ap_const_logic_1; } else { weight_23_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_23_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_23_V_ce1 = ap_const_logic_1; } else { weight_23_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_2_V_address0() { weight_2_V_address0 = weight_2_V_addr_reg_14867.read(); } void subconv_1x1_8_p::thread_weight_2_V_address1() { weight_2_V_address1 = weight_2_V_addr_4_reg_14872.read(); } void subconv_1x1_8_p::thread_weight_2_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_2_V_ce0 = ap_const_logic_1; } else { weight_2_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_2_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_2_V_ce1 = ap_const_logic_1; } else { weight_2_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_3_V_address0() { weight_3_V_address0 = weight_3_V_addr_reg_14877.read(); } void subconv_1x1_8_p::thread_weight_3_V_address1() { weight_3_V_address1 = weight_3_V_addr_4_reg_14882.read(); } void subconv_1x1_8_p::thread_weight_3_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_3_V_ce0 = ap_const_logic_1; } else { weight_3_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_3_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_3_V_ce1 = ap_const_logic_1; } else { weight_3_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_4_V_address0() { weight_4_V_address0 = weight_4_V_addr_reg_14887.read(); } void subconv_1x1_8_p::thread_weight_4_V_address1() { weight_4_V_address1 = weight_4_V_addr_4_reg_14892.read(); } void subconv_1x1_8_p::thread_weight_4_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_4_V_ce0 = ap_const_logic_1; } else { weight_4_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_4_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_4_V_ce1 = ap_const_logic_1; } else { weight_4_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_5_V_address0() { weight_5_V_address0 = weight_5_V_addr_reg_14897.read(); } void subconv_1x1_8_p::thread_weight_5_V_address1() { weight_5_V_address1 = weight_5_V_addr_4_reg_14902.read(); } void subconv_1x1_8_p::thread_weight_5_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_5_V_ce0 = ap_const_logic_1; } else { weight_5_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_5_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_5_V_ce1 = ap_const_logic_1; } else { weight_5_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_6_V_address0() { weight_6_V_address0 = weight_6_V_addr_reg_14907.read(); } void subconv_1x1_8_p::thread_weight_6_V_address1() { weight_6_V_address1 = weight_6_V_addr_4_reg_14912.read(); } void subconv_1x1_8_p::thread_weight_6_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_6_V_ce0 = ap_const_logic_1; } else { weight_6_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_6_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_6_V_ce1 = ap_const_logic_1; } else { weight_6_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_7_V_address0() { weight_7_V_address0 = weight_7_V_addr_reg_14917.read(); } void subconv_1x1_8_p::thread_weight_7_V_address1() { weight_7_V_address1 = weight_7_V_addr_4_reg_14922.read(); } void subconv_1x1_8_p::thread_weight_7_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_7_V_ce0 = ap_const_logic_1; } else { weight_7_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_7_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_7_V_ce1 = ap_const_logic_1; } else { weight_7_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_8_V_address0() { weight_8_V_address0 = weight_8_V_addr_reg_14927.read(); } void subconv_1x1_8_p::thread_weight_8_V_address1() { weight_8_V_address1 = weight_8_V_addr_4_reg_14932.read(); } void subconv_1x1_8_p::thread_weight_8_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_8_V_ce0 = ap_const_logic_1; } else { weight_8_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_8_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_8_V_ce1 = ap_const_logic_1; } else { weight_8_V_ce1 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_9_V_address0() { weight_9_V_address0 = weight_9_V_addr_reg_14937.read(); } void subconv_1x1_8_p::thread_weight_9_V_address1() { weight_9_V_address1 = weight_9_V_addr_4_reg_14942.read(); } void subconv_1x1_8_p::thread_weight_9_V_ce0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_9_V_ce0 = ap_const_logic_1; } else { weight_9_V_ce0 = ap_const_logic_0; } } void subconv_1x1_8_p::thread_weight_9_V_ce1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state18.read())) { weight_9_V_ce1 = ap_const_logic_1; } else { weight_9_V_ce1 = ap_const_logic_0; } } }
[ "jzfengziyan@gmail.com" ]
jzfengziyan@gmail.com
263adde4a6a0e04f728596e8fc0cbb258bfce1d1
f48f598536152808a94d7053174ba1086103b562
/ejercicio8.cpp
5f6039a4e3bbdc55cc76266cee74ffd83fd0f00d
[]
no_license
Fundamentos-Prog-Electronica-18-2/ejercicios-clase-8-DorisAlejandra
4c9acffe6a54025a4d36d5e26918243f692cf979
1793754c81e2ef2ede72b4d1a84a9d215e7a12b4
refs/heads/master
2020-04-07T17:05:38.086172
2018-11-21T16:39:01
2018-11-21T16:39:01
158,556,317
0
0
null
null
null
null
UTF-8
C++
false
false
655
cpp
#include <iostream> using namespace std; int main() { int numero,limite,opcion,contador=0,suma,multiplicacion; cout<< "ingrese el numero"; cin>>numero; cout << "Ingrese el limite"; cin>> limite; cout<< "ingrse una opcion"; cin >> opcion; if(opcion==1){ while(contador<=limite){ multiplicacion=numero *contador; cout<< numero <<"* " << contador<<"= " << multiplicacion<< endl; contador=contador+1; } }else{ if(opcion==2){ while(contador<=limite){ suma=numero +contador; cout<<numero <<"+ " << contador <<"= " << suma<< endl; contador=contador+1; } }else{ cout << "opcion incorrecta"; } } return 0; }
[ "alejita13102015@gmail.com" ]
alejita13102015@gmail.com
a847446e1555f5e92db6005273d7b65dd8ebe962
ea7fd7124f4a8889407a876475a195deacec6d87
/Scan/Stock Manager/digit_get.cpp
0c7b712fe477d1eed424f8439465b94120e57151
[]
no_license
BreakTheWind/cScan
942b6fad5f488f62fef3348cd0ccdf69df40e139
7816a6bc5fbfa2fc96a3f847e5cf988dd460c675
refs/heads/master
2021-01-20T18:54:47.160934
2016-06-21T18:01:04
2016-06-21T18:01:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,306
cpp
#include <math.h> #include "digit.h" //Digit is given in a right-to-left order. int digit_get64(int64_t number, int place) { int64_t target = number; int digit = 0; target /= (int64_t)pow(10, place); digit = target % 10; return digit; } int digit_get32(int32_t number, int place) { int32_t target = number; int digit = 0; target /= (int32_t)pow(10, place); digit = target % 10; return digit; } int digit_get16(int16_t number, int place) { int16_t target = number; int digit = 0; target /= (int16_t)pow(10, place); digit = target % 10; return digit; } int digit_getshort(short number, int place) { int target = number; short digit = 0; target /= (short)pow(10, place); digit = target % 10; return digit; } int digit_getint(int number, int place) { int target = number; int digit = 0; target /= (int)pow(10, place); digit = target % 10; return digit; } int digit_getlong(long number, int place) { int target = number; long digit = 0; target /= (long)pow(10, place); digit = target % 10; return digit; } int digit_getlonglong(long long number, int place) { int target = number; long long digit = 0; target /= (long long)pow(10, place); digit = target % 10; return digit; }
[ "noreply@github.com" ]
noreply@github.com
0305860a76d04e484a82d4767c52595ac73095a4
05f7573db159e870fb26c847991c4cb8c407ed4c
/VBF/Source/VBF_App/ModelingTool/C_ViewerWidget3D.h
dc0ac71b5b07850e094cf27d9f70d1fda0194426
[]
no_license
riyue625/OneGIS.ModelingTool
e126ef43429ce58d22c65832d96dbd113eacbf85
daf3dc91584df7ecfed6a51130ecdf6671614ac4
refs/heads/master
2020-05-28T12:12:43.543730
2018-09-06T07:42:00
2018-09-06T07:42:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
337
h
#pragma once #include <QTimer> #include "GraphicsWindowQt.h" #include "C_GlobalGIS.h" class C_ViewerWidget3D: public GLWidget { public: C_ViewerWidget3D(QWidget* pParent = 0); virtual ~C_ViewerWidget3D(void); protected: virtual void paintEvent(QPaintEvent* event); private: QTimer m_timer; ref_ptr<C_GlobalGIS> m_pGlobalGIS; };
[ "robertsam@126.com" ]
robertsam@126.com
aa72bd41eb06a44d062c1413953bd9d98edd13ae
8cb36e9645d8cdbe5dd260c5c90a1d7e92f82929
/!test/FizzBuzzTest/FizzBuzzTest.ino
befad06ac09b01ad399cf209d29268d227957bca
[]
no_license
systemengineerbasic/EspSystem
10ed3a8cb85bc5ce322c3f09bd0a5017aa7ba753
340205467e924ed1da95ef944bdcf8ded89c6d67
refs/heads/master
2021-07-24T09:47:00.068536
2020-05-31T09:37:08
2020-05-31T09:37:08
181,398,108
0
0
null
null
null
null
UTF-8
C++
false
false
409
ino
void setup() { Serial.begin(115200); for(int i = 1; i <= 100; i ++) { Serial.print(i); if(((i%3)==0) && ((i%5)==0)) { Serial.println(" : KonicaMinolta"); } else if((i%3)==0) { Serial.println(" : Konica"); } else if((i%5)==0) { Serial.println(" : Minolta"); } else { Serial.println(); } } } void loop() { }
[ "yushi.nishimura@konicaminolta.com" ]
yushi.nishimura@konicaminolta.com
f05d033c93baaa52bbbf4e2bfa5cc9d9654b946e
0ee655544bf5963ebd6741126c9affb94f83800a
/src/app/common/entry/input.cpp
5fdad9c0bb638db139dae869369cdebb9be61e47
[ "MIT" ]
permissive
Stynson/minecraft
9525f6ff287d20341d0b9571ce9c9caa75f85c11
a3fe5c69318106360b41c640251b534ce41a6ce9
refs/heads/master
2021-05-04T15:08:19.188171
2018-06-14T21:18:31
2018-06-14T21:18:31
120,221,286
3
1
MIT
2018-02-08T14:43:32
2018-02-04T20:40:06
CMake
UTF-8
C++
false
false
7,605
cpp
/* * Copyright 2010-2018 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #include <memory.h> #include "entry_p.h" #include "input.h" #include "cmd.h" #include <bx/allocator.h> #include <bx/ringbuffer.h> #include <tinystl/string.h> #include <tinystl/allocator.h> #include <tinystl/unordered_map.h> namespace stl = tinystl; struct InputMouse { InputMouse() : m_width(1280) , m_height(720) , m_wheelDelta(120) , m_lock(false) { } void reset() { if (m_lock) { m_norm[0] = 0.0f; m_norm[1] = 0.0f; m_norm[2] = 0.0f; } bx::memSet(m_buttons, 0, sizeof(m_buttons) ); } void setResolution(uint16_t _width, uint16_t _height) { m_width = _width; m_height = _height; } void setPos(int32_t _mx, int32_t _my, int32_t _mz) { m_absolute[0] = _mx; m_absolute[1] = _my; m_absolute[2] = _mz; m_norm[0] = float(_mx)/float(m_width); m_norm[1] = float(_my)/float(m_height); m_norm[2] = float(_mz)/float(m_wheelDelta); } void setButtonState(entry::MouseButton::Enum _button, uint8_t _state) { m_buttons[_button] = _state; } int32_t m_absolute[3]; float m_norm[3]; int32_t m_wheel; uint8_t m_buttons[entry::MouseButton::Count]; uint16_t m_width; uint16_t m_height; uint16_t m_wheelDelta; bool m_lock; }; struct InputKeyboard { InputKeyboard() : m_ring(BX_COUNTOF(m_char)-4) { } void reset() { bx::memSet(m_key, 0, sizeof(m_key) ); bx::memSet(m_once, 0xff, sizeof(m_once) ); } static uint32_t encodeKeyState(uint8_t _modifiers, bool _down) { uint32_t state = 0; state |= uint32_t(_down ? _modifiers : 0)<<16; state |= uint32_t(_down)<<8; return state; } static bool decodeKeyState(uint32_t _state, uint8_t& _modifiers) { _modifiers = (_state>>16)&0xff; return 0 != ( (_state>> 8)&0xff); } void setKeyState(entry::Key::Enum _key, uint8_t _modifiers, bool _down) { m_key[_key] = encodeKeyState(_modifiers, _down); m_once[_key] = false; } bool getKeyState(entry::Key::Enum _key, uint8_t* _modifiers) { uint8_t modifiers; _modifiers = NULL == _modifiers ? &modifiers : _modifiers; return decodeKeyState(m_key[_key], *_modifiers); } uint8_t getModifiersState() { uint8_t modifiers = 0; for (uint32_t ii = 0; ii < entry::Key::Count; ++ii) { modifiers |= (m_key[ii]>>16)&0xff; } return modifiers; } void pushChar(uint8_t _len, const uint8_t _char[4]) { for (uint32_t len = m_ring.reserve(4) ; len < _len ; len = m_ring.reserve(4) ) { popChar(); } bx::memCopy(&m_char[m_ring.m_current], _char, 4); m_ring.commit(4); } const uint8_t* popChar() { if (0 < m_ring.available() ) { uint8_t* utf8 = &m_char[m_ring.m_read]; m_ring.consume(4); return utf8; } return NULL; } void charFlush() { m_ring.m_current = 0; m_ring.m_write = 0; m_ring.m_read = 0; } uint32_t m_key[256]; bool m_once[256]; bx::RingBufferControl m_ring; uint8_t m_char[256]; }; struct Gamepad { Gamepad() { reset(); } void reset() { bx::memSet(m_axis, 0, sizeof(m_axis) ); } void setAxis(entry::GamepadAxis::Enum _axis, int32_t _value) { m_axis[_axis] = _value; } int32_t getAxis(entry::GamepadAxis::Enum _axis) { return m_axis[_axis]; } int32_t m_axis[entry::GamepadAxis::Count]; }; struct Input { Input() { reset(); } ~Input() { } void addBindings(const char* _name, const InputBinding* _bindings) { m_inputBindingsMap.insert(stl::make_pair(stl::string(_name), _bindings) ); } void removeBindings(const char* _name) { InputBindingMap::iterator it = m_inputBindingsMap.find(stl::string(_name)); if (it != m_inputBindingsMap.end() ) { m_inputBindingsMap.erase(it); } } void process(const InputBinding* _bindings) { for (const InputBinding* binding = _bindings; binding->m_key != entry::Key::None; ++binding) { uint8_t modifiers; bool down = InputKeyboard::decodeKeyState(m_keyboard.m_key[binding->m_key], modifiers); if (binding->m_flags == 1) { if (down) { if (modifiers == binding->m_modifiers && !m_keyboard.m_once[binding->m_key]) { if (NULL == binding->m_fn) { cmdExec( (const char*)binding->m_userData); } else { binding->m_fn(binding->m_userData); } m_keyboard.m_once[binding->m_key] = true; } } else { m_keyboard.m_once[binding->m_key] = false; } } else { if (down && modifiers == binding->m_modifiers) { if (NULL == binding->m_fn) { cmdExec( (const char*)binding->m_userData); } else { binding->m_fn(binding->m_userData); } } } } } void process() { for (InputBindingMap::const_iterator it = m_inputBindingsMap.begin(); it != m_inputBindingsMap.end(); ++it) { process(it->second); } } void reset() { m_mouse.reset(); m_keyboard.reset(); for (uint32_t ii = 0; ii < BX_COUNTOF(m_gamepad); ++ii) { m_gamepad[ii].reset(); } } typedef stl::unordered_map<stl::string, const InputBinding*> InputBindingMap; InputBindingMap m_inputBindingsMap; InputKeyboard m_keyboard; InputMouse m_mouse; Gamepad m_gamepad[ENTRY_CONFIG_MAX_GAMEPADS]; }; static Input* s_input; void inputInit() { s_input = BX_NEW(entry::getAllocator(), Input); } void inputShutdown() { BX_DELETE(entry::getAllocator(), s_input); } void inputAddBindings(const char* _name, const InputBinding* _bindings) { s_input->addBindings(_name, _bindings); } void inputRemoveBindings(const char* _name) { s_input->removeBindings(_name); } void inputProcess() { s_input->process(); } void inputSetMouseResolution(uint16_t _width, uint16_t _height) { s_input->m_mouse.setResolution(_width, _height); } void inputSetKeyState(entry::Key::Enum _key, uint8_t _modifiers, bool _down) { s_input->m_keyboard.setKeyState(_key, _modifiers, _down); } bool inputGetKeyState(entry::Key::Enum _key, uint8_t* _modifiers) { return s_input->m_keyboard.getKeyState(_key, _modifiers); } uint8_t inputGetModifiersState() { return s_input->m_keyboard.getModifiersState(); } void inputChar(uint8_t _len, const uint8_t _char[4]) { s_input->m_keyboard.pushChar(_len, _char); } const uint8_t* inputGetChar() { return s_input->m_keyboard.popChar(); } void inputCharFlush() { s_input->m_keyboard.charFlush(); } void inputSetMousePos(int32_t _mx, int32_t _my, int32_t _mz) { s_input->m_mouse.setPos(_mx, _my, _mz); } void inputSetMouseButtonState(entry::MouseButton::Enum _button, uint8_t _state) { s_input->m_mouse.setButtonState(_button, _state); } void inputGetMouse(float _mouse[3]) { _mouse[0] = s_input->m_mouse.m_norm[0]; _mouse[1] = s_input->m_mouse.m_norm[1]; _mouse[2] = s_input->m_mouse.m_norm[2]; s_input->m_mouse.m_norm[0] = 0.0f; s_input->m_mouse.m_norm[1] = 0.0f; s_input->m_mouse.m_norm[2] = 0.0f; } bool inputIsMouseLocked() { return s_input->m_mouse.m_lock; } void inputSetMouseLock(bool _lock) { if (s_input->m_mouse.m_lock != _lock) { s_input->m_mouse.m_lock = _lock; entry::WindowHandle defaultWindow = { 0 }; entry::setMouseLock(defaultWindow, _lock); if (_lock) { s_input->m_mouse.m_norm[0] = 0.0f; s_input->m_mouse.m_norm[1] = 0.0f; s_input->m_mouse.m_norm[2] = 0.0f; } } } void inputSetGamepadAxis(entry::GamepadHandle _handle, entry::GamepadAxis::Enum _axis, int32_t _value) { s_input->m_gamepad[_handle.idx].setAxis(_axis, _value); } int32_t inputGetGamepadAxis(entry::GamepadHandle _handle, entry::GamepadAxis::Enum _axis) { return s_input->m_gamepad[_handle.idx].getAxis(_axis); }
[ "dulyts@inf.elte.hu" ]
dulyts@inf.elte.hu
9826a8b66416cc7d873122fa756d54d822e79e3a
770020440191739742f01a110111bdcaf9e748f7
/library/dfx/comon/main_dfx.cpp
5e166980c1ae2ef0d8e4535a70363b13eecf611c
[ "MIT" ]
permissive
ValensTry/atom
f63091ff375ec68449d5991bcfd1f576ad4cc8b6
855ea73ccb73851eb6201deb18d14311a3898890
refs/heads/master
2020-09-12T03:02:56.109223
2019-11-17T16:57:55
2019-11-17T16:57:55
222,280,486
0
0
null
2019-11-17T16:50:11
2019-11-17T16:50:11
null
GB18030
C++
false
false
1,266
cpp
#include "unit_test.hpp" #include "..\..\rsc\common\utility.h" /* 想加入什么单元测试就直接在以下 include 子模块的文件加入编译时会自动注册对应的单元测试类。 */ #define S3_UT 1 #if S3_UT #include "dfx\s3_interface\s3_test.hpp" #endif //S3_UT static void printSetting(int Argc_F, char* Argv_F[], char* Envp_F[]) { printf("\r\n############## UNIT TEST ################\r\n"); printf("| No. | Arguments(Total: [%d])\r\n", Argc_F); for (int iIndex = 0; iIndex < Argc_F; iIndex++) { printf("+------+-------------------------------\r\n"); printf("| %-4d : %s\n", iIndex, Argv_F[iIndex]); } printf("+======+===============================\r\n"); printf("| No. | Environment\r\n"); for (int iIndex = 0; Envp_F[iIndex] != NULL; iIndex++) { printf("+------+-------------------------------\r\n"); printf("| %-4d : %s\n", iIndex, Envp_F[iIndex]); } printf("+======+===============================\r\n"); system("pause"); } int main(int argc, char *argv[], char *envp[]) { printSetting(argc, argv, envp); InitWinSock instWinsock2; return RUN_ALL_TESTS(argc == 2 ? argv[1] : '\0'); }
[ "pengwanring@live.com" ]
pengwanring@live.com
6a5d71676082bd191b8743ea63def188c606762d
fa3c7c425578f773186aa267c8383ff1e9fedb9d
/src/utilities/ppm.cpp
6312bb04bc70a82b767808af07bcda7826d0f881
[]
no_license
davetcoleman/ompl_visual_tools
ff74fb7dc834ea629bc18ed642a85c3d6d44c8b5
4882529b9c46b4e6959c98e7344b7179d0a1857e
refs/heads/kinetic-devel
2020-05-21T19:59:57.761491
2017-03-12T22:07:45
2017-03-12T22:07:45
5,268,019
45
26
null
2017-03-04T23:45:49
2012-08-02T03:48:34
C++
UTF-8
C++
false
false
4,084
cpp
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2015, University of Colorado, Boulder * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Univ of CO, Boulder 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 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. *********************************************************************/ /* * PPM Image Format Reader * Code adapted from http://stackoverflow.com/questions/2693631/read-ppm-file-and-store-it-in-an-array-coded-with-c * User: rpf * 8/1/2012 */ #include <ompl_visual_tools/utilities/ppm.h> namespace ompl_visual_tools { // ************************************************************************************************* // Reading Function // ************************************************************************************************* PPMImage *readPPM(const char *filename) { char buff[16]; PPMImage *img; FILE *fp; int c, rgb_comp_color; //open PPM file for reading fp = fopen(filename, "rb"); if (!fp) { fprintf(stderr, "Unable to open file '%s'\n", filename); exit(1); } //read image format if (!fgets(buff, sizeof(buff), fp)) { perror(filename); exit(1); } //check the image format if (buff[0] != 'P' || buff[1] != '6') { fprintf(stderr, "Invalid image format (must be 'P6')\n"); exit(1); } //alloc memory form image img = (PPMImage *)malloc(sizeof(PPMImage)); if (!img) { fprintf(stderr, "Unable to allocate memory\n"); exit(1); } //check for comments c = getc(fp); while (c == '#') { while (getc(fp) != '\n') ; c = getc(fp); } ungetc(c, fp); //read image size information if (fscanf(fp, "%d %d", &img->x, &img->y) != 2) { fprintf(stderr, "Invalid image size (error loading '%s')\n", filename); exit(1); } //read rgb component if (fscanf(fp, "%d", &rgb_comp_color) != 1) { fprintf(stderr, "Invalid rgb component (error loading '%s')\n", filename); exit(1); } //check rgb component depth if (rgb_comp_color!= RGB_COMPONENT_COLOR) { fprintf(stderr, "'%s' does not have 8-bits components\n", filename); exit(1); } while (fgetc(fp) != '\n') ; //memory allocation for pixel data img->data = (PPMPixel*)malloc(img->x * img->y * sizeof(PPMPixel)); if (!img) { fprintf(stderr, "Unable to allocate memory\n"); exit(1); } //read pixel data from file if ( fread( img->data, 3 * img->x, img->y, fp) != img->y) { fprintf(stderr, "Error loading image '%s'\n", filename); exit(1); } // Close the file pointer fclose(fp); return img; } } // namespace
[ "davetcoleman@gmail.com" ]
davetcoleman@gmail.com
298e624b9a1cb25ad8f1fdb5bf891a965356d620
e58c3c7281a612d3a1d4cd6e06fa7fb4ce67a5b4
/Products/PDFWorks/dms_comm.h
0c056fe8b366504bd849013e47aa11deb3f5ca72
[ "MIT" ]
permissive
TrevorDArcyEvans/Diving-Magpie-Software
b6e117e4c50030b208f5e2e9650fd169f7d6daac
7ffcfef653b110e514d5db735d11be0aae9953ec
refs/heads/master
2022-04-10T11:23:57.914631
2020-03-24T13:24:54
2020-03-24T13:24:54
249,255,200
3
0
null
null
null
null
UTF-8
C++
false
false
17,698
h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 5.01.0164 */ /* at Sun Nov 05 15:14:43 2000 */ /* Compiler settings for C:\Wombat\Pro\DMS_Common\DMS_Comm.idl: Os (OptLev=s), W1, Zp8, env=Win32, ms_ext, c_ext error checks: allocation ref bounds_check enum stub_data */ //@@MIDL_FILE_HEADING( ) /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 440 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __DMS_Comm_h__ #define __DMS_Comm_h__ #ifdef __cplusplus extern "C"{ #endif /* Forward Declarations */ #ifndef __IDMS_Common_FWD_DEFINED__ #define __IDMS_Common_FWD_DEFINED__ typedef interface IDMS_Common IDMS_Common; #endif /* __IDMS_Common_FWD_DEFINED__ */ #ifndef __DMS_Common_FWD_DEFINED__ #define __DMS_Common_FWD_DEFINED__ #ifdef __cplusplus typedef class DMS_Common DMS_Common; #else typedef struct DMS_Common DMS_Common; #endif /* __cplusplus */ #endif /* __DMS_Common_FWD_DEFINED__ */ void __RPC_FAR * __RPC_USER MIDL_user_allocate(size_t); void __RPC_USER MIDL_user_free( void __RPC_FAR * ); #ifndef __DMS_Comm_LIBRARY_DEFINED__ #define __DMS_Comm_LIBRARY_DEFINED__ /* library DMS_Comm */ /* [custom][custom][helpstring][version][uuid] */ DEFINE_GUID(LIBID_DMS_Comm,0xFC99C7B2,0x4A88,0x11D4,0x8A,0x03,0x00,0x20,0xAF,0xCC,0x56,0x95); #ifndef __IDMS_Common_INTERFACE_DEFINED__ #define __IDMS_Common_INTERFACE_DEFINED__ /* interface IDMS_Common */ /* [object][oleautomation][dual][helpstring][version][uuid] */ DEFINE_GUID(IID_IDMS_Common,0xFC99C7B3,0x4A88,0x11D4,0x8A,0x03,0x00,0x20,0xAF,0xCC,0x56,0x95); #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("FC99C7B3-4A88-11D4-8A03-0020AFCC5695") IDMS_Common : public IDispatch { public: virtual /* [id] */ HRESULT __stdcall About( void) = 0; virtual /* [id][propput] */ HRESULT __stdcall put_Icon( /* [in] */ long Param1) = 0; virtual /* [id][propput] */ HRESULT __stdcall put_ProductName( /* [in] */ BSTR sProductName) = 0; virtual /* [id][propget] */ HRESULT __stdcall get_ProductName( /* [retval][out] */ BSTR __RPC_FAR *sProductName) = 0; virtual /* [id][propput] */ HRESULT __stdcall put_ProductCode( /* [in] */ BSTR sProductCode) = 0; virtual /* [id][propget] */ HRESULT __stdcall get_ProductCode( /* [retval][out] */ BSTR __RPC_FAR *sProductCode) = 0; virtual /* [id][propput] */ HRESULT __stdcall put_AuthCode( /* [in] */ BSTR Param1) = 0; virtual /* [id][propget] */ HRESULT __stdcall get_IsRegistered( /* [retval][out] */ int __RPC_FAR *bIsRegistered) = 0; virtual /* [id] */ HRESULT __stdcall Register( void) = 0; virtual /* [id] */ HRESULT __stdcall IsSolidWorksFile( /* [in] */ BSTR sFileName, /* [retval][out] */ int __RPC_FAR *bIsSolidWorksFile) = 0; virtual /* [id][propget] */ HRESULT __stdcall get_Commercial( /* [retval][out] */ int __RPC_FAR *Value) = 0; virtual /* [id][propput] */ HRESULT __stdcall put_Commercial( /* [in] */ int Value) = 0; virtual /* [id] */ HRESULT __stdcall IsSolidWorksRunning( /* [retval][out] */ int __RPC_FAR *bIsSolidWorksRunning) = 0; virtual /* [id] */ HRESULT __stdcall GetMachineID( /* [retval][out] */ BSTR __RPC_FAR *sMachineID) = 0; virtual /* [id][propget] */ HRESULT __stdcall get_IniFileName( /* [retval][out] */ BSTR __RPC_FAR *Value) = 0; virtual /* [id][propput] */ HRESULT __stdcall put_IniFileName( /* [in] */ BSTR Value) = 0; virtual /* [id][propput] */ HRESULT __stdcall put_SolidWorks( /* [in] */ IDispatch __RPC_FAR *Value) = 0; }; #else /* C style interface */ typedef struct IDMS_CommonVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( IDMS_Common __RPC_FAR * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( IDMS_Common __RPC_FAR * This); ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( IDMS_Common __RPC_FAR * This); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTypeInfoCount )( IDMS_Common __RPC_FAR * This, /* [out] */ UINT __RPC_FAR *pctinfo); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTypeInfo )( IDMS_Common __RPC_FAR * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetIDsOfNames )( IDMS_Common __RPC_FAR * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Invoke )( IDMS_Common __RPC_FAR * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); /* [id] */ HRESULT ( __stdcall __RPC_FAR *About )( IDMS_Common __RPC_FAR * This); /* [id][propput] */ HRESULT ( __stdcall __RPC_FAR *put_Icon )( IDMS_Common __RPC_FAR * This, /* [in] */ long Param1); /* [id][propput] */ HRESULT ( __stdcall __RPC_FAR *put_ProductName )( IDMS_Common __RPC_FAR * This, /* [in] */ BSTR sProductName); /* [id][propget] */ HRESULT ( __stdcall __RPC_FAR *get_ProductName )( IDMS_Common __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *sProductName); /* [id][propput] */ HRESULT ( __stdcall __RPC_FAR *put_ProductCode )( IDMS_Common __RPC_FAR * This, /* [in] */ BSTR sProductCode); /* [id][propget] */ HRESULT ( __stdcall __RPC_FAR *get_ProductCode )( IDMS_Common __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *sProductCode); /* [id][propput] */ HRESULT ( __stdcall __RPC_FAR *put_AuthCode )( IDMS_Common __RPC_FAR * This, /* [in] */ BSTR Param1); /* [id][propget] */ HRESULT ( __stdcall __RPC_FAR *get_IsRegistered )( IDMS_Common __RPC_FAR * This, /* [retval][out] */ int __RPC_FAR *bIsRegistered); /* [id] */ HRESULT ( __stdcall __RPC_FAR *Register )( IDMS_Common __RPC_FAR * This); /* [id] */ HRESULT ( __stdcall __RPC_FAR *IsSolidWorksFile )( IDMS_Common __RPC_FAR * This, /* [in] */ BSTR sFileName, /* [retval][out] */ int __RPC_FAR *bIsSolidWorksFile); /* [id][propget] */ HRESULT ( __stdcall __RPC_FAR *get_Commercial )( IDMS_Common __RPC_FAR * This, /* [retval][out] */ int __RPC_FAR *Value); /* [id][propput] */ HRESULT ( __stdcall __RPC_FAR *put_Commercial )( IDMS_Common __RPC_FAR * This, /* [in] */ int Value); /* [id] */ HRESULT ( __stdcall __RPC_FAR *IsSolidWorksRunning )( IDMS_Common __RPC_FAR * This, /* [retval][out] */ int __RPC_FAR *bIsSolidWorksRunning); /* [id] */ HRESULT ( __stdcall __RPC_FAR *GetMachineID )( IDMS_Common __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *sMachineID); /* [id][propget] */ HRESULT ( __stdcall __RPC_FAR *get_IniFileName )( IDMS_Common __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Value); /* [id][propput] */ HRESULT ( __stdcall __RPC_FAR *put_IniFileName )( IDMS_Common __RPC_FAR * This, /* [in] */ BSTR Value); /* [id][propput] */ HRESULT ( __stdcall __RPC_FAR *put_SolidWorks )( IDMS_Common __RPC_FAR * This, /* [in] */ IDispatch __RPC_FAR *Value); END_INTERFACE } IDMS_CommonVtbl; interface IDMS_Common { CONST_VTBL struct IDMS_CommonVtbl __RPC_FAR *lpVtbl; }; #ifdef COBJMACROS #define IDMS_Common_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IDMS_Common_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IDMS_Common_Release(This) \ (This)->lpVtbl -> Release(This) #define IDMS_Common_GetTypeInfoCount(This,pctinfo) \ (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) #define IDMS_Common_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define IDMS_Common_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define IDMS_Common_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #define IDMS_Common_About(This) \ (This)->lpVtbl -> About(This) #define IDMS_Common_put_Icon(This,Param1) \ (This)->lpVtbl -> put_Icon(This,Param1) #define IDMS_Common_put_ProductName(This,sProductName) \ (This)->lpVtbl -> put_ProductName(This,sProductName) #define IDMS_Common_get_ProductName(This,sProductName) \ (This)->lpVtbl -> get_ProductName(This,sProductName) #define IDMS_Common_put_ProductCode(This,sProductCode) \ (This)->lpVtbl -> put_ProductCode(This,sProductCode) #define IDMS_Common_get_ProductCode(This,sProductCode) \ (This)->lpVtbl -> get_ProductCode(This,sProductCode) #define IDMS_Common_put_AuthCode(This,Param1) \ (This)->lpVtbl -> put_AuthCode(This,Param1) #define IDMS_Common_get_IsRegistered(This,bIsRegistered) \ (This)->lpVtbl -> get_IsRegistered(This,bIsRegistered) #define IDMS_Common_Register(This) \ (This)->lpVtbl -> Register(This) #define IDMS_Common_IsSolidWorksFile(This,sFileName,bIsSolidWorksFile) \ (This)->lpVtbl -> IsSolidWorksFile(This,sFileName,bIsSolidWorksFile) #define IDMS_Common_get_Commercial(This,Value) \ (This)->lpVtbl -> get_Commercial(This,Value) #define IDMS_Common_put_Commercial(This,Value) \ (This)->lpVtbl -> put_Commercial(This,Value) #define IDMS_Common_IsSolidWorksRunning(This,bIsSolidWorksRunning) \ (This)->lpVtbl -> IsSolidWorksRunning(This,bIsSolidWorksRunning) #define IDMS_Common_GetMachineID(This,sMachineID) \ (This)->lpVtbl -> GetMachineID(This,sMachineID) #define IDMS_Common_get_IniFileName(This,Value) \ (This)->lpVtbl -> get_IniFileName(This,Value) #define IDMS_Common_put_IniFileName(This,Value) \ (This)->lpVtbl -> put_IniFileName(This,Value) #define IDMS_Common_put_SolidWorks(This,Value) \ (This)->lpVtbl -> put_SolidWorks(This,Value) #endif /* COBJMACROS */ #endif /* C style interface */ /* [id] */ HRESULT __stdcall IDMS_Common_About_Proxy( IDMS_Common __RPC_FAR * This); void __RPC_STUB IDMS_Common_About_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propput] */ HRESULT __stdcall IDMS_Common_put_Icon_Proxy( IDMS_Common __RPC_FAR * This, /* [in] */ long Param1); void __RPC_STUB IDMS_Common_put_Icon_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propput] */ HRESULT __stdcall IDMS_Common_put_ProductName_Proxy( IDMS_Common __RPC_FAR * This, /* [in] */ BSTR sProductName); void __RPC_STUB IDMS_Common_put_ProductName_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propget] */ HRESULT __stdcall IDMS_Common_get_ProductName_Proxy( IDMS_Common __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *sProductName); void __RPC_STUB IDMS_Common_get_ProductName_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propput] */ HRESULT __stdcall IDMS_Common_put_ProductCode_Proxy( IDMS_Common __RPC_FAR * This, /* [in] */ BSTR sProductCode); void __RPC_STUB IDMS_Common_put_ProductCode_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propget] */ HRESULT __stdcall IDMS_Common_get_ProductCode_Proxy( IDMS_Common __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *sProductCode); void __RPC_STUB IDMS_Common_get_ProductCode_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propput] */ HRESULT __stdcall IDMS_Common_put_AuthCode_Proxy( IDMS_Common __RPC_FAR * This, /* [in] */ BSTR Param1); void __RPC_STUB IDMS_Common_put_AuthCode_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propget] */ HRESULT __stdcall IDMS_Common_get_IsRegistered_Proxy( IDMS_Common __RPC_FAR * This, /* [retval][out] */ int __RPC_FAR *bIsRegistered); void __RPC_STUB IDMS_Common_get_IsRegistered_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id] */ HRESULT __stdcall IDMS_Common_Register_Proxy( IDMS_Common __RPC_FAR * This); void __RPC_STUB IDMS_Common_Register_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id] */ HRESULT __stdcall IDMS_Common_IsSolidWorksFile_Proxy( IDMS_Common __RPC_FAR * This, /* [in] */ BSTR sFileName, /* [retval][out] */ int __RPC_FAR *bIsSolidWorksFile); void __RPC_STUB IDMS_Common_IsSolidWorksFile_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propget] */ HRESULT __stdcall IDMS_Common_get_Commercial_Proxy( IDMS_Common __RPC_FAR * This, /* [retval][out] */ int __RPC_FAR *Value); void __RPC_STUB IDMS_Common_get_Commercial_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propput] */ HRESULT __stdcall IDMS_Common_put_Commercial_Proxy( IDMS_Common __RPC_FAR * This, /* [in] */ int Value); void __RPC_STUB IDMS_Common_put_Commercial_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id] */ HRESULT __stdcall IDMS_Common_IsSolidWorksRunning_Proxy( IDMS_Common __RPC_FAR * This, /* [retval][out] */ int __RPC_FAR *bIsSolidWorksRunning); void __RPC_STUB IDMS_Common_IsSolidWorksRunning_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id] */ HRESULT __stdcall IDMS_Common_GetMachineID_Proxy( IDMS_Common __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *sMachineID); void __RPC_STUB IDMS_Common_GetMachineID_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propget] */ HRESULT __stdcall IDMS_Common_get_IniFileName_Proxy( IDMS_Common __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Value); void __RPC_STUB IDMS_Common_get_IniFileName_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propput] */ HRESULT __stdcall IDMS_Common_put_IniFileName_Proxy( IDMS_Common __RPC_FAR * This, /* [in] */ BSTR Value); void __RPC_STUB IDMS_Common_put_IniFileName_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propput] */ HRESULT __stdcall IDMS_Common_put_SolidWorks_Proxy( IDMS_Common __RPC_FAR * This, /* [in] */ IDispatch __RPC_FAR *Value); void __RPC_STUB IDMS_Common_put_SolidWorks_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IDMS_Common_INTERFACE_DEFINED__ */ DEFINE_GUID(CLSID_DMS_Common,0xFC99C7B5,0x4A88,0x11D4,0x8A,0x03,0x00,0x20,0xAF,0xCC,0x56,0x95); #ifdef __cplusplus class DECLSPEC_UUID("FC99C7B5-4A88-11D4-8A03-0020AFCC5695") DMS_Common; #endif #endif /* __DMS_Comm_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
[ "tdarcyevans@hotmail.com" ]
tdarcyevans@hotmail.com
ea4604694f3c4799442307dafbf5ebb9e605f05a
4c7abf4437e65f3a88e082cf702f78772ca2cd07
/constraint.h
b5ecd38c2cbf926b6e9cdbba7f26861ada331d3b
[]
no_license
DoubleTimeOnly/Battleship-Puzzle-
5d6c918ceeafcac4ecae486787b1b317759dc8cc
b8d97406ba899dd8a17358b20a2e586e00fe7a3b
refs/heads/master
2020-06-12T16:06:49.820554
2016-12-07T03:36:01
2016-12-07T03:36:01
75,795,543
0
0
null
null
null
null
UTF-8
C++
false
false
270
h
//File: constraint.h #ifndef _CONSTRAINT_H_INCLUDED #define _CONSTRAINT_H_INCLUDED class Constraint { public: Constraint(int a_row,int a_column,char a_type) : row(a_row),column(a_column),type(a_type) {} int row,column; char type; }; #endif
[ "noreply@github.com" ]
noreply@github.com
7ea13d10efe2d03f0c6a39d9aa553368ce1fb061
31cb75420b6476675081a59afa7927e0eadc9151
/3/playground/try_for.cpp
1dd19020144a2c4edd7362af4c60f9d8b3d203a2
[]
no_license
LakshSingla/learning-cpp
5963af2f5265bedc407d9d71ca3a61bc82f3e8fa
7c7794cc3a8db2ee41cde62c292ffdea951098ad
refs/heads/master
2018-09-19T17:56:56.280855
2018-07-28T16:40:39
2018-07-28T16:40:39
117,106,116
0
0
null
null
null
null
UTF-8
C++
false
false
174
cpp
#include <iostream> using namespace std; int main(){ for(int i = 1; i <=10; i++){ cout<<i<<endl; if(i%2){ continue; } cout<<i<<endl; } cout<<endl; return 0; }
[ "lakshsingla@gmail.com" ]
lakshsingla@gmail.com
92f621a5a54a8ee869d8cd7cc30236f0fa064cc4
ccab7298de8b2b426bf31a3a7ff39408c379ead5
/Common/Utils.cpp
92529ab3074b7e1cec5fb42a93654f29ed707336
[ "MIT" ]
permissive
zbqxyz/J1939-Framework
c0ae876873c6ac186777ef37f2b64940e7623ecb
1209dcbba3fbd1702c85f7b1daa58f6f10df0c50
refs/heads/master
2020-04-27T20:08:18.740723
2019-03-04T20:38:59
2019-03-04T20:38:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,204
cpp
/* * Utils.cpp * * Created on: Apr 5, 2018 * Author: famez */ #include <chrono> #include "Utils.h" namespace Utils { u32 getElapsedMillis(timespec* start, timespec* end) { return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_nsec - start->tv_nsec) / 1000000; } timespec addMillis(timespec* time, u32 millis) { timespec retVal; retVal.tv_nsec = time->tv_nsec + (millis % 1000) * 1000000; retVal.tv_sec = time->tv_sec + millis / 1000; return retVal; } TimeStamp TimeStamp::operator-(const TimeStamp& other) const { TimeStamp retVal(*this); if(other.mMicroSec > mMicroSec) { if(other.mSeconds >= mSeconds) { return TimeStamp(); } else { retVal.mMicroSec = mMicroSec + 1000000; retVal.mSeconds = mSeconds - 1; } } if(other.mSeconds > retVal.mSeconds) { return TimeStamp(); } retVal.mSeconds = retVal.mSeconds - other.mSeconds; retVal.mMicroSec = retVal.mMicroSec - other.mMicroSec; return retVal; } TimeStamp TimeStamp::operator+(const TimeStamp& other) const { TimeStamp retVal(*this); retVal.mSeconds = retVal.mSeconds + other.mSeconds; retVal.mMicroSec = retVal.mMicroSec + other.mMicroSec; if(retVal.mMicroSec > 1000000) { retVal.mMicroSec -= 1000000; ++retVal.mSeconds; } return retVal; } bool TimeStamp::operator>(const TimeStamp& other) const { if(mSeconds > other.mSeconds) return true; if(mSeconds == other.mSeconds && mMicroSec > other.mMicroSec) return true; return false; } bool TimeStamp::operator<(const TimeStamp& other) const { if(mSeconds < other.mSeconds) return true; if(mSeconds == other.mSeconds && mMicroSec < other.mMicroSec) return true; return false; } TimeStamp TimeStamp::operator-(u32 millis) const { TimeStamp aux(millis/1000, (millis%1000)*1000); return (*this - aux); } TimeStamp TimeStamp::operator+(u32 millis) const { TimeStamp aux(millis/1000, (millis%1000)*1000); return (*this + aux); } TimeStamp TimeStamp::now() { auto now = std::chrono::steady_clock::now(); auto duration = now.time_since_epoch(); auto micro = std::chrono::duration_cast<std::chrono::microseconds>(duration); return TimeStamp(micro.count() / 1000000, micro.count() % 1000000); } }
[ "f.amez1992@gmail.com" ]
f.amez1992@gmail.com
dc60cf1e93434bca21bf580f4fcf9f8aeb2c3537
83d9d024ee6015978e65612593de6cc682cf585a
/src/test/skiplist_tests.cpp
79fac30fffc8c461595c50aec438732e345e4061
[ "MIT" ]
permissive
waggoxpay/waggox
ba0ceba1d8830782b1ad9b758d0ba12325caa104
d301ef289238510bc46ea2429bc25af0d1c616d7
refs/heads/master
2020-04-22T06:16:50.316701
2019-02-12T18:24:41
2019-02-12T18:24:41
163,040,649
0
0
MIT
2019-02-11T13:21:11
2018-12-25T03:03:16
C++
UTF-8
C++
false
false
6,015
cpp
// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chain.h" #include "util.h" #include "test/test_waggox.h" #include "test/test_random.h" #include <vector> #include <boost/test/unit_test.hpp> #define SKIPLIST_LENGTH 300000 BOOST_FIXTURE_TEST_SUITE(skiplist_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(skiplist_test) { std::vector<CBlockIndex> vIndex(SKIPLIST_LENGTH); for (int i=0; i<SKIPLIST_LENGTH; i++) { vIndex[i].nHeight = i; vIndex[i].pprev = (i == 0) ? NULL : &vIndex[i - 1]; vIndex[i].BuildSkip(); } for (int i=0; i<SKIPLIST_LENGTH; i++) { if (i > 0) { BOOST_CHECK(vIndex[i].pskip == &vIndex[vIndex[i].pskip->nHeight]); BOOST_CHECK(vIndex[i].pskip->nHeight < i); } else { BOOST_CHECK(vIndex[i].pskip == NULL); } } for (int i=0; i < 1000; i++) { int from = insecure_rand() % (SKIPLIST_LENGTH - 1); int to = insecure_rand() % (from + 1); BOOST_CHECK(vIndex[SKIPLIST_LENGTH - 1].GetAncestor(from) == &vIndex[from]); BOOST_CHECK(vIndex[from].GetAncestor(to) == &vIndex[to]); BOOST_CHECK(vIndex[from].GetAncestor(0) == &vIndex[0]); } } BOOST_AUTO_TEST_CASE(getlocator_test) { // Build a main chain 100000 blocks long. std::vector<uint256> vHashMain(100000); std::vector<CBlockIndex> vBlocksMain(100000); for (unsigned int i=0; i<vBlocksMain.size(); i++) { vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height, so we can quickly check the distances. vBlocksMain[i].nHeight = i; vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : NULL; vBlocksMain[i].phashBlock = &vHashMain[i]; vBlocksMain[i].BuildSkip(); BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksMain[i].GetBlockHash()).GetLow64(), vBlocksMain[i].nHeight); BOOST_CHECK(vBlocksMain[i].pprev == NULL || vBlocksMain[i].nHeight == vBlocksMain[i].pprev->nHeight + 1); } // Build a branch that splits off at block 424126, 50000 blocks long. std::vector<uint256> vHashSide(50000); std::vector<CBlockIndex> vBlocksSide(50000); for (unsigned int i=0; i<vBlocksSide.size(); i++) { vHashSide[i] = ArithToUint256(i + 50000 + (arith_uint256(1) << 128)); // Add 1<<128 to the hashes, so GetLow64() still returns the height. vBlocksSide[i].nHeight = i + 50000; vBlocksSide[i].pprev = i ? &vBlocksSide[i - 1] : &vBlocksMain[424126]; vBlocksSide[i].phashBlock = &vHashSide[i]; vBlocksSide[i].BuildSkip(); BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksSide[i].GetBlockHash()).GetLow64(), vBlocksSide[i].nHeight); BOOST_CHECK(vBlocksSide[i].pprev == NULL || vBlocksSide[i].nHeight == vBlocksSide[i].pprev->nHeight + 1); } // Build a CChain for the main branch. CChain chain; chain.SetTip(&vBlocksMain.back()); // Test 100 random starting points for locators. for (int n=0; n<100; n++) { int r = insecure_rand() % 150000; CBlockIndex* tip = (r < 100000) ? &vBlocksMain[r] : &vBlocksSide[r - 100000]; CBlockLocator locator = chain.GetLocator(tip); // The first result must be the block itself, the last one must be genesis. BOOST_CHECK(locator.vHave.front() == tip->GetBlockHash()); BOOST_CHECK(locator.vHave.back() == vBlocksMain[0].GetBlockHash()); // Entries 1 through 11 (inclusive) go back one step each. for (unsigned int i = 1; i < 12 && i < locator.vHave.size() - 1; i++) { BOOST_CHECK_EQUAL(UintToArith256(locator.vHave[i]).GetLow64(), tip->nHeight - i); } // The further ones (excluding the last one) go back with exponential steps. unsigned int dist = 2; for (unsigned int i = 12; i < locator.vHave.size() - 1; i++) { BOOST_CHECK_EQUAL(UintToArith256(locator.vHave[i - 1]).GetLow64() - UintToArith256(locator.vHave[i]).GetLow64(), dist); dist *= 2; } } } BOOST_AUTO_TEST_CASE(findearliestatleast_test) { std::vector<uint256> vHashMain(100000); std::vector<CBlockIndex> vBlocksMain(100000); for (unsigned int i=0; i<vBlocksMain.size(); i++) { vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height vBlocksMain[i].nHeight = i; vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : NULL; vBlocksMain[i].phashBlock = &vHashMain[i]; vBlocksMain[i].BuildSkip(); if (i < 10) { vBlocksMain[i].nTime = i; vBlocksMain[i].nTimeMax = i; } else { // randomly choose something in the range [MTP, MTP*2] int64_t medianTimePast = vBlocksMain[i].GetMedianTimePast(); int r = insecure_rand() % medianTimePast; vBlocksMain[i].nTime = r + medianTimePast; vBlocksMain[i].nTimeMax = std::max(vBlocksMain[i].nTime, vBlocksMain[i-1].nTimeMax); } } // Check that we set nTimeMax up correctly. unsigned int curTimeMax = 0; for (unsigned int i=0; i<vBlocksMain.size(); ++i) { curTimeMax = std::max(curTimeMax, vBlocksMain[i].nTime); BOOST_CHECK(curTimeMax == vBlocksMain[i].nTimeMax); } // Build a CChain for the main branch. CChain chain; chain.SetTip(&vBlocksMain.back()); // Verify that FindEarliestAtLeast is correct. for (unsigned int i=0; i<10000; ++i) { // Pick a random element in vBlocksMain. int r = insecure_rand() % vBlocksMain.size(); int64_t test_time = vBlocksMain[r].nTime; CBlockIndex *ret = chain.FindEarliestAtLeast(test_time); BOOST_CHECK(ret->nTimeMax >= test_time); BOOST_CHECK((ret->pprev==NULL) || ret->pprev->nTimeMax < test_time); BOOST_CHECK(vBlocksMain[r].GetAncestor(ret->nHeight) == ret); } } BOOST_AUTO_TEST_SUITE_END()
[ "txchange8@gmail.com" ]
txchange8@gmail.com
60b1b9fb0bccb0548fc7703acf7737accc2dc3ee
8ed505a357a9cd47f90a194e3c86a37591cafa16
/src/Currency.cpp
f34953a5fb2211dc0f65a37f2548d43c4a12f873
[]
no_license
rbapub/homebk
ff845e5fef38e1187fcc66b7802b3b15f5f986e6
988594fb926af989858e73e4d0d0f25fc9e94d38
refs/heads/master
2023-07-11T05:44:42.551677
2021-08-28T16:06:49
2021-08-28T16:06:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
380
cpp
#include <string> #include "Currency.h" using std::string; int Currency::nextId = 1; Currency::Currency(string cName) { id = nextId; nextId++; name = cName; } int Currency::getId() const { return id; } void Currency::setId(int i) { id = i; } string Currency::getName() const { return name; } void Currency::setName(string n) { name = n; } Currency::~Currency() { }
[ "romanab@live.ru" ]
romanab@live.ru
33fa5ebc8b77e7db497fbd1aa16fbd16f4eb18a0
4fa07a9065cbb7ab30e77cc7418a49a7bf5038dd
/src/caffe/util/io.cpp
729d1ad8e6ea279750ac64b018235025e2d0140f
[ "BSD-2-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
ZhaofanQiu/caffe-windows-3dConvNet
8367927e5a5aa661d8e2baf012b7704f8644521b
e4c16bba24329d3205e8aad26b5b8718d6b43cb2
refs/heads/master
2020-05-02T20:51:20.696956
2015-09-04T13:22:24
2015-09-04T13:22:24
41,130,759
10
6
null
null
null
null
UTF-8
C++
false
false
5,962
cpp
// Copyright 2014 BVLC and contributors. #include <stdint.h> #include <fcntl.h> #include <google/protobuf/text_format.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/io/coded_stream.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/highgui/highgui_c.h> #include <opencv2/imgproc/imgproc.hpp> #include <algorithm> #include <string> #include <vector> #include <fstream> // NOLINT(readability/streams) #include "caffe/common.hpp" #include "caffe/util/io.hpp" #include "caffe/proto/caffe.pb.h" #define open _open #define close _close using std::fstream; using std::ios; using std::max; using std::string; using google::protobuf::io::FileInputStream; using google::protobuf::io::FileOutputStream; using google::protobuf::io::ZeroCopyInputStream; using google::protobuf::io::CodedInputStream; using google::protobuf::io::ZeroCopyOutputStream; using google::protobuf::io::CodedOutputStream; using google::protobuf::Message; namespace caffe { bool ReadProtoFromTextFile(const char* filename, Message* proto) { int fd = open(filename, O_RDONLY); CHECK_NE(fd, -1) << "File not found: " << filename; FileInputStream* input = new FileInputStream(fd); bool success = google::protobuf::TextFormat::Parse(input, proto); delete input; close(fd); return success; } void WriteProtoToTextFile(const Message& proto, const char* filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644); FileOutputStream* output = new FileOutputStream(fd); CHECK(google::protobuf::TextFormat::Print(proto, output)); delete output; close(fd); } bool ReadProtoFromBinaryFile(const char* filename, Message* proto) { int fd = open(filename, O_RDONLY | O_BINARY); CHECK_NE(fd, -1) << "File not found: " << filename; ZeroCopyInputStream* raw_input = new FileInputStream(fd); CodedInputStream* coded_input = new CodedInputStream(raw_input); //coded_input->SetTotalBytesLimit(1073741824, 536870912); coded_input->SetTotalBytesLimit(2147483647, 1073741824); bool success = proto->ParseFromCodedStream(coded_input); delete coded_input; delete raw_input; close(fd); return success; } void WriteProtoToBinaryFile(const Message& proto, const char* filename) { fstream output(filename, ios::out | ios::trunc | ios::binary); CHECK(proto.SerializeToOstream(&output)); } bool ReadImageToDatum(const string& filename, const int label, const int height, const int width, Datum* datum) { cv::Mat cv_img; if (height > 0 && width > 0) { cv::Mat cv_img_origin = cv::imread(filename, CV_LOAD_IMAGE_COLOR); if (!cv_img_origin.data){ LOG(ERROR) << "Could not open or find file " << filename; return false; } cv::resize(cv_img_origin, cv_img, cv::Size(width, height)); } else { cv_img = cv::imread(filename, CV_LOAD_IMAGE_COLOR); } if (!cv_img.data) { LOG(ERROR) << "Could not open or find file " << filename; return false; } datum->set_channels(3); datum->set_height(cv_img.rows); datum->set_width(cv_img.cols); datum->set_label(label); datum->clear_data(); datum->clear_float_data(); string* datum_string = datum->mutable_data(); for (int c = 0; c < 3; ++c) { for (int h = 0; h < cv_img.rows; ++h) { for (int w = 0; w < cv_img.cols; ++w) { datum_string->push_back( static_cast<char>(cv_img.at<cv::Vec3b>(h, w)[c])); } } } return true; } // Verifies format of data stored in HDF5 file and reshapes blob accordingly. template <typename Dtype> void hdf5_load_nd_dataset_helper( hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<Dtype>* blob) { // Verify that the number of dimensions is in the accepted range. herr_t status; int ndims; status = H5LTget_dataset_ndims(file_id, dataset_name_, &ndims); CHECK_GE(ndims, min_dim); CHECK_LE(ndims, max_dim); // Verify that the data format is what we expect: float or double. std::vector<hsize_t> dims(ndims); H5T_class_t class_; status = H5LTget_dataset_info( file_id, dataset_name_, dims.data(), &class_, NULL); CHECK_EQ(class_, H5T_FLOAT) << "Expected float or double data"; blob->Reshape( dims[0], (dims.size() > 1) ? dims[1] : 1, (dims.size() > 2) ? dims[2] : 1, (dims.size() > 3) ? dims[3] : 1, (dims.size() > 4) ? dims[4] : 1); } template <> void hdf5_load_nd_dataset<float>(hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<float>* blob) { hdf5_load_nd_dataset_helper(file_id, dataset_name_, min_dim, max_dim, blob); herr_t status = H5LTread_dataset_float( file_id, dataset_name_, blob->mutable_cpu_data()); } template <> void hdf5_load_nd_dataset<double>(hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<double>* blob) { hdf5_load_nd_dataset_helper(file_id, dataset_name_, min_dim, max_dim, blob); herr_t status = H5LTread_dataset_double( file_id, dataset_name_, blob->mutable_cpu_data()); } template <> void hdf5_save_nd_dataset<float>( const hid_t file_id, const string dataset_name, const Blob<float>& blob) { hsize_t dims[HDF5_NUM_DIMS]; dims[0] = blob.num(); dims[1] = blob.channels(); dims[2] = blob.height(); dims[3] = blob.width(); herr_t status = H5LTmake_dataset_float( file_id, dataset_name.c_str(), HDF5_NUM_DIMS, dims, blob.cpu_data()); CHECK_GE(status, 0) << "Failed to make float dataset " << dataset_name; } template <> void hdf5_save_nd_dataset<double>( const hid_t file_id, const string dataset_name, const Blob<double>& blob) { hsize_t dims[HDF5_NUM_DIMS]; dims[0] = blob.num(); dims[1] = blob.channels(); dims[2] = blob.height(); dims[3] = blob.width(); herr_t status = H5LTmake_dataset_double( file_id, dataset_name.c_str(), HDF5_NUM_DIMS, dims, blob.cpu_data()); CHECK_GE(status, 0) << "Failed to make double dataset " << dataset_name; } } // namespace caffe
[ "zhaofanqiu@gmail.com" ]
zhaofanqiu@gmail.com
bcd3fcff086d8b327cfbcb90c58c64d0b3f3d3c3
c20c4812ac0164c8ec2434e1126c1fdb1a2cc09e
/Source/Source/Server/SO3GameCenter/Test/TestProject/NameGenerator.h
eda93af6af7237294a91c326d02b5a73f536eab8
[ "MIT" ]
permissive
uvbs/FullSource
f8673b02e10c8c749b9b88bf18018a69158e8cb9
07601c5f18d243fb478735b7bdcb8955598b9a90
refs/heads/master
2020-03-24T03:11:13.148940
2018-07-25T18:30:25
2018-07-25T18:30:25
142,408,505
2
2
null
2018-07-26T07:58:12
2018-07-26T07:58:12
null
UTF-8
C++
false
false
465
h
#pragma once #include <string> #include "utility.h" #include "Engine/KTextFilter.h" #include "testtools.h" #include <string> class NameGenerator { public: static NameGenerator* Instance(); bool Init(); ~NameGenerator(); TestTools::KRoleInfo Generator(); std::string IllegalName(int nLength); std::string LegalName(int nLength); private: NameGenerator(void); int m_nIndex; std::string m_NameBuff; ScopedPtrMalloc<ITextFilter, ComRelease> m_TextFilter; };
[ "dark.hades.1102@GAMIL.COM" ]
dark.hades.1102@GAMIL.COM
e0b6b8e55e1afc1adecd60c9c7a129593d94ff52
9167a62044270f6c5aa27a3b42fad8447a0391b6
/Player.cpp
ea6adecc379feda9ce480a86903c9db974fb904b
[]
no_license
alumina334/QuarterViewGame
e4e189c5ab6db449bc7f737a4d3aa9bfff0bbd7d
aa0e5ad18612cb28c277029ca7bd66d53737718b
refs/heads/master
2020-12-23T13:57:20.208148
2020-02-11T04:57:08
2020-02-11T04:57:08
237,173,315
0
0
null
null
null
null
UTF-8
C++
false
false
767
cpp
#include "Player.h" #include "DxLib.h" Player::Player(double x, double y, double z): mX(x), mY(y), mZ(z), mHandle(0){ } void Player::initialize() { mHandle = LoadGraph("./images/select_block.png"); } void Player::finalize() { } void Player::update() { if (Keyboard::keyboardGet(KEY_INPUT_W) > 0) { mZ -= 0.2; }else if (Keyboard::keyboardGet(KEY_INPUT_A) > 0) { mY -= 0.2; }else if (Keyboard::keyboardGet(KEY_INPUT_S) > 0) { mZ += 0.2; }else if (Keyboard::keyboardGet(KEY_INPUT_D) > 0) { mY += 0.2; } } void Player::draw(int x, int y) { DrawGraph(x - 16 , y - 32, mHandle, TRUE); } void Player::setXYZ(double x, double y, double z) { mX = x; mY = y; mZ = z; } void Player::getXYZ(double& x, double& y, double& z) { x = mX; y = mY; z = mZ; }
[ "rf.nazr@gmail.com" ]
rf.nazr@gmail.com
d9427f1986c7e70a576a986b68b05e2000e3069e
8ae6b1b46d56ed9a221ac498a3a67a655159b83a
/flexc++/rules/setlopblocks.cc
3a6bf51bfb26673523e2e68dda66f876fb4b5923
[]
no_license
ajunlonglive/flexcpp
decc3baa645ddfe6f455291c110d3250ba9c18bf
2de6b90d79d930152f767bf0117a8d2b26a11e12
refs/heads/master
2023-03-16T11:32:46.610788
2018-06-25T12:45:38
2018-06-25T12:45:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
931
cc
#include "rules.ih" void Rules::setLopBlocks() { // the last rule always has a (possibly empty) block. // visit all blocks from the last until the first for ( size_t idx = d_rules.size(), actionIdx = idx, lopIdx = idx; idx-- != 0; // canonical decrement ) { Rule &rule = d_rules[idx]; RuleType type = rule.type(); if (type == RuleType::LOP_1 or type == RuleType::LOP_FIXED) { lopIdx = idx; // remember the last LOP rule if (rule.orAction()) rule.assignBlock(d_rules[actionIdx].block()); else actionIdx = idx; } else if (not rule.orAction()) // normal rule actionIdx = idx; else if (lopIdx == actionIdx) { rule.assignBlock(d_rules[lopIdx].block()); actionIdx = idx; } } }
[ "f.b.brokken@rug.nl" ]
f.b.brokken@rug.nl
3c54369ee7951d9d2cffe6f8f1174ed58ce6a95c
43a2fbc77f5cea2487c05c7679a30e15db9a3a50
/Cpp/Internal/SDK/wld_sea_rock_cluster_e_functions.cpp
0e30d3e753b196e020fd5f44c8bcd0b2da680d24
[]
no_license
zH4x/SoT-Insider-SDK
57e2e05ede34ca1fd90fc5904cf7a79f0259085c
6bff738a1b701c34656546e333b7e59c98c63ad7
refs/heads/main
2023-06-09T23:10:32.929216
2021-07-07T01:34:27
2021-07-07T01:34:27
383,638,719
0
0
null
null
null
null
UTF-8
C++
false
false
905
cpp
// Name: SoT-Insider, Version: 1.102.2382.0 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function wld_sea_rock_cluster_e.wld_sea_rock_cluster_e_C.UserConstructionScript // (Event, Public, BlueprintCallable, BlueprintEvent) void Awld_sea_rock_cluster_e_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function wld_sea_rock_cluster_e.wld_sea_rock_cluster_e_C.UserConstructionScript"); Awld_sea_rock_cluster_e_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "Massimo.linker@gmail.com" ]
Massimo.linker@gmail.com
cec6d2ecdce5a14098a7029faf3fb446f8fc34e1
206ef4edc43c7101c81a0eca117901a724c757eb
/Algorithms/strcut_solutions.cpp
e29c8f52b6ed1ece9bc36905468c7c21392e85b6
[]
no_license
Rollcorn/Study
85879f622c2109c19572914966d626666bd5418e
9d50952935c1fbc5a9ba5291fcdfb69bfb9458a2
refs/heads/master
2023-07-13T08:14:37.701912
2021-08-14T18:52:10
2021-08-14T18:52:10
287,374,777
1
0
null
null
null
null
UTF-8
C++
false
false
352
cpp
#include <iostream> #include <string> int main() { std::string hello = "hello, world!"; std::string result; std::cout << hello << std::endl; int times_to_concatenate; std::cin >> times_to_concatenate; for(int i=0;i<times_to_concatenate;i++) result += hello; std::cout << result << std::endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
beacbe09d517a8d68833cc6981783fd3af4b74e8
df6fc5177b4ba7438076c572ec8a194d9ce8be22
/src/pb_operator.hh
aea51e3544028aa5c2390c781ac37d9f4a132186
[]
no_license
kessel/dune-pnp
f50a96f8deae286924c51ae6de563052b606e075
3df65b776076068d39253d451d3584ac7d1b3af0
refs/heads/master
2020-12-24T14:10:43.384639
2013-07-07T10:18:59
2013-07-07T10:18:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,620
hh
#include <dune/geometry/referenceelements.hh> #include <dune/geometry/quadraturerules.hh> #include<dune/pdelab/common/geometrywrapper.hh> #include<dune/pdelab/localoperator/defaultimp.hh> #include<dune/pdelab/localoperator/pattern.hh> #include<dune/pdelab/localoperator/flags.hh> /** a local operator for solving the equation * * - \Delta u + a*u = f in \Omega * u = g on \Gamma_D\subseteq\partial\Omega * -\nabla u \cdot n = j on \Gamma_N = \partial\Omega\setminus\Gamma_D * * with conforming finite elements on all types of grids in any dimension * * \tparam B a function indicating the type of boundary condition */ #define PI 3.1415 template<class PbB, class F, class S, class FluxContainer> class PBOperator : public Dune::PDELab::NumericalJacobianApplyVolume <PBOperator<PbB, F, S, FluxContainer> >, public Dune::PDELab::NumericalJacobianVolume <PBOperator<PbB, F, S, FluxContainer> >, public Dune::PDELab::NumericalJacobianApplyBoundary <PBOperator<PbB, F, S, FluxContainer> >, public Dune::PDELab::NumericalJacobianBoundary <PBOperator<PbB, F, S, FluxContainer> >, public Dune::PDELab::FullVolumePattern, public Dune::PDELab::LocalOperatorDefaultFlags { public: // pattern assembly flags enum { doPatternVolume = true }; // residual assembly flags enum { doAlphaVolume = true }; enum { doAlphaBoundary = true }; // assemble boundary PBOperator (const PbB& pbB_, const F& f_, S& s_, FluxContainer fluxContainer_, unsigned int intorder_=3) // needs boundary cond. type : pbB(pbB_), f(f_), s(s_), fluxContainer(fluxContainer_), intorder(intorder_) {} // volume integral depending on test and ansatz functions template<typename EG, typename LFSU, typename X, typename LFSV, typename R> void alpha_volume (const EG& eg, const LFSU& lfsu, const X& x, const LFSV& lfsv, R& r) const { typedef typename LFSV::Traits::FiniteElementType:: Traits::LocalBasisType::Traits::DomainFieldType DF; typedef typename LFSV::Traits::FiniteElementType:: Traits::LocalBasisType::Traits::RangeFieldType RF; typedef typename LFSU::Traits::FiniteElementType:: Traits::LocalBasisType::Traits::RangeType RangeType; typedef typename LFSV::Traits::SizeType size_type; typedef typename LFSU::Traits::FiniteElementType:: Traits::LocalBasisType::Traits::JacobianType JacobianType; // dimensions const int dim = EG::Geometry::dimension; const int dimw = EG::Geometry::dimensionworld; // select quadrature rule Dune::GeometryType gt = eg.geometry().type(); const Dune::QuadratureRule<DF,dim>& rule = Dune::QuadratureRules<DF,dim>::rule(gt,intorder); // loop over quadrature points for (typename Dune::QuadratureRule<DF,dim>::const_iterator it=rule.begin(); it!=rule.end(); ++it) { // transform gradients from reference element to real element const Dune::FieldMatrix<DF,dimw,dim> jac = eg.geometry().jacobianInverseTransposed(it->position()); Dune::FieldVector<RF,dim> globalpos = eg.geometry().global(it->position()); RF factor = it->weight()*eg.geometry().integrationElement(it->position()); if (s.cylindrical) factor *= globalpos[1]*2*PI; // evaluate basis functions on reference element std::vector<RangeType> phi(lfsu.size()); lfsu.finiteElement().localBasis().evaluateFunction(it->position(),phi); // compute u at integration point RF u=0.0; for (size_type i=0; i<lfsu.size(); i++) u += x(lfsu, i)*phi[i]; // std::cout << globalpos << " " << u_phi << " " << u_cp << " " << u_cm << " values" << std::endl; // evaluate gradient of basis functions on reference element std::vector<JacobianType> js(lfsu.size()); lfsu.finiteElement().localBasis().evaluateJacobian(it->position(),js); // transform gradients from reference element to real element std::vector<Dune::FieldVector<RF,dim> > gradphi(lfsu.size()); for (size_type i=0; i<lfsu.size(); i++) jac.mv(js[i][0],gradphi[i]); // compute gradient of u Dune::FieldVector<RF,dim> gradu(0.0); for (size_type i=0; i<lfsu.size(); i++) gradu.axpy(x(lfsu, i), gradphi[i]); ////////////////////////// Weak Formulation ///////////////////////////////////////////// // integrate grad u * grad phi_i + a*u*phi_i - f phi_i for (size_type i=0; i<lfsu.size(); i++) { double thisResidual = ( gradu*gradphi[i] + 8*PI*s.l_b*s.c0*sinh(u)*phi[i] )*factor; r.accumulate(lfsu, i, thisResidual); } } } // boundary integral template<typename IG, typename LFSU, typename X, typename LFSV, typename R> void alpha_boundary (const IG& ig, const LFSU& lfsu, const X& x_s, const LFSV& lfsv, R& r_s) const { // some types typedef typename LFSV::Traits::FiniteElementType:: Traits::LocalBasisType::Traits::DomainFieldType DF; typedef typename LFSV::Traits::FiniteElementType:: Traits::LocalBasisType::Traits::RangeFieldType RF; typedef typename LFSU::Traits::FiniteElementType:: Traits::LocalBasisType::Traits::RangeType RangeType; typedef typename LFSV::Traits::SizeType size_type; typedef typename LFSU::Traits::FiniteElementType:: Traits::LocalBasisType::Traits::JacobianType JacobianTypePhi; typedef typename LFSU::Traits::FiniteElementType:: Traits::LocalBasisType::Traits::JacobianType JacobianTypeCp; typedef typename LFSU::Traits::FiniteElementType:: Traits::LocalBasisType::Traits::JacobianType JacobianTypeCm; // dimensions const int dim = IG::dimension; // select quadrature rule for face Dune::GeometryType gtface = ig.geometryInInside().type(); const Dune::QuadratureRule<DF,dim-1>& rule = Dune::QuadratureRules<DF,dim-1>::rule(gtface,intorder); // loop over quadrature points and integrate normal flux for (typename Dune::QuadratureRule<DF,dim-1>::const_iterator it=rule.begin(); it!=rule.end(); ++it) { // evaluate boundary condition type bool pbBtype; pbBtype = pbB.isDirichlet(ig,it->position()); // position of quadrature point in local coordinates of element Dune::FieldVector<DF,dim> local = ig.geometryInInside().global(it->position()); Dune::FieldVector<DF,dim> global = ig.geometry().global(it->position()); RF factor = it->weight()*ig.geometry().integrationElement(it->position()); if (s.cylindrical) factor *= global[1]*2*PI; RF j; // evaluate basis functions on reference element std::vector<RangeType> phi(lfsu.size()); lfsu.finiteElement().localBasis().evaluateFunction(local,phi); if (!pbBtype) { // evaluate flux boundary condition j = fluxContainer[ig.intersection().boundarySegmentIndex()][0]; // integrate j for (size_type i=0; i<lfsv.size(); i++) { double thisResidual_s = j*phi[i]*factor; r_s.accumulate(lfsu, i, thisResidual_s); } } } } private: const PbB & pbB; const F& f; const S& s; const FluxContainer fluxContainer; unsigned int intorder; };
[ "stefan@kesselheim-online.de" ]
stefan@kesselheim-online.de
63376f5167e7fd9a83913d1228a70e696c42dc56
fab83426542b9b0efff74d7307de9c80937724cd
/src/models/quad.cpp
360759be7b383adf3da01767b257ce7d6ed42e69
[]
no_license
RobinRouphael/Opengl_engine
c1aae1286fa33701c2e8d9473bec50554b67dc23
94b6799fe0b2305fcfd63b1858bd271acbababbe
refs/heads/master
2023-02-02T23:08:00.802251
2020-11-18T22:52:23
2020-11-18T22:52:23
296,370,090
2
0
null
2020-11-18T23:09:16
2020-09-17T15:39:44
C++
UTF-8
C++
false
false
1,168
cpp
// // Created by robin on 23/10/2020. // #include "quad.h" ScreenQuad::ScreenQuad(float t_x, float t_y, float t_width, float t_height): Asset(), m_x(t_x), m_y(t_y), m_width(t_width), m_height(t_height) { setAssetType(AssetType::Custom); setup(); } void ScreenQuad::setup(){ std::vector<Vertex> vertices; std::vector<GLuint> indices= {0, 1, 2, 0, 2, 3}; Vertex v; v.position = glm::vec3(m_x, m_y, 0.f); v.texCoords = glm::vec2(0.f, 1.f); v.normal = glm::vec3(0,0,1); vertices.push_back(v); v.position = glm::vec3(m_x + m_width, m_y, 0.f); v.texCoords = glm::vec2(1.f, 1.f); v.normal = glm::vec3(0,0,1); vertices.push_back(v); v.position = glm::vec3(m_x + m_width, m_y - m_height, 0.f); v.texCoords = glm::vec2(1.f, 0.f); v.normal = glm::vec3(0,0,1); vertices.push_back(v); v.position = glm::vec3(m_x, m_y - m_height, 0.f); v.texCoords = glm::vec2(0.f, 0.f); v.normal = glm::vec3(0,0,1); vertices.push_back(v); addMesh(std::make_shared<Mesh>(vertices, indices,std::make_shared<Material>())); vertices.clear(); indices.clear(); }
[ "robin.rouphael@gmail.com" ]
robin.rouphael@gmail.com
58672a658e12c6008e2a54d423f5d581b7923a13
75ca5c494970ea48c31225af81f66d0c69867a6a
/src/RunAction.cc
ccb18685d8ecad994d4119d782b34f5b7e4eb92a
[]
no_license
vladkrylov/Diamond
a4cf7970d1f15aa52d71e4c5ca53c65fadb1ab1f
2da50f943ff116042a109465c403d45d1262083a
refs/heads/master
2021-01-23T00:16:06.378323
2015-08-11T22:18:33
2015-08-11T22:18:33
39,257,118
1
0
null
null
null
null
UTF-8
C++
false
false
1,664
cc
#include <ctime> #include "g4csv.hh" #include "G4Run.hh" #include "G4RunManager.hh" #include "RunAction.hh" #include "PrimaryGeneratorAction.hh" RunAction::RunAction() : G4UserRunAction() { systime = time(NULL); G4AnalysisManager* analysisManager = G4AnalysisManager::Instance(); analysisManager->SetFirstHistoId(1); analysisManager->CreateNtuple("DD", "Edep and Ekin"); analysisManager->CreateNtupleDColumn("Edep"); analysisManager->FinishNtuple(); } RunAction::~RunAction() { delete G4AnalysisManager::Instance(); } void RunAction::BeginOfRunAction(const G4Run* run) { bool autoSeed = true; if (autoSeed) { // automatic (time-based) random seeds for each run G4cout << "*******************" << G4endl; G4cout << "*** AUTOSEED ON ***" << G4endl; G4cout << "*******************" << G4endl; long seeds[2]; //time_t systime = time(NULL); seeds[0] = (long) systime; seeds[1] = (long) (systime*G4UniformRand()); G4Random::setTheSeeds(seeds); G4Random::showEngineStatus(); } else { G4Random::showEngineStatus(); } //inform the runManager to save random number seed G4RunManager::GetRunManager()->SetRandomNumberStore(false); // Get analysis manager G4AnalysisManager* analysisManager = G4AnalysisManager::Instance(); // Open an output file analysisManager->OpenFile("results.csv"); } void RunAction::EndOfRunAction(const G4Run* run) { G4int nofEvents = run->GetNumberOfEvent(); if (nofEvents == 0) return; // print histogram statistics // G4AnalysisManager* analysisManager = G4AnalysisManager::Instance(); analysisManager->Write(); analysisManager->CloseFile(); }
[ "vladkrilov9@gmail.com" ]
vladkrilov9@gmail.com
db32464337dbe2e7ba4e94de59ad99fba240ec4d
9923a00a9afcd97c2fb02f6ed615adea3fc3fe1d
/Branch/Perception/LaneDetectionMT/armadillo/include/armadillo_bits/field_bones.hpp
16216f26fd29fa426c020df14cd6d15e16c5e9f9
[ "MIT" ]
permissive
Tsinghua-OpenICV/OpenICV
93df0e3dda406a5b8958f50ee763756a45182bf3
3bdb2ba744fabe934b31e36ba9c1e6ced2d5e6fc
refs/heads/master
2022-03-02T03:09:02.236509
2021-12-26T08:09:42
2021-12-26T08:09:42
225,785,128
13
9
null
2020-08-06T02:42:03
2019-12-04T05:17:57
C++
UTF-8
C++
false
false
12,077
hpp
// Copyright (C) 2008-2013 Conrad Sanderson // Copyright (C) 2008-2013 NICTA (www.nicta.com.au) // Copyright (C) 2009-2010 Ian Cullinan // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! \addtogroup field //! @{ struct field_prealloc_n_elem { static const uword val = 16; }; //! A lightweight 2D container for arbitrary objects //! (the objects must have a copy constructor) template<typename oT> class field { public: typedef oT object_type; const uword n_rows; //!< number of rows in the field (read-only) const uword n_cols; //!< number of columns in the field (read-only) const uword n_elem; //!< number of elements in the field (read-only) private: arma_aligned oT** mem; //!< pointer to memory used by the object arma_aligned oT* mem_local[ field_prealloc_n_elem::val ]; //!< Internal memory, to avoid calling the 'new' operator for small amounts of memory public: inline ~field(); inline field(); inline field(const field& x); inline const field& operator=(const field& x); inline field(const subview_field<oT>& x); inline const field& operator=(const subview_field<oT>& x); inline explicit field(const uword n_elem_in); inline field(const uword n_rows_in, const uword n_cols_in); inline void set_size(const uword n_obj_in); inline void set_size(const uword n_rows_in, const uword n_cols_in); template<typename oT2> inline void copy_size(const field<oT2>& x); arma_inline oT& operator[](const uword i); arma_inline const oT& operator[](const uword i) const; arma_inline oT& at(const uword i); arma_inline const oT& at(const uword i) const; arma_inline oT& operator()(const uword i); arma_inline const oT& operator()(const uword i) const; arma_inline oT& at(const uword row, const uword col); arma_inline const oT& at(const uword row, const uword col) const; arma_inline oT& operator()(const uword row, const uword col); arma_inline const oT& operator()(const uword row, const uword col) const; inline field_injector<field> operator<<(const oT& val); inline field_injector<field> operator<<(const injector_end_of_row<>& x); inline subview_field<oT> row(const uword row_num); inline const subview_field<oT> row(const uword row_num) const; inline subview_field<oT> col(const uword col_num); inline const subview_field<oT> col(const uword col_num) const; inline subview_field<oT> rows(const uword in_row1, const uword in_row2); inline const subview_field<oT> rows(const uword in_row1, const uword in_row2) const; inline subview_field<oT> cols(const uword in_col1, const uword in_col2); inline const subview_field<oT> cols(const uword in_col1, const uword in_col2) const; inline subview_field<oT> subfield(const uword in_row1, const uword in_col1, const uword in_row2, const uword in_col2); inline const subview_field<oT> subfield(const uword in_row1, const uword in_col1, const uword in_row2, const uword in_col2) const; inline subview_field<oT> subfield(const uword in_row1, const uword in_col1, const SizeMat& s); inline const subview_field<oT> subfield(const uword in_row1, const uword in_col1, const SizeMat& s) const; inline subview_field<oT> subfield (const span& row_span, const span& col_span); inline const subview_field<oT> subfield (const span& row_span, const span& col_span) const; inline subview_field<oT> operator()(const span& row_span, const span& col_span); inline const subview_field<oT> operator()(const span& row_span, const span& col_span) const; inline subview_field<oT> operator()(const uword in_row1, const uword in_col1, const SizeMat& s); inline const subview_field<oT> operator()(const uword in_row1, const uword in_col1, const SizeMat& s) const; inline void print(const std::string extra_text = "") const; inline void print(std::ostream& user_stream, const std::string extra_text = "") const; inline void fill(const oT& x); inline void reset(); inline void reset_objects(); arma_inline bool is_empty() const; arma_inline arma_warn_unused bool in_range(const uword i) const; arma_inline arma_warn_unused bool in_range(const span& x) const; arma_inline arma_warn_unused bool in_range(const uword in_row, const uword in_col) const; arma_inline arma_warn_unused bool in_range(const span& row_span, const uword in_col) const; arma_inline arma_warn_unused bool in_range(const uword in_row, const span& col_span) const; arma_inline arma_warn_unused bool in_range(const span& row_span, const span& col_span) const; arma_inline arma_warn_unused bool in_range(const uword in_row, const uword in_col, const SizeMat& s) const; inline bool save(const std::string name, const file_type type = arma_binary, const bool print_status = true) const; inline bool save( std::ostream& os, const file_type type = arma_binary, const bool print_status = true) const; inline bool load(const std::string name, const file_type type = auto_detect, const bool print_status = true); inline bool load( std::istream& is, const file_type type = auto_detect, const bool print_status = true); inline bool quiet_save(const std::string name, const file_type type = arma_binary) const; inline bool quiet_save( std::ostream& os, const file_type type = arma_binary) const; inline bool quiet_load(const std::string name, const file_type type = auto_detect); inline bool quiet_load( std::istream& is, const file_type type = auto_detect); // for container-like functionality typedef oT value_type; typedef uword size_type; class iterator { public: inline iterator(field<oT>& in_M, const bool at_end = false); inline oT& operator* (); inline iterator& operator++(); inline void operator++(int); inline iterator& operator--(); inline void operator--(int); inline bool operator!=(const iterator& X) const; inline bool operator==(const iterator& X) const; arma_aligned field<oT>& M; arma_aligned uword i; }; class const_iterator { public: const_iterator(const field<oT>& in_M, const bool at_end = false); const_iterator(const iterator& X); inline const oT& operator*() const; inline const_iterator& operator++(); inline void operator++(int); inline const_iterator& operator--(); inline void operator--(int); inline bool operator!=(const const_iterator& X) const; inline bool operator==(const const_iterator& X) const; arma_aligned const field<oT>& M; arma_aligned uword i; }; inline iterator begin(); inline const_iterator begin() const; inline const_iterator cbegin() const; inline iterator end(); inline const_iterator end() const; inline const_iterator cend() const; inline void clear(); inline bool empty() const; inline uword size() const; private: inline void init(const field<oT>& x); inline void init(const uword n_rows_in, const uword n_cols_in); inline void delete_objects(); inline void create_objects(); friend class field_aux; friend class subview_field<oT>; public: #ifdef ARMA_EXTRA_FIELD_PROTO #include ARMA_INCFILE_WRAP(ARMA_EXTRA_FIELD_PROTO) #endif }; class field_aux { public: template<typename oT> inline static void reset_objects(field< oT >& x); template<typename eT> inline static void reset_objects(field< Mat<eT> >& x); template<typename eT> inline static void reset_objects(field< Col<eT> >& x); template<typename eT> inline static void reset_objects(field< Row<eT> >& x); template<typename eT> inline static void reset_objects(field< Cube<eT> >& x); inline static void reset_objects(field< std::string >& x); template<typename oT> inline static bool save(const field< oT >& x, const std::string& name, const file_type type, std::string& err_msg); template<typename oT> inline static bool save(const field< oT >& x, std::ostream& os, const file_type type, std::string& err_msg); template<typename oT> inline static bool load( field< oT >& x, const std::string& name, const file_type type, std::string& err_msg); template<typename oT> inline static bool load( field< oT >& x, std::istream& is, const file_type type, std::string& err_msg); template<typename eT> inline static bool save(const field< Mat<eT> >& x, const std::string& name, const file_type type, std::string& err_msg); template<typename eT> inline static bool save(const field< Mat<eT> >& x, std::ostream& os, const file_type type, std::string& err_msg); template<typename eT> inline static bool load( field< Mat<eT> >& x, const std::string& name, const file_type type, std::string& err_msg); template<typename eT> inline static bool load( field< Mat<eT> >& x, std::istream& is, const file_type type, std::string& err_msg); template<typename eT> inline static bool save(const field< Col<eT> >& x, const std::string& name, const file_type type, std::string& err_msg); template<typename eT> inline static bool save(const field< Col<eT> >& x, std::ostream& os, const file_type type, std::string& err_msg); template<typename eT> inline static bool load( field< Col<eT> >& x, const std::string& name, const file_type type, std::string& err_msg); template<typename eT> inline static bool load( field< Col<eT> >& x, std::istream& is, const file_type type, std::string& err_msg); template<typename eT> inline static bool save(const field< Row<eT> >& x, const std::string& name, const file_type type, std::string& err_msg); template<typename eT> inline static bool save(const field< Row<eT> >& x, std::ostream& os, const file_type type, std::string& err_msg); template<typename eT> inline static bool load( field< Row<eT> >& x, const std::string& name, const file_type type, std::string& err_msg); template<typename eT> inline static bool load( field< Row<eT> >& x, std::istream& is, const file_type type, std::string& err_msg); template<typename eT> inline static bool save(const field< Cube<eT> >& x, const std::string& name, const file_type type, std::string& err_msg); template<typename eT> inline static bool save(const field< Cube<eT> >& x, std::ostream& os, const file_type type, std::string& err_msg); template<typename eT> inline static bool load( field< Cube<eT> >& x, const std::string& name, const file_type type, std::string& err_msg); template<typename eT> inline static bool load( field< Cube<eT> >& x, std::istream& is, const file_type type, std::string& err_msg); inline static bool save(const field< std::string >& x, const std::string& name, const file_type type, std::string& err_msg); inline static bool save(const field< std::string >& x, std::ostream& os, const file_type type, std::string& err_msg); inline static bool load( field< std::string >& x, const std::string& name, const file_type type, std::string& err_msg); inline static bool load( field< std::string >& x, std::istream& is, const file_type type, std::string& err_msg); }; //! @}
[ "syn17@mails.tsinghua.edu.cn" ]
syn17@mails.tsinghua.edu.cn
c4bd3bde024d538e500486a0b5f33edfc434411e
49cea9e88a48297ddc922757bce023f799b37d16
/funsort.cpp
73b8f0d0a9ae4cc865b6395788d100b2f83eafa3
[]
no_license
msandeep03/C-Programming-Samples
a5087ace6a33c7f47c82beee66c9818ae7ac6319
a9433fae4e7617479274b0d1a4798e742926f5e7
refs/heads/master
2021-01-10T06:48:08.667946
2015-11-30T10:23:08
2015-11-30T10:23:08
47,117,995
0
0
null
null
null
null
UTF-8
C++
false
false
386
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> void sort(int *a) { static int temp; for(int i=0;i<2;i++) { if(a[i]>a[i+1]) {temp=a[i];a[i]=a[i+1];a[i+1]=a[i];} } for(int i=0;i<2;i++) {printf("%d\t",a[i]);} } int main() { int a[2]={2,1}; sort(&a[]); system("pause"); return 0; }
[ "sandeepmishra1993@yahoo.com" ]
sandeepmishra1993@yahoo.com
38a658adc1a0bbe6818227a8205bb01b24e57b61
745c48f47a813c2804cc1a9c9e60ef93ed571802
/4.3.cpp
e32bd77f860d75efd7130dabff59aa1d191bca1c
[]
no_license
EmpireShadow/PTA_ZJUMOOC
23fbcb4853b8b98872f1fdb3841db8adcffebcfc
11c260f4270549338bbf8877f1685a3235288279
refs/heads/main
2023-04-28T20:59:32.370937
2021-05-27T14:59:38
2021-05-27T14:59:38
357,166,833
0
0
null
null
null
null
UTF-8
C++
false
false
819
cpp
//目前自己写还不会写,看柳婼学姐的... #include <iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; vector <int> in,level; void levelout(int start,int end,int index); int main(){ int n; cin>>n; in.resize(n); level.resize(n); for(int i=0;i<n;i++){ cin>>in[i]; } sort(in.begin(),in.end()); levelout(0,n-1,0); printf("%d",level[0]); for(int i=1;i<n;i++) printf(" %d",level[i]); return 0; } void levelout(int start,int end,int index){ if(start>end) return; int n=end-start+1; int l=log(n+1)/log(2); int leave=n-(pow(2,l)-1); int root=start+(pow(2,l-1)-1)+min(leave,(int)(pow(2,l-1))); level[index]=in[root]; levelout(start,root-1,2*index+1); levelout(root+1,end,2*index+2); }
[ "noreply@github.com" ]
noreply@github.com
3a14a071470496063771284fdfb84c10a17280e7
f7db1bfc1cf81d15393e2af7ad63e6399e769916
/arvore_bin/arvore_bin.hpp
ea320385cc0e8c9165273c86568538411222cd99
[]
no_license
Tonikawa/Arvore-Binaria
babb816b65a3f093b4127e16d3cc2ff250ee05d3
14b097d73c7556b326d55b46d8555b550e0fedad
refs/heads/main
2023-07-29T20:16:34.134790
2021-09-26T22:45:13
2021-09-26T22:45:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,532
hpp
// Created by Gabriel Batista Cristiano // TIA: 32090722 // And Fabio Silveira Tanikawa // TIA: 32092563 #ifndef arvore_bin_h #define arvore_bin_h #include <string> #include <iostream> using namespace std; class Node { private: string nData; Node* leftNode; Node* rightNode; Node* parentNode; public: Node(); ~Node(); string GetData() const; void SetData(const string& data); Node* GetLeftNode() const; void SetLeftNode(Node* left); Node* GetRightNode() const; void SetRightNode(Node* right); Node* GetParentNode() const; void SetParentNode(Node* parent); bool IsRoot(Node* node) const; bool IsLeaf(const Node* node); int GetDegree(const Node* node); int GetDepth(Node* node) const; int GetHeight(const Node* node); }; class Tree { private: Node* root; string TraverseInOrderInt(const Node* node) const; string TraversePreOrderInt(const Node* node) const; string TraversePostOrderInt(const Node* node) const; //string TraversePerLevelInt(const Node* node) const; public: Tree(); Tree(Node* root); ~Tree(); Node* GetRoot() const; void SetRoot(Node* root); string TraverseInOrder() const; string TraversePreOrder() const; string TraversePostOrder() const; //string TraversePerLevel() const; }; #endif /* arvore_bin_h */
[ "gabriel.devproject@gmail.com" ]
gabriel.devproject@gmail.com
7a8d5716c230c87396400f313d316da321228f4d
362f4be39c394db5d88ab0792e617f9e54f74803
/3labgit/SortTester.cpp
1bfb48cf906336d2425b7c955a84c6954d63a734
[]
no_license
retryfc/TiMP_3
d7094b6a55cee59b293f5e8052ee59bd8473d6a5
a3502af6e5f9742abddca3bf3d09563aee277048
refs/heads/master
2020-03-17T17:31:35.187017
2018-05-17T10:01:46
2018-05-17T10:01:46
133,791,564
0
0
null
null
null
null
UTF-8
C++
false
false
2,718
cpp
#include "stdafx.h" #include "SortTester.h" #include <cstdlib> SortTester::SortTester(int numArrs, int* arrSizes, std::ostream* output) { NumArrs = numArrs; ArrSizes = arrSizes; Arrs = new int*[numArrs]; for (int i = 0; i < NumArrs; i++) { Arrs[i] = new int[ArrSizes[i]]; } CurrentSort = nullptr; Output = output; } SortTester::~SortTester() { for (int i = 0; i < NumArrs; i++) { delete[] Arrs[i]; } delete[] Arrs; delete CurrentSort; } void SortTester::GenerateArr(int num, GenerationType GT) { SortType ST = CurrentSort->ST; switch (GT) { case Random: for (int i = 0; i < ArrSizes[num]; i++) { Arrs[num][i] = rand(); } break; case Best: switch (ST) { case MS: for (int i = 0; i < ArrSizes[num]; i++) { Arrs[num][i] = ArrSizes[num] - i; } break; case QS3W: case SS: for (int i = 0; i < ArrSizes[num]; i++) { Arrs[num][i] = i; } break; default: break; } break; case Worst: switch (ST) { case MS: for (int i = 0; i < ArrSizes[num]; i++) { Arrs[num][i] = i; } break; case QS3W: for (int i = 0; i < ArrSizes[num]; i++) { Arrs[num][i] = ArrSizes[num] - i; } break; case SS: for (int i = 0; i < ArrSizes[num]; i++) { if ((double)rand() / RAND_MAX < 0.8) { Arrs[num][i] = 1; } else { Arrs[num][i] = 2; } } break; default: break; } break; default: break; } } void SortTester::SetSort(Sort* s) { delete CurrentSort; CurrentSort = s; } void SortTester::TestSort() { switch (CurrentSort->ST) { case MS: *Output << "Merge sort:" << std::endl; break; case QS3W: *Output << "Qwick sort 3-way:" << std::endl; break; case SS: *Output << "Selection sort:" << std::endl; break; default: break; } *Output <<"Random: "<< std::endl; TestSortWithGT(Random); *Output << std::endl << "Best: " << std::endl; TestSortWithGT(Best); *Output << std::endl << "Worst: " << std::endl; TestSortWithGT(Worst); *Output << std::endl; } void SortTester::TestSortWithGT(GenerationType GT) { *Output << "N " << "Comps " << "Swaps " << "Time" << std::endl; int numTests = 100; if (GT != Random) { numTests = 1; } for (int i = 0; i < NumArrs; i++) { double Comps = 0; double Swaps = 0; double Time = 0; for (int j = 0; j < numTests; j++) { GenerateArr(i,GT); int CurrComps = 0; int CurrSwaps = 0; int CurrTime = 0; CurrentSort->Sorting(Arrs[i], ArrSizes[i], CurrComps, CurrSwaps, CurrTime); Comps += CurrComps; Swaps += CurrSwaps; Time += CurrTime; } Comps /= numTests; Swaps /= numTests; Time /= numTests; *Output << ArrSizes[i] << " " << Comps << " " << Swaps << " " << Time << " " << std::endl; } }
[ "perminovdima@gmail.com" ]
perminovdima@gmail.com